dgenerate-ultralytics-headless 8.3.253__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 (299) hide show
  1. dgenerate_ultralytics_headless-8.3.253.dist-info/METADATA +405 -0
  2. dgenerate_ultralytics_headless-8.3.253.dist-info/RECORD +299 -0
  3. dgenerate_ultralytics_headless-8.3.253.dist-info/WHEEL +5 -0
  4. dgenerate_ultralytics_headless-8.3.253.dist-info/entry_points.txt +3 -0
  5. dgenerate_ultralytics_headless-8.3.253.dist-info/licenses/LICENSE +661 -0
  6. dgenerate_ultralytics_headless-8.3.253.dist-info/top_level.txt +1 -0
  7. tests/__init__.py +23 -0
  8. tests/conftest.py +59 -0
  9. tests/test_cli.py +131 -0
  10. tests/test_cuda.py +216 -0
  11. tests/test_engine.py +157 -0
  12. tests/test_exports.py +309 -0
  13. tests/test_integrations.py +151 -0
  14. tests/test_python.py +777 -0
  15. tests/test_solutions.py +371 -0
  16. ultralytics/__init__.py +48 -0
  17. ultralytics/assets/bus.jpg +0 -0
  18. ultralytics/assets/zidane.jpg +0 -0
  19. ultralytics/cfg/__init__.py +1028 -0
  20. ultralytics/cfg/datasets/Argoverse.yaml +78 -0
  21. ultralytics/cfg/datasets/DOTAv1.5.yaml +37 -0
  22. ultralytics/cfg/datasets/DOTAv1.yaml +36 -0
  23. ultralytics/cfg/datasets/GlobalWheat2020.yaml +68 -0
  24. ultralytics/cfg/datasets/HomeObjects-3K.yaml +32 -0
  25. ultralytics/cfg/datasets/ImageNet.yaml +2025 -0
  26. ultralytics/cfg/datasets/Objects365.yaml +447 -0
  27. ultralytics/cfg/datasets/SKU-110K.yaml +58 -0
  28. ultralytics/cfg/datasets/TT100K.yaml +346 -0
  29. ultralytics/cfg/datasets/VOC.yaml +102 -0
  30. ultralytics/cfg/datasets/VisDrone.yaml +87 -0
  31. ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
  32. ultralytics/cfg/datasets/brain-tumor.yaml +22 -0
  33. ultralytics/cfg/datasets/carparts-seg.yaml +44 -0
  34. ultralytics/cfg/datasets/coco-pose.yaml +64 -0
  35. ultralytics/cfg/datasets/coco.yaml +118 -0
  36. ultralytics/cfg/datasets/coco128-seg.yaml +101 -0
  37. ultralytics/cfg/datasets/coco128.yaml +101 -0
  38. ultralytics/cfg/datasets/coco8-grayscale.yaml +103 -0
  39. ultralytics/cfg/datasets/coco8-multispectral.yaml +104 -0
  40. ultralytics/cfg/datasets/coco8-pose.yaml +47 -0
  41. ultralytics/cfg/datasets/coco8-seg.yaml +101 -0
  42. ultralytics/cfg/datasets/coco8.yaml +101 -0
  43. ultralytics/cfg/datasets/construction-ppe.yaml +32 -0
  44. ultralytics/cfg/datasets/crack-seg.yaml +22 -0
  45. ultralytics/cfg/datasets/dog-pose.yaml +52 -0
  46. ultralytics/cfg/datasets/dota8-multispectral.yaml +38 -0
  47. ultralytics/cfg/datasets/dota8.yaml +35 -0
  48. ultralytics/cfg/datasets/hand-keypoints.yaml +50 -0
  49. ultralytics/cfg/datasets/kitti.yaml +27 -0
  50. ultralytics/cfg/datasets/lvis.yaml +1240 -0
  51. ultralytics/cfg/datasets/medical-pills.yaml +21 -0
  52. ultralytics/cfg/datasets/open-images-v7.yaml +663 -0
  53. ultralytics/cfg/datasets/package-seg.yaml +22 -0
  54. ultralytics/cfg/datasets/signature.yaml +21 -0
  55. ultralytics/cfg/datasets/tiger-pose.yaml +41 -0
  56. ultralytics/cfg/datasets/xView.yaml +155 -0
  57. ultralytics/cfg/default.yaml +130 -0
  58. ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +17 -0
  59. ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
  60. ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
  61. ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
  62. ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
  63. ultralytics/cfg/models/11/yolo11.yaml +50 -0
  64. ultralytics/cfg/models/11/yoloe-11-seg.yaml +48 -0
  65. ultralytics/cfg/models/11/yoloe-11.yaml +48 -0
  66. ultralytics/cfg/models/12/yolo12-cls.yaml +32 -0
  67. ultralytics/cfg/models/12/yolo12-obb.yaml +48 -0
  68. ultralytics/cfg/models/12/yolo12-pose.yaml +49 -0
  69. ultralytics/cfg/models/12/yolo12-seg.yaml +48 -0
  70. ultralytics/cfg/models/12/yolo12.yaml +48 -0
  71. ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +53 -0
  72. ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +45 -0
  73. ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +45 -0
  74. ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +57 -0
  75. ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
  76. ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
  77. ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
  78. ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
  79. ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
  80. ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
  81. ultralytics/cfg/models/v3/yolov3-spp.yaml +49 -0
  82. ultralytics/cfg/models/v3/yolov3-tiny.yaml +40 -0
  83. ultralytics/cfg/models/v3/yolov3.yaml +49 -0
  84. ultralytics/cfg/models/v5/yolov5-p6.yaml +62 -0
  85. ultralytics/cfg/models/v5/yolov5.yaml +51 -0
  86. ultralytics/cfg/models/v6/yolov6.yaml +56 -0
  87. ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +48 -0
  88. ultralytics/cfg/models/v8/yoloe-v8.yaml +48 -0
  89. ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +28 -0
  90. ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +28 -0
  91. ultralytics/cfg/models/v8/yolov8-cls.yaml +32 -0
  92. ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +58 -0
  93. ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +60 -0
  94. ultralytics/cfg/models/v8/yolov8-ghost.yaml +50 -0
  95. ultralytics/cfg/models/v8/yolov8-obb.yaml +49 -0
  96. ultralytics/cfg/models/v8/yolov8-p2.yaml +57 -0
  97. ultralytics/cfg/models/v8/yolov8-p6.yaml +59 -0
  98. ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +60 -0
  99. ultralytics/cfg/models/v8/yolov8-pose.yaml +50 -0
  100. ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +49 -0
  101. ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +59 -0
  102. ultralytics/cfg/models/v8/yolov8-seg.yaml +49 -0
  103. ultralytics/cfg/models/v8/yolov8-world.yaml +51 -0
  104. ultralytics/cfg/models/v8/yolov8-worldv2.yaml +49 -0
  105. ultralytics/cfg/models/v8/yolov8.yaml +49 -0
  106. ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
  107. ultralytics/cfg/models/v9/yolov9c.yaml +41 -0
  108. ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
  109. ultralytics/cfg/models/v9/yolov9e.yaml +64 -0
  110. ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
  111. ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
  112. ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
  113. ultralytics/cfg/trackers/botsort.yaml +21 -0
  114. ultralytics/cfg/trackers/bytetrack.yaml +12 -0
  115. ultralytics/data/__init__.py +26 -0
  116. ultralytics/data/annotator.py +66 -0
  117. ultralytics/data/augment.py +2801 -0
  118. ultralytics/data/base.py +435 -0
  119. ultralytics/data/build.py +437 -0
  120. ultralytics/data/converter.py +855 -0
  121. ultralytics/data/dataset.py +834 -0
  122. ultralytics/data/loaders.py +704 -0
  123. ultralytics/data/scripts/download_weights.sh +18 -0
  124. ultralytics/data/scripts/get_coco.sh +61 -0
  125. ultralytics/data/scripts/get_coco128.sh +18 -0
  126. ultralytics/data/scripts/get_imagenet.sh +52 -0
  127. ultralytics/data/split.py +138 -0
  128. ultralytics/data/split_dota.py +344 -0
  129. ultralytics/data/utils.py +798 -0
  130. ultralytics/engine/__init__.py +1 -0
  131. ultralytics/engine/exporter.py +1580 -0
  132. ultralytics/engine/model.py +1125 -0
  133. ultralytics/engine/predictor.py +508 -0
  134. ultralytics/engine/results.py +1522 -0
  135. ultralytics/engine/trainer.py +977 -0
  136. ultralytics/engine/tuner.py +449 -0
  137. ultralytics/engine/validator.py +387 -0
  138. ultralytics/hub/__init__.py +166 -0
  139. ultralytics/hub/auth.py +151 -0
  140. ultralytics/hub/google/__init__.py +174 -0
  141. ultralytics/hub/session.py +422 -0
  142. ultralytics/hub/utils.py +162 -0
  143. ultralytics/models/__init__.py +9 -0
  144. ultralytics/models/fastsam/__init__.py +7 -0
  145. ultralytics/models/fastsam/model.py +79 -0
  146. ultralytics/models/fastsam/predict.py +169 -0
  147. ultralytics/models/fastsam/utils.py +23 -0
  148. ultralytics/models/fastsam/val.py +38 -0
  149. ultralytics/models/nas/__init__.py +7 -0
  150. ultralytics/models/nas/model.py +98 -0
  151. ultralytics/models/nas/predict.py +56 -0
  152. ultralytics/models/nas/val.py +38 -0
  153. ultralytics/models/rtdetr/__init__.py +7 -0
  154. ultralytics/models/rtdetr/model.py +63 -0
  155. ultralytics/models/rtdetr/predict.py +88 -0
  156. ultralytics/models/rtdetr/train.py +89 -0
  157. ultralytics/models/rtdetr/val.py +216 -0
  158. ultralytics/models/sam/__init__.py +25 -0
  159. ultralytics/models/sam/amg.py +275 -0
  160. ultralytics/models/sam/build.py +365 -0
  161. ultralytics/models/sam/build_sam3.py +377 -0
  162. ultralytics/models/sam/model.py +169 -0
  163. ultralytics/models/sam/modules/__init__.py +1 -0
  164. ultralytics/models/sam/modules/blocks.py +1067 -0
  165. ultralytics/models/sam/modules/decoders.py +495 -0
  166. ultralytics/models/sam/modules/encoders.py +794 -0
  167. ultralytics/models/sam/modules/memory_attention.py +298 -0
  168. ultralytics/models/sam/modules/sam.py +1160 -0
  169. ultralytics/models/sam/modules/tiny_encoder.py +979 -0
  170. ultralytics/models/sam/modules/transformer.py +344 -0
  171. ultralytics/models/sam/modules/utils.py +512 -0
  172. ultralytics/models/sam/predict.py +3940 -0
  173. ultralytics/models/sam/sam3/__init__.py +3 -0
  174. ultralytics/models/sam/sam3/decoder.py +546 -0
  175. ultralytics/models/sam/sam3/encoder.py +529 -0
  176. ultralytics/models/sam/sam3/geometry_encoders.py +415 -0
  177. ultralytics/models/sam/sam3/maskformer_segmentation.py +286 -0
  178. ultralytics/models/sam/sam3/model_misc.py +199 -0
  179. ultralytics/models/sam/sam3/necks.py +129 -0
  180. ultralytics/models/sam/sam3/sam3_image.py +339 -0
  181. ultralytics/models/sam/sam3/text_encoder_ve.py +307 -0
  182. ultralytics/models/sam/sam3/vitdet.py +547 -0
  183. ultralytics/models/sam/sam3/vl_combiner.py +160 -0
  184. ultralytics/models/utils/__init__.py +1 -0
  185. ultralytics/models/utils/loss.py +466 -0
  186. ultralytics/models/utils/ops.py +315 -0
  187. ultralytics/models/yolo/__init__.py +7 -0
  188. ultralytics/models/yolo/classify/__init__.py +7 -0
  189. ultralytics/models/yolo/classify/predict.py +90 -0
  190. ultralytics/models/yolo/classify/train.py +202 -0
  191. ultralytics/models/yolo/classify/val.py +216 -0
  192. ultralytics/models/yolo/detect/__init__.py +7 -0
  193. ultralytics/models/yolo/detect/predict.py +122 -0
  194. ultralytics/models/yolo/detect/train.py +227 -0
  195. ultralytics/models/yolo/detect/val.py +507 -0
  196. ultralytics/models/yolo/model.py +430 -0
  197. ultralytics/models/yolo/obb/__init__.py +7 -0
  198. ultralytics/models/yolo/obb/predict.py +56 -0
  199. ultralytics/models/yolo/obb/train.py +79 -0
  200. ultralytics/models/yolo/obb/val.py +302 -0
  201. ultralytics/models/yolo/pose/__init__.py +7 -0
  202. ultralytics/models/yolo/pose/predict.py +65 -0
  203. ultralytics/models/yolo/pose/train.py +110 -0
  204. ultralytics/models/yolo/pose/val.py +248 -0
  205. ultralytics/models/yolo/segment/__init__.py +7 -0
  206. ultralytics/models/yolo/segment/predict.py +109 -0
  207. ultralytics/models/yolo/segment/train.py +69 -0
  208. ultralytics/models/yolo/segment/val.py +307 -0
  209. ultralytics/models/yolo/world/__init__.py +5 -0
  210. ultralytics/models/yolo/world/train.py +173 -0
  211. ultralytics/models/yolo/world/train_world.py +178 -0
  212. ultralytics/models/yolo/yoloe/__init__.py +22 -0
  213. ultralytics/models/yolo/yoloe/predict.py +162 -0
  214. ultralytics/models/yolo/yoloe/train.py +287 -0
  215. ultralytics/models/yolo/yoloe/train_seg.py +122 -0
  216. ultralytics/models/yolo/yoloe/val.py +206 -0
  217. ultralytics/nn/__init__.py +27 -0
  218. ultralytics/nn/autobackend.py +964 -0
  219. ultralytics/nn/modules/__init__.py +182 -0
  220. ultralytics/nn/modules/activation.py +54 -0
  221. ultralytics/nn/modules/block.py +1947 -0
  222. ultralytics/nn/modules/conv.py +669 -0
  223. ultralytics/nn/modules/head.py +1183 -0
  224. ultralytics/nn/modules/transformer.py +793 -0
  225. ultralytics/nn/modules/utils.py +159 -0
  226. ultralytics/nn/tasks.py +1768 -0
  227. ultralytics/nn/text_model.py +356 -0
  228. ultralytics/py.typed +1 -0
  229. ultralytics/solutions/__init__.py +41 -0
  230. ultralytics/solutions/ai_gym.py +108 -0
  231. ultralytics/solutions/analytics.py +264 -0
  232. ultralytics/solutions/config.py +107 -0
  233. ultralytics/solutions/distance_calculation.py +123 -0
  234. ultralytics/solutions/heatmap.py +125 -0
  235. ultralytics/solutions/instance_segmentation.py +86 -0
  236. ultralytics/solutions/object_blurrer.py +89 -0
  237. ultralytics/solutions/object_counter.py +190 -0
  238. ultralytics/solutions/object_cropper.py +87 -0
  239. ultralytics/solutions/parking_management.py +280 -0
  240. ultralytics/solutions/queue_management.py +93 -0
  241. ultralytics/solutions/region_counter.py +133 -0
  242. ultralytics/solutions/security_alarm.py +151 -0
  243. ultralytics/solutions/similarity_search.py +219 -0
  244. ultralytics/solutions/solutions.py +828 -0
  245. ultralytics/solutions/speed_estimation.py +114 -0
  246. ultralytics/solutions/streamlit_inference.py +260 -0
  247. ultralytics/solutions/templates/similarity-search.html +156 -0
  248. ultralytics/solutions/trackzone.py +88 -0
  249. ultralytics/solutions/vision_eye.py +67 -0
  250. ultralytics/trackers/__init__.py +7 -0
  251. ultralytics/trackers/basetrack.py +115 -0
  252. ultralytics/trackers/bot_sort.py +257 -0
  253. ultralytics/trackers/byte_tracker.py +469 -0
  254. ultralytics/trackers/track.py +116 -0
  255. ultralytics/trackers/utils/__init__.py +1 -0
  256. ultralytics/trackers/utils/gmc.py +339 -0
  257. ultralytics/trackers/utils/kalman_filter.py +482 -0
  258. ultralytics/trackers/utils/matching.py +154 -0
  259. ultralytics/utils/__init__.py +1450 -0
  260. ultralytics/utils/autobatch.py +118 -0
  261. ultralytics/utils/autodevice.py +205 -0
  262. ultralytics/utils/benchmarks.py +728 -0
  263. ultralytics/utils/callbacks/__init__.py +5 -0
  264. ultralytics/utils/callbacks/base.py +233 -0
  265. ultralytics/utils/callbacks/clearml.py +146 -0
  266. ultralytics/utils/callbacks/comet.py +625 -0
  267. ultralytics/utils/callbacks/dvc.py +197 -0
  268. ultralytics/utils/callbacks/hub.py +110 -0
  269. ultralytics/utils/callbacks/mlflow.py +134 -0
  270. ultralytics/utils/callbacks/neptune.py +126 -0
  271. ultralytics/utils/callbacks/platform.py +453 -0
  272. ultralytics/utils/callbacks/raytune.py +42 -0
  273. ultralytics/utils/callbacks/tensorboard.py +123 -0
  274. ultralytics/utils/callbacks/wb.py +188 -0
  275. ultralytics/utils/checks.py +1020 -0
  276. ultralytics/utils/cpu.py +85 -0
  277. ultralytics/utils/dist.py +123 -0
  278. ultralytics/utils/downloads.py +529 -0
  279. ultralytics/utils/errors.py +35 -0
  280. ultralytics/utils/events.py +113 -0
  281. ultralytics/utils/export/__init__.py +7 -0
  282. ultralytics/utils/export/engine.py +237 -0
  283. ultralytics/utils/export/imx.py +325 -0
  284. ultralytics/utils/export/tensorflow.py +231 -0
  285. ultralytics/utils/files.py +219 -0
  286. ultralytics/utils/git.py +137 -0
  287. ultralytics/utils/instance.py +484 -0
  288. ultralytics/utils/logger.py +506 -0
  289. ultralytics/utils/loss.py +849 -0
  290. ultralytics/utils/metrics.py +1563 -0
  291. ultralytics/utils/nms.py +337 -0
  292. ultralytics/utils/ops.py +664 -0
  293. ultralytics/utils/patches.py +201 -0
  294. ultralytics/utils/plotting.py +1047 -0
  295. ultralytics/utils/tal.py +404 -0
  296. ultralytics/utils/torch_utils.py +984 -0
  297. ultralytics/utils/tqdm.py +443 -0
  298. ultralytics/utils/triton.py +112 -0
  299. ultralytics/utils/tuner.py +168 -0
@@ -0,0 +1,3940 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+ """
3
+ Generate predictions using the Segment Anything Model (SAM).
4
+
5
+ SAM is an advanced image segmentation model offering features like promptable segmentation and zero-shot performance.
6
+ This module contains the implementation of the prediction logic and auxiliary utilities required to perform segmentation
7
+ using SAM. It forms an integral part of the Ultralytics framework and is designed for high-performance, real-time image
8
+ segmentation tasks.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from collections import OrderedDict, defaultdict
14
+ from copy import deepcopy
15
+ from typing import Any
16
+
17
+ import cv2
18
+ import numpy as np
19
+ import torch
20
+ import torch.nn.functional as F
21
+
22
+ from ultralytics.data.augment import LetterBox
23
+ from ultralytics.engine.predictor import BasePredictor
24
+ from ultralytics.engine.results import Results
25
+ from ultralytics.utils import DEFAULT_CFG, LOGGER, ops
26
+ from ultralytics.utils.metrics import box_iou, mask_iou
27
+ from ultralytics.utils.torch_utils import select_device, smart_inference_mode
28
+
29
+ from .amg import (
30
+ batch_iterator,
31
+ batched_mask_to_box,
32
+ build_all_layer_point_grids,
33
+ calculate_stability_score,
34
+ generate_crop_boxes,
35
+ is_box_near_crop_edge,
36
+ remove_small_regions,
37
+ uncrop_boxes_xyxy,
38
+ uncrop_masks,
39
+ )
40
+ from .sam3.geometry_encoders import Prompt
41
+
42
+
43
+ class Predictor(BasePredictor):
44
+ """Predictor class for SAM, enabling real-time image segmentation with promptable capabilities.
45
+
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.
49
+
50
+ Attributes:
51
+ args (SimpleNamespace): Configuration arguments for the predictor.
52
+ model (torch.nn.Module): The loaded SAM model.
53
+ device (torch.device): The device (CPU or GPU) on which the model is loaded.
54
+ im (torch.Tensor): The preprocessed input image.
55
+ features (torch.Tensor): Extracted image features.
56
+ prompts (dict[str, Any]): Dictionary to store various types of prompts (e.g., bboxes, points, masks).
57
+ segment_all (bool): Flag to indicate if full image segmentation should be performed.
58
+ mean (torch.Tensor): Mean values for image normalization.
59
+ std (torch.Tensor): Standard deviation values for image normalization.
60
+
61
+ Methods:
62
+ preprocess: Prepare input images for model inference.
63
+ pre_transform: Perform initial transformations on the input image.
64
+ inference: Perform segmentation inference based on input prompts.
65
+ prompt_inference: Internal function for prompt-based segmentation inference.
66
+ generate: Generate segmentation masks for an entire image.
67
+ setup_model: Initialize the SAM model for inference.
68
+ get_model: Build and return a SAM model.
69
+ postprocess: Post-process model outputs to generate final results.
70
+ setup_source: Set up the data source for inference.
71
+ set_image: Set and preprocess a single image for inference.
72
+ get_im_features: Extract image features using the SAM image encoder.
73
+ set_prompts: Set prompts for subsequent inference.
74
+ reset_image: Reset the current image and its features.
75
+ remove_small_regions: Remove small disconnected regions and holes from masks.
76
+
77
+ Examples:
78
+ >>> predictor = Predictor()
79
+ >>> predictor.setup_model(model_path="sam_model.pt")
80
+ >>> predictor.set_image("image.jpg")
81
+ >>> bboxes = [[100, 100, 200, 200]]
82
+ >>> results = predictor(bboxes=bboxes)
83
+ """
84
+
85
+ stride = 16
86
+
87
+ def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):
88
+ """Initialize the Predictor with configuration, overrides, and callbacks.
89
+
90
+ Sets up the Predictor object for SAM (Segment Anything Model) and applies any configuration overrides or
91
+ callbacks provided. Initializes task-specific settings for SAM, such as retina_masks being set to True for
92
+ optimal results.
93
+
94
+ Args:
95
+ cfg (dict): Configuration dictionary containing default settings.
96
+ overrides (dict | None): Dictionary of values to override default configuration.
97
+ _callbacks (dict | None): Dictionary of callback functions to customize behavior.
98
+ """
99
+ if overrides is None:
100
+ overrides = {}
101
+ overrides.update(dict(task="segment", mode="predict", batch=1))
102
+ super().__init__(cfg, overrides, _callbacks)
103
+ self.args.retina_masks = True
104
+ self.im = None
105
+ self.features = None
106
+ self.prompts = {}
107
+ self.segment_all = False
108
+
109
+ def preprocess(self, im):
110
+ """Preprocess the input image for model inference.
111
+
112
+ This method prepares the input image by applying transformations and normalization. It supports both
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.
115
+
116
+ Args:
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.
119
+
120
+ Returns:
121
+ (torch.Tensor): The preprocessed image tensor, normalized and converted to the appropriate dtype.
122
+
123
+ Examples:
124
+ >>> predictor = Predictor()
125
+ >>> image = torch.rand(1, 3, 640, 640)
126
+ >>> preprocessed_image = predictor.preprocess(image)
127
+ """
128
+ if self.im is not None:
129
+ return self.im
130
+ not_tensor = not isinstance(im, torch.Tensor)
131
+ if not_tensor:
132
+ im = np.stack(self.pre_transform(im))
133
+ im = im[..., ::-1].transpose((0, 3, 1, 2))
134
+ im = np.ascontiguousarray(im)
135
+ im = torch.from_numpy(im)
136
+
137
+ im = im.to(self.device)
138
+ if not_tensor:
139
+ im = (im - self.mean) / self.std
140
+ im = im.half() if self.model.fp16 else im.float()
141
+ return im
142
+
143
+ def pre_transform(self, im):
144
+ """Perform initial transformations on the input image for preprocessing.
145
+
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.
148
+
149
+ Args:
150
+ im (list[np.ndarray]): List containing a single image in HWC numpy array format.
151
+
152
+ Returns:
153
+ (list[np.ndarray]): List containing the transformed image.
154
+
155
+ Raises:
156
+ AssertionError: If the input list contains more than one image.
157
+
158
+ Examples:
159
+ >>> predictor = Predictor()
160
+ >>> image = np.random.rand(480, 640, 3) # Single HWC image
161
+ >>> transformed = predictor.pre_transform([image])
162
+ >>> print(len(transformed))
163
+ 1
164
+ """
165
+ assert len(im) == 1, "SAM model does not currently support batched inference"
166
+ letterbox = LetterBox(self.imgsz, auto=False, center=False)
167
+ return [letterbox(image=x) for x in im]
168
+
169
+ def inference(self, im, bboxes=None, points=None, labels=None, masks=None, multimask_output=False, *args, **kwargs):
170
+ """Perform image segmentation inference based on the given input cues, using the currently loaded image.
171
+
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.
174
+
175
+ Args:
176
+ im (torch.Tensor): The preprocessed input image in tensor format, with shape (N, C, H, W).
177
+ bboxes (np.ndarray | list | None): Bounding boxes with shape (N, 4), in XYXY format.
178
+ points (np.ndarray | list | None): Points indicating object locations with shape (N, 2), in pixels.
179
+ labels (np.ndarray | list | None): Labels for point prompts, shape (N,). 1 = foreground, 0 = background.
180
+ masks (np.ndarray | None): Low-resolution masks from previous predictions, shape (N, H, W). For SAM H=W=256.
181
+ multimask_output (bool): Flag to return multiple masks. Helpful for ambiguous prompts.
182
+ *args (Any): Additional positional arguments.
183
+ **kwargs (Any): Additional keyword arguments.
184
+
185
+ Returns:
186
+ pred_masks (torch.Tensor): The output masks in shape (C, H, W), where C is the number of generated masks.
187
+ pred_scores (torch.Tensor): An array of length C containing quality scores predicted by the model for each
188
+ mask.
189
+
190
+ Examples:
191
+ >>> predictor = Predictor()
192
+ >>> predictor.setup_model(model_path="sam_model.pt")
193
+ >>> predictor.set_image("image.jpg")
194
+ >>> results = predictor(bboxes=[[0, 0, 100, 100]])
195
+ """
196
+ # Override prompts if any stored in self.prompts
197
+ bboxes = self.prompts.pop("bboxes", bboxes)
198
+ points = self.prompts.pop("points", points)
199
+ masks = self.prompts.pop("masks", masks)
200
+ labels = self.prompts.pop("labels", labels)
201
+
202
+ if all(i is None for i in [bboxes, points, masks]):
203
+ return self.generate(im, *args, **kwargs)
204
+
205
+ return self.prompt_inference(im, bboxes, points, labels, masks, multimask_output)
206
+
207
+ def prompt_inference(self, im, bboxes=None, points=None, labels=None, masks=None, multimask_output=False):
208
+ """Perform image segmentation inference based on input cues using SAM's specialized architecture.
209
+
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.
212
+
213
+ Args:
214
+ im (torch.Tensor): Preprocessed input image tensor with shape (N, C, H, W).
215
+ bboxes (np.ndarray | list | None): Bounding boxes in XYXY format with shape (N, 4).
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.
220
+ masks (np.ndarray | None): Low-res masks from previous predictions with shape (N, H, W). For SAM, H=W=256.
221
+ multimask_output (bool): Flag to return multiple masks for ambiguous prompts.
222
+
223
+ Returns:
224
+ pred_masks (torch.Tensor): Output masks with shape (C, H, W), where C is the number of generated masks.
225
+ pred_scores (torch.Tensor): Quality scores predicted by the model for each mask, with length C.
226
+
227
+ Examples:
228
+ >>> predictor = Predictor()
229
+ >>> im = torch.rand(1, 3, 1024, 1024)
230
+ >>> bboxes = [[100, 100, 200, 200]]
231
+ >>> masks, scores, logits = predictor.prompt_inference(im, bboxes=bboxes)
232
+ """
233
+ features = self.get_im_features(im) if self.features is None else self.features
234
+
235
+ prompts = self._prepare_prompts(im.shape[2:], self.batch[1][0].shape[:2], bboxes, points, labels, masks)
236
+ return self._inference_features(features, *prompts, multimask_output)
237
+
238
+ def _inference_features(
239
+ self,
240
+ features,
241
+ bboxes=None,
242
+ points=None,
243
+ labels=None,
244
+ masks=None,
245
+ multimask_output=False,
246
+ ):
247
+ """Perform inference on image features using the SAM model.
248
+
249
+ Args:
250
+ features (torch.Tensor): Extracted image features with shape (B, C, H, W) from the SAM model image encoder.
251
+ bboxes (np.ndarray | list[list[float]] | None): Bounding boxes in XYXY format with shape (N, 4).
252
+ points (np.ndarray | list[list[float]] | None): Object location points with shape (N, 2), in pixels.
253
+ labels (np.ndarray | list[int] | None): Point prompt labels with shape (N,). 1 = foreground, 0 = background.
254
+ masks (list[np.ndarray] | np.ndarray | None): Masks for the objects, where each mask is a 2D array.
255
+ multimask_output (bool): Flag to return multiple masks for ambiguous prompts.
256
+
257
+ Returns:
258
+ pred_masks (torch.Tensor): Output masks with shape (C, H, W), where C is the number of generated masks.
259
+ pred_scores (torch.Tensor): Quality scores for each mask, with length C.
260
+ """
261
+ points = (points, labels) if points is not None else None
262
+ # Embed prompts
263
+ sparse_embeddings, dense_embeddings = self.model.prompt_encoder(points=points, boxes=bboxes, masks=masks)
264
+
265
+ # Predict masks
266
+ pred_masks, pred_scores = self.model.mask_decoder(
267
+ image_embeddings=features,
268
+ image_pe=self.model.prompt_encoder.get_dense_pe(),
269
+ sparse_prompt_embeddings=sparse_embeddings,
270
+ dense_prompt_embeddings=dense_embeddings,
271
+ multimask_output=multimask_output,
272
+ )
273
+
274
+ # (N, d, H, W) --> (N*d, H, W), (N, d) --> (N*d, )
275
+ # `d` could be 1 or 3 depends on `multimask_output`.
276
+ return pred_masks.flatten(0, 1), pred_scores.flatten(0, 1)
277
+
278
+ def _prepare_prompts(self, dst_shape, src_shape, bboxes=None, points=None, labels=None, masks=None):
279
+ """Prepare and transform the input prompts for processing based on the destination shape.
280
+
281
+ Args:
282
+ dst_shape (tuple[int, int]): The target shape (height, width) for the prompts.
283
+ src_shape (tuple[int, int]): The source shape (height, width) of the input image.
284
+ bboxes (np.ndarray | list | None): Bounding boxes in XYXY format with shape (N, 4).
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
+
292
+ Returns:
293
+ bboxes (torch.Tensor | None): Transformed bounding boxes.
294
+ points (torch.Tensor | None): Transformed points.
295
+ labels (torch.Tensor | None): Transformed labels.
296
+ masks (torch.Tensor | None): Transformed masks.
297
+
298
+ Raises:
299
+ AssertionError: If the number of points don't match the number of labels, in case labels were passed.
300
+ """
301
+ r = 1.0 if self.segment_all else min(dst_shape[0] / src_shape[0], dst_shape[1] / src_shape[1])
302
+ # Transform input prompts
303
+ if points is not None:
304
+ points = torch.as_tensor(points, dtype=self.torch_dtype, device=self.device)
305
+ points = points[None] if points.ndim == 1 else points
306
+ # Assuming labels are all positive if users don't pass labels.
307
+ if labels is None:
308
+ labels = np.ones(points.shape[:-1])
309
+ labels = torch.as_tensor(labels, dtype=torch.int32, device=self.device)
310
+ assert points.shape[-2] == labels.shape[-1], (
311
+ f"Number of points {points.shape[-2]} should match number of labels {labels.shape[-1]}."
312
+ )
313
+ points *= r
314
+ if points.ndim == 2:
315
+ # (N, 2) --> (N, 1, 2), (N, ) --> (N, 1)
316
+ points, labels = points[:, None, :], labels[:, None]
317
+ if bboxes is not None:
318
+ bboxes = torch.as_tensor(bboxes, dtype=self.torch_dtype, device=self.device)
319
+ bboxes = bboxes[None] if bboxes.ndim == 1 else bboxes
320
+ bboxes *= r
321
+ if masks is not None:
322
+ masks = np.asarray(masks, dtype=np.uint8)
323
+ masks = masks[None] if masks.ndim == 2 else masks
324
+ letterbox = LetterBox(dst_shape, auto=False, center=False, padding_value=0, interpolation=cv2.INTER_NEAREST)
325
+ masks = np.stack([letterbox(image=x).squeeze() for x in masks], axis=0)
326
+ masks = torch.tensor(masks, dtype=self.torch_dtype, device=self.device)
327
+ return bboxes, points, labels, masks
328
+
329
+ def generate(
330
+ self,
331
+ im,
332
+ crop_n_layers=0,
333
+ crop_overlap_ratio=512 / 1500,
334
+ crop_downscale_factor=1,
335
+ point_grids=None,
336
+ points_stride=32,
337
+ points_batch_size=64,
338
+ conf_thres=0.88,
339
+ stability_score_thresh=0.95,
340
+ stability_score_offset=0.95,
341
+ crop_nms_thresh=0.7,
342
+ ):
343
+ """Perform image segmentation using the Segment Anything Model (SAM).
344
+
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.
347
+
348
+ Args:
349
+ im (torch.Tensor): Input tensor representing the preprocessed image with shape (N, C, H, W).
350
+ crop_n_layers (int): Number of layers for additional mask predictions on image crops.
351
+ crop_overlap_ratio (float): Overlap between crops, scaled down in subsequent layers.
352
+ crop_downscale_factor (int): Scaling factor for sampled points-per-side in each layer.
353
+ point_grids (list[np.ndarray] | None): Custom grids for point sampling normalized to [0,1].
354
+ points_stride (int): Number of points to sample along each side of the image.
355
+ points_batch_size (int): Batch size for the number of points processed simultaneously.
356
+ conf_thres (float): Confidence threshold [0,1] for filtering based on mask quality prediction.
357
+ stability_score_thresh (float): Stability threshold [0,1] for mask filtering based on stability.
358
+ stability_score_offset (float): Offset value for calculating stability score.
359
+ crop_nms_thresh (float): IoU cutoff for NMS to remove duplicate masks between crops.
360
+
361
+ Returns:
362
+ pred_masks (torch.Tensor): Segmented masks with shape (N, H, W).
363
+ pred_scores (torch.Tensor): Confidence scores for each mask with shape (N,).
364
+ pred_bboxes (torch.Tensor): Bounding boxes for each mask with shape (N, 4).
365
+
366
+ Examples:
367
+ >>> predictor = Predictor()
368
+ >>> im = torch.rand(1, 3, 1024, 1024) # Example input image
369
+ >>> masks, scores, boxes = predictor.generate(im)
370
+ """
371
+ import torchvision # scope for faster 'import ultralytics'
372
+
373
+ self.segment_all = True
374
+ ih, iw = im.shape[2:]
375
+ crop_regions, layer_idxs = generate_crop_boxes((ih, iw), crop_n_layers, crop_overlap_ratio)
376
+ if point_grids is None:
377
+ point_grids = build_all_layer_point_grids(points_stride, crop_n_layers, crop_downscale_factor)
378
+ pred_masks, pred_scores, pred_bboxes, region_areas = [], [], [], []
379
+ for crop_region, layer_idx in zip(crop_regions, layer_idxs):
380
+ x1, y1, x2, y2 = crop_region
381
+ w, h = x2 - x1, y2 - y1
382
+ area = torch.tensor(w * h, device=im.device)
383
+ points_scale = np.array([[w, h]]) # w, h
384
+ # Crop image and interpolate to input size
385
+ crop_im = F.interpolate(im[..., y1:y2, x1:x2], (ih, iw), mode="bilinear", align_corners=False)
386
+ # (num_points, 2)
387
+ points_for_image = point_grids[layer_idx] * points_scale
388
+ crop_masks, crop_scores, crop_bboxes = [], [], []
389
+ for (points,) in batch_iterator(points_batch_size, points_for_image):
390
+ pred_mask, pred_score = self.prompt_inference(crop_im, points=points, multimask_output=True)
391
+ # Interpolate predicted masks to input size
392
+ pred_mask = F.interpolate(pred_mask[None], (h, w), mode="bilinear", align_corners=False)[0]
393
+ idx = pred_score > conf_thres
394
+ pred_mask, pred_score = pred_mask[idx], pred_score[idx]
395
+
396
+ stability_score = calculate_stability_score(
397
+ pred_mask, self.model.mask_threshold, stability_score_offset
398
+ )
399
+ idx = stability_score > stability_score_thresh
400
+ pred_mask, pred_score = pred_mask[idx], pred_score[idx]
401
+ # Bool type is much more memory-efficient.
402
+ pred_mask = pred_mask > self.model.mask_threshold
403
+ # (N, 4)
404
+ pred_bbox = batched_mask_to_box(pred_mask).float()
405
+ keep_mask = ~is_box_near_crop_edge(pred_bbox, crop_region, [0, 0, iw, ih])
406
+ if not torch.all(keep_mask):
407
+ pred_bbox, pred_mask, pred_score = pred_bbox[keep_mask], pred_mask[keep_mask], pred_score[keep_mask]
408
+
409
+ crop_masks.append(pred_mask)
410
+ crop_bboxes.append(pred_bbox)
411
+ crop_scores.append(pred_score)
412
+
413
+ # Do nms within this crop
414
+ crop_masks = torch.cat(crop_masks)
415
+ crop_bboxes = torch.cat(crop_bboxes)
416
+ crop_scores = torch.cat(crop_scores)
417
+ keep = torchvision.ops.nms(crop_bboxes, crop_scores, self.args.iou) # NMS
418
+ crop_bboxes = uncrop_boxes_xyxy(crop_bboxes[keep], crop_region)
419
+ crop_masks = uncrop_masks(crop_masks[keep], crop_region, ih, iw)
420
+ crop_scores = crop_scores[keep]
421
+
422
+ pred_masks.append(crop_masks)
423
+ pred_bboxes.append(crop_bboxes)
424
+ pred_scores.append(crop_scores)
425
+ region_areas.append(area.expand(crop_masks.shape[0]))
426
+
427
+ pred_masks = torch.cat(pred_masks)
428
+ pred_bboxes = torch.cat(pred_bboxes)
429
+ pred_scores = torch.cat(pred_scores)
430
+ region_areas = torch.cat(region_areas)
431
+
432
+ # Remove duplicate masks between crops
433
+ if len(crop_regions) > 1:
434
+ scores = 1 / region_areas
435
+ keep = torchvision.ops.nms(pred_bboxes, scores, crop_nms_thresh)
436
+ pred_masks, pred_bboxes, pred_scores = pred_masks[keep], pred_bboxes[keep], pred_scores[keep]
437
+
438
+ return pred_masks, pred_scores, pred_bboxes
439
+
440
+ def setup_model(self, model=None, verbose=True):
441
+ """Initialize the Segment Anything Model (SAM) for inference.
442
+
443
+ This method sets up the SAM model by allocating it to the appropriate device and initializing the necessary
444
+ parameters for image normalization and other Ultralytics compatibility settings.
445
+
446
+ Args:
447
+ model (torch.nn.Module | None): A pretrained SAM model. If None, a new model is built based on config.
448
+ verbose (bool): If True, prints selected device information.
449
+
450
+ Examples:
451
+ >>> predictor = Predictor()
452
+ >>> predictor.setup_model(model=sam_model, verbose=True)
453
+ """
454
+ device = select_device(self.args.device, verbose=verbose)
455
+ if model is None:
456
+ model = self.get_model()
457
+ model.eval()
458
+ model = model.to(device)
459
+ self.model = model.half() if self.args.half else model.float()
460
+ self.device = device
461
+ self.mean = torch.tensor([123.675, 116.28, 103.53]).view(-1, 1, 1).to(device)
462
+ self.std = torch.tensor([58.395, 57.12, 57.375]).view(-1, 1, 1).to(device)
463
+
464
+ # Ultralytics compatibility settings
465
+ self.model.pt = False
466
+ self.model.triton = False
467
+ self.model.stride = 32
468
+ self.model.fp16 = self.args.half
469
+ self.done_warmup = True
470
+ self.torch_dtype = torch.float16 if self.model.fp16 else torch.float32
471
+
472
+ def get_model(self):
473
+ """Retrieve or build the Segment Anything Model (SAM) for image segmentation tasks."""
474
+ from .build import build_sam # slow import
475
+
476
+ return build_sam(self.args.model)
477
+
478
+ def postprocess(self, preds, img, orig_imgs):
479
+ """Post-process SAM's inference outputs to generate object detection masks and bounding boxes.
480
+
481
+ This method scales masks and boxes to the original image size and applies a threshold to the mask
482
+ predictions. It leverages SAM's advanced architecture for real-time, promptable segmentation tasks.
483
+
484
+ Args:
485
+ preds (tuple): The output from SAM model inference, containing:
486
+ - pred_masks (torch.Tensor): Predicted masks with shape (N, 1, H, W).
487
+ - pred_scores (torch.Tensor): Confidence scores for each mask with shape (N, 1).
488
+ - pred_bboxes (torch.Tensor, optional): Predicted bounding boxes if segment_all is True.
489
+ img (torch.Tensor): The processed input image tensor with shape (C, H, W).
490
+ orig_imgs (list[np.ndarray] | torch.Tensor): The original, unprocessed images.
491
+
492
+ Returns:
493
+ (list[Results]): List of Results objects containing detection masks, bounding boxes, and other metadata for
494
+ each processed image.
495
+
496
+ Examples:
497
+ >>> predictor = Predictor()
498
+ >>> preds = predictor.inference(img)
499
+ >>> results = predictor.postprocess(preds, img, orig_imgs)
500
+ """
501
+ # (N, 1, H, W), (N, 1)
502
+ pred_masks, pred_scores = preds[:2]
503
+ pred_bboxes = preds[2] if self.segment_all else None
504
+ names = dict(enumerate(str(i) for i in range(pred_masks.shape[0])))
505
+
506
+ if not isinstance(orig_imgs, list): # input images are a torch.Tensor, not a list
507
+ orig_imgs = ops.convert_torch2numpy_batch(orig_imgs)[..., ::-1]
508
+
509
+ results = []
510
+ for masks, orig_img, img_path in zip([pred_masks], orig_imgs, self.batch[0]):
511
+ if masks.shape[0] == 0:
512
+ masks, pred_bboxes = None, torch.zeros((0, 6), device=pred_masks.device)
513
+ else:
514
+ masks = ops.scale_masks(masks[None].float(), orig_img.shape[:2], padding=False)[0]
515
+ masks = masks > self.model.mask_threshold # to bool
516
+ if pred_bboxes is not None:
517
+ pred_bboxes = ops.scale_boxes(img.shape[2:], pred_bboxes.float(), orig_img.shape, padding=False)
518
+ else:
519
+ pred_bboxes = batched_mask_to_box(masks)
520
+ # NOTE: SAM models do not return cls info. This `cls` here is just a placeholder for consistency.
521
+ cls = torch.arange(pred_masks.shape[0], dtype=torch.int32, device=pred_masks.device)
522
+ idx = pred_scores > self.args.conf
523
+ pred_bboxes = torch.cat([pred_bboxes, pred_scores[:, None], cls[:, None]], dim=-1)[idx]
524
+ masks = masks[idx]
525
+ results.append(Results(orig_img, path=img_path, names=names, masks=masks, boxes=pred_bboxes))
526
+ # Reset segment-all mode.
527
+ self.segment_all = False
528
+ return results
529
+
530
+ def set_image(self, image):
531
+ """Preprocess and set a single image for inference.
532
+
533
+ This method prepares the model for inference on a single image by setting up the model if not already
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.
536
+
537
+ Args:
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.
543
+
544
+ Examples:
545
+ >>> predictor = Predictor()
546
+ >>> predictor.set_image("path/to/image.jpg")
547
+ >>> predictor.set_image(cv2.imread("path/to/image.jpg"))
548
+
549
+ Notes:
550
+ - This method should be called before performing inference on a new image.
551
+ - The extracted features are stored in the `self.features` attribute for later use.
552
+ """
553
+ if self.model is None:
554
+ self.setup_model()
555
+ self.setup_source(image)
556
+ assert len(self.dataset) == 1, "`set_image` only supports setting one image!"
557
+ for batch in self.dataset:
558
+ im = self.preprocess(batch[1])
559
+ self.features = self.get_im_features(im)
560
+ break
561
+
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)
567
+ assert isinstance(self.imgsz, (tuple, list)) and self.imgsz[0] == self.imgsz[1], (
568
+ f"SAM models only support square image size, but got {self.imgsz}."
569
+ )
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."""
574
+ return self.model.image_encoder(im)
575
+
576
+ def set_prompts(self, prompts):
577
+ """Set prompts for subsequent inference operations."""
578
+ self.prompts = prompts
579
+
580
+ def reset_image(self):
581
+ """Reset the current image and its features, clearing them for subsequent inference."""
582
+ self.im = None
583
+ self.features = None
584
+
585
+ @staticmethod
586
+ def remove_small_regions(masks, min_area=0, nms_thresh=0.7):
587
+ """Remove small disconnected regions and holes from segmentation masks.
588
+
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.
592
+
593
+ Args:
594
+ masks (torch.Tensor): Segmentation masks to be processed, with shape (N, H, W) where N is the number of
595
+ masks, H is height, and W is width.
596
+ min_area (int): Minimum area threshold for removing disconnected regions and holes. Regions smaller than
597
+ this will be removed.
598
+ nms_thresh (float): IoU threshold for the NMS algorithm to remove duplicate boxes.
599
+
600
+ Returns:
601
+ new_masks (torch.Tensor): Processed masks with small regions removed, shape (N, H, W).
602
+ keep (list[int]): Indices of remaining masks after NMS, for filtering corresponding boxes.
603
+
604
+ Examples:
605
+ >>> masks = torch.rand(5, 640, 640) > 0.5 # 5 random binary masks
606
+ >>> new_masks, keep = remove_small_regions(masks, min_area=100, nms_thresh=0.7)
607
+ >>> print(f"Original masks: {masks.shape}, Processed masks: {new_masks.shape}")
608
+ >>> print(f"Indices of kept masks: {keep}")
609
+ """
610
+ import torchvision # scope for faster 'import ultralytics'
611
+
612
+ if masks.shape[0] == 0:
613
+ return masks
614
+
615
+ # Filter small disconnected regions and holes
616
+ new_masks = []
617
+ scores = []
618
+ for mask in masks:
619
+ mask = mask.cpu().numpy().astype(np.uint8)
620
+ mask, changed = remove_small_regions(mask, min_area, mode="holes")
621
+ unchanged = not changed
622
+ mask, changed = remove_small_regions(mask, min_area, mode="islands")
623
+ unchanged = unchanged and not changed
624
+
625
+ new_masks.append(torch.as_tensor(mask).unsqueeze(0))
626
+ # Give score=0 to changed masks and 1 to unchanged masks so NMS prefers masks not needing postprocessing
627
+ scores.append(float(unchanged))
628
+
629
+ # Recalculate boxes and remove any new duplicates
630
+ new_masks = torch.cat(new_masks, dim=0)
631
+ boxes = batched_mask_to_box(new_masks)
632
+ keep = torchvision.ops.nms(boxes.float(), torch.as_tensor(scores), nms_thresh)
633
+
634
+ return new_masks[keep].to(device=masks.device, dtype=masks.dtype), keep
635
+
636
+ @smart_inference_mode()
637
+ def inference_features(
638
+ self,
639
+ features,
640
+ src_shape,
641
+ dst_shape=None,
642
+ bboxes=None,
643
+ points=None,
644
+ labels=None,
645
+ masks=None,
646
+ multimask_output=False,
647
+ ):
648
+ """Perform prompts preprocessing and inference on provided image features using the SAM model.
649
+
650
+ Args:
651
+ features (torch.Tensor | dict[str, Any]): Extracted image features from the SAM/SAM2 model image encoder.
652
+ src_shape (tuple[int, int]): The source shape (height, width) of the input image.
653
+ dst_shape (tuple[int, int] | None): The target shape (height, width) for the prompts. If None, defaults to
654
+ (imgsz, imgsz).
655
+ bboxes (np.ndarray | list[list[float]] | None): Bounding boxes in xyxy format with shape (N, 4).
656
+ points (np.ndarray | list[list[float]] | None): Points indicating object locations with shape (N, 2), in
657
+ pixels.
658
+ labels (np.ndarray | list[int] | None): Point prompt labels with shape (N, ).
659
+ masks (list[np.ndarray] | np.ndarray | None): Masks for the objects, where each mask is a 2D array.
660
+ multimask_output (bool): Flag to return multiple masks for ambiguous prompts.
661
+
662
+ Returns:
663
+ pred_masks (torch.Tensor): The output masks in shape (C, H, W), where C is the number of generated masks.
664
+ pred_bboxes (torch.Tensor): Bounding boxes for each mask with shape (N, 6), where N is the number of boxes.
665
+ Each box is in xyxy format with additional columns for score and class.
666
+
667
+ Notes:
668
+ - 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.
669
+ """
670
+ dst_shape = dst_shape or (self.args.imgsz, self.args.imgsz)
671
+ prompts = self._prepare_prompts(dst_shape, src_shape, bboxes, points, labels, masks)
672
+ pred_masks, pred_scores = self._inference_features(features, *prompts, multimask_output)
673
+ if pred_masks.shape[0] == 0:
674
+ pred_masks, pred_bboxes = None, torch.zeros((0, 6), device=pred_masks.device)
675
+ else:
676
+ pred_masks = ops.scale_masks(pred_masks[None].float(), src_shape, padding=False)[0]
677
+ pred_masks = pred_masks > self.model.mask_threshold # to bool
678
+ pred_bboxes = batched_mask_to_box(pred_masks)
679
+ # NOTE: SAM models do not return cls info. This `cls` here is just a placeholder for consistency.
680
+ cls = torch.arange(pred_masks.shape[0], dtype=torch.int32, device=pred_masks.device)
681
+ pred_bboxes = torch.cat([pred_bboxes, pred_scores[:, None], cls[:, None]], dim=-1)
682
+ return pred_masks, pred_bboxes
683
+
684
+
685
+ class SAM2Predictor(Predictor):
686
+ """SAM2Predictor class for advanced image segmentation using Segment Anything Model 2 architecture.
687
+
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.
690
+
691
+ Attributes:
692
+ _bb_feat_sizes (list[tuple]): Feature sizes for different backbone levels.
693
+ model (torch.nn.Module): The loaded SAM2 model.
694
+ device (torch.device): The device (CPU or GPU) on which the model is loaded.
695
+ features (dict): Cached image features for efficient inference.
696
+ segment_all (bool): Flag to indicate if all segments should be predicted.
697
+ prompts (dict[str, Any]): Dictionary to store various types of prompts for inference.
698
+
699
+ Methods:
700
+ get_model: Retrieve and initialize the SAM2 model.
701
+ prompt_inference: Perform image segmentation inference based on various prompts.
702
+ set_image: Preprocess and set a single image for inference.
703
+ get_im_features: Extract and process image features using SAM2's image encoder.
704
+
705
+ Examples:
706
+ >>> predictor = SAM2Predictor(cfg)
707
+ >>> predictor.set_image("path/to/image.jpg")
708
+ >>> bboxes = [[100, 100, 200, 200]]
709
+ >>> result = predictor(bboxes=bboxes)[0]
710
+ >>> print(f"Predicted {len(result.masks)} masks with average score {result.boxes.conf.mean():.2f}")
711
+ """
712
+
713
+ _bb_feat_sizes = [
714
+ (256, 256),
715
+ (128, 128),
716
+ (64, 64),
717
+ ]
718
+ stride = 16
719
+
720
+ def get_model(self):
721
+ """Retrieve and initialize the Segment Anything Model 2 (SAM2) for image segmentation tasks."""
722
+ from .build import build_sam # slow import
723
+
724
+ return build_sam(self.args.model)
725
+
726
+ def _prepare_prompts(self, dst_shape, src_shape, bboxes=None, points=None, labels=None, masks=None):
727
+ """Prepare and transform the input prompts for processing based on the destination shape.
728
+
729
+ Args:
730
+ dst_shape (tuple[int, int]): The target shape (height, width) for the prompts.
731
+ src_shape (tuple[int, int]): The source shape (height, width) of the input image.
732
+ bboxes (np.ndarray | list | None): Bounding boxes in XYXY format with shape (N, 4).
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.
737
+ masks (list | np.ndarray | None): Masks for the objects, where each mask is a 2D array.
738
+
739
+ Returns:
740
+ points (torch.Tensor | None): Transformed points.
741
+ labels (torch.Tensor | None): Transformed labels.
742
+ masks (torch.Tensor | None): Transformed masks.
743
+
744
+ Raises:
745
+ AssertionError: If the number of points don't match the number of labels, in case labels were passed.
746
+ """
747
+ bboxes, points, labels, masks = super()._prepare_prompts(dst_shape, src_shape, bboxes, points, labels, masks)
748
+ if bboxes is not None:
749
+ bboxes = bboxes.view(-1, 2, 2)
750
+ bbox_labels = torch.tensor([[2, 3]], dtype=torch.int32, device=bboxes.device).expand(bboxes.shape[0], -1)
751
+ # NOTE: merge "boxes" and "points" into a single "points" input
752
+ # (where boxes are added at the beginning) to model.sam_prompt_encoder
753
+ if points is not None:
754
+ points = torch.cat([bboxes, points], dim=1)
755
+ labels = torch.cat([bbox_labels, labels], dim=1)
756
+ else:
757
+ points, labels = bboxes, bbox_labels
758
+ return points, labels, masks
759
+
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]]
764
+
765
+ def get_im_features(self, im):
766
+ """Extract image features from the SAM image encoder for subsequent processing."""
767
+ backbone_out = self.model.forward_image(im)
768
+ _, vision_feats, _, _ = self.model._prepare_backbone_features(backbone_out)
769
+ if self.model.directly_add_no_mem_embed:
770
+ vision_feats[-1] = vision_feats[-1] + self.model.no_mem_embed
771
+ feats = [
772
+ feat.permute(1, 2, 0).view(1, -1, *feat_size) for feat, feat_size in zip(vision_feats, self._bb_feat_sizes)
773
+ ]
774
+ return {"image_embed": feats[-1], "high_res_feats": feats[:-1]}
775
+
776
+ def _inference_features(
777
+ self,
778
+ features,
779
+ points=None,
780
+ labels=None,
781
+ masks=None,
782
+ multimask_output=False,
783
+ img_idx=-1,
784
+ ):
785
+ """Perform inference on image features using the SAM2 model.
786
+
787
+ Args:
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:
790
+ - image_embed (torch.Tensor): Image embedding with shape (B, C, H, W).
791
+ - high_res_feats (list[torch.Tensor]): List of high-resolution feature maps from the backbone, each with shape (B, C, H, W).
792
+ points (np.ndarray | list[list[float]] | None): Object location points with shape (N, 2), in pixels.
793
+ labels (np.ndarray | list[int] | None): Point prompt labels with shape (N,). 1 = foreground, 0 = background.
794
+ masks (list[np.ndarray] | np.ndarray | None): Masks for the objects, where each mask is a 2D array.
795
+ multimask_output (bool): Flag to return multiple masks for ambiguous prompts.
796
+ img_idx (int): Index of the image in the batch to process.
797
+
798
+ Returns:
799
+ pred_masks (torch.Tensor): Output masks with shape (C, H, W), where C is the number of generated masks.
800
+ pred_scores (torch.Tensor): Quality scores for each mask, with length C.
801
+ """
802
+ points = (points, labels) if points is not None else None
803
+ sparse_embeddings, dense_embeddings = self.model.sam_prompt_encoder(
804
+ points=points,
805
+ boxes=None,
806
+ masks=masks,
807
+ )
808
+ # Predict masks
809
+ batched_mode = points is not None and points[0].shape[0] > 1 # multi object prediction
810
+ high_res_features = None
811
+ if isinstance(features, dict):
812
+ high_res_features = [feat_level[img_idx].unsqueeze(0) for feat_level in features["high_res_feats"]]
813
+ features = features["image_embed"][[img_idx]]
814
+ pred_masks, pred_scores, _, _ = self.model.sam_mask_decoder(
815
+ image_embeddings=features,
816
+ image_pe=self.model.sam_prompt_encoder.get_dense_pe(),
817
+ sparse_prompt_embeddings=sparse_embeddings,
818
+ dense_prompt_embeddings=dense_embeddings,
819
+ multimask_output=multimask_output,
820
+ repeat_image=batched_mode,
821
+ high_res_features=high_res_features,
822
+ )
823
+ # (N, d, H, W) --> (N*d, H, W), (N, d) --> (N*d, )
824
+ # `d` could be 1 or 3 depends on `multimask_output`.
825
+ return pred_masks.flatten(0, 1), pred_scores.flatten(0, 1)
826
+
827
+
828
+ class SAM2VideoPredictor(SAM2Predictor):
829
+ """SAM2VideoPredictor to handle user interactions with videos and manage inference states.
830
+
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.
834
+
835
+ Attributes:
836
+ inference_state (dict): A dictionary to store the current state of inference operations.
837
+ non_overlap_masks (bool): A flag indicating whether masks should be non-overlapping.
838
+ clear_non_cond_mem_around_input (bool): A flag to control clearing non-conditional memory around inputs.
839
+ clear_non_cond_mem_for_multi_obj (bool): A flag to control clearing non-conditional memory for multi-object
840
+ scenarios.
841
+ callbacks (dict): A dictionary of callbacks for various prediction lifecycle events.
842
+
843
+ Methods:
844
+ get_model: Retrieve and configure the model with binarization enabled.
845
+ inference: Perform image segmentation inference based on the given input cues.
846
+ postprocess: Post-process the predictions to apply non-overlapping constraints if required.
847
+ add_new_prompts: Add new points or masks to a specific frame for a given object ID.
848
+ propagate_in_video_preflight: Prepare inference_state and consolidate temporary outputs before tracking.
849
+ init_state: Initialize an inference state for the predictor.
850
+ get_im_features: Extract image features using SAM2's image encoder for subsequent segmentation tasks.
851
+
852
+ Examples:
853
+ >>> predictor = SAM2VideoPredictor(cfg=DEFAULT_CFG)
854
+ >>> predictor.set_image("path/to/video_frame.jpg")
855
+ >>> bboxes = [[100, 100, 200, 200]]
856
+ >>> results = predictor(bboxes=bboxes)
857
+
858
+ Notes:
859
+ The `fill_hole_area` attribute is defined but not used in the current implementation.
860
+ """
861
+
862
+ # fill_hole_area = 8 # not used
863
+
864
+ def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):
865
+ """Initialize the predictor with configuration and optional overrides.
866
+
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.
869
+
870
+ Args:
871
+ cfg (dict): Configuration dictionary containing default settings.
872
+ overrides (dict | None): Dictionary of values to override default configuration.
873
+ _callbacks (dict | None): Dictionary of callback functions to customize behavior.
874
+ """
875
+ super().__init__(cfg, overrides, _callbacks)
876
+ self.inference_state = {}
877
+ self.non_overlap_masks = True
878
+ self.clear_non_cond_mem_around_input = False
879
+ self.clear_non_cond_mem_for_multi_obj = False
880
+ self.callbacks["on_predict_start"].append(self.init_state)
881
+ self.clear_non_cond_mem = True # Whether to clear non-conditioning memory periodically
882
+
883
+ def get_model(self):
884
+ """Retrieve and configure the model with binarization enabled.
885
+
886
+ Notes:
887
+ This method overrides the base class implementation to set the binarize flag to True.
888
+ """
889
+ model = super().get_model()
890
+ model.set_binarize(True)
891
+ return model
892
+
893
+ def inference(self, im, bboxes=None, points=None, labels=None, masks=None):
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.
897
+
898
+ Args:
899
+ im (torch.Tensor): The preprocessed input image in tensor format, with shape (N, C, H, W).
900
+ bboxes (np.ndarray | list, optional): Bounding boxes with shape (N, 4), in XYXY format.
901
+ points (np.ndarray | list, optional): Points indicating object locations with shape (N, 2), in pixels.
902
+ labels (np.ndarray | list, optional): Labels for point prompts, shape (N, ). 1 = foreground, 0 = background.
903
+ masks (np.ndarray, optional): Low-resolution masks from previous predictions shape (N,H,W). For SAM H=W=256.
904
+
905
+ Returns:
906
+ pred_masks (torch.Tensor): The output masks in shape CxHxW, where C is the number of generated masks.
907
+ pred_scores (torch.Tensor): An array of length C containing predicted quality scores for each mask.
908
+ """
909
+ # Override prompts if any stored in self.prompts
910
+ bboxes = self.prompts.pop("bboxes", bboxes)
911
+ points = self.prompts.pop("points", points)
912
+ masks = self.prompts.pop("masks", masks)
913
+
914
+ frame = self.dataset.frame
915
+ self.inference_state["im"] = im
916
+ output_dict = self.inference_state["output_dict"]
917
+ if len(output_dict["cond_frame_outputs"]) == 0: # initialize prompts
918
+ points, labels, masks = self._prepare_prompts(
919
+ im.shape[2:], self.batch[1][0].shape[:2], bboxes, points, labels, masks
920
+ )
921
+ if points is not None:
922
+ for i in range(len(points)):
923
+ self.add_new_prompts(obj_id=i, points=points[[i]], labels=labels[[i]], frame_idx=frame)
924
+ elif masks is not None:
925
+ for i in range(len(masks)):
926
+ self.add_new_prompts(obj_id=i, masks=masks[[i]], frame_idx=frame)
927
+ self.propagate_in_video_preflight()
928
+
929
+ consolidated_frame_inds = self.inference_state["consolidated_frame_inds"]
930
+ batch_size = len(self.inference_state["obj_idx_to_id"])
931
+ if len(output_dict["cond_frame_outputs"]) == 0:
932
+ raise RuntimeError("No points are provided; please add points first")
933
+
934
+ if frame in consolidated_frame_inds["cond_frame_outputs"]:
935
+ storage_key = "cond_frame_outputs"
936
+ current_out = output_dict[storage_key][frame]
937
+ if self.clear_non_cond_mem_around_input and (self.clear_non_cond_mem_for_multi_obj or batch_size <= 1):
938
+ # clear non-conditioning memory of the surrounding frames
939
+ self._clear_non_cond_mem_around_input(frame)
940
+ elif frame in consolidated_frame_inds["non_cond_frame_outputs"]:
941
+ storage_key = "non_cond_frame_outputs"
942
+ current_out = output_dict[storage_key][frame]
943
+ else:
944
+ storage_key = "non_cond_frame_outputs"
945
+ current_out = self._run_single_frame_inference(
946
+ output_dict=output_dict,
947
+ frame_idx=frame,
948
+ batch_size=batch_size,
949
+ is_init_cond_frame=False,
950
+ point_inputs=None,
951
+ mask_inputs=None,
952
+ reverse=False,
953
+ run_mem_encoder=True,
954
+ )
955
+ output_dict[storage_key][frame] = current_out
956
+ self._prune_non_cond_memory(frame)
957
+ # Create slices of per-object outputs for subsequent interaction with each
958
+ # individual object after tracking.
959
+ self._add_output_per_object(frame, current_out, storage_key)
960
+ self.inference_state["frames_already_tracked"].append(frame)
961
+ pred_masks = current_out["pred_masks"].flatten(0, 1)
962
+ pred_masks = pred_masks[(pred_masks > self.model.mask_threshold).sum((1, 2)) > 0] # filter blank masks
963
+
964
+ return pred_masks, torch.ones(pred_masks.shape[0], dtype=pred_masks.dtype, device=pred_masks.device)
965
+
966
+ def postprocess(self, preds, img, orig_imgs):
967
+ """Post-process the predictions to apply non-overlapping constraints if required.
968
+
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.
972
+
973
+ Args:
974
+ preds (tuple[torch.Tensor, torch.Tensor]): The predicted masks and scores from the model.
975
+ img (torch.Tensor): The processed image tensor.
976
+ orig_imgs (list[np.ndarray]): The original images before processing.
977
+
978
+ Returns:
979
+ (list): The post-processed predictions.
980
+
981
+ Notes:
982
+ If `non_overlap_masks` is True, the method applies constraints to ensure non-overlapping masks.
983
+ """
984
+ results = super().postprocess(preds, img, orig_imgs)
985
+ if self.non_overlap_masks:
986
+ for result in results:
987
+ if result.masks is None or len(result.masks) == 0:
988
+ continue
989
+ result.masks.data = self.model._apply_non_overlapping_constraints(result.masks.data.unsqueeze(0))[0]
990
+ return results
991
+
992
+ @smart_inference_mode()
993
+ def add_new_prompts(
994
+ self,
995
+ obj_id,
996
+ points=None,
997
+ labels=None,
998
+ masks=None,
999
+ frame_idx=0,
1000
+ inference_state: dict[str, Any] | None = None,
1001
+ ):
1002
+ """Add new points or masks to a specific frame for a given object ID.
1003
+
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.
1008
+
1009
+ Args:
1010
+ obj_id (int): The ID of the object to which the prompts are associated.
1011
+ points (torch.Tensor, optional): The coordinates of the points of interest.
1012
+ labels (torch.Tensor, optional): The labels corresponding to the points.
1013
+ masks (torch.Tensor, optional): Binary masks for the object.
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.
1017
+
1018
+ Returns:
1019
+ pred_masks (torch.Tensor): The flattened predicted masks.
1020
+ pred_scores (torch.Tensor): A tensor of ones indicating the number of objects.
1021
+
1022
+ Raises:
1023
+ AssertionError: If both `masks` and `points` are provided, or neither is provided.
1024
+
1025
+ Notes:
1026
+ - Only one type of prompt (either points or masks) can be added per call.
1027
+ - If the frame is being tracked for the first time, it is treated as an initial conditioning frame.
1028
+ - The method handles the consolidation of outputs and resizing of masks to the original video resolution.
1029
+ """
1030
+ inference_state = inference_state or self.inference_state
1031
+ assert (masks is None) ^ (points is None), "'masks' and 'points' prompts are not compatible with each other."
1032
+ obj_idx = self._obj_id_to_idx(obj_id, inference_state)
1033
+
1034
+ point_inputs = None
1035
+ pop_key = "point_inputs_per_obj"
1036
+ if points is not None:
1037
+ point_inputs = {"point_coords": points, "point_labels": labels}
1038
+ inference_state["point_inputs_per_obj"][obj_idx][frame_idx] = point_inputs
1039
+ pop_key = "mask_inputs_per_obj"
1040
+ inference_state["mask_inputs_per_obj"][obj_idx][frame_idx] = masks
1041
+ inference_state[pop_key][obj_idx].pop(frame_idx, None)
1042
+ # If this frame hasn't been tracked before, we treat it as an initial conditioning
1043
+ # frame, meaning that the inputs points are to generate segments on this frame without
1044
+ # using any memory from other frames, like in SAM. Otherwise (if it has been tracked),
1045
+ # the input points will be used to correct the already tracked masks.
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]
1049
+ # Add a frame to conditioning output if it's an initial conditioning frame or
1050
+ # if the model sees all frames receiving clicks/mask as conditioning frames.
1051
+ is_cond = is_init_cond_frame or self.model.add_all_frames_to_correct_as_cond
1052
+ storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
1053
+
1054
+ # Get any previously predicted mask logits on this object and feed it along with
1055
+ # the new clicks into the SAM mask decoder.
1056
+ prev_sam_mask_logits = None
1057
+ # lookup temporary output dict first, which contains the most recent output
1058
+ # (if not found, then lookup conditioning and non-conditioning frame output)
1059
+ if point_inputs is not None:
1060
+ prev_out = (
1061
+ obj_temp_output_dict[storage_key].get(frame_idx)
1062
+ or obj_output_dict["cond_frame_outputs"].get(frame_idx)
1063
+ or obj_output_dict["non_cond_frame_outputs"].get(frame_idx)
1064
+ )
1065
+
1066
+ if prev_out is not None and prev_out.get("pred_masks") is not None:
1067
+ prev_sam_mask_logits = prev_out["pred_masks"].to(
1068
+ device=self.device, non_blocking=self.device.type == "cuda"
1069
+ )
1070
+ # Clamp the scale of prev_sam_mask_logits to avoid rare numerical issues.
1071
+ prev_sam_mask_logits.clamp_(-32.0, 32.0)
1072
+ current_out = self._run_single_frame_inference(
1073
+ output_dict=obj_output_dict, # run on the slice of a single object
1074
+ frame_idx=frame_idx,
1075
+ batch_size=1, # run on the slice of a single object
1076
+ is_init_cond_frame=is_init_cond_frame,
1077
+ point_inputs=point_inputs,
1078
+ mask_inputs=masks,
1079
+ reverse=False,
1080
+ # Skip the memory encoder when adding clicks or mask. We execute the memory encoder
1081
+ # at the beginning of `propagate_in_video` (after user finalize their clicks). This
1082
+ # allows us to enforce non-overlapping constraints on all objects before encoding
1083
+ # them into memory.
1084
+ run_mem_encoder=False,
1085
+ prev_sam_mask_logits=prev_sam_mask_logits,
1086
+ inference_state=inference_state,
1087
+ )
1088
+ # Add the output to the output dict (to be used as future memory)
1089
+ obj_temp_output_dict[storage_key][frame_idx] = current_out
1090
+
1091
+ # Resize the output mask to the original video resolution
1092
+ consolidated_out = self._consolidate_temp_output_across_obj(
1093
+ frame_idx,
1094
+ is_cond=is_cond,
1095
+ run_mem_encoder=False,
1096
+ inference_state=inference_state,
1097
+ )
1098
+ pred_masks = consolidated_out["pred_masks"].flatten(0, 1)
1099
+ return pred_masks.flatten(0, 1), torch.ones(1, dtype=pred_masks.dtype, device=pred_masks.device)
1100
+
1101
+ @smart_inference_mode()
1102
+ def propagate_in_video_preflight(self, inference_state: dict[str, Any] | None = None):
1103
+ """Prepare inference_state and consolidate temporary outputs before tracking.
1104
+
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.
1113
+ """
1114
+ inference_state = inference_state or self.inference_state
1115
+ # Tracking has started and we don't allow adding new objects until session is reset.
1116
+ inference_state["tracking_has_started"] = True
1117
+ batch_size = len(inference_state["obj_idx_to_id"])
1118
+
1119
+ # Consolidate per-object temporary outputs in "temp_output_dict_per_obj" and
1120
+ # add them into "output_dict".
1121
+ temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"]
1122
+ output_dict = inference_state["output_dict"]
1123
+ # "consolidated_frame_inds" contains indices of those frames where consolidated
1124
+ # temporary outputs have been added (either in this call or any previous calls
1125
+ # to `propagate_in_video_preflight`).
1126
+ consolidated_frame_inds = inference_state["consolidated_frame_inds"]
1127
+ for is_cond in {False, True}:
1128
+ # Separately consolidate conditioning and non-conditioning temp outputs
1129
+ storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
1130
+ # Find all the frames that contain temporary outputs for any objects
1131
+ # (these should be the frames that have just received clicks for mask inputs
1132
+ # via `add_new_points` or `add_new_mask`)
1133
+ temp_frame_inds = set()
1134
+ for obj_temp_output_dict in temp_output_dict_per_obj.values():
1135
+ temp_frame_inds.update(obj_temp_output_dict[storage_key].keys())
1136
+ consolidated_frame_inds[storage_key].update(temp_frame_inds)
1137
+ # consolidate the temporary output across all objects on this frame
1138
+ for frame_idx in temp_frame_inds:
1139
+ consolidated_out = self._consolidate_temp_output_across_obj(
1140
+ frame_idx, is_cond=is_cond, run_mem_encoder=True, inference_state=inference_state
1141
+ )
1142
+ # merge them into "output_dict" and also create per-object slices
1143
+ output_dict[storage_key][frame_idx] = consolidated_out
1144
+ self._add_output_per_object(frame_idx, consolidated_out, storage_key, inference_state=inference_state)
1145
+ if self.clear_non_cond_mem_around_input and (self.clear_non_cond_mem_for_multi_obj or batch_size <= 1):
1146
+ # clear non-conditioning memory of the surrounding frames
1147
+ self._clear_non_cond_mem_around_input(frame_idx)
1148
+
1149
+ # clear temporary outputs in `temp_output_dict_per_obj`
1150
+ for obj_temp_output_dict in temp_output_dict_per_obj.values():
1151
+ obj_temp_output_dict[storage_key].clear()
1152
+
1153
+ # edge case: if an output is added to "cond_frame_outputs", we remove any prior
1154
+ # output on the same frame in "non_cond_frame_outputs"
1155
+ for frame_idx in output_dict["cond_frame_outputs"]:
1156
+ output_dict["non_cond_frame_outputs"].pop(frame_idx, None)
1157
+ for obj_output_dict in inference_state["output_dict_per_obj"].values():
1158
+ for frame_idx in obj_output_dict["cond_frame_outputs"]:
1159
+ obj_output_dict["non_cond_frame_outputs"].pop(frame_idx, None)
1160
+ for frame_idx in consolidated_frame_inds["cond_frame_outputs"]:
1161
+ assert frame_idx in output_dict["cond_frame_outputs"]
1162
+ consolidated_frame_inds["non_cond_frame_outputs"].discard(frame_idx)
1163
+
1164
+ # Make sure that the frame indices in "consolidated_frame_inds" are exactly those frames
1165
+ # with either points or mask inputs (which should be true under a correct workflow).
1166
+ all_consolidated_frame_inds = (
1167
+ consolidated_frame_inds["cond_frame_outputs"] | consolidated_frame_inds["non_cond_frame_outputs"]
1168
+ )
1169
+ input_frames_inds = set()
1170
+ for point_inputs_per_frame in inference_state["point_inputs_per_obj"].values():
1171
+ input_frames_inds.update(point_inputs_per_frame.keys())
1172
+ for mask_inputs_per_frame in inference_state["mask_inputs_per_obj"].values():
1173
+ input_frames_inds.update(mask_inputs_per_frame.keys())
1174
+ assert all_consolidated_frame_inds == input_frames_inds
1175
+
1176
+ @staticmethod
1177
+ def init_state(predictor):
1178
+ """Initialize an inference state for the predictor.
1179
+
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.
1183
+
1184
+ Args:
1185
+ predictor (SAM2VideoPredictor): The predictor object for which to initialize the state.
1186
+ """
1187
+ if len(predictor.inference_state) > 0: # means initialized
1188
+ return
1189
+ assert predictor.dataset is not None
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.
1200
+
1201
+ Args:
1202
+ num_frames (int): The number of frames in the video.
1203
+ """
1204
+ inference_state = {
1205
+ "num_frames": num_frames, # TODO: see if there's any chance to remove it
1206
+ "point_inputs_per_obj": {}, # inputs points on each frame
1207
+ "mask_inputs_per_obj": {}, # inputs mask on each frame
1208
+ "constants": {}, # values that don't change across frames (so we only need to hold one copy of them)
1209
+ # mapping between client-side object id and model-side object index
1210
+ "obj_id_to_idx": OrderedDict(),
1211
+ "obj_idx_to_id": OrderedDict(),
1212
+ "obj_ids": [],
1213
+ # A storage to hold the model's tracking results and states on each frame
1214
+ "output_dict": {
1215
+ "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
1216
+ "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
1217
+ },
1218
+ # Slice (view) of each object tracking results, sharing the same memory with "output_dict"
1219
+ "output_dict_per_obj": {},
1220
+ # A temporary storage to hold new outputs when user interact with a frame
1221
+ # to add clicks or mask (it's merged into "output_dict" before propagation starts)
1222
+ "temp_output_dict_per_obj": {},
1223
+ # Frames that already holds consolidated outputs from click or mask inputs
1224
+ # (we directly use their consolidated outputs during tracking)
1225
+ "consolidated_frame_inds": {
1226
+ "cond_frame_outputs": set(), # set containing frame indices
1227
+ "non_cond_frame_outputs": set(), # set containing frame indices
1228
+ },
1229
+ # metadata for each tracking frame (e.g. which direction it's tracked)
1230
+ "tracking_has_started": False,
1231
+ "frames_already_tracked": [],
1232
+ }
1233
+ return inference_state
1234
+
1235
+ def get_im_features(self, im, batch=1):
1236
+ """Extract and process image features using SAM2's image encoder for subsequent segmentation tasks.
1237
+
1238
+ Args:
1239
+ im (torch.Tensor): The input image tensor.
1240
+ batch (int, optional): The batch size for expanding features if there are multiple prompts.
1241
+
1242
+ Returns:
1243
+ vis_feats (torch.Tensor): The visual features extracted from the image.
1244
+ vis_pos_embed (torch.Tensor): The positional embeddings for the visual features.
1245
+ feat_sizes (list[tuple]): A list containing the sizes of the extracted features.
1246
+
1247
+ Notes:
1248
+ - If `batch` is greater than 1, the features are expanded to fit the batch size.
1249
+ - The method leverages the model's `_prepare_backbone_features` method to prepare the backbone features.
1250
+ """
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)
1256
+ return vis_feats, vis_pos_embed, feat_sizes
1257
+
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.
1260
+
1261
+ Args:
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.
1265
+
1266
+ Returns:
1267
+ (int): The index of the object on the model side.
1268
+
1269
+ Raises:
1270
+ RuntimeError: If an attempt is made to add a new object after tracking has started.
1271
+
1272
+ Notes:
1273
+ - The method updates or retrieves mappings between object IDs and indices stored in
1274
+ `inference_state`.
1275
+ - It ensures that new objects can only be added before tracking commences.
1276
+ - It maintains two-way mappings between IDs and indices (`obj_id_to_idx` and `obj_idx_to_id`).
1277
+ - Additional data structures are initialized for the new object to store inputs and outputs.
1278
+ """
1279
+ inference_state = inference_state or self.inference_state
1280
+ obj_idx = inference_state["obj_id_to_idx"].get(obj_id, None)
1281
+ if obj_idx is not None:
1282
+ return obj_idx
1283
+
1284
+ # This is a new object id not sent to the server before. We only allow adding
1285
+ # new objects *before* the tracking starts.
1286
+ allow_new_object = not inference_state["tracking_has_started"]
1287
+ if allow_new_object:
1288
+ # get the next object slot
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"])
1293
+ # set up input and output structures for this object
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] = {
1297
+ "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
1298
+ "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
1299
+ }
1300
+ inference_state["temp_output_dict_per_obj"][obj_idx] = {
1301
+ "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
1302
+ "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
1303
+ }
1304
+ return obj_idx
1305
+ else:
1306
+ raise RuntimeError(
1307
+ f"Cannot add new object id {obj_id} after tracking starts. "
1308
+ f"All existing object ids: {inference_state['obj_ids']}. "
1309
+ f"Please call 'reset_state' to restart from scratch."
1310
+ )
1311
+
1312
+ def _run_single_frame_inference(
1313
+ self,
1314
+ output_dict,
1315
+ frame_idx,
1316
+ batch_size,
1317
+ is_init_cond_frame,
1318
+ point_inputs,
1319
+ mask_inputs,
1320
+ reverse,
1321
+ run_mem_encoder,
1322
+ prev_sam_mask_logits=None,
1323
+ inference_state: dict[str, Any] | None = None,
1324
+ ):
1325
+ """Run tracking on a single frame based on current inputs and previous memory.
1326
+
1327
+ Args:
1328
+ output_dict (dict): The dictionary containing the output states of the tracking process.
1329
+ frame_idx (int): The index of the current frame.
1330
+ batch_size (int): The batch size for processing the frame.
1331
+ is_init_cond_frame (bool): Indicates if the current frame is an initial conditioning frame.
1332
+ point_inputs (dict | None): Input points and their labels.
1333
+ mask_inputs (torch.Tensor | None): Input binary masks.
1334
+ reverse (bool): Indicates if the tracking should be performed in reverse order.
1335
+ run_mem_encoder (bool): Indicates if the memory encoder should be executed.
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.
1339
+
1340
+ Returns:
1341
+ (dict): A dictionary containing the output of the tracking step, including updated features and predictions.
1342
+
1343
+ Raises:
1344
+ AssertionError: If both `point_inputs` and `mask_inputs` are provided, or neither is provided.
1345
+
1346
+ Notes:
1347
+ - The method assumes that `point_inputs` and `mask_inputs` are mutually exclusive.
1348
+ - The method retrieves image features using the `get_im_features` method.
1349
+ - The `maskmem_pos_enc` is assumed to be constant across frames, hence only one copy is stored.
1350
+ - The `fill_holes_in_mask_scores` function is commented out and currently unsupported due to CUDA extension requirements.
1351
+ """
1352
+ inference_state = inference_state or self.inference_state
1353
+ # Retrieve correct image features
1354
+ current_vision_feats, current_vision_pos_embeds, feat_sizes = self.get_im_features(
1355
+ inference_state["im"], batch_size
1356
+ )
1357
+
1358
+ # point and mask should not appear as input simultaneously on the same frame
1359
+ assert point_inputs is None or mask_inputs is None
1360
+ current_out = self.model.track_step(
1361
+ frame_idx=frame_idx,
1362
+ is_init_cond_frame=is_init_cond_frame,
1363
+ current_vision_feats=current_vision_feats,
1364
+ current_vision_pos_embeds=current_vision_pos_embeds,
1365
+ feat_sizes=feat_sizes,
1366
+ point_inputs=point_inputs,
1367
+ mask_inputs=mask_inputs,
1368
+ output_dict=output_dict,
1369
+ num_frames=inference_state["num_frames"],
1370
+ track_in_reverse=reverse,
1371
+ run_mem_encoder=run_mem_encoder,
1372
+ prev_sam_mask_logits=prev_sam_mask_logits,
1373
+ )
1374
+
1375
+ maskmem_features = current_out["maskmem_features"]
1376
+ if maskmem_features is not None:
1377
+ current_out["maskmem_features"] = maskmem_features.to(
1378
+ dtype=torch.float16, device=self.device, non_blocking=self.device.type == "cuda"
1379
+ )
1380
+ # NOTE: Do not support the `fill_holes_in_mask_scores` function since it needs cuda extensions
1381
+ # potentially fill holes in the predicted masks
1382
+ # if self.fill_hole_area > 0:
1383
+ # pred_masks = current_out["pred_masks"].to(self.device, non_blocking=self.device.type == "cuda")
1384
+ # pred_masks = fill_holes_in_mask_scores(pred_masks, self.fill_hole_area)
1385
+
1386
+ # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
1387
+ current_out["maskmem_pos_enc"] = self._get_maskmem_pos_enc(current_out["maskmem_pos_enc"], inference_state)
1388
+ return current_out
1389
+
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.
1392
+
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.
1398
+
1399
+ Args:
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.
1404
+
1405
+ Returns:
1406
+ (list[torch.Tensor]): The positional encoding for mask memory, either cached or expanded.
1407
+
1408
+ Notes:
1409
+ - The method assumes that `out_maskmem_pos_enc` is a list of tensors or None.
1410
+ - Only a single object's slice is cached since the encoding is the same across objects.
1411
+ - The method checks if the positional encoding has already been cached in the session's constants.
1412
+ - If the batch size is greater than one, the cached encoding is expanded to fit the batch size.
1413
+ """
1414
+ inference_state = inference_state or self.inference_state
1415
+ model_constants = inference_state["constants"]
1416
+ # "out_maskmem_pos_enc" should be either a list of tensors or None
1417
+ if out_maskmem_pos_enc is not None:
1418
+ if "maskmem_pos_enc" not in model_constants:
1419
+ assert isinstance(out_maskmem_pos_enc, list)
1420
+ # only take the slice for one object, since it's same across objects
1421
+ maskmem_pos_enc = [x[:1].clone() for x in out_maskmem_pos_enc]
1422
+ model_constants["maskmem_pos_enc"] = maskmem_pos_enc
1423
+ else:
1424
+ maskmem_pos_enc = model_constants["maskmem_pos_enc"]
1425
+ # expand the cached maskmem_pos_enc to the actual batch size
1426
+ batch_size = out_maskmem_pos_enc[0].shape[0]
1427
+ if batch_size > 1:
1428
+ out_maskmem_pos_enc = [x.expand(batch_size, -1, -1, -1) for x in maskmem_pos_enc]
1429
+ return out_maskmem_pos_enc
1430
+
1431
+ def _consolidate_temp_output_across_obj(
1432
+ self,
1433
+ frame_idx,
1434
+ is_cond=False,
1435
+ run_mem_encoder=False,
1436
+ inference_state: dict[str, Any] | None = None,
1437
+ ):
1438
+ """Consolidate per-object temporary outputs into a single output for all objects.
1439
+
1440
+ This method combines the temporary outputs for each object on a given frame into a unified
1441
+ output. It fills in any missing objects either from the main output dictionary or leaves
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.
1444
+
1445
+ Args:
1446
+ frame_idx (int): The index of the frame for which to consolidate outputs.
1447
+ is_cond (bool, optional): Indicates if the frame is considered a conditioning frame.
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.
1452
+
1453
+ Returns:
1454
+ (dict): A consolidated output dictionary containing the combined results for all objects.
1455
+
1456
+ Notes:
1457
+ - The method initializes the consolidated output with placeholder values for missing objects.
1458
+ - It searches for outputs in both the temporary and main output dictionaries.
1459
+ - If `run_mem_encoder` is True, it applies non-overlapping constraints and re-runs the memory encoder.
1460
+ - The `maskmem_features` and `maskmem_pos_enc` are only populated when `run_mem_encoder` is True.
1461
+ """
1462
+ inference_state = inference_state or self.inference_state
1463
+ batch_size = len(inference_state["obj_idx_to_id"])
1464
+ storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
1465
+
1466
+ # Initialize `consolidated_out`. Its "maskmem_features" and "maskmem_pos_enc"
1467
+ # will be added when rerunning the memory encoder after applying non-overlapping
1468
+ # constraints to object scores. Its "pred_masks" are prefilled with a large
1469
+ # negative value (NO_OBJ_SCORE) to represent missing objects.
1470
+ consolidated_out = {
1471
+ "maskmem_features": None,
1472
+ "maskmem_pos_enc": None,
1473
+ "pred_masks": torch.full(
1474
+ # size=(batch_size, 1, self.imgsz[0] // 4, self.imgsz[1] // 4),
1475
+ size=(batch_size, 1, *self._bb_feat_sizes[0]),
1476
+ fill_value=-1024.0,
1477
+ dtype=self.torch_dtype,
1478
+ device=self.device,
1479
+ ),
1480
+ "obj_ptr": torch.full(
1481
+ size=(batch_size, self.model.hidden_dim),
1482
+ fill_value=-1024.0,
1483
+ dtype=self.torch_dtype,
1484
+ device=self.device,
1485
+ ),
1486
+ "object_score_logits": torch.full(
1487
+ size=(batch_size, 1),
1488
+ # default to 10.0 for object_score_logits, i.e. assuming the object is
1489
+ # present as sigmoid(10)=1, same as in `predict_masks` of `MaskDecoder`
1490
+ fill_value=10.0,
1491
+ dtype=self.torch_dtype,
1492
+ device=self.device,
1493
+ ),
1494
+ }
1495
+ for obj_idx in range(batch_size):
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]
1498
+ out = (
1499
+ obj_temp_output_dict[storage_key].get(frame_idx)
1500
+ # If the object doesn't appear in "temp_output_dict_per_obj" on this frame,
1501
+ # we fall back and look up its previous output in "output_dict_per_obj".
1502
+ # We look up both "cond_frame_outputs" and "non_cond_frame_outputs" in
1503
+ # "output_dict_per_obj" to find a previous output for this object.
1504
+ or obj_output_dict["cond_frame_outputs"].get(frame_idx)
1505
+ or obj_output_dict["non_cond_frame_outputs"].get(frame_idx)
1506
+ )
1507
+ # If the object doesn't appear in "output_dict_per_obj" either, we skip it
1508
+ # and leave its mask scores to the default scores (i.e. the NO_OBJ_SCORE
1509
+ # placeholder above) and set its object pointer to be a dummy pointer.
1510
+ if out is None:
1511
+ # Fill in dummy object pointers for those objects without any inputs or
1512
+ # tracking outcomes on this frame (only do it under `run_mem_encoder=True`,
1513
+ # i.e. when we need to build the memory for tracking).
1514
+ if run_mem_encoder:
1515
+ # fill object pointer with a dummy pointer (based on an empty mask)
1516
+ consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = self._get_empty_mask_ptr(frame_idx)
1517
+ continue
1518
+ # Add the temporary object output mask to consolidated output mask
1519
+ consolidated_out["pred_masks"][obj_idx : obj_idx + 1] = out["pred_masks"]
1520
+ consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = out["obj_ptr"]
1521
+
1522
+ # Optionally, apply non-overlapping constraints on the consolidated scores and rerun the memory encoder
1523
+ if run_mem_encoder:
1524
+ high_res_masks = F.interpolate(
1525
+ consolidated_out["pred_masks"],
1526
+ size=self.imgsz,
1527
+ mode="bilinear",
1528
+ align_corners=False,
1529
+ )
1530
+ if self.model.non_overlap_masks_for_mem_enc:
1531
+ high_res_masks = self.model._apply_non_overlapping_constraints(high_res_masks)
1532
+ consolidated_out["maskmem_features"], consolidated_out["maskmem_pos_enc"] = self._run_memory_encoder(
1533
+ batch_size=batch_size,
1534
+ high_res_masks=high_res_masks,
1535
+ is_mask_from_pts=True, # these frames are what the user interacted with
1536
+ object_score_logits=consolidated_out["object_score_logits"],
1537
+ inference_state=inference_state,
1538
+ )
1539
+
1540
+ return consolidated_out
1541
+
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.
1544
+
1545
+ Args:
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.
1549
+
1550
+ Returns:
1551
+ (torch.Tensor): A tensor representing the dummy object pointer generated from the empty mask.
1552
+ """
1553
+ inference_state = inference_state or self.inference_state
1554
+ # Retrieve correct image features
1555
+ current_vision_feats, current_vision_pos_embeds, feat_sizes = self.get_im_features(inference_state["im"])
1556
+
1557
+ # Feed the empty mask and image feature above to get a dummy object pointer
1558
+ current_out = self.model.track_step(
1559
+ frame_idx=frame_idx,
1560
+ is_init_cond_frame=True,
1561
+ current_vision_feats=current_vision_feats,
1562
+ current_vision_pos_embeds=current_vision_pos_embeds,
1563
+ feat_sizes=feat_sizes,
1564
+ point_inputs=None,
1565
+ # A dummy (empty) mask with a single object
1566
+ mask_inputs=torch.zeros((1, 1, *self.imgsz), dtype=self.torch_dtype, device=self.device),
1567
+ output_dict={},
1568
+ num_frames=inference_state["num_frames"],
1569
+ track_in_reverse=False,
1570
+ run_mem_encoder=False,
1571
+ prev_sam_mask_logits=None,
1572
+ )
1573
+ return current_out["obj_ptr"]
1574
+
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.
1584
+
1585
+ This is usually after applying non-overlapping constraints to object scores. Since their scores changed, their
1586
+ memory also needs to be computed again with the memory encoder.
1587
+
1588
+ Args:
1589
+ batch_size (int): The batch size for processing the frame.
1590
+ high_res_masks (torch.Tensor): High-resolution masks for which to compute the memory.
1591
+ object_score_logits (torch.Tensor): Logits representing the object scores.
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.
1595
+
1596
+ Returns:
1597
+ maskmem_features (torch.Tensor): The encoded mask features.
1598
+ maskmem_pos_enc (torch.Tensor): The positional encoding.
1599
+ """
1600
+ inference_state = inference_state or self.inference_state
1601
+ # Retrieve correct image features
1602
+ current_vision_feats, _, feat_sizes = self.get_im_features(inference_state["im"], batch_size)
1603
+ maskmem_features, maskmem_pos_enc = self.model._encode_new_memory(
1604
+ current_vision_feats=current_vision_feats,
1605
+ feat_sizes=feat_sizes,
1606
+ pred_masks_high_res=high_res_masks,
1607
+ is_mask_from_pts=is_mask_from_pts,
1608
+ object_score_logits=object_score_logits,
1609
+ )
1610
+
1611
+ # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
1612
+ maskmem_pos_enc = self._get_maskmem_pos_enc(maskmem_pos_enc, inference_state)
1613
+ return maskmem_features.to(
1614
+ dtype=torch.float16, device=self.device, non_blocking=self.device.type == "cuda"
1615
+ ), maskmem_pos_enc
1616
+
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.
1621
+
1622
+ The resulting slices share the same tensor storage.
1623
+
1624
+ Args:
1625
+ frame_idx (int): The index of the current frame.
1626
+ current_out (dict): The current output dictionary containing multi-object outputs.
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.
1630
+ """
1631
+ inference_state = inference_state or self.inference_state
1632
+ maskmem_features = current_out["maskmem_features"]
1633
+ assert maskmem_features is None or isinstance(maskmem_features, torch.Tensor)
1634
+
1635
+ maskmem_pos_enc = current_out["maskmem_pos_enc"]
1636
+ assert maskmem_pos_enc is None or isinstance(maskmem_pos_enc, list)
1637
+
1638
+ for obj_idx, obj_output_dict in inference_state["output_dict_per_obj"].items():
1639
+ obj_slice = slice(obj_idx, obj_idx + 1)
1640
+ obj_out = {
1641
+ "maskmem_features": None,
1642
+ "maskmem_pos_enc": None,
1643
+ "pred_masks": current_out["pred_masks"][obj_slice],
1644
+ "obj_ptr": current_out["obj_ptr"][obj_slice],
1645
+ }
1646
+ if maskmem_features is not None:
1647
+ obj_out["maskmem_features"] = maskmem_features[obj_slice]
1648
+ if maskmem_pos_enc is not None:
1649
+ obj_out["maskmem_pos_enc"] = [x[obj_slice] for x in maskmem_pos_enc]
1650
+ obj_output_dict[storage_key][frame_idx] = obj_out
1651
+
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.
1654
+
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.
1659
+
1660
+ Args:
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.
1664
+ """
1665
+ inference_state = inference_state or self.inference_state
1666
+ r = self.model.memory_temporal_stride_for_eval
1667
+ frame_idx_begin = frame_idx - r * self.model.num_maskmem
1668
+ frame_idx_end = frame_idx + r * self.model.num_maskmem
1669
+ for t in range(frame_idx_begin, frame_idx_end + 1):
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():
1672
+ obj_output_dict["non_cond_frame_outputs"].pop(t, None)
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
+
1855
+
1856
+ class SAM2DynamicInteractivePredictor(SAM2Predictor):
1857
+ """SAM2DynamicInteractivePredictor extends SAM2Predictor to support dynamic interactions with video frames or a
1858
+ sequence of images.
1859
+
1860
+ Attributes:
1861
+ memory_bank (list): OrderedDict: Stores the states of each image with prompts.
1862
+ obj_idx_set (set): A set to keep track of the object indices that have been added.
1863
+ obj_id_to_idx (OrderedDict): Maps object IDs to their corresponding indices.
1864
+ obj_idx_to_id (OrderedDict): Maps object indices to their corresponding IDs.
1865
+
1866
+ Methods:
1867
+ get_model: Retrieves and configures the model with binarization enabled.
1868
+ inference: Performs inference on a single image with optional prompts and object IDs.
1869
+ postprocess: Post-processes the predictions to apply non-overlapping constraints if required.
1870
+ update_memory: Append the imgState to the memory_bank and update the memory for the model.
1871
+ track_step: Tracking step for the current image state to predict masks.
1872
+ get_maskmem_enc: Get memory and positional encoding from the memory bank.
1873
+
1874
+ Examples:
1875
+ >>> predictor = SAM2DynamicInteractivePredictor(cfg=DEFAULT_CFG)
1876
+ >>> predictor(source=support_img1, bboxes=bboxes1, obj_ids=labels1, update_memory=True)
1877
+ >>> results1 = predictor(source=query_img1)
1878
+ >>> predictor(source=support_img2, bboxes=bboxes2, obj_ids=labels2, update_memory=True)
1879
+ >>> results2 = predictor(source=query_img2)
1880
+ """
1881
+
1882
+ def __init__(
1883
+ self,
1884
+ cfg: Any = DEFAULT_CFG,
1885
+ overrides: dict[str, Any] | None = None,
1886
+ max_obj_num: int = 3,
1887
+ _callbacks: dict[str, Any] | None = None,
1888
+ ) -> None:
1889
+ """Initialize the predictor with configuration and optional overrides.
1890
+
1891
+ This constructor initializes the SAM2DynamicInteractivePredictor with a given configuration, applies any
1892
+ specified overrides
1893
+
1894
+ Args:
1895
+ cfg (dict[str, Any]): Configuration dictionary containing default settings.
1896
+ overrides (dict[str, Any] | None): Dictionary of values to override default configuration.
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.
1899
+ _callbacks (dict[str, Any] | None): Dictionary of callback functions to customize behavior.
1900
+ """
1901
+ super().__init__(cfg, overrides, _callbacks)
1902
+ self.non_overlap_masks = True
1903
+
1904
+ # Initialize the memory bank to store image states
1905
+ # NOTE: probably need to use dict for better query
1906
+ self.memory_bank = []
1907
+
1908
+ # Initialize the object index set and mappings
1909
+ self.obj_idx_set = set()
1910
+ self.obj_id_to_idx = self.obj_idx_to_id = OrderedDict(enumerate(range(max_obj_num)))
1911
+ self._max_obj_num = max_obj_num
1912
+
1913
+ @smart_inference_mode()
1914
+ def inference(
1915
+ self,
1916
+ im: torch.Tensor | np.ndarray,
1917
+ bboxes: list[list[float]] | None = None,
1918
+ masks: torch.Tensor | np.ndarray | None = None,
1919
+ points: list[list[float]] | None = None,
1920
+ labels: list[int] | None = None,
1921
+ obj_ids: list[int] | None = None,
1922
+ update_memory: bool = False,
1923
+ ) -> tuple[torch.Tensor, torch.Tensor]:
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.
1929
+
1930
+ Args:
1931
+ im (torch.Tensor | np.ndarray): The input image tensor or numpy array.
1932
+ bboxes (list[list[float]] | None): Optional list of bounding boxes to update the memory.
1933
+ masks (list[torch.Tensor | np.ndarray] | None): Optional masks to update the memory.
1934
+ points (list[list[float]] | None): Optional list of points to update the memory, each point is [x, y].
1935
+ labels (list[int] | None): Optional list of object IDs corresponding to the points (>0 for positive, 0 for
1936
+ negative).
1937
+ obj_ids (list[int] | None): Optional list of object IDs corresponding to the prompts.
1938
+ update_memory (bool): Flag to indicate whether to update the memory with new objects.
1939
+
1940
+ Returns:
1941
+ res_masks (torch.Tensor): The output masks in shape (C, H, W)
1942
+ object_score_logits (torch.Tensor): Quality scores for each mask
1943
+ """
1944
+ self.get_im_features(im)
1945
+ points, labels, masks = self._prepare_prompts(
1946
+ dst_shape=self.imgsz,
1947
+ src_shape=self.batch[1][0].shape[:2],
1948
+ points=points,
1949
+ bboxes=bboxes,
1950
+ labels=labels,
1951
+ masks=masks,
1952
+ )
1953
+
1954
+ if update_memory:
1955
+ if isinstance(obj_ids, int):
1956
+ obj_ids = [obj_ids]
1957
+ assert obj_ids is not None, "obj_ids must be provided when update_memory is True"
1958
+ assert masks is not None or points is not None, (
1959
+ "bboxes, masks, or points must be provided when update_memory is True"
1960
+ )
1961
+ if points is None: # placeholder
1962
+ points = torch.zeros((len(obj_ids), 0, 2), dtype=self.torch_dtype, device=self.device)
1963
+ labels = torch.zeros((len(obj_ids), 0), dtype=torch.int32, device=self.device)
1964
+ if masks is not None:
1965
+ assert len(masks) == len(obj_ids), "masks and obj_ids must have the same length."
1966
+ assert len(points) == len(obj_ids), "points and obj_ids must have the same length."
1967
+ self.update_memory(obj_ids, points, labels, masks)
1968
+
1969
+ current_out = self.track_step()
1970
+ pred_masks, pred_scores = current_out["pred_masks"], current_out["object_score_logits"]
1971
+ # filter the masks and logits based on the object indices
1972
+ if len(self.obj_idx_set) == 0:
1973
+ raise RuntimeError("No objects have been added to the state. Please add objects before inference.")
1974
+ idx = list(self.obj_idx_set) # cls id
1975
+ pred_masks, pred_scores = pred_masks[idx], pred_scores[idx]
1976
+ # the original score are in [-32,32], and a object score larger than 0 means the object is present, we map it to [-1,1] range,
1977
+ # and use a activate function to make sure the object score logits are non-negative, so that we can use it as a mask
1978
+ pred_scores = torch.clamp_(pred_scores / 32, min=0)
1979
+ return pred_masks.flatten(0, 1), pred_scores.flatten(0, 1)
1980
+
1981
+ def get_im_features(self, img: torch.Tensor | np.ndarray) -> None:
1982
+ """Initialize the image state by processing the input image and extracting features.
1983
+
1984
+ Args:
1985
+ img (torch.Tensor | np.ndarray): The input image tensor or numpy array.
1986
+ """
1987
+ vis_feats, vis_pos_embed, feat_sizes = SAM2VideoPredictor.get_im_features(self, img, batch=self._max_obj_num)
1988
+ self.high_res_features = [
1989
+ feat.permute(1, 2, 0).view(*feat.shape[1:], *feat_size)
1990
+ for feat, feat_size in zip(vis_feats[:-1], feat_sizes[:-1])
1991
+ ]
1992
+
1993
+ self.vision_feats = vis_feats
1994
+ self.vision_pos_embeds = vis_pos_embed
1995
+ self.feat_sizes = feat_sizes
1996
+
1997
+ @smart_inference_mode()
1998
+ def update_memory(
1999
+ self,
2000
+ obj_ids: list[int] | None = None,
2001
+ points: torch.Tensor | None = None,
2002
+ labels: torch.Tensor | None = None,
2003
+ masks: torch.Tensor | None = None,
2004
+ ) -> None:
2005
+ """Append the imgState to the memory_bank and update the memory for the model.
2006
+
2007
+ Args:
2008
+ obj_ids (list[int]): List of object IDs corresponding to the prompts.
2009
+ points (torch.Tensor | None): Tensor of shape (B, N, 2) representing the input points for N objects.
2010
+ labels (torch.Tensor | None): Tensor of shape (B, N) representing the labels for the input points.
2011
+ masks (torch.Tensor | None): Optional tensor of shape (N, H, W) representing the input masks for N objects.
2012
+ """
2013
+ consolidated_out = {
2014
+ "maskmem_features": None,
2015
+ "maskmem_pos_enc": None,
2016
+ "pred_masks": torch.full(
2017
+ size=(self._max_obj_num, 1, self.imgsz[0] // 4, self.imgsz[1] // 4),
2018
+ fill_value=-1024.0,
2019
+ dtype=self.torch_dtype,
2020
+ device=self.device,
2021
+ ),
2022
+ "obj_ptr": torch.full(
2023
+ size=(self._max_obj_num, self.model.hidden_dim),
2024
+ fill_value=-1024.0,
2025
+ dtype=self.torch_dtype,
2026
+ device=self.device,
2027
+ ),
2028
+ "object_score_logits": torch.full(
2029
+ size=(self._max_obj_num, 1),
2030
+ # default to 10.0 for object_score_logits, i.e. assuming the object is
2031
+ # present as sigmoid(10)=1, same as in `predict_masks` of `MaskDecoder`
2032
+ fill_value=-32, # 10.0,
2033
+ dtype=self.torch_dtype,
2034
+ device=self.device,
2035
+ ),
2036
+ }
2037
+
2038
+ for i, obj_id in enumerate(obj_ids):
2039
+ assert obj_id < self._max_obj_num
2040
+ obj_idx = self._obj_id_to_idx(int(obj_id))
2041
+ self.obj_idx_set.add(obj_idx)
2042
+ point, label = points[[i]], labels[[i]]
2043
+ mask = masks[[i]][None] if masks is not None else None
2044
+ # Currently, only bbox prompt or mask prompt is supported, so we assert that bbox is not None.
2045
+ assert point is not None or mask is not None, "Either bbox, points or mask is required"
2046
+ out = self.track_step(obj_idx, point, label, mask)
2047
+ if out is not None:
2048
+ obj_mask = out["pred_masks"]
2049
+ assert obj_mask.shape[-2:] == consolidated_out["pred_masks"].shape[-2:], (
2050
+ f"Expected mask shape {consolidated_out['pred_masks'].shape[-2:]} but got {obj_mask.shape[-2:]} for object {obj_idx}."
2051
+ )
2052
+ consolidated_out["pred_masks"][obj_idx : obj_idx + 1] = obj_mask
2053
+ consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = out["obj_ptr"]
2054
+
2055
+ if "object_score_logits" in out.keys():
2056
+ consolidated_out["object_score_logits"][obj_idx : obj_idx + 1] = out["object_score_logits"]
2057
+
2058
+ high_res_masks = F.interpolate(
2059
+ consolidated_out["pred_masks"].to(self.device, non_blocking=self.device.type == "cuda"),
2060
+ size=self.imgsz,
2061
+ mode="bilinear",
2062
+ align_corners=False,
2063
+ )
2064
+
2065
+ if self.model.non_overlap_masks_for_mem_enc:
2066
+ high_res_masks = self.model._apply_non_overlapping_constraints(high_res_masks)
2067
+ maskmem_features, maskmem_pos_enc = self.model._encode_new_memory(
2068
+ current_vision_feats=self.vision_feats,
2069
+ feat_sizes=self.feat_sizes,
2070
+ pred_masks_high_res=high_res_masks,
2071
+ object_score_logits=consolidated_out["object_score_logits"],
2072
+ is_mask_from_pts=True,
2073
+ )
2074
+ consolidated_out["maskmem_features"] = maskmem_features
2075
+ consolidated_out["maskmem_pos_enc"] = maskmem_pos_enc
2076
+ self.memory_bank.append(consolidated_out)
2077
+
2078
+ def _prepare_memory_conditioned_features(self, obj_idx: int | None) -> torch.Tensor:
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.
2085
+
2086
+ Args:
2087
+ obj_idx (int | None): The index of the object for which to prepare the features.
2088
+
2089
+ Returns:
2090
+ pix_feat_with_mem (torch.Tensor): The memory-conditioned pixel features.
2091
+ """
2092
+ if len(self.memory_bank) == 0 or isinstance(obj_idx, int):
2093
+ # For initial conditioning frames, encode without using any previous memory.
2094
+ # Directly add the no-memory embedding (instead of using the transformer encoder).
2095
+ pix_feat_with_mem = self.vision_feats[-1] + self.model.no_mem_embed
2096
+ else:
2097
+ # for inference frames, use the memory features from previous frames
2098
+ memory, memory_pos_embed = self.get_maskmem_enc()
2099
+ pix_feat_with_mem = self.model.memory_attention(
2100
+ curr=self.vision_feats[-1:],
2101
+ curr_pos=self.vision_pos_embeds[-1:],
2102
+ memory=memory,
2103
+ memory_pos=memory_pos_embed,
2104
+ num_obj_ptr_tokens=0, # num_obj_ptr_tokens
2105
+ )
2106
+ # Reshape output (HW)BC => BCHW
2107
+ return pix_feat_with_mem.permute(1, 2, 0).view(
2108
+ self._max_obj_num,
2109
+ self.model.memory_attention.d_model,
2110
+ *self.feat_sizes[-1],
2111
+ )
2112
+
2113
+ def get_maskmem_enc(self) -> tuple[torch.Tensor, torch.Tensor]:
2114
+ """Get memory and positional encoding from memory, which is used to condition the current image features."""
2115
+ to_cat_memory, to_cat_memory_pos_embed = [], []
2116
+ for consolidated_out in self.memory_bank:
2117
+ to_cat_memory.append(consolidated_out["maskmem_features"].flatten(2).permute(2, 0, 1)) # (H*W, B, C)
2118
+ maskmem_enc = consolidated_out["maskmem_pos_enc"][-1].flatten(2).permute(2, 0, 1)
2119
+ maskmem_enc = maskmem_enc + self.model.maskmem_tpos_enc[self.model.num_maskmem - 1]
2120
+ to_cat_memory_pos_embed.append(maskmem_enc)
2121
+
2122
+ memory = torch.cat(to_cat_memory, dim=0)
2123
+ memory_pos_embed = torch.cat(to_cat_memory_pos_embed, dim=0)
2124
+ return memory, memory_pos_embed
2125
+
2126
+ def _obj_id_to_idx(self, obj_id: int) -> int | None:
2127
+ """Map client-side object id to model-side object index.
2128
+
2129
+ Args:
2130
+ obj_id (int): The client-side object ID.
2131
+
2132
+ Returns:
2133
+ (int): The model-side object index, or None if not found.
2134
+ """
2135
+ return self.obj_id_to_idx.get(obj_id, None)
2136
+
2137
+ def track_step(
2138
+ self,
2139
+ obj_idx: int | None = None,
2140
+ point: torch.Tensor | None = None,
2141
+ label: torch.Tensor | None = None,
2142
+ mask: torch.Tensor | None = None,
2143
+ ) -> dict[str, Any]:
2144
+ """Tracking step for the current image state to predict masks.
2145
+
2146
+ This method processes the image features and runs the SAM heads to predict masks. If obj_idx is provided, it
2147
+ processes the features for a specific prompted object in the image. If obj_idx is None, it processes the
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.
2150
+
2151
+ Args:
2152
+ obj_idx (int | None): The index of the object for which to predict masks. If None, it processes all objects.
2153
+ point (torch.Tensor | None): The coordinates of the points of interest with shape (N, 2).
2154
+ label (torch.Tensor | None): The labels corresponding to the points where 1 means positive clicks, 0 means
2155
+ negative clicks.
2156
+ mask (torch.Tensor | None): The mask input for the object with shape (H, W).
2157
+
2158
+ Returns:
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'.
2162
+ """
2163
+ if mask is not None and self.model.use_mask_input_as_output_without_sam:
2164
+ # When use_mask_input_as_output_without_sam=True, we directly output the mask input
2165
+ # (see it as a GT mask) without using a SAM prompt encoder + mask decoder.
2166
+ pix_feat = self.vision_feats[-1].permute(1, 2, 0)
2167
+ pix_feat = pix_feat.view(-1, self.model.memory_attention.d_model, *self.feat_sizes[-1])
2168
+ _, _, _, low_res_masks, high_res_masks, obj_ptr, object_score_logits = self.model._use_mask_as_output(mask)
2169
+ else:
2170
+ # Fuse visual features with previous memory features in the memory bank.
2171
+ pix_feat_with_mem = self._prepare_memory_conditioned_features(obj_idx)
2172
+ # If ``obj_idx`` is provided (i.e., prompts are being added), keep only the first feature map.
2173
+ pix_feat_with_mem = pix_feat_with_mem[:1] if obj_idx is not None else pix_feat_with_mem
2174
+ _, _, _, low_res_masks, high_res_masks, obj_ptr, object_score_logits = self.model._forward_sam_heads(
2175
+ backbone_features=pix_feat_with_mem,
2176
+ point_inputs={"point_coords": point, "point_labels": label} if obj_idx is not None else None,
2177
+ mask_inputs=mask,
2178
+ multimask_output=False,
2179
+ high_res_features=[feat[: pix_feat_with_mem.shape[0]] for feat in self.high_res_features],
2180
+ )
2181
+ return {
2182
+ "pred_masks": low_res_masks,
2183
+ "pred_masks_high_res": high_res_masks,
2184
+ "obj_ptr": obj_ptr,
2185
+ "object_score_logits": object_score_logits,
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