dgenerate-ultralytics-headless 8.3.214__py3-none-any.whl → 8.4.7__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 (249) hide show
  1. {dgenerate_ultralytics_headless-8.3.214.dist-info → dgenerate_ultralytics_headless-8.4.7.dist-info}/METADATA +64 -74
  2. dgenerate_ultralytics_headless-8.4.7.dist-info/RECORD +311 -0
  3. {dgenerate_ultralytics_headless-8.3.214.dist-info → dgenerate_ultralytics_headless-8.4.7.dist-info}/WHEEL +1 -1
  4. tests/__init__.py +7 -9
  5. tests/conftest.py +8 -15
  6. tests/test_cli.py +1 -1
  7. tests/test_cuda.py +13 -10
  8. tests/test_engine.py +9 -9
  9. tests/test_exports.py +65 -13
  10. tests/test_integrations.py +13 -13
  11. tests/test_python.py +125 -69
  12. tests/test_solutions.py +161 -152
  13. ultralytics/__init__.py +1 -1
  14. ultralytics/cfg/__init__.py +86 -92
  15. ultralytics/cfg/datasets/Argoverse.yaml +7 -6
  16. ultralytics/cfg/datasets/DOTAv1.5.yaml +1 -1
  17. ultralytics/cfg/datasets/DOTAv1.yaml +1 -1
  18. ultralytics/cfg/datasets/ImageNet.yaml +1 -1
  19. ultralytics/cfg/datasets/TT100K.yaml +346 -0
  20. ultralytics/cfg/datasets/VOC.yaml +15 -16
  21. ultralytics/cfg/datasets/african-wildlife.yaml +1 -1
  22. ultralytics/cfg/datasets/coco-pose.yaml +21 -0
  23. ultralytics/cfg/datasets/coco12-formats.yaml +101 -0
  24. ultralytics/cfg/datasets/coco128-seg.yaml +1 -1
  25. ultralytics/cfg/datasets/coco8-pose.yaml +21 -0
  26. ultralytics/cfg/datasets/dog-pose.yaml +28 -0
  27. ultralytics/cfg/datasets/dota8-multispectral.yaml +1 -1
  28. ultralytics/cfg/datasets/dota8.yaml +2 -2
  29. ultralytics/cfg/datasets/hand-keypoints.yaml +26 -2
  30. ultralytics/cfg/datasets/kitti.yaml +27 -0
  31. ultralytics/cfg/datasets/lvis.yaml +5 -5
  32. ultralytics/cfg/datasets/open-images-v7.yaml +1 -1
  33. ultralytics/cfg/datasets/tiger-pose.yaml +16 -0
  34. ultralytics/cfg/datasets/xView.yaml +16 -16
  35. ultralytics/cfg/default.yaml +4 -2
  36. ultralytics/cfg/models/11/yolo11-pose.yaml +1 -1
  37. ultralytics/cfg/models/11/yoloe-11-seg.yaml +2 -2
  38. ultralytics/cfg/models/11/yoloe-11.yaml +2 -2
  39. ultralytics/cfg/models/26/yolo26-cls.yaml +33 -0
  40. ultralytics/cfg/models/26/yolo26-obb.yaml +52 -0
  41. ultralytics/cfg/models/26/yolo26-p2.yaml +60 -0
  42. ultralytics/cfg/models/26/yolo26-p6.yaml +62 -0
  43. ultralytics/cfg/models/26/yolo26-pose.yaml +53 -0
  44. ultralytics/cfg/models/26/yolo26-seg.yaml +52 -0
  45. ultralytics/cfg/models/26/yolo26.yaml +52 -0
  46. ultralytics/cfg/models/26/yoloe-26-seg.yaml +53 -0
  47. ultralytics/cfg/models/26/yoloe-26.yaml +53 -0
  48. ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +1 -1
  49. ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +1 -1
  50. ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +1 -1
  51. ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +1 -1
  52. ultralytics/cfg/models/v10/yolov10b.yaml +2 -2
  53. ultralytics/cfg/models/v10/yolov10l.yaml +2 -2
  54. ultralytics/cfg/models/v10/yolov10m.yaml +2 -2
  55. ultralytics/cfg/models/v10/yolov10n.yaml +2 -2
  56. ultralytics/cfg/models/v10/yolov10s.yaml +2 -2
  57. ultralytics/cfg/models/v10/yolov10x.yaml +2 -2
  58. ultralytics/cfg/models/v3/yolov3-tiny.yaml +1 -1
  59. ultralytics/cfg/models/v6/yolov6.yaml +1 -1
  60. ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +9 -6
  61. ultralytics/cfg/models/v8/yoloe-v8.yaml +9 -6
  62. ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +1 -1
  63. ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +1 -1
  64. ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +2 -2
  65. ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +2 -2
  66. ultralytics/cfg/models/v8/yolov8-ghost.yaml +2 -2
  67. ultralytics/cfg/models/v8/yolov8-obb.yaml +1 -1
  68. ultralytics/cfg/models/v8/yolov8-p2.yaml +1 -1
  69. ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +1 -1
  70. ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +1 -1
  71. ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +1 -1
  72. ultralytics/cfg/models/v8/yolov8-world.yaml +1 -1
  73. ultralytics/cfg/models/v8/yolov8-worldv2.yaml +6 -6
  74. ultralytics/cfg/models/v9/yolov9s.yaml +1 -1
  75. ultralytics/data/__init__.py +4 -4
  76. ultralytics/data/annotator.py +5 -6
  77. ultralytics/data/augment.py +300 -475
  78. ultralytics/data/base.py +18 -26
  79. ultralytics/data/build.py +147 -25
  80. ultralytics/data/converter.py +108 -87
  81. ultralytics/data/dataset.py +47 -75
  82. ultralytics/data/loaders.py +42 -49
  83. ultralytics/data/split.py +5 -6
  84. ultralytics/data/split_dota.py +8 -15
  85. ultralytics/data/utils.py +36 -45
  86. ultralytics/engine/exporter.py +351 -263
  87. ultralytics/engine/model.py +186 -225
  88. ultralytics/engine/predictor.py +45 -54
  89. ultralytics/engine/results.py +198 -325
  90. ultralytics/engine/trainer.py +165 -106
  91. ultralytics/engine/tuner.py +41 -43
  92. ultralytics/engine/validator.py +55 -38
  93. ultralytics/hub/__init__.py +16 -19
  94. ultralytics/hub/auth.py +6 -12
  95. ultralytics/hub/google/__init__.py +7 -10
  96. ultralytics/hub/session.py +15 -25
  97. ultralytics/hub/utils.py +5 -8
  98. ultralytics/models/__init__.py +1 -1
  99. ultralytics/models/fastsam/__init__.py +1 -1
  100. ultralytics/models/fastsam/model.py +8 -10
  101. ultralytics/models/fastsam/predict.py +18 -30
  102. ultralytics/models/fastsam/utils.py +1 -2
  103. ultralytics/models/fastsam/val.py +5 -7
  104. ultralytics/models/nas/__init__.py +1 -1
  105. ultralytics/models/nas/model.py +5 -8
  106. ultralytics/models/nas/predict.py +7 -9
  107. ultralytics/models/nas/val.py +1 -2
  108. ultralytics/models/rtdetr/__init__.py +1 -1
  109. ultralytics/models/rtdetr/model.py +5 -8
  110. ultralytics/models/rtdetr/predict.py +15 -19
  111. ultralytics/models/rtdetr/train.py +10 -13
  112. ultralytics/models/rtdetr/val.py +21 -23
  113. ultralytics/models/sam/__init__.py +15 -2
  114. ultralytics/models/sam/amg.py +14 -20
  115. ultralytics/models/sam/build.py +26 -19
  116. ultralytics/models/sam/build_sam3.py +377 -0
  117. ultralytics/models/sam/model.py +29 -32
  118. ultralytics/models/sam/modules/blocks.py +83 -144
  119. ultralytics/models/sam/modules/decoders.py +19 -37
  120. ultralytics/models/sam/modules/encoders.py +44 -101
  121. ultralytics/models/sam/modules/memory_attention.py +16 -30
  122. ultralytics/models/sam/modules/sam.py +200 -73
  123. ultralytics/models/sam/modules/tiny_encoder.py +64 -83
  124. ultralytics/models/sam/modules/transformer.py +18 -28
  125. ultralytics/models/sam/modules/utils.py +174 -50
  126. ultralytics/models/sam/predict.py +2248 -350
  127. ultralytics/models/sam/sam3/__init__.py +3 -0
  128. ultralytics/models/sam/sam3/decoder.py +546 -0
  129. ultralytics/models/sam/sam3/encoder.py +529 -0
  130. ultralytics/models/sam/sam3/geometry_encoders.py +415 -0
  131. ultralytics/models/sam/sam3/maskformer_segmentation.py +286 -0
  132. ultralytics/models/sam/sam3/model_misc.py +199 -0
  133. ultralytics/models/sam/sam3/necks.py +129 -0
  134. ultralytics/models/sam/sam3/sam3_image.py +339 -0
  135. ultralytics/models/sam/sam3/text_encoder_ve.py +307 -0
  136. ultralytics/models/sam/sam3/vitdet.py +547 -0
  137. ultralytics/models/sam/sam3/vl_combiner.py +160 -0
  138. ultralytics/models/utils/loss.py +14 -26
  139. ultralytics/models/utils/ops.py +13 -17
  140. ultralytics/models/yolo/__init__.py +1 -1
  141. ultralytics/models/yolo/classify/predict.py +10 -13
  142. ultralytics/models/yolo/classify/train.py +12 -33
  143. ultralytics/models/yolo/classify/val.py +30 -29
  144. ultralytics/models/yolo/detect/predict.py +9 -12
  145. ultralytics/models/yolo/detect/train.py +17 -23
  146. ultralytics/models/yolo/detect/val.py +77 -59
  147. ultralytics/models/yolo/model.py +43 -60
  148. ultralytics/models/yolo/obb/predict.py +7 -16
  149. ultralytics/models/yolo/obb/train.py +14 -17
  150. ultralytics/models/yolo/obb/val.py +40 -37
  151. ultralytics/models/yolo/pose/__init__.py +1 -1
  152. ultralytics/models/yolo/pose/predict.py +7 -22
  153. ultralytics/models/yolo/pose/train.py +13 -16
  154. ultralytics/models/yolo/pose/val.py +39 -58
  155. ultralytics/models/yolo/segment/predict.py +17 -21
  156. ultralytics/models/yolo/segment/train.py +7 -10
  157. ultralytics/models/yolo/segment/val.py +95 -47
  158. ultralytics/models/yolo/world/train.py +8 -14
  159. ultralytics/models/yolo/world/train_world.py +11 -34
  160. ultralytics/models/yolo/yoloe/__init__.py +7 -7
  161. ultralytics/models/yolo/yoloe/predict.py +16 -23
  162. ultralytics/models/yolo/yoloe/train.py +36 -44
  163. ultralytics/models/yolo/yoloe/train_seg.py +11 -11
  164. ultralytics/models/yolo/yoloe/val.py +15 -20
  165. ultralytics/nn/__init__.py +7 -7
  166. ultralytics/nn/autobackend.py +159 -85
  167. ultralytics/nn/modules/__init__.py +68 -60
  168. ultralytics/nn/modules/activation.py +4 -6
  169. ultralytics/nn/modules/block.py +260 -224
  170. ultralytics/nn/modules/conv.py +52 -97
  171. ultralytics/nn/modules/head.py +831 -299
  172. ultralytics/nn/modules/transformer.py +76 -88
  173. ultralytics/nn/modules/utils.py +16 -21
  174. ultralytics/nn/tasks.py +180 -195
  175. ultralytics/nn/text_model.py +45 -69
  176. ultralytics/optim/__init__.py +5 -0
  177. ultralytics/optim/muon.py +338 -0
  178. ultralytics/solutions/__init__.py +12 -12
  179. ultralytics/solutions/ai_gym.py +13 -19
  180. ultralytics/solutions/analytics.py +15 -16
  181. ultralytics/solutions/config.py +6 -7
  182. ultralytics/solutions/distance_calculation.py +10 -13
  183. ultralytics/solutions/heatmap.py +8 -14
  184. ultralytics/solutions/instance_segmentation.py +6 -9
  185. ultralytics/solutions/object_blurrer.py +7 -10
  186. ultralytics/solutions/object_counter.py +12 -19
  187. ultralytics/solutions/object_cropper.py +8 -14
  188. ultralytics/solutions/parking_management.py +34 -32
  189. ultralytics/solutions/queue_management.py +10 -12
  190. ultralytics/solutions/region_counter.py +9 -12
  191. ultralytics/solutions/security_alarm.py +15 -20
  192. ultralytics/solutions/similarity_search.py +10 -15
  193. ultralytics/solutions/solutions.py +77 -76
  194. ultralytics/solutions/speed_estimation.py +7 -10
  195. ultralytics/solutions/streamlit_inference.py +2 -4
  196. ultralytics/solutions/templates/similarity-search.html +7 -18
  197. ultralytics/solutions/trackzone.py +7 -10
  198. ultralytics/solutions/vision_eye.py +5 -8
  199. ultralytics/trackers/__init__.py +1 -1
  200. ultralytics/trackers/basetrack.py +3 -5
  201. ultralytics/trackers/bot_sort.py +10 -27
  202. ultralytics/trackers/byte_tracker.py +21 -37
  203. ultralytics/trackers/track.py +4 -7
  204. ultralytics/trackers/utils/gmc.py +11 -22
  205. ultralytics/trackers/utils/kalman_filter.py +37 -48
  206. ultralytics/trackers/utils/matching.py +12 -15
  207. ultralytics/utils/__init__.py +124 -124
  208. ultralytics/utils/autobatch.py +2 -4
  209. ultralytics/utils/autodevice.py +17 -18
  210. ultralytics/utils/benchmarks.py +57 -71
  211. ultralytics/utils/callbacks/base.py +8 -10
  212. ultralytics/utils/callbacks/clearml.py +5 -13
  213. ultralytics/utils/callbacks/comet.py +32 -46
  214. ultralytics/utils/callbacks/dvc.py +13 -18
  215. ultralytics/utils/callbacks/mlflow.py +4 -5
  216. ultralytics/utils/callbacks/neptune.py +7 -15
  217. ultralytics/utils/callbacks/platform.py +423 -38
  218. ultralytics/utils/callbacks/raytune.py +3 -4
  219. ultralytics/utils/callbacks/tensorboard.py +25 -31
  220. ultralytics/utils/callbacks/wb.py +16 -14
  221. ultralytics/utils/checks.py +127 -85
  222. ultralytics/utils/cpu.py +3 -8
  223. ultralytics/utils/dist.py +9 -12
  224. ultralytics/utils/downloads.py +25 -33
  225. ultralytics/utils/errors.py +6 -14
  226. ultralytics/utils/events.py +2 -4
  227. ultralytics/utils/export/__init__.py +4 -236
  228. ultralytics/utils/export/engine.py +246 -0
  229. ultralytics/utils/export/imx.py +117 -63
  230. ultralytics/utils/export/tensorflow.py +231 -0
  231. ultralytics/utils/files.py +26 -30
  232. ultralytics/utils/git.py +9 -11
  233. ultralytics/utils/instance.py +30 -51
  234. ultralytics/utils/logger.py +212 -114
  235. ultralytics/utils/loss.py +601 -215
  236. ultralytics/utils/metrics.py +128 -156
  237. ultralytics/utils/nms.py +13 -16
  238. ultralytics/utils/ops.py +117 -166
  239. ultralytics/utils/patches.py +75 -21
  240. ultralytics/utils/plotting.py +75 -80
  241. ultralytics/utils/tal.py +125 -59
  242. ultralytics/utils/torch_utils.py +53 -79
  243. ultralytics/utils/tqdm.py +24 -21
  244. ultralytics/utils/triton.py +13 -19
  245. ultralytics/utils/tuner.py +19 -10
  246. dgenerate_ultralytics_headless-8.3.214.dist-info/RECORD +0 -283
  247. {dgenerate_ultralytics_headless-8.3.214.dist-info → dgenerate_ultralytics_headless-8.4.7.dist-info}/entry_points.txt +0 -0
  248. {dgenerate_ultralytics_headless-8.3.214.dist-info → dgenerate_ultralytics_headless-8.4.7.dist-info}/licenses/LICENSE +0 -0
  249. {dgenerate_ultralytics_headless-8.3.214.dist-info → dgenerate_ultralytics_headless-8.4.7.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,15 +37,15 @@ 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):
41
- """
42
- Predictor class for SAM, enabling real-time image segmentation with promptable capabilities.
44
+ """Predictor class for SAM, enabling real-time image segmentation with promptable capabilities.
43
45
 
44
- This class extends BasePredictor and implements the Segment Anything Model (SAM) for advanced image
45
- segmentation tasks. It supports various input prompts like points, bounding boxes, and masks for
46
- fine-grained control over segmentation results.
46
+ This class extends BasePredictor and implements the Segment Anything Model (SAM) for advanced image segmentation
47
+ tasks. It supports various input prompts like points, bounding boxes, and masks for fine-grained control over
48
+ segmentation results.
47
49
 
48
50
  Attributes:
49
51
  args (SimpleNamespace): Configuration arguments for the predictor.
@@ -80,23 +82,19 @@ class Predictor(BasePredictor):
80
82
  >>> results = predictor(bboxes=bboxes)
81
83
  """
82
84
 
85
+ stride = 16
86
+
83
87
  def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):
84
- """
85
- Initialize the Predictor with configuration, overrides, and callbacks.
88
+ """Initialize the Predictor with configuration, overrides, and callbacks.
86
89
 
87
90
  Sets up the Predictor object for SAM (Segment Anything Model) and applies any configuration overrides or
88
- callbacks provided. Initializes task-specific settings for SAM, such as retina_masks being set to True
89
- for optimal results.
91
+ callbacks provided. Initializes task-specific settings for SAM, such as retina_masks being set to True for
92
+ optimal results.
90
93
 
91
94
  Args:
92
95
  cfg (dict): Configuration dictionary containing default settings.
93
96
  overrides (dict | None): Dictionary of values to override default configuration.
94
97
  _callbacks (dict | None): Dictionary of callback functions to customize behavior.
95
-
96
- Examples:
97
- >>> predictor_example = Predictor(cfg=DEFAULT_CFG)
98
- >>> predictor_example_with_imgsz = Predictor(overrides={"imgsz": 640})
99
- >>> predictor_example_with_callback = Predictor(_callbacks={"on_predict_start": custom_callback})
100
98
  """
101
99
  if overrides is None:
102
100
  overrides = {}
@@ -109,14 +107,15 @@ class Predictor(BasePredictor):
109
107
  self.segment_all = False
110
108
 
111
109
  def preprocess(self, im):
112
- """
113
- Preprocess the input image for model inference.
110
+ """Preprocess the input image for model inference.
114
111
 
115
112
  This method prepares the input image by applying transformations and normalization. It supports both
116
- torch.Tensor and list of np.ndarray as input formats.
113
+ torch.Tensor and list of np.ndarray as input formats. For OpenCV-loaded images, the input is typically BGR and
114
+ is converted to RGB during preprocessing.
117
115
 
118
116
  Args:
119
- im (torch.Tensor | list[np.ndarray]): Input image(s) in BCHW tensor format or list of HWC numpy arrays.
117
+ im (torch.Tensor | list[np.ndarray]): Input image(s) in BCHW tensor format or a list of HWC NumPy arrays.
118
+ NumPy arrays are expected to be in BGR order (as returned by OpenCV) and will be converted to RGB.
120
119
 
121
120
  Returns:
122
121
  (torch.Tensor): The preprocessed image tensor, normalized and converted to the appropriate dtype.
@@ -142,11 +141,10 @@ class Predictor(BasePredictor):
142
141
  return im
143
142
 
144
143
  def pre_transform(self, im):
145
- """
146
- Perform initial transformations on the input image for preprocessing.
144
+ """Perform initial transformations on the input image for preprocessing.
147
145
 
148
- This method applies transformations such as resizing to prepare the image for further preprocessing.
149
- Currently, batched inference is not supported; hence the list length should be 1.
146
+ This method applies transformations such as resizing to prepare the image for further preprocessing. Currently,
147
+ batched inference is not supported; hence the list length should be 1.
150
148
 
151
149
  Args:
152
150
  im (list[np.ndarray]): List containing a single image in HWC numpy array format.
@@ -165,15 +163,14 @@ class Predictor(BasePredictor):
165
163
  1
166
164
  """
167
165
  assert len(im) == 1, "SAM model does not currently support batched inference"
168
- letterbox = LetterBox(self.args.imgsz, auto=False, center=False)
166
+ letterbox = LetterBox(self.imgsz, auto=False, center=False)
169
167
  return [letterbox(image=x) for x in im]
170
168
 
171
169
  def inference(self, im, bboxes=None, points=None, labels=None, masks=None, multimask_output=False, *args, **kwargs):
172
- """
173
- Perform image segmentation inference based on the given input cues, using the currently loaded image.
170
+ """Perform image segmentation inference based on the given input cues, using the currently loaded image.
174
171
 
175
- This method leverages SAM's (Segment Anything Model) architecture consisting of image encoder, prompt
176
- encoder, and mask decoder for real-time and promptable segmentation tasks.
172
+ This method leverages SAM's (Segment Anything Model) architecture consisting of image encoder, prompt encoder,
173
+ and mask decoder for real-time and promptable segmentation tasks.
177
174
 
178
175
  Args:
179
176
  im (torch.Tensor): The preprocessed input image in tensor format, with shape (N, C, H, W).
@@ -187,7 +184,8 @@ class Predictor(BasePredictor):
187
184
 
188
185
  Returns:
189
186
  pred_masks (torch.Tensor): The output masks in shape (C, H, W), where C is the number of generated masks.
190
- pred_scores (torch.Tensor): An array of length C containing quality scores predicted by the model for each mask.
187
+ pred_scores (torch.Tensor): An array of length C containing quality scores predicted by the model for each
188
+ mask.
191
189
 
192
190
  Examples:
193
191
  >>> predictor = Predictor()
@@ -207,17 +205,18 @@ class Predictor(BasePredictor):
207
205
  return self.prompt_inference(im, bboxes, points, labels, masks, multimask_output)
208
206
 
209
207
  def prompt_inference(self, im, bboxes=None, points=None, labels=None, masks=None, multimask_output=False):
210
- """
211
- Perform image segmentation inference based on input cues using SAM's specialized architecture.
208
+ """Perform image segmentation inference based on input cues using SAM's specialized architecture.
212
209
 
213
- This internal function leverages the Segment Anything Model (SAM) for prompt-based, real-time segmentation.
214
- It processes various input prompts such as bounding boxes, points, and masks to generate segmentation masks.
210
+ This internal function leverages the Segment Anything Model (SAM) for prompt-based, real-time segmentation. It
211
+ processes various input prompts such as bounding boxes, points, and masks to generate segmentation masks.
215
212
 
216
213
  Args:
217
214
  im (torch.Tensor): Preprocessed input image tensor with shape (N, C, H, W).
218
215
  bboxes (np.ndarray | list | None): Bounding boxes in XYXY format with shape (N, 4).
219
- points (np.ndarray | list | None): Points indicating object locations with shape (N, 2) or (N, num_points, 2), in pixels.
220
- labels (np.ndarray | list | None): Point prompt labels with shape (N) or (N, num_points). 1 for foreground, 0 for background.
216
+ points (np.ndarray | list | None): Points indicating object locations with shape (N, 2) or (N, num_points,
217
+ 2), in pixels.
218
+ labels (np.ndarray | list | None): Point prompt labels with shape (N) or (N, num_points). 1 for foreground,
219
+ 0 for background.
221
220
  masks (np.ndarray | None): Low-res masks from previous predictions with shape (N, H, W). For SAM, H=W=256.
222
221
  multimask_output (bool): Flag to return multiple masks for ambiguous prompts.
223
222
 
@@ -245,8 +244,7 @@ class Predictor(BasePredictor):
245
244
  masks=None,
246
245
  multimask_output=False,
247
246
  ):
248
- """
249
- Perform inference on image features using the SAM model.
247
+ """Perform inference on image features using the SAM model.
250
248
 
251
249
  Args:
252
250
  features (torch.Tensor): Extracted image features with shape (B, C, H, W) from the SAM model image encoder.
@@ -278,16 +276,18 @@ class Predictor(BasePredictor):
278
276
  return pred_masks.flatten(0, 1), pred_scores.flatten(0, 1)
279
277
 
280
278
  def _prepare_prompts(self, dst_shape, src_shape, bboxes=None, points=None, labels=None, masks=None):
281
- """
282
- Prepare and transform the input prompts for processing based on the destination shape.
279
+ """Prepare and transform the input prompts for processing based on the destination shape.
283
280
 
284
281
  Args:
285
282
  dst_shape (tuple[int, int]): The target shape (height, width) for the prompts.
286
283
  src_shape (tuple[int, int]): The source shape (height, width) of the input image.
287
284
  bboxes (np.ndarray | list | None): Bounding boxes in XYXY format with shape (N, 4).
288
- points (np.ndarray | list | None): Points indicating object locations with shape (N, 2) or (N, num_points, 2), in pixels.
289
- labels (np.ndarray | list | None): Point prompt labels with shape (N) or (N, num_points). 1 for foreground, 0 for background.
290
- masks (list[np.ndarray] | np.ndarray | None): Masks for the objects, where each mask is a 2D array with shape (H, W).
285
+ points (np.ndarray | list | None): Points indicating object locations with shape (N, 2) or (N, num_points,
286
+ 2), in pixels.
287
+ labels (np.ndarray | list | None): Point prompt labels with shape (N) or (N, num_points). 1 for foreground,
288
+ 0 for background.
289
+ masks (list[np.ndarray] | np.ndarray | None): Masks for the objects, where each mask is a 2D array with
290
+ shape (H, W).
291
291
 
292
292
  Returns:
293
293
  bboxes (torch.Tensor | None): Transformed bounding boxes.
@@ -340,11 +340,10 @@ class Predictor(BasePredictor):
340
340
  stability_score_offset=0.95,
341
341
  crop_nms_thresh=0.7,
342
342
  ):
343
- """
344
- Perform image segmentation using the Segment Anything Model (SAM).
343
+ """Perform image segmentation using the Segment Anything Model (SAM).
345
344
 
346
- This method segments an entire image into constituent parts by leveraging SAM's advanced architecture
347
- and real-time performance capabilities. It can optionally work on image crops for finer segmentation.
345
+ This method segments an entire image into constituent parts by leveraging SAM's advanced architecture and
346
+ real-time performance capabilities. It can optionally work on image crops for finer segmentation.
348
347
 
349
348
  Args:
350
349
  im (torch.Tensor): Input tensor representing the preprocessed image with shape (N, C, H, W).
@@ -439,8 +438,7 @@ class Predictor(BasePredictor):
439
438
  return pred_masks, pred_scores, pred_bboxes
440
439
 
441
440
  def setup_model(self, model=None, verbose=True):
442
- """
443
- Initialize the Segment Anything Model (SAM) for inference.
441
+ """Initialize the Segment Anything Model (SAM) for inference.
444
442
 
445
443
  This method sets up the SAM model by allocating it to the appropriate device and initializing the necessary
446
444
  parameters for image normalization and other Ultralytics compatibility settings.
@@ -478,8 +476,7 @@ class Predictor(BasePredictor):
478
476
  return build_sam(self.args.model)
479
477
 
480
478
  def postprocess(self, preds, img, orig_imgs):
481
- """
482
- Post-process SAM's inference outputs to generate object detection masks and bounding boxes.
479
+ """Post-process SAM's inference outputs to generate object detection masks and bounding boxes.
483
480
 
484
481
  This method scales masks and boxes to the original image size and applies a threshold to the mask
485
482
  predictions. It leverages SAM's advanced architecture for real-time, promptable segmentation tasks.
@@ -493,8 +490,8 @@ class Predictor(BasePredictor):
493
490
  orig_imgs (list[np.ndarray] | torch.Tensor): The original, unprocessed images.
494
491
 
495
492
  Returns:
496
- (list[Results]): List of Results objects containing detection masks, bounding boxes, and other
497
- metadata for each processed image.
493
+ (list[Results]): List of Results objects containing detection masks, bounding boxes, and other metadata for
494
+ each processed image.
498
495
 
499
496
  Examples:
500
497
  >>> predictor = Predictor()
@@ -507,7 +504,7 @@ class Predictor(BasePredictor):
507
504
  names = dict(enumerate(str(i) for i in range(pred_masks.shape[0])))
508
505
 
509
506
  if not isinstance(orig_imgs, list): # input images are a torch.Tensor, not a list
510
- orig_imgs = ops.convert_torch2numpy_batch(orig_imgs)
507
+ orig_imgs = ops.convert_torch2numpy_batch(orig_imgs)[..., ::-1]
511
508
 
512
509
  results = []
513
510
  for masks, orig_img, img_path in zip([pred_masks], orig_imgs, self.batch[0]):
@@ -530,51 +527,25 @@ class Predictor(BasePredictor):
530
527
  self.segment_all = False
531
528
  return results
532
529
 
533
- def setup_source(self, source):
534
- """
535
- Set up the data source for inference.
536
-
537
- This method configures the data source from which images will be fetched for inference. It supports
538
- various input types such as image files, directories, video files, and other compatible data sources.
539
-
540
- Args:
541
- source (str | Path | None): The path or identifier for the image data source. Can be a file path,
542
- directory path, URL, or other supported source types.
543
-
544
- Examples:
545
- >>> predictor = Predictor()
546
- >>> predictor.setup_source("path/to/images")
547
- >>> predictor.setup_source("video.mp4")
548
- >>> predictor.setup_source(None) # Uses default source if available
549
-
550
- Notes:
551
- - If source is None, the method may use a default source if configured.
552
- - The method adapts to different source types and prepares them for subsequent inference steps.
553
- - Supported source types may include local files, directories, URLs, and video streams.
554
- """
555
- if source is not None:
556
- super().setup_source(source)
557
-
558
530
  def set_image(self, image):
559
- """
560
- Preprocess and set a single image for inference.
531
+ """Preprocess and set a single image for inference.
561
532
 
562
533
  This method prepares the model for inference on a single image by setting up the model if not already
563
- initialized, configuring the data source, and preprocessing the image for feature extraction. It
564
- ensures that only one image is set at a time and extracts image features for subsequent use.
534
+ initialized, configuring the data source, and preprocessing the image for feature extraction. It ensures that
535
+ only one image is set at a time and extracts image features for subsequent use.
565
536
 
566
537
  Args:
567
- image (str | np.ndarray): Path to the image file as a string, or a numpy array representing
568
- an image read by cv2.
538
+ image (str | np.ndarray): Path to the image file as a string, or a numpy array representing an image read by
539
+ cv2 (BGR channel order).
540
+
541
+ Raises:
542
+ AssertionError: If more than one image is attempted to be set.
569
543
 
570
544
  Examples:
571
545
  >>> predictor = Predictor()
572
546
  >>> predictor.set_image("path/to/image.jpg")
573
547
  >>> predictor.set_image(cv2.imread("path/to/image.jpg"))
574
548
 
575
- Raises:
576
- AssertionError: If more than one image is attempted to be set.
577
-
578
549
  Notes:
579
550
  - This method should be called before performing inference on a new image.
580
551
  - The extracted features are stored in the `self.features` attribute for later use.
@@ -588,12 +559,18 @@ class Predictor(BasePredictor):
588
559
  self.features = self.get_im_features(im)
589
560
  break
590
561
 
591
- def get_im_features(self, im):
592
- """Extract image features using the SAM model's image encoder for subsequent mask prediction."""
562
+ def setup_source(self, source):
563
+ """Set up the data source for SAM inference."""
564
+ if source is None: # handle the situation when set_imgsz in advance
565
+ return
566
+ super().setup_source(source, self.stride)
593
567
  assert isinstance(self.imgsz, (tuple, list)) and self.imgsz[0] == self.imgsz[1], (
594
568
  f"SAM models only support square image size, but got {self.imgsz}."
595
569
  )
596
570
  self.model.set_imgsz(self.imgsz)
571
+
572
+ def get_im_features(self, im):
573
+ """Extract image features using the SAM model's image encoder for subsequent mask prediction."""
597
574
  return self.model.image_encoder(im)
598
575
 
599
576
  def set_prompts(self, prompts):
@@ -607,12 +584,11 @@ class Predictor(BasePredictor):
607
584
 
608
585
  @staticmethod
609
586
  def remove_small_regions(masks, min_area=0, nms_thresh=0.7):
610
- """
611
- Remove small disconnected regions and holes from segmentation masks.
587
+ """Remove small disconnected regions and holes from segmentation masks.
612
588
 
613
- This function performs post-processing on segmentation masks generated by the Segment Anything Model (SAM).
614
- It removes small disconnected regions and holes from the input masks, and then performs Non-Maximum
615
- Suppression (NMS) to eliminate any newly created duplicate boxes.
589
+ This function performs post-processing on segmentation masks generated by the Segment Anything Model (SAM). It
590
+ removes small disconnected regions and holes from the input masks, and then performs Non-Maximum Suppression
591
+ (NMS) to eliminate any newly created duplicate boxes.
616
592
 
617
593
  Args:
618
594
  masks (torch.Tensor): Segmentation masks to be processed, with shape (N, H, W) where N is the number of
@@ -669,15 +645,16 @@ class Predictor(BasePredictor):
669
645
  masks=None,
670
646
  multimask_output=False,
671
647
  ):
672
- """
673
- Perform prompts preprocessing and inference on provided image features using the SAM model.
648
+ """Perform prompts preprocessing and inference on provided image features using the SAM model.
674
649
 
675
650
  Args:
676
651
  features (torch.Tensor | dict[str, Any]): Extracted image features from the SAM/SAM2 model image encoder.
677
652
  src_shape (tuple[int, int]): The source shape (height, width) of the input image.
678
- dst_shape (tuple[int, int] | None): The target shape (height, width) for the prompts. If None, defaults to (imgsz, imgsz).
653
+ dst_shape (tuple[int, int] | None): The target shape (height, width) for the prompts. If None, defaults to
654
+ (imgsz, imgsz).
679
655
  bboxes (np.ndarray | list[list[float]] | None): Bounding boxes in xyxy format with shape (N, 4).
680
- points (np.ndarray | list[list[float]] | None): Points indicating object locations with shape (N, 2), in pixels.
656
+ points (np.ndarray | list[list[float]] | None): Points indicating object locations with shape (N, 2), in
657
+ pixels.
681
658
  labels (np.ndarray | list[int] | None): Point prompt labels with shape (N, ).
682
659
  masks (list[np.ndarray] | np.ndarray | None): Masks for the objects, where each mask is a 2D array.
683
660
  multimask_output (bool): Flag to return multiple masks for ambiguous prompts.
@@ -706,12 +683,10 @@ class Predictor(BasePredictor):
706
683
 
707
684
 
708
685
  class SAM2Predictor(Predictor):
709
- """
710
- SAM2Predictor class for advanced image segmentation using Segment Anything Model 2 architecture.
686
+ """SAM2Predictor class for advanced image segmentation using Segment Anything Model 2 architecture.
711
687
 
712
- This class extends the base Predictor class to implement SAM2-specific functionality for image
713
- segmentation tasks. It provides methods for model initialization, feature extraction, and
714
- prompt-based inference.
688
+ This class extends the base Predictor class to implement SAM2-specific functionality for image segmentation tasks.
689
+ It provides methods for model initialization, feature extraction, and prompt-based inference.
715
690
 
716
691
  Attributes:
717
692
  _bb_feat_sizes (list[tuple]): Feature sizes for different backbone levels.
@@ -740,6 +715,7 @@ class SAM2Predictor(Predictor):
740
715
  (128, 128),
741
716
  (64, 64),
742
717
  ]
718
+ stride = 16
743
719
 
744
720
  def get_model(self):
745
721
  """Retrieve and initialize the Segment Anything Model 2 (SAM2) for image segmentation tasks."""
@@ -748,15 +724,16 @@ class SAM2Predictor(Predictor):
748
724
  return build_sam(self.args.model)
749
725
 
750
726
  def _prepare_prompts(self, dst_shape, src_shape, bboxes=None, points=None, labels=None, masks=None):
751
- """
752
- Prepare and transform the input prompts for processing based on the destination shape.
727
+ """Prepare and transform the input prompts for processing based on the destination shape.
753
728
 
754
729
  Args:
755
730
  dst_shape (tuple[int, int]): The target shape (height, width) for the prompts.
756
731
  src_shape (tuple[int, int]): The source shape (height, width) of the input image.
757
732
  bboxes (np.ndarray | list | None): Bounding boxes in XYXY format with shape (N, 4).
758
- points (np.ndarray | list | None): Points indicating object locations with shape (N, 2) or (N, num_points, 2), in pixels.
759
- labels (np.ndarray | list | None): Point prompt labels with shape (N,) or (N, num_points). 1 for foreground, 0 for background.
733
+ points (np.ndarray | list | None): Points indicating object locations with shape (N, 2) or (N, num_points,
734
+ 2), in pixels.
735
+ labels (np.ndarray | list | None): Point prompt labels with shape (N,) or (N, num_points). 1 for foreground,
736
+ 0 for background.
760
737
  masks (list | np.ndarray | None): Masks for the objects, where each mask is a 2D array.
761
738
 
762
739
  Returns:
@@ -780,46 +757,13 @@ class SAM2Predictor(Predictor):
780
757
  points, labels = bboxes, bbox_labels
781
758
  return points, labels, masks
782
759
 
783
- def set_image(self, image):
784
- """
785
- Preprocess and set a single image for inference using the SAM2 model.
786
-
787
- This method initializes the model if not already done, configures the data source to the specified image,
788
- and preprocesses the image for feature extraction. It supports setting only one image at a time.
789
-
790
- Args:
791
- image (str | np.ndarray): Path to the image file as a string, or a numpy array representing the image.
792
-
793
- Examples:
794
- >>> predictor = SAM2Predictor()
795
- >>> predictor.set_image("path/to/image.jpg")
796
- >>> predictor.set_image(np.array([...])) # Using a numpy array
797
-
798
- Raises:
799
- AssertionError: If more than one image is attempted to be set.
800
-
801
- Notes:
802
- - This method must be called before performing any inference on a new image.
803
- - The method caches the extracted features for efficient subsequent inferences on the same image.
804
- - Only one image can be set at a time. To process multiple images, call this method for each new image.
805
- """
806
- if self.model is None:
807
- self.setup_model(model=None)
808
- self.setup_source(image)
809
- assert len(self.dataset) == 1, "`set_image` only supports setting one image!"
810
- for batch in self.dataset:
811
- im = self.preprocess(batch[1])
812
- self.features = self.get_im_features(im)
813
- break
760
+ def setup_source(self, source):
761
+ """Set up the data source and image size for SAM2 inference."""
762
+ super().setup_source(source)
763
+ self._bb_feat_sizes = [[int(x / (self.stride * i)) for x in self.imgsz] for i in [1 / 4, 1 / 2, 1]]
814
764
 
815
765
  def get_im_features(self, im):
816
766
  """Extract image features from the SAM image encoder for subsequent processing."""
817
- assert isinstance(self.imgsz, (tuple, list)) and self.imgsz[0] == self.imgsz[1], (
818
- f"SAM 2 models only support square image size, but got {self.imgsz}."
819
- )
820
- self.model.set_imgsz(self.imgsz)
821
- self._bb_feat_sizes = [[x // (4 * i) for x in self.imgsz] for i in [1, 2, 4]]
822
-
823
767
  backbone_out = self.model.forward_image(im)
824
768
  _, vision_feats, _, _ = self.model._prepare_backbone_features(backbone_out)
825
769
  if self.model.directly_add_no_mem_embed:
@@ -838,12 +782,11 @@ class SAM2Predictor(Predictor):
838
782
  multimask_output=False,
839
783
  img_idx=-1,
840
784
  ):
841
- """
842
- Perform inference on image features using the SAM2 model.
785
+ """Perform inference on image features using the SAM2 model.
843
786
 
844
787
  Args:
845
- features (torch.Tensor | dict[str, Any]): Extracted image features with shape (B, C, H, W) from the SAM2 model image encoder, it
846
- could also be a dictionary including:
788
+ features (torch.Tensor | dict[str, Any]): Extracted image features with shape (B, C, H, W) from the SAM2
789
+ model image encoder, it could also be a dictionary including:
847
790
  - image_embed (torch.Tensor): Image embedding with shape (B, C, H, W).
848
791
  - high_res_feats (list[torch.Tensor]): List of high-resolution feature maps from the backbone, each with shape (B, C, H, W).
849
792
  points (np.ndarray | list[list[float]] | None): Object location points with shape (N, 2), in pixels.
@@ -883,18 +826,18 @@ class SAM2Predictor(Predictor):
883
826
 
884
827
 
885
828
  class SAM2VideoPredictor(SAM2Predictor):
886
- """
887
- SAM2VideoPredictor to handle user interactions with videos and manage inference states.
829
+ """SAM2VideoPredictor to handle user interactions with videos and manage inference states.
888
830
 
889
- This class extends the functionality of SAM2Predictor to support video processing and maintains
890
- the state of inference operations. It includes configurations for managing non-overlapping masks,
891
- clearing memory for non-conditional inputs, and setting up callbacks for prediction events.
831
+ This class extends the functionality of SAM2Predictor to support video processing and maintains the state of
832
+ inference operations. It includes configurations for managing non-overlapping masks, clearing memory for
833
+ non-conditional inputs, and setting up callbacks for prediction events.
892
834
 
893
835
  Attributes:
894
836
  inference_state (dict): A dictionary to store the current state of inference operations.
895
837
  non_overlap_masks (bool): A flag indicating whether masks should be non-overlapping.
896
838
  clear_non_cond_mem_around_input (bool): A flag to control clearing non-conditional memory around inputs.
897
- clear_non_cond_mem_for_multi_obj (bool): A flag to control clearing non-conditional memory for multi-object scenarios.
839
+ clear_non_cond_mem_for_multi_obj (bool): A flag to control clearing non-conditional memory for multi-object
840
+ scenarios.
898
841
  callbacks (dict): A dictionary of callbacks for various prediction lifecycle events.
899
842
 
900
843
  Methods:
@@ -904,7 +847,7 @@ class SAM2VideoPredictor(SAM2Predictor):
904
847
  add_new_prompts: Add new points or masks to a specific frame for a given object ID.
905
848
  propagate_in_video_preflight: Prepare inference_state and consolidate temporary outputs before tracking.
906
849
  init_state: Initialize an inference state for the predictor.
907
- get_im_features: Extract and process image features using SAM2's image encoder for subsequent segmentation tasks.
850
+ get_im_features: Extract image features using SAM2's image encoder for subsequent segmentation tasks.
908
851
 
909
852
  Examples:
910
853
  >>> predictor = SAM2VideoPredictor(cfg=DEFAULT_CFG)
@@ -912,29 +855,22 @@ class SAM2VideoPredictor(SAM2Predictor):
912
855
  >>> bboxes = [[100, 100, 200, 200]]
913
856
  >>> results = predictor(bboxes=bboxes)
914
857
 
915
- Note:
858
+ Notes:
916
859
  The `fill_hole_area` attribute is defined but not used in the current implementation.
917
860
  """
918
861
 
919
862
  # fill_hole_area = 8 # not used
920
863
 
921
864
  def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):
922
- """
923
- Initialize the predictor with configuration and optional overrides.
865
+ """Initialize the predictor with configuration and optional overrides.
924
866
 
925
- This constructor initializes the SAM2VideoPredictor with a given configuration, applies any
926
- specified overrides, and sets up the inference state along with certain flags
927
- that control the behavior of the predictor.
867
+ This constructor initializes the SAM2VideoPredictor with a given configuration, applies any specified overrides,
868
+ and sets up the inference state along with certain flags that control the behavior of the predictor.
928
869
 
929
870
  Args:
930
871
  cfg (dict): Configuration dictionary containing default settings.
931
872
  overrides (dict | None): Dictionary of values to override default configuration.
932
873
  _callbacks (dict | None): Dictionary of callback functions to customize behavior.
933
-
934
- Examples:
935
- >>> predictor = SAM2VideoPredictor(cfg=DEFAULT_CFG)
936
- >>> predictor_example_with_imgsz = SAM2VideoPredictor(overrides={"imgsz": 640})
937
- >>> predictor_example_with_callback = SAM2VideoPredictor(_callbacks={"on_predict_start": custom_callback})
938
874
  """
939
875
  super().__init__(cfg, overrides, _callbacks)
940
876
  self.inference_state = {}
@@ -942,12 +878,12 @@ class SAM2VideoPredictor(SAM2Predictor):
942
878
  self.clear_non_cond_mem_around_input = False
943
879
  self.clear_non_cond_mem_for_multi_obj = False
944
880
  self.callbacks["on_predict_start"].append(self.init_state)
881
+ self.clear_non_cond_mem = True # Whether to clear non-conditioning memory periodically
945
882
 
946
883
  def get_model(self):
947
- """
948
- Retrieve and configure the model with binarization enabled.
884
+ """Retrieve and configure the model with binarization enabled.
949
885
 
950
- Note:
886
+ Notes:
951
887
  This method overrides the base class implementation to set the binarize flag to True.
952
888
  """
953
889
  model = super().get_model()
@@ -955,10 +891,9 @@ class SAM2VideoPredictor(SAM2Predictor):
955
891
  return model
956
892
 
957
893
  def inference(self, im, bboxes=None, points=None, labels=None, masks=None):
958
- """
959
- Perform image segmentation inference based on the given input cues, using the currently loaded image. This
960
- method leverages SAM's (Segment Anything Model) architecture consisting of image encoder, prompt encoder, and
961
- mask decoder for real-time and promptable segmentation tasks.
894
+ """Perform image segmentation inference based on the given input cues, using the currently loaded image. This
895
+ method leverages SAM's (Segment Anything Model) architecture consisting of image encoder, prompt
896
+ encoder, and mask decoder for real-time and promptable segmentation tasks.
962
897
 
963
898
  Args:
964
899
  im (torch.Tensor): The preprocessed input image in tensor format, with shape (N, C, H, W).
@@ -969,7 +904,7 @@ class SAM2VideoPredictor(SAM2Predictor):
969
904
 
970
905
  Returns:
971
906
  pred_masks (torch.Tensor): The output masks in shape CxHxW, where C is the number of generated masks.
972
- pred_scores (torch.Tensor): An array of length C containing quality scores predicted by the model for each mask.
907
+ pred_scores (torch.Tensor): An array of length C containing predicted quality scores for each mask.
973
908
  """
974
909
  # Override prompts if any stored in self.prompts
975
910
  bboxes = self.prompts.pop("bboxes", bboxes)
@@ -1018,6 +953,7 @@ class SAM2VideoPredictor(SAM2Predictor):
1018
953
  run_mem_encoder=True,
1019
954
  )
1020
955
  output_dict[storage_key][frame] = current_out
956
+ self._prune_non_cond_memory(frame)
1021
957
  # Create slices of per-object outputs for subsequent interaction with each
1022
958
  # individual object after tracking.
1023
959
  self._add_output_per_object(frame, current_out, storage_key)
@@ -1028,12 +964,11 @@ class SAM2VideoPredictor(SAM2Predictor):
1028
964
  return pred_masks, torch.ones(pred_masks.shape[0], dtype=pred_masks.dtype, device=pred_masks.device)
1029
965
 
1030
966
  def postprocess(self, preds, img, orig_imgs):
1031
- """
1032
- Post-process the predictions to apply non-overlapping constraints if required.
967
+ """Post-process the predictions to apply non-overlapping constraints if required.
1033
968
 
1034
- This method extends the post-processing functionality by applying non-overlapping constraints
1035
- to the predicted masks if the `non_overlap_masks` flag is set to True. This ensures that
1036
- the masks do not overlap, which can be useful for certain applications.
969
+ This method extends the post-processing functionality by applying non-overlapping constraints to the predicted
970
+ masks if the `non_overlap_masks` flag is set to True. This ensures that the masks do not overlap, which can be
971
+ useful for certain applications.
1037
972
 
1038
973
  Args:
1039
974
  preds (tuple[torch.Tensor, torch.Tensor]): The predicted masks and scores from the model.
@@ -1043,7 +978,7 @@ class SAM2VideoPredictor(SAM2Predictor):
1043
978
  Returns:
1044
979
  (list): The post-processed predictions.
1045
980
 
1046
- Note:
981
+ Notes:
1047
982
  If `non_overlap_masks` is True, the method applies constraints to ensure non-overlapping masks.
1048
983
  """
1049
984
  results = super().postprocess(preds, img, orig_imgs)
@@ -1062,14 +997,14 @@ class SAM2VideoPredictor(SAM2Predictor):
1062
997
  labels=None,
1063
998
  masks=None,
1064
999
  frame_idx=0,
1000
+ inference_state: dict[str, Any] | None = None,
1065
1001
  ):
1066
- """
1067
- Add new points or masks to a specific frame for a given object ID.
1002
+ """Add new points or masks to a specific frame for a given object ID.
1068
1003
 
1069
- This method updates the inference state with new prompts (points or masks) for a specified
1070
- object and frame index. It ensures that the prompts are either points or masks, but not both,
1071
- and updates the internal state accordingly. It also handles the generation of new segmentations
1072
- based on the provided prompts and the existing state.
1004
+ This method updates the inference state with new prompts (points or masks) for a specified object and frame
1005
+ index. It ensures that the prompts are either points or masks, but not both, and updates the internal state
1006
+ accordingly. It also handles the generation of new segmentations based on the provided prompts and the existing
1007
+ state.
1073
1008
 
1074
1009
  Args:
1075
1010
  obj_id (int): The ID of the object to which the prompts are associated.
@@ -1077,6 +1012,8 @@ class SAM2VideoPredictor(SAM2Predictor):
1077
1012
  labels (torch.Tensor, optional): The labels corresponding to the points.
1078
1013
  masks (torch.Tensor, optional): Binary masks for the object.
1079
1014
  frame_idx (int, optional): The index of the frame to which the prompts are applied.
1015
+ inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
1016
+ inference state.
1080
1017
 
1081
1018
  Returns:
1082
1019
  pred_masks (torch.Tensor): The flattened predicted masks.
@@ -1085,29 +1022,30 @@ class SAM2VideoPredictor(SAM2Predictor):
1085
1022
  Raises:
1086
1023
  AssertionError: If both `masks` and `points` are provided, or neither is provided.
1087
1024
 
1088
- Note:
1025
+ Notes:
1089
1026
  - Only one type of prompt (either points or masks) can be added per call.
1090
1027
  - If the frame is being tracked for the first time, it is treated as an initial conditioning frame.
1091
1028
  - The method handles the consolidation of outputs and resizing of masks to the original video resolution.
1092
1029
  """
1030
+ inference_state = inference_state or self.inference_state
1093
1031
  assert (masks is None) ^ (points is None), "'masks' and 'points' prompts are not compatible with each other."
1094
- obj_idx = self._obj_id_to_idx(obj_id)
1032
+ obj_idx = self._obj_id_to_idx(obj_id, inference_state)
1095
1033
 
1096
1034
  point_inputs = None
1097
1035
  pop_key = "point_inputs_per_obj"
1098
1036
  if points is not None:
1099
1037
  point_inputs = {"point_coords": points, "point_labels": labels}
1100
- self.inference_state["point_inputs_per_obj"][obj_idx][frame_idx] = point_inputs
1038
+ inference_state["point_inputs_per_obj"][obj_idx][frame_idx] = point_inputs
1101
1039
  pop_key = "mask_inputs_per_obj"
1102
- self.inference_state["mask_inputs_per_obj"][obj_idx][frame_idx] = masks
1103
- self.inference_state[pop_key][obj_idx].pop(frame_idx, None)
1040
+ inference_state["mask_inputs_per_obj"][obj_idx][frame_idx] = masks
1041
+ inference_state[pop_key][obj_idx].pop(frame_idx, None)
1104
1042
  # If this frame hasn't been tracked before, we treat it as an initial conditioning
1105
1043
  # frame, meaning that the inputs points are to generate segments on this frame without
1106
1044
  # using any memory from other frames, like in SAM. Otherwise (if it has been tracked),
1107
1045
  # the input points will be used to correct the already tracked masks.
1108
- is_init_cond_frame = frame_idx not in self.inference_state["frames_already_tracked"]
1109
- obj_output_dict = self.inference_state["output_dict_per_obj"][obj_idx]
1110
- obj_temp_output_dict = self.inference_state["temp_output_dict_per_obj"][obj_idx]
1046
+ is_init_cond_frame = frame_idx not in inference_state["frames_already_tracked"]
1047
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
1048
+ obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
1111
1049
  # Add a frame to conditioning output if it's an initial conditioning frame or
1112
1050
  # if the model sees all frames receiving clicks/mask as conditioning frames.
1113
1051
  is_cond = is_init_cond_frame or self.model.add_all_frames_to_correct_as_cond
@@ -1145,6 +1083,7 @@ class SAM2VideoPredictor(SAM2Predictor):
1145
1083
  # them into memory.
1146
1084
  run_mem_encoder=False,
1147
1085
  prev_sam_mask_logits=prev_sam_mask_logits,
1086
+ inference_state=inference_state,
1148
1087
  )
1149
1088
  # Add the output to the output dict (to be used as future memory)
1150
1089
  obj_temp_output_dict[storage_key][frame_idx] = current_out
@@ -1154,32 +1093,37 @@ class SAM2VideoPredictor(SAM2Predictor):
1154
1093
  frame_idx,
1155
1094
  is_cond=is_cond,
1156
1095
  run_mem_encoder=False,
1096
+ inference_state=inference_state,
1157
1097
  )
1158
1098
  pred_masks = consolidated_out["pred_masks"].flatten(0, 1)
1159
1099
  return pred_masks.flatten(0, 1), torch.ones(1, dtype=pred_masks.dtype, device=pred_masks.device)
1160
1100
 
1161
1101
  @smart_inference_mode()
1162
- def propagate_in_video_preflight(self):
1163
- """
1164
- Prepare inference_state and consolidate temporary outputs before tracking.
1102
+ def propagate_in_video_preflight(self, inference_state: dict[str, Any] | None = None):
1103
+ """Prepare inference_state and consolidate temporary outputs before tracking.
1165
1104
 
1166
- This method marks the start of tracking, disallowing the addition of new objects until the session is reset.
1167
- It consolidates temporary outputs from `temp_output_dict_per_obj` and merges them into `output_dict`.
1168
- Additionally, it clears non-conditioning memory around input frames and ensures that the state is consistent
1169
- with the provided inputs.
1105
+ This method marks the start of tracking, disallowing the addition of new objects until the session is reset. It
1106
+ consolidates temporary outputs from `temp_output_dict_per_obj` and merges them into `output_dict`. Additionally,
1107
+ it clears non-conditioning memory around input frames and ensures that the state is consistent with the provided
1108
+ inputs.
1109
+
1110
+ Args:
1111
+ inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
1112
+ inference state.
1170
1113
  """
1114
+ inference_state = inference_state or self.inference_state
1171
1115
  # Tracking has started and we don't allow adding new objects until session is reset.
1172
- self.inference_state["tracking_has_started"] = True
1173
- batch_size = len(self.inference_state["obj_idx_to_id"])
1116
+ inference_state["tracking_has_started"] = True
1117
+ batch_size = len(inference_state["obj_idx_to_id"])
1174
1118
 
1175
1119
  # Consolidate per-object temporary outputs in "temp_output_dict_per_obj" and
1176
1120
  # add them into "output_dict".
1177
- temp_output_dict_per_obj = self.inference_state["temp_output_dict_per_obj"]
1178
- output_dict = self.inference_state["output_dict"]
1121
+ temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"]
1122
+ output_dict = inference_state["output_dict"]
1179
1123
  # "consolidated_frame_inds" contains indices of those frames where consolidated
1180
1124
  # temporary outputs have been added (either in this call or any previous calls
1181
1125
  # to `propagate_in_video_preflight`).
1182
- consolidated_frame_inds = self.inference_state["consolidated_frame_inds"]
1126
+ consolidated_frame_inds = inference_state["consolidated_frame_inds"]
1183
1127
  for is_cond in {False, True}:
1184
1128
  # Separately consolidate conditioning and non-conditioning temp outputs
1185
1129
  storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
@@ -1193,11 +1137,11 @@ class SAM2VideoPredictor(SAM2Predictor):
1193
1137
  # consolidate the temporary output across all objects on this frame
1194
1138
  for frame_idx in temp_frame_inds:
1195
1139
  consolidated_out = self._consolidate_temp_output_across_obj(
1196
- frame_idx, is_cond=is_cond, run_mem_encoder=True
1140
+ frame_idx, is_cond=is_cond, run_mem_encoder=True, inference_state=inference_state
1197
1141
  )
1198
1142
  # merge them into "output_dict" and also create per-object slices
1199
1143
  output_dict[storage_key][frame_idx] = consolidated_out
1200
- self._add_output_per_object(frame_idx, consolidated_out, storage_key)
1144
+ self._add_output_per_object(frame_idx, consolidated_out, storage_key, inference_state=inference_state)
1201
1145
  if self.clear_non_cond_mem_around_input and (self.clear_non_cond_mem_for_multi_obj or batch_size <= 1):
1202
1146
  # clear non-conditioning memory of the surrounding frames
1203
1147
  self._clear_non_cond_mem_around_input(frame_idx)
@@ -1210,7 +1154,7 @@ class SAM2VideoPredictor(SAM2Predictor):
1210
1154
  # output on the same frame in "non_cond_frame_outputs"
1211
1155
  for frame_idx in output_dict["cond_frame_outputs"]:
1212
1156
  output_dict["non_cond_frame_outputs"].pop(frame_idx, None)
1213
- for obj_output_dict in self.inference_state["output_dict_per_obj"].values():
1157
+ for obj_output_dict in inference_state["output_dict_per_obj"].values():
1214
1158
  for frame_idx in obj_output_dict["cond_frame_outputs"]:
1215
1159
  obj_output_dict["non_cond_frame_outputs"].pop(frame_idx, None)
1216
1160
  for frame_idx in consolidated_frame_inds["cond_frame_outputs"]:
@@ -1223,20 +1167,19 @@ class SAM2VideoPredictor(SAM2Predictor):
1223
1167
  consolidated_frame_inds["cond_frame_outputs"] | consolidated_frame_inds["non_cond_frame_outputs"]
1224
1168
  )
1225
1169
  input_frames_inds = set()
1226
- for point_inputs_per_frame in self.inference_state["point_inputs_per_obj"].values():
1170
+ for point_inputs_per_frame in inference_state["point_inputs_per_obj"].values():
1227
1171
  input_frames_inds.update(point_inputs_per_frame.keys())
1228
- for mask_inputs_per_frame in self.inference_state["mask_inputs_per_obj"].values():
1172
+ for mask_inputs_per_frame in inference_state["mask_inputs_per_obj"].values():
1229
1173
  input_frames_inds.update(mask_inputs_per_frame.keys())
1230
1174
  assert all_consolidated_frame_inds == input_frames_inds
1231
1175
 
1232
1176
  @staticmethod
1233
1177
  def init_state(predictor):
1234
- """
1235
- Initialize an inference state for the predictor.
1178
+ """Initialize an inference state for the predictor.
1236
1179
 
1237
- This function sets up the initial state required for performing inference on video data.
1238
- It includes initializing various dictionaries and ordered dictionaries that will store
1239
- inputs, outputs, and other metadata relevant to the tracking process.
1180
+ This function sets up the initial state required for performing inference on video data. It includes
1181
+ initializing various dictionaries and ordered dictionaries that will store inputs, outputs, and other metadata
1182
+ relevant to the tracking process.
1240
1183
 
1241
1184
  Args:
1242
1185
  predictor (SAM2VideoPredictor): The predictor object for which to initialize the state.
@@ -1245,9 +1188,21 @@ class SAM2VideoPredictor(SAM2Predictor):
1245
1188
  return
1246
1189
  assert predictor.dataset is not None
1247
1190
  assert predictor.dataset.mode == "video"
1191
+ predictor.inference_state = predictor._init_state(predictor.dataset.frames)
1192
+
1193
+ @staticmethod
1194
+ def _init_state(num_frames):
1195
+ """Initialize an inference state.
1196
+
1197
+ This function sets up the initial state required for performing inference on video data. It includes
1198
+ initializing various dictionaries and ordered dictionaries that will store inputs, outputs, and other metadata
1199
+ relevant to the tracking process.
1248
1200
 
1201
+ Args:
1202
+ num_frames (int): The number of frames in the video.
1203
+ """
1249
1204
  inference_state = {
1250
- "num_frames": predictor.dataset.frames,
1205
+ "num_frames": num_frames, # TODO: see if there's any chance to remove it
1251
1206
  "point_inputs_per_obj": {}, # inputs points on each frame
1252
1207
  "mask_inputs_per_obj": {}, # inputs mask on each frame
1253
1208
  "constants": {}, # values that don't change across frames (so we only need to hold one copy of them)
@@ -1275,11 +1230,10 @@ class SAM2VideoPredictor(SAM2Predictor):
1275
1230
  "tracking_has_started": False,
1276
1231
  "frames_already_tracked": [],
1277
1232
  }
1278
- predictor.inference_state = inference_state
1233
+ return inference_state
1279
1234
 
1280
1235
  def get_im_features(self, im, batch=1):
1281
- """
1282
- Extract and process image features using SAM2's image encoder for subsequent segmentation tasks.
1236
+ """Extract and process image features using SAM2's image encoder for subsequent segmentation tasks.
1283
1237
 
1284
1238
  Args:
1285
1239
  im (torch.Tensor): The input image tensor.
@@ -1290,27 +1244,24 @@ class SAM2VideoPredictor(SAM2Predictor):
1290
1244
  vis_pos_embed (torch.Tensor): The positional embeddings for the visual features.
1291
1245
  feat_sizes (list[tuple]): A list containing the sizes of the extracted features.
1292
1246
 
1293
- Note:
1247
+ Notes:
1294
1248
  - If `batch` is greater than 1, the features are expanded to fit the batch size.
1295
1249
  - The method leverages the model's `_prepare_backbone_features` method to prepare the backbone features.
1296
1250
  """
1297
- self.model.set_imgsz(self.imgsz)
1298
- backbone_out = self.model.forward_image(im)
1299
- if batch > 1: # expand features if there's more than one prompt
1300
- for i, feat in enumerate(backbone_out["backbone_fpn"]):
1301
- backbone_out["backbone_fpn"][i] = feat.expand(batch, -1, -1, -1)
1302
- for i, pos in enumerate(backbone_out["vision_pos_enc"]):
1303
- pos = pos.expand(batch, -1, -1, -1)
1304
- backbone_out["vision_pos_enc"][i] = pos
1305
- _, vis_feats, vis_pos_embed, feat_sizes = self.model._prepare_backbone_features(backbone_out)
1251
+ # check if there's precomputed backbone output
1252
+ backbone_out = getattr(self, "backbone_out", None)
1253
+ if backbone_out is None:
1254
+ backbone_out = self.model.forward_image(im)
1255
+ _, vis_feats, vis_pos_embed, feat_sizes = self.model._prepare_backbone_features(backbone_out, batch=batch)
1306
1256
  return vis_feats, vis_pos_embed, feat_sizes
1307
1257
 
1308
- def _obj_id_to_idx(self, obj_id):
1309
- """
1310
- Map client-side object id to model-side object index.
1258
+ def _obj_id_to_idx(self, obj_id, inference_state: dict[str, Any] | None = None):
1259
+ """Map client-side object id to model-side object index.
1311
1260
 
1312
1261
  Args:
1313
1262
  obj_id (int): The unique identifier of the object provided by the client side.
1263
+ inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
1264
+ inference state.
1314
1265
 
1315
1266
  Returns:
1316
1267
  (int): The index of the object on the model side.
@@ -1318,34 +1269,35 @@ class SAM2VideoPredictor(SAM2Predictor):
1318
1269
  Raises:
1319
1270
  RuntimeError: If an attempt is made to add a new object after tracking has started.
1320
1271
 
1321
- Note:
1272
+ Notes:
1322
1273
  - The method updates or retrieves mappings between object IDs and indices stored in
1323
1274
  `inference_state`.
1324
1275
  - It ensures that new objects can only be added before tracking commences.
1325
1276
  - It maintains two-way mappings between IDs and indices (`obj_id_to_idx` and `obj_idx_to_id`).
1326
1277
  - Additional data structures are initialized for the new object to store inputs and outputs.
1327
1278
  """
1328
- obj_idx = self.inference_state["obj_id_to_idx"].get(obj_id, None)
1279
+ inference_state = inference_state or self.inference_state
1280
+ obj_idx = inference_state["obj_id_to_idx"].get(obj_id, None)
1329
1281
  if obj_idx is not None:
1330
1282
  return obj_idx
1331
1283
 
1332
1284
  # This is a new object id not sent to the server before. We only allow adding
1333
1285
  # new objects *before* the tracking starts.
1334
- allow_new_object = not self.inference_state["tracking_has_started"]
1286
+ allow_new_object = not inference_state["tracking_has_started"]
1335
1287
  if allow_new_object:
1336
1288
  # get the next object slot
1337
- obj_idx = len(self.inference_state["obj_id_to_idx"])
1338
- self.inference_state["obj_id_to_idx"][obj_id] = obj_idx
1339
- self.inference_state["obj_idx_to_id"][obj_idx] = obj_id
1340
- self.inference_state["obj_ids"] = list(self.inference_state["obj_id_to_idx"])
1289
+ obj_idx = len(inference_state["obj_id_to_idx"])
1290
+ inference_state["obj_id_to_idx"][obj_id] = obj_idx
1291
+ inference_state["obj_idx_to_id"][obj_idx] = obj_id
1292
+ inference_state["obj_ids"] = list(inference_state["obj_id_to_idx"])
1341
1293
  # set up input and output structures for this object
1342
- self.inference_state["point_inputs_per_obj"][obj_idx] = {}
1343
- self.inference_state["mask_inputs_per_obj"][obj_idx] = {}
1344
- self.inference_state["output_dict_per_obj"][obj_idx] = {
1294
+ inference_state["point_inputs_per_obj"][obj_idx] = {}
1295
+ inference_state["mask_inputs_per_obj"][obj_idx] = {}
1296
+ inference_state["output_dict_per_obj"][obj_idx] = {
1345
1297
  "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
1346
1298
  "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
1347
1299
  }
1348
- self.inference_state["temp_output_dict_per_obj"][obj_idx] = {
1300
+ inference_state["temp_output_dict_per_obj"][obj_idx] = {
1349
1301
  "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
1350
1302
  "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
1351
1303
  }
@@ -1353,7 +1305,7 @@ class SAM2VideoPredictor(SAM2Predictor):
1353
1305
  else:
1354
1306
  raise RuntimeError(
1355
1307
  f"Cannot add new object id {obj_id} after tracking starts. "
1356
- f"All existing object ids: {self.inference_state['obj_ids']}. "
1308
+ f"All existing object ids: {inference_state['obj_ids']}. "
1357
1309
  f"Please call 'reset_state' to restart from scratch."
1358
1310
  )
1359
1311
 
@@ -1368,9 +1320,9 @@ class SAM2VideoPredictor(SAM2Predictor):
1368
1320
  reverse,
1369
1321
  run_mem_encoder,
1370
1322
  prev_sam_mask_logits=None,
1323
+ inference_state: dict[str, Any] | None = None,
1371
1324
  ):
1372
- """
1373
- Run tracking on a single frame based on current inputs and previous memory.
1325
+ """Run tracking on a single frame based on current inputs and previous memory.
1374
1326
 
1375
1327
  Args:
1376
1328
  output_dict (dict): The dictionary containing the output states of the tracking process.
@@ -1382,6 +1334,8 @@ class SAM2VideoPredictor(SAM2Predictor):
1382
1334
  reverse (bool): Indicates if the tracking should be performed in reverse order.
1383
1335
  run_mem_encoder (bool): Indicates if the memory encoder should be executed.
1384
1336
  prev_sam_mask_logits (torch.Tensor | None): Previous mask logits for the current object.
1337
+ inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
1338
+ inference state.
1385
1339
 
1386
1340
  Returns:
1387
1341
  (dict): A dictionary containing the output of the tracking step, including updated features and predictions.
@@ -1389,15 +1343,16 @@ class SAM2VideoPredictor(SAM2Predictor):
1389
1343
  Raises:
1390
1344
  AssertionError: If both `point_inputs` and `mask_inputs` are provided, or neither is provided.
1391
1345
 
1392
- Note:
1346
+ Notes:
1393
1347
  - The method assumes that `point_inputs` and `mask_inputs` are mutually exclusive.
1394
1348
  - The method retrieves image features using the `get_im_features` method.
1395
1349
  - The `maskmem_pos_enc` is assumed to be constant across frames, hence only one copy is stored.
1396
1350
  - The `fill_holes_in_mask_scores` function is commented out and currently unsupported due to CUDA extension requirements.
1397
1351
  """
1352
+ inference_state = inference_state or self.inference_state
1398
1353
  # Retrieve correct image features
1399
1354
  current_vision_feats, current_vision_pos_embeds, feat_sizes = self.get_im_features(
1400
- self.inference_state["im"], batch_size
1355
+ inference_state["im"], batch_size
1401
1356
  )
1402
1357
 
1403
1358
  # point and mask should not appear as input simultaneously on the same frame
@@ -1411,7 +1366,7 @@ class SAM2VideoPredictor(SAM2Predictor):
1411
1366
  point_inputs=point_inputs,
1412
1367
  mask_inputs=mask_inputs,
1413
1368
  output_dict=output_dict,
1414
- num_frames=self.inference_state["num_frames"],
1369
+ num_frames=inference_state["num_frames"],
1415
1370
  track_in_reverse=reverse,
1416
1371
  run_mem_encoder=run_mem_encoder,
1417
1372
  prev_sam_mask_logits=prev_sam_mask_logits,
@@ -1429,34 +1384,35 @@ class SAM2VideoPredictor(SAM2Predictor):
1429
1384
  # pred_masks = fill_holes_in_mask_scores(pred_masks, self.fill_hole_area)
1430
1385
 
1431
1386
  # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
1432
- current_out["maskmem_pos_enc"] = self._get_maskmem_pos_enc(current_out["maskmem_pos_enc"])
1387
+ current_out["maskmem_pos_enc"] = self._get_maskmem_pos_enc(current_out["maskmem_pos_enc"], inference_state)
1433
1388
  return current_out
1434
1389
 
1435
- def _get_maskmem_pos_enc(self, out_maskmem_pos_enc):
1436
- """
1437
- Cache and manage the positional encoding for mask memory across frames and objects.
1390
+ def _get_maskmem_pos_enc(self, out_maskmem_pos_enc, inference_state: dict[str, Any] | None = None):
1391
+ """Cache and manage the positional encoding for mask memory across frames and objects.
1438
1392
 
1439
- This method optimizes storage by caching the positional encoding (`maskmem_pos_enc`) for
1440
- mask memory, which is constant across frames and objects, thus reducing the amount of
1441
- redundant information stored during an inference session. It checks if the positional
1442
- encoding has already been cached; if not, it caches a slice of the provided encoding.
1443
- If the batch size is greater than one, it expands the cached positional encoding to match
1444
- the current batch size.
1393
+ This method optimizes storage by caching the positional encoding (`maskmem_pos_enc`) for mask memory, which is
1394
+ constant across frames and objects, thus reducing the amount of redundant information stored during an inference
1395
+ session. It checks if the positional encoding has already been cached; if not, it caches a slice of the provided
1396
+ encoding. If the batch size is greater than one, it expands the cached positional encoding to match the current
1397
+ batch size.
1445
1398
 
1446
1399
  Args:
1447
- out_maskmem_pos_enc (list[torch.Tensor] | None): The positional encoding for mask memory.
1448
- Should be a list of tensors or None.
1400
+ out_maskmem_pos_enc (list[torch.Tensor] | None): The positional encoding for mask memory. Should be a list
1401
+ of tensors or None.
1402
+ inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
1403
+ inference state.
1449
1404
 
1450
1405
  Returns:
1451
1406
  (list[torch.Tensor]): The positional encoding for mask memory, either cached or expanded.
1452
1407
 
1453
- Note:
1408
+ Notes:
1454
1409
  - The method assumes that `out_maskmem_pos_enc` is a list of tensors or None.
1455
1410
  - Only a single object's slice is cached since the encoding is the same across objects.
1456
1411
  - The method checks if the positional encoding has already been cached in the session's constants.
1457
1412
  - If the batch size is greater than one, the cached encoding is expanded to fit the batch size.
1458
1413
  """
1459
- model_constants = self.inference_state["constants"]
1414
+ inference_state = inference_state or self.inference_state
1415
+ model_constants = inference_state["constants"]
1460
1416
  # "out_maskmem_pos_enc" should be either a list of tensors or None
1461
1417
  if out_maskmem_pos_enc is not None:
1462
1418
  if "maskmem_pos_enc" not in model_constants:
@@ -1477,31 +1433,34 @@ class SAM2VideoPredictor(SAM2Predictor):
1477
1433
  frame_idx,
1478
1434
  is_cond=False,
1479
1435
  run_mem_encoder=False,
1436
+ inference_state: dict[str, Any] | None = None,
1480
1437
  ):
1481
- """
1482
- Consolidate per-object temporary outputs into a single output for all objects.
1438
+ """Consolidate per-object temporary outputs into a single output for all objects.
1483
1439
 
1484
1440
  This method combines the temporary outputs for each object on a given frame into a unified
1485
1441
  output. It fills in any missing objects either from the main output dictionary or leaves
1486
- placeholders if they do not exist in the main output. Optionally, it can re-run the memory
1487
- encoder after applying non-overlapping constraints to the object scores.
1442
+ placeholders if they do not exist in the main output. Optionally, it can re-run the memory encoder after
1443
+ applying non-overlapping constraints to the object scores.
1488
1444
 
1489
1445
  Args:
1490
1446
  frame_idx (int): The index of the frame for which to consolidate outputs.
1491
1447
  is_cond (bool, optional): Indicates if the frame is considered a conditioning frame.
1492
- run_mem_encoder (bool, optional): Specifies whether to run the memory encoder after
1493
- consolidating the outputs.
1448
+ run_mem_encoder (bool, optional): Specifies whether to run the memory encoder after consolidating the
1449
+ outputs.
1450
+ inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
1451
+ inference state.
1494
1452
 
1495
1453
  Returns:
1496
1454
  (dict): A consolidated output dictionary containing the combined results for all objects.
1497
1455
 
1498
- Note:
1456
+ Notes:
1499
1457
  - The method initializes the consolidated output with placeholder values for missing objects.
1500
1458
  - It searches for outputs in both the temporary and main output dictionaries.
1501
1459
  - If `run_mem_encoder` is True, it applies non-overlapping constraints and re-runs the memory encoder.
1502
1460
  - The `maskmem_features` and `maskmem_pos_enc` are only populated when `run_mem_encoder` is True.
1503
1461
  """
1504
- batch_size = len(self.inference_state["obj_idx_to_id"])
1462
+ inference_state = inference_state or self.inference_state
1463
+ batch_size = len(inference_state["obj_idx_to_id"])
1505
1464
  storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
1506
1465
 
1507
1466
  # Initialize `consolidated_out`. Its "maskmem_features" and "maskmem_pos_enc"
@@ -1512,7 +1471,8 @@ class SAM2VideoPredictor(SAM2Predictor):
1512
1471
  "maskmem_features": None,
1513
1472
  "maskmem_pos_enc": None,
1514
1473
  "pred_masks": torch.full(
1515
- size=(batch_size, 1, self.imgsz[0] // 4, self.imgsz[1] // 4),
1474
+ # size=(batch_size, 1, self.imgsz[0] // 4, self.imgsz[1] // 4),
1475
+ size=(batch_size, 1, *self._bb_feat_sizes[0]),
1516
1476
  fill_value=-1024.0,
1517
1477
  dtype=self.torch_dtype,
1518
1478
  device=self.device,
@@ -1533,8 +1493,8 @@ class SAM2VideoPredictor(SAM2Predictor):
1533
1493
  ),
1534
1494
  }
1535
1495
  for obj_idx in range(batch_size):
1536
- obj_temp_output_dict = self.inference_state["temp_output_dict_per_obj"][obj_idx]
1537
- obj_output_dict = self.inference_state["output_dict_per_obj"][obj_idx]
1496
+ obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
1497
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
1538
1498
  out = (
1539
1499
  obj_temp_output_dict[storage_key].get(frame_idx)
1540
1500
  # If the object doesn't appear in "temp_output_dict_per_obj" on this frame,
@@ -1574,22 +1534,25 @@ class SAM2VideoPredictor(SAM2Predictor):
1574
1534
  high_res_masks=high_res_masks,
1575
1535
  is_mask_from_pts=True, # these frames are what the user interacted with
1576
1536
  object_score_logits=consolidated_out["object_score_logits"],
1537
+ inference_state=inference_state,
1577
1538
  )
1578
1539
 
1579
1540
  return consolidated_out
1580
1541
 
1581
- def _get_empty_mask_ptr(self, frame_idx):
1582
- """
1583
- Get a dummy object pointer based on an empty mask on the current frame.
1542
+ def _get_empty_mask_ptr(self, frame_idx, inference_state: dict[str, Any] | None = None):
1543
+ """Get a dummy object pointer based on an empty mask on the current frame.
1584
1544
 
1585
1545
  Args:
1586
1546
  frame_idx (int): The index of the current frame for which to generate the dummy object pointer.
1547
+ inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
1548
+ inference state.
1587
1549
 
1588
1550
  Returns:
1589
1551
  (torch.Tensor): A tensor representing the dummy object pointer generated from the empty mask.
1590
1552
  """
1553
+ inference_state = inference_state or self.inference_state
1591
1554
  # Retrieve correct image features
1592
- current_vision_feats, current_vision_pos_embeds, feat_sizes = self.get_im_features(self.inference_state["im"])
1555
+ current_vision_feats, current_vision_pos_embeds, feat_sizes = self.get_im_features(inference_state["im"])
1593
1556
 
1594
1557
  # Feed the empty mask and image feature above to get a dummy object pointer
1595
1558
  current_out = self.model.track_step(
@@ -1602,16 +1565,22 @@ class SAM2VideoPredictor(SAM2Predictor):
1602
1565
  # A dummy (empty) mask with a single object
1603
1566
  mask_inputs=torch.zeros((1, 1, *self.imgsz), dtype=self.torch_dtype, device=self.device),
1604
1567
  output_dict={},
1605
- num_frames=self.inference_state["num_frames"],
1568
+ num_frames=inference_state["num_frames"],
1606
1569
  track_in_reverse=False,
1607
1570
  run_mem_encoder=False,
1608
1571
  prev_sam_mask_logits=None,
1609
1572
  )
1610
1573
  return current_out["obj_ptr"]
1611
1574
 
1612
- def _run_memory_encoder(self, batch_size, high_res_masks, object_score_logits, is_mask_from_pts):
1613
- """
1614
- Run the memory encoder on masks.
1575
+ def _run_memory_encoder(
1576
+ self,
1577
+ batch_size,
1578
+ high_res_masks,
1579
+ object_score_logits,
1580
+ is_mask_from_pts,
1581
+ inference_state: dict[str, Any] | None = None,
1582
+ ):
1583
+ """Run the memory encoder on masks.
1615
1584
 
1616
1585
  This is usually after applying non-overlapping constraints to object scores. Since their scores changed, their
1617
1586
  memory also needs to be computed again with the memory encoder.
@@ -1621,13 +1590,16 @@ class SAM2VideoPredictor(SAM2Predictor):
1621
1590
  high_res_masks (torch.Tensor): High-resolution masks for which to compute the memory.
1622
1591
  object_score_logits (torch.Tensor): Logits representing the object scores.
1623
1592
  is_mask_from_pts (bool): Indicates if the mask is derived from point interactions.
1593
+ inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
1594
+ inference state.
1624
1595
 
1625
1596
  Returns:
1626
1597
  maskmem_features (torch.Tensor): The encoded mask features.
1627
1598
  maskmem_pos_enc (torch.Tensor): The positional encoding.
1628
1599
  """
1600
+ inference_state = inference_state or self.inference_state
1629
1601
  # Retrieve correct image features
1630
- current_vision_feats, _, feat_sizes = self.get_im_features(self.inference_state["im"], batch_size)
1602
+ current_vision_feats, _, feat_sizes = self.get_im_features(inference_state["im"], batch_size)
1631
1603
  maskmem_features, maskmem_pos_enc = self.model._encode_new_memory(
1632
1604
  current_vision_feats=current_vision_feats,
1633
1605
  feat_sizes=feat_sizes,
@@ -1637,14 +1609,15 @@ class SAM2VideoPredictor(SAM2Predictor):
1637
1609
  )
1638
1610
 
1639
1611
  # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
1640
- maskmem_pos_enc = self._get_maskmem_pos_enc(maskmem_pos_enc)
1612
+ maskmem_pos_enc = self._get_maskmem_pos_enc(maskmem_pos_enc, inference_state)
1641
1613
  return maskmem_features.to(
1642
1614
  dtype=torch.float16, device=self.device, non_blocking=self.device.type == "cuda"
1643
1615
  ), maskmem_pos_enc
1644
1616
 
1645
- def _add_output_per_object(self, frame_idx, current_out, storage_key):
1646
- """
1647
- Split a multi-object output into per-object output slices and add them into Output_Dict_Per_Obj.
1617
+ def _add_output_per_object(
1618
+ self, frame_idx, current_out, storage_key, inference_state: dict[str, Any] | None = None
1619
+ ):
1620
+ """Split a multi-object output into per-object output slices and add them into Output_Dict_Per_Obj.
1648
1621
 
1649
1622
  The resulting slices share the same tensor storage.
1650
1623
 
@@ -1652,14 +1625,17 @@ class SAM2VideoPredictor(SAM2Predictor):
1652
1625
  frame_idx (int): The index of the current frame.
1653
1626
  current_out (dict): The current output dictionary containing multi-object outputs.
1654
1627
  storage_key (str): The key used to store the output in the per-object output dictionary.
1628
+ inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
1629
+ inference state.
1655
1630
  """
1631
+ inference_state = inference_state or self.inference_state
1656
1632
  maskmem_features = current_out["maskmem_features"]
1657
1633
  assert maskmem_features is None or isinstance(maskmem_features, torch.Tensor)
1658
1634
 
1659
1635
  maskmem_pos_enc = current_out["maskmem_pos_enc"]
1660
1636
  assert maskmem_pos_enc is None or isinstance(maskmem_pos_enc, list)
1661
1637
 
1662
- for obj_idx, obj_output_dict in self.inference_state["output_dict_per_obj"].items():
1638
+ for obj_idx, obj_output_dict in inference_state["output_dict_per_obj"].items():
1663
1639
  obj_slice = slice(obj_idx, obj_idx + 1)
1664
1640
  obj_out = {
1665
1641
  "maskmem_features": None,
@@ -1673,29 +1649,212 @@ class SAM2VideoPredictor(SAM2Predictor):
1673
1649
  obj_out["maskmem_pos_enc"] = [x[obj_slice] for x in maskmem_pos_enc]
1674
1650
  obj_output_dict[storage_key][frame_idx] = obj_out
1675
1651
 
1676
- def _clear_non_cond_mem_around_input(self, frame_idx):
1677
- """
1678
- Remove the non-conditioning memory around the input frame.
1652
+ def _clear_non_cond_mem_around_input(self, frame_idx, inference_state: dict[str, Any] | None = None):
1653
+ """Remove the non-conditioning memory around the input frame.
1679
1654
 
1680
- When users provide correction clicks, the surrounding frames' non-conditioning memories can still contain outdated
1681
- object appearance information and could confuse the model. This method clears those non-conditioning memories
1682
- surrounding the interacted frame to avoid giving the model both old and new information about the object.
1655
+ When users provide correction clicks, the surrounding frames' non-conditioning memories can still contain
1656
+ outdated object appearance information and could confuse the model. This method clears those non-conditioning
1657
+ memories surrounding the interacted frame to avoid giving the model both old and new information about the
1658
+ object.
1683
1659
 
1684
1660
  Args:
1685
1661
  frame_idx (int): The index of the current frame where user interaction occurred.
1662
+ inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
1663
+ inference state.
1686
1664
  """
1665
+ inference_state = inference_state or self.inference_state
1687
1666
  r = self.model.memory_temporal_stride_for_eval
1688
1667
  frame_idx_begin = frame_idx - r * self.model.num_maskmem
1689
1668
  frame_idx_end = frame_idx + r * self.model.num_maskmem
1690
1669
  for t in range(frame_idx_begin, frame_idx_end + 1):
1691
- self.inference_state["output_dict"]["non_cond_frame_outputs"].pop(t, None)
1692
- for obj_output_dict in self.inference_state["output_dict_per_obj"].values():
1670
+ inference_state["output_dict"]["non_cond_frame_outputs"].pop(t, None)
1671
+ for obj_output_dict in inference_state["output_dict_per_obj"].values():
1693
1672
  obj_output_dict["non_cond_frame_outputs"].pop(t, None)
1694
1673
 
1674
+ @smart_inference_mode()
1675
+ def remove_object(self, inference_state, obj_id, strict=False):
1676
+ """Remove an object id from the tracking state. If strict is True, we check whether the object id actually
1677
+ exists and raise an error if it doesn't exist.
1678
+ """
1679
+ old_obj_idx_to_rm = inference_state["obj_id_to_idx"].get(obj_id, None)
1680
+ # Check whether this object_id to remove actually exists and possibly raise an error.
1681
+ if old_obj_idx_to_rm is None:
1682
+ if not strict:
1683
+ return inference_state["obj_ids"]
1684
+ raise RuntimeError(
1685
+ f"Cannot remove object id {obj_id} as it doesn't exist. "
1686
+ f"All existing object ids: {inference_state['obj_ids']}."
1687
+ )
1688
+
1689
+ # If this is the only remaining object id, we simply reset the state.
1690
+ if len(inference_state["obj_id_to_idx"]) == 1:
1691
+ self.clear_all_points_in_video(inference_state)
1692
+ return inference_state["obj_ids"]
1693
+
1694
+ # There are still remaining objects after removing this object id. In this case,
1695
+ # we need to delete the object storage from inference state tensors.
1696
+ # Step 0: clear the input on those frames where this object id has point or mask input
1697
+ # (note that this step is required as it might downgrade conditioning frames to
1698
+ # non-conditioning ones)
1699
+ obj_input_frames_inds = set()
1700
+ obj_input_frames_inds.update(inference_state["point_inputs_per_obj"][old_obj_idx_to_rm])
1701
+ obj_input_frames_inds.update(inference_state["mask_inputs_per_obj"][old_obj_idx_to_rm])
1702
+ for frame_idx in obj_input_frames_inds:
1703
+ self.clear_all_points_in_frame(inference_state, frame_idx, obj_id)
1704
+
1705
+ # Step 1: Update the object id mapping (note that it must be done after Step 0,
1706
+ # since Step 0 still requires the old object id mappings in inference_state)
1707
+ old_obj_ids = inference_state["obj_ids"]
1708
+ old_obj_inds = list(range(len(old_obj_ids)))
1709
+ remain_old_obj_inds = old_obj_inds.copy()
1710
+ remain_old_obj_inds.remove(old_obj_idx_to_rm)
1711
+ new_obj_ids = [old_obj_ids[old_idx] for old_idx in remain_old_obj_inds]
1712
+ new_obj_inds = list(range(len(new_obj_ids)))
1713
+ # build new mappings
1714
+ old_idx_to_new_idx = dict(zip(remain_old_obj_inds, new_obj_inds))
1715
+ inference_state["obj_id_to_idx"] = dict(zip(new_obj_ids, new_obj_inds))
1716
+ inference_state["obj_idx_to_id"] = dict(zip(new_obj_inds, new_obj_ids))
1717
+ inference_state["obj_ids"] = new_obj_ids
1718
+
1719
+ # Step 2: For per-object tensor storage, we shift their obj_idx in the dict keys.
1720
+ # (note that "consolidated_frame_inds" doesn't need to be updated in this step as
1721
+ # it's already handled in Step 0)
1722
+ def _map_keys(container):
1723
+ new_kvs = []
1724
+ for k in old_obj_inds:
1725
+ v = container.pop(k)
1726
+ if k in old_idx_to_new_idx:
1727
+ new_kvs.append((old_idx_to_new_idx[k], v))
1728
+ container.update(new_kvs)
1729
+
1730
+ _map_keys(inference_state["point_inputs_per_obj"])
1731
+ _map_keys(inference_state["mask_inputs_per_obj"])
1732
+ _map_keys(inference_state["output_dict_per_obj"])
1733
+ _map_keys(inference_state["temp_output_dict_per_obj"])
1734
+
1735
+ # Step 3: For packed tensor storage, we index the remaining ids and rebuild the per-object slices.
1736
+ def _slice_state(output_dict, storage_key):
1737
+ for frame_idx, out in output_dict[storage_key].items():
1738
+ out["maskmem_features"] = out["maskmem_features"][remain_old_obj_inds]
1739
+ out["maskmem_pos_enc"] = [x[remain_old_obj_inds] for x in out["maskmem_pos_enc"]]
1740
+ # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
1741
+ out["maskmem_pos_enc"] = self._get_maskmem_pos_enc(out["maskmem_pos_enc"], inference_state)
1742
+ out["pred_masks"] = out["pred_masks"][remain_old_obj_inds]
1743
+ out["obj_ptr"] = out["obj_ptr"][remain_old_obj_inds]
1744
+ out["object_score_logits"] = out["object_score_logits"][remain_old_obj_inds]
1745
+ # also update the per-object slices
1746
+ self._add_output_per_object(frame_idx, out, storage_key, inference_state=inference_state)
1747
+
1748
+ _slice_state(inference_state["output_dict"], "cond_frame_outputs")
1749
+ _slice_state(inference_state["output_dict"], "non_cond_frame_outputs")
1750
+
1751
+ return inference_state["obj_ids"]
1752
+
1753
+ @smart_inference_mode()
1754
+ def clear_all_points_in_frame(self, inference_state, frame_idx, obj_id):
1755
+ """Remove all input points or mask in a specific frame for a given object."""
1756
+ obj_idx = self._obj_id_to_idx(obj_id, inference_state)
1757
+
1758
+ # Clear the conditioning information on the given frame
1759
+ inference_state["point_inputs_per_obj"][obj_idx].pop(frame_idx, None)
1760
+ inference_state["mask_inputs_per_obj"][obj_idx].pop(frame_idx, None)
1761
+
1762
+ temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"]
1763
+ temp_output_dict_per_obj[obj_idx]["cond_frame_outputs"].pop(frame_idx, None)
1764
+ temp_output_dict_per_obj[obj_idx]["non_cond_frame_outputs"].pop(frame_idx, None)
1765
+
1766
+ # Check and see if there are still any inputs left on this frame
1767
+ batch_size = len(inference_state["obj_idx_to_id"])
1768
+ frame_has_input = False
1769
+ for obj_idx2 in range(batch_size):
1770
+ if frame_idx in inference_state["point_inputs_per_obj"][obj_idx2]:
1771
+ frame_has_input = True
1772
+ break
1773
+ if frame_idx in inference_state["mask_inputs_per_obj"][obj_idx2]:
1774
+ frame_has_input = True
1775
+ break
1776
+
1777
+ # If this frame has no remaining inputs for any objects, we further clear its
1778
+ # conditioning frame status
1779
+ if not frame_has_input:
1780
+ output_dict = inference_state["output_dict"]
1781
+ consolidated_frame_inds = inference_state["consolidated_frame_inds"]
1782
+ consolidated_frame_inds["cond_frame_outputs"].discard(frame_idx)
1783
+ consolidated_frame_inds["non_cond_frame_outputs"].discard(frame_idx)
1784
+ # Remove the frame's conditioning output (possibly downgrading it to non-conditioning)
1785
+ out = output_dict["cond_frame_outputs"].pop(frame_idx, None)
1786
+ if out is not None:
1787
+ # The frame is not a conditioning frame anymore since it's not receiving inputs,
1788
+ # so we "downgrade" its output (if exists) to a non-conditioning frame output.
1789
+ output_dict["non_cond_frame_outputs"][frame_idx] = out
1790
+ inference_state["frames_already_tracked"].pop(frame_idx, None)
1791
+ # Similarly, do it for the sliced output on each object.
1792
+ for obj_idx2 in range(batch_size):
1793
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx2]
1794
+ obj_out = obj_output_dict["cond_frame_outputs"].pop(frame_idx, None)
1795
+ if obj_out is not None:
1796
+ obj_output_dict["non_cond_frame_outputs"][frame_idx] = obj_out
1797
+
1798
+ # If all the conditioning frames have been removed, we also clear the tracking outputs
1799
+ if len(output_dict["cond_frame_outputs"]) == 0:
1800
+ self._reset_tracking_results(inference_state)
1801
+
1802
+ @smart_inference_mode()
1803
+ def clear_all_points_in_video(self, inference_state):
1804
+ """Remove all input points or mask in all frames throughout the video."""
1805
+ self._reset_tracking_results(inference_state)
1806
+ # Remove all object ids
1807
+ inference_state["obj_id_to_idx"].clear()
1808
+ inference_state["obj_idx_to_id"].clear()
1809
+ inference_state["obj_ids"].clear()
1810
+ inference_state["point_inputs_per_obj"].clear()
1811
+ inference_state["mask_inputs_per_obj"].clear()
1812
+ inference_state["output_dict_per_obj"].clear()
1813
+ inference_state["temp_output_dict_per_obj"].clear()
1814
+
1815
+ @staticmethod
1816
+ def _reset_tracking_results(inference_state):
1817
+ """Reset all tracking inputs and results across the videos."""
1818
+ for v in inference_state["point_inputs_per_obj"].values():
1819
+ v.clear()
1820
+ for v in inference_state["mask_inputs_per_obj"].values():
1821
+ v.clear()
1822
+ for v in inference_state["output_dict_per_obj"].values():
1823
+ v["cond_frame_outputs"].clear()
1824
+ v["non_cond_frame_outputs"].clear()
1825
+ for v in inference_state["temp_output_dict_per_obj"].values():
1826
+ v["cond_frame_outputs"].clear()
1827
+ v["non_cond_frame_outputs"].clear()
1828
+ inference_state["output_dict"]["cond_frame_outputs"].clear()
1829
+ inference_state["output_dict"]["non_cond_frame_outputs"].clear()
1830
+ inference_state["consolidated_frame_inds"]["cond_frame_outputs"].clear()
1831
+ inference_state["consolidated_frame_inds"]["non_cond_frame_outputs"].clear()
1832
+ inference_state["tracking_has_started"] = False
1833
+ inference_state["frames_already_tracked"].clear()
1834
+ inference_state["first_ann_frame_idx"] = None
1835
+
1836
+ def _prune_non_cond_memory(self, frame_idx, inference_state=None):
1837
+ """Prune old non-conditioning frames to bound memory usage."""
1838
+ if not self.clear_non_cond_mem:
1839
+ return
1840
+ inference_state = inference_state or self.inference_state
1841
+
1842
+ # Determine window size
1843
+ min_frame = frame_idx - self.model.num_maskmem * self.model.memory_temporal_stride_for_eval
1844
+ output_dict = inference_state["output_dict"]
1845
+
1846
+ # Prune global non_cond_frame_outputs
1847
+ for f in [k for k in output_dict["non_cond_frame_outputs"] if k < min_frame]:
1848
+ output_dict["non_cond_frame_outputs"].pop(f, None)
1849
+
1850
+ # Prune per-object non_cond_frame_outputs
1851
+ for obj_output_dict in inference_state.get("output_dict_per_obj", {}).values():
1852
+ for f in [k for k in obj_output_dict["non_cond_frame_outputs"] if k < min_frame]:
1853
+ obj_output_dict["non_cond_frame_outputs"].pop(f, None)
1854
+
1695
1855
 
1696
1856
  class SAM2DynamicInteractivePredictor(SAM2Predictor):
1697
- """
1698
- SAM2DynamicInteractivePredictor extends SAM2Predictor to support dynamic interactions with video frames or a
1857
+ """SAM2DynamicInteractivePredictor extends SAM2Predictor to support dynamic interactions with video frames or a
1699
1858
  sequence of images.
1700
1859
 
1701
1860
  Attributes:
@@ -1727,8 +1886,7 @@ class SAM2DynamicInteractivePredictor(SAM2Predictor):
1727
1886
  max_obj_num: int = 3,
1728
1887
  _callbacks: dict[str, Any] | None = None,
1729
1888
  ) -> None:
1730
- """
1731
- Initialize the predictor with configuration and optional overrides.
1889
+ """Initialize the predictor with configuration and optional overrides.
1732
1890
 
1733
1891
  This constructor initializes the SAM2DynamicInteractivePredictor with a given configuration, applies any
1734
1892
  specified overrides
@@ -1736,15 +1894,9 @@ class SAM2DynamicInteractivePredictor(SAM2Predictor):
1736
1894
  Args:
1737
1895
  cfg (dict[str, Any]): Configuration dictionary containing default settings.
1738
1896
  overrides (dict[str, Any] | None): Dictionary of values to override default configuration.
1739
- max_obj_num (int): Maximum number of objects to track. Default is 3. this is set to keep fix feature size for the model.
1897
+ max_obj_num (int): Maximum number of objects to track. Default is 3. this is set to keep fix feature size
1898
+ for the model.
1740
1899
  _callbacks (dict[str, Any] | None): Dictionary of callback functions to customize behavior.
1741
-
1742
- Examples:
1743
- >>> predictor = SAM2DynamicInteractivePredictor(cfg=DEFAULT_CFG)
1744
- >>> predictor_example_with_imgsz = SAM2DynamicInteractivePredictor(overrides={"imgsz": 640})
1745
- >>> predictor_example_with_callback = SAM2DynamicInteractivePredictor(
1746
- ... _callbacks={"on_predict_start": custom_callback}
1747
- ... )
1748
1900
  """
1749
1901
  super().__init__(cfg, overrides, _callbacks)
1750
1902
  self.non_overlap_masks = True
@@ -1755,12 +1907,8 @@ class SAM2DynamicInteractivePredictor(SAM2Predictor):
1755
1907
 
1756
1908
  # Initialize the object index set and mappings
1757
1909
  self.obj_idx_set = set()
1758
- self.obj_id_to_idx = OrderedDict()
1759
- self.obj_idx_to_id = OrderedDict()
1910
+ self.obj_id_to_idx = self.obj_idx_to_id = OrderedDict(enumerate(range(max_obj_num)))
1760
1911
  self._max_obj_num = max_obj_num
1761
- for i in range(self._max_obj_num):
1762
- self.obj_id_to_idx[i + 1] = i
1763
- self.obj_idx_to_id[i] = i + 1
1764
1912
 
1765
1913
  @smart_inference_mode()
1766
1914
  def inference(
@@ -1773,19 +1921,19 @@ class SAM2DynamicInteractivePredictor(SAM2Predictor):
1773
1921
  obj_ids: list[int] | None = None,
1774
1922
  update_memory: bool = False,
1775
1923
  ) -> tuple[torch.Tensor, torch.Tensor]:
1776
- """
1777
- Perform inference on a single image with optional bounding boxes, masks, points and object IDs.
1778
- It has two modes: one is to run inference on a single image without updating the memory,
1779
- and the other is to update the memory with the provided prompts and object IDs.
1780
- When update_memory is True, it will update the memory with the provided prompts and obj_ids.
1781
- When update_memory is False, it will only run inference on the provided image without updating the memory.
1924
+ """Perform inference on a single image with optional bounding boxes, masks, points and object IDs. It has two
1925
+ modes: one is to run inference on a single image without updating the memory, and the other is to update
1926
+ the memory with the provided prompts and object IDs. When update_memory is True, it will update the
1927
+ memory with the provided prompts and obj_ids. When update_memory is False, it will only run inference on
1928
+ the provided image without updating the memory.
1782
1929
 
1783
1930
  Args:
1784
1931
  im (torch.Tensor | np.ndarray): The input image tensor or numpy array.
1785
1932
  bboxes (list[list[float]] | None): Optional list of bounding boxes to update the memory.
1786
1933
  masks (list[torch.Tensor | np.ndarray] | None): Optional masks to update the memory.
1787
1934
  points (list[list[float]] | None): Optional list of points to update the memory, each point is [x, y].
1788
- labels (list[int] | None): Optional list of object IDs corresponding to the points (>0 for positive, 0 for negative).
1935
+ labels (list[int] | None): Optional list of object IDs corresponding to the points (>0 for positive, 0 for
1936
+ negative).
1789
1937
  obj_ids (list[int] | None): Optional list of object IDs corresponding to the prompts.
1790
1938
  update_memory (bool): Flag to indicate whether to update the memory with new objects.
1791
1939
 
@@ -1831,8 +1979,7 @@ class SAM2DynamicInteractivePredictor(SAM2Predictor):
1831
1979
  return pred_masks.flatten(0, 1), pred_scores.flatten(0, 1)
1832
1980
 
1833
1981
  def get_im_features(self, img: torch.Tensor | np.ndarray) -> None:
1834
- """
1835
- Initialize the image state by processing the input image and extracting features.
1982
+ """Initialize the image state by processing the input image and extracting features.
1836
1983
 
1837
1984
  Args:
1838
1985
  img (torch.Tensor | np.ndarray): The input image tensor or numpy array.
@@ -1850,13 +1997,12 @@ class SAM2DynamicInteractivePredictor(SAM2Predictor):
1850
1997
  @smart_inference_mode()
1851
1998
  def update_memory(
1852
1999
  self,
1853
- obj_ids: list[int] = None,
2000
+ obj_ids: list[int] | None = None,
1854
2001
  points: torch.Tensor | None = None,
1855
2002
  labels: torch.Tensor | None = None,
1856
2003
  masks: torch.Tensor | None = None,
1857
2004
  ) -> None:
1858
- """
1859
- Append the imgState to the memory_bank and update the memory for the model.
2005
+ """Append the imgState to the memory_bank and update the memory for the model.
1860
2006
 
1861
2007
  Args:
1862
2008
  obj_ids (list[int]): List of object IDs corresponding to the prompts.
@@ -1930,12 +2076,12 @@ class SAM2DynamicInteractivePredictor(SAM2Predictor):
1930
2076
  self.memory_bank.append(consolidated_out)
1931
2077
 
1932
2078
  def _prepare_memory_conditioned_features(self, obj_idx: int | None) -> torch.Tensor:
1933
- """
1934
- Prepare the memory-conditioned features for the current image state. If obj_idx is provided, it supposes to
1935
- prepare features for a specific prompted object in the image. If obj_idx is None, it prepares features for all
1936
- objects in the image. If there is no memory, it will directly add a no-memory embedding to the current vision
1937
- features. If there is memory, it will use the memory features from previous frames to condition the current
1938
- vision features using a transformer attention mechanism.
2079
+ """Prepare memory-conditioned features for the current image state.
2080
+
2081
+ If ``obj_idx`` is provided, features are prepared for a specific prompted object in the image. If ``obj_idx`` is
2082
+ None, features are prepared for all objects. If no memory is available, a no-memory embedding is added to the
2083
+ current vision features. Otherwise, memory from previous frames is used to condition the current vision features
2084
+ via a transformer attention mechanism.
1939
2085
 
1940
2086
  Args:
1941
2087
  obj_idx (int | None): The index of the object for which to prepare the features.
@@ -1944,8 +2090,8 @@ class SAM2DynamicInteractivePredictor(SAM2Predictor):
1944
2090
  pix_feat_with_mem (torch.Tensor): The memory-conditioned pixel features.
1945
2091
  """
1946
2092
  if len(self.memory_bank) == 0 or isinstance(obj_idx, int):
1947
- # for initial conditioning frames with, encode them without using any previous memory
1948
- # directly add no-mem embedding (instead of using the transformer encoder)
2093
+ # For initial conditioning frames, encode without using any previous memory.
2094
+ # Directly add the no-memory embedding (instead of using the transformer encoder).
1949
2095
  pix_feat_with_mem = self.vision_feats[-1] + self.model.no_mem_embed
1950
2096
  else:
1951
2097
  # for inference frames, use the memory features from previous frames
@@ -1957,7 +2103,7 @@ class SAM2DynamicInteractivePredictor(SAM2Predictor):
1957
2103
  memory_pos=memory_pos_embed,
1958
2104
  num_obj_ptr_tokens=0, # num_obj_ptr_tokens
1959
2105
  )
1960
- # reshape the output (HW)BC => BCHW
2106
+ # Reshape output (HW)BC => BCHW
1961
2107
  return pix_feat_with_mem.permute(1, 2, 0).view(
1962
2108
  self._max_obj_num,
1963
2109
  self.model.memory_attention.d_model,
@@ -1965,9 +2111,7 @@ class SAM2DynamicInteractivePredictor(SAM2Predictor):
1965
2111
  )
1966
2112
 
1967
2113
  def get_maskmem_enc(self) -> tuple[torch.Tensor, torch.Tensor]:
1968
- """Get the memory and positional encoding from the memory, which is used to condition the current image
1969
- features.
1970
- """
2114
+ """Get memory and positional encoding from memory, which is used to condition the current image features."""
1971
2115
  to_cat_memory, to_cat_memory_pos_embed = [], []
1972
2116
  for consolidated_out in self.memory_bank:
1973
2117
  to_cat_memory.append(consolidated_out["maskmem_features"].flatten(2).permute(2, 0, 1)) # (H*W, B, C)
@@ -1980,8 +2124,7 @@ class SAM2DynamicInteractivePredictor(SAM2Predictor):
1980
2124
  return memory, memory_pos_embed
1981
2125
 
1982
2126
  def _obj_id_to_idx(self, obj_id: int) -> int | None:
1983
- """
1984
- Map client-side object id to model-side object index.
2127
+ """Map client-side object id to model-side object index.
1985
2128
 
1986
2129
  Args:
1987
2130
  obj_id (int): The client-side object ID.
@@ -1998,23 +2141,24 @@ class SAM2DynamicInteractivePredictor(SAM2Predictor):
1998
2141
  label: torch.Tensor | None = None,
1999
2142
  mask: torch.Tensor | None = None,
2000
2143
  ) -> dict[str, Any]:
2001
- """
2002
- Tracking step for the current image state to predict masks.
2144
+ """Tracking step for the current image state to predict masks.
2003
2145
 
2004
2146
  This method processes the image features and runs the SAM heads to predict masks. If obj_idx is provided, it
2005
2147
  processes the features for a specific prompted object in the image. If obj_idx is None, it processes the
2006
- features for all objects in the image. The method supports both mask-based output without SAM and full
2007
- SAM processing with memory-conditioned features.
2148
+ features for all objects in the image. The method supports both mask-based output without SAM and full SAM
2149
+ processing with memory-conditioned features.
2008
2150
 
2009
2151
  Args:
2010
2152
  obj_idx (int | None): The index of the object for which to predict masks. If None, it processes all objects.
2011
2153
  point (torch.Tensor | None): The coordinates of the points of interest with shape (N, 2).
2012
- label (torch.Tensor | None): The labels corresponding to the points where 1 means positive clicks, 0 means negative clicks.
2154
+ label (torch.Tensor | None): The labels corresponding to the points where 1 means positive clicks, 0 means
2155
+ negative clicks.
2013
2156
  mask (torch.Tensor | None): The mask input for the object with shape (H, W).
2014
2157
 
2015
2158
  Returns:
2016
- current_out (dict[str, Any]): A dictionary containing the current output with mask predictions and object pointers.
2017
- Keys include 'point_inputs', 'mask_inputs', 'pred_masks', 'pred_masks_high_res', 'obj_ptr', 'object_score_logits'.
2159
+ current_out (dict[str, Any]): A dictionary containing the current output with mask predictions and object
2160
+ pointers. Keys include 'point_inputs', 'mask_inputs', 'pred_masks', 'pred_masks_high_res',
2161
+ 'obj_ptr', 'object_score_logits'.
2018
2162
  """
2019
2163
  if mask is not None and self.model.use_mask_input_as_output_without_sam:
2020
2164
  # When use_mask_input_as_output_without_sam=True, we directly output the mask input
@@ -2023,9 +2167,9 @@ class SAM2DynamicInteractivePredictor(SAM2Predictor):
2023
2167
  pix_feat = pix_feat.view(-1, self.model.memory_attention.d_model, *self.feat_sizes[-1])
2024
2168
  _, _, _, low_res_masks, high_res_masks, obj_ptr, object_score_logits = self.model._use_mask_as_output(mask)
2025
2169
  else:
2026
- # fused the visual feature with previous memory features in the memory bank
2170
+ # Fuse visual features with previous memory features in the memory bank.
2027
2171
  pix_feat_with_mem = self._prepare_memory_conditioned_features(obj_idx)
2028
- # calculate the first feature if adding obj_idx exists(means adding prompts)
2172
+ # If ``obj_idx`` is provided (i.e., prompts are being added), keep only the first feature map.
2029
2173
  pix_feat_with_mem = pix_feat_with_mem[:1] if obj_idx is not None else pix_feat_with_mem
2030
2174
  _, _, _, low_res_masks, high_res_masks, obj_ptr, object_score_logits = self.model._forward_sam_heads(
2031
2175
  backbone_features=pix_feat_with_mem,
@@ -2040,3 +2184,1757 @@ class SAM2DynamicInteractivePredictor(SAM2Predictor):
2040
2184
  "obj_ptr": obj_ptr,
2041
2185
  "object_score_logits": object_score_logits,
2042
2186
  }
2187
+
2188
+
2189
+ class SAM3Predictor(SAM2Predictor):
2190
+ """Segment Anything Model 3 (SAM3) Interactive Predictor for image segmentation tasks."""
2191
+
2192
+ _bb_feat_sizes = [
2193
+ (288, 288),
2194
+ (144, 144),
2195
+ (72, 72),
2196
+ ]
2197
+ stride = 14
2198
+
2199
+ def setup_model(self, model=None, verbose=True):
2200
+ """Setup the SAM3 model with appropriate mean and standard deviation for preprocessing."""
2201
+ super().setup_model(model, verbose)
2202
+ # update mean and std
2203
+ self.mean = torch.tensor([127.5, 127.5, 127.5]).view(-1, 1, 1).to(self.device)
2204
+ self.std = torch.tensor([127.5, 127.5, 127.5]).view(-1, 1, 1).to(self.device)
2205
+
2206
+ def get_model(self):
2207
+ """Retrieve and initialize the Segment Anything Model 3 (SAM3) for image segmentation tasks."""
2208
+ from .build_sam3 import build_interactive_sam3 # slow import
2209
+
2210
+ return build_interactive_sam3(self.args.model, compile=self.args.compile)
2211
+
2212
+
2213
+ class SAM3SemanticPredictor(SAM3Predictor):
2214
+ """Segment Anything Model 3 (SAM3) Predictor for image segmentation tasks."""
2215
+
2216
+ def get_model(self):
2217
+ """Retrieve and initialize the Segment Anything Model 3 (SAM3) for image segmentation tasks."""
2218
+ from .build_sam3 import build_sam3_image_model # slow import
2219
+
2220
+ return build_sam3_image_model(self.args.model, compile=self.args.compile)
2221
+
2222
+ @smart_inference_mode()
2223
+ def get_im_features(self, im):
2224
+ """Extract image features using the model's backbone."""
2225
+ return self.model.backbone.forward_image(im)
2226
+
2227
+ def pre_transform(self, im):
2228
+ """Perform initial transformations on the input image for preprocessing.
2229
+
2230
+ This method applies transformations such as resizing to prepare the image for further preprocessing. Currently,
2231
+ batched inference is not supported; hence the list length should be 1.
2232
+
2233
+ Args:
2234
+ im (list[np.ndarray]): List containing a single image in HWC numpy array format.
2235
+
2236
+ Returns:
2237
+ (list[np.ndarray]): List containing the transformed image.
2238
+
2239
+ Raises:
2240
+ AssertionError: If the input list contains more than one image.
2241
+
2242
+ Examples:
2243
+ >>> predictor = Predictor()
2244
+ >>> image = np.random.rand(480, 640, 3) # Single HWC image
2245
+ >>> transformed = predictor.pre_transform([image])
2246
+ >>> print(len(transformed))
2247
+ 1
2248
+ """
2249
+ assert len(im) == 1, "SAM model does not currently support batched inference"
2250
+ letterbox = LetterBox(self.imgsz, auto=False, center=False, scale_fill=True) # hardcode here for sam3
2251
+ return [letterbox(image=x) for x in im]
2252
+
2253
+ def _prepare_geometric_prompts(self, src_shape, bboxes=None, labels=None):
2254
+ """Prepare prompts by normalizing bounding boxes and points to the destination shape."""
2255
+ if bboxes is not None:
2256
+ bboxes = torch.as_tensor(bboxes, dtype=self.torch_dtype, device=self.device)
2257
+ bboxes = bboxes[None] if bboxes.ndim == 1 else bboxes
2258
+ # needs xywh as input
2259
+ bboxes = ops.xyxy2xywh(bboxes)
2260
+ bboxes[:, 0::2] /= src_shape[1]
2261
+ bboxes[:, 1::2] /= src_shape[0]
2262
+ # Assuming labels are all positive if users don't pass labels.
2263
+ if labels is None:
2264
+ labels = np.ones(bboxes.shape[:-1])
2265
+ labels = torch.as_tensor(labels, dtype=torch.int32, device=self.device)
2266
+ assert bboxes.shape[-2] == labels.shape[-1], (
2267
+ f"Number of points {bboxes.shape[-2]} should match number of labels {labels.shape[-1]}."
2268
+ )
2269
+ bboxes = bboxes.view(-1, 1, 4) # (N, 1, 4)
2270
+ labels = labels.view(-1, 1) # (N, 1)
2271
+ return bboxes, labels
2272
+
2273
+ def _inference_features(self, features, bboxes=None, labels=None, text: list[str] | None = None):
2274
+ """Run inference on the extracted features with optional bounding boxes and labels."""
2275
+ # NOTE: priority: bboxes > text > pre-set classes
2276
+ nc = 1 if bboxes is not None else len(text) if text is not None else len(self.model.names)
2277
+ geometric_prompt = self._get_dummy_prompt(nc)
2278
+ if bboxes is not None:
2279
+ for i in range(len(bboxes)):
2280
+ geometric_prompt.append_boxes(bboxes[[i]], labels[[i]])
2281
+ if text is None:
2282
+ text = ["visual"] # bboxes needs this `visual` text prompt if no text passed
2283
+ if text is not None and self.model.names != text:
2284
+ self.model.set_classes(text=text)
2285
+ outputs = self.model.forward_grounding(
2286
+ backbone_out=features,
2287
+ text_ids=torch.arange(nc, device=self.device, dtype=torch.long),
2288
+ geometric_prompt=geometric_prompt,
2289
+ )
2290
+ return outputs
2291
+
2292
+ def postprocess(self, preds, img, orig_imgs):
2293
+ """Post-process the predictions to apply non-overlapping constraints if required."""
2294
+ pred_boxes = preds["pred_boxes"] # (nc, num_query, 4)
2295
+ pred_logits = preds["pred_logits"]
2296
+ pred_masks = preds["pred_masks"]
2297
+ pred_scores = pred_logits.sigmoid()
2298
+ presence_score = preds["presence_logit_dec"].sigmoid().unsqueeze(1)
2299
+ pred_scores = (pred_scores * presence_score).squeeze(-1)
2300
+ pred_cls = torch.tensor(
2301
+ list(range(pred_scores.shape[0])),
2302
+ dtype=pred_scores.dtype,
2303
+ device=pred_scores.device,
2304
+ )[:, None].expand_as(pred_scores)
2305
+ pred_boxes = torch.cat([pred_boxes, pred_scores[..., None], pred_cls[..., None]], dim=-1)
2306
+
2307
+ keep = pred_scores > self.args.conf
2308
+ pred_masks = pred_masks[keep]
2309
+ pred_boxes = pred_boxes[keep]
2310
+ pred_boxes[:, :4] = ops.xywh2xyxy(pred_boxes[:, :4])
2311
+
2312
+ names = getattr(self.model, "names", [str(i) for i in range(pred_scores.shape[0])])
2313
+ if not isinstance(orig_imgs, list): # input images are a torch.Tensor, not a list
2314
+ orig_imgs = ops.convert_torch2numpy_batch(orig_imgs)
2315
+ results = []
2316
+ for masks, boxes, orig_img, img_path in zip([pred_masks], [pred_boxes], orig_imgs, self.batch[0]):
2317
+ if masks.shape[0] == 0:
2318
+ masks, boxes = None, torch.zeros((0, 6), device=pred_masks.device)
2319
+ else:
2320
+ masks = F.interpolate(masks.float()[None], orig_img.shape[:2], mode="bilinear")[0] > 0.5
2321
+ boxes[..., [0, 2]] *= orig_img.shape[1]
2322
+ boxes[..., [1, 3]] *= orig_img.shape[0]
2323
+ results.append(Results(orig_img, path=img_path, names=names, masks=masks, boxes=boxes))
2324
+ return results
2325
+
2326
+ def inference(self, im, bboxes=None, labels=None, text: list[str] | None = None, *args, **kwargs):
2327
+ """Perform inference on a single image with optional prompts."""
2328
+ bboxes = self.prompts.pop("bboxes", bboxes)
2329
+ labels = self.prompts.pop("labels", labels)
2330
+ text = self.prompts.pop("text", text)
2331
+ features = self.get_im_features(im) if self.features is None else self.features
2332
+ prompts = self._prepare_geometric_prompts(self.batch[1][0].shape[:2], bboxes, labels)
2333
+ return self._inference_features(features, *prompts, text=text)
2334
+
2335
+ @smart_inference_mode()
2336
+ def inference_features(
2337
+ self,
2338
+ features,
2339
+ src_shape,
2340
+ bboxes=None,
2341
+ labels=None,
2342
+ text: list[str] | None = None,
2343
+ ):
2344
+ """Perform prompts preprocessing and inference on provided image features using the SAM model.
2345
+
2346
+ Args:
2347
+ features (dict[str, Any]): Extracted image features from the SAM3 model image encoder.
2348
+ src_shape (tuple[int, int]): The source shape (height, width) of the input image.
2349
+ bboxes (np.ndarray | list[list[float]] | None): Bounding boxes in xyxy format with shape (N, 4). pixels.
2350
+ labels (np.ndarray | list[int] | None): Point prompt labels with shape (N, ).
2351
+ text (list[str] | None): List of text prompts corresponding to the classes.
2352
+
2353
+ Returns:
2354
+ pred_masks (torch.Tensor): The output masks in shape (C, H, W), where C is the number of generated masks.
2355
+ pred_bboxes (torch.Tensor): Bounding boxes for each mask with shape (N, 6), where N is the number of boxes.
2356
+ Each box is in xyxy format with additional columns for score and class.
2357
+
2358
+ Notes:
2359
+ - 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.
2360
+ """
2361
+ prompts = self._prepare_geometric_prompts(src_shape[:2], bboxes, labels)
2362
+ preds = self._inference_features(features, *prompts, text=text)
2363
+ pred_boxes = preds["pred_boxes"] # (nc, num_query, 4)
2364
+ pred_logits = preds["pred_logits"]
2365
+ pred_masks = preds["pred_masks"]
2366
+ pred_scores = pred_logits.sigmoid()
2367
+ presence_score = preds["presence_logit_dec"].sigmoid().unsqueeze(1)
2368
+ pred_scores = (pred_scores * presence_score).squeeze(-1)
2369
+ pred_cls = torch.tensor(
2370
+ list(range(pred_scores.shape[0])),
2371
+ dtype=pred_scores.dtype,
2372
+ device=pred_scores.device,
2373
+ )[:, None].expand_as(pred_scores)
2374
+ pred_boxes = torch.cat([pred_boxes, pred_scores[..., None], pred_cls[..., None]], dim=-1)
2375
+
2376
+ keep = pred_scores > self.args.conf
2377
+ pred_masks = pred_masks[keep]
2378
+ pred_boxes = pred_boxes[keep]
2379
+ pred_boxes[:, :4] = ops.xywh2xyxy(pred_boxes[:, :4])
2380
+
2381
+ if pred_masks.shape[0] == 0:
2382
+ pred_masks, pred_boxes = None, torch.zeros((0, 6), device=pred_masks.device)
2383
+ else:
2384
+ pred_masks = F.interpolate(pred_masks.float()[None], src_shape[:2], mode="bilinear")[0] > 0.5
2385
+ pred_boxes[..., 0] *= src_shape[1]
2386
+ pred_boxes[..., 1] *= src_shape[0]
2387
+ pred_boxes[..., 2] *= src_shape[1]
2388
+ pred_boxes[..., 3] *= src_shape[0]
2389
+ return pred_masks, pred_boxes
2390
+
2391
+ def reset_prompts(self):
2392
+ """Reset the prompts for the predictor."""
2393
+ self.prompts = {}
2394
+ self.model.text_embeddings = {}
2395
+
2396
+ def _get_dummy_prompt(self, num_prompts=1):
2397
+ """Get a dummy geometric prompt with zero boxes."""
2398
+ geometric_prompt = Prompt(
2399
+ box_embeddings=torch.zeros(0, num_prompts, 4, device=self.device),
2400
+ box_mask=torch.zeros(num_prompts, 0, device=self.device, dtype=torch.bool),
2401
+ )
2402
+ return geometric_prompt
2403
+
2404
+
2405
+ class SAM3VideoPredictor(SAM2VideoPredictor, SAM3Predictor):
2406
+ """Segment Anything Model 3 (SAM3) Video Predictor for video segmentation tasks."""
2407
+
2408
+ def propagate_in_video(self, inference_state, frame_idx):
2409
+ """Perform image segmentation inference based on the given input cues, using the currently loaded image. This
2410
+ method leverages SAM's (Segment Anything Model) architecture consisting of image encoder, prompt
2411
+ encoder, and mask decoder for real-time and promptable segmentation tasks.
2412
+
2413
+ Args:
2414
+ inference_state (dict): The current state of inference, including input cues and previous outputs.
2415
+ frame_idx (int): The index of the current frame in the video sequence.
2416
+ """
2417
+ frame = frame_idx
2418
+ output_dict = inference_state["output_dict"]
2419
+ obj_ids = inference_state["obj_ids"]
2420
+ consolidated_frame_inds = inference_state["consolidated_frame_inds"]
2421
+ batch_size = len(inference_state["obj_idx_to_id"])
2422
+ if len(output_dict["cond_frame_outputs"]) == 0:
2423
+ raise RuntimeError("No points are provided; please add points first")
2424
+
2425
+ if frame in consolidated_frame_inds["cond_frame_outputs"]:
2426
+ storage_key = "cond_frame_outputs"
2427
+ current_out = output_dict[storage_key][frame]
2428
+ if self.clear_non_cond_mem_around_input and (self.clear_non_cond_mem_for_multi_obj or batch_size <= 1):
2429
+ # clear non-conditioning memory of the surrounding frames
2430
+ self._clear_non_cond_mem_around_input(frame)
2431
+ elif frame in consolidated_frame_inds["non_cond_frame_outputs"]:
2432
+ storage_key = "non_cond_frame_outputs"
2433
+ current_out = output_dict[storage_key][frame]
2434
+ else:
2435
+ storage_key = "non_cond_frame_outputs"
2436
+ current_out = self._run_single_frame_inference(
2437
+ output_dict=output_dict,
2438
+ frame_idx=frame,
2439
+ batch_size=batch_size,
2440
+ is_init_cond_frame=False,
2441
+ point_inputs=None,
2442
+ mask_inputs=None,
2443
+ reverse=False,
2444
+ run_mem_encoder=True,
2445
+ inference_state=inference_state,
2446
+ )
2447
+ output_dict[storage_key][frame] = current_out
2448
+ self._prune_non_cond_memory(frame, inference_state=inference_state)
2449
+ # Create slices of per-object outputs for subsequent interaction with each
2450
+ # individual object after tracking.
2451
+ self._add_output_per_object(frame, current_out, storage_key, inference_state=inference_state)
2452
+ inference_state["frames_already_tracked"].append(frame)
2453
+ pred_masks = current_out["pred_masks"].flatten(0, 1)
2454
+ obj_scores = current_out["object_score_logits"]
2455
+
2456
+ return obj_ids, pred_masks, obj_scores
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
+ # prob threshold for detection outputs -- only keep detections above this threshold
2483
+ # enters NMS and det-to-track matching
2484
+ score_threshold_detection=0.5,
2485
+ # IoU threshold for detection NMS
2486
+ det_nms_thresh=0.0,
2487
+ # IoU threshold for det-to-track matching -- a detection is considered "matched" to a tracklet it
2488
+ # overlaps with a tracklet above this threshold -- it is often a loose threshold like 0.1
2489
+ assoc_iou_thresh=0.5,
2490
+ # IoU threshold for det-to-track matching, which is used to determine whether a masklet is "unmatched"
2491
+ # by any detections -- it is often a stricter threshold like 0.5
2492
+ trk_assoc_iou_thresh=0.5,
2493
+ # prob threshold for a detection to be added as a new object
2494
+ new_det_thresh=0.0,
2495
+ # hotstart parameters: we hold off the outputs for `hotstart_delay` frames and
2496
+ # 1) remove those tracklets unmatched by any detections based on `hotstart_unmatch_thresh`
2497
+ # 2) remove those tracklets overlapping with one another based on `hotstart_dup_thresh`
2498
+ hotstart_delay=0,
2499
+ hotstart_unmatch_thresh=3,
2500
+ hotstart_dup_thresh=3,
2501
+ init_trk_keep_alive=30,
2502
+ max_trk_keep_alive=30,
2503
+ min_trk_keep_alive=-4,
2504
+ # Threshold for suppressing overlapping objects based on recent occlusion
2505
+ suppress_overlapping_based_on_recent_occlusion_threshold=0.0,
2506
+ decrease_trk_keep_alive_for_empty_masklets=True,
2507
+ o2o_matching_masklets_enable=False, # Enable hungarian matching to match existing masklets
2508
+ suppress_det_close_to_boundary=False,
2509
+ fill_hole_area=16,
2510
+ # The maximum number of objects (masklets) to track across all GPUs (for no limit, set it to -1)
2511
+ max_num_objects=-1,
2512
+ recondition_every_nth_frame=-1,
2513
+ # masket confirmation status (to suppress unconfirmed masklets)
2514
+ masklet_confirmation_enable=False,
2515
+ # a masklet is confirmed after being consecutively detected and matched for
2516
+ # `masklet_confirmation_consecutive_det_thresh`
2517
+ masklet_confirmation_consecutive_det_thresh=3,
2518
+ # bbox heuristic parameters
2519
+ reconstruction_bbox_iou_thresh=0.0,
2520
+ reconstruction_bbox_det_score=0.0,
2521
+ ):
2522
+ """Initialize the SAM3VideoSemanticPredictor with configuration and optional overrides."""
2523
+ super().__init__(cfg, overrides, _callbacks)
2524
+ self.score_threshold_detection = score_threshold_detection
2525
+ self.det_nms_thresh = det_nms_thresh
2526
+ self.assoc_iou_thresh = assoc_iou_thresh
2527
+ self.trk_assoc_iou_thresh = trk_assoc_iou_thresh
2528
+ self.new_det_thresh = new_det_thresh
2529
+
2530
+ # hotstart parameters
2531
+ if hotstart_delay > 0:
2532
+ assert hotstart_unmatch_thresh <= hotstart_delay
2533
+ assert hotstart_dup_thresh <= hotstart_delay
2534
+ self.hotstart_delay = hotstart_delay
2535
+ self.hotstart_unmatch_thresh = hotstart_unmatch_thresh
2536
+ self.hotstart_dup_thresh = hotstart_dup_thresh
2537
+ self.init_trk_keep_alive = init_trk_keep_alive
2538
+ self.max_trk_keep_alive = max_trk_keep_alive
2539
+ self.min_trk_keep_alive = min_trk_keep_alive
2540
+ self.suppress_overlapping_based_on_recent_occlusion_threshold = (
2541
+ suppress_overlapping_based_on_recent_occlusion_threshold
2542
+ )
2543
+ self.suppress_det_close_to_boundary = suppress_det_close_to_boundary
2544
+ self.decrease_trk_keep_alive_for_empty_masklets = decrease_trk_keep_alive_for_empty_masklets
2545
+ self.o2o_matching_masklets_enable = o2o_matching_masklets_enable
2546
+ self.fill_hole_area = fill_hole_area
2547
+ self._dist_pg_cpu = None # CPU process group (lazy-initialized on first use)
2548
+
2549
+ max_num_objects = 10000 # no limit
2550
+ num_obj_for_compile = 16
2551
+ self.max_num_objects = max_num_objects
2552
+ self.num_obj_for_compile = num_obj_for_compile
2553
+ self.recondition_every_nth_frame = recondition_every_nth_frame
2554
+ self.masklet_confirmation_enable = masklet_confirmation_enable
2555
+ self.masklet_confirmation_consecutive_det_thresh = masklet_confirmation_consecutive_det_thresh
2556
+ self.reconstruction_bbox_iou_thresh = reconstruction_bbox_iou_thresh
2557
+ self.reconstruction_bbox_det_score = reconstruction_bbox_det_score
2558
+
2559
+ # build SAM3 tracker
2560
+ self.tracker = SAM3VideoPredictor(overrides=overrides)
2561
+
2562
+ self.inference_state = {}
2563
+ self.callbacks["on_predict_start"].append(self.init_state)
2564
+
2565
+ def setup_model(self, model=None, verbose=True):
2566
+ """Setup the SAM3VideoSemanticPredictor model."""
2567
+ super().setup_model(model, verbose)
2568
+ from .build_sam3 import build_interactive_sam3
2569
+
2570
+ # Initialize the SAM3 tracker model without backbone (backbone is handled in the detector)
2571
+ model = build_interactive_sam3(self.args.model, with_backbone=False)
2572
+ self.tracker.setup_model(model=model, verbose=False)
2573
+
2574
+ def setup_source(self, source):
2575
+ """Setup the source for the SAM3VideoSemanticPredictor model."""
2576
+ super().setup_source(source)
2577
+ self.tracker.imgsz = self.imgsz
2578
+ self.tracker.model.set_imgsz(self.imgsz)
2579
+ self.tracker._bb_feat_sizes = [[int(x / (self.stride * i)) for x in self.imgsz] for i in [1 / 4, 1 / 2, 1]]
2580
+ self.interpol_size = self.tracker.model.memory_encoder.mask_downsampler.interpol_size
2581
+
2582
+ @staticmethod
2583
+ def init_state(predictor):
2584
+ """Initialize an inference state for the predictor.
2585
+
2586
+ This function sets up the initial state required for performing inference on video data. It includes
2587
+ initializing various dictionaries and ordered dictionaries that will store inputs, outputs, and other metadata
2588
+ relevant to the tracking process.
2589
+
2590
+ Args:
2591
+ predictor (SAM3VideoSemanticPredictor): The predictor object for which to initialize the state.
2592
+ """
2593
+ if len(predictor.inference_state) > 0: # means initialized
2594
+ return
2595
+ assert predictor.dataset is not None
2596
+ assert predictor.dataset.mode == "video"
2597
+ num_frames = predictor.dataset.frames
2598
+ inference_state = {
2599
+ "num_frames": num_frames,
2600
+ "tracker_inference_states": [],
2601
+ "tracker_metadata": {},
2602
+ "text_prompt": None,
2603
+ "per_frame_geometric_prompt": [None] * num_frames,
2604
+ }
2605
+ predictor.inference_state = inference_state
2606
+
2607
+ def inference(self, im, bboxes=None, labels=None, text: list[str] | None = None, *args, **kwargs):
2608
+ """Perform inference on a video sequence with optional prompts."""
2609
+ frame = self.dataset.frame - 1 # align frame index to be 0-based
2610
+ self.inference_state["im"] = im # only pass image for subsequent frames
2611
+ if "text_ids" not in self.inference_state: # first frame processing
2612
+ self.add_prompt(frame_idx=frame, text=text, bboxes=bboxes, labels=labels)
2613
+ return self._run_single_frame_inference(frame, reverse=False)
2614
+
2615
+ def postprocess(self, preds, img, orig_imgs):
2616
+ """Post-process the predictions to apply non-overlapping constraints if required."""
2617
+ obj_id_to_mask = preds["obj_id_to_mask"] # low res masks
2618
+ curr_obj_ids = sorted(obj_id_to_mask.keys())
2619
+ if not isinstance(orig_imgs, list): # input images are a torch.Tensor, not a list
2620
+ orig_imgs = ops.convert_torch2numpy_batch(orig_imgs)
2621
+
2622
+ if len(curr_obj_ids) == 0:
2623
+ pred_masks, pred_boxes = None, torch.zeros((0, 7), device=self.device)
2624
+ else:
2625
+ pred_masks = torch.cat([obj_id_to_mask[obj_id] for obj_id in curr_obj_ids], dim=0)
2626
+ pred_masks = F.interpolate(pred_masks.float()[None], orig_imgs[0].shape[:2], mode="bilinear")[0] > 0.5
2627
+ pred_ids = torch.tensor(curr_obj_ids, dtype=torch.int32, device=pred_masks.device)
2628
+ pred_scores = torch.tensor(
2629
+ [preds["obj_id_to_score"][obj_id] for obj_id in curr_obj_ids], device=pred_masks.device
2630
+ )
2631
+ pred_cls = torch.tensor(
2632
+ [preds["obj_id_to_cls"][obj_id] for obj_id in curr_obj_ids], device=pred_masks.device
2633
+ )
2634
+ keep = (pred_scores > self.args.conf) & pred_masks.any(dim=(1, 2))
2635
+ pred_masks = pred_masks[keep]
2636
+ pred_boxes = batched_mask_to_box(pred_masks)
2637
+ pred_boxes = torch.cat(
2638
+ [pred_boxes, pred_ids[keep][:, None], pred_scores[keep][..., None], pred_cls[keep][..., None]], dim=-1
2639
+ )
2640
+ if pred_masks.shape[0] > 1:
2641
+ tracker_scores = torch.tensor(
2642
+ [
2643
+ (
2644
+ preds["obj_id_to_tracker_score"][obj_id]
2645
+ if obj_id in preds["obj_id_to_tracker_score"]
2646
+ else 0.0
2647
+ )
2648
+ for obj_id in curr_obj_ids
2649
+ ],
2650
+ device=pred_masks.device,
2651
+ )[keep]
2652
+ pred_masks = (
2653
+ self._apply_object_wise_non_overlapping_constraints(
2654
+ pred_masks.unsqueeze(1),
2655
+ tracker_scores.unsqueeze(1),
2656
+ background_value=0,
2657
+ ).squeeze(1)
2658
+ ) > 0
2659
+
2660
+ # names = getattr(self.model, "names", [str(i) for i in range(pred_scores.shape[0])])
2661
+ names = dict(enumerate(str(i) for i in range(pred_boxes.shape[0])))
2662
+ results = []
2663
+ for masks, boxes, orig_img, img_path in zip([pred_masks], [pred_boxes], orig_imgs, self.batch[0]):
2664
+ results.append(Results(orig_img, path=img_path, names=names, masks=masks, boxes=boxes))
2665
+ return results
2666
+
2667
+ def _run_single_frame_inference(self, frame_idx, reverse=False, inference_state=None):
2668
+ """Perform inference on a single frame and get its inference results."""
2669
+ inference_state = inference_state or self.inference_state
2670
+ # prepare inputs
2671
+ tracker_states_local = inference_state["tracker_inference_states"]
2672
+ has_text_prompt = inference_state["text_prompt"] is not None
2673
+ has_geometric_prompt = inference_state["per_frame_geometric_prompt"][frame_idx] is not None
2674
+ # run inference for the current frame
2675
+ (
2676
+ obj_id_to_mask,
2677
+ obj_id_to_score,
2678
+ obj_id_to_cls,
2679
+ tracker_states_local_new,
2680
+ tracker_metadata_new,
2681
+ frame_stats,
2682
+ _,
2683
+ ) = self._det_track_one_frame(
2684
+ frame_idx=frame_idx,
2685
+ num_frames=inference_state["num_frames"],
2686
+ reverse=reverse,
2687
+ im=inference_state["im"],
2688
+ text_ids=inference_state["text_ids"],
2689
+ geometric_prompt=(
2690
+ self._get_dummy_prompt(num_prompts=len(inference_state["text_ids"]))
2691
+ if not has_geometric_prompt
2692
+ else inference_state["per_frame_geometric_prompt"][frame_idx]
2693
+ ),
2694
+ tracker_states_local=tracker_states_local,
2695
+ tracker_metadata_prev=inference_state["tracker_metadata"],
2696
+ allow_new_detections=has_text_prompt or has_geometric_prompt,
2697
+ )
2698
+ # update inference state
2699
+ inference_state["tracker_inference_states"] = tracker_states_local_new
2700
+ inference_state["tracker_metadata"] = tracker_metadata_new
2701
+
2702
+ out = {
2703
+ "obj_id_to_mask": obj_id_to_mask,
2704
+ "obj_id_to_score": obj_id_to_score, # first frame detection score
2705
+ "obj_id_to_cls": obj_id_to_cls, # first frame detection score
2706
+ "obj_id_to_tracker_score": tracker_metadata_new["obj_id_to_tracker_score_frame_wise"][frame_idx],
2707
+ }
2708
+ # removed_obj_ids is only needed on rank 0 to handle hotstart delay buffer
2709
+ metadata = tracker_metadata_new["metadata"]
2710
+ removed_obj_ids = metadata["removed_obj_ids"]
2711
+ out["removed_obj_ids"] = removed_obj_ids
2712
+ out["frame_stats"] = frame_stats
2713
+ if self.masklet_confirmation_enable:
2714
+ status = metadata["masklet_confirmation"]["status"]
2715
+ is_unconfirmed = status == self.UNCONFIRMED
2716
+ out["unconfirmed_obj_ids"] = tracker_metadata_new["obj_ids_all_gpu"][is_unconfirmed].tolist()
2717
+ else:
2718
+ out["unconfirmed_obj_ids"] = []
2719
+ return out
2720
+
2721
+ @smart_inference_mode()
2722
+ def add_prompt(
2723
+ self,
2724
+ frame_idx,
2725
+ text=None,
2726
+ bboxes=None,
2727
+ labels=None,
2728
+ inference_state=None,
2729
+ ):
2730
+ """Add text, point or box prompts on a single frame. This method returns the inference outputs only on the
2731
+ prompted frame.
2732
+
2733
+ Note that text prompts are NOT associated with a particular frame (i.e. they apply
2734
+ to all frames). However, we only run inference on the frame specified in `frame_idx`.
2735
+ """
2736
+ inference_state = inference_state or self.inference_state
2737
+ assert text is not None or bboxes is not None, "at least one type of prompt (text, boxes) must be provided"
2738
+
2739
+ # 1) handle text prompt
2740
+ use_text = text is not None
2741
+ text = text if use_text else "visual"
2742
+ text_batch = [text] if isinstance(text, str) else text
2743
+ inference_state["text_prompt"] = text if use_text else None
2744
+ n = len(text_batch)
2745
+ text_ids = torch.arange(n, device=self.device, dtype=torch.long)
2746
+ inference_state["text_ids"] = text_ids
2747
+ if text is not None and self.model.names != text:
2748
+ self.model.set_classes(text=text)
2749
+
2750
+ # 2) handle box prompt
2751
+ bboxes, labels = self._prepare_geometric_prompts(self.batch[1][0].shape[:2], bboxes, labels)
2752
+ assert (bboxes is not None) == (labels is not None)
2753
+ geometric_prompt = self._get_dummy_prompt(num_prompts=n)
2754
+ if bboxes is not None:
2755
+ for i in range(len(bboxes)):
2756
+ geometric_prompt.append_boxes(bboxes[[i]], labels[[i]])
2757
+ inference_state["per_frame_geometric_prompt"][frame_idx] = geometric_prompt
2758
+ out = self._run_single_frame_inference(frame_idx, reverse=False, inference_state=inference_state)
2759
+ return frame_idx, out
2760
+
2761
+ def _apply_object_wise_non_overlapping_constraints(self, pred_masks, obj_scores, background_value=-10.0):
2762
+ """Applies non-overlapping constraints object wise (i.e. only one object can claim the overlapping region)."""
2763
+ # Replace pixel scores with object scores
2764
+ pred_masks_single_score = torch.where(pred_masks > 0, obj_scores[..., None, None], background_value)
2765
+ # Apply pixel-wise non-overlapping constraint based on mask scores
2766
+ pixel_level_non_overlapping_masks = self.tracker.model._apply_non_overlapping_constraints(
2767
+ pred_masks_single_score
2768
+ )
2769
+ # Replace object scores with pixel scores. Note, that now only one object can claim the overlapping region
2770
+ pred_masks = torch.where(
2771
+ pixel_level_non_overlapping_masks > 0,
2772
+ pred_masks,
2773
+ torch.clamp(pred_masks, max=background_value),
2774
+ )
2775
+ return pred_masks
2776
+
2777
+ def _det_track_one_frame(
2778
+ self,
2779
+ im: torch.Tensor,
2780
+ text_ids: torch.Tensor,
2781
+ frame_idx: int,
2782
+ num_frames: int,
2783
+ reverse: bool,
2784
+ geometric_prompt: Prompt,
2785
+ tracker_states_local: list[Any],
2786
+ tracker_metadata_prev: dict[str, Any],
2787
+ allow_new_detections: bool = True,
2788
+ ):
2789
+ """This function handles one-step inference for the DenseTracking model in an SPMD manner. At a high-level, all
2790
+ GPUs execute the same function calls as if it's done on a single GPU, while under the hood, some
2791
+ function calls involve distributed computation based on sharded SAM2 states.
2792
+
2793
+ - `input_batch` contains image and other inputs on the entire video; it should be identical across GPUs
2794
+ - `tracker_states_local` holds the local masklet information in this GPU shard
2795
+ - `tracker_metadata_prev` manages the metadata for SAM2 objects, such as which masklet is hold on which GPUs
2796
+ it contains both global and local masklet information
2797
+ """
2798
+ # Step 1: run backbone and detector in a distributed manner -- this is done via Sam3ImageOnVideoMultiGPU,
2799
+ # a MultiGPU model (assigned to `self.detector`) that shards frames in a round-robin manner.
2800
+ det_out = self.run_backbone_and_detection(
2801
+ im=im,
2802
+ text_ids=text_ids,
2803
+ geometric_prompt=geometric_prompt,
2804
+ allow_new_detections=allow_new_detections,
2805
+ )
2806
+
2807
+ # Step 2: each GPU propagates its local SAM2 states to get the SAM2 prediction masks.
2808
+ # the returned `tracker_low_res_masks_global` contains the concatenated masklet predictions
2809
+ # gathered from all GPUs (as if they are propagated on a single GPU). Note that this step only
2810
+ # runs the SAM2 propagation step, but doesn't encode new memory for the predicted masks;
2811
+ # we defer memory encoding to `run_tracker_update_execution_phase` after resolving all heuristics.
2812
+ if tracker_metadata_prev == {}:
2813
+ # initialize masklet metadata if it's uninitialized (empty dict)
2814
+ tracker_metadata_prev.update(self._initialize_metadata())
2815
+ tracker_low_res_masks_global, tracker_obj_scores_global = self.run_tracker_propagation(
2816
+ frame_idx=frame_idx,
2817
+ tracker_states_local=tracker_states_local,
2818
+ tracker_metadata_prev=tracker_metadata_prev,
2819
+ )
2820
+
2821
+ # Step 3: based on detection outputs and the propagated SAM2 prediction masks, we make plans
2822
+ # for SAM2 masklet updates (i.e. which objects to add and remove, how to load-balance them, etc).
2823
+ # We also run SAM2 memory encoder globally in this step to resolve non-overlapping constraints.
2824
+ # **This step should involve all the heuristics needed for any updates.** Most of the update
2825
+ # planning will be done on the master rank (GPU 0) and the resulting plan `tracker_update_plan` is
2826
+ # broadcasted to other GPUs (to be executed in a distributed manner). This step also generates the
2827
+ # new masklet metadata `tracker_metadata_new` (based on its previous version `tracker_metadata_prev`).
2828
+ tracker_update_plan, tracker_metadata_new = self.run_tracker_update_planning_phase(
2829
+ frame_idx=frame_idx,
2830
+ reverse=reverse,
2831
+ det_out=det_out,
2832
+ tracker_low_res_masks_global=tracker_low_res_masks_global,
2833
+ tracker_obj_scores_global=tracker_obj_scores_global,
2834
+ tracker_metadata_prev=tracker_metadata_prev,
2835
+ tracker_states_local=tracker_states_local,
2836
+ )
2837
+
2838
+ # Get reconditioning info from the update plan
2839
+ reconditioned_obj_ids = tracker_update_plan.get("reconditioned_obj_ids", set())
2840
+
2841
+ # Step 4: based on `tracker_update_plan`, each GPU executes the update w.r.t. its local SAM2 inference states
2842
+ tracker_states_local_new = self.run_tracker_update_execution_phase(
2843
+ frame_idx=frame_idx,
2844
+ num_frames=num_frames,
2845
+ det_out=det_out,
2846
+ tracker_states_local=tracker_states_local,
2847
+ tracker_update_plan=tracker_update_plan,
2848
+ )
2849
+
2850
+ # Step 5: finally, build the outputs for this frame (it only needs to be done on GPU 0 since
2851
+ # only GPU 0 will send outputs to the server).
2852
+ obj_id_to_mask = self.build_outputs(
2853
+ det_out=det_out,
2854
+ tracker_low_res_masks_global=tracker_low_res_masks_global,
2855
+ tracker_metadata_prev=tracker_metadata_prev,
2856
+ tracker_update_plan=tracker_update_plan,
2857
+ reconditioned_obj_ids=reconditioned_obj_ids,
2858
+ )
2859
+ obj_id_to_score = tracker_metadata_new["obj_id_to_score"]
2860
+ obj_id_to_cls = tracker_metadata_new["obj_id_to_cls"]
2861
+ # a few statistics for the current frame as a part of the output
2862
+ frame_stats = {
2863
+ "num_obj_tracked": np.sum(tracker_metadata_new["num_obj"]),
2864
+ "num_obj_dropped": tracker_update_plan["num_obj_dropped_due_to_limit"],
2865
+ }
2866
+ # add tracker scores to metadata, it should be fired for frames except the first frame
2867
+ if tracker_obj_scores_global.shape[0] > 0:
2868
+ # Convert tracker_obj_scores_global to sigmoid scores before updating
2869
+ tracker_obj_scores_global = tracker_obj_scores_global.sigmoid().tolist()
2870
+ tracker_obj_ids = tracker_metadata_prev["obj_ids"]
2871
+ tracker_metadata_new["obj_id_to_tracker_score_frame_wise"][frame_idx].update(
2872
+ dict(zip(tracker_obj_ids, tracker_obj_scores_global))
2873
+ )
2874
+ return (
2875
+ obj_id_to_mask, # a dict: obj_id --> output mask
2876
+ obj_id_to_score, # a dict: obj_id --> output score (prob)
2877
+ obj_id_to_cls, # a dict: obj_id --> output cls (int)
2878
+ tracker_states_local_new,
2879
+ tracker_metadata_new,
2880
+ frame_stats,
2881
+ tracker_obj_scores_global, # a dict: obj_id --> tracker frame-level scores
2882
+ )
2883
+
2884
+ @staticmethod
2885
+ def _suppress_detections_close_to_boundary(boxes, margin=0.025):
2886
+ """Suppress detections too close to image edges (for normalized boxes).
2887
+
2888
+ boxes: (N, 4) in xyxy format, normalized [0,1]
2889
+ margin: fraction of image
2890
+ """
2891
+ x_min, y_min, x_max, y_max = boxes.unbind(-1)
2892
+ x_c = (x_min + x_max) / 2
2893
+ y_c = (y_min + y_max) / 2
2894
+ keep = (x_c > margin) & (x_c < 1.0 - margin) & (y_c > margin) & (y_c < 1.0 - margin)
2895
+
2896
+ return keep
2897
+
2898
+ def run_backbone_and_detection(
2899
+ self, im: torch.Tensor, text_ids: torch.Tensor, geometric_prompt: Prompt, allow_new_detections: bool
2900
+ ):
2901
+ """Run backbone and detection for a single frame."""
2902
+ features = self.get_im_features(im)
2903
+ sam3_image_out = self.model.forward_grounding(
2904
+ backbone_out=features, text_ids=text_ids, geometric_prompt=geometric_prompt
2905
+ )
2906
+ det_out = self._extract_detection_outputs(sam3_image_out, allow_new_detections)
2907
+ self._cache_backbone_features(sam3_image_out)
2908
+ return det_out
2909
+
2910
+ def _extract_detection_outputs(self, sam3_image_out, allow_new_detections):
2911
+ """Extract and filter detection outputs."""
2912
+ pred_probs = sam3_image_out["pred_logits"].squeeze(-1).sigmoid()
2913
+ if not allow_new_detections:
2914
+ pred_probs = pred_probs - 1e8
2915
+
2916
+ pred_cls = torch.tensor(
2917
+ list(range(pred_probs.shape[0])),
2918
+ dtype=pred_probs.dtype,
2919
+ device=pred_probs.device,
2920
+ )[:, None].expand_as(pred_probs)
2921
+
2922
+ pred_boxes_xyxy = sam3_image_out["pred_boxes_xyxy"]
2923
+ pred_masks = sam3_image_out["pred_masks"]
2924
+
2925
+ keep = pred_probs > self.score_threshold_detection
2926
+ return {
2927
+ "bbox": pred_boxes_xyxy[keep],
2928
+ "mask": pred_masks[keep],
2929
+ "scores": pred_probs[keep],
2930
+ "cls": pred_cls[keep],
2931
+ }
2932
+
2933
+ def _cache_backbone_features(self, sam3_image_out):
2934
+ """Build and cache SAM2 backbone features."""
2935
+ sam_mask_decoder = self.tracker.model.sam_mask_decoder
2936
+ feats = sam3_image_out["backbone_out"]["sam2_backbone_out"]
2937
+ tracker_backbone_fpn = [
2938
+ sam_mask_decoder.conv_s0(feats["backbone_fpn"][0]),
2939
+ sam_mask_decoder.conv_s1(feats["backbone_fpn"][1]),
2940
+ feats["backbone_fpn"][2],
2941
+ ]
2942
+ tracker_backbone_out = {
2943
+ "vision_features": tracker_backbone_fpn[-1],
2944
+ "vision_pos_enc": feats["vision_pos_enc"],
2945
+ "backbone_fpn": tracker_backbone_fpn,
2946
+ }
2947
+ # cache the SAM2 backbone features for `frame_idx` in the tracker
2948
+ self.tracker.backbone_out = tracker_backbone_out
2949
+
2950
+ def run_tracker_propagation(
2951
+ self, frame_idx: int, tracker_states_local: list[Any], tracker_metadata_prev: dict[str, np.ndarray]
2952
+ ):
2953
+ """Run the tracker propagation phase for a single frame in an SPMD manner."""
2954
+ # Step 1: propagate the local SAM2 states to get the current frame's prediction
2955
+ # `low_res_masks_local` of the existing masklets on this GPU
2956
+ # - obj_ids_local: list[int] -- list of object IDs
2957
+ # - low_res_masks_local: Tensor -- (num_local_obj, H_mask, W_mask)
2958
+ obj_ids_local, low_res_masks_local, obj_scores_local = self._propogate_tracker_one_frame_local_gpu(
2959
+ tracker_states_local, frame_idx=frame_idx
2960
+ )
2961
+
2962
+ assert np.all(obj_ids_local == tracker_metadata_prev["obj_ids"]), "{} != {}".format(
2963
+ obj_ids_local, tracker_metadata_prev["obj_ids"]
2964
+ )
2965
+
2966
+ # Step 2: all-gather `low_res_masks_local` into `low_res_masks_global`
2967
+ # - low_res_masks_global: Tensor -- (num_global_obj, H_mask, W_mask)
2968
+ low_res_masks_global = low_res_masks_local
2969
+ obj_scores_global = obj_scores_local
2970
+ return low_res_masks_global, obj_scores_global
2971
+
2972
+ def _recondition_masklets(
2973
+ self,
2974
+ frame_idx,
2975
+ det_out: dict[str, torch.Tensor],
2976
+ trk_id_to_max_iou_high_conf_det: list[int],
2977
+ tracker_states_local: list[Any],
2978
+ tracker_metadata: dict[str, np.ndarray],
2979
+ tracker_obj_scores_global: torch.Tensor,
2980
+ ):
2981
+ """Recondition masklets based on new high-confidence detections."""
2982
+ # Recondition the masklets based on the new detections
2983
+ for trk_obj_id, det_idx in trk_id_to_max_iou_high_conf_det.items():
2984
+ new_mask = det_out["mask"][det_idx : det_idx + 1]
2985
+ new_mask_binary = (
2986
+ F.interpolate(new_mask.unsqueeze(1), size=self.interpol_size, mode="bilinear", align_corners=False) > 0
2987
+ )
2988
+ HIGH_CONF_THRESH = 0.8
2989
+ reconditioned_states_idx = set()
2990
+ obj_idx = np.where(tracker_metadata["obj_ids"] == trk_obj_id)[0].item()
2991
+ obj_score = tracker_obj_scores_global[obj_idx]
2992
+ for state_idx, inference_state in enumerate(tracker_states_local):
2993
+ if (
2994
+ trk_obj_id in inference_state["obj_ids"]
2995
+ # NOTE: Goal of this condition is to avoid reconditioning masks that are occluded/low qualiy.
2996
+ # Unfortunately, these can get reconditioned anyway due to batching. We should consider removing these heuristics.
2997
+ and obj_score > HIGH_CONF_THRESH
2998
+ ):
2999
+ LOGGER.debug(
3000
+ f"Adding new mask for track {trk_obj_id} at frame {frame_idx}. Objects {inference_state['obj_ids']} are all reconditioned."
3001
+ )
3002
+ self.tracker.add_new_prompts(
3003
+ inference_state=inference_state,
3004
+ frame_idx=frame_idx,
3005
+ obj_id=trk_obj_id,
3006
+ masks=new_mask_binary,
3007
+ )
3008
+ reconditioned_states_idx.add(state_idx)
3009
+
3010
+ for idx in reconditioned_states_idx:
3011
+ self.tracker.propagate_in_video_preflight(tracker_states_local[idx])
3012
+ return tracker_states_local
3013
+
3014
+ def run_tracker_update_planning_phase(
3015
+ self,
3016
+ frame_idx: int,
3017
+ reverse: bool,
3018
+ det_out: dict[str, torch.Tensor],
3019
+ tracker_low_res_masks_global: torch.Tensor,
3020
+ tracker_obj_scores_global: torch.Tensor,
3021
+ tracker_metadata_prev: dict[str, np.ndarray],
3022
+ tracker_states_local: list[Any],
3023
+ ):
3024
+ """Run the tracker update planning phase for a single frame in an SPMD manner."""
3025
+ # initialize new metadata from previous metadata (its values will be updated later)
3026
+ tracker_metadata_new = {
3027
+ "obj_ids": deepcopy(tracker_metadata_prev["obj_ids"]),
3028
+ "num_obj": deepcopy(tracker_metadata_prev["num_obj"]),
3029
+ "obj_id_to_score": deepcopy(tracker_metadata_prev["obj_id_to_score"]),
3030
+ "obj_id_to_cls": deepcopy(tracker_metadata_prev["obj_id_to_cls"]),
3031
+ "obj_id_to_tracker_score_frame_wise": deepcopy(tracker_metadata_prev["obj_id_to_tracker_score_frame_wise"]),
3032
+ "obj_id_to_last_occluded": {}, # will be filled later
3033
+ "max_obj_id": deepcopy(tracker_metadata_prev["max_obj_id"]),
3034
+ }
3035
+
3036
+ # Initialize reconditioned_obj_ids early to avoid UnboundLocalError
3037
+ reconditioned_obj_ids = set()
3038
+
3039
+ # Step 1: make the update plan and resolve heuristics on GPU 0
3040
+ det_mask_preds: torch.Tensor = det_out["mask"] # low-res mask logits
3041
+ det_scores_np: np.ndarray = det_out["scores"].float().cpu().numpy()
3042
+ det_cls_np: np.ndarray = det_out["cls"].float().cpu().numpy()
3043
+ det_bbox_xyxy: torch.Tensor = det_out["bbox"]
3044
+ # a) match detector and tracker masks and find new objects
3045
+ (
3046
+ new_det_fa_inds,
3047
+ unmatched_trk_obj_ids,
3048
+ det_to_matched_trk_obj_ids,
3049
+ trk_id_to_max_iou_high_conf_det,
3050
+ empty_trk_obj_ids,
3051
+ ) = self._associate_det_trk(
3052
+ det_masks=det_mask_preds,
3053
+ det_scores_np=det_scores_np,
3054
+ trk_masks=tracker_low_res_masks_global,
3055
+ trk_obj_ids=tracker_metadata_prev["obj_ids"],
3056
+ )
3057
+ if self.suppress_det_close_to_boundary:
3058
+ keep = self._suppress_detections_close_to_boundary(det_bbox_xyxy[new_det_fa_inds])
3059
+ new_det_fa_inds = new_det_fa_inds[keep.cpu().numpy()]
3060
+
3061
+ # check whether we've hit the maximum number of objects we can track (and if so, drop some detections)
3062
+ prev_obj_num = np.sum(tracker_metadata_prev["num_obj"])
3063
+ new_det_num = len(new_det_fa_inds)
3064
+ num_obj_dropped_due_to_limit = 0
3065
+ if prev_obj_num + new_det_num > self.max_num_objects:
3066
+ LOGGER.warning(f"hitting {self.max_num_objects=} with {new_det_num=} and {prev_obj_num=}")
3067
+ new_det_num_to_keep = self.max_num_objects - prev_obj_num
3068
+ num_obj_dropped_due_to_limit = new_det_num - new_det_num_to_keep
3069
+ new_det_fa_inds = self._drop_new_det_with_obj_limit(new_det_fa_inds, det_scores_np, new_det_num_to_keep)
3070
+ assert len(new_det_fa_inds) == new_det_num_to_keep
3071
+ new_det_num = len(new_det_fa_inds)
3072
+
3073
+ # assign object IDs to new detections and decide which GPU to place them
3074
+ new_det_obj_ids = tracker_metadata_prev["max_obj_id"] + 1 + np.arange(new_det_num)
3075
+
3076
+ # b) handle hotstart heuristics to remove objects
3077
+ # here `metadata` contains metadata stored on (and only accessible to) GPU 0;
3078
+ # we avoid broadcasting them to other GPUs to save communication cost, assuming
3079
+ # that `metadata` is not needed by other GPUs
3080
+ metadata_new = deepcopy(tracker_metadata_prev["metadata"])
3081
+ if not hasattr(self, "_warm_up_complete") or self._warm_up_complete:
3082
+ obj_ids_newly_removed, metadata_new = self._process_hotstart(
3083
+ frame_idx=frame_idx,
3084
+ reverse=reverse,
3085
+ det_to_matched_trk_obj_ids=det_to_matched_trk_obj_ids,
3086
+ new_det_obj_ids=new_det_obj_ids,
3087
+ empty_trk_obj_ids=empty_trk_obj_ids,
3088
+ unmatched_trk_obj_ids=unmatched_trk_obj_ids,
3089
+ metadata=metadata_new,
3090
+ )
3091
+ else:
3092
+ # if warm-up is not complete, we don't remove any objects
3093
+ obj_ids_newly_removed = set()
3094
+ tracker_metadata_new["metadata"] = metadata_new
3095
+
3096
+ # `tracker_update_plan` should be identical on all GPUs after broadcasting
3097
+ tracker_update_plan = {
3098
+ "new_det_fa_inds": new_det_fa_inds, # np.ndarray
3099
+ "new_det_obj_ids": new_det_obj_ids, # np.ndarray
3100
+ # "new_det_gpu_ids": new_det_gpu_ids, # np.ndarray
3101
+ "unmatched_trk_obj_ids": unmatched_trk_obj_ids, # np.ndarray
3102
+ "det_to_matched_trk_obj_ids": det_to_matched_trk_obj_ids, # dict
3103
+ "obj_ids_newly_removed": obj_ids_newly_removed, # set
3104
+ "num_obj_dropped_due_to_limit": num_obj_dropped_due_to_limit, # int
3105
+ "trk_id_to_max_iou_high_conf_det": trk_id_to_max_iou_high_conf_det, # dict
3106
+ "reconditioned_obj_ids": reconditioned_obj_ids, # set
3107
+ }
3108
+
3109
+ # Step 3 (optional): recondition masklets based on high-confidence detections before memory encoding
3110
+ # NOTE: Running this in execution phase (after memory encoding) can lead to suboptimal results
3111
+ should_recondition_iou = False
3112
+
3113
+ # Evaluate tracklets for reconditioning based on bbox IoU mismatch with detections
3114
+ if self.reconstruction_bbox_iou_thresh > 0 and len(trk_id_to_max_iou_high_conf_det) > 0:
3115
+ for trk_obj_id, det_idx in trk_id_to_max_iou_high_conf_det.items():
3116
+ det_box = det_out["bbox"][det_idx]
3117
+ det_score = det_out["scores"][det_idx]
3118
+
3119
+ try:
3120
+ trk_idx = list(tracker_metadata_prev["obj_ids"]).index(trk_obj_id)
3121
+ except ValueError:
3122
+ continue # Skip if tracklet not found
3123
+
3124
+ tracker_mask = tracker_low_res_masks_global[trk_idx]
3125
+ mask_binary = tracker_mask > 0
3126
+ mask_area = mask_binary.sum().item()
3127
+
3128
+ if mask_area == 0:
3129
+ continue # Skip tracklets with zero mask area
3130
+
3131
+ # Get bounding box from SAM2 mask and convert to normalized coordinates
3132
+ tracker_box_pixels = batched_mask_to_box(mask_binary.unsqueeze(0)).squeeze(0)
3133
+ mask_height, mask_width = tracker_mask.shape[-2:]
3134
+ tracker_box_normalized = torch.tensor(
3135
+ [
3136
+ tracker_box_pixels[0] / mask_width,
3137
+ tracker_box_pixels[1] / mask_height,
3138
+ tracker_box_pixels[2] / mask_width,
3139
+ tracker_box_pixels[3] / mask_height,
3140
+ ],
3141
+ device=tracker_box_pixels.device,
3142
+ )
3143
+
3144
+ # Compute IoU between detection and SAM2 tracklet bounding boxes
3145
+ det_box_batch = det_box.unsqueeze(0)
3146
+ tracker_box_batch = tracker_box_normalized.unsqueeze(0)
3147
+ iou = box_iou(det_box_batch, tracker_box_batch)[0]
3148
+
3149
+ if iou < self.reconstruction_bbox_iou_thresh and det_score >= self.reconstruction_bbox_det_score:
3150
+ should_recondition_iou = True
3151
+ reconditioned_obj_ids.add(trk_obj_id)
3152
+
3153
+ should_recondition_periodic = (
3154
+ self.recondition_every_nth_frame > 0
3155
+ and frame_idx % self.recondition_every_nth_frame == 0
3156
+ and len(trk_id_to_max_iou_high_conf_det) > 0
3157
+ )
3158
+
3159
+ # Recondition if periodic or IoU condition met
3160
+ if should_recondition_periodic or should_recondition_iou:
3161
+ self._recondition_masklets(
3162
+ frame_idx,
3163
+ det_out,
3164
+ trk_id_to_max_iou_high_conf_det,
3165
+ tracker_states_local,
3166
+ tracker_metadata_prev,
3167
+ tracker_obj_scores_global,
3168
+ )
3169
+
3170
+ # Step 4: Run SAM2 memory encoder on the current frame's prediction masks
3171
+ # This is done on all GPUs
3172
+ batch_size = tracker_low_res_masks_global.size(0)
3173
+ if batch_size > 0:
3174
+ if not hasattr(self, "_warm_up_complete") or self._warm_up_complete:
3175
+ if self.suppress_overlapping_based_on_recent_occlusion_threshold > 0.0:
3176
+ # NOTE: tracker_low_res_masks_global is updated in-place then returned
3177
+ tracker_low_res_masks_global = self._suppress_overlapping_based_on_recent_occlusion(
3178
+ frame_idx,
3179
+ tracker_low_res_masks_global,
3180
+ tracker_metadata_prev,
3181
+ tracker_metadata_new,
3182
+ obj_ids_newly_removed,
3183
+ reverse,
3184
+ )
3185
+
3186
+ self._tracker_update_memories(tracker_states_local, frame_idx, low_res_masks=tracker_low_res_masks_global)
3187
+
3188
+ # Step 4: update the SAM2 metadata based on the update plan
3189
+ updated_obj_ids_this_gpu = tracker_metadata_new["obj_ids"]
3190
+ if len(new_det_obj_ids) > 0:
3191
+ updated_obj_ids_this_gpu = np.concatenate([updated_obj_ids_this_gpu, new_det_obj_ids])
3192
+ if len(obj_ids_newly_removed) > 0:
3193
+ is_removed = np.isin(updated_obj_ids_this_gpu, list(obj_ids_newly_removed))
3194
+ updated_obj_ids_this_gpu = updated_obj_ids_this_gpu[~is_removed]
3195
+ tracker_metadata_new["obj_ids"] = updated_obj_ids_this_gpu
3196
+ tracker_metadata_new["num_obj"] = len(updated_obj_ids_this_gpu)
3197
+ # update object scores and the maximum object ID assigned so far
3198
+ if len(new_det_obj_ids) > 0:
3199
+ tracker_metadata_new["obj_id_to_score"].update(zip(new_det_obj_ids, det_scores_np[new_det_fa_inds]))
3200
+ tracker_metadata_new["obj_id_to_cls"].update(zip(new_det_obj_ids, det_cls_np[new_det_fa_inds]))
3201
+ # tracker scores are not available for new objects, use det score instead.
3202
+ tracker_metadata_new["obj_id_to_tracker_score_frame_wise"][frame_idx].update(
3203
+ zip(new_det_obj_ids, det_scores_np[new_det_fa_inds])
3204
+ )
3205
+ tracker_metadata_new["max_obj_id"] = max(tracker_metadata_new["max_obj_id"], np.max(new_det_obj_ids))
3206
+ # for removed objects, we set their scores to a very low value (-1e4) but still
3207
+ # keep them in "obj_id_to_score" (it's easier to handle outputs this way)
3208
+ for obj_id in obj_ids_newly_removed:
3209
+ tracker_metadata_new["obj_id_to_score"][obj_id] = -1e4
3210
+ tracker_metadata_new["obj_id_to_tracker_score_frame_wise"][frame_idx][obj_id] = -1e4
3211
+ tracker_metadata_new["obj_id_to_last_occluded"].pop(obj_id, None)
3212
+ # check that "metadata" is in tracker_metadata_new if and only if it's GPU 0
3213
+ assert "metadata" in tracker_metadata_new
3214
+ if self.masklet_confirmation_enable:
3215
+ metadata = self.update_masklet_confirmation_status(
3216
+ metadata=tracker_metadata_new["metadata"],
3217
+ obj_ids_all_gpu_prev=tracker_metadata_prev["obj_ids"],
3218
+ obj_ids_all_gpu_updated=tracker_metadata_new["obj_ids"],
3219
+ det_to_matched_trk_obj_ids=det_to_matched_trk_obj_ids,
3220
+ new_det_obj_ids=new_det_obj_ids,
3221
+ )
3222
+ tracker_metadata_new["metadata"] = metadata
3223
+
3224
+ return tracker_update_plan, tracker_metadata_new
3225
+
3226
+ def _suppress_overlapping_based_on_recent_occlusion(
3227
+ self,
3228
+ frame_idx: int,
3229
+ tracker_low_res_masks_global: torch.Tensor,
3230
+ tracker_metadata_prev: dict[str, Any],
3231
+ tracker_metadata_new: dict[str, Any],
3232
+ obj_ids_newly_removed: set[int],
3233
+ reverse: bool = False,
3234
+ ):
3235
+ """Suppress overlapping masks based on the most recent occlusion information. If an object is removed by
3236
+ hotstart, we always suppress it if it overlaps with any other object.
3237
+
3238
+ Args:
3239
+ frame_idx (int): The current frame index.
3240
+ tracker_low_res_masks_global (torch.Tensor): The low-resolution masks for the current frame.
3241
+ tracker_metadata_prev (dict[str, Any]): The metadata from the previous frame.
3242
+ tracker_metadata_new (dict[str, Any]): The metadata for the current frame.
3243
+ obj_ids_newly_removed (set[int]): The object IDs that have been removed.
3244
+ reverse (bool): Whether the tracking is in reverse order.
3245
+
3246
+ Returns:
3247
+ (torch.Tensor): The updated low-resolution masks with some objects suppressed.
3248
+ """
3249
+ obj_ids_global = tracker_metadata_prev["obj_ids"]
3250
+ binary_tracker_low_res_masks_global = tracker_low_res_masks_global > 0
3251
+ batch_size = tracker_low_res_masks_global.size(0)
3252
+ if batch_size > 0:
3253
+ assert len(obj_ids_global) == batch_size, (
3254
+ f"Mismatch in number of objects: {len(obj_ids_global)} vs {batch_size}"
3255
+ )
3256
+ last_occluded_prev = torch.cat(
3257
+ [
3258
+ tracker_metadata_prev["obj_id_to_last_occluded"].get(
3259
+ obj_id,
3260
+ torch.full(
3261
+ (1,),
3262
+ fill_value=(
3263
+ self.NEVER_OCCLUDED if obj_id not in obj_ids_newly_removed else self.ALWAYS_OCCLUDED
3264
+ ),
3265
+ device=binary_tracker_low_res_masks_global.device,
3266
+ dtype=torch.long,
3267
+ ),
3268
+ )
3269
+ for obj_id in obj_ids_global
3270
+ ],
3271
+ dim=0,
3272
+ )
3273
+ to_suppress = self._get_objects_to_suppress_based_on_most_recently_occluded(
3274
+ binary_tracker_low_res_masks_global,
3275
+ last_occluded_prev,
3276
+ obj_ids_global,
3277
+ frame_idx,
3278
+ reverse,
3279
+ )
3280
+
3281
+ # Update metadata with occlusion information
3282
+ is_obj_occluded = ~(binary_tracker_low_res_masks_global.any(dim=(-1, -2)))
3283
+ is_obj_occluded_or_suppressed = is_obj_occluded | to_suppress
3284
+ last_occluded_new = last_occluded_prev.clone()
3285
+ last_occluded_new[is_obj_occluded_or_suppressed] = frame_idx
3286
+ # Slice out the last occluded frame for each object
3287
+ tracker_metadata_new["obj_id_to_last_occluded"] = {
3288
+ obj_id: last_occluded_new[obj_idx : obj_idx + 1] for obj_idx, obj_id in enumerate(obj_ids_global)
3289
+ }
3290
+
3291
+ # Zero out suppressed masks before memory encoding
3292
+ tracker_low_res_masks_global[to_suppress] = self.NO_OBJ_LOGIT
3293
+
3294
+ return tracker_low_res_masks_global
3295
+
3296
+ def run_tracker_update_execution_phase(
3297
+ self,
3298
+ frame_idx: int,
3299
+ num_frames: int,
3300
+ det_out: dict[str, torch.Tensor],
3301
+ tracker_states_local: list[Any],
3302
+ tracker_update_plan: dict[str, np.ndarray],
3303
+ ):
3304
+ """Execute the tracker update plan for a single frame in an SPMD manner."""
3305
+ # initialize tracking scores with detection scores
3306
+ new_det_fa_inds: np.ndarray = tracker_update_plan["new_det_fa_inds"]
3307
+ new_det_obj_ids: np.ndarray = tracker_update_plan["new_det_obj_ids"]
3308
+ # new_det_gpu_ids: np.ndarray = tracker_update_plan["new_det_gpu_ids"]
3309
+ new_det_obj_ids_local: np.ndarray = new_det_obj_ids
3310
+ new_det_fa_inds_local: np.ndarray = new_det_fa_inds
3311
+ obj_ids_newly_removed: set[int] = tracker_update_plan["obj_ids_newly_removed"]
3312
+
3313
+ # Step 1: add new objects from the detector to SAM2 inference states
3314
+ if len(new_det_fa_inds_local) > 0:
3315
+ new_det_fa_inds_local_t = torch.from_numpy(new_det_fa_inds_local)
3316
+ new_det_masks: torch.Tensor = det_out["mask"][new_det_fa_inds_local_t]
3317
+ # initialize SAM2 with new object masks
3318
+ tracker_states_local = self._tracker_add_new_objects(
3319
+ frame_idx=frame_idx,
3320
+ num_frames=num_frames,
3321
+ new_obj_ids=new_det_obj_ids_local,
3322
+ new_obj_masks=new_det_masks,
3323
+ tracker_states_local=tracker_states_local,
3324
+ )
3325
+
3326
+ # Step 2: remove from SAM2 inference states those objects removed by heuristics
3327
+ if len(obj_ids_newly_removed) > 0:
3328
+ self._tracker_remove_objects(tracker_states_local, obj_ids_newly_removed)
3329
+
3330
+ return tracker_states_local
3331
+
3332
+ @staticmethod
3333
+ def build_outputs(
3334
+ det_out: dict[str, torch.Tensor],
3335
+ tracker_low_res_masks_global: torch.Tensor,
3336
+ tracker_metadata_prev: dict[str, np.ndarray],
3337
+ tracker_update_plan: dict[str, np.ndarray],
3338
+ reconditioned_obj_ids: set | None = None,
3339
+ ):
3340
+ """Build the output masks for the current frame."""
3341
+ new_det_fa_inds: np.ndarray = tracker_update_plan["new_det_fa_inds"]
3342
+ new_det_obj_ids: np.ndarray = tracker_update_plan["new_det_obj_ids"]
3343
+ obj_id_to_mask = {} # obj_id --> output mask tensor
3344
+
3345
+ # Part 1: masks from previous SAM2 propagation
3346
+ existing_masklet_obj_ids = tracker_metadata_prev["obj_ids"]
3347
+ existing_masklet_binary = tracker_low_res_masks_global.unsqueeze(1)
3348
+ assert len(existing_masklet_obj_ids) == len(existing_masklet_binary)
3349
+ for obj_id, mask in zip(existing_masklet_obj_ids, existing_masklet_binary):
3350
+ obj_id_to_mask[obj_id] = mask # (1, H_video, W_video)
3351
+
3352
+ # Part 2: masks from new detections
3353
+ new_det_fa_inds_t = torch.from_numpy(new_det_fa_inds)
3354
+ new_det_low_res_masks = det_out["mask"][new_det_fa_inds_t].unsqueeze(1)
3355
+ assert len(new_det_obj_ids) == len(new_det_low_res_masks)
3356
+ for obj_id, mask in zip(new_det_obj_ids, new_det_low_res_masks):
3357
+ obj_id_to_mask[obj_id] = mask # (1, H_video, W_video)
3358
+
3359
+ # Part 3: Override masks for reconditioned objects using detection masks
3360
+ if reconditioned_obj_ids is not None and len(reconditioned_obj_ids) > 0:
3361
+ trk_id_to_max_iou_high_conf_det = tracker_update_plan.get("trk_id_to_max_iou_high_conf_det", {})
3362
+
3363
+ for obj_id in reconditioned_obj_ids:
3364
+ det_idx = trk_id_to_max_iou_high_conf_det.get(obj_id)
3365
+
3366
+ if det_idx is not None:
3367
+ obj_id_to_mask[obj_id] = det_out["mask"][det_idx].unsqueeze(0)
3368
+
3369
+ return obj_id_to_mask
3370
+
3371
+ def _get_objects_to_suppress_based_on_most_recently_occluded(
3372
+ self,
3373
+ binary_low_res_masks: torch.Tensor,
3374
+ last_occluded: list[int],
3375
+ obj_ids: list[int],
3376
+ frame_idx: int | None = None,
3377
+ reverse: bool = False,
3378
+ ):
3379
+ # Suppress overlapping masks for objects that were most recently occluded
3380
+ assert binary_low_res_masks.dtype == torch.bool, f"Expected boolean tensor, got {binary_low_res_masks.dtype}"
3381
+ to_suppress = torch.zeros(
3382
+ binary_low_res_masks.size(0),
3383
+ device=binary_low_res_masks.device,
3384
+ dtype=torch.bool,
3385
+ )
3386
+ if len(obj_ids) <= 1:
3387
+ return to_suppress
3388
+
3389
+ iou = mask_iou(binary_low_res_masks.flatten(1), binary_low_res_masks.flatten(1)) # [N,N]
3390
+
3391
+ # Create masks for upper triangular matrix (i < j) and IoU threshold
3392
+ mask_iou_thresh = iou >= self.suppress_overlapping_based_on_recent_occlusion_threshold
3393
+ overlapping_pairs = torch.triu(mask_iou_thresh, diagonal=1) # [N,N]
3394
+
3395
+ last_occ_expanded_i = last_occluded.unsqueeze(1) # (N, 1)
3396
+ last_occ_expanded_j = last_occluded.unsqueeze(0) # (1, N)
3397
+ # Suppress most recently occluded
3398
+ cmp_op = torch.gt if not reverse else torch.lt
3399
+ suppress_i_mask = (
3400
+ overlapping_pairs
3401
+ & cmp_op(last_occ_expanded_i, last_occ_expanded_j) # (last_occ_expanded_i > last_occ_expanded_j)
3402
+ & (last_occ_expanded_j > -1) # j can suppress i only if i was previously occluded
3403
+ )
3404
+ suppress_j_mask = (
3405
+ overlapping_pairs
3406
+ & cmp_op(last_occ_expanded_j, last_occ_expanded_i)
3407
+ & (last_occ_expanded_i > -1) # i can suppress j only if j was previously occluded
3408
+ )
3409
+ # Apply suppression
3410
+ to_suppress = suppress_i_mask.any(dim=1) | suppress_j_mask.any(dim=0)
3411
+
3412
+ # Log for debugging
3413
+ if LOGGER.isEnabledFor(10) and frame_idx is not None:
3414
+ suppress_i_mask = suppress_i_mask.cpu().numpy()
3415
+ suppress_j_mask = suppress_j_mask.cpu().numpy()
3416
+ last_occluded = last_occluded.cpu().numpy()
3417
+
3418
+ # Find all suppression pairs without using torch.where
3419
+ batch_size = suppress_i_mask.shape[0]
3420
+
3421
+ # Log i-suppression cases (where i gets suppressed in favor of j)
3422
+ for i in range(batch_size):
3423
+ for j in range(batch_size):
3424
+ if suppress_i_mask[i, j]:
3425
+ LOGGER.debug(
3426
+ f"{frame_idx=}: Suppressing obj {obj_ids[i]} last occluded {last_occluded[i]} in favor of {obj_ids[j]} last occluded {last_occluded[j]}"
3427
+ )
3428
+
3429
+ # Log j-suppression cases (where j gets suppressed in favor of i)
3430
+ for i in range(batch_size):
3431
+ for j in range(batch_size):
3432
+ if suppress_j_mask[i, j]:
3433
+ LOGGER.debug(
3434
+ f"{frame_idx=}: Suppressing obj {obj_ids[j]} last occluded {last_occluded[j]} in favor of {obj_ids[i]} last occluded {last_occluded[i]}"
3435
+ )
3436
+
3437
+ return to_suppress
3438
+
3439
+ def _propogate_tracker_one_frame_local_gpu(self, inference_states: list[Any], frame_idx: int):
3440
+ """Inference_states: list of inference states, each state corresponds to a different set of objects."""
3441
+ obj_ids_local = []
3442
+ low_res_masks_list = []
3443
+ obj_scores_list = []
3444
+ for inference_state in inference_states:
3445
+ if len(inference_state["obj_ids"]) == 0:
3446
+ continue # skip propagation on empty inference states
3447
+
3448
+ out_obj_ids, out_low_res_masks, out_obj_scores = self.tracker.propagate_in_video(
3449
+ inference_state, frame_idx=frame_idx
3450
+ )
3451
+ assert isinstance(out_obj_ids, list)
3452
+ obj_ids_local.extend(out_obj_ids)
3453
+ low_res_masks_list.append(out_low_res_masks.squeeze(1))
3454
+ obj_scores_list.append(out_obj_scores.squeeze(1))
3455
+
3456
+ # concatenate the output masklets from all local inference states
3457
+ if len(low_res_masks_list) > 0:
3458
+ low_res_masks_local = torch.cat(low_res_masks_list, dim=0)
3459
+ obj_scores_local = torch.cat(obj_scores_list, dim=0)
3460
+ low_res_masks_local = low_res_masks_local.squeeze(1)
3461
+ else:
3462
+ low_res_masks_local = torch.zeros(0, *self._bb_feat_sizes[0], device=self.device)
3463
+ obj_scores_local = torch.zeros(0, device=self.device)
3464
+
3465
+ return obj_ids_local, low_res_masks_local, obj_scores_local
3466
+
3467
+ def _associate_det_trk(
3468
+ self,
3469
+ det_masks: torch.Tensor,
3470
+ det_scores_np: np.ndarray,
3471
+ trk_masks: torch.Tensor,
3472
+ trk_obj_ids: np.ndarray,
3473
+ ):
3474
+ """Match detections on the current frame with the existing masklets.
3475
+
3476
+ Args:
3477
+ det_masks: (N, H, W) tensor of predicted masks
3478
+ det_scores_np: (N,) array of detection scores
3479
+ trk_masks: (M, H, W) tensor of track masks
3480
+ trk_obj_ids: (M,) array of object IDs corresponding to trk_masks
3481
+
3482
+ Returns:
3483
+ new_det_fa_inds: array of new object indices.
3484
+ unmatched_trk_obj_ids: array of existing masklet object IDs that are not matched to any detections on this
3485
+ frame (for unmatched, we only count masklets with >0 area)
3486
+ det_to_matched_trk_obj_ids: dict[int, np.ndarray]: mapping from detector's detection indices to the list of
3487
+ matched tracklet object IDs
3488
+ empty_trk_obj_ids: array of existing masklet object IDs with zero area in SAM2 prediction
3489
+ """
3490
+ iou_threshold = self.assoc_iou_thresh
3491
+ iou_threshold_trk = self.trk_assoc_iou_thresh
3492
+ new_det_thresh = self.new_det_thresh
3493
+
3494
+ assert det_masks.is_floating_point(), "float tensor expected (do not binarize)"
3495
+ assert trk_masks.is_floating_point(), "float tensor expected (do not binarize)"
3496
+ assert trk_masks.size(0) == len(trk_obj_ids), (
3497
+ f"trk_masks and trk_obj_ids should have the same length, {trk_masks.size(0)} vs {len(trk_obj_ids)}"
3498
+ )
3499
+ if trk_masks.size(0) == 0:
3500
+ # all detections are new
3501
+ new_det_fa_inds = np.arange(det_masks.size(0))
3502
+ unmatched_trk_obj_ids = np.array([], np.int64)
3503
+ empty_trk_obj_ids = np.array([], np.int64)
3504
+ det_to_matched_trk_obj_ids = {}
3505
+ trk_id_to_max_iou_high_conf_det = {}
3506
+ return (
3507
+ new_det_fa_inds,
3508
+ unmatched_trk_obj_ids,
3509
+ det_to_matched_trk_obj_ids,
3510
+ trk_id_to_max_iou_high_conf_det,
3511
+ empty_trk_obj_ids,
3512
+ )
3513
+ elif det_masks.size(0) == 0:
3514
+ # all previous tracklets are unmatched if they have a non-zero area
3515
+ new_det_fa_inds = np.array([], np.int64)
3516
+ trk_is_nonempty = (trk_masks > 0).any(dim=(1, 2)).cpu().numpy()
3517
+ unmatched_trk_obj_ids = trk_obj_ids[trk_is_nonempty]
3518
+ empty_trk_obj_ids = trk_obj_ids[~trk_is_nonempty]
3519
+ det_to_matched_trk_obj_ids = {}
3520
+ trk_id_to_max_iou_high_conf_det = {}
3521
+ return (
3522
+ new_det_fa_inds,
3523
+ unmatched_trk_obj_ids,
3524
+ det_to_matched_trk_obj_ids,
3525
+ trk_id_to_max_iou_high_conf_det,
3526
+ empty_trk_obj_ids,
3527
+ )
3528
+
3529
+ if det_masks.shape[-2:] != trk_masks.shape[-2:]:
3530
+ # resize to the smaller size to save GPU memory
3531
+ if np.prod(det_masks.shape[-2:]) < np.prod(trk_masks.shape[-2:]):
3532
+ trk_masks = F.interpolate(
3533
+ trk_masks.unsqueeze(1),
3534
+ size=det_masks.shape[-2:],
3535
+ mode="bilinear",
3536
+ align_corners=False,
3537
+ ).squeeze(1)
3538
+ else:
3539
+ # resize detections to track size
3540
+ det_masks = F.interpolate(
3541
+ det_masks.unsqueeze(1),
3542
+ size=trk_masks.shape[-2:],
3543
+ mode="bilinear",
3544
+ align_corners=False,
3545
+ ).squeeze(1)
3546
+
3547
+ det_masks_binary = det_masks > 0
3548
+ trk_masks_binary = trk_masks > 0
3549
+ ious = mask_iou(det_masks_binary.flatten(1).float(), trk_masks_binary.flatten(1).float()) # (N, M)
3550
+
3551
+ ious_np = ious.cpu().numpy()
3552
+ if self.o2o_matching_masklets_enable:
3553
+ from scipy.optimize import linear_sum_assignment
3554
+
3555
+ # Hungarian matching for tracks (one-to-one: each track matches at most one detection)
3556
+ cost_matrix = 1 - ious_np # Hungarian solves for minimum cost
3557
+ row_ind, col_ind = linear_sum_assignment(cost_matrix)
3558
+ trk_is_matched = np.zeros(trk_masks.size(0), dtype=bool)
3559
+ for d, t in zip(row_ind, col_ind):
3560
+ if ious_np[d, t] >= iou_threshold_trk:
3561
+ trk_is_matched[t] = True
3562
+ else:
3563
+ trk_is_matched = (ious_np >= iou_threshold_trk).any(axis=0)
3564
+ # Non-empty tracks not matched by Hungarian assignment above threshold are unmatched
3565
+ trk_is_nonempty = trk_masks_binary.any(dim=(1, 2)).cpu().numpy()
3566
+ trk_is_unmatched = np.logical_and(trk_is_nonempty, ~trk_is_matched)
3567
+ unmatched_trk_obj_ids = trk_obj_ids[trk_is_unmatched]
3568
+ # also record masklets that have zero area in SAM 2 prediction
3569
+ empty_trk_obj_ids = trk_obj_ids[~trk_is_nonempty]
3570
+
3571
+ # For detections: allow many tracks to match to the same detection (many-to-one)
3572
+ # So, a detection is 'new' if it does not match any track above threshold
3573
+ is_new_det = np.logical_and(
3574
+ det_scores_np >= new_det_thresh,
3575
+ np.logical_not(np.any(ious_np >= iou_threshold, axis=1)),
3576
+ )
3577
+ new_det_fa_inds = np.nonzero(is_new_det)[0]
3578
+
3579
+ # for each detection, which tracks it matched to (above threshold)
3580
+ det_to_matched_trk_obj_ids = {}
3581
+ trk_id_to_max_iou_high_conf_det = {} # trk id --> exactly one detection idx
3582
+ det_to_max_iou_trk_idx = np.argmax(ious_np, axis=1)
3583
+ det_is_high_conf = (det_scores_np >= self.HIGH_CONF_THRESH) & ~is_new_det
3584
+ det_is_high_iou = np.max(ious_np, axis=1) >= self.HIGH_IOU_THRESH
3585
+ det_is_high_conf_and_iou = set(np.nonzero(det_is_high_conf & det_is_high_iou)[0])
3586
+ for d in range(det_masks.size(0)):
3587
+ det_to_matched_trk_obj_ids[d] = trk_obj_ids[ious_np[d, :] >= iou_threshold]
3588
+ if d in det_is_high_conf_and_iou:
3589
+ trk_obj_id = trk_obj_ids[det_to_max_iou_trk_idx[d]].item()
3590
+ trk_id_to_max_iou_high_conf_det[trk_obj_id] = d
3591
+
3592
+ return (
3593
+ new_det_fa_inds,
3594
+ unmatched_trk_obj_ids,
3595
+ det_to_matched_trk_obj_ids,
3596
+ trk_id_to_max_iou_high_conf_det,
3597
+ empty_trk_obj_ids,
3598
+ )
3599
+
3600
+ def _process_hotstart(
3601
+ self,
3602
+ frame_idx: int,
3603
+ reverse: bool,
3604
+ det_to_matched_trk_obj_ids: dict[int, np.ndarray],
3605
+ new_det_obj_ids: np.ndarray,
3606
+ empty_trk_obj_ids: np.ndarray,
3607
+ unmatched_trk_obj_ids: np.ndarray,
3608
+ metadata: dict[str, Any],
3609
+ ):
3610
+ """Handle hotstart heuristics to remove unmatched or duplicated objects."""
3611
+ # obj_id --> first frame index where the object was detected
3612
+ obj_first_frame_idx = metadata["obj_first_frame_idx"]
3613
+ # obj_id --> [mismatched frame indices]
3614
+ unmatched_frame_inds = metadata["unmatched_frame_inds"]
3615
+ trk_keep_alive = metadata["trk_keep_alive"]
3616
+ # (first_appear_obj_id, obj_id) --> [overlap frame indices]
3617
+ overlap_pair_to_frame_inds = metadata["overlap_pair_to_frame_inds"]
3618
+ # removed_obj_ids: object IDs that are suppressed via hot-start
3619
+ removed_obj_ids = metadata["removed_obj_ids"]
3620
+
3621
+ obj_ids_newly_removed = set() # object IDs to be newly removed on this frame
3622
+ hotstart_diff = frame_idx - self.hotstart_delay if not reverse else frame_idx + self.hotstart_delay
3623
+
3624
+ # Step 1: log the frame index where each object ID first appears
3625
+ for obj_id in new_det_obj_ids:
3626
+ if obj_id not in obj_first_frame_idx:
3627
+ obj_first_frame_idx[obj_id] = frame_idx
3628
+ assert obj_id not in trk_keep_alive
3629
+ trk_keep_alive[obj_id] = self.init_trk_keep_alive
3630
+
3631
+ matched_trks = set()
3632
+ # We use the det-->tracks list to check for matched objects. Otherwise, we need to compute areas to decide whether they're occluded
3633
+ for matched_trks_per_det in det_to_matched_trk_obj_ids.values():
3634
+ matched_trks.update(matched_trks_per_det)
3635
+ for obj_id in matched_trks:
3636
+ # NOTE: To minimize number of configurable params, we use the hotstart_unmatch_thresh to set the max value of trk_keep_alive
3637
+ trk_keep_alive[obj_id] = min(self.max_trk_keep_alive, trk_keep_alive[obj_id] + 1)
3638
+ for obj_id in unmatched_trk_obj_ids:
3639
+ unmatched_frame_inds[obj_id].append(frame_idx)
3640
+ # NOTE: To minimize number of configurable params, we use the hotstart_unmatch_thresh to set the min value of trk_keep_alive
3641
+ # 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.
3642
+ trk_keep_alive[obj_id] = max(self.min_trk_keep_alive, trk_keep_alive[obj_id] - 1)
3643
+ if self.decrease_trk_keep_alive_for_empty_masklets:
3644
+ for obj_id in empty_trk_obj_ids:
3645
+ # NOTE: To minimize number of configurable params, we use the hotstart_unmatch_thresh to set the min value of trk_keep_alive
3646
+ trk_keep_alive[obj_id] = max(self.min_trk_keep_alive, trk_keep_alive[obj_id] - 1)
3647
+
3648
+ # Step 2: removed tracks that has not matched with detections for `hotstart_unmatch_thresh` frames with hotstart period
3649
+ # a) add unmatched frame indices for each existing object ID
3650
+ # note that `unmatched_trk_obj_ids` contains those frames where the SAM2 output mask
3651
+ # doesn't match any detection; it excludes those frames where SAM2 gives an empty mask
3652
+ # b) remove a masklet if it first appears after `hotstart_diff` and is unmatched for more
3653
+ # than `self.hotstart_unmatch_thresh` frames
3654
+ for obj_id, frame_indices in unmatched_frame_inds.items():
3655
+ if obj_id in removed_obj_ids or obj_id in obj_ids_newly_removed:
3656
+ continue # skip if the object is already removed
3657
+ if len(frame_indices) >= self.hotstart_unmatch_thresh:
3658
+ is_within_hotstart = (obj_first_frame_idx[obj_id] > hotstart_diff and not reverse) or (
3659
+ obj_first_frame_idx[obj_id] < hotstart_diff and reverse
3660
+ )
3661
+ if is_within_hotstart:
3662
+ obj_ids_newly_removed.add(obj_id)
3663
+ LOGGER.debug(
3664
+ f"Removing object {obj_id} at frame {frame_idx} "
3665
+ f"since it is unmatched for frames: {frame_indices}"
3666
+ )
3667
+ if (
3668
+ trk_keep_alive[obj_id] <= 0 # Object has not been matched for too long
3669
+ and obj_id not in removed_obj_ids
3670
+ and obj_id not in obj_ids_newly_removed
3671
+ ):
3672
+ LOGGER.debug(f"Removing object {obj_id} at frame {frame_idx}, due to being unmatched")
3673
+ # directly removed the object instead of suppressing it
3674
+ obj_ids_newly_removed.add(obj_id)
3675
+
3676
+ # Step 3: removed tracks that overlaps with another track for `hotstart_dup_thresh` frames
3677
+ # a) find overlaps tracks -- we consider overlap if they match to the same detection
3678
+ for _, matched_trk_obj_ids in det_to_matched_trk_obj_ids.items():
3679
+ if len(matched_trk_obj_ids) < 2:
3680
+ continue # only count detections that are matched to multiple (>=2) masklets
3681
+ # if there are multiple matched track ids, we need to find the one that appeared first;
3682
+ # these later appearing ids may be removed since they may be considered as duplicates
3683
+ first_appear_obj_id = (
3684
+ min(matched_trk_obj_ids, key=lambda x: obj_first_frame_idx[x])
3685
+ if not reverse
3686
+ else max(matched_trk_obj_ids, key=lambda x: obj_first_frame_idx[x])
3687
+ )
3688
+ for obj_id in matched_trk_obj_ids:
3689
+ if obj_id != first_appear_obj_id:
3690
+ key = (first_appear_obj_id, obj_id)
3691
+ overlap_pair_to_frame_inds[key].append(frame_idx)
3692
+
3693
+ # b) remove a masklet if it first appears after `hotstart_diff` and it overlaps with another
3694
+ # masklet (that appears earlier) for more than `self.hotstart_dup_thresh` frames
3695
+ for (first_obj_id, obj_id), frame_indices in overlap_pair_to_frame_inds.items():
3696
+ if obj_id in removed_obj_ids or obj_id in obj_ids_newly_removed:
3697
+ continue # skip if the object is already removed
3698
+ if (obj_first_frame_idx[obj_id] > hotstart_diff and not reverse) or (
3699
+ obj_first_frame_idx[obj_id] < hotstart_diff and reverse
3700
+ ):
3701
+ if len(frame_indices) >= self.hotstart_dup_thresh:
3702
+ obj_ids_newly_removed.add(obj_id)
3703
+ LOGGER.debug(
3704
+ f"Removing object {obj_id} at frame {frame_idx} "
3705
+ f"since it overlaps with another track {first_obj_id} at frames: {frame_indices}"
3706
+ )
3707
+
3708
+ removed_obj_ids.update(obj_ids_newly_removed)
3709
+ return obj_ids_newly_removed, metadata
3710
+
3711
+ def _tracker_update_memories(
3712
+ self, tracker_inference_states: list[Any], frame_idx: int, low_res_masks: torch.Tensor
3713
+ ):
3714
+ """Run Sam2 memory encoder, enforcing non-overlapping constraints globally."""
3715
+ if len(tracker_inference_states) == 0:
3716
+ return
3717
+ # NOTE: inspect this part if we observe OOMs in the demo
3718
+ high_res_masks = F.interpolate(
3719
+ low_res_masks.unsqueeze(1),
3720
+ size=self.interpol_size,
3721
+ mode="bilinear",
3722
+ align_corners=False,
3723
+ )
3724
+ # We first apply non-overlapping constraints before memory encoding. This may include some suppression heuristics.
3725
+ if not hasattr(self, "_warm_up_complete") or self._warm_up_complete:
3726
+ high_res_masks = self.tracker.model._suppress_object_pw_area_shrinkage(high_res_masks)
3727
+ # Instead of gathering the predicted object scores, we use mask areas as a proxy.
3728
+ object_score_logits = torch.where((high_res_masks > 0).any(dim=(-1, -2)), 10.0, -10.0)
3729
+
3730
+ # Run the memory encoder on local slices for each GPU
3731
+ start_idx_gpu = 0
3732
+ start_idx_state = start_idx_gpu
3733
+ for tracker_state in tracker_inference_states:
3734
+ num_obj_per_state = len(tracker_state["obj_ids"])
3735
+ if num_obj_per_state == 0:
3736
+ continue
3737
+ # Get the local high-res masks and object score logits for this inference state
3738
+ end_idx_state = start_idx_state + num_obj_per_state
3739
+ local_high_res_masks = high_res_masks[start_idx_state:end_idx_state]
3740
+ local_object_score_logits = object_score_logits[start_idx_state:end_idx_state]
3741
+ local_batch_size = local_high_res_masks.size(0)
3742
+ # Run Sam2 memory encoder. Note that we do not re-enforce the non-overlapping constraint as it is turned off by default
3743
+
3744
+ encoded_mem = self.tracker._run_memory_encoder(
3745
+ local_batch_size,
3746
+ local_high_res_masks,
3747
+ local_object_score_logits,
3748
+ is_mask_from_pts=False,
3749
+ inference_state=tracker_state,
3750
+ )
3751
+ local_maskmem_features, local_maskmem_pos_enc = encoded_mem
3752
+ # Store encoded memories in the local inference state
3753
+ output_dict = tracker_state["output_dict"]
3754
+ for storage_key in ["cond_frame_outputs", "non_cond_frame_outputs"]:
3755
+ if frame_idx not in output_dict[storage_key]:
3756
+ continue
3757
+ output_dict[storage_key][frame_idx]["maskmem_features"] = local_maskmem_features
3758
+ output_dict[storage_key][frame_idx]["maskmem_pos_enc"] = [pos for pos in local_maskmem_pos_enc]
3759
+ # for batched inference state, we also need to add per-object
3760
+ # memory slides to support instance interactivity
3761
+ self.tracker._add_output_per_object(
3762
+ inference_state=tracker_state,
3763
+ frame_idx=frame_idx,
3764
+ current_out=output_dict[storage_key][frame_idx],
3765
+ storage_key=storage_key,
3766
+ )
3767
+ start_idx_state += num_obj_per_state
3768
+
3769
+ def _tracker_add_new_objects(
3770
+ self,
3771
+ frame_idx: int,
3772
+ num_frames: int,
3773
+ new_obj_ids: list[int],
3774
+ new_obj_masks: torch.Tensor,
3775
+ tracker_states_local: list[Any],
3776
+ ):
3777
+ """Add a new object to SAM2 inference states."""
3778
+ prev_tracker_state = tracker_states_local[0] if len(tracker_states_local) > 0 else None
3779
+
3780
+ # prepare inference_state
3781
+ # batch objects that first appear on the same frame together
3782
+ # Clear inference state. Keep the cached image features if available.
3783
+ new_tracker_state = self.tracker._init_state(num_frames=num_frames)
3784
+ # NOTE: adding image placeholder
3785
+ new_tracker_state["im"] = None
3786
+ new_tracker_state["backbone_out"] = (
3787
+ prev_tracker_state.get("backbone_out", None) if prev_tracker_state is not None else None
3788
+ )
3789
+
3790
+ assert len(new_obj_ids) == new_obj_masks.size(0)
3791
+ assert new_obj_masks.is_floating_point()
3792
+ new_obj_masks = F.interpolate(
3793
+ new_obj_masks.unsqueeze(0),
3794
+ size=self.interpol_size,
3795
+ mode="bilinear",
3796
+ align_corners=False,
3797
+ ).squeeze(0)
3798
+ new_obj_masks = new_obj_masks > 0
3799
+
3800
+ # add object one by one
3801
+ for new_obj_id, new_mask in zip(new_obj_ids, new_obj_masks):
3802
+ self.tracker.add_new_prompts(
3803
+ inference_state=new_tracker_state,
3804
+ frame_idx=frame_idx,
3805
+ obj_id=new_obj_id,
3806
+ masks=new_mask[None, None], # add bs, channel
3807
+ )
3808
+ # NOTE: we skip enforcing the non-overlapping constraint **globally** when adding new objects.
3809
+ self.tracker.propagate_in_video_preflight(new_tracker_state)
3810
+ tracker_states_local.append(new_tracker_state)
3811
+ return tracker_states_local
3812
+
3813
+ def _tracker_remove_objects(self, tracker_states_local: list[Any], obj_ids: list[int]):
3814
+ """Remove an object from SAM2 inference states. This would remove the object from all frames in the video."""
3815
+ if not obj_ids:
3816
+ return
3817
+ # Filter out states that become empty after removal
3818
+ active_states = []
3819
+ for state in tracker_states_local:
3820
+ for obj_id in obj_ids:
3821
+ # we try to remove `obj_id` on every inference state with `strict=False`
3822
+ # it will not do anything if an inference state doesn't contain `obj_id`
3823
+ self.tracker.remove_object(state, obj_id, strict=False)
3824
+
3825
+ if len(state["obj_ids"]) > 0:
3826
+ active_states.append(state)
3827
+
3828
+ # Update the list in-place
3829
+ tracker_states_local[:] = active_states
3830
+
3831
+ def _initialize_metadata(self):
3832
+ """Initialize metadata for the masklets."""
3833
+ tracker_metadata = {
3834
+ "obj_ids": np.array([], np.int32),
3835
+ "num_obj": np.zeros(1, np.int32),
3836
+ "max_obj_id": -1,
3837
+ "obj_id_to_score": {},
3838
+ "obj_id_to_cls": {},
3839
+ "obj_id_to_tracker_score_frame_wise": defaultdict(dict),
3840
+ "obj_id_to_last_occluded": {},
3841
+ }
3842
+ # "metadata" contains metadata that is only stored on (and accessible to) GPU 0
3843
+ # - obj_first_frame_idx: obj_id --> first frame index where the object was detected
3844
+ # - unmatched_frame_inds: obj_id --> [mismatched frame indices]
3845
+ # - overlap_pair_to_frame_inds: (first_appear_obj_id, obj_id) --> [overlap frame indices]
3846
+ # - removed_obj_ids: object IDs that are suppressed via hot-start
3847
+ metadata = {
3848
+ "obj_first_frame_idx": {},
3849
+ "unmatched_frame_inds": defaultdict(list),
3850
+ "trk_keep_alive": defaultdict(int), # This is used only for object suppression not for removal
3851
+ "overlap_pair_to_frame_inds": defaultdict(list),
3852
+ "removed_obj_ids": set(),
3853
+ }
3854
+ if self.masklet_confirmation_enable:
3855
+ # all the following are np.ndarray with the same shape as `obj_ids_all_gpu`
3856
+ metadata["masklet_confirmation"] = {
3857
+ # "status" is the confirmation status of each masklet
3858
+ "status": np.array([], np.int64),
3859
+ # "consecutive_det_num" is the number of consecutive frames where the masklet is
3860
+ # detected by the detector (with a matched detection)
3861
+ "consecutive_det_num": np.array([], np.int64),
3862
+ }
3863
+ tracker_metadata["metadata"] = metadata
3864
+
3865
+ return tracker_metadata
3866
+
3867
+ def update_masklet_confirmation_status(
3868
+ self,
3869
+ metadata: dict[str, Any],
3870
+ obj_ids_all_gpu_prev: np.ndarray,
3871
+ obj_ids_all_gpu_updated: np.ndarray,
3872
+ det_to_matched_trk_obj_ids: dict[int, np.ndarray],
3873
+ new_det_obj_ids: np.ndarray,
3874
+ ):
3875
+ """Update the confirmation status of masklets based on the current frame's detection results."""
3876
+ confirmation_data = metadata["masklet_confirmation"]
3877
+
3878
+ # a) first, expand "confirmation_data" to include new masklets added in this frame
3879
+ status_prev = confirmation_data["status"]
3880
+ consecutive_det_num_prev = confirmation_data["consecutive_det_num"]
3881
+ assert status_prev.shape == obj_ids_all_gpu_prev.shape, (
3882
+ f"Got {status_prev.shape} vs {obj_ids_all_gpu_prev.shape}"
3883
+ )
3884
+
3885
+ obj_id_to_updated_idx = {obj_id: idx for idx, obj_id in enumerate(obj_ids_all_gpu_updated)}
3886
+ prev_elem_is_in_updated = np.isin(obj_ids_all_gpu_prev, obj_ids_all_gpu_updated)
3887
+ prev_elem_obj_ids_in_updated = obj_ids_all_gpu_prev[prev_elem_is_in_updated]
3888
+ prev_elem_inds_in_updated = np.array(
3889
+ [obj_id_to_updated_idx[obj_id] for obj_id in prev_elem_obj_ids_in_updated],
3890
+ dtype=np.int64,
3891
+ )
3892
+ # newly added masklets are initialized to "UNCONFIRMED" status
3893
+ unconfirmed_val = self.UNCONFIRMED
3894
+ status = np.full_like(obj_ids_all_gpu_updated, fill_value=unconfirmed_val)
3895
+ status[prev_elem_inds_in_updated] = status_prev[prev_elem_is_in_updated]
3896
+ consecutive_det_num = np.zeros_like(obj_ids_all_gpu_updated)
3897
+ consecutive_det_num[prev_elem_inds_in_updated] = consecutive_det_num_prev[prev_elem_is_in_updated]
3898
+
3899
+ # b) update the confirmation status of all masklets based on the current frame
3900
+ # b.1) update "consecutive_det_num"
3901
+ # "is_matched": whether a masklet is matched to a detection on this frame
3902
+ is_matched = np.isin(obj_ids_all_gpu_updated, new_det_obj_ids)
3903
+ for matched_trk_obj_ids in det_to_matched_trk_obj_ids.values():
3904
+ is_matched |= np.isin(obj_ids_all_gpu_updated, matched_trk_obj_ids)
3905
+ consecutive_det_num = np.where(is_matched, consecutive_det_num + 1, 0)
3906
+
3907
+ # b.2) update "status"
3908
+ change_to_confirmed = consecutive_det_num >= self.masklet_confirmation_consecutive_det_thresh
3909
+ status[change_to_confirmed] = self.CONFIRMED
3910
+
3911
+ confirmation_data["status"] = status
3912
+ confirmation_data["consecutive_det_num"] = consecutive_det_num
3913
+ return metadata
3914
+
3915
+ def _load_checkpoint(self, ckpt_path: str, strict: bool = True):
3916
+ sd = torch.load(ckpt_path, map_location="cpu", weights_only=True)["model"]
3917
+ missing_keys, unexpected_keys = self.load_state_dict(sd, strict=strict)
3918
+ if len(missing_keys) > 0 or len(unexpected_keys) > 0:
3919
+ LOGGER.warning(f"Loaded ckpt with {missing_keys=}, {unexpected_keys=}")
3920
+ else:
3921
+ LOGGER.info("Loaded ckpt successfully without missing or unexpected keys")
3922
+
3923
+ def _encode_prompt(self, **kwargs):
3924
+ return self.model._encode_prompt(**kwargs)
3925
+
3926
+ @staticmethod
3927
+ def _drop_new_det_with_obj_limit(new_det_fa_inds, det_scores_np, num_to_keep):
3928
+ """Drop a few new detections based on the maximum number of objects. We drop new objects based on their
3929
+ detection scores, keeping the high-scoring ones and dropping the low-scoring ones.
3930
+ """
3931
+ assert 0 <= num_to_keep <= len(new_det_fa_inds)
3932
+ if num_to_keep == 0:
3933
+ return np.array([], np.int64) # keep none
3934
+ if num_to_keep == len(new_det_fa_inds):
3935
+ return new_det_fa_inds # keep all
3936
+
3937
+ # keep the top-scoring detections
3938
+ score_order = np.argsort(det_scores_np[new_det_fa_inds])[::-1]
3939
+ new_det_fa_inds = new_det_fa_inds[score_order[:num_to_keep]]
3940
+ return new_det_fa_inds