VictorLJZ commited on
Commit
55b5faf
·
1 Parent(s): fffa1c9

added MedSAM2 code locally

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. MedSAM2/efficient_track_anything/__init__.py +11 -0
  2. MedSAM2/efficient_track_anything/automatic_mask_generator.py +457 -0
  3. MedSAM2/efficient_track_anything/benchmark.py +106 -0
  4. MedSAM2/efficient_track_anything/build_efficienttam.py +222 -0
  5. MedSAM2/efficient_track_anything/configs/efficienttam_s_512x512.yaml +120 -0
  6. MedSAM2/efficient_track_anything/configs/efficienttam_ti_512x512.yaml +120 -0
  7. MedSAM2/efficient_track_anything/csrc/connected_components.cu +289 -0
  8. MedSAM2/efficient_track_anything/efficienttam_image_predictor.py +472 -0
  9. MedSAM2/efficient_track_anything/efficienttam_video_predictor.py +1223 -0
  10. MedSAM2/efficient_track_anything/efficienttam_video_predictor_npz.py +1226 -0
  11. MedSAM2/efficient_track_anything/modeling/__init__.py +5 -0
  12. MedSAM2/efficient_track_anything/modeling/backbones/__init__.py +5 -0
  13. MedSAM2/efficient_track_anything/modeling/backbones/image_encoder.py +108 -0
  14. MedSAM2/efficient_track_anything/modeling/backbones/utils.py +128 -0
  15. MedSAM2/efficient_track_anything/modeling/backbones/vitdet.py +299 -0
  16. MedSAM2/efficient_track_anything/modeling/efficienttam_base.py +911 -0
  17. MedSAM2/efficient_track_anything/modeling/efficienttam_utils.py +338 -0
  18. MedSAM2/efficient_track_anything/modeling/memory_attention.py +184 -0
  19. MedSAM2/efficient_track_anything/modeling/memory_encoder.py +185 -0
  20. MedSAM2/efficient_track_anything/modeling/position_encoding.py +239 -0
  21. MedSAM2/efficient_track_anything/modeling/sam/__init__.py +5 -0
  22. MedSAM2/efficient_track_anything/modeling/sam/mask_decoder.py +295 -0
  23. MedSAM2/efficient_track_anything/modeling/sam/prompt_encoder.py +202 -0
  24. MedSAM2/efficient_track_anything/modeling/sam/transformer.py +532 -0
  25. MedSAM2/efficient_track_anything/utils/__init__.py +5 -0
  26. MedSAM2/efficient_track_anything/utils/amg.py +348 -0
  27. MedSAM2/efficient_track_anything/utils/misc.py +347 -0
  28. MedSAM2/efficient_track_anything/utils/transforms.py +116 -0
  29. MedSAM2/sam2/__init__.py +11 -0
  30. MedSAM2/sam2/build_sam.py +207 -0
  31. MedSAM2/sam2/configs/efficientmedsam_s_512_FLARE_RECIST.yaml +357 -0
  32. MedSAM2/sam2/configs/efficientmedsam_ti_512_FLARE_RECIST.yaml +356 -0
  33. MedSAM2/sam2/configs/efficienttam_ti_512.yaml +120 -0
  34. MedSAM2/sam2/configs/sam2.1_hiera_t512.yaml +121 -0
  35. MedSAM2/sam2/configs/sam2.1_hiera_tiny512_FLARE_RECIST.yaml +342 -0
  36. MedSAM2/sam2/configs/sam2.1_hiera_tiny_finetune512.yaml +389 -0
  37. MedSAM2/sam2/csrc/connected_components.cu +289 -0
  38. MedSAM2/sam2/modeling/__init__.py +5 -0
  39. MedSAM2/sam2/modeling/backbones/__init__.py +5 -0
  40. MedSAM2/sam2/modeling/backbones/hieradet.py +317 -0
  41. MedSAM2/sam2/modeling/backbones/image_encoder.py +202 -0
  42. MedSAM2/sam2/modeling/backbones/utils.py +128 -0
  43. MedSAM2/sam2/modeling/backbones/vitdet.py +317 -0
  44. MedSAM2/sam2/modeling/efficienttam_base.py +911 -0
  45. MedSAM2/sam2/modeling/efficienttam_utils.py +338 -0
  46. MedSAM2/sam2/modeling/memory_attention.py +169 -0
  47. MedSAM2/sam2/modeling/memory_encoder.py +181 -0
  48. MedSAM2/sam2/modeling/position_encoding.py +221 -0
  49. MedSAM2/sam2/modeling/sam/__init__.py +5 -0
  50. MedSAM2/sam2/modeling/sam/mask_decoder.py +295 -0
MedSAM2/efficient_track_anything/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from hydra import initialize_config_module
8
+ from hydra.core.global_hydra import GlobalHydra
9
+
10
+ if not GlobalHydra.instance().is_initialized():
11
+ initialize_config_module("efficient_track_anything", version_base="1.2")
MedSAM2/efficient_track_anything/automatic_mask_generator.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # Adapted from https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/automatic_mask_generator.py
8
+ from typing import Any, Dict, List, Optional, Tuple
9
+
10
+ import numpy as np
11
+ import torch
12
+ from efficient_track_anything.efficienttam_image_predictor import (
13
+ EfficientTAMImagePredictor,
14
+ )
15
+
16
+ from efficient_track_anything.modeling.efficienttam_base import EfficientTAMBase
17
+ from efficient_track_anything.utils.amg import (
18
+ area_from_rle,
19
+ batch_iterator,
20
+ batched_mask_to_box,
21
+ box_xyxy_to_xywh,
22
+ build_all_layer_point_grids,
23
+ calculate_stability_score,
24
+ coco_encode_rle,
25
+ generate_crop_boxes,
26
+ is_box_near_crop_edge,
27
+ mask_to_rle_pytorch,
28
+ MaskData,
29
+ remove_small_regions,
30
+ rle_to_mask,
31
+ uncrop_boxes_xyxy,
32
+ uncrop_masks,
33
+ uncrop_points,
34
+ )
35
+ from torchvision.ops.boxes import batched_nms, box_area # type: ignore
36
+
37
+
38
+ class EfficientTAMAutomaticMaskGenerator:
39
+ def __init__(
40
+ self,
41
+ model: EfficientTAMBase,
42
+ points_per_side: Optional[int] = 32,
43
+ points_per_batch: int = 64,
44
+ pred_iou_thresh: float = 0.8,
45
+ stability_score_thresh: float = 0.95,
46
+ stability_score_offset: float = 1.0,
47
+ mask_threshold: float = 0.0,
48
+ box_nms_thresh: float = 0.7,
49
+ crop_n_layers: int = 0,
50
+ crop_nms_thresh: float = 0.7,
51
+ crop_overlap_ratio: float = 512 / 1500,
52
+ crop_n_points_downscale_factor: int = 1,
53
+ point_grids: Optional[List[np.ndarray]] = None,
54
+ min_mask_region_area: int = 0,
55
+ output_mode: str = "binary_mask",
56
+ use_m2m: bool = False,
57
+ multimask_output: bool = True,
58
+ **kwargs,
59
+ ) -> None:
60
+ """
61
+ Using an Efficient Track Anything model, generates masks for the entire image.
62
+ Generates a grid of point prompts over the image, then filters
63
+ low quality and duplicate masks. We use ViT backbone for Efficient Track Anything.
64
+
65
+ Arguments:
66
+ model (EfficientTAM): The EfficientTAM model to use for mask prediction.
67
+ points_per_side (int or None): The number of points to be sampled
68
+ along one side of the image. The total number of points is
69
+ points_per_side**2. If None, 'point_grids' must provide explicit
70
+ point sampling.
71
+ points_per_batch (int): Sets the number of points run simultaneously
72
+ by the model. Higher numbers may be faster but use more GPU memory.
73
+ pred_iou_thresh (float): A filtering threshold in [0,1], using the
74
+ model's predicted mask quality.
75
+ stability_score_thresh (float): A filtering threshold in [0,1], using
76
+ the stability of the mask under changes to the cutoff used to binarize
77
+ the model's mask predictions.
78
+ stability_score_offset (float): The amount to shift the cutoff when
79
+ calculated the stability score.
80
+ mask_threshold (float): Threshold for binarizing the mask logits
81
+ box_nms_thresh (float): The box IoU cutoff used by non-maximal
82
+ suppression to filter duplicate masks.
83
+ crop_n_layers (int): If >0, mask prediction will be run again on
84
+ crops of the image. Sets the number of layers to run, where each
85
+ layer has 2**i_layer number of image crops.
86
+ crop_nms_thresh (float): The box IoU cutoff used by non-maximal
87
+ suppression to filter duplicate masks between different crops.
88
+ crop_overlap_ratio (float): Sets the degree to which crops overlap.
89
+ In the first crop layer, crops will overlap by this fraction of
90
+ the image length. Later layers with more crops scale down this overlap.
91
+ crop_n_points_downscale_factor (int): The number of points-per-side
92
+ sampled in layer n is scaled down by crop_n_points_downscale_factor**n.
93
+ point_grids (list(np.ndarray) or None): A list over explicit grids
94
+ of points used for sampling, normalized to [0,1]. The nth grid in the
95
+ list is used in the nth crop layer. Exclusive with points_per_side.
96
+ min_mask_region_area (int): If >0, postprocessing will be applied
97
+ to remove disconnected regions and holes in masks with area smaller
98
+ than min_mask_region_area. Requires opencv.
99
+ output_mode (str): The form masks are returned in. Can be 'binary_mask',
100
+ 'uncompressed_rle', or 'coco_rle'. 'coco_rle' requires pycocotools.
101
+ For large resolutions, 'binary_mask' may consume large amounts of
102
+ memory.
103
+ use_m2m (bool): Whether to add a one step refinement using previous mask predictions.
104
+ multimask_output (bool): Whether to output multimask at each point of the grid.
105
+ """
106
+
107
+ assert (points_per_side is None) != (
108
+ point_grids is None
109
+ ), "Exactly one of points_per_side or point_grid must be provided."
110
+ if points_per_side is not None:
111
+ self.point_grids = build_all_layer_point_grids(
112
+ points_per_side,
113
+ crop_n_layers,
114
+ crop_n_points_downscale_factor,
115
+ )
116
+ elif point_grids is not None:
117
+ self.point_grids = point_grids
118
+ else:
119
+ raise ValueError("Can't have both points_per_side and point_grid be None.")
120
+
121
+ assert output_mode in [
122
+ "binary_mask",
123
+ "uncompressed_rle",
124
+ "coco_rle",
125
+ ], f"Unknown output_mode {output_mode}."
126
+ if output_mode == "coco_rle":
127
+ try:
128
+ from pycocotools import mask as mask_utils # type: ignore # noqa: F401
129
+ except ImportError as e:
130
+ print("Please install pycocotools")
131
+ raise e
132
+
133
+ self.predictor = EfficientTAMImagePredictor(
134
+ model,
135
+ max_hole_area=min_mask_region_area,
136
+ max_sprinkle_area=min_mask_region_area,
137
+ )
138
+ self.points_per_batch = points_per_batch
139
+ self.pred_iou_thresh = pred_iou_thresh
140
+ self.stability_score_thresh = stability_score_thresh
141
+ self.stability_score_offset = stability_score_offset
142
+ self.mask_threshold = mask_threshold
143
+ self.box_nms_thresh = box_nms_thresh
144
+ self.crop_n_layers = crop_n_layers
145
+ self.crop_nms_thresh = crop_nms_thresh
146
+ self.crop_overlap_ratio = crop_overlap_ratio
147
+ self.crop_n_points_downscale_factor = crop_n_points_downscale_factor
148
+ self.min_mask_region_area = min_mask_region_area
149
+ self.output_mode = output_mode
150
+ self.use_m2m = use_m2m
151
+ self.multimask_output = multimask_output
152
+
153
+ @classmethod
154
+ def from_pretrained(
155
+ cls, model_id: str, **kwargs
156
+ ) -> "EfficientTAMAutomaticMaskGenerator":
157
+ """
158
+ Load a pretrained model from the Hugging Face hub.
159
+
160
+ Arguments:
161
+ model_id (str): The Hugging Face repository ID.
162
+ **kwargs: Additional arguments to pass to the model constructor.
163
+
164
+ Returns:
165
+ (EfficientTAMAutomaticMaskGenerator): The loaded model.
166
+ """
167
+ from efficient_track_anything.build_efficienttam import build_efficienttam_hf
168
+
169
+ efficienttam_model = build_efficienttam_hf(model_id, **kwargs)
170
+ return cls(efficienttam_model, **kwargs)
171
+
172
+ @torch.no_grad()
173
+ def generate(self, image: np.ndarray) -> List[Dict[str, Any]]:
174
+ """
175
+ Generates masks for the given image.
176
+
177
+ Arguments:
178
+ image (np.ndarray): The image to generate masks for, in HWC uint8 format.
179
+
180
+ Returns:
181
+ list(dict(str, any)): A list over records for masks. Each record is
182
+ a dict containing the following keys:
183
+ segmentation (dict(str, any) or np.ndarray): The mask. If
184
+ output_mode='binary_mask', is an array of shape HW. Otherwise,
185
+ is a dictionary containing the RLE.
186
+ bbox (list(float)): The box around the mask, in XYWH format.
187
+ area (int): The area in pixels of the mask.
188
+ predicted_iou (float): The model's own prediction of the mask's
189
+ quality. This is filtered by the pred_iou_thresh parameter.
190
+ point_coords (list(list(float))): The point coordinates input
191
+ to the model to generate this mask.
192
+ stability_score (float): A measure of the mask's quality. This
193
+ is filtered on using the stability_score_thresh parameter.
194
+ crop_box (list(float)): The crop of the image used to generate
195
+ the mask, given in XYWH format.
196
+ """
197
+
198
+ # Generate masks
199
+ mask_data = self._generate_masks(image)
200
+
201
+ # Encode masks
202
+ if self.output_mode == "coco_rle":
203
+ mask_data["segmentations"] = [
204
+ coco_encode_rle(rle) for rle in mask_data["rles"]
205
+ ]
206
+ elif self.output_mode == "binary_mask":
207
+ mask_data["segmentations"] = [rle_to_mask(rle) for rle in mask_data["rles"]]
208
+ else:
209
+ mask_data["segmentations"] = mask_data["rles"]
210
+
211
+ # Write mask records
212
+ curr_anns = []
213
+ for idx in range(len(mask_data["segmentations"])):
214
+ ann = {
215
+ "segmentation": mask_data["segmentations"][idx],
216
+ "area": area_from_rle(mask_data["rles"][idx]),
217
+ "bbox": box_xyxy_to_xywh(mask_data["boxes"][idx]).tolist(),
218
+ "predicted_iou": mask_data["iou_preds"][idx].item(),
219
+ "point_coords": [mask_data["points"][idx].tolist()],
220
+ "stability_score": mask_data["stability_score"][idx].item(),
221
+ "crop_box": box_xyxy_to_xywh(mask_data["crop_boxes"][idx]).tolist(),
222
+ }
223
+ curr_anns.append(ann)
224
+
225
+ return curr_anns
226
+
227
+ def _generate_masks(self, image: np.ndarray) -> MaskData:
228
+ orig_size = image.shape[:2]
229
+ crop_boxes, layer_idxs = generate_crop_boxes(
230
+ orig_size, self.crop_n_layers, self.crop_overlap_ratio
231
+ )
232
+
233
+ # Iterate over image crops
234
+ data = MaskData()
235
+ for crop_box, layer_idx in zip(crop_boxes, layer_idxs):
236
+ crop_data = self._process_crop(image, crop_box, layer_idx, orig_size)
237
+ data.cat(crop_data)
238
+
239
+ # Remove duplicate masks between crops
240
+ if len(crop_boxes) > 1:
241
+ # Prefer masks from smaller crops
242
+ scores = 1 / box_area(data["crop_boxes"])
243
+ scores = scores.to(data["boxes"].device)
244
+ keep_by_nms = batched_nms(
245
+ data["boxes"].float(),
246
+ scores,
247
+ torch.zeros_like(data["boxes"][:, 0]), # categories
248
+ iou_threshold=self.crop_nms_thresh,
249
+ )
250
+ data.filter(keep_by_nms)
251
+ data.to_numpy()
252
+ return data
253
+
254
+ def _process_crop(
255
+ self,
256
+ image: np.ndarray,
257
+ crop_box: List[int],
258
+ crop_layer_idx: int,
259
+ orig_size: Tuple[int, ...],
260
+ ) -> MaskData:
261
+ # Crop the image and calculate embeddings
262
+ x0, y0, x1, y1 = crop_box
263
+ cropped_im = image[y0:y1, x0:x1, :]
264
+ cropped_im_size = cropped_im.shape[:2]
265
+ self.predictor.set_image(cropped_im)
266
+
267
+ # Get points for this crop
268
+ points_scale = np.array(cropped_im_size)[None, ::-1]
269
+ points_for_image = self.point_grids[crop_layer_idx] * points_scale
270
+
271
+ # Generate masks for this crop in batches
272
+ data = MaskData()
273
+ for (points,) in batch_iterator(self.points_per_batch, points_for_image):
274
+ batch_data = self._process_batch(
275
+ points, cropped_im_size, crop_box, orig_size, normalize=True
276
+ )
277
+ data.cat(batch_data)
278
+ del batch_data
279
+ self.predictor.reset_predictor()
280
+
281
+ # Remove duplicates within this crop.
282
+ keep_by_nms = batched_nms(
283
+ data["boxes"].float(),
284
+ data["iou_preds"],
285
+ torch.zeros_like(data["boxes"][:, 0]), # categories
286
+ iou_threshold=self.box_nms_thresh,
287
+ )
288
+ data.filter(keep_by_nms)
289
+
290
+ # Return to the original image frame
291
+ data["boxes"] = uncrop_boxes_xyxy(data["boxes"], crop_box)
292
+ data["points"] = uncrop_points(data["points"], crop_box)
293
+ data["crop_boxes"] = torch.tensor([crop_box for _ in range(len(data["rles"]))])
294
+
295
+ return data
296
+
297
+ def _process_batch(
298
+ self,
299
+ points: np.ndarray,
300
+ im_size: Tuple[int, ...],
301
+ crop_box: List[int],
302
+ orig_size: Tuple[int, ...],
303
+ normalize=False,
304
+ ) -> MaskData:
305
+ orig_h, orig_w = orig_size
306
+
307
+ # Run model on this batch
308
+ points = torch.as_tensor(
309
+ points, dtype=torch.float32, device=self.predictor.device
310
+ )
311
+ in_points = self.predictor._transforms.transform_coords(
312
+ points, normalize=normalize, orig_hw=im_size
313
+ )
314
+ in_labels = torch.ones(
315
+ in_points.shape[0], dtype=torch.int, device=in_points.device
316
+ )
317
+ masks, iou_preds, low_res_masks = self.predictor._predict(
318
+ in_points[:, None, :],
319
+ in_labels[:, None],
320
+ multimask_output=self.multimask_output,
321
+ return_logits=True,
322
+ )
323
+
324
+ # Serialize predictions and store in MaskData
325
+ data = MaskData(
326
+ masks=masks.flatten(0, 1),
327
+ iou_preds=iou_preds.flatten(0, 1),
328
+ points=points.repeat_interleave(masks.shape[1], dim=0),
329
+ low_res_masks=low_res_masks.flatten(0, 1),
330
+ )
331
+ del masks
332
+
333
+ if not self.use_m2m:
334
+ # Filter by predicted IoU
335
+ if self.pred_iou_thresh > 0.0:
336
+ keep_mask = data["iou_preds"] > self.pred_iou_thresh
337
+ data.filter(keep_mask)
338
+
339
+ # Calculate and filter by stability score
340
+ data["stability_score"] = calculate_stability_score(
341
+ data["masks"], self.mask_threshold, self.stability_score_offset
342
+ )
343
+ if self.stability_score_thresh > 0.0:
344
+ keep_mask = data["stability_score"] >= self.stability_score_thresh
345
+ data.filter(keep_mask)
346
+ else:
347
+ # One step refinement using previous mask predictions
348
+ in_points = self.predictor._transforms.transform_coords(
349
+ data["points"], normalize=normalize, orig_hw=im_size
350
+ )
351
+ labels = torch.ones(
352
+ in_points.shape[0], dtype=torch.int, device=in_points.device
353
+ )
354
+ masks, ious = self.refine_with_m2m(
355
+ in_points, labels, data["low_res_masks"], self.points_per_batch
356
+ )
357
+ data["masks"] = masks.squeeze(1)
358
+ data["iou_preds"] = ious.squeeze(1)
359
+
360
+ if self.pred_iou_thresh > 0.0:
361
+ keep_mask = data["iou_preds"] > self.pred_iou_thresh
362
+ data.filter(keep_mask)
363
+
364
+ data["stability_score"] = calculate_stability_score(
365
+ data["masks"], self.mask_threshold, self.stability_score_offset
366
+ )
367
+ if self.stability_score_thresh > 0.0:
368
+ keep_mask = data["stability_score"] >= self.stability_score_thresh
369
+ data.filter(keep_mask)
370
+
371
+ # Threshold masks and calculate boxes
372
+ data["masks"] = data["masks"] > self.mask_threshold
373
+ data["boxes"] = batched_mask_to_box(data["masks"])
374
+
375
+ # Filter boxes that touch crop boundaries
376
+ keep_mask = ~is_box_near_crop_edge(
377
+ data["boxes"], crop_box, [0, 0, orig_w, orig_h]
378
+ )
379
+ if not torch.all(keep_mask):
380
+ data.filter(keep_mask)
381
+
382
+ # Compress to RLE
383
+ data["masks"] = uncrop_masks(data["masks"], crop_box, orig_h, orig_w)
384
+ data["rles"] = mask_to_rle_pytorch(data["masks"])
385
+ del data["masks"]
386
+
387
+ return data
388
+
389
+ @staticmethod
390
+ def postprocess_small_regions(
391
+ mask_data: MaskData, min_area: int, nms_thresh: float
392
+ ) -> MaskData:
393
+ """
394
+ Removes small disconnected regions and holes in masks, then reruns
395
+ box NMS to remove any new duplicates.
396
+
397
+ Edits mask_data in place.
398
+
399
+ Requires open-cv as a dependency.
400
+ """
401
+ if len(mask_data["rles"]) == 0:
402
+ return mask_data
403
+
404
+ # Filter small disconnected regions and holes
405
+ new_masks = []
406
+ scores = []
407
+ for rle in mask_data["rles"]:
408
+ mask = rle_to_mask(rle)
409
+
410
+ mask, changed = remove_small_regions(mask, min_area, mode="holes")
411
+ unchanged = not changed
412
+ mask, changed = remove_small_regions(mask, min_area, mode="islands")
413
+ unchanged = unchanged and not changed
414
+
415
+ new_masks.append(torch.as_tensor(mask).unsqueeze(0))
416
+ # Give score=0 to changed masks and score=1 to unchanged masks
417
+ # so NMS will prefer ones that didn't need postprocessing
418
+ scores.append(float(unchanged))
419
+
420
+ # Recalculate boxes and remove any new duplicates
421
+ masks = torch.cat(new_masks, dim=0)
422
+ boxes = batched_mask_to_box(masks)
423
+ keep_by_nms = batched_nms(
424
+ boxes.float(),
425
+ torch.as_tensor(scores),
426
+ torch.zeros_like(boxes[:, 0]), # categories
427
+ iou_threshold=nms_thresh,
428
+ )
429
+
430
+ # Only recalculate RLEs for masks that have changed
431
+ for i_mask in keep_by_nms:
432
+ if scores[i_mask] == 0.0:
433
+ mask_torch = masks[i_mask].unsqueeze(0)
434
+ mask_data["rles"][i_mask] = mask_to_rle_pytorch(mask_torch)[0]
435
+ mask_data["boxes"][i_mask] = boxes[i_mask] # update res directly
436
+ mask_data.filter(keep_by_nms)
437
+
438
+ return mask_data
439
+
440
+ def refine_with_m2m(self, points, point_labels, low_res_masks, points_per_batch):
441
+ new_masks = []
442
+ new_iou_preds = []
443
+
444
+ for cur_points, cur_point_labels, low_res_mask in batch_iterator(
445
+ points_per_batch, points, point_labels, low_res_masks
446
+ ):
447
+ best_masks, best_iou_preds, _ = self.predictor._predict(
448
+ cur_points[:, None, :],
449
+ cur_point_labels[:, None],
450
+ mask_input=low_res_mask[:, None, :],
451
+ multimask_output=False,
452
+ return_logits=True,
453
+ )
454
+ new_masks.append(best_masks)
455
+ new_iou_preds.append(best_iou_preds)
456
+ masks = torch.cat(new_masks, dim=0)
457
+ return masks, torch.cat(new_iou_preds, dim=0)
MedSAM2/efficient_track_anything/benchmark.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # Adapted from https://github.com/facebookresearch/sam2/blob/main/sam2/benchmark.py
8
+
9
+ import os
10
+ import time
11
+
12
+ import numpy as np
13
+ import torch
14
+
15
+ from efficient_track_anything.build_efficienttam import (
16
+ build_efficienttam_video_predictor,
17
+ )
18
+ from tqdm import tqdm
19
+
20
+ if torch.cuda.is_available():
21
+ device = torch.device("cuda")
22
+ torch.autocast(device_type="cuda", dtype=torch.bfloat16).__enter__()
23
+ if torch.cuda.get_device_properties(0).major >= 8:
24
+ # turn on tfloat32 for Ampere GPUs (https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices)
25
+ torch.backends.cuda.matmul.allow_tf32 = True
26
+ torch.backends.cudnn.allow_tf32 = True
27
+ elif torch.mps.is_available():
28
+ device = torch.device("mps")
29
+ else:
30
+ raise RuntimeError("No CUDA or MPS device found")
31
+
32
+ # Config and checkpoint
33
+ # model_cfg = "configs/efficienttam/efficienttam_s.yaml"
34
+ # model_cfg = "configs/efficienttam/efficienttam_s_1.yaml"
35
+ # model_cfg = "configs/efficienttam/efficienttam_s_2.yaml"
36
+ model_cfg = "configs/efficienttam/efficienttam_s_512x512.yaml"
37
+ # model_cfg = "configs/efficienttam/efficienttam_ti.yaml"
38
+ # model_cfg = "configs/efficienttam/efficienttam_ti_1.yaml"
39
+ # model_cfg = "configs/efficienttam/efficienttam_ti_2.yaml"
40
+ # model_cfg = "configs/efficienttam/efficienttam_ti_512x512.yaml"
41
+ efficienttam_checkpoint = None
42
+
43
+ # Build video predictor with vos_optimized=True setting
44
+ predictor = build_efficienttam_video_predictor(
45
+ model_cfg, efficienttam_checkpoint, device=device, vos_optimized=True
46
+ )
47
+
48
+ model_total_params = sum(p.numel() for p in predictor.parameters())
49
+ print("Model Size: ", model_total_params)
50
+
51
+ # Initialize with video
52
+ video_dir = "notebooks/videos/bedroom"
53
+ # scan all the JPEG frame names in this directory
54
+ frame_names = [
55
+ p
56
+ for p in os.listdir(video_dir)
57
+ if os.path.splitext(p)[-1] in [".jpg", ".jpeg", ".JPG", ".JPEG"]
58
+ ]
59
+ frame_names.sort(key=lambda p: int(os.path.splitext(p)[0]))
60
+ inference_state = predictor.init_state(video_path=video_dir)
61
+
62
+
63
+ # Number of runs, warmup etc
64
+ warm_up, runs = 5, 25
65
+ verbose = True
66
+ num_frames = len(frame_names)
67
+ total, count = 0, 0
68
+ torch.cuda.empty_cache()
69
+
70
+ # We will select an object with a click.
71
+ # See video_predictor_example.ipynb for more detailed explanation
72
+ ann_frame_idx, ann_obj_id = 0, 1
73
+ # Add a positive click at (x, y) = (210, 350)
74
+ # For labels, `1` means positive click
75
+ points = np.array([[210, 350]], dtype=np.float32)
76
+ labels = np.array([1], np.int32)
77
+
78
+ _, out_obj_ids, out_mask_logits = predictor.add_new_points_or_box(
79
+ inference_state=inference_state,
80
+ frame_idx=ann_frame_idx,
81
+ obj_id=ann_obj_id,
82
+ points=points,
83
+ labels=labels,
84
+ )
85
+
86
+ # Warmup and then average FPS over several runs
87
+ with torch.inference_mode():
88
+ for i in tqdm(range(runs), disable=not verbose, desc="Benchmarking"):
89
+ start = time.time()
90
+ # Start tracking
91
+ for (
92
+ out_frame_idx,
93
+ out_obj_ids,
94
+ out_mask_logits,
95
+ ) in predictor.propagate_in_video(inference_state):
96
+ pass
97
+
98
+ end = time.time()
99
+ total += end - start
100
+ count += 1
101
+ if i == warm_up - 1:
102
+ print("Warmup FPS: ", count * num_frames / total)
103
+ total = 0
104
+ count = 0
105
+
106
+ print("FPS: ", count * num_frames / total)
MedSAM2/efficient_track_anything/build_efficienttam.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import logging
8
+ import os
9
+
10
+ import efficient_track_anything
11
+
12
+ import torch
13
+ from hydra import compose
14
+ from hydra.utils import instantiate
15
+ from omegaconf import OmegaConf
16
+
17
+ if os.path.isdir(
18
+ os.path.join(efficient_track_anything.__path__[0], "efficient_track_anything")
19
+ ):
20
+ raise RuntimeError(
21
+ "You're likely running Python from the parent directory of the EfficientTAM repository "
22
+ )
23
+
24
+ # Working on putting efficient track anything models on Facebook Hugging Face Hub.
25
+ # This is just for demonstration.
26
+ # Please download efficient track anything models from https://huggingface.co/yunyangx/efficient-track-anything.
27
+ # and use build_efficienttam/build_efficienttam_video_predictor for loading them.
28
+ HF_MODEL_ID_TO_FILENAMES = {
29
+ "facebook/efficienttam_s": (
30
+ "configs/efficienttam/efficienttam_s.yaml",
31
+ "efficienttam_s.pt",
32
+ ),
33
+ "facebook/efficienttam_s_512x512": (
34
+ "configs/efficienttam/efficienttam_s_512x512.yaml",
35
+ "efficienttam_s_512x512.pt",
36
+ ),
37
+ "facebook/efficienttam_s_1": (
38
+ "configs/efficienttam/efficienttam_s_1.yaml",
39
+ "efficienttam_s_1.pt",
40
+ ),
41
+ "facebook/efficienttam_s_2": (
42
+ "configs/efficienttam/efficienttam_s_2.yaml",
43
+ "efficienttam_s_2.pt",
44
+ ),
45
+ "facebook/efficienttam_ti": (
46
+ "configs/efficienttam/efficienttam_ti.yaml",
47
+ "efficienttam_ti.pt",
48
+ ),
49
+ "facebook/efficienttam_ti_512x512": (
50
+ "configs/efficienttam/efficienttam_ti_512x512.yaml",
51
+ "efficienttam_ti_512x512.pt",
52
+ ),
53
+ "facebook/efficienttam_ti_1": (
54
+ "configs/efficienttam/efficienttam_ti_1.yaml",
55
+ "efficienttam_ti_1.pt",
56
+ ),
57
+ "facebook/efficienttam_ti_2": (
58
+ "configs/efficienttam/efficienttam_ti_2.yaml",
59
+ "efficienttam_ti_2.pt",
60
+ ),
61
+ }
62
+
63
+
64
+ def build_efficienttam(
65
+ config_file,
66
+ ckpt_path=None,
67
+ device="cuda",
68
+ mode="eval",
69
+ hydra_overrides_extra=[],
70
+ apply_postprocessing=True,
71
+ **kwargs,
72
+ ):
73
+
74
+ if apply_postprocessing:
75
+ hydra_overrides_extra = hydra_overrides_extra.copy()
76
+ hydra_overrides_extra += [
77
+ # dynamically fall back to multi-mask if the single mask is not stable
78
+ "++model.sam_mask_decoder_extra_args.dynamic_multimask_via_stability=true",
79
+ "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_delta=0.05",
80
+ "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_thresh=0.98",
81
+ ]
82
+ # Read config and init model
83
+ cfg = compose(config_name=config_file, overrides=hydra_overrides_extra)
84
+ OmegaConf.resolve(cfg)
85
+ model = instantiate(cfg.model, _recursive_=True)
86
+ _load_checkpoint(model, ckpt_path)
87
+ model = model.to(device)
88
+ if mode == "eval":
89
+ model.eval()
90
+ return model
91
+
92
+
93
+ def build_efficienttam_video_predictor(
94
+ config_file,
95
+ ckpt_path=None,
96
+ device="cuda",
97
+ mode="eval",
98
+ hydra_overrides_extra=[],
99
+ apply_postprocessing=True,
100
+ vos_optimized=False,
101
+ **kwargs,
102
+ ):
103
+ if not torch.cuda.is_available() or torch.cuda.get_device_properties(0).major < 8:
104
+ print("Disable torch compile due to unsupported GPU.")
105
+ hydra_overrides_extra = ["++model.compile_image_encoder=False"]
106
+ vos_optimized = False
107
+
108
+ hydra_overrides = [
109
+ "++model._target_=efficient_track_anything.efficienttam_video_predictor.EfficientTAMVideoPredictor",
110
+ ]
111
+ if vos_optimized:
112
+ hydra_overrides = [
113
+ "++model._target_=efficient_track_anything.efficienttam_video_predictor.EfficientTAMVideoPredictorVOS",
114
+ "++model.compile_image_encoder=True", # Let efficienttam_base handle this
115
+ ]
116
+
117
+ if apply_postprocessing:
118
+ hydra_overrides_extra = hydra_overrides_extra.copy()
119
+ hydra_overrides_extra += [
120
+ # dynamically fall back to multi-mask if the single mask is not stable
121
+ "++model.sam_mask_decoder_extra_args.dynamic_multimask_via_stability=true",
122
+ "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_delta=0.05",
123
+ "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_thresh=0.98",
124
+ # the sigmoid mask logits on interacted frames with clicks in the memory encoder so that the encoded masks are exactly as what users see from clicking
125
+ "++model.binarize_mask_from_pts_for_mem_enc=true",
126
+ # fill small holes in the low-res masks up to `fill_hole_area` (before resizing them to the original video resolution)
127
+ "++model.fill_hole_area=8",
128
+ ]
129
+ hydra_overrides.extend(hydra_overrides_extra)
130
+
131
+ # Read config and init model
132
+ cfg = compose(config_name=config_file, overrides=hydra_overrides)
133
+ OmegaConf.resolve(cfg)
134
+ model = instantiate(cfg.model, _recursive_=True)
135
+ if ckpt_path is not None:
136
+ _load_checkpoint(model, ckpt_path)
137
+ model = model.to(device)
138
+ if mode == "eval":
139
+ model.eval()
140
+ return model
141
+
142
+
143
+ def _hf_download(model_id):
144
+ from huggingface_hub import hf_hub_download
145
+
146
+ config_name, checkpoint_name = HF_MODEL_ID_TO_FILENAMES[model_id]
147
+ ckpt_path = hf_hub_download(repo_id=model_id, filename=checkpoint_name)
148
+ return config_name, ckpt_path
149
+
150
+
151
+ def build_efficienttam_hf(model_id, **kwargs):
152
+ config_name, ckpt_path = _hf_download(model_id)
153
+ return build_efficienttam(config_file=config_name, ckpt_path=ckpt_path, **kwargs)
154
+
155
+
156
+ def build_efficienttam_video_predictor_hf(model_id, **kwargs):
157
+ config_name, ckpt_path = _hf_download(model_id)
158
+ return build_efficienttam_video_predictor(
159
+ config_file=config_name, ckpt_path=ckpt_path, **kwargs
160
+ )
161
+
162
+
163
+ def _load_checkpoint(model, ckpt_path):
164
+ if ckpt_path is not None:
165
+ sd = torch.load(ckpt_path, map_location="cpu", weights_only=True)["model"]
166
+ missing_keys, unexpected_keys = model.load_state_dict(sd)
167
+ if missing_keys:
168
+ logging.error(missing_keys)
169
+ raise RuntimeError()
170
+ if unexpected_keys:
171
+ logging.error(unexpected_keys)
172
+ raise RuntimeError()
173
+ logging.info("Loaded checkpoint sucessfully")
174
+
175
+ def build_efficienttam_video_predictor_npz(
176
+ config_file,
177
+ ckpt_path=None,
178
+ device="cuda",
179
+ mode="eval",
180
+ hydra_overrides_extra=[],
181
+ apply_postprocessing=True,
182
+ vos_optimized=False,
183
+ **kwargs,
184
+ ):
185
+ if not torch.cuda.is_available() or torch.cuda.get_device_properties(0).major < 8:
186
+ print("Disable torch compile due to unsupported GPU.")
187
+ hydra_overrides_extra = ["++model.compile_image_encoder=False"]
188
+ vos_optimized = False
189
+
190
+ hydra_overrides = [
191
+ "++model._target_=efficient_track_anything.efficienttam_video_predictor_npz.EfficientTAMVideoPredictorNPZ",
192
+ ]
193
+ if vos_optimized:
194
+ hydra_overrides = [
195
+ "++model._target_=efficient_track_anything.efficienttam_video_predictor_npz.EfficientTAMVideoPredictorVOSNPZ",
196
+ "++model.compile_image_encoder=True", # Let efficienttam_base handle this
197
+ ]
198
+
199
+ if apply_postprocessing:
200
+ hydra_overrides_extra = hydra_overrides_extra.copy()
201
+ hydra_overrides_extra += [
202
+ # dynamically fall back to multi-mask if the single mask is not stable
203
+ "++model.sam_mask_decoder_extra_args.dynamic_multimask_via_stability=true",
204
+ "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_delta=0.05",
205
+ "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_thresh=0.98",
206
+ # the sigmoid mask logits on interacted frames with clicks in the memory encoder so that the encoded masks are exactly as what users see from clicking
207
+ "++model.binarize_mask_from_pts_for_mem_enc=true",
208
+ # fill small holes in the low-res masks up to `fill_hole_area` (before resizing them to the original video resolution)
209
+ "++model.fill_hole_area=8",
210
+ ]
211
+ hydra_overrides.extend(hydra_overrides_extra)
212
+
213
+ # Read config and init model
214
+ cfg = compose(config_name=config_file, overrides=hydra_overrides)
215
+ OmegaConf.resolve(cfg)
216
+ model = instantiate(cfg.model, _recursive_=True)
217
+ if ckpt_path is not None:
218
+ _load_checkpoint(model, ckpt_path)
219
+ model = model.to(device)
220
+ if mode == "eval":
221
+ model.eval()
222
+ return model
MedSAM2/efficient_track_anything/configs/efficienttam_s_512x512.yaml ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+
3
+ # Model
4
+ model:
5
+ _target_: efficient_track_anything.modeling.efficienttam_base.EfficientTAMBase
6
+ image_encoder:
7
+ _target_: efficient_track_anything.modeling.backbones.image_encoder.ImageEncoder
8
+ scalp: 0
9
+ trunk:
10
+ _target_: efficient_track_anything.modeling.backbones.vitdet.ViT
11
+ patch_size: 16
12
+ embed_dim: 384
13
+ depth: 12
14
+ num_heads: 6
15
+ mlp_ratio: 4.0
16
+ qkv_bias: true
17
+ drop_path_rate: 0.0
18
+ use_rel_pos: false
19
+ window_size: 14
20
+ window_block_indexes: [0, 1, 3, 4, 6, 7, 9, 10]
21
+ neck:
22
+ _target_: efficient_track_anything.modeling.backbones.image_encoder.ViTDetNeck
23
+ position_encoding:
24
+ _target_: efficient_track_anything.modeling.position_encoding.PositionEmbeddingSine
25
+ num_pos_feats: 256
26
+ normalize: true
27
+ scale: null
28
+ temperature: 10000
29
+ d_model: 256
30
+ backbone_channel_list: [384,]
31
+ neck_norm: LN
32
+
33
+ memory_attention:
34
+ _target_: efficient_track_anything.modeling.memory_attention.MemoryAttention
35
+ d_model: 256
36
+ pos_enc_at_input: true
37
+ layer:
38
+ _target_: efficient_track_anything.modeling.memory_attention.MemoryAttentionLayer
39
+ activation: relu
40
+ dim_feedforward: 2048
41
+ dropout: 0.1
42
+ pos_enc_at_attn: false
43
+ self_attention:
44
+ _target_: efficient_track_anything.modeling.sam.transformer.RoPEAttention
45
+ rope_theta: 10000.0
46
+ feat_sizes: [32, 32]
47
+ embedding_dim: 256
48
+ num_heads: 1
49
+ downsample_rate: 1
50
+ dropout: 0.1
51
+ d_model: 256
52
+ pos_enc_at_cross_attn_keys: true
53
+ pos_enc_at_cross_attn_queries: false
54
+ cross_attention:
55
+ _target_: efficient_track_anything.modeling.sam.transformer.RoPEAttention
56
+ rope_theta: 10000.0
57
+ feat_sizes: [32, 32]
58
+ rope_k_repeat: True
59
+ embedding_dim: 256
60
+ num_heads: 1
61
+ downsample_rate: 1
62
+ dropout: 0.1
63
+ kv_in_dim: 64
64
+ num_layers: 4
65
+
66
+ memory_encoder:
67
+ _target_: efficient_track_anything.modeling.memory_encoder.MemoryEncoder
68
+ out_dim: 64
69
+ position_encoding:
70
+ _target_: efficient_track_anything.modeling.position_encoding.PositionEmbeddingSine
71
+ num_pos_feats: 64
72
+ normalize: true
73
+ scale: null
74
+ temperature: 10000
75
+ mask_downsampler:
76
+ _target_: efficient_track_anything.modeling.memory_encoder.MaskDownSampler
77
+ kernel_size: 3
78
+ stride: 2
79
+ padding: 1
80
+ fuser:
81
+ _target_: efficient_track_anything.modeling.memory_encoder.Fuser
82
+ layer:
83
+ _target_: efficient_track_anything.modeling.memory_encoder.CXBlock
84
+ dim: 256
85
+ kernel_size: 7
86
+ padding: 3
87
+ layer_scale_init_value: 1e-6
88
+ use_dwconv: True # depth-wise convs
89
+ num_layers: 2
90
+
91
+ num_maskmem: 7
92
+ image_size: 512
93
+ # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask
94
+ # SAM decoder
95
+ sigmoid_scale_for_mem_enc: 20.0
96
+ sigmoid_bias_for_mem_enc: -10.0
97
+ use_mask_input_as_output_without_sam: true
98
+ # Memory
99
+ directly_add_no_mem_embed: true
100
+ use_high_res_features_in_sam: false
101
+ # output 3 masks on the first click on initial conditioning frames
102
+ multimask_output_in_sam: true
103
+ # SAM heads
104
+ iou_prediction_use_sigmoid: True
105
+ # cross-attend to object pointers from other frames in the ViT encoder
106
+ use_obj_ptrs_in_encoder: true
107
+ add_tpos_enc_to_obj_ptrs: false
108
+ only_obj_ptrs_in_the_past_for_eval: true
109
+ # object occlusion prediction
110
+ pred_obj_scores: true
111
+ pred_obj_scores_mlp: true
112
+ fixed_no_obj_ptr: true
113
+ # multimask tracking settings
114
+ multimask_output_for_tracking: true
115
+ use_multimask_token_for_obj_ptr: true
116
+ multimask_min_pt_num: 0
117
+ multimask_max_pt_num: 1
118
+ use_mlp_for_obj_ptr_proj: true
119
+ # Compilation flag
120
+ compile_image_encoder: true
MedSAM2/efficient_track_anything/configs/efficienttam_ti_512x512.yaml ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+
3
+ # Model
4
+ model:
5
+ _target_: efficient_track_anything.modeling.efficienttam_base.EfficientTAMBase
6
+ image_encoder:
7
+ _target_: efficient_track_anything.modeling.backbones.image_encoder.ImageEncoder
8
+ scalp: 0
9
+ trunk:
10
+ _target_: efficient_track_anything.modeling.backbones.vitdet.ViT
11
+ patch_size: 16
12
+ embed_dim: 192
13
+ depth: 12
14
+ num_heads: 3
15
+ mlp_ratio: 4.0
16
+ qkv_bias: true
17
+ drop_path_rate: 0.0
18
+ use_rel_pos: false
19
+ window_size: 14
20
+ window_block_indexes: [0, 1, 3, 4, 6, 7, 9, 10]
21
+ neck:
22
+ _target_: efficient_track_anything.modeling.backbones.image_encoder.ViTDetNeck
23
+ position_encoding:
24
+ _target_: efficient_track_anything.modeling.position_encoding.PositionEmbeddingSine
25
+ num_pos_feats: 256
26
+ normalize: true
27
+ scale: null
28
+ temperature: 10000
29
+ d_model: 256
30
+ backbone_channel_list: [192,]
31
+ neck_norm: LN
32
+
33
+ memory_attention:
34
+ _target_: efficient_track_anything.modeling.memory_attention.MemoryAttention
35
+ d_model: 256
36
+ pos_enc_at_input: true
37
+ layer:
38
+ _target_: efficient_track_anything.modeling.memory_attention.MemoryAttentionLayer
39
+ activation: relu
40
+ dim_feedforward: 2048
41
+ dropout: 0.1
42
+ pos_enc_at_attn: false
43
+ self_attention:
44
+ _target_: efficient_track_anything.modeling.sam.transformer.RoPEAttention
45
+ rope_theta: 10000.0
46
+ feat_sizes: [32, 32]
47
+ embedding_dim: 256
48
+ num_heads: 1
49
+ downsample_rate: 1
50
+ dropout: 0.1
51
+ d_model: 256
52
+ pos_enc_at_cross_attn_keys: true
53
+ pos_enc_at_cross_attn_queries: false
54
+ cross_attention:
55
+ _target_: efficient_track_anything.modeling.sam.transformer.RoPEAttention
56
+ rope_theta: 10000.0
57
+ feat_sizes: [32, 32]
58
+ rope_k_repeat: True
59
+ embedding_dim: 256
60
+ num_heads: 1
61
+ downsample_rate: 1
62
+ dropout: 0.1
63
+ kv_in_dim: 64
64
+ num_layers: 4
65
+
66
+ memory_encoder:
67
+ _target_: efficient_track_anything.modeling.memory_encoder.MemoryEncoder
68
+ out_dim: 64
69
+ position_encoding:
70
+ _target_: efficient_track_anything.modeling.position_encoding.PositionEmbeddingSine
71
+ num_pos_feats: 64
72
+ normalize: true
73
+ scale: null
74
+ temperature: 10000
75
+ mask_downsampler:
76
+ _target_: efficient_track_anything.modeling.memory_encoder.MaskDownSampler
77
+ kernel_size: 3
78
+ stride: 2
79
+ padding: 1
80
+ fuser:
81
+ _target_: efficient_track_anything.modeling.memory_encoder.Fuser
82
+ layer:
83
+ _target_: efficient_track_anything.modeling.memory_encoder.CXBlock
84
+ dim: 256
85
+ kernel_size: 7
86
+ padding: 3
87
+ layer_scale_init_value: 1e-6
88
+ use_dwconv: True # depth-wise convs
89
+ num_layers: 2
90
+
91
+ num_maskmem: 7
92
+ image_size: 512
93
+ # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask
94
+ # SAM decoder
95
+ sigmoid_scale_for_mem_enc: 20.0
96
+ sigmoid_bias_for_mem_enc: -10.0
97
+ use_mask_input_as_output_without_sam: true
98
+ # Memory
99
+ directly_add_no_mem_embed: true
100
+ use_high_res_features_in_sam: false
101
+ # output 3 masks on the first click on initial conditioning frames
102
+ multimask_output_in_sam: true
103
+ # SAM heads
104
+ iou_prediction_use_sigmoid: True
105
+ # cross-attend to object pointers from other frames in the ViT encoder
106
+ use_obj_ptrs_in_encoder: true
107
+ add_tpos_enc_to_obj_ptrs: false
108
+ only_obj_ptrs_in_the_past_for_eval: true
109
+ # object occlusion prediction
110
+ pred_obj_scores: true
111
+ pred_obj_scores_mlp: true
112
+ fixed_no_obj_ptr: true
113
+ # multimask tracking settings
114
+ multimask_output_for_tracking: true
115
+ use_multimask_token_for_obj_ptr: true
116
+ multimask_min_pt_num: 0
117
+ multimask_max_pt_num: 1
118
+ use_mlp_for_obj_ptr_proj: true
119
+ # Compilation flag
120
+ compile_image_encoder: true
MedSAM2/efficient_track_anything/csrc/connected_components.cu ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ // All rights reserved.
3
+
4
+ // This source code is licensed under the license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ // adapted from https://github.com/zsef123/Connected_components_PyTorch
8
+ // with license found in the LICENSE_cctorch file in the root directory.
9
+ #include <ATen/cuda/CUDAContext.h>
10
+ #include <cuda.h>
11
+ #include <cuda_runtime.h>
12
+ #include <torch/extension.h>
13
+ #include <torch/script.h>
14
+ #include <vector>
15
+
16
+ // 2d
17
+ #define BLOCK_ROWS 16
18
+ #define BLOCK_COLS 16
19
+
20
+ namespace cc2d {
21
+
22
+ template <typename T>
23
+ __device__ __forceinline__ unsigned char hasBit(T bitmap, unsigned char pos) {
24
+ return (bitmap >> pos) & 1;
25
+ }
26
+
27
+ __device__ int32_t find(const int32_t* s_buf, int32_t n) {
28
+ while (s_buf[n] != n)
29
+ n = s_buf[n];
30
+ return n;
31
+ }
32
+
33
+ __device__ int32_t find_n_compress(int32_t* s_buf, int32_t n) {
34
+ const int32_t id = n;
35
+ while (s_buf[n] != n) {
36
+ n = s_buf[n];
37
+ s_buf[id] = n;
38
+ }
39
+ return n;
40
+ }
41
+
42
+ __device__ void union_(int32_t* s_buf, int32_t a, int32_t b) {
43
+ bool done;
44
+ do {
45
+ a = find(s_buf, a);
46
+ b = find(s_buf, b);
47
+
48
+ if (a < b) {
49
+ int32_t old = atomicMin(s_buf + b, a);
50
+ done = (old == b);
51
+ b = old;
52
+ } else if (b < a) {
53
+ int32_t old = atomicMin(s_buf + a, b);
54
+ done = (old == a);
55
+ a = old;
56
+ } else
57
+ done = true;
58
+
59
+ } while (!done);
60
+ }
61
+
62
+ __global__ void
63
+ init_labeling(int32_t* label, const uint32_t W, const uint32_t H) {
64
+ const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y) * 2;
65
+ const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x) * 2;
66
+ const uint32_t idx = row * W + col;
67
+
68
+ if (row < H && col < W)
69
+ label[idx] = idx;
70
+ }
71
+
72
+ __global__ void
73
+ merge(uint8_t* img, int32_t* label, const uint32_t W, const uint32_t H) {
74
+ const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y) * 2;
75
+ const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x) * 2;
76
+ const uint32_t idx = row * W + col;
77
+
78
+ if (row >= H || col >= W)
79
+ return;
80
+
81
+ uint32_t P = 0;
82
+
83
+ if (img[idx])
84
+ P |= 0x777;
85
+ if (row + 1 < H && img[idx + W])
86
+ P |= 0x777 << 4;
87
+ if (col + 1 < W && img[idx + 1])
88
+ P |= 0x777 << 1;
89
+
90
+ if (col == 0)
91
+ P &= 0xEEEE;
92
+ if (col + 1 >= W)
93
+ P &= 0x3333;
94
+ else if (col + 2 >= W)
95
+ P &= 0x7777;
96
+
97
+ if (row == 0)
98
+ P &= 0xFFF0;
99
+ if (row + 1 >= H)
100
+ P &= 0xFF;
101
+
102
+ if (P > 0) {
103
+ // If need check about top-left pixel(if flag the first bit) and hit the
104
+ // top-left pixel
105
+ if (hasBit(P, 0) && img[idx - W - 1]) {
106
+ union_(label, idx, idx - 2 * W - 2); // top left block
107
+ }
108
+
109
+ if ((hasBit(P, 1) && img[idx - W]) || (hasBit(P, 2) && img[idx - W + 1]))
110
+ union_(label, idx, idx - 2 * W); // top bottom block
111
+
112
+ if (hasBit(P, 3) && img[idx + 2 - W])
113
+ union_(label, idx, idx - 2 * W + 2); // top right block
114
+
115
+ if ((hasBit(P, 4) && img[idx - 1]) || (hasBit(P, 8) && img[idx + W - 1]))
116
+ union_(label, idx, idx - 2); // just left block
117
+ }
118
+ }
119
+
120
+ __global__ void compression(int32_t* label, const int32_t W, const int32_t H) {
121
+ const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y) * 2;
122
+ const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x) * 2;
123
+ const uint32_t idx = row * W + col;
124
+
125
+ if (row < H && col < W)
126
+ find_n_compress(label, idx);
127
+ }
128
+
129
+ __global__ void final_labeling(
130
+ const uint8_t* img,
131
+ int32_t* label,
132
+ const int32_t W,
133
+ const int32_t H) {
134
+ const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y) * 2;
135
+ const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x) * 2;
136
+ const uint32_t idx = row * W + col;
137
+
138
+ if (row >= H || col >= W)
139
+ return;
140
+
141
+ int32_t y = label[idx] + 1;
142
+
143
+ if (img[idx])
144
+ label[idx] = y;
145
+ else
146
+ label[idx] = 0;
147
+
148
+ if (col + 1 < W) {
149
+ if (img[idx + 1])
150
+ label[idx + 1] = y;
151
+ else
152
+ label[idx + 1] = 0;
153
+
154
+ if (row + 1 < H) {
155
+ if (img[idx + W + 1])
156
+ label[idx + W + 1] = y;
157
+ else
158
+ label[idx + W + 1] = 0;
159
+ }
160
+ }
161
+
162
+ if (row + 1 < H) {
163
+ if (img[idx + W])
164
+ label[idx + W] = y;
165
+ else
166
+ label[idx + W] = 0;
167
+ }
168
+ }
169
+
170
+ __global__ void init_counting(
171
+ const int32_t* label,
172
+ int32_t* count_init,
173
+ const int32_t W,
174
+ const int32_t H) {
175
+ const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y);
176
+ const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x);
177
+ const uint32_t idx = row * W + col;
178
+
179
+ if (row >= H || col >= W)
180
+ return;
181
+
182
+ int32_t y = label[idx];
183
+ if (y > 0) {
184
+ int32_t count_idx = y - 1;
185
+ atomicAdd(count_init + count_idx, 1);
186
+ }
187
+ }
188
+
189
+ __global__ void final_counting(
190
+ const int32_t* label,
191
+ const int32_t* count_init,
192
+ int32_t* count_final,
193
+ const int32_t W,
194
+ const int32_t H) {
195
+ const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y);
196
+ const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x);
197
+ const uint32_t idx = row * W + col;
198
+
199
+ if (row >= H || col >= W)
200
+ return;
201
+
202
+ int32_t y = label[idx];
203
+ if (y > 0) {
204
+ int32_t count_idx = y - 1;
205
+ count_final[idx] = count_init[count_idx];
206
+ } else {
207
+ count_final[idx] = 0;
208
+ }
209
+ }
210
+
211
+ } // namespace cc2d
212
+
213
+ std::vector<torch::Tensor> get_connected_componnets(
214
+ const torch::Tensor& inputs) {
215
+ AT_ASSERTM(inputs.is_cuda(), "inputs must be a CUDA tensor");
216
+ AT_ASSERTM(inputs.ndimension() == 4, "inputs must be [N, 1, H, W] shape");
217
+ AT_ASSERTM(
218
+ inputs.scalar_type() == torch::kUInt8, "inputs must be a uint8 type");
219
+
220
+ const uint32_t N = inputs.size(0);
221
+ const uint32_t C = inputs.size(1);
222
+ const uint32_t H = inputs.size(2);
223
+ const uint32_t W = inputs.size(3);
224
+
225
+ AT_ASSERTM(C == 1, "inputs must be [N, 1, H, W] shape");
226
+ AT_ASSERTM((H % 2) == 0, "height must be an even number");
227
+ AT_ASSERTM((W % 2) == 0, "width must be an even number");
228
+
229
+ // label must be uint32_t
230
+ auto label_options =
231
+ torch::TensorOptions().dtype(torch::kInt32).device(inputs.device());
232
+ torch::Tensor labels = torch::zeros({N, C, H, W}, label_options);
233
+ torch::Tensor counts_init = torch::zeros({N, C, H, W}, label_options);
234
+ torch::Tensor counts_final = torch::zeros({N, C, H, W}, label_options);
235
+
236
+ dim3 grid = dim3(
237
+ ((W + 1) / 2 + BLOCK_COLS - 1) / BLOCK_COLS,
238
+ ((H + 1) / 2 + BLOCK_ROWS - 1) / BLOCK_ROWS);
239
+ dim3 block = dim3(BLOCK_COLS, BLOCK_ROWS);
240
+ dim3 grid_count =
241
+ dim3((W + BLOCK_COLS) / BLOCK_COLS, (H + BLOCK_ROWS) / BLOCK_ROWS);
242
+ dim3 block_count = dim3(BLOCK_COLS, BLOCK_ROWS);
243
+ cudaStream_t stream = at::cuda::getCurrentCUDAStream();
244
+
245
+ for (int n = 0; n < N; n++) {
246
+ uint32_t offset = n * H * W;
247
+
248
+ cc2d::init_labeling<<<grid, block, 0, stream>>>(
249
+ labels.data_ptr<int32_t>() + offset, W, H);
250
+ cc2d::merge<<<grid, block, 0, stream>>>(
251
+ inputs.data_ptr<uint8_t>() + offset,
252
+ labels.data_ptr<int32_t>() + offset,
253
+ W,
254
+ H);
255
+ cc2d::compression<<<grid, block, 0, stream>>>(
256
+ labels.data_ptr<int32_t>() + offset, W, H);
257
+ cc2d::final_labeling<<<grid, block, 0, stream>>>(
258
+ inputs.data_ptr<uint8_t>() + offset,
259
+ labels.data_ptr<int32_t>() + offset,
260
+ W,
261
+ H);
262
+
263
+ // get the counting of each pixel
264
+ cc2d::init_counting<<<grid_count, block_count, 0, stream>>>(
265
+ labels.data_ptr<int32_t>() + offset,
266
+ counts_init.data_ptr<int32_t>() + offset,
267
+ W,
268
+ H);
269
+ cc2d::final_counting<<<grid_count, block_count, 0, stream>>>(
270
+ labels.data_ptr<int32_t>() + offset,
271
+ counts_init.data_ptr<int32_t>() + offset,
272
+ counts_final.data_ptr<int32_t>() + offset,
273
+ W,
274
+ H);
275
+ }
276
+
277
+ // returned values are [labels, counts]
278
+ std::vector<torch::Tensor> outputs;
279
+ outputs.push_back(labels);
280
+ outputs.push_back(counts_final);
281
+ return outputs;
282
+ }
283
+
284
+ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
285
+ m.def(
286
+ "get_connected_componnets",
287
+ &get_connected_componnets,
288
+ "get_connected_componnets");
289
+ }
MedSAM2/efficient_track_anything/efficienttam_image_predictor.py ADDED
@@ -0,0 +1,472 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import logging
8
+
9
+ from typing import List, Optional, Tuple, Union
10
+
11
+ import numpy as np
12
+ import torch
13
+
14
+ from efficient_track_anything.modeling.efficienttam_base import EfficientTAMBase
15
+
16
+ from efficient_track_anything.utils.transforms import EfficientTAMTransforms
17
+ from PIL.Image import Image
18
+
19
+
20
+ class EfficientTAMImagePredictor:
21
+ def __init__(
22
+ self,
23
+ efficienttam_model: EfficientTAMBase,
24
+ mask_threshold=0.0,
25
+ max_hole_area=0.0,
26
+ max_sprinkle_area=0.0,
27
+ **kwargs,
28
+ ) -> None:
29
+ """
30
+ Uses EfficientTAM to calculate the image embedding for an image, and then
31
+ allow repeated, efficient mask prediction given prompts.
32
+
33
+ Arguments:
34
+ efficienttam_model (EfficientTAM): The model to use for mask prediction.
35
+ mask_threshold (float): The threshold to use when converting mask logits
36
+ to binary masks. Masks are thresholded at 0 by default.
37
+ max_hole_area (int): If max_hole_area > 0, we fill small holes in up to
38
+ the maximum area of max_hole_area in low_res_masks.
39
+ max_sprinkle_area (int): If max_sprinkle_area > 0, we remove small sprinkles up to
40
+ the maximum area of max_sprinkle_area in low_res_masks.
41
+ """
42
+ super().__init__()
43
+ self.model = efficienttam_model
44
+ self._transforms = EfficientTAMTransforms(
45
+ resolution=self.model.image_size,
46
+ mask_threshold=mask_threshold,
47
+ max_hole_area=max_hole_area,
48
+ max_sprinkle_area=max_sprinkle_area,
49
+ )
50
+
51
+ # Predictor state
52
+ self._is_image_set = False
53
+ self._features = None
54
+ self._orig_hw = None
55
+ # Whether the predictor is set for single image or a batch of images
56
+ self._is_batch = False
57
+
58
+ # Predictor config
59
+ self.mask_threshold = mask_threshold
60
+
61
+ # Spatial dim for backbone feature maps
62
+ self._bb_feat_sizes = [
63
+ (256, 256),
64
+ (128, 128),
65
+ (64, 64),
66
+ ]
67
+ if self.model.image_size == 512:
68
+ self._bb_feat_sizes = [
69
+ (128, 128),
70
+ (64, 64),
71
+ (32, 32),
72
+ ]
73
+
74
+ @classmethod
75
+ def from_pretrained(cls, model_id: str, **kwargs) -> "EfficientTAMImagePredictor":
76
+ """
77
+ Load a pretrained model from the Hugging Face hub.
78
+
79
+ Arguments:
80
+ model_id (str): The Hugging Face repository ID.
81
+ **kwargs: Additional arguments to pass to the model constructor.
82
+
83
+ Returns:
84
+ (EfficientTAMImagePredictor): The loaded model.
85
+ """
86
+ from efficient_track_anything.build_efficienttam import build_efficienttam_hf
87
+
88
+ tam_model = build_efficienttam_hf(model_id, **kwargs)
89
+ return cls(tam_model, **kwargs)
90
+
91
+ @torch.no_grad()
92
+ def set_image(
93
+ self,
94
+ image: Union[np.ndarray, Image],
95
+ ) -> None:
96
+ """
97
+ Calculates the image embeddings for the provided image, allowing
98
+ masks to be predicted with the 'predict' method.
99
+
100
+ Arguments:
101
+ image (np.ndarray or PIL Image): The input image to embed in RGB format. The image should be in HWC format if np.ndarray, or WHC format if PIL Image
102
+ with pixel values in [0, 255].
103
+ image_format (str): The color format of the image, in ['RGB', 'BGR'].
104
+ """
105
+ self.reset_predictor()
106
+ # Transform the image to the form expected by the model
107
+ if isinstance(image, np.ndarray):
108
+ logging.info("For numpy array image, we assume (HxWxC) format")
109
+ self._orig_hw = [image.shape[:2]]
110
+ elif isinstance(image, Image):
111
+ w, h = image.size
112
+ self._orig_hw = [(h, w)]
113
+ else:
114
+ raise NotImplementedError("Image format not supported")
115
+
116
+ input_image = self._transforms(image)
117
+ input_image = input_image[None, ...].to(self.device)
118
+
119
+ assert (
120
+ len(input_image.shape) == 4 and input_image.shape[1] == 3
121
+ ), f"input_image must be of size 1x3xHxW, got {input_image.shape}"
122
+ logging.info("Computing image embeddings for the provided image...")
123
+ backbone_out = self.model.forward_image(input_image)
124
+ _, vision_feats, _, _ = self.model._prepare_backbone_features(backbone_out)
125
+ # Add no_mem_embed, which is added to the lowest rest feat. map during training on videos
126
+ if self.model.directly_add_no_mem_embed:
127
+ vision_feats[-1] = vision_feats[-1] + self.model.no_mem_embed
128
+
129
+ feats = [
130
+ feat.permute(1, 2, 0).view(1, -1, *feat_size)
131
+ for feat, feat_size in zip(vision_feats[::-1], self._bb_feat_sizes[::-1])
132
+ ][::-1]
133
+ self._features = {"image_embed": feats[-1], "high_res_feats": feats[:-1]}
134
+ self._is_image_set = True
135
+ logging.info("Image embeddings computed.")
136
+
137
+ @torch.no_grad()
138
+ def set_image_batch(
139
+ self,
140
+ image_list: List[Union[np.ndarray]],
141
+ ) -> None:
142
+ """
143
+ Calculates the image embeddings for the provided image batch, allowing
144
+ masks to be predicted with the 'predict_batch' method.
145
+
146
+ Arguments:
147
+ image_list (List[np.ndarray]): The input images to embed in RGB format. The image should be in HWC format if np.ndarray
148
+ with pixel values in [0, 255].
149
+ """
150
+ self.reset_predictor()
151
+ assert isinstance(image_list, list)
152
+ self._orig_hw = []
153
+ for image in image_list:
154
+ assert isinstance(
155
+ image, np.ndarray
156
+ ), "Images are expected to be an np.ndarray in RGB format, and of shape HWC"
157
+ self._orig_hw.append(image.shape[:2])
158
+ # Transform the image to the form expected by the model
159
+ img_batch = self._transforms.forward_batch(image_list)
160
+ img_batch = img_batch.to(self.device)
161
+ batch_size = img_batch.shape[0]
162
+ assert (
163
+ len(img_batch.shape) == 4 and img_batch.shape[1] == 3
164
+ ), f"img_batch must be of size Bx3xHxW, got {img_batch.shape}"
165
+ logging.info("Computing image embeddings for the provided images...")
166
+ backbone_out = self.model.forward_image(img_batch)
167
+ _, vision_feats, _, _ = self.model._prepare_backbone_features(backbone_out)
168
+ # Add no_mem_embed, which is added to the lowest rest feat. map during training on videos
169
+ if self.model.directly_add_no_mem_embed:
170
+ vision_feats[-1] = vision_feats[-1] + self.model.no_mem_embed
171
+
172
+ feats = [
173
+ feat.permute(1, 2, 0).view(batch_size, -1, *feat_size)
174
+ for feat, feat_size in zip(vision_feats[::-1], self._bb_feat_sizes[::-1])
175
+ ][::-1]
176
+ self._features = {"image_embed": feats[-1], "high_res_feats": feats[:-1]}
177
+ self._is_image_set = True
178
+ self._is_batch = True
179
+ logging.info("Image embeddings computed.")
180
+
181
+ def predict_batch(
182
+ self,
183
+ point_coords_batch: List[np.ndarray] = None,
184
+ point_labels_batch: List[np.ndarray] = None,
185
+ box_batch: List[np.ndarray] = None,
186
+ mask_input_batch: List[np.ndarray] = None,
187
+ multimask_output: bool = True,
188
+ return_logits: bool = False,
189
+ normalize_coords=True,
190
+ ) -> Tuple[List[np.ndarray], List[np.ndarray], List[np.ndarray]]:
191
+ """This function is very similar to predict(...), however it is used for batched mode, when the model is expected to generate predictions on multiple images.
192
+ It returns a tuple of lists of masks, ious, and low_res_masks_logits.
193
+ """
194
+ assert self._is_batch, "This function should only be used when in batched mode"
195
+ if not self._is_image_set:
196
+ raise RuntimeError(
197
+ "An image must be set with .set_image_batch(...) before mask prediction."
198
+ )
199
+ num_images = len(self._features["image_embed"])
200
+ all_masks = []
201
+ all_ious = []
202
+ all_low_res_masks = []
203
+ for img_idx in range(num_images):
204
+ # Transform input prompts
205
+ point_coords = (
206
+ point_coords_batch[img_idx] if point_coords_batch is not None else None
207
+ )
208
+ point_labels = (
209
+ point_labels_batch[img_idx] if point_labels_batch is not None else None
210
+ )
211
+ box = box_batch[img_idx] if box_batch is not None else None
212
+ mask_input = (
213
+ mask_input_batch[img_idx] if mask_input_batch is not None else None
214
+ )
215
+ mask_input, unnorm_coords, labels, unnorm_box = self._prep_prompts(
216
+ point_coords,
217
+ point_labels,
218
+ box,
219
+ mask_input,
220
+ normalize_coords,
221
+ img_idx=img_idx,
222
+ )
223
+ masks, iou_predictions, low_res_masks = self._predict(
224
+ unnorm_coords,
225
+ labels,
226
+ unnorm_box,
227
+ mask_input,
228
+ multimask_output,
229
+ return_logits=return_logits,
230
+ img_idx=img_idx,
231
+ )
232
+ masks_np = masks.squeeze(0).float().detach().cpu().numpy()
233
+ iou_predictions_np = (
234
+ iou_predictions.squeeze(0).float().detach().cpu().numpy()
235
+ )
236
+ low_res_masks_np = low_res_masks.squeeze(0).float().detach().cpu().numpy()
237
+ all_masks.append(masks_np)
238
+ all_ious.append(iou_predictions_np)
239
+ all_low_res_masks.append(low_res_masks_np)
240
+
241
+ return all_masks, all_ious, all_low_res_masks
242
+
243
+ def predict(
244
+ self,
245
+ point_coords: Optional[np.ndarray] = None,
246
+ point_labels: Optional[np.ndarray] = None,
247
+ box: Optional[np.ndarray] = None,
248
+ mask_input: Optional[np.ndarray] = None,
249
+ multimask_output: bool = True,
250
+ return_logits: bool = False,
251
+ normalize_coords=True,
252
+ ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
253
+ """
254
+ Predict masks for the given input prompts, using the currently set image.
255
+
256
+ Arguments:
257
+ point_coords (np.ndarray or None): A Nx2 array of point prompts to the
258
+ model. Each point is in (X,Y) in pixels.
259
+ point_labels (np.ndarray or None): A length N array of labels for the
260
+ point prompts. 1 indicates a foreground point and 0 indicates a
261
+ background point.
262
+ box (np.ndarray or None): A length 4 array given a box prompt to the
263
+ model, in XYXY format.
264
+ mask_input (np.ndarray): A low resolution mask input to the model, typically
265
+ coming from a previous prediction iteration. Has form 1xHxW, where
266
+ for SAM, H=W=256.
267
+ multimask_output (bool): If true, the model will return three masks.
268
+ For ambiguous input prompts (such as a single click), this will often
269
+ produce better masks than a single prediction. If only a single
270
+ mask is needed, the model's predicted quality score can be used
271
+ to select the best mask. For non-ambiguous prompts, such as multiple
272
+ input prompts, multimask_output=False can give better results.
273
+ return_logits (bool): If true, returns un-thresholded masks logits
274
+ instead of a binary mask.
275
+ normalize_coords (bool): If true, the point coordinates will be normalized to the range [0,1] and point_coords is expected to be wrt. image dimensions.
276
+
277
+ Returns:
278
+ (np.ndarray): The output masks in CxHxW format, where C is the
279
+ number of masks, and (H, W) is the original image size.
280
+ (np.ndarray): An array of length C containing the model's
281
+ predictions for the quality of each mask.
282
+ (np.ndarray): An array of shape CxHxW, where C is the number
283
+ of masks and H=W=256. These low resolution logits can be passed to
284
+ a subsequent iteration as mask input.
285
+ """
286
+ if not self._is_image_set:
287
+ raise RuntimeError(
288
+ "An image must be set with .set_image(...) before mask prediction."
289
+ )
290
+
291
+ # Transform input prompts
292
+
293
+ mask_input, unnorm_coords, labels, unnorm_box = self._prep_prompts(
294
+ point_coords, point_labels, box, mask_input, normalize_coords
295
+ )
296
+
297
+ masks, iou_predictions, low_res_masks = self._predict(
298
+ unnorm_coords,
299
+ labels,
300
+ unnorm_box,
301
+ mask_input,
302
+ multimask_output,
303
+ return_logits=return_logits,
304
+ )
305
+
306
+ masks_np = masks.squeeze(0).float().detach().cpu().numpy()
307
+ iou_predictions_np = iou_predictions.squeeze(0).float().detach().cpu().numpy()
308
+ low_res_masks_np = low_res_masks.squeeze(0).float().detach().cpu().numpy()
309
+ return masks_np, iou_predictions_np, low_res_masks_np
310
+
311
+ def _prep_prompts(
312
+ self, point_coords, point_labels, box, mask_logits, normalize_coords, img_idx=-1
313
+ ):
314
+
315
+ unnorm_coords, labels, unnorm_box, mask_input = None, None, None, None
316
+ if point_coords is not None:
317
+ assert (
318
+ point_labels is not None
319
+ ), "point_labels must be supplied if point_coords is supplied."
320
+ point_coords = torch.as_tensor(
321
+ point_coords, dtype=torch.float, device=self.device
322
+ )
323
+ unnorm_coords = self._transforms.transform_coords(
324
+ point_coords, normalize=normalize_coords, orig_hw=self._orig_hw[img_idx]
325
+ )
326
+ labels = torch.as_tensor(point_labels, dtype=torch.int, device=self.device)
327
+ if len(unnorm_coords.shape) == 2:
328
+ unnorm_coords, labels = unnorm_coords[None, ...], labels[None, ...]
329
+ if box is not None:
330
+ box = torch.as_tensor(box, dtype=torch.float, device=self.device)
331
+ unnorm_box = self._transforms.transform_boxes(
332
+ box, normalize=normalize_coords, orig_hw=self._orig_hw[img_idx]
333
+ ) # Bx2x2
334
+ if mask_logits is not None:
335
+ mask_input = torch.as_tensor(
336
+ mask_logits, dtype=torch.float, device=self.device
337
+ )
338
+ if len(mask_input.shape) == 3:
339
+ mask_input = mask_input[None, :, :, :]
340
+ return mask_input, unnorm_coords, labels, unnorm_box
341
+
342
+ @torch.no_grad()
343
+ def _predict(
344
+ self,
345
+ point_coords: Optional[torch.Tensor],
346
+ point_labels: Optional[torch.Tensor],
347
+ boxes: Optional[torch.Tensor] = None,
348
+ mask_input: Optional[torch.Tensor] = None,
349
+ multimask_output: bool = True,
350
+ return_logits: bool = False,
351
+ img_idx: int = -1,
352
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
353
+ """
354
+ Predict masks for the given input prompts, using the currently set image.
355
+ Input prompts are batched torch tensors and are expected to already be
356
+ transformed to the input frame using EfficientTAMTransforms.
357
+
358
+ Arguments:
359
+ point_coords (torch.Tensor or None): A BxNx2 array of point prompts to the
360
+ model. Each point is in (X,Y) in pixels.
361
+ point_labels (torch.Tensor or None): A BxN array of labels for the
362
+ point prompts. 1 indicates a foreground point and 0 indicates a
363
+ background point.
364
+ boxes (np.ndarray or None): A Bx4 array given a box prompt to the
365
+ model, in XYXY format.
366
+ mask_input (np.ndarray): A low resolution mask input to the model, typically
367
+ coming from a previous prediction iteration. Has form Bx1xHxW, where
368
+ for SAM, H=W=256. Masks returned by a previous iteration of the
369
+ predict method do not need further transformation.
370
+ multimask_output (bool): If true, the model will return three masks.
371
+ For ambiguous input prompts (such as a single click), this will often
372
+ produce better masks than a single prediction. If only a single
373
+ mask is needed, the model's predicted quality score can be used
374
+ to select the best mask. For non-ambiguous prompts, such as multiple
375
+ input prompts, multimask_output=False can give better results.
376
+ return_logits (bool): If true, returns un-thresholded masks logits
377
+ instead of a binary mask.
378
+
379
+ Returns:
380
+ (torch.Tensor): The output masks in BxCxHxW format, where C is the
381
+ number of masks, and (H, W) is the original image size.
382
+ (torch.Tensor): An array of shape BxC containing the model's
383
+ predictions for the quality of each mask.
384
+ (torch.Tensor): An array of shape BxCxHxW, where C is the number
385
+ of masks and H=W=256. These low res logits can be passed to
386
+ a subsequent iteration as mask input.
387
+ """
388
+ if not self._is_image_set:
389
+ raise RuntimeError(
390
+ "An image must be set with .set_image(...) before mask prediction."
391
+ )
392
+
393
+ if point_coords is not None:
394
+ concat_points = (point_coords, point_labels)
395
+ else:
396
+ concat_points = None
397
+
398
+ # Embed prompts
399
+ if boxes is not None:
400
+ box_coords = boxes.reshape(-1, 2, 2)
401
+ box_labels = torch.tensor([[2, 3]], dtype=torch.int, device=boxes.device)
402
+ box_labels = box_labels.repeat(boxes.size(0), 1)
403
+ # we merge "boxes" and "points" into a single "concat_points" input (where
404
+ # boxes are added at the beginning) to sam_prompt_encoder
405
+ if concat_points is not None:
406
+ concat_coords = torch.cat([box_coords, concat_points[0]], dim=1)
407
+ concat_labels = torch.cat([box_labels, concat_points[1]], dim=1)
408
+ concat_points = (concat_coords, concat_labels)
409
+ else:
410
+ concat_points = (box_coords, box_labels)
411
+
412
+ sparse_embeddings, dense_embeddings = self.model.sam_prompt_encoder(
413
+ points=concat_points,
414
+ boxes=None,
415
+ masks=mask_input,
416
+ )
417
+
418
+ # Predict masks
419
+ batched_mode = (
420
+ concat_points is not None and concat_points[0].shape[0] > 1
421
+ ) # multi object prediction
422
+ high_res_features = [
423
+ feat_level[img_idx].unsqueeze(0)
424
+ for feat_level in self._features["high_res_feats"]
425
+ ]
426
+ low_res_masks, iou_predictions, _, _ = self.model.sam_mask_decoder(
427
+ image_embeddings=self._features["image_embed"][img_idx].unsqueeze(0),
428
+ image_pe=self.model.sam_prompt_encoder.get_dense_pe(),
429
+ sparse_prompt_embeddings=sparse_embeddings,
430
+ dense_prompt_embeddings=dense_embeddings,
431
+ multimask_output=multimask_output,
432
+ repeat_image=batched_mode,
433
+ high_res_features=high_res_features,
434
+ )
435
+
436
+ # Upscale the masks to the original image resolution
437
+ masks = self._transforms.postprocess_masks(
438
+ low_res_masks, self._orig_hw[img_idx]
439
+ )
440
+ low_res_masks = torch.clamp(low_res_masks, -32.0, 32.0)
441
+ if not return_logits:
442
+ masks = masks > self.mask_threshold
443
+
444
+ return masks, iou_predictions, low_res_masks
445
+
446
+ def get_image_embedding(self) -> torch.Tensor:
447
+ """
448
+ Returns the image embeddings for the currently set image, with
449
+ shape 1xCxHxW, where C is the embedding dimension and (H,W) are
450
+ the embedding spatial dimension of SAM (typically C=256, H=W=64).
451
+ """
452
+ if not self._is_image_set:
453
+ raise RuntimeError(
454
+ "An image must be set with .set_image(...) to generate an embedding."
455
+ )
456
+ assert (
457
+ self._features is not None
458
+ ), "Features must exist if an image has been set."
459
+ return self._features["image_embed"]
460
+
461
+ @property
462
+ def device(self) -> torch.device:
463
+ return self.model.device
464
+
465
+ def reset_predictor(self) -> None:
466
+ """
467
+ Resets the image embeddings and other state variables.
468
+ """
469
+ self._is_image_set = False
470
+ self._features = None
471
+ self._orig_hw = None
472
+ self._is_batch = False
MedSAM2/efficient_track_anything/efficienttam_video_predictor.py ADDED
@@ -0,0 +1,1223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import warnings
8
+ from collections import OrderedDict
9
+
10
+ import torch
11
+ import torch.nn.functional as F
12
+
13
+ from efficient_track_anything.modeling.efficienttam_base import (
14
+ EfficientTAMBase,
15
+ NO_OBJ_SCORE,
16
+ )
17
+ from efficient_track_anything.utils.misc import (
18
+ concat_points,
19
+ fill_holes_in_mask_scores,
20
+ load_video_frames,
21
+ )
22
+
23
+ from tqdm import tqdm
24
+
25
+
26
+ class EfficientTAMVideoPredictor(EfficientTAMBase):
27
+ """The predictor class to handle user interactions and manage inference states."""
28
+
29
+ def __init__(
30
+ self,
31
+ fill_hole_area=0,
32
+ # whether to apply non-overlapping constraints on the output object masks
33
+ non_overlap_masks=False,
34
+ # whether to clear non-conditioning memory of the surrounding frames (which may contain outdated information) after adding correction clicks;
35
+ # note that this would only apply to *single-object tracking* unless `clear_non_cond_mem_for_multi_obj` is also set to True)
36
+ clear_non_cond_mem_around_input=False,
37
+ # if `add_all_frames_to_correct_as_cond` is True, we also append to the conditioning frame list any frame that receives a later correction click
38
+ # if `add_all_frames_to_correct_as_cond` is False, we conditioning frame list to only use those initial conditioning frames
39
+ add_all_frames_to_correct_as_cond=False,
40
+ **kwargs,
41
+ ):
42
+ super().__init__(**kwargs)
43
+ self.fill_hole_area = fill_hole_area
44
+ self.non_overlap_masks = non_overlap_masks
45
+ self.clear_non_cond_mem_around_input = clear_non_cond_mem_around_input
46
+ self.add_all_frames_to_correct_as_cond = add_all_frames_to_correct_as_cond
47
+
48
+ @torch.inference_mode()
49
+ def init_state(
50
+ self,
51
+ video_path,
52
+ offload_video_to_cpu=False,
53
+ offload_state_to_cpu=False,
54
+ async_loading_frames=False,
55
+ ):
56
+ """Initialize an inference state."""
57
+ compute_device = self.device # device of the model
58
+ images, video_height, video_width = load_video_frames(
59
+ video_path=video_path,
60
+ image_size=self.image_size,
61
+ offload_video_to_cpu=offload_video_to_cpu,
62
+ async_loading_frames=async_loading_frames,
63
+ compute_device=compute_device,
64
+ )
65
+ inference_state = {}
66
+ inference_state["images"] = images
67
+ inference_state["num_frames"] = len(images)
68
+ # whether to offload the video frames to CPU memory
69
+ # turning on this option saves the GPU memory with only a very small overhead
70
+ inference_state["offload_video_to_cpu"] = offload_video_to_cpu
71
+ # whether to offload the inference state to CPU memory
72
+ # turning on this option saves the GPU memory at the cost of a lower tracking fps
73
+ # (e.g. in a test case of 768x768 model, fps dropped from 27 to 24 when tracking one object
74
+ # and from 24 to 21 when tracking two objects)
75
+ inference_state["offload_state_to_cpu"] = offload_state_to_cpu
76
+ # the original video height and width, used for resizing final output scores
77
+ inference_state["video_height"] = video_height
78
+ inference_state["video_width"] = video_width
79
+ inference_state["device"] = compute_device
80
+ if offload_state_to_cpu:
81
+ inference_state["storage_device"] = torch.device("cpu")
82
+ else:
83
+ inference_state["storage_device"] = compute_device
84
+ # inputs on each frame
85
+ inference_state["point_inputs_per_obj"] = {}
86
+ inference_state["mask_inputs_per_obj"] = {}
87
+ # visual features on a small number of recently visited frames for quick interactions
88
+ inference_state["cached_features"] = {}
89
+ # values that don't change across frames (so we only need to hold one copy of them)
90
+ inference_state["constants"] = {}
91
+ # mapping between client-side object id and model-side object index
92
+ inference_state["obj_id_to_idx"] = OrderedDict()
93
+ inference_state["obj_idx_to_id"] = OrderedDict()
94
+ inference_state["obj_ids"] = []
95
+ # Slice (view) of each object tracking results, sharing the same memory with "output_dict"
96
+ inference_state["output_dict_per_obj"] = {}
97
+ # A temporary storage to hold new outputs when user interact with a frame
98
+ # to add clicks or mask (it's merged into "output_dict" before propagation starts)
99
+ inference_state["temp_output_dict_per_obj"] = {}
100
+ # Frames that already holds consolidated outputs from click or mask inputs
101
+ # (we directly use their consolidated outputs during tracking)
102
+ # metadata for each tracking frame (e.g. which direction it's tracked)
103
+ inference_state["frames_tracked_per_obj"] = {}
104
+ # Warm up the visual backbone and cache the image feature on frame 0
105
+ self._get_image_feature(inference_state, frame_idx=0, batch_size=1)
106
+ return inference_state
107
+
108
+ @classmethod
109
+ def from_pretrained(cls, model_id: str, **kwargs) -> "EfficientTAMVideoPredictor":
110
+ """
111
+ Load a pretrained model from the Hugging Face hub.
112
+
113
+ Arguments:
114
+ model_id (str): The Hugging Face repository ID.
115
+ **kwargs: Additional arguments to pass to the model constructor.
116
+
117
+ Returns:
118
+ (EfficientTAMVideoPredictor): The loaded model.
119
+ """
120
+ from efficient_track_anything.build_efficienttam import (
121
+ build_efficienttam_video_predictor_hf,
122
+ )
123
+
124
+ efficienttam_model = build_efficienttam_video_predictor_hf(model_id, **kwargs)
125
+ return efficienttam_model
126
+
127
+ def _obj_id_to_idx(self, inference_state, obj_id):
128
+ """Map client-side object id to model-side object index."""
129
+ obj_idx = inference_state["obj_id_to_idx"].get(obj_id, None)
130
+ if obj_idx is not None:
131
+ return obj_idx
132
+
133
+ # We always allow adding new objects (including after tracking starts).
134
+ allow_new_object = True
135
+ if allow_new_object:
136
+ # get the next object slot
137
+ obj_idx = len(inference_state["obj_id_to_idx"])
138
+ inference_state["obj_id_to_idx"][obj_id] = obj_idx
139
+ inference_state["obj_idx_to_id"][obj_idx] = obj_id
140
+ inference_state["obj_ids"] = list(inference_state["obj_id_to_idx"])
141
+ # set up input and output structures for this object
142
+ inference_state["point_inputs_per_obj"][obj_idx] = {}
143
+ inference_state["mask_inputs_per_obj"][obj_idx] = {}
144
+ inference_state["output_dict_per_obj"][obj_idx] = {
145
+ "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
146
+ "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
147
+ }
148
+ inference_state["temp_output_dict_per_obj"][obj_idx] = {
149
+ "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
150
+ "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
151
+ }
152
+ inference_state["frames_tracked_per_obj"][obj_idx] = {}
153
+ return obj_idx
154
+ else:
155
+ raise RuntimeError(
156
+ f"Cannot add new object id {obj_id} after tracking starts. "
157
+ f"All existing object ids: {inference_state['obj_ids']}. "
158
+ f"Please call 'reset_state' to restart from scratch."
159
+ )
160
+
161
+ def _obj_idx_to_id(self, inference_state, obj_idx):
162
+ """Map model-side object index to client-side object id."""
163
+ return inference_state["obj_idx_to_id"][obj_idx]
164
+
165
+ def _get_obj_num(self, inference_state):
166
+ """Get the total number of unique object ids received so far in this session."""
167
+ return len(inference_state["obj_idx_to_id"])
168
+
169
+ @torch.inference_mode()
170
+ def add_new_points_or_box(
171
+ self,
172
+ inference_state,
173
+ frame_idx,
174
+ obj_id,
175
+ points=None,
176
+ labels=None,
177
+ clear_old_points=True,
178
+ normalize_coords=True,
179
+ box=None,
180
+ ):
181
+ """Add new points to a frame."""
182
+ obj_idx = self._obj_id_to_idx(inference_state, obj_id)
183
+ point_inputs_per_frame = inference_state["point_inputs_per_obj"][obj_idx]
184
+ mask_inputs_per_frame = inference_state["mask_inputs_per_obj"][obj_idx]
185
+
186
+ if (points is not None) != (labels is not None):
187
+ raise ValueError("points and labels must be provided together")
188
+ if points is None and box is None:
189
+ raise ValueError("at least one of points or box must be provided as input")
190
+
191
+ if points is None:
192
+ points = torch.zeros(0, 2, dtype=torch.float32)
193
+ elif not isinstance(points, torch.Tensor):
194
+ points = torch.tensor(points, dtype=torch.float32)
195
+ if labels is None:
196
+ labels = torch.zeros(0, dtype=torch.int32)
197
+ elif not isinstance(labels, torch.Tensor):
198
+ labels = torch.tensor(labels, dtype=torch.int32)
199
+ if points.dim() == 2:
200
+ points = points.unsqueeze(0) # add batch dimension
201
+ if labels.dim() == 1:
202
+ labels = labels.unsqueeze(0) # add batch dimension
203
+
204
+ # If `box` is provided, we add it as the first two points with labels 2 and 3
205
+ # along with the user-provided points (consistent with how EfficientTAM is trained).
206
+ if box is not None:
207
+ if not clear_old_points:
208
+ raise ValueError(
209
+ "cannot add box without clearing old points, since "
210
+ "box prompt must be provided before any point prompt "
211
+ "(please use clear_old_points=True instead)"
212
+ )
213
+ if not isinstance(box, torch.Tensor):
214
+ box = torch.tensor(box, dtype=torch.float32, device=points.device)
215
+ box_coords = box.reshape(1, 2, 2)
216
+ box_labels = torch.tensor([2, 3], dtype=torch.int32, device=labels.device)
217
+ box_labels = box_labels.reshape(1, 2)
218
+ points = torch.cat([box_coords, points], dim=1)
219
+ labels = torch.cat([box_labels, labels], dim=1)
220
+
221
+ if normalize_coords:
222
+ video_H = inference_state["video_height"]
223
+ video_W = inference_state["video_width"]
224
+ points = points / torch.tensor([video_W, video_H]).to(points.device)
225
+ # scale the (normalized) coordinates by the model's internal image size
226
+ points = points * self.image_size
227
+ points = points.to(inference_state["device"])
228
+ labels = labels.to(inference_state["device"])
229
+
230
+ if not clear_old_points:
231
+ point_inputs = point_inputs_per_frame.get(frame_idx, None)
232
+ else:
233
+ point_inputs = None
234
+ point_inputs = concat_points(point_inputs, points, labels)
235
+
236
+ point_inputs_per_frame[frame_idx] = point_inputs
237
+ mask_inputs_per_frame.pop(frame_idx, None)
238
+ # If this frame hasn't been tracked before, we treat it as an initial conditioning
239
+ # frame, meaning that the inputs points are to generate segments on this frame without
240
+ # using any memory from other frames, like in SAM. Otherwise (if it has been tracked),
241
+ # the input points will be used to correct the already tracked masks.
242
+ obj_frames_tracked = inference_state["frames_tracked_per_obj"][obj_idx]
243
+ is_init_cond_frame = frame_idx not in obj_frames_tracked
244
+ # whether to track in reverse time order
245
+ if is_init_cond_frame:
246
+ reverse = False
247
+ else:
248
+ reverse = obj_frames_tracked[frame_idx]["reverse"]
249
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
250
+ obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
251
+ # Add a frame to conditioning output if it's an initial conditioning frame or
252
+ # if the model sees all frames receiving clicks/mask as conditioning frames.
253
+ is_cond = is_init_cond_frame or self.add_all_frames_to_correct_as_cond
254
+ storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
255
+
256
+ # Get any previously predicted mask logits on this object and feed it along with
257
+ # the new clicks into the SAM mask decoder.
258
+ prev_sam_mask_logits = None
259
+ # lookup temporary output dict first, which contains the most recent output
260
+ # (if not found, then lookup conditioning and non-conditioning frame output)
261
+ prev_out = obj_temp_output_dict[storage_key].get(frame_idx)
262
+ if prev_out is None:
263
+ prev_out = obj_output_dict["cond_frame_outputs"].get(frame_idx)
264
+ if prev_out is None:
265
+ prev_out = obj_output_dict["non_cond_frame_outputs"].get(frame_idx)
266
+
267
+ if prev_out is not None and prev_out["pred_masks"] is not None:
268
+ device = inference_state["device"]
269
+ prev_sam_mask_logits = prev_out["pred_masks"].to(device, non_blocking=True)
270
+ # Clamp the scale of prev_sam_mask_logits to avoid rare numerical issues.
271
+ prev_sam_mask_logits = torch.clamp(prev_sam_mask_logits, -32.0, 32.0)
272
+ current_out, _ = self._run_single_frame_inference(
273
+ inference_state=inference_state,
274
+ output_dict=obj_output_dict, # run on the slice of a single object
275
+ frame_idx=frame_idx,
276
+ batch_size=1, # run on the slice of a single object
277
+ is_init_cond_frame=is_init_cond_frame,
278
+ point_inputs=point_inputs,
279
+ mask_inputs=None,
280
+ reverse=reverse,
281
+ # Skip the memory encoder when adding clicks or mask. We execute the memory encoder
282
+ # at the beginning of `propagate_in_video` (after user finalize their clicks). This
283
+ # allows us to enforce non-overlapping constraints on all objects before encoding
284
+ # them into memory.
285
+ run_mem_encoder=False,
286
+ prev_sam_mask_logits=prev_sam_mask_logits,
287
+ )
288
+ # Add the output to the output dict (to be used as future memory)
289
+ obj_temp_output_dict[storage_key][frame_idx] = current_out
290
+
291
+ # Resize the output mask to the original video resolution
292
+ obj_ids = inference_state["obj_ids"]
293
+ consolidated_out = self._consolidate_temp_output_across_obj(
294
+ inference_state,
295
+ frame_idx,
296
+ is_cond=is_cond,
297
+ consolidate_at_video_res=True,
298
+ )
299
+ _, video_res_masks = self._get_orig_video_res_output(
300
+ inference_state, consolidated_out["pred_masks_video_res"]
301
+ )
302
+ return frame_idx, obj_ids, video_res_masks
303
+
304
+ def add_new_points(self, *args, **kwargs):
305
+ """Deprecated method. Please use `add_new_points_or_box` instead."""
306
+ return self.add_new_points_or_box(*args, **kwargs)
307
+
308
+ @torch.inference_mode()
309
+ def add_new_mask(
310
+ self,
311
+ inference_state,
312
+ frame_idx,
313
+ obj_id,
314
+ mask,
315
+ ):
316
+ """Add new mask to a frame."""
317
+ obj_idx = self._obj_id_to_idx(inference_state, obj_id)
318
+ point_inputs_per_frame = inference_state["point_inputs_per_obj"][obj_idx]
319
+ mask_inputs_per_frame = inference_state["mask_inputs_per_obj"][obj_idx]
320
+
321
+ if not isinstance(mask, torch.Tensor):
322
+ mask = torch.tensor(mask, dtype=torch.bool)
323
+ assert mask.dim() == 2
324
+ mask_H, mask_W = mask.shape
325
+ mask_inputs_orig = mask[None, None] # add batch and channel dimension
326
+ mask_inputs_orig = mask_inputs_orig.float().to(inference_state["device"])
327
+
328
+ # resize the mask if it doesn't match the model's image size
329
+ if mask_H != self.image_size or mask_W != self.image_size:
330
+ mask_inputs = torch.nn.functional.interpolate(
331
+ mask_inputs_orig,
332
+ size=(self.image_size, self.image_size),
333
+ align_corners=False,
334
+ mode="bilinear",
335
+ antialias=True, # use antialias for downsampling
336
+ )
337
+ mask_inputs = (mask_inputs >= 0.5).float()
338
+ else:
339
+ mask_inputs = mask_inputs_orig
340
+
341
+ mask_inputs_per_frame[frame_idx] = mask_inputs
342
+ point_inputs_per_frame.pop(frame_idx, None)
343
+ # If this frame hasn't been tracked before, we treat it as an initial conditioning
344
+ # frame, meaning that the inputs points are to generate segments on this frame without
345
+ # using any memory from other frames, like in SAM. Otherwise (if it has been tracked),
346
+ # the input points will be used to correct the already tracked masks.
347
+ obj_frames_tracked = inference_state["frames_tracked_per_obj"][obj_idx]
348
+ is_init_cond_frame = frame_idx not in obj_frames_tracked
349
+ # whether to track in reverse time order
350
+ if is_init_cond_frame:
351
+ reverse = False
352
+ else:
353
+ reverse = obj_frames_tracked[frame_idx]["reverse"]
354
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
355
+ obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
356
+ # Add a frame to conditioning output if it's an initial conditioning frame or
357
+ # if the model sees all frames receiving clicks/mask as conditioning frames.
358
+ is_cond = is_init_cond_frame or self.add_all_frames_to_correct_as_cond
359
+ storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
360
+
361
+ current_out, _ = self._run_single_frame_inference(
362
+ inference_state=inference_state,
363
+ output_dict=obj_output_dict, # run on the slice of a single object
364
+ frame_idx=frame_idx,
365
+ batch_size=1, # run on the slice of a single object
366
+ is_init_cond_frame=is_init_cond_frame,
367
+ point_inputs=None,
368
+ mask_inputs=mask_inputs,
369
+ reverse=reverse,
370
+ # Skip the memory encoder when adding clicks or mask. We execute the memory encoder
371
+ # at the beginning of `propagate_in_video` (after user finalize their clicks). This
372
+ # allows us to enforce non-overlapping constraints on all objects before encoding
373
+ # them into memory.
374
+ run_mem_encoder=False,
375
+ )
376
+ # Add the output to the output dict (to be used as future memory)
377
+ obj_temp_output_dict[storage_key][frame_idx] = current_out
378
+
379
+ # Resize the output mask to the original video resolution
380
+ obj_ids = inference_state["obj_ids"]
381
+ consolidated_out = self._consolidate_temp_output_across_obj(
382
+ inference_state,
383
+ frame_idx,
384
+ is_cond=is_cond,
385
+ consolidate_at_video_res=True,
386
+ )
387
+ _, video_res_masks = self._get_orig_video_res_output(
388
+ inference_state, consolidated_out["pred_masks_video_res"]
389
+ )
390
+ return frame_idx, obj_ids, video_res_masks
391
+
392
+ def _get_orig_video_res_output(self, inference_state, any_res_masks):
393
+ """
394
+ Resize the object scores to the original video resolution (video_res_masks)
395
+ and apply non-overlapping constraints for final output.
396
+ """
397
+ device = inference_state["device"]
398
+ video_H = inference_state["video_height"]
399
+ video_W = inference_state["video_width"]
400
+ any_res_masks = any_res_masks.to(device, non_blocking=True)
401
+ if any_res_masks.shape[-2:] == (video_H, video_W):
402
+ video_res_masks = any_res_masks
403
+ else:
404
+ video_res_masks = torch.nn.functional.interpolate(
405
+ any_res_masks,
406
+ size=(video_H, video_W),
407
+ mode="bilinear",
408
+ align_corners=False,
409
+ )
410
+ if self.non_overlap_masks:
411
+ video_res_masks = self._apply_non_overlapping_constraints(video_res_masks)
412
+ return any_res_masks, video_res_masks
413
+
414
+ def _consolidate_temp_output_across_obj(
415
+ self,
416
+ inference_state,
417
+ frame_idx,
418
+ is_cond,
419
+ consolidate_at_video_res=False,
420
+ ):
421
+ """
422
+ Consolidate the per-object temporary outputs in `temp_output_dict_per_obj` on
423
+ a frame into a single output for all objects, including
424
+ 1) fill any missing objects either from `output_dict_per_obj` (if they exist in
425
+ `output_dict_per_obj` for this frame) or leave them as placeholder values
426
+ (if they don't exist in `output_dict_per_obj` for this frame);
427
+ 2) if specified, rerun memory encoder after apply non-overlapping constraints
428
+ on the object scores.
429
+ """
430
+ batch_size = self._get_obj_num(inference_state)
431
+ storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
432
+ # Optionally, we allow consolidating the temporary outputs at the original
433
+ # video resolution (to provide a better editing experience for mask prompts).
434
+ if consolidate_at_video_res:
435
+ consolidated_H = inference_state["video_height"]
436
+ consolidated_W = inference_state["video_width"]
437
+ consolidated_mask_key = "pred_masks_video_res"
438
+ else:
439
+ consolidated_H = consolidated_W = self.image_size // 4
440
+ consolidated_mask_key = "pred_masks"
441
+
442
+ # Initialize `consolidated_out`. Its "maskmem_features" and "maskmem_pos_enc"
443
+ # will be added when rerunning the memory encoder after applying non-overlapping
444
+ # constraints to object scores. Its "pred_masks" are prefilled with a large
445
+ # negative value (NO_OBJ_SCORE) to represent missing objects.
446
+ consolidated_out = {
447
+ consolidated_mask_key: torch.full(
448
+ size=(batch_size, 1, consolidated_H, consolidated_W),
449
+ fill_value=NO_OBJ_SCORE,
450
+ dtype=torch.float32,
451
+ device=inference_state["storage_device"],
452
+ ),
453
+ }
454
+ for obj_idx in range(batch_size):
455
+ obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
456
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
457
+ out = obj_temp_output_dict[storage_key].get(frame_idx, None)
458
+ # If the object doesn't appear in "temp_output_dict_per_obj" on this frame,
459
+ # we fall back and look up its previous output in "output_dict_per_obj".
460
+ # We look up both "cond_frame_outputs" and "non_cond_frame_outputs" in
461
+ # "output_dict_per_obj" to find a previous output for this object.
462
+ if out is None:
463
+ out = obj_output_dict["cond_frame_outputs"].get(frame_idx, None)
464
+ if out is None:
465
+ out = obj_output_dict["non_cond_frame_outputs"].get(frame_idx, None)
466
+ # If the object doesn't appear in "output_dict_per_obj" either, we skip it
467
+ # and leave its mask scores to the default scores (i.e. the NO_OBJ_SCORE
468
+ # placeholder above) and set its object pointer to be a dummy pointer.
469
+ if out is None:
470
+ continue
471
+ # Add the temporary object output mask to consolidated output mask
472
+ obj_mask = out["pred_masks"]
473
+ consolidated_pred_masks = consolidated_out[consolidated_mask_key]
474
+ if obj_mask.shape[-2:] == consolidated_pred_masks.shape[-2:]:
475
+ consolidated_pred_masks[obj_idx : obj_idx + 1] = obj_mask
476
+ else:
477
+ # Resize first if temporary object mask has a different resolution
478
+ resized_obj_mask = torch.nn.functional.interpolate(
479
+ obj_mask,
480
+ size=consolidated_pred_masks.shape[-2:],
481
+ mode="bilinear",
482
+ align_corners=False,
483
+ )
484
+ consolidated_pred_masks[obj_idx : obj_idx + 1] = resized_obj_mask
485
+
486
+ return consolidated_out
487
+
488
+ @torch.inference_mode()
489
+ def propagate_in_video_preflight(self, inference_state):
490
+ """Prepare inference_state and consolidate temporary outputs before tracking."""
491
+ # Check and make sure that every object has received input points or masks.
492
+ batch_size = self._get_obj_num(inference_state)
493
+ if batch_size == 0:
494
+ raise RuntimeError(
495
+ "No input points or masks are provided for any object; please add inputs first."
496
+ )
497
+
498
+ # Consolidate per-object temporary outputs in "temp_output_dict_per_obj" and
499
+ # add them into "output_dict".
500
+ for obj_idx in range(batch_size):
501
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
502
+ obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
503
+ for is_cond in [False, True]:
504
+ # Separately consolidate conditioning and non-conditioning temp outputs
505
+ storage_key = (
506
+ "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
507
+ )
508
+ # Find all the frames that contain temporary outputs for any objects
509
+ # (these should be the frames that have just received clicks for mask inputs
510
+ # via `add_new_points_or_box` or `add_new_mask`)
511
+ for frame_idx, out in obj_temp_output_dict[storage_key].items():
512
+ # Run memory encoder on the temporary outputs (if the memory feature is missing)
513
+ if out["maskmem_features"] is None:
514
+ high_res_masks = torch.nn.functional.interpolate(
515
+ out["pred_masks"].to(inference_state["device"]),
516
+ size=(self.image_size, self.image_size),
517
+ mode="bilinear",
518
+ align_corners=False,
519
+ )
520
+ maskmem_features, maskmem_pos_enc = self._run_memory_encoder(
521
+ inference_state=inference_state,
522
+ frame_idx=frame_idx,
523
+ batch_size=1, # run on the slice of a single object
524
+ high_res_masks=high_res_masks,
525
+ object_score_logits=out["object_score_logits"],
526
+ # these frames are what the user interacted with
527
+ is_mask_from_pts=True,
528
+ )
529
+ out["maskmem_features"] = maskmem_features
530
+ out["maskmem_pos_enc"] = maskmem_pos_enc
531
+
532
+ obj_output_dict[storage_key][frame_idx] = out
533
+ if self.clear_non_cond_mem_around_input:
534
+ # clear non-conditioning memory of the surrounding frames
535
+ self._clear_obj_non_cond_mem_around_input(
536
+ inference_state, frame_idx, obj_idx
537
+ )
538
+
539
+ # clear temporary outputs in `temp_output_dict_per_obj`
540
+ obj_temp_output_dict[storage_key].clear()
541
+
542
+ # check and make sure that every object has received input points or masks
543
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
544
+ if len(obj_output_dict["cond_frame_outputs"]) == 0:
545
+ obj_id = self._obj_idx_to_id(inference_state, obj_idx)
546
+ raise RuntimeError(
547
+ f"No input points or masks are provided for object id {obj_id}; please add inputs first."
548
+ )
549
+ # edge case: if an output is added to "cond_frame_outputs", we remove any prior
550
+ # output on the same frame in "non_cond_frame_outputs"
551
+ for frame_idx in obj_output_dict["cond_frame_outputs"]:
552
+ obj_output_dict["non_cond_frame_outputs"].pop(frame_idx, None)
553
+
554
+ @torch.inference_mode()
555
+ def propagate_in_video(
556
+ self,
557
+ inference_state,
558
+ start_frame_idx=None,
559
+ max_frame_num_to_track=None,
560
+ reverse=False,
561
+ ):
562
+ """Propagate the input points across frames to track in the entire video."""
563
+ self.propagate_in_video_preflight(inference_state)
564
+
565
+ obj_ids = inference_state["obj_ids"]
566
+ num_frames = inference_state["num_frames"]
567
+ batch_size = self._get_obj_num(inference_state)
568
+
569
+ # set start index, end index, and processing order
570
+ if start_frame_idx is None:
571
+ # default: start from the earliest frame with input points
572
+ start_frame_idx = min(
573
+ t
574
+ for obj_output_dict in inference_state["output_dict_per_obj"].values()
575
+ for t in obj_output_dict["cond_frame_outputs"]
576
+ )
577
+ if max_frame_num_to_track is None:
578
+ # default: track all the frames in the video
579
+ max_frame_num_to_track = num_frames
580
+ if reverse:
581
+ end_frame_idx = max(start_frame_idx - max_frame_num_to_track, 0)
582
+ if start_frame_idx > 0:
583
+ processing_order = range(start_frame_idx, end_frame_idx - 1, -1)
584
+ else:
585
+ processing_order = [] # skip reverse tracking if starting from frame 0
586
+ else:
587
+ end_frame_idx = min(
588
+ start_frame_idx + max_frame_num_to_track, num_frames - 1
589
+ )
590
+ processing_order = range(start_frame_idx, end_frame_idx + 1)
591
+
592
+ for frame_idx in tqdm(processing_order, desc="propagate in video"):
593
+ pred_masks_per_obj = [None] * batch_size
594
+ for obj_idx in range(batch_size):
595
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
596
+ # We skip those frames already in consolidated outputs (these are frames
597
+ # that received input clicks or mask). Note that we cannot directly run
598
+ # batched forward on them via `_run_single_frame_inference` because the
599
+ # number of clicks on each object might be different.
600
+ if frame_idx in obj_output_dict["cond_frame_outputs"]:
601
+ storage_key = "cond_frame_outputs"
602
+ current_out = obj_output_dict[storage_key][frame_idx]
603
+ device = inference_state["device"]
604
+ pred_masks = current_out["pred_masks"].to(device, non_blocking=True)
605
+ if self.clear_non_cond_mem_around_input:
606
+ # clear non-conditioning memory of the surrounding frames
607
+ self._clear_obj_non_cond_mem_around_input(
608
+ inference_state, frame_idx, obj_idx
609
+ )
610
+ else:
611
+ storage_key = "non_cond_frame_outputs"
612
+ current_out, pred_masks = self._run_single_frame_inference(
613
+ inference_state=inference_state,
614
+ output_dict=obj_output_dict,
615
+ frame_idx=frame_idx,
616
+ batch_size=1, # run on the slice of a single object
617
+ is_init_cond_frame=False,
618
+ point_inputs=None,
619
+ mask_inputs=None,
620
+ reverse=reverse,
621
+ run_mem_encoder=True,
622
+ )
623
+ obj_output_dict[storage_key][frame_idx] = current_out
624
+
625
+ inference_state["frames_tracked_per_obj"][obj_idx][frame_idx] = {
626
+ "reverse": reverse
627
+ }
628
+ pred_masks_per_obj[obj_idx] = pred_masks
629
+
630
+ # Resize the output mask to the original video resolution (we directly use
631
+ # the mask scores on GPU for output to avoid any CPU conversion in between)
632
+ if len(pred_masks_per_obj) > 1:
633
+ all_pred_masks = torch.cat(pred_masks_per_obj, dim=0)
634
+ else:
635
+ all_pred_masks = pred_masks_per_obj[0]
636
+ _, video_res_masks = self._get_orig_video_res_output(
637
+ inference_state, all_pred_masks
638
+ )
639
+ yield frame_idx, obj_ids, video_res_masks
640
+
641
+ @torch.inference_mode()
642
+ def clear_all_prompts_in_frame(
643
+ self, inference_state, frame_idx, obj_id, need_output=True
644
+ ):
645
+ """Remove all input points or mask in a specific frame for a given object."""
646
+ obj_idx = self._obj_id_to_idx(inference_state, obj_id)
647
+
648
+ # Clear the conditioning information on the given frame
649
+ inference_state["point_inputs_per_obj"][obj_idx].pop(frame_idx, None)
650
+ inference_state["mask_inputs_per_obj"][obj_idx].pop(frame_idx, None)
651
+
652
+ temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"]
653
+ temp_output_dict_per_obj[obj_idx]["cond_frame_outputs"].pop(frame_idx, None)
654
+ temp_output_dict_per_obj[obj_idx]["non_cond_frame_outputs"].pop(frame_idx, None)
655
+
656
+ # Remove the frame's conditioning output (possibly downgrading it to non-conditioning)
657
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
658
+ out = obj_output_dict["cond_frame_outputs"].pop(frame_idx, None)
659
+ if out is not None:
660
+ # The frame is not a conditioning frame anymore since it's not receiving inputs,
661
+ # so we "downgrade" its output (if exists) to a non-conditioning frame output.
662
+ obj_output_dict["non_cond_frame_outputs"][frame_idx] = out
663
+ inference_state["frames_tracked_per_obj"][obj_idx].pop(frame_idx, None)
664
+
665
+ if not need_output:
666
+ return
667
+ # Finally, output updated masks per object (after removing the inputs above)
668
+ obj_ids = inference_state["obj_ids"]
669
+ is_cond = any(
670
+ frame_idx in obj_temp_output_dict["cond_frame_outputs"]
671
+ for obj_temp_output_dict in temp_output_dict_per_obj.values()
672
+ )
673
+ consolidated_out = self._consolidate_temp_output_across_obj(
674
+ inference_state,
675
+ frame_idx,
676
+ is_cond=is_cond,
677
+ consolidate_at_video_res=True,
678
+ )
679
+ _, video_res_masks = self._get_orig_video_res_output(
680
+ inference_state, consolidated_out["pred_masks_video_res"]
681
+ )
682
+ return frame_idx, obj_ids, video_res_masks
683
+
684
+ @torch.inference_mode()
685
+ def reset_state(self, inference_state):
686
+ """Remove all input points or mask in all frames throughout the video."""
687
+ self._reset_tracking_results(inference_state)
688
+ # Remove all object ids
689
+ inference_state["obj_id_to_idx"].clear()
690
+ inference_state["obj_idx_to_id"].clear()
691
+ inference_state["obj_ids"].clear()
692
+ inference_state["point_inputs_per_obj"].clear()
693
+ inference_state["mask_inputs_per_obj"].clear()
694
+ inference_state["output_dict_per_obj"].clear()
695
+ inference_state["temp_output_dict_per_obj"].clear()
696
+ inference_state["frames_tracked_per_obj"].clear()
697
+
698
+ def _reset_tracking_results(self, inference_state):
699
+ """Reset all tracking inputs and results across the videos."""
700
+ for v in inference_state["point_inputs_per_obj"].values():
701
+ v.clear()
702
+ for v in inference_state["mask_inputs_per_obj"].values():
703
+ v.clear()
704
+ for v in inference_state["output_dict_per_obj"].values():
705
+ v["cond_frame_outputs"].clear()
706
+ v["non_cond_frame_outputs"].clear()
707
+ for v in inference_state["temp_output_dict_per_obj"].values():
708
+ v["cond_frame_outputs"].clear()
709
+ v["non_cond_frame_outputs"].clear()
710
+ for v in inference_state["frames_tracked_per_obj"].values():
711
+ v.clear()
712
+
713
+ def _get_image_feature(self, inference_state, frame_idx, batch_size):
714
+ """Compute the image features on a given frame."""
715
+ # Look up in the cache first
716
+ image, backbone_out = inference_state["cached_features"].get(
717
+ frame_idx, (None, None)
718
+ )
719
+ if backbone_out is None:
720
+ # Cache miss -- we will run inference on a single image
721
+ device = inference_state["device"]
722
+ image = inference_state["images"][frame_idx].to(device).float().unsqueeze(0)
723
+ backbone_out = self.forward_image(image)
724
+ # Cache the most recent frame's feature (for repeated interactions with
725
+ # a frame; we can use an LRU cache for more frames in the future).
726
+ inference_state["cached_features"] = {frame_idx: (image, backbone_out)}
727
+
728
+ # expand the features to have the same dimension as the number of objects
729
+ expanded_image = image.expand(batch_size, -1, -1, -1)
730
+ expanded_backbone_out = {
731
+ "backbone_fpn": backbone_out["backbone_fpn"].copy(),
732
+ "vision_pos_enc": backbone_out["vision_pos_enc"].copy(),
733
+ }
734
+ for i, feat in enumerate(expanded_backbone_out["backbone_fpn"]):
735
+ expanded_backbone_out["backbone_fpn"][i] = feat.expand(
736
+ batch_size, -1, -1, -1
737
+ )
738
+ for i, pos in enumerate(expanded_backbone_out["vision_pos_enc"]):
739
+ pos = pos.expand(batch_size, -1, -1, -1)
740
+ expanded_backbone_out["vision_pos_enc"][i] = pos
741
+
742
+ features = self._prepare_backbone_features(expanded_backbone_out)
743
+ features = (expanded_image,) + features
744
+ return features
745
+
746
+ def _run_single_frame_inference(
747
+ self,
748
+ inference_state,
749
+ output_dict,
750
+ frame_idx,
751
+ batch_size,
752
+ is_init_cond_frame,
753
+ point_inputs,
754
+ mask_inputs,
755
+ reverse,
756
+ run_mem_encoder,
757
+ prev_sam_mask_logits=None,
758
+ ):
759
+ """Run tracking on a single frame based on current inputs and previous memory."""
760
+ # Retrieve correct image features
761
+ (
762
+ _,
763
+ _,
764
+ current_vision_feats,
765
+ current_vision_pos_embeds,
766
+ feat_sizes,
767
+ ) = self._get_image_feature(inference_state, frame_idx, batch_size)
768
+
769
+ # point and mask should not appear as input simultaneously on the same frame
770
+ assert point_inputs is None or mask_inputs is None
771
+ current_out = self.track_step(
772
+ frame_idx=frame_idx,
773
+ is_init_cond_frame=is_init_cond_frame,
774
+ current_vision_feats=current_vision_feats,
775
+ current_vision_pos_embeds=current_vision_pos_embeds,
776
+ feat_sizes=feat_sizes,
777
+ point_inputs=point_inputs,
778
+ mask_inputs=mask_inputs,
779
+ output_dict=output_dict,
780
+ num_frames=inference_state["num_frames"],
781
+ track_in_reverse=reverse,
782
+ run_mem_encoder=run_mem_encoder,
783
+ prev_sam_mask_logits=prev_sam_mask_logits,
784
+ )
785
+
786
+ # optionally offload the output to CPU memory to save GPU space
787
+ storage_device = inference_state["storage_device"]
788
+ maskmem_features = current_out["maskmem_features"]
789
+ if maskmem_features is not None:
790
+ maskmem_features = maskmem_features.to(torch.bfloat16)
791
+ maskmem_features = maskmem_features.to(storage_device, non_blocking=True)
792
+ pred_masks_gpu = current_out["pred_masks"]
793
+ # potentially fill holes in the predicted masks
794
+ if self.fill_hole_area > 0:
795
+ pred_masks_gpu = fill_holes_in_mask_scores(
796
+ pred_masks_gpu, self.fill_hole_area
797
+ )
798
+ pred_masks = pred_masks_gpu.to(storage_device, non_blocking=True)
799
+ # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
800
+ maskmem_pos_enc = self._get_maskmem_pos_enc(inference_state, current_out)
801
+ # object pointer is a small tensor, so we always keep it on GPU memory for fast access
802
+ obj_ptr = current_out["obj_ptr"]
803
+ object_score_logits = current_out["object_score_logits"]
804
+ # make a compact version of this frame's output to reduce the state size
805
+ compact_current_out = {
806
+ "maskmem_features": maskmem_features,
807
+ "maskmem_pos_enc": maskmem_pos_enc,
808
+ "pred_masks": pred_masks,
809
+ "obj_ptr": obj_ptr,
810
+ "object_score_logits": object_score_logits,
811
+ }
812
+ return compact_current_out, pred_masks_gpu
813
+
814
+ def _run_memory_encoder(
815
+ self,
816
+ inference_state,
817
+ frame_idx,
818
+ batch_size,
819
+ high_res_masks,
820
+ object_score_logits,
821
+ is_mask_from_pts,
822
+ ):
823
+ """
824
+ Run the memory encoder on `high_res_masks`. This is usually after applying
825
+ non-overlapping constraints to object scores. Since their scores changed, their
826
+ memory also need to be computed again with the memory encoder.
827
+ """
828
+ # Retrieve correct image features
829
+ _, _, current_vision_feats, _, feat_sizes = self._get_image_feature(
830
+ inference_state, frame_idx, batch_size
831
+ )
832
+ maskmem_features, maskmem_pos_enc = self._encode_new_memory(
833
+ current_vision_feats=current_vision_feats,
834
+ feat_sizes=feat_sizes,
835
+ pred_masks_high_res=high_res_masks,
836
+ object_score_logits=object_score_logits,
837
+ is_mask_from_pts=is_mask_from_pts,
838
+ )
839
+
840
+ # optionally offload the output to CPU memory to save GPU space
841
+ storage_device = inference_state["storage_device"]
842
+ maskmem_features = maskmem_features.to(torch.bfloat16)
843
+ maskmem_features = maskmem_features.to(storage_device, non_blocking=True)
844
+ # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
845
+ maskmem_pos_enc = self._get_maskmem_pos_enc(
846
+ inference_state, {"maskmem_pos_enc": maskmem_pos_enc}
847
+ )
848
+ return maskmem_features, maskmem_pos_enc
849
+
850
+ def _get_maskmem_pos_enc(self, inference_state, current_out):
851
+ """
852
+ `maskmem_pos_enc` is the same across frames and objects, so we cache it as
853
+ a constant in the inference session to reduce session storage size.
854
+ """
855
+ model_constants = inference_state["constants"]
856
+ # "out_maskmem_pos_enc" should be either a list of tensors or None
857
+ out_maskmem_pos_enc = current_out["maskmem_pos_enc"]
858
+ if out_maskmem_pos_enc is not None:
859
+ if "maskmem_pos_enc" not in model_constants:
860
+ assert isinstance(out_maskmem_pos_enc, list)
861
+ # only take the slice for one object, since it's same across objects
862
+ maskmem_pos_enc = [x[0:1].clone() for x in out_maskmem_pos_enc]
863
+ model_constants["maskmem_pos_enc"] = maskmem_pos_enc
864
+ else:
865
+ maskmem_pos_enc = model_constants["maskmem_pos_enc"]
866
+ # expand the cached maskmem_pos_enc to the actual batch size
867
+ batch_size = out_maskmem_pos_enc[0].size(0)
868
+ expanded_maskmem_pos_enc = [
869
+ x.expand(batch_size, -1, -1, -1) for x in maskmem_pos_enc
870
+ ]
871
+ else:
872
+ expanded_maskmem_pos_enc = None
873
+ return expanded_maskmem_pos_enc
874
+
875
+ @torch.inference_mode()
876
+ def remove_object(self, inference_state, obj_id, strict=False, need_output=True):
877
+ """
878
+ Remove an object id from the tracking state. If strict is True, we check whether
879
+ the object id actually exists and raise an error if it doesn't exist.
880
+ """
881
+ old_obj_idx_to_rm = inference_state["obj_id_to_idx"].get(obj_id, None)
882
+ updated_frames = []
883
+ # Check whether this object_id to remove actually exists and possibly raise an error.
884
+ if old_obj_idx_to_rm is None:
885
+ if not strict:
886
+ return inference_state["obj_ids"], updated_frames
887
+ raise RuntimeError(
888
+ f"Cannot remove object id {obj_id} as it doesn't exist. "
889
+ f"All existing object ids: {inference_state['obj_ids']}."
890
+ )
891
+
892
+ # If this is the only remaining object id, we simply reset the state.
893
+ if len(inference_state["obj_id_to_idx"]) == 1:
894
+ self.reset_state(inference_state)
895
+ return inference_state["obj_ids"], updated_frames
896
+
897
+ # There are still remaining objects after removing this object id. In this case,
898
+ # we need to delete the object storage from inference state tensors.
899
+ # Step 0: clear the input on those frames where this object id has point or mask input
900
+ # (note that this step is required as it might downgrade conditioning frames to
901
+ # non-conditioning ones)
902
+ obj_input_frames_inds = set()
903
+ obj_input_frames_inds.update(
904
+ inference_state["point_inputs_per_obj"][old_obj_idx_to_rm]
905
+ )
906
+ obj_input_frames_inds.update(
907
+ inference_state["mask_inputs_per_obj"][old_obj_idx_to_rm]
908
+ )
909
+ for frame_idx in obj_input_frames_inds:
910
+ self.clear_all_prompts_in_frame(
911
+ inference_state, frame_idx, obj_id, need_output=False
912
+ )
913
+
914
+ # Step 1: Update the object id mapping (note that it must be done after Step 0,
915
+ # since Step 0 still requires the old object id mappings in inference_state)
916
+ old_obj_ids = inference_state["obj_ids"]
917
+ old_obj_inds = list(range(len(old_obj_ids)))
918
+ remain_old_obj_inds = old_obj_inds.copy()
919
+ remain_old_obj_inds.remove(old_obj_idx_to_rm)
920
+ new_obj_ids = [old_obj_ids[old_idx] for old_idx in remain_old_obj_inds]
921
+ new_obj_inds = list(range(len(new_obj_ids)))
922
+ # build new mappings
923
+ old_idx_to_new_idx = dict(zip(remain_old_obj_inds, new_obj_inds))
924
+ inference_state["obj_id_to_idx"] = dict(zip(new_obj_ids, new_obj_inds))
925
+ inference_state["obj_idx_to_id"] = dict(zip(new_obj_inds, new_obj_ids))
926
+ inference_state["obj_ids"] = new_obj_ids
927
+
928
+ # Step 2: For per-object tensor storage, we shift their obj_idx in the dict keys.
929
+ def _map_keys(container):
930
+ new_kvs = []
931
+ for k in old_obj_inds:
932
+ v = container.pop(k)
933
+ if k in old_idx_to_new_idx:
934
+ new_kvs.append((old_idx_to_new_idx[k], v))
935
+ container.update(new_kvs)
936
+
937
+ _map_keys(inference_state["point_inputs_per_obj"])
938
+ _map_keys(inference_state["mask_inputs_per_obj"])
939
+ _map_keys(inference_state["output_dict_per_obj"])
940
+ _map_keys(inference_state["temp_output_dict_per_obj"])
941
+ _map_keys(inference_state["frames_tracked_per_obj"])
942
+
943
+ # Step 3: Further collect the outputs on those frames in `obj_input_frames_inds`, which
944
+ # could show an updated mask for objects previously occluded by the object being removed
945
+ if need_output:
946
+ temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"]
947
+ for frame_idx in obj_input_frames_inds:
948
+ is_cond = any(
949
+ frame_idx in obj_temp_output_dict["cond_frame_outputs"]
950
+ for obj_temp_output_dict in temp_output_dict_per_obj.values()
951
+ )
952
+ consolidated_out = self._consolidate_temp_output_across_obj(
953
+ inference_state,
954
+ frame_idx,
955
+ is_cond=is_cond,
956
+ consolidate_at_video_res=True,
957
+ )
958
+ _, video_res_masks = self._get_orig_video_res_output(
959
+ inference_state, consolidated_out["pred_masks_video_res"]
960
+ )
961
+ updated_frames.append((frame_idx, video_res_masks))
962
+
963
+ return inference_state["obj_ids"], updated_frames
964
+
965
+ def _clear_non_cond_mem_around_input(self, inference_state, frame_idx):
966
+ """
967
+ Remove the non-conditioning memory around the input frame. When users provide
968
+ correction clicks, the surrounding frames' non-conditioning memories can still
969
+ contain outdated object appearance information and could confuse the model.
970
+
971
+ This method clears those non-conditioning memories surrounding the interacted
972
+ frame to avoid giving the model both old and new information about the object.
973
+ """
974
+ r = self.memory_temporal_stride_for_eval
975
+ frame_idx_begin = frame_idx - r * self.num_maskmem
976
+ frame_idx_end = frame_idx + r * self.num_maskmem
977
+ batch_size = self._get_obj_num(inference_state)
978
+ for obj_idx in range(batch_size):
979
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
980
+ non_cond_frame_outputs = obj_output_dict["non_cond_frame_outputs"]
981
+ for t in range(frame_idx_begin, frame_idx_end + 1):
982
+ non_cond_frame_outputs.pop(t, None)
983
+
984
+
985
+ class EfficientTAMVideoPredictorVOS(EfficientTAMVideoPredictor):
986
+ """Optimized for the VOS setting"""
987
+
988
+ def __init__(self, *args, **kwargs):
989
+ super().__init__(*args, **kwargs)
990
+ self._compile_all_components()
991
+
992
+ def _compile_all_components(self):
993
+ print("Compiling all components for VOS setting. First time may be very slow.")
994
+ self.memory_encoder.forward = torch.compile(
995
+ self.memory_encoder.forward,
996
+ mode="max-autotune",
997
+ fullgraph=True,
998
+ dynamic=False,
999
+ )
1000
+
1001
+ self.memory_attention.forward = torch.compile(
1002
+ self.memory_attention.forward,
1003
+ mode="max-autotune",
1004
+ fullgraph=True,
1005
+ dynamic=True, # Num. of memories varies
1006
+ )
1007
+
1008
+ self.sam_prompt_encoder.forward = torch.compile(
1009
+ self.sam_prompt_encoder.forward,
1010
+ mode="max-autotune",
1011
+ fullgraph=True,
1012
+ dynamic=False, # Accuracy regression on True
1013
+ )
1014
+
1015
+ self.sam_mask_decoder.forward = torch.compile(
1016
+ self.sam_mask_decoder.forward,
1017
+ mode="max-autotune",
1018
+ fullgraph=True,
1019
+ dynamic=False, # Accuracy regression on True
1020
+ )
1021
+
1022
+ def forward_image(self, img_batch: torch.Tensor):
1023
+ """
1024
+ Identical to the corresponding method in the parent (EfficientTAMVideoPredictor), but
1025
+ cloning the backbone features and pos encoding to enable compilation.
1026
+ """
1027
+ backbone_out = self.image_encoder(img_batch)
1028
+ # Clone to help torch.compile
1029
+ for i in range(len(backbone_out["backbone_fpn"])):
1030
+ backbone_out["backbone_fpn"][i] = backbone_out["backbone_fpn"][i].clone()
1031
+ backbone_out["vision_pos_enc"][i] = backbone_out["vision_pos_enc"][
1032
+ i
1033
+ ].clone()
1034
+ return backbone_out
1035
+
1036
+ def _forward_sam_heads(
1037
+ self,
1038
+ backbone_features,
1039
+ point_inputs=None,
1040
+ mask_inputs=None,
1041
+ high_res_features=None,
1042
+ multimask_output=False,
1043
+ ):
1044
+ """
1045
+ Identical to the corresponding method in the parent (EfficientTAMVideoPredictor), but
1046
+ cloning the outputs of prompt_encoder and mask_decoder to enable compilation.
1047
+ """
1048
+ B = backbone_features.size(0)
1049
+ device = backbone_features.device
1050
+ assert backbone_features.size(1) == self.sam_prompt_embed_dim
1051
+ assert backbone_features.size(2) == self.sam_image_embedding_size
1052
+ assert backbone_features.size(3) == self.sam_image_embedding_size
1053
+
1054
+ # a) Handle point prompts
1055
+ if point_inputs is not None:
1056
+ sam_point_coords = point_inputs["point_coords"]
1057
+ sam_point_labels = point_inputs["point_labels"]
1058
+ assert sam_point_coords.size(0) == B and sam_point_labels.size(0) == B
1059
+ else:
1060
+ # If no points are provide, pad with an empty point (with label -1)
1061
+ sam_point_coords = torch.zeros(B, 1, 2, device=device)
1062
+ sam_point_labels = -torch.ones(B, 1, dtype=torch.int32, device=device)
1063
+
1064
+ # b) Handle mask prompts
1065
+ if mask_inputs is not None:
1066
+ # If mask_inputs is provided, downsize it into low-res mask input if needed
1067
+ # and feed it as a dense mask prompt into the SAM mask encoder
1068
+ assert len(mask_inputs.shape) == 4 and mask_inputs.shape[:2] == (B, 1)
1069
+ if mask_inputs.shape[-2:] != self.sam_prompt_encoder.mask_input_size:
1070
+ sam_mask_prompt = F.interpolate(
1071
+ mask_inputs.float(),
1072
+ size=self.sam_prompt_encoder.mask_input_size,
1073
+ align_corners=False,
1074
+ mode="bilinear",
1075
+ antialias=True, # use antialias for downsampling
1076
+ )
1077
+ else:
1078
+ sam_mask_prompt = mask_inputs
1079
+ else:
1080
+ # Otherwise, simply feed None (and SAM's prompt encoder will add
1081
+ # a learned `no_mask_embed` to indicate no mask input in this case).
1082
+ sam_mask_prompt = None
1083
+
1084
+ sparse_embeddings, dense_embeddings = self.sam_prompt_encoder(
1085
+ points=(sam_point_coords, sam_point_labels),
1086
+ boxes=None,
1087
+ masks=sam_mask_prompt,
1088
+ )
1089
+ # Clone image_pe and the outputs of sam_prompt_encoder
1090
+ # to enable compilation
1091
+ sparse_embeddings = sparse_embeddings.clone()
1092
+ dense_embeddings = dense_embeddings.clone()
1093
+ image_pe = self.sam_prompt_encoder.get_dense_pe().clone()
1094
+ (
1095
+ low_res_multimasks,
1096
+ ious,
1097
+ sam_output_tokens,
1098
+ object_score_logits,
1099
+ ) = self.sam_mask_decoder(
1100
+ image_embeddings=backbone_features,
1101
+ image_pe=image_pe,
1102
+ sparse_prompt_embeddings=sparse_embeddings,
1103
+ dense_prompt_embeddings=dense_embeddings,
1104
+ multimask_output=multimask_output,
1105
+ repeat_image=False, # the image is already batched
1106
+ high_res_features=high_res_features,
1107
+ )
1108
+ # Clone the output of sam_mask_decoder
1109
+ # to enable compilation
1110
+ low_res_multimasks = low_res_multimasks.clone()
1111
+ ious = ious.clone()
1112
+ sam_output_tokens = sam_output_tokens.clone()
1113
+ object_score_logits = object_score_logits.clone()
1114
+
1115
+ if self.pred_obj_scores:
1116
+ is_obj_appearing = object_score_logits > 0
1117
+
1118
+ # Mask used for spatial memories is always a *hard* choice between obj and no obj,
1119
+ # consistent with the actual mask prediction
1120
+ low_res_multimasks = torch.where(
1121
+ is_obj_appearing[:, None, None],
1122
+ low_res_multimasks,
1123
+ NO_OBJ_SCORE,
1124
+ )
1125
+
1126
+ # convert masks from possibly bfloat16 (or float16) to float32
1127
+ # (older PyTorch versions before 2.1 don't support `interpolate` on bf16)
1128
+ low_res_multimasks = low_res_multimasks.float()
1129
+ high_res_multimasks = F.interpolate(
1130
+ low_res_multimasks,
1131
+ size=(self.image_size, self.image_size),
1132
+ mode="bilinear",
1133
+ align_corners=False,
1134
+ )
1135
+
1136
+ sam_output_token = sam_output_tokens[:, 0]
1137
+ if multimask_output:
1138
+ # take the best mask prediction (with the highest IoU estimation)
1139
+ best_iou_inds = torch.argmax(ious, dim=-1)
1140
+ batch_inds = torch.arange(B, device=device)
1141
+ low_res_masks = low_res_multimasks[batch_inds, best_iou_inds].unsqueeze(1)
1142
+ high_res_masks = high_res_multimasks[batch_inds, best_iou_inds].unsqueeze(1)
1143
+ if sam_output_tokens.size(1) > 1:
1144
+ sam_output_token = sam_output_tokens[batch_inds, best_iou_inds]
1145
+ else:
1146
+ low_res_masks, high_res_masks = low_res_multimasks, high_res_multimasks
1147
+
1148
+ # Extract object pointer from the SAM output token (with occlusion handling)
1149
+ obj_ptr = self.obj_ptr_proj(sam_output_token)
1150
+ if self.pred_obj_scores:
1151
+ # Allow *soft* no obj ptr, unlike for masks
1152
+ if self.soft_no_obj_ptr:
1153
+ lambda_is_obj_appearing = object_score_logits.sigmoid()
1154
+ else:
1155
+ lambda_is_obj_appearing = is_obj_appearing.float()
1156
+
1157
+ if self.fixed_no_obj_ptr:
1158
+ obj_ptr = lambda_is_obj_appearing * obj_ptr
1159
+ obj_ptr = obj_ptr + (1 - lambda_is_obj_appearing) * self.no_obj_ptr
1160
+
1161
+ return (
1162
+ low_res_multimasks,
1163
+ high_res_multimasks,
1164
+ ious,
1165
+ low_res_masks,
1166
+ high_res_masks,
1167
+ obj_ptr,
1168
+ object_score_logits,
1169
+ )
1170
+
1171
+ def _encode_new_memory(
1172
+ self,
1173
+ current_vision_feats,
1174
+ feat_sizes,
1175
+ pred_masks_high_res,
1176
+ object_score_logits,
1177
+ is_mask_from_pts,
1178
+ ):
1179
+ """
1180
+ Identical to the corresponding method in the parent (EfficientTAMVideoPredictor), but
1181
+ cloning the memories and their pos enc to enable compilation.
1182
+ """
1183
+ B = current_vision_feats[-1].size(1) # batch size on this frame
1184
+ C = self.hidden_dim
1185
+ H, W = feat_sizes[-1] # top-level (lowest-resolution) feature size
1186
+ # top-level feature, (HW)BC => BCHW
1187
+ pix_feat = current_vision_feats[-1].permute(1, 2, 0).view(B, C, H, W)
1188
+ if self.non_overlap_masks_for_mem_enc and not self.training:
1189
+ # optionally, apply non-overlapping constraints to the masks (it's applied
1190
+ # in the batch dimension and should only be used during eval, where all
1191
+ # the objects come from the same video under batch size 1).
1192
+ pred_masks_high_res = self._apply_non_overlapping_constraints(
1193
+ pred_masks_high_res
1194
+ )
1195
+ # scale the raw mask logits with a temperature before applying sigmoid
1196
+ binarize = self.binarize_mask_from_pts_for_mem_enc and is_mask_from_pts
1197
+ if binarize and not self.training:
1198
+ mask_for_mem = (pred_masks_high_res > 0).float()
1199
+ else:
1200
+ # apply sigmoid on the raw mask logits to turn them into range (0, 1)
1201
+ mask_for_mem = torch.sigmoid(pred_masks_high_res)
1202
+ # apply scale and bias terms to the sigmoid probabilities
1203
+ if self.sigmoid_scale_for_mem_enc != 1.0:
1204
+ mask_for_mem = mask_for_mem * self.sigmoid_scale_for_mem_enc
1205
+ if self.sigmoid_bias_for_mem_enc != 0.0:
1206
+ mask_for_mem = mask_for_mem + self.sigmoid_bias_for_mem_enc
1207
+ maskmem_out = self.memory_encoder(
1208
+ pix_feat, mask_for_mem, skip_mask_sigmoid=True # sigmoid already applied
1209
+ )
1210
+ # Clone the feats and pos_enc to enable compilation
1211
+ maskmem_features = maskmem_out["vision_features"].clone()
1212
+ maskmem_pos_enc = [m.clone() for m in maskmem_out["vision_pos_enc"]]
1213
+ # add a no-object embedding to the spatial memory to indicate that the frame
1214
+ # is predicted to be occluded (i.e. no object is appearing in the frame)
1215
+ if self.no_obj_embed_spatial is not None:
1216
+ is_obj_appearing = (object_score_logits > 0).float()
1217
+ maskmem_features += (
1218
+ 1 - is_obj_appearing[..., None, None]
1219
+ ) * self.no_obj_embed_spatial[..., None, None].expand(
1220
+ *maskmem_features.shape
1221
+ )
1222
+
1223
+ return maskmem_features, maskmem_pos_enc
MedSAM2/efficient_track_anything/efficienttam_video_predictor_npz.py ADDED
@@ -0,0 +1,1226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import warnings
8
+ from collections import OrderedDict
9
+
10
+ import torch
11
+ import torch.nn.functional as F
12
+
13
+ from efficient_track_anything.modeling.efficienttam_base import (
14
+ EfficientTAMBase,
15
+ NO_OBJ_SCORE,
16
+ )
17
+ from efficient_track_anything.utils.misc import (
18
+ concat_points,
19
+ fill_holes_in_mask_scores,
20
+ load_video_frames,
21
+ )
22
+
23
+ from tqdm import tqdm
24
+
25
+
26
+ class EfficientTAMVideoPredictorNPZ(EfficientTAMBase):
27
+ """The predictor class to handle user interactions and manage inference states."""
28
+
29
+ def __init__(
30
+ self,
31
+ fill_hole_area=0,
32
+ # whether to apply non-overlapping constraints on the output object masks
33
+ non_overlap_masks=False,
34
+ # whether to clear non-conditioning memory of the surrounding frames (which may contain outdated information) after adding correction clicks;
35
+ # note that this would only apply to *single-object tracking* unless `clear_non_cond_mem_for_multi_obj` is also set to True)
36
+ clear_non_cond_mem_around_input=False,
37
+ # if `add_all_frames_to_correct_as_cond` is True, we also append to the conditioning frame list any frame that receives a later correction click
38
+ # if `add_all_frames_to_correct_as_cond` is False, we conditioning frame list to only use those initial conditioning frames
39
+ add_all_frames_to_correct_as_cond=False,
40
+ **kwargs,
41
+ ):
42
+ super().__init__(**kwargs)
43
+ self.fill_hole_area = fill_hole_area
44
+ self.non_overlap_masks = non_overlap_masks
45
+ self.clear_non_cond_mem_around_input = clear_non_cond_mem_around_input
46
+ self.add_all_frames_to_correct_as_cond = add_all_frames_to_correct_as_cond
47
+
48
+ @torch.inference_mode()
49
+ def init_state(
50
+ self,
51
+ images,
52
+ video_height,
53
+ video_width,
54
+ #video_path,
55
+ offload_video_to_cpu=False,
56
+ offload_state_to_cpu=False,
57
+ async_loading_frames=False,
58
+ ):
59
+ """Initialize an inference state."""
60
+ compute_device = self.device # device of the model
61
+ # images, video_height, video_width = load_video_frames(
62
+ # video_path=video_path,
63
+ # image_size=self.image_size,
64
+ # offload_video_to_cpu=offload_video_to_cpu,
65
+ # async_loading_frames=async_loading_frames,
66
+ # compute_device=compute_device,
67
+ # )
68
+ inference_state = {}
69
+ inference_state["images"] = images
70
+ inference_state["num_frames"] = len(images)
71
+ # whether to offload the video frames to CPU memory
72
+ # turning on this option saves the GPU memory with only a very small overhead
73
+ inference_state["offload_video_to_cpu"] = offload_video_to_cpu
74
+ # whether to offload the inference state to CPU memory
75
+ # turning on this option saves the GPU memory at the cost of a lower tracking fps
76
+ # (e.g. in a test case of 768x768 model, fps dropped from 27 to 24 when tracking one object
77
+ # and from 24 to 21 when tracking two objects)
78
+ inference_state["offload_state_to_cpu"] = offload_state_to_cpu
79
+ # the original video height and width, used for resizing final output scores
80
+ inference_state["video_height"] = video_height
81
+ inference_state["video_width"] = video_width
82
+ inference_state["device"] = compute_device
83
+ if offload_state_to_cpu:
84
+ inference_state["storage_device"] = torch.device("cpu")
85
+ else:
86
+ inference_state["storage_device"] = compute_device
87
+ # inputs on each frame
88
+ inference_state["point_inputs_per_obj"] = {}
89
+ inference_state["mask_inputs_per_obj"] = {}
90
+ # visual features on a small number of recently visited frames for quick interactions
91
+ inference_state["cached_features"] = {}
92
+ # values that don't change across frames (so we only need to hold one copy of them)
93
+ inference_state["constants"] = {}
94
+ # mapping between client-side object id and model-side object index
95
+ inference_state["obj_id_to_idx"] = OrderedDict()
96
+ inference_state["obj_idx_to_id"] = OrderedDict()
97
+ inference_state["obj_ids"] = []
98
+ # Slice (view) of each object tracking results, sharing the same memory with "output_dict"
99
+ inference_state["output_dict_per_obj"] = {}
100
+ # A temporary storage to hold new outputs when user interact with a frame
101
+ # to add clicks or mask (it's merged into "output_dict" before propagation starts)
102
+ inference_state["temp_output_dict_per_obj"] = {}
103
+ # Frames that already holds consolidated outputs from click or mask inputs
104
+ # (we directly use their consolidated outputs during tracking)
105
+ # metadata for each tracking frame (e.g. which direction it's tracked)
106
+ inference_state["frames_tracked_per_obj"] = {}
107
+ # Warm up the visual backbone and cache the image feature on frame 0
108
+ self._get_image_feature(inference_state, frame_idx=0, batch_size=1)
109
+ return inference_state
110
+
111
+ @classmethod
112
+ def from_pretrained(cls, model_id: str, **kwargs) -> "EfficientTAMVideoPredictor":
113
+ """
114
+ Load a pretrained model from the Hugging Face hub.
115
+
116
+ Arguments:
117
+ model_id (str): The Hugging Face repository ID.
118
+ **kwargs: Additional arguments to pass to the model constructor.
119
+
120
+ Returns:
121
+ (EfficientTAMVideoPredictor): The loaded model.
122
+ """
123
+ from efficient_track_anything.build_efficienttam import (
124
+ build_efficienttam_video_predictor_hf,
125
+ )
126
+
127
+ efficienttam_model = build_efficienttam_video_predictor_hf(model_id, **kwargs)
128
+ return efficienttam_model
129
+
130
+ def _obj_id_to_idx(self, inference_state, obj_id):
131
+ """Map client-side object id to model-side object index."""
132
+ obj_idx = inference_state["obj_id_to_idx"].get(obj_id, None)
133
+ if obj_idx is not None:
134
+ return obj_idx
135
+
136
+ # We always allow adding new objects (including after tracking starts).
137
+ allow_new_object = True
138
+ if allow_new_object:
139
+ # get the next object slot
140
+ obj_idx = len(inference_state["obj_id_to_idx"])
141
+ inference_state["obj_id_to_idx"][obj_id] = obj_idx
142
+ inference_state["obj_idx_to_id"][obj_idx] = obj_id
143
+ inference_state["obj_ids"] = list(inference_state["obj_id_to_idx"])
144
+ # set up input and output structures for this object
145
+ inference_state["point_inputs_per_obj"][obj_idx] = {}
146
+ inference_state["mask_inputs_per_obj"][obj_idx] = {}
147
+ inference_state["output_dict_per_obj"][obj_idx] = {
148
+ "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
149
+ "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
150
+ }
151
+ inference_state["temp_output_dict_per_obj"][obj_idx] = {
152
+ "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
153
+ "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
154
+ }
155
+ inference_state["frames_tracked_per_obj"][obj_idx] = {}
156
+ return obj_idx
157
+ else:
158
+ raise RuntimeError(
159
+ f"Cannot add new object id {obj_id} after tracking starts. "
160
+ f"All existing object ids: {inference_state['obj_ids']}. "
161
+ f"Please call 'reset_state' to restart from scratch."
162
+ )
163
+
164
+ def _obj_idx_to_id(self, inference_state, obj_idx):
165
+ """Map model-side object index to client-side object id."""
166
+ return inference_state["obj_idx_to_id"][obj_idx]
167
+
168
+ def _get_obj_num(self, inference_state):
169
+ """Get the total number of unique object ids received so far in this session."""
170
+ return len(inference_state["obj_idx_to_id"])
171
+
172
+ @torch.inference_mode()
173
+ def add_new_points_or_box(
174
+ self,
175
+ inference_state,
176
+ frame_idx,
177
+ obj_id,
178
+ points=None,
179
+ labels=None,
180
+ clear_old_points=True,
181
+ normalize_coords=True,
182
+ box=None,
183
+ ):
184
+ """Add new points to a frame."""
185
+ obj_idx = self._obj_id_to_idx(inference_state, obj_id)
186
+ point_inputs_per_frame = inference_state["point_inputs_per_obj"][obj_idx]
187
+ mask_inputs_per_frame = inference_state["mask_inputs_per_obj"][obj_idx]
188
+
189
+ if (points is not None) != (labels is not None):
190
+ raise ValueError("points and labels must be provided together")
191
+ if points is None and box is None:
192
+ raise ValueError("at least one of points or box must be provided as input")
193
+
194
+ if points is None:
195
+ points = torch.zeros(0, 2, dtype=torch.float32)
196
+ elif not isinstance(points, torch.Tensor):
197
+ points = torch.tensor(points, dtype=torch.float32)
198
+ if labels is None:
199
+ labels = torch.zeros(0, dtype=torch.int32)
200
+ elif not isinstance(labels, torch.Tensor):
201
+ labels = torch.tensor(labels, dtype=torch.int32)
202
+ if points.dim() == 2:
203
+ points = points.unsqueeze(0) # add batch dimension
204
+ if labels.dim() == 1:
205
+ labels = labels.unsqueeze(0) # add batch dimension
206
+
207
+ # If `box` is provided, we add it as the first two points with labels 2 and 3
208
+ # along with the user-provided points (consistent with how EfficientTAM is trained).
209
+ if box is not None:
210
+ if not clear_old_points:
211
+ raise ValueError(
212
+ "cannot add box without clearing old points, since "
213
+ "box prompt must be provided before any point prompt "
214
+ "(please use clear_old_points=True instead)"
215
+ )
216
+ if not isinstance(box, torch.Tensor):
217
+ box = torch.tensor(box, dtype=torch.float32, device=points.device)
218
+ box_coords = box.reshape(1, 2, 2)
219
+ box_labels = torch.tensor([2, 3], dtype=torch.int32, device=labels.device)
220
+ box_labels = box_labels.reshape(1, 2)
221
+ points = torch.cat([box_coords, points], dim=1)
222
+ labels = torch.cat([box_labels, labels], dim=1)
223
+
224
+ if normalize_coords:
225
+ video_H = inference_state["video_height"]
226
+ video_W = inference_state["video_width"]
227
+ points = points / torch.tensor([video_W, video_H]).to(points.device)
228
+ # scale the (normalized) coordinates by the model's internal image size
229
+ points = points * self.image_size
230
+ points = points.to(inference_state["device"])
231
+ labels = labels.to(inference_state["device"])
232
+
233
+ if not clear_old_points:
234
+ point_inputs = point_inputs_per_frame.get(frame_idx, None)
235
+ else:
236
+ point_inputs = None
237
+ point_inputs = concat_points(point_inputs, points, labels)
238
+
239
+ point_inputs_per_frame[frame_idx] = point_inputs
240
+ mask_inputs_per_frame.pop(frame_idx, None)
241
+ # If this frame hasn't been tracked before, we treat it as an initial conditioning
242
+ # frame, meaning that the inputs points are to generate segments on this frame without
243
+ # using any memory from other frames, like in SAM. Otherwise (if it has been tracked),
244
+ # the input points will be used to correct the already tracked masks.
245
+ obj_frames_tracked = inference_state["frames_tracked_per_obj"][obj_idx]
246
+ is_init_cond_frame = frame_idx not in obj_frames_tracked
247
+ # whether to track in reverse time order
248
+ if is_init_cond_frame:
249
+ reverse = False
250
+ else:
251
+ reverse = obj_frames_tracked[frame_idx]["reverse"]
252
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
253
+ obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
254
+ # Add a frame to conditioning output if it's an initial conditioning frame or
255
+ # if the model sees all frames receiving clicks/mask as conditioning frames.
256
+ is_cond = is_init_cond_frame or self.add_all_frames_to_correct_as_cond
257
+ storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
258
+
259
+ # Get any previously predicted mask logits on this object and feed it along with
260
+ # the new clicks into the SAM mask decoder.
261
+ prev_sam_mask_logits = None
262
+ # lookup temporary output dict first, which contains the most recent output
263
+ # (if not found, then lookup conditioning and non-conditioning frame output)
264
+ prev_out = obj_temp_output_dict[storage_key].get(frame_idx)
265
+ if prev_out is None:
266
+ prev_out = obj_output_dict["cond_frame_outputs"].get(frame_idx)
267
+ if prev_out is None:
268
+ prev_out = obj_output_dict["non_cond_frame_outputs"].get(frame_idx)
269
+
270
+ if prev_out is not None and prev_out["pred_masks"] is not None:
271
+ device = inference_state["device"]
272
+ prev_sam_mask_logits = prev_out["pred_masks"].to(device, non_blocking=True)
273
+ # Clamp the scale of prev_sam_mask_logits to avoid rare numerical issues.
274
+ prev_sam_mask_logits = torch.clamp(prev_sam_mask_logits, -32.0, 32.0)
275
+ current_out, _ = self._run_single_frame_inference(
276
+ inference_state=inference_state,
277
+ output_dict=obj_output_dict, # run on the slice of a single object
278
+ frame_idx=frame_idx,
279
+ batch_size=1, # run on the slice of a single object
280
+ is_init_cond_frame=is_init_cond_frame,
281
+ point_inputs=point_inputs,
282
+ mask_inputs=None,
283
+ reverse=reverse,
284
+ # Skip the memory encoder when adding clicks or mask. We execute the memory encoder
285
+ # at the beginning of `propagate_in_video` (after user finalize their clicks). This
286
+ # allows us to enforce non-overlapping constraints on all objects before encoding
287
+ # them into memory.
288
+ run_mem_encoder=False,
289
+ prev_sam_mask_logits=prev_sam_mask_logits,
290
+ )
291
+ # Add the output to the output dict (to be used as future memory)
292
+ obj_temp_output_dict[storage_key][frame_idx] = current_out
293
+
294
+ # Resize the output mask to the original video resolution
295
+ obj_ids = inference_state["obj_ids"]
296
+ consolidated_out = self._consolidate_temp_output_across_obj(
297
+ inference_state,
298
+ frame_idx,
299
+ is_cond=is_cond,
300
+ consolidate_at_video_res=True,
301
+ )
302
+ _, video_res_masks = self._get_orig_video_res_output(
303
+ inference_state, consolidated_out["pred_masks_video_res"]
304
+ )
305
+ return frame_idx, obj_ids, video_res_masks
306
+
307
+ def add_new_points(self, *args, **kwargs):
308
+ """Deprecated method. Please use `add_new_points_or_box` instead."""
309
+ return self.add_new_points_or_box(*args, **kwargs)
310
+
311
+ @torch.inference_mode()
312
+ def add_new_mask(
313
+ self,
314
+ inference_state,
315
+ frame_idx,
316
+ obj_id,
317
+ mask,
318
+ ):
319
+ """Add new mask to a frame."""
320
+ obj_idx = self._obj_id_to_idx(inference_state, obj_id)
321
+ point_inputs_per_frame = inference_state["point_inputs_per_obj"][obj_idx]
322
+ mask_inputs_per_frame = inference_state["mask_inputs_per_obj"][obj_idx]
323
+
324
+ if not isinstance(mask, torch.Tensor):
325
+ mask = torch.tensor(mask, dtype=torch.bool)
326
+ assert mask.dim() == 2
327
+ mask_H, mask_W = mask.shape
328
+ mask_inputs_orig = mask[None, None] # add batch and channel dimension
329
+ mask_inputs_orig = mask_inputs_orig.float().to(inference_state["device"])
330
+
331
+ # resize the mask if it doesn't match the model's image size
332
+ if mask_H != self.image_size or mask_W != self.image_size:
333
+ mask_inputs = torch.nn.functional.interpolate(
334
+ mask_inputs_orig,
335
+ size=(self.image_size, self.image_size),
336
+ align_corners=False,
337
+ mode="bilinear",
338
+ antialias=True, # use antialias for downsampling
339
+ )
340
+ mask_inputs = (mask_inputs >= 0.5).float()
341
+ else:
342
+ mask_inputs = mask_inputs_orig
343
+
344
+ mask_inputs_per_frame[frame_idx] = mask_inputs
345
+ point_inputs_per_frame.pop(frame_idx, None)
346
+ # If this frame hasn't been tracked before, we treat it as an initial conditioning
347
+ # frame, meaning that the inputs points are to generate segments on this frame without
348
+ # using any memory from other frames, like in SAM. Otherwise (if it has been tracked),
349
+ # the input points will be used to correct the already tracked masks.
350
+ obj_frames_tracked = inference_state["frames_tracked_per_obj"][obj_idx]
351
+ is_init_cond_frame = frame_idx not in obj_frames_tracked
352
+ # whether to track in reverse time order
353
+ if is_init_cond_frame:
354
+ reverse = False
355
+ else:
356
+ reverse = obj_frames_tracked[frame_idx]["reverse"]
357
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
358
+ obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
359
+ # Add a frame to conditioning output if it's an initial conditioning frame or
360
+ # if the model sees all frames receiving clicks/mask as conditioning frames.
361
+ is_cond = is_init_cond_frame or self.add_all_frames_to_correct_as_cond
362
+ storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
363
+
364
+ current_out, _ = self._run_single_frame_inference(
365
+ inference_state=inference_state,
366
+ output_dict=obj_output_dict, # run on the slice of a single object
367
+ frame_idx=frame_idx,
368
+ batch_size=1, # run on the slice of a single object
369
+ is_init_cond_frame=is_init_cond_frame,
370
+ point_inputs=None,
371
+ mask_inputs=mask_inputs,
372
+ reverse=reverse,
373
+ # Skip the memory encoder when adding clicks or mask. We execute the memory encoder
374
+ # at the beginning of `propagate_in_video` (after user finalize their clicks). This
375
+ # allows us to enforce non-overlapping constraints on all objects before encoding
376
+ # them into memory.
377
+ run_mem_encoder=False,
378
+ )
379
+ # Add the output to the output dict (to be used as future memory)
380
+ obj_temp_output_dict[storage_key][frame_idx] = current_out
381
+
382
+ # Resize the output mask to the original video resolution
383
+ obj_ids = inference_state["obj_ids"]
384
+ consolidated_out = self._consolidate_temp_output_across_obj(
385
+ inference_state,
386
+ frame_idx,
387
+ is_cond=is_cond,
388
+ consolidate_at_video_res=True,
389
+ )
390
+ _, video_res_masks = self._get_orig_video_res_output(
391
+ inference_state, consolidated_out["pred_masks_video_res"]
392
+ )
393
+ return frame_idx, obj_ids, video_res_masks
394
+
395
+ def _get_orig_video_res_output(self, inference_state, any_res_masks):
396
+ """
397
+ Resize the object scores to the original video resolution (video_res_masks)
398
+ and apply non-overlapping constraints for final output.
399
+ """
400
+ device = inference_state["device"]
401
+ video_H = inference_state["video_height"]
402
+ video_W = inference_state["video_width"]
403
+ any_res_masks = any_res_masks.to(device, non_blocking=True)
404
+ if any_res_masks.shape[-2:] == (video_H, video_W):
405
+ video_res_masks = any_res_masks
406
+ else:
407
+ video_res_masks = torch.nn.functional.interpolate(
408
+ any_res_masks,
409
+ size=(video_H, video_W),
410
+ mode="bilinear",
411
+ align_corners=False,
412
+ )
413
+ if self.non_overlap_masks:
414
+ video_res_masks = self._apply_non_overlapping_constraints(video_res_masks)
415
+ return any_res_masks, video_res_masks
416
+
417
+ def _consolidate_temp_output_across_obj(
418
+ self,
419
+ inference_state,
420
+ frame_idx,
421
+ is_cond,
422
+ consolidate_at_video_res=False,
423
+ ):
424
+ """
425
+ Consolidate the per-object temporary outputs in `temp_output_dict_per_obj` on
426
+ a frame into a single output for all objects, including
427
+ 1) fill any missing objects either from `output_dict_per_obj` (if they exist in
428
+ `output_dict_per_obj` for this frame) or leave them as placeholder values
429
+ (if they don't exist in `output_dict_per_obj` for this frame);
430
+ 2) if specified, rerun memory encoder after apply non-overlapping constraints
431
+ on the object scores.
432
+ """
433
+ batch_size = self._get_obj_num(inference_state)
434
+ storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
435
+ # Optionally, we allow consolidating the temporary outputs at the original
436
+ # video resolution (to provide a better editing experience for mask prompts).
437
+ if consolidate_at_video_res:
438
+ consolidated_H = inference_state["video_height"]
439
+ consolidated_W = inference_state["video_width"]
440
+ consolidated_mask_key = "pred_masks_video_res"
441
+ else:
442
+ consolidated_H = consolidated_W = self.image_size // 4
443
+ consolidated_mask_key = "pred_masks"
444
+
445
+ # Initialize `consolidated_out`. Its "maskmem_features" and "maskmem_pos_enc"
446
+ # will be added when rerunning the memory encoder after applying non-overlapping
447
+ # constraints to object scores. Its "pred_masks" are prefilled with a large
448
+ # negative value (NO_OBJ_SCORE) to represent missing objects.
449
+ consolidated_out = {
450
+ consolidated_mask_key: torch.full(
451
+ size=(batch_size, 1, consolidated_H, consolidated_W),
452
+ fill_value=NO_OBJ_SCORE,
453
+ dtype=torch.float32,
454
+ device=inference_state["storage_device"],
455
+ ),
456
+ }
457
+ for obj_idx in range(batch_size):
458
+ obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
459
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
460
+ out = obj_temp_output_dict[storage_key].get(frame_idx, None)
461
+ # If the object doesn't appear in "temp_output_dict_per_obj" on this frame,
462
+ # we fall back and look up its previous output in "output_dict_per_obj".
463
+ # We look up both "cond_frame_outputs" and "non_cond_frame_outputs" in
464
+ # "output_dict_per_obj" to find a previous output for this object.
465
+ if out is None:
466
+ out = obj_output_dict["cond_frame_outputs"].get(frame_idx, None)
467
+ if out is None:
468
+ out = obj_output_dict["non_cond_frame_outputs"].get(frame_idx, None)
469
+ # If the object doesn't appear in "output_dict_per_obj" either, we skip it
470
+ # and leave its mask scores to the default scores (i.e. the NO_OBJ_SCORE
471
+ # placeholder above) and set its object pointer to be a dummy pointer.
472
+ if out is None:
473
+ continue
474
+ # Add the temporary object output mask to consolidated output mask
475
+ obj_mask = out["pred_masks"]
476
+ consolidated_pred_masks = consolidated_out[consolidated_mask_key]
477
+ if obj_mask.shape[-2:] == consolidated_pred_masks.shape[-2:]:
478
+ consolidated_pred_masks[obj_idx : obj_idx + 1] = obj_mask
479
+ else:
480
+ # Resize first if temporary object mask has a different resolution
481
+ resized_obj_mask = torch.nn.functional.interpolate(
482
+ obj_mask,
483
+ size=consolidated_pred_masks.shape[-2:],
484
+ mode="bilinear",
485
+ align_corners=False,
486
+ )
487
+ consolidated_pred_masks[obj_idx : obj_idx + 1] = resized_obj_mask
488
+
489
+ return consolidated_out
490
+
491
+ @torch.inference_mode()
492
+ def propagate_in_video_preflight(self, inference_state):
493
+ """Prepare inference_state and consolidate temporary outputs before tracking."""
494
+ # Check and make sure that every object has received input points or masks.
495
+ batch_size = self._get_obj_num(inference_state)
496
+ if batch_size == 0:
497
+ raise RuntimeError(
498
+ "No input points or masks are provided for any object; please add inputs first."
499
+ )
500
+
501
+ # Consolidate per-object temporary outputs in "temp_output_dict_per_obj" and
502
+ # add them into "output_dict".
503
+ for obj_idx in range(batch_size):
504
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
505
+ obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
506
+ for is_cond in [False, True]:
507
+ # Separately consolidate conditioning and non-conditioning temp outputs
508
+ storage_key = (
509
+ "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
510
+ )
511
+ # Find all the frames that contain temporary outputs for any objects
512
+ # (these should be the frames that have just received clicks for mask inputs
513
+ # via `add_new_points_or_box` or `add_new_mask`)
514
+ for frame_idx, out in obj_temp_output_dict[storage_key].items():
515
+ # Run memory encoder on the temporary outputs (if the memory feature is missing)
516
+ if out["maskmem_features"] is None:
517
+ high_res_masks = torch.nn.functional.interpolate(
518
+ out["pred_masks"].to(inference_state["device"]),
519
+ size=(self.image_size, self.image_size),
520
+ mode="bilinear",
521
+ align_corners=False,
522
+ )
523
+ maskmem_features, maskmem_pos_enc = self._run_memory_encoder(
524
+ inference_state=inference_state,
525
+ frame_idx=frame_idx,
526
+ batch_size=1, # run on the slice of a single object
527
+ high_res_masks=high_res_masks,
528
+ object_score_logits=out["object_score_logits"],
529
+ # these frames are what the user interacted with
530
+ is_mask_from_pts=True,
531
+ )
532
+ out["maskmem_features"] = maskmem_features
533
+ out["maskmem_pos_enc"] = maskmem_pos_enc
534
+
535
+ obj_output_dict[storage_key][frame_idx] = out
536
+ if self.clear_non_cond_mem_around_input:
537
+ # clear non-conditioning memory of the surrounding frames
538
+ self._clear_obj_non_cond_mem_around_input(
539
+ inference_state, frame_idx, obj_idx
540
+ )
541
+
542
+ # clear temporary outputs in `temp_output_dict_per_obj`
543
+ obj_temp_output_dict[storage_key].clear()
544
+
545
+ # check and make sure that every object has received input points or masks
546
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
547
+ if len(obj_output_dict["cond_frame_outputs"]) == 0:
548
+ obj_id = self._obj_idx_to_id(inference_state, obj_idx)
549
+ raise RuntimeError(
550
+ f"No input points or masks are provided for object id {obj_id}; please add inputs first."
551
+ )
552
+ # edge case: if an output is added to "cond_frame_outputs", we remove any prior
553
+ # output on the same frame in "non_cond_frame_outputs"
554
+ for frame_idx in obj_output_dict["cond_frame_outputs"]:
555
+ obj_output_dict["non_cond_frame_outputs"].pop(frame_idx, None)
556
+
557
+ @torch.inference_mode()
558
+ def propagate_in_video(
559
+ self,
560
+ inference_state,
561
+ start_frame_idx=None,
562
+ max_frame_num_to_track=None,
563
+ reverse=False,
564
+ ):
565
+ """Propagate the input points across frames to track in the entire video."""
566
+ self.propagate_in_video_preflight(inference_state)
567
+
568
+ obj_ids = inference_state["obj_ids"]
569
+ num_frames = inference_state["num_frames"]
570
+ batch_size = self._get_obj_num(inference_state)
571
+
572
+ # set start index, end index, and processing order
573
+ if start_frame_idx is None:
574
+ # default: start from the earliest frame with input points
575
+ start_frame_idx = min(
576
+ t
577
+ for obj_output_dict in inference_state["output_dict_per_obj"].values()
578
+ for t in obj_output_dict["cond_frame_outputs"]
579
+ )
580
+ if max_frame_num_to_track is None:
581
+ # default: track all the frames in the video
582
+ max_frame_num_to_track = num_frames
583
+ if reverse:
584
+ end_frame_idx = max(start_frame_idx - max_frame_num_to_track, 0)
585
+ if start_frame_idx > 0:
586
+ processing_order = range(start_frame_idx, end_frame_idx - 1, -1)
587
+ else:
588
+ processing_order = [] # skip reverse tracking if starting from frame 0
589
+ else:
590
+ end_frame_idx = min(
591
+ start_frame_idx + max_frame_num_to_track, num_frames - 1
592
+ )
593
+ processing_order = range(start_frame_idx, end_frame_idx + 1)
594
+
595
+ for frame_idx in tqdm(processing_order, desc="propagate in video"):
596
+ pred_masks_per_obj = [None] * batch_size
597
+ for obj_idx in range(batch_size):
598
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
599
+ # We skip those frames already in consolidated outputs (these are frames
600
+ # that received input clicks or mask). Note that we cannot directly run
601
+ # batched forward on them via `_run_single_frame_inference` because the
602
+ # number of clicks on each object might be different.
603
+ if frame_idx in obj_output_dict["cond_frame_outputs"]:
604
+ storage_key = "cond_frame_outputs"
605
+ current_out = obj_output_dict[storage_key][frame_idx]
606
+ device = inference_state["device"]
607
+ pred_masks = current_out["pred_masks"].to(device, non_blocking=True)
608
+ if self.clear_non_cond_mem_around_input:
609
+ # clear non-conditioning memory of the surrounding frames
610
+ self._clear_obj_non_cond_mem_around_input(
611
+ inference_state, frame_idx, obj_idx
612
+ )
613
+ else:
614
+ storage_key = "non_cond_frame_outputs"
615
+ current_out, pred_masks = self._run_single_frame_inference(
616
+ inference_state=inference_state,
617
+ output_dict=obj_output_dict,
618
+ frame_idx=frame_idx,
619
+ batch_size=1, # run on the slice of a single object
620
+ is_init_cond_frame=False,
621
+ point_inputs=None,
622
+ mask_inputs=None,
623
+ reverse=reverse,
624
+ run_mem_encoder=True,
625
+ )
626
+ obj_output_dict[storage_key][frame_idx] = current_out
627
+
628
+ inference_state["frames_tracked_per_obj"][obj_idx][frame_idx] = {
629
+ "reverse": reverse
630
+ }
631
+ pred_masks_per_obj[obj_idx] = pred_masks
632
+
633
+ # Resize the output mask to the original video resolution (we directly use
634
+ # the mask scores on GPU for output to avoid any CPU conversion in between)
635
+ if len(pred_masks_per_obj) > 1:
636
+ all_pred_masks = torch.cat(pred_masks_per_obj, dim=0)
637
+ else:
638
+ all_pred_masks = pred_masks_per_obj[0]
639
+ _, video_res_masks = self._get_orig_video_res_output(
640
+ inference_state, all_pred_masks
641
+ )
642
+ yield frame_idx, obj_ids, video_res_masks
643
+
644
+ @torch.inference_mode()
645
+ def clear_all_prompts_in_frame(
646
+ self, inference_state, frame_idx, obj_id, need_output=True
647
+ ):
648
+ """Remove all input points or mask in a specific frame for a given object."""
649
+ obj_idx = self._obj_id_to_idx(inference_state, obj_id)
650
+
651
+ # Clear the conditioning information on the given frame
652
+ inference_state["point_inputs_per_obj"][obj_idx].pop(frame_idx, None)
653
+ inference_state["mask_inputs_per_obj"][obj_idx].pop(frame_idx, None)
654
+
655
+ temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"]
656
+ temp_output_dict_per_obj[obj_idx]["cond_frame_outputs"].pop(frame_idx, None)
657
+ temp_output_dict_per_obj[obj_idx]["non_cond_frame_outputs"].pop(frame_idx, None)
658
+
659
+ # Remove the frame's conditioning output (possibly downgrading it to non-conditioning)
660
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
661
+ out = obj_output_dict["cond_frame_outputs"].pop(frame_idx, None)
662
+ if out is not None:
663
+ # The frame is not a conditioning frame anymore since it's not receiving inputs,
664
+ # so we "downgrade" its output (if exists) to a non-conditioning frame output.
665
+ obj_output_dict["non_cond_frame_outputs"][frame_idx] = out
666
+ inference_state["frames_tracked_per_obj"][obj_idx].pop(frame_idx, None)
667
+
668
+ if not need_output:
669
+ return
670
+ # Finally, output updated masks per object (after removing the inputs above)
671
+ obj_ids = inference_state["obj_ids"]
672
+ is_cond = any(
673
+ frame_idx in obj_temp_output_dict["cond_frame_outputs"]
674
+ for obj_temp_output_dict in temp_output_dict_per_obj.values()
675
+ )
676
+ consolidated_out = self._consolidate_temp_output_across_obj(
677
+ inference_state,
678
+ frame_idx,
679
+ is_cond=is_cond,
680
+ consolidate_at_video_res=True,
681
+ )
682
+ _, video_res_masks = self._get_orig_video_res_output(
683
+ inference_state, consolidated_out["pred_masks_video_res"]
684
+ )
685
+ return frame_idx, obj_ids, video_res_masks
686
+
687
+ @torch.inference_mode()
688
+ def reset_state(self, inference_state):
689
+ """Remove all input points or mask in all frames throughout the video."""
690
+ self._reset_tracking_results(inference_state)
691
+ # Remove all object ids
692
+ inference_state["obj_id_to_idx"].clear()
693
+ inference_state["obj_idx_to_id"].clear()
694
+ inference_state["obj_ids"].clear()
695
+ inference_state["point_inputs_per_obj"].clear()
696
+ inference_state["mask_inputs_per_obj"].clear()
697
+ inference_state["output_dict_per_obj"].clear()
698
+ inference_state["temp_output_dict_per_obj"].clear()
699
+ inference_state["frames_tracked_per_obj"].clear()
700
+
701
+ def _reset_tracking_results(self, inference_state):
702
+ """Reset all tracking inputs and results across the videos."""
703
+ for v in inference_state["point_inputs_per_obj"].values():
704
+ v.clear()
705
+ for v in inference_state["mask_inputs_per_obj"].values():
706
+ v.clear()
707
+ for v in inference_state["output_dict_per_obj"].values():
708
+ v["cond_frame_outputs"].clear()
709
+ v["non_cond_frame_outputs"].clear()
710
+ for v in inference_state["temp_output_dict_per_obj"].values():
711
+ v["cond_frame_outputs"].clear()
712
+ v["non_cond_frame_outputs"].clear()
713
+ for v in inference_state["frames_tracked_per_obj"].values():
714
+ v.clear()
715
+
716
+ def _get_image_feature(self, inference_state, frame_idx, batch_size):
717
+ """Compute the image features on a given frame."""
718
+ # Look up in the cache first
719
+ image, backbone_out = inference_state["cached_features"].get(
720
+ frame_idx, (None, None)
721
+ )
722
+ if backbone_out is None:
723
+ # Cache miss -- we will run inference on a single image
724
+ device = inference_state["device"]
725
+ image = inference_state["images"][frame_idx].to(device).float().unsqueeze(0)
726
+ backbone_out = self.forward_image(image)
727
+ # Cache the most recent frame's feature (for repeated interactions with
728
+ # a frame; we can use an LRU cache for more frames in the future).
729
+ inference_state["cached_features"] = {frame_idx: (image, backbone_out)}
730
+
731
+ # expand the features to have the same dimension as the number of objects
732
+ expanded_image = image.expand(batch_size, -1, -1, -1)
733
+ expanded_backbone_out = {
734
+ "backbone_fpn": backbone_out["backbone_fpn"].copy(),
735
+ "vision_pos_enc": backbone_out["vision_pos_enc"].copy(),
736
+ }
737
+ for i, feat in enumerate(expanded_backbone_out["backbone_fpn"]):
738
+ expanded_backbone_out["backbone_fpn"][i] = feat.expand(
739
+ batch_size, -1, -1, -1
740
+ )
741
+ for i, pos in enumerate(expanded_backbone_out["vision_pos_enc"]):
742
+ pos = pos.expand(batch_size, -1, -1, -1)
743
+ expanded_backbone_out["vision_pos_enc"][i] = pos
744
+
745
+ features = self._prepare_backbone_features(expanded_backbone_out)
746
+ features = (expanded_image,) + features
747
+ return features
748
+
749
+ def _run_single_frame_inference(
750
+ self,
751
+ inference_state,
752
+ output_dict,
753
+ frame_idx,
754
+ batch_size,
755
+ is_init_cond_frame,
756
+ point_inputs,
757
+ mask_inputs,
758
+ reverse,
759
+ run_mem_encoder,
760
+ prev_sam_mask_logits=None,
761
+ ):
762
+ """Run tracking on a single frame based on current inputs and previous memory."""
763
+ # Retrieve correct image features
764
+ (
765
+ _,
766
+ _,
767
+ current_vision_feats,
768
+ current_vision_pos_embeds,
769
+ feat_sizes,
770
+ ) = self._get_image_feature(inference_state, frame_idx, batch_size)
771
+
772
+ # point and mask should not appear as input simultaneously on the same frame
773
+ assert point_inputs is None or mask_inputs is None
774
+ current_out = self.track_step(
775
+ frame_idx=frame_idx,
776
+ is_init_cond_frame=is_init_cond_frame,
777
+ current_vision_feats=current_vision_feats,
778
+ current_vision_pos_embeds=current_vision_pos_embeds,
779
+ feat_sizes=feat_sizes,
780
+ point_inputs=point_inputs,
781
+ mask_inputs=mask_inputs,
782
+ output_dict=output_dict,
783
+ num_frames=inference_state["num_frames"],
784
+ track_in_reverse=reverse,
785
+ run_mem_encoder=run_mem_encoder,
786
+ prev_sam_mask_logits=prev_sam_mask_logits,
787
+ )
788
+
789
+ # optionally offload the output to CPU memory to save GPU space
790
+ storage_device = inference_state["storage_device"]
791
+ maskmem_features = current_out["maskmem_features"]
792
+ if maskmem_features is not None:
793
+ maskmem_features = maskmem_features.to(torch.bfloat16)
794
+ maskmem_features = maskmem_features.to(storage_device, non_blocking=True)
795
+ pred_masks_gpu = current_out["pred_masks"]
796
+ # potentially fill holes in the predicted masks
797
+ if self.fill_hole_area > 0:
798
+ pred_masks_gpu = fill_holes_in_mask_scores(
799
+ pred_masks_gpu, self.fill_hole_area
800
+ )
801
+ pred_masks = pred_masks_gpu.to(storage_device, non_blocking=True)
802
+ # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
803
+ maskmem_pos_enc = self._get_maskmem_pos_enc(inference_state, current_out)
804
+ # object pointer is a small tensor, so we always keep it on GPU memory for fast access
805
+ obj_ptr = current_out["obj_ptr"]
806
+ object_score_logits = current_out["object_score_logits"]
807
+ # make a compact version of this frame's output to reduce the state size
808
+ compact_current_out = {
809
+ "maskmem_features": maskmem_features,
810
+ "maskmem_pos_enc": maskmem_pos_enc,
811
+ "pred_masks": pred_masks,
812
+ "obj_ptr": obj_ptr,
813
+ "object_score_logits": object_score_logits,
814
+ }
815
+ return compact_current_out, pred_masks_gpu
816
+
817
+ def _run_memory_encoder(
818
+ self,
819
+ inference_state,
820
+ frame_idx,
821
+ batch_size,
822
+ high_res_masks,
823
+ object_score_logits,
824
+ is_mask_from_pts,
825
+ ):
826
+ """
827
+ Run the memory encoder on `high_res_masks`. This is usually after applying
828
+ non-overlapping constraints to object scores. Since their scores changed, their
829
+ memory also need to be computed again with the memory encoder.
830
+ """
831
+ # Retrieve correct image features
832
+ _, _, current_vision_feats, _, feat_sizes = self._get_image_feature(
833
+ inference_state, frame_idx, batch_size
834
+ )
835
+ maskmem_features, maskmem_pos_enc = self._encode_new_memory(
836
+ current_vision_feats=current_vision_feats,
837
+ feat_sizes=feat_sizes,
838
+ pred_masks_high_res=high_res_masks,
839
+ object_score_logits=object_score_logits,
840
+ is_mask_from_pts=is_mask_from_pts,
841
+ )
842
+
843
+ # optionally offload the output to CPU memory to save GPU space
844
+ storage_device = inference_state["storage_device"]
845
+ maskmem_features = maskmem_features.to(torch.bfloat16)
846
+ maskmem_features = maskmem_features.to(storage_device, non_blocking=True)
847
+ # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
848
+ maskmem_pos_enc = self._get_maskmem_pos_enc(
849
+ inference_state, {"maskmem_pos_enc": maskmem_pos_enc}
850
+ )
851
+ return maskmem_features, maskmem_pos_enc
852
+
853
+ def _get_maskmem_pos_enc(self, inference_state, current_out):
854
+ """
855
+ `maskmem_pos_enc` is the same across frames and objects, so we cache it as
856
+ a constant in the inference session to reduce session storage size.
857
+ """
858
+ model_constants = inference_state["constants"]
859
+ # "out_maskmem_pos_enc" should be either a list of tensors or None
860
+ out_maskmem_pos_enc = current_out["maskmem_pos_enc"]
861
+ if out_maskmem_pos_enc is not None:
862
+ if "maskmem_pos_enc" not in model_constants:
863
+ assert isinstance(out_maskmem_pos_enc, list)
864
+ # only take the slice for one object, since it's same across objects
865
+ maskmem_pos_enc = [x[0:1].clone() for x in out_maskmem_pos_enc]
866
+ model_constants["maskmem_pos_enc"] = maskmem_pos_enc
867
+ else:
868
+ maskmem_pos_enc = model_constants["maskmem_pos_enc"]
869
+ # expand the cached maskmem_pos_enc to the actual batch size
870
+ batch_size = out_maskmem_pos_enc[0].size(0)
871
+ expanded_maskmem_pos_enc = [
872
+ x.expand(batch_size, -1, -1, -1) for x in maskmem_pos_enc
873
+ ]
874
+ else:
875
+ expanded_maskmem_pos_enc = None
876
+ return expanded_maskmem_pos_enc
877
+
878
+ @torch.inference_mode()
879
+ def remove_object(self, inference_state, obj_id, strict=False, need_output=True):
880
+ """
881
+ Remove an object id from the tracking state. If strict is True, we check whether
882
+ the object id actually exists and raise an error if it doesn't exist.
883
+ """
884
+ old_obj_idx_to_rm = inference_state["obj_id_to_idx"].get(obj_id, None)
885
+ updated_frames = []
886
+ # Check whether this object_id to remove actually exists and possibly raise an error.
887
+ if old_obj_idx_to_rm is None:
888
+ if not strict:
889
+ return inference_state["obj_ids"], updated_frames
890
+ raise RuntimeError(
891
+ f"Cannot remove object id {obj_id} as it doesn't exist. "
892
+ f"All existing object ids: {inference_state['obj_ids']}."
893
+ )
894
+
895
+ # If this is the only remaining object id, we simply reset the state.
896
+ if len(inference_state["obj_id_to_idx"]) == 1:
897
+ self.reset_state(inference_state)
898
+ return inference_state["obj_ids"], updated_frames
899
+
900
+ # There are still remaining objects after removing this object id. In this case,
901
+ # we need to delete the object storage from inference state tensors.
902
+ # Step 0: clear the input on those frames where this object id has point or mask input
903
+ # (note that this step is required as it might downgrade conditioning frames to
904
+ # non-conditioning ones)
905
+ obj_input_frames_inds = set()
906
+ obj_input_frames_inds.update(
907
+ inference_state["point_inputs_per_obj"][old_obj_idx_to_rm]
908
+ )
909
+ obj_input_frames_inds.update(
910
+ inference_state["mask_inputs_per_obj"][old_obj_idx_to_rm]
911
+ )
912
+ for frame_idx in obj_input_frames_inds:
913
+ self.clear_all_prompts_in_frame(
914
+ inference_state, frame_idx, obj_id, need_output=False
915
+ )
916
+
917
+ # Step 1: Update the object id mapping (note that it must be done after Step 0,
918
+ # since Step 0 still requires the old object id mappings in inference_state)
919
+ old_obj_ids = inference_state["obj_ids"]
920
+ old_obj_inds = list(range(len(old_obj_ids)))
921
+ remain_old_obj_inds = old_obj_inds.copy()
922
+ remain_old_obj_inds.remove(old_obj_idx_to_rm)
923
+ new_obj_ids = [old_obj_ids[old_idx] for old_idx in remain_old_obj_inds]
924
+ new_obj_inds = list(range(len(new_obj_ids)))
925
+ # build new mappings
926
+ old_idx_to_new_idx = dict(zip(remain_old_obj_inds, new_obj_inds))
927
+ inference_state["obj_id_to_idx"] = dict(zip(new_obj_ids, new_obj_inds))
928
+ inference_state["obj_idx_to_id"] = dict(zip(new_obj_inds, new_obj_ids))
929
+ inference_state["obj_ids"] = new_obj_ids
930
+
931
+ # Step 2: For per-object tensor storage, we shift their obj_idx in the dict keys.
932
+ def _map_keys(container):
933
+ new_kvs = []
934
+ for k in old_obj_inds:
935
+ v = container.pop(k)
936
+ if k in old_idx_to_new_idx:
937
+ new_kvs.append((old_idx_to_new_idx[k], v))
938
+ container.update(new_kvs)
939
+
940
+ _map_keys(inference_state["point_inputs_per_obj"])
941
+ _map_keys(inference_state["mask_inputs_per_obj"])
942
+ _map_keys(inference_state["output_dict_per_obj"])
943
+ _map_keys(inference_state["temp_output_dict_per_obj"])
944
+ _map_keys(inference_state["frames_tracked_per_obj"])
945
+
946
+ # Step 3: Further collect the outputs on those frames in `obj_input_frames_inds`, which
947
+ # could show an updated mask for objects previously occluded by the object being removed
948
+ if need_output:
949
+ temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"]
950
+ for frame_idx in obj_input_frames_inds:
951
+ is_cond = any(
952
+ frame_idx in obj_temp_output_dict["cond_frame_outputs"]
953
+ for obj_temp_output_dict in temp_output_dict_per_obj.values()
954
+ )
955
+ consolidated_out = self._consolidate_temp_output_across_obj(
956
+ inference_state,
957
+ frame_idx,
958
+ is_cond=is_cond,
959
+ consolidate_at_video_res=True,
960
+ )
961
+ _, video_res_masks = self._get_orig_video_res_output(
962
+ inference_state, consolidated_out["pred_masks_video_res"]
963
+ )
964
+ updated_frames.append((frame_idx, video_res_masks))
965
+
966
+ return inference_state["obj_ids"], updated_frames
967
+
968
+ def _clear_non_cond_mem_around_input(self, inference_state, frame_idx):
969
+ """
970
+ Remove the non-conditioning memory around the input frame. When users provide
971
+ correction clicks, the surrounding frames' non-conditioning memories can still
972
+ contain outdated object appearance information and could confuse the model.
973
+
974
+ This method clears those non-conditioning memories surrounding the interacted
975
+ frame to avoid giving the model both old and new information about the object.
976
+ """
977
+ r = self.memory_temporal_stride_for_eval
978
+ frame_idx_begin = frame_idx - r * self.num_maskmem
979
+ frame_idx_end = frame_idx + r * self.num_maskmem
980
+ batch_size = self._get_obj_num(inference_state)
981
+ for obj_idx in range(batch_size):
982
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
983
+ non_cond_frame_outputs = obj_output_dict["non_cond_frame_outputs"]
984
+ for t in range(frame_idx_begin, frame_idx_end + 1):
985
+ non_cond_frame_outputs.pop(t, None)
986
+
987
+
988
+ class EfficientTAMVideoPredictorVOSNPZ(EfficientTAMVideoPredictorNPZ):
989
+ """Optimized for the VOS setting"""
990
+
991
+ def __init__(self, *args, **kwargs):
992
+ super().__init__(*args, **kwargs)
993
+ self._compile_all_components()
994
+
995
+ def _compile_all_components(self):
996
+ print("Compiling all components for VOS setting. First time may be very slow.")
997
+ self.memory_encoder.forward = torch.compile(
998
+ self.memory_encoder.forward,
999
+ mode="max-autotune",
1000
+ fullgraph=True,
1001
+ dynamic=False,
1002
+ )
1003
+
1004
+ self.memory_attention.forward = torch.compile(
1005
+ self.memory_attention.forward,
1006
+ mode="max-autotune",
1007
+ fullgraph=True,
1008
+ dynamic=True, # Num. of memories varies
1009
+ )
1010
+
1011
+ self.sam_prompt_encoder.forward = torch.compile(
1012
+ self.sam_prompt_encoder.forward,
1013
+ mode="max-autotune",
1014
+ fullgraph=True,
1015
+ dynamic=False, # Accuracy regression on True
1016
+ )
1017
+
1018
+ self.sam_mask_decoder.forward = torch.compile(
1019
+ self.sam_mask_decoder.forward,
1020
+ mode="max-autotune",
1021
+ fullgraph=True,
1022
+ dynamic=False, # Accuracy regression on True
1023
+ )
1024
+
1025
+ def forward_image(self, img_batch: torch.Tensor):
1026
+ """
1027
+ Identical to the corresponding method in the parent (EfficientTAMVideoPredictor), but
1028
+ cloning the backbone features and pos encoding to enable compilation.
1029
+ """
1030
+ backbone_out = self.image_encoder(img_batch)
1031
+ # Clone to help torch.compile
1032
+ for i in range(len(backbone_out["backbone_fpn"])):
1033
+ backbone_out["backbone_fpn"][i] = backbone_out["backbone_fpn"][i].clone()
1034
+ backbone_out["vision_pos_enc"][i] = backbone_out["vision_pos_enc"][
1035
+ i
1036
+ ].clone()
1037
+ return backbone_out
1038
+
1039
+ def _forward_sam_heads(
1040
+ self,
1041
+ backbone_features,
1042
+ point_inputs=None,
1043
+ mask_inputs=None,
1044
+ high_res_features=None,
1045
+ multimask_output=False,
1046
+ ):
1047
+ """
1048
+ Identical to the corresponding method in the parent (EfficientTAMVideoPredictor), but
1049
+ cloning the outputs of prompt_encoder and mask_decoder to enable compilation.
1050
+ """
1051
+ B = backbone_features.size(0)
1052
+ device = backbone_features.device
1053
+ assert backbone_features.size(1) == self.sam_prompt_embed_dim
1054
+ assert backbone_features.size(2) == self.sam_image_embedding_size
1055
+ assert backbone_features.size(3) == self.sam_image_embedding_size
1056
+
1057
+ # a) Handle point prompts
1058
+ if point_inputs is not None:
1059
+ sam_point_coords = point_inputs["point_coords"]
1060
+ sam_point_labels = point_inputs["point_labels"]
1061
+ assert sam_point_coords.size(0) == B and sam_point_labels.size(0) == B
1062
+ else:
1063
+ # If no points are provide, pad with an empty point (with label -1)
1064
+ sam_point_coords = torch.zeros(B, 1, 2, device=device)
1065
+ sam_point_labels = -torch.ones(B, 1, dtype=torch.int32, device=device)
1066
+
1067
+ # b) Handle mask prompts
1068
+ if mask_inputs is not None:
1069
+ # If mask_inputs is provided, downsize it into low-res mask input if needed
1070
+ # and feed it as a dense mask prompt into the SAM mask encoder
1071
+ assert len(mask_inputs.shape) == 4 and mask_inputs.shape[:2] == (B, 1)
1072
+ if mask_inputs.shape[-2:] != self.sam_prompt_encoder.mask_input_size:
1073
+ sam_mask_prompt = F.interpolate(
1074
+ mask_inputs.float(),
1075
+ size=self.sam_prompt_encoder.mask_input_size,
1076
+ align_corners=False,
1077
+ mode="bilinear",
1078
+ antialias=True, # use antialias for downsampling
1079
+ )
1080
+ else:
1081
+ sam_mask_prompt = mask_inputs
1082
+ else:
1083
+ # Otherwise, simply feed None (and SAM's prompt encoder will add
1084
+ # a learned `no_mask_embed` to indicate no mask input in this case).
1085
+ sam_mask_prompt = None
1086
+
1087
+ sparse_embeddings, dense_embeddings = self.sam_prompt_encoder(
1088
+ points=(sam_point_coords, sam_point_labels),
1089
+ boxes=None,
1090
+ masks=sam_mask_prompt,
1091
+ )
1092
+ # Clone image_pe and the outputs of sam_prompt_encoder
1093
+ # to enable compilation
1094
+ sparse_embeddings = sparse_embeddings.clone()
1095
+ dense_embeddings = dense_embeddings.clone()
1096
+ image_pe = self.sam_prompt_encoder.get_dense_pe().clone()
1097
+ (
1098
+ low_res_multimasks,
1099
+ ious,
1100
+ sam_output_tokens,
1101
+ object_score_logits,
1102
+ ) = self.sam_mask_decoder(
1103
+ image_embeddings=backbone_features,
1104
+ image_pe=image_pe,
1105
+ sparse_prompt_embeddings=sparse_embeddings,
1106
+ dense_prompt_embeddings=dense_embeddings,
1107
+ multimask_output=multimask_output,
1108
+ repeat_image=False, # the image is already batched
1109
+ high_res_features=high_res_features,
1110
+ )
1111
+ # Clone the output of sam_mask_decoder
1112
+ # to enable compilation
1113
+ low_res_multimasks = low_res_multimasks.clone()
1114
+ ious = ious.clone()
1115
+ sam_output_tokens = sam_output_tokens.clone()
1116
+ object_score_logits = object_score_logits.clone()
1117
+
1118
+ if self.pred_obj_scores:
1119
+ is_obj_appearing = object_score_logits > 0
1120
+
1121
+ # Mask used for spatial memories is always a *hard* choice between obj and no obj,
1122
+ # consistent with the actual mask prediction
1123
+ low_res_multimasks = torch.where(
1124
+ is_obj_appearing[:, None, None],
1125
+ low_res_multimasks,
1126
+ NO_OBJ_SCORE,
1127
+ )
1128
+
1129
+ # convert masks from possibly bfloat16 (or float16) to float32
1130
+ # (older PyTorch versions before 2.1 don't support `interpolate` on bf16)
1131
+ low_res_multimasks = low_res_multimasks.float()
1132
+ high_res_multimasks = F.interpolate(
1133
+ low_res_multimasks,
1134
+ size=(self.image_size, self.image_size),
1135
+ mode="bilinear",
1136
+ align_corners=False,
1137
+ )
1138
+
1139
+ sam_output_token = sam_output_tokens[:, 0]
1140
+ if multimask_output:
1141
+ # take the best mask prediction (with the highest IoU estimation)
1142
+ best_iou_inds = torch.argmax(ious, dim=-1)
1143
+ batch_inds = torch.arange(B, device=device)
1144
+ low_res_masks = low_res_multimasks[batch_inds, best_iou_inds].unsqueeze(1)
1145
+ high_res_masks = high_res_multimasks[batch_inds, best_iou_inds].unsqueeze(1)
1146
+ if sam_output_tokens.size(1) > 1:
1147
+ sam_output_token = sam_output_tokens[batch_inds, best_iou_inds]
1148
+ else:
1149
+ low_res_masks, high_res_masks = low_res_multimasks, high_res_multimasks
1150
+
1151
+ # Extract object pointer from the SAM output token (with occlusion handling)
1152
+ obj_ptr = self.obj_ptr_proj(sam_output_token)
1153
+ if self.pred_obj_scores:
1154
+ # Allow *soft* no obj ptr, unlike for masks
1155
+ if self.soft_no_obj_ptr:
1156
+ lambda_is_obj_appearing = object_score_logits.sigmoid()
1157
+ else:
1158
+ lambda_is_obj_appearing = is_obj_appearing.float()
1159
+
1160
+ if self.fixed_no_obj_ptr:
1161
+ obj_ptr = lambda_is_obj_appearing * obj_ptr
1162
+ obj_ptr = obj_ptr + (1 - lambda_is_obj_appearing) * self.no_obj_ptr
1163
+
1164
+ return (
1165
+ low_res_multimasks,
1166
+ high_res_multimasks,
1167
+ ious,
1168
+ low_res_masks,
1169
+ high_res_masks,
1170
+ obj_ptr,
1171
+ object_score_logits,
1172
+ )
1173
+
1174
+ def _encode_new_memory(
1175
+ self,
1176
+ current_vision_feats,
1177
+ feat_sizes,
1178
+ pred_masks_high_res,
1179
+ object_score_logits,
1180
+ is_mask_from_pts,
1181
+ ):
1182
+ """
1183
+ Identical to the corresponding method in the parent (EfficientTAMVideoPredictor), but
1184
+ cloning the memories and their pos enc to enable compilation.
1185
+ """
1186
+ B = current_vision_feats[-1].size(1) # batch size on this frame
1187
+ C = self.hidden_dim
1188
+ H, W = feat_sizes[-1] # top-level (lowest-resolution) feature size
1189
+ # top-level feature, (HW)BC => BCHW
1190
+ pix_feat = current_vision_feats[-1].permute(1, 2, 0).view(B, C, H, W)
1191
+ if self.non_overlap_masks_for_mem_enc and not self.training:
1192
+ # optionally, apply non-overlapping constraints to the masks (it's applied
1193
+ # in the batch dimension and should only be used during eval, where all
1194
+ # the objects come from the same video under batch size 1).
1195
+ pred_masks_high_res = self._apply_non_overlapping_constraints(
1196
+ pred_masks_high_res
1197
+ )
1198
+ # scale the raw mask logits with a temperature before applying sigmoid
1199
+ binarize = self.binarize_mask_from_pts_for_mem_enc and is_mask_from_pts
1200
+ if binarize and not self.training:
1201
+ mask_for_mem = (pred_masks_high_res > 0).float()
1202
+ else:
1203
+ # apply sigmoid on the raw mask logits to turn them into range (0, 1)
1204
+ mask_for_mem = torch.sigmoid(pred_masks_high_res)
1205
+ # apply scale and bias terms to the sigmoid probabilities
1206
+ if self.sigmoid_scale_for_mem_enc != 1.0:
1207
+ mask_for_mem = mask_for_mem * self.sigmoid_scale_for_mem_enc
1208
+ if self.sigmoid_bias_for_mem_enc != 0.0:
1209
+ mask_for_mem = mask_for_mem + self.sigmoid_bias_for_mem_enc
1210
+ maskmem_out = self.memory_encoder(
1211
+ pix_feat, mask_for_mem, skip_mask_sigmoid=True # sigmoid already applied
1212
+ )
1213
+ # Clone the feats and pos_enc to enable compilation
1214
+ maskmem_features = maskmem_out["vision_features"].clone()
1215
+ maskmem_pos_enc = [m.clone() for m in maskmem_out["vision_pos_enc"]]
1216
+ # add a no-object embedding to the spatial memory to indicate that the frame
1217
+ # is predicted to be occluded (i.e. no object is appearing in the frame)
1218
+ if self.no_obj_embed_spatial is not None:
1219
+ is_obj_appearing = (object_score_logits > 0).float()
1220
+ maskmem_features += (
1221
+ 1 - is_obj_appearing[..., None, None]
1222
+ ) * self.no_obj_embed_spatial[..., None, None].expand(
1223
+ *maskmem_features.shape
1224
+ )
1225
+
1226
+ return maskmem_features, maskmem_pos_enc
MedSAM2/efficient_track_anything/modeling/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
MedSAM2/efficient_track_anything/modeling/backbones/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
MedSAM2/efficient_track_anything/modeling/backbones/image_encoder.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from typing import List, Optional
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+
13
+ from efficient_track_anything.modeling.efficienttam_utils import LayerNorm2d
14
+
15
+
16
+ class ImageEncoder(nn.Module):
17
+ def __init__(
18
+ self,
19
+ trunk: nn.Module,
20
+ neck: nn.Module,
21
+ scalp: int = 0,
22
+ ):
23
+ super().__init__()
24
+ self.trunk = trunk
25
+ self.neck = neck
26
+ self.scalp = scalp
27
+ assert (
28
+ self.trunk.channel_list == self.neck.backbone_channel_list
29
+ ), f"Channel dims of trunk and neck do not match. Trunk: {self.trunk.channel_list}, neck: {self.neck.backbone_channel_list}"
30
+
31
+ def forward(self, sample: torch.Tensor):
32
+ # Forward through backbone
33
+ features, pos = self.neck(self.trunk(sample))
34
+ if self.scalp > 0:
35
+ # Discard the lowest resolution features
36
+ features, pos = features[: -self.scalp], pos[: -self.scalp]
37
+
38
+ src = features[-1]
39
+ output = {
40
+ "vision_features": src,
41
+ "vision_pos_enc": pos,
42
+ "backbone_fpn": features,
43
+ }
44
+ return output
45
+
46
+
47
+ class ViTDetNeck(nn.Module):
48
+ def __init__(
49
+ self,
50
+ position_encoding: nn.Module,
51
+ d_model: int,
52
+ backbone_channel_list: List[int],
53
+ kernel_size: int = 1,
54
+ stride: int = 1,
55
+ padding: int = 0,
56
+ neck_norm=None,
57
+ ):
58
+ """Initialize the neck
59
+
60
+ :param trunk: the backbone
61
+ :param position_encoding: the positional encoding to use
62
+ :param d_model: the dimension of the model
63
+ :param neck_norm: the normalization to use
64
+ """
65
+ super().__init__()
66
+ self.backbone_channel_list = backbone_channel_list
67
+ self.position_encoding = position_encoding
68
+ self.convs = nn.ModuleList()
69
+ self.d_model = d_model
70
+ use_bias = neck_norm is None
71
+ for dim in self.backbone_channel_list:
72
+ current = nn.Sequential()
73
+ current.add_module(
74
+ "conv_1x1",
75
+ nn.Conv2d(
76
+ in_channels=dim,
77
+ out_channels=d_model,
78
+ kernel_size=1,
79
+ bias=use_bias,
80
+ ),
81
+ )
82
+ if neck_norm is not None:
83
+ current.add_module("norm_0", LayerNorm2d(d_model))
84
+ current.add_module(
85
+ "conv_3x3",
86
+ nn.Conv2d(
87
+ in_channels=d_model,
88
+ out_channels=d_model,
89
+ kernel_size=3,
90
+ padding=1,
91
+ bias=use_bias,
92
+ ),
93
+ )
94
+ if neck_norm is not None:
95
+ current.add_module("norm_1", LayerNorm2d(d_model))
96
+ self.convs.append(current)
97
+
98
+ def forward(self, xs: List[torch.Tensor]):
99
+ out = [None] * len(self.convs)
100
+ pos = [None] * len(self.convs)
101
+ assert len(xs) == len(self.convs)
102
+
103
+ x = xs[0]
104
+ x_out = self.convs[0](x)
105
+ out[0] = x_out
106
+ pos[0] = self.position_encoding(x_out).to(x_out.dtype)
107
+
108
+ return out, pos
MedSAM2/efficient_track_anything/modeling/backbones/utils.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """Some utilities for backbones, in particular for windowing"""
8
+
9
+ from typing import Tuple
10
+
11
+ import torch
12
+ import torch.nn as nn
13
+ import torch.nn.functional as F
14
+
15
+ import math
16
+
17
+ def window_partition(x, window_size):
18
+ """
19
+ Partition into non-overlapping windows with padding if needed.
20
+ Args:
21
+ x (tensor): input tokens with [B, H, W, C].
22
+ window_size (int): window size.
23
+ Returns:
24
+ windows: windows after partition with [B * num_windows, window_size, window_size, C].
25
+ (Hp, Wp): padded height and width before partition
26
+ """
27
+ B, H, W, C = x.shape
28
+
29
+ pad_h = (window_size - H % window_size) % window_size
30
+ pad_w = (window_size - W % window_size) % window_size
31
+ if pad_h > 0 or pad_w > 0:
32
+ x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h))
33
+ Hp, Wp = H + pad_h, W + pad_w
34
+
35
+ x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C)
36
+ windows = x.permute(0, 1, 3, 2, 4, 5).reshape(-1, window_size, window_size, C)
37
+ return windows, (Hp, Wp)
38
+
39
+
40
+ def window_unpartition(windows, window_size, pad_hw, hw):
41
+ """
42
+ Window unpartition into original sequences and removing padding.
43
+ Args:
44
+ x (tensor): input tokens with [B * num_windows, window_size, window_size, C].
45
+ window_size (int): window size.
46
+ pad_hw (Tuple): padded height and width (Hp, Wp).
47
+ hw (Tuple): original height and width (H, W) before padding.
48
+ Returns:
49
+ x: unpartitioned sequences with [B, H, W, C].
50
+ """
51
+ Hp, Wp = pad_hw
52
+ H, W = hw
53
+ B = windows.shape[0] // (Hp * Wp // window_size // window_size)
54
+ x = windows.reshape(
55
+ B, Hp // window_size, Wp // window_size, window_size, window_size, -1
56
+ )
57
+ x = x.permute(0, 1, 3, 2, 4, 5).reshape(B, Hp, Wp, -1)
58
+
59
+ if Hp > H or Wp > W:
60
+ x = x[:, :H, :W, :]
61
+ return x
62
+
63
+
64
+ class PatchEmbed(nn.Module):
65
+ """
66
+ Image to Patch Embedding.
67
+ """
68
+
69
+ def __init__(
70
+ self,
71
+ kernel_size: Tuple[int, ...] = (7, 7),
72
+ stride: Tuple[int, ...] = (4, 4),
73
+ padding: Tuple[int, ...] = (3, 3),
74
+ in_chans: int = 3,
75
+ embed_dim: int = 768,
76
+ ):
77
+ """
78
+ Args:
79
+ kernel_size (Tuple): kernel size of the projection layer.
80
+ stride (Tuple): stride of the projection layer.
81
+ padding (Tuple): padding size of the projection layer.
82
+ in_chans (int): Number of input image channels.
83
+ embed_dim (int): embed_dim (int): Patch embedding dimension.
84
+ """
85
+ super().__init__()
86
+ self.proj = nn.Conv2d(
87
+ in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding
88
+ )
89
+
90
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
91
+ x = self.proj(x)
92
+ # B C H W -> B H W C
93
+ x = x.permute(0, 2, 3, 1)
94
+ return x
95
+
96
+
97
+ def get_abs_pos(abs_pos, has_cls_token, hw):
98
+ """
99
+ Calculate absolute positional embeddings. If needed, resize embeddings and remove cls_token
100
+ dimension for the original embeddings.
101
+ Args:
102
+ abs_pos (Tensor): absolute positional embeddings with (1, num_position, C).
103
+ has_cls_token (bool): If true, has 1 embedding in abs_pos for cls token.
104
+ hw (Tuple): size of input image tokens.
105
+ Returns:
106
+ Absolute positional embeddings after processing with shape (1, H, W, C)
107
+ """
108
+ h, w = hw
109
+ if has_cls_token:
110
+ abs_pos = abs_pos[:, 1:]
111
+ xy_num = abs_pos.shape[1]
112
+ size = int(math.sqrt(xy_num))
113
+ assert size * size == xy_num
114
+
115
+ if size != h or size != w:
116
+ interpolate_mode = "bicubic"
117
+ if not torch.cuda.is_available() and torch.mps.is_available():
118
+ # bicubic is not supported on torch mps
119
+ interpolate_mode = "bilinear"
120
+ new_abs_pos = F.interpolate(
121
+ abs_pos.reshape(1, size, size, -1).permute(0, 3, 1, 2),
122
+ size=(h, w),
123
+ mode=interpolate_mode,
124
+ align_corners=False,
125
+ )
126
+ return new_abs_pos.permute(0, 2, 3, 1)
127
+ else:
128
+ return abs_pos.reshape(1, h, w, -1)
MedSAM2/efficient_track_anything/modeling/backbones/vitdet.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ViTDet backbone adapted from Detectron2"""
2
+
3
+ from functools import partial
4
+ from typing import List, Tuple, Union
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+
10
+ from efficient_track_anything.modeling.backbones.utils import (
11
+ get_abs_pos,
12
+ PatchEmbed,
13
+ window_partition,
14
+ window_unpartition,
15
+ )
16
+
17
+ from efficient_track_anything.modeling.efficienttam_utils import (
18
+ DropPath,
19
+ LayerScale,
20
+ MLP,
21
+ )
22
+
23
+
24
+ class Attention(nn.Module):
25
+ """Multi-head Attention block with relative position embeddings."""
26
+
27
+ def __init__(
28
+ self,
29
+ dim,
30
+ num_heads=8,
31
+ qkv_bias=True,
32
+ use_rel_pos=False,
33
+ rel_pos_zero_init=True,
34
+ input_size=None,
35
+ ):
36
+ """
37
+ Args:
38
+ dim (int): Number of input channels.
39
+ num_heads (int): Number of attention heads.
40
+ qkv_bias (bool: If True, add a learnable bias to query, key, value.
41
+ rel_pos (bool): If True, add relative positional embeddings to the attention map.
42
+ rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
43
+ input_size (int or None): Input resolution for calculating the relative positional
44
+ parameter size.
45
+ attn_type: Type of attention operation, e.g. "vanilla", "vanilla-xformer".
46
+ """
47
+ super().__init__()
48
+ self.num_heads = num_heads
49
+ head_dim = dim // num_heads
50
+ self.scale = head_dim**-0.5
51
+
52
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
53
+ self.proj = nn.Linear(dim, dim)
54
+
55
+ self.use_rel_pos = use_rel_pos
56
+
57
+ def forward(self, x):
58
+ B, H, W, _ = x.shape
59
+ # qkv with shape (3, B, nHead, H * W, C)
60
+ qkv = (
61
+ self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
62
+ )
63
+ # q, k, v with shape (B * nHead, H * W, C)
64
+ q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0)
65
+
66
+ q = q.view(B, self.num_heads, H * W, -1)
67
+ k = k.view(B, self.num_heads, H * W, -1)
68
+ v = v.view(B, self.num_heads, H * W, -1)
69
+
70
+ x = F.scaled_dot_product_attention(q, k, v)
71
+
72
+ x = (
73
+ x.view(B, self.num_heads, H, W, -1)
74
+ .permute(0, 2, 3, 1, 4)
75
+ .reshape(B, H, W, -1)
76
+ )
77
+ x = self.proj(x)
78
+
79
+ return x
80
+
81
+
82
+ class Block(nn.Module):
83
+ """Transformer blocks with support of window attention"""
84
+
85
+ def __init__(
86
+ self,
87
+ dim,
88
+ num_heads,
89
+ mlp_ratio=4.0,
90
+ qkv_bias=True,
91
+ drop_path=0.0,
92
+ norm_layer=nn.LayerNorm,
93
+ act_layer=nn.GELU,
94
+ use_rel_pos=False,
95
+ rel_pos_zero_init=True,
96
+ window_size=0,
97
+ input_size=None,
98
+ dropout=0.0,
99
+ init_values=None,
100
+ ):
101
+ """
102
+ Args:
103
+ dim (int): Number of input channels.
104
+ num_heads (int): Number of attention heads in each ViT block.
105
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
106
+ qkv_bias (bool): If True, add a learnable bias to query, key, value.
107
+ drop_path (float): Stochastic depth rate.
108
+ norm_layer (nn.Module): Normalization layer.
109
+ act_layer (nn.Module): Activation layer.
110
+ use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
111
+ rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
112
+ window_size (int): Window size for window attention blocks. If it equals 0, then not
113
+ use window attention.
114
+ input_size (int or None): Input resolution for calculating the relative positional
115
+ parameter size.
116
+ dropout (float): Dropout rate.
117
+ """
118
+ super().__init__()
119
+ self.norm1 = norm_layer(dim)
120
+ self.attn = Attention(
121
+ dim,
122
+ num_heads=num_heads,
123
+ qkv_bias=qkv_bias,
124
+ use_rel_pos=use_rel_pos,
125
+ rel_pos_zero_init=rel_pos_zero_init,
126
+ input_size=input_size if window_size == 0 else (window_size, window_size),
127
+ )
128
+ self.ls1 = (
129
+ LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
130
+ )
131
+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
132
+
133
+ self.norm2 = norm_layer(dim)
134
+ self.mlp = MLP(
135
+ dim,
136
+ int(dim * mlp_ratio),
137
+ dim,
138
+ num_layers=2,
139
+ activation=act_layer,
140
+ )
141
+ self.ls2 = (
142
+ LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
143
+ )
144
+ self.dropout = nn.Dropout(dropout)
145
+ self.window_size = window_size
146
+
147
+ def forward(self, x):
148
+ shortcut = x
149
+ x = self.norm1(x)
150
+ # Window partition
151
+ if self.window_size > 0:
152
+ H, W = x.shape[1], x.shape[2]
153
+ x, pad_hw = window_partition(x, self.window_size)
154
+
155
+ x = self.ls1(self.attn(x))
156
+ # Reverse window partition
157
+ if self.window_size > 0:
158
+ x = window_unpartition(x, self.window_size, pad_hw, (H, W))
159
+
160
+ x = shortcut + self.dropout(self.drop_path(x))
161
+ x = x + self.dropout(self.drop_path(self.ls2(self.mlp(self.norm2(x)))))
162
+
163
+ return x
164
+
165
+
166
+ class ViT(nn.Module):
167
+ """
168
+ This module implements Vision Transformer (ViT) backbone in :paper:`vitdet`.
169
+ "Exploring Plain Vision Transformer Backbones for Object Detection",
170
+ https://arxiv.org/abs/2203.16527
171
+ """
172
+
173
+ def __init__(
174
+ self,
175
+ img_size=1024,
176
+ patch_size=16,
177
+ in_chans=3,
178
+ embed_dim=768,
179
+ depth=12,
180
+ num_heads=12,
181
+ mlp_ratio=4.0,
182
+ qkv_bias=True,
183
+ drop_path_rate=0.0,
184
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
185
+ act_layer=nn.GELU,
186
+ use_abs_pos=True,
187
+ use_rel_pos=False,
188
+ rel_pos_zero_init=True,
189
+ window_size=14,
190
+ window_block_indexes=(0, 1, 3, 4, 6, 7, 9, 10),
191
+ use_act_checkpoint=False,
192
+ pretrain_img_size=224,
193
+ pretrain_use_cls_token=True,
194
+ dropout=0.0,
195
+ weights_path=None,
196
+ return_interm_layers=False,
197
+ init_values=None,
198
+ ):
199
+ """
200
+ Args:
201
+ img_size (int): Input image size. Only relevant for rel pos.
202
+ patch_size (int): Patch size.
203
+ in_chans (int): Number of input image channels.
204
+ embed_dim (int): Patch embedding dimension.
205
+ depth (int): Depth of ViT.
206
+ num_heads (int): Number of attention heads in each ViT block.
207
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
208
+ qkv_bias (bool): If True, add a learnable bias to query, key, value.
209
+ drop_path_rate (float): Stochastic depth rate.
210
+ norm_layer (nn.Module): Normalization layer.
211
+ act_layer (nn.Module): Activation layer.
212
+ use_abs_pos (bool): If True, use absolute positional embeddings.
213
+ use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
214
+ rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
215
+ window_size (int): Window size for window attention blocks.
216
+ window_block_indexes (list): Indexes for blocks using window attention.
217
+ residual_block_indexes (list): Indexes for blocks using conv propagation.
218
+ use_act_checkpoint (bool): If True, use activation checkpointing.
219
+ pretrain_img_size (int): input image size for pretraining models.
220
+ pretrain_use_cls_token (bool): If True, pretrainig models use class token.
221
+ dropout (float): Dropout rate. Applied in residual blocks of attn, mlp and inside the mlp.
222
+ path (str or None): Path to the pretrained weights.
223
+ return_interm_layers (bool): Whether to return intermediate layers (all global attention blocks).
224
+ freezing (BackboneFreezingType): Type of freezing.
225
+ """
226
+ super().__init__()
227
+ self.pretrain_use_cls_token = pretrain_use_cls_token
228
+
229
+ self.patch_embed = PatchEmbed(
230
+ kernel_size=(patch_size, patch_size),
231
+ stride=(patch_size, patch_size),
232
+ padding=(0, 0),
233
+ in_chans=in_chans,
234
+ embed_dim=embed_dim,
235
+ )
236
+
237
+ if use_abs_pos:
238
+ # Initialize absolute positional embedding with pretrain image size.
239
+ num_patches = (pretrain_img_size // patch_size) * (
240
+ pretrain_img_size // patch_size
241
+ )
242
+ num_positions = (num_patches + 1) if pretrain_use_cls_token else num_patches
243
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_positions, embed_dim))
244
+ else:
245
+ self.pos_embed = None
246
+
247
+ # stochastic depth decay rule
248
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)]
249
+
250
+ self.blocks = nn.ModuleList()
251
+ self.full_attn_ids = []
252
+ cur_stage = 1
253
+ for i in range(depth):
254
+ block = Block(
255
+ dim=embed_dim,
256
+ num_heads=num_heads,
257
+ mlp_ratio=mlp_ratio,
258
+ qkv_bias=qkv_bias,
259
+ drop_path=dpr[i],
260
+ norm_layer=norm_layer,
261
+ act_layer=act_layer,
262
+ use_rel_pos=use_rel_pos,
263
+ rel_pos_zero_init=rel_pos_zero_init,
264
+ window_size=window_size if i in window_block_indexes else 0,
265
+ input_size=(img_size // patch_size, img_size // patch_size),
266
+ dropout=dropout,
267
+ init_values=init_values,
268
+ )
269
+ if i not in window_block_indexes:
270
+ self.full_attn_ids.append(i)
271
+ cur_stage += 1
272
+
273
+ self.blocks.append(block)
274
+
275
+ self.return_interm_layers = return_interm_layers
276
+ self.channel_list = (
277
+ [embed_dim] * len(self.full_attn_ids)
278
+ if return_interm_layers
279
+ else [embed_dim]
280
+ )
281
+
282
+ def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
283
+
284
+ x = self.patch_embed(x)
285
+ if self.pos_embed is not None:
286
+ x = x + get_abs_pos(
287
+ self.pos_embed, self.pretrain_use_cls_token, (x.shape[1], x.shape[2])
288
+ )
289
+
290
+ outputs = []
291
+ for i, blk in enumerate(self.blocks):
292
+ x = blk(x)
293
+ if (i == self.full_attn_ids[-1]) or (
294
+ self.return_interm_layers and i in self.full_attn_ids
295
+ ):
296
+ feats = x.permute(0, 3, 1, 2)
297
+ outputs.append(feats)
298
+
299
+ return outputs
MedSAM2/efficient_track_anything/modeling/efficienttam_base.py ADDED
@@ -0,0 +1,911 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import torch
8
+ import torch.distributed
9
+ import torch.nn.functional as F
10
+ from efficient_track_anything.modeling.efficienttam_utils import (
11
+ get_1d_sine_pe,
12
+ MLP,
13
+ select_closest_cond_frames,
14
+ )
15
+
16
+ from efficient_track_anything.modeling.sam.mask_decoder import MaskDecoder
17
+ from efficient_track_anything.modeling.sam.prompt_encoder import PromptEncoder
18
+ from efficient_track_anything.modeling.sam.transformer import TwoWayTransformer
19
+
20
+ from torch.nn.init import trunc_normal_
21
+
22
+ # a large negative value as a placeholder score for missing objects
23
+ NO_OBJ_SCORE = -1024.0
24
+
25
+
26
+ class EfficientTAMBase(torch.nn.Module):
27
+ def __init__(
28
+ self,
29
+ image_encoder,
30
+ memory_attention,
31
+ memory_encoder,
32
+ num_maskmem=7, # default 1 input frame + 6 previous frames
33
+ image_size=512,
34
+ backbone_stride=16, # stride of the image backbone output
35
+ sigmoid_scale_for_mem_enc=1.0, # scale factor for mask sigmoid prob
36
+ sigmoid_bias_for_mem_enc=0.0, # bias factor for mask sigmoid prob
37
+ # During evaluation, whether to binarize the sigmoid mask logits on interacted frames with clicks
38
+ binarize_mask_from_pts_for_mem_enc=False,
39
+ use_mask_input_as_output_without_sam=False, # on frames with mask input, whether to directly output the input mask without using a SAM prompt encoder + mask decoder
40
+ # The maximum number of conditioning frames to participate in the memory attention (-1 means no limit; if there are more conditioning frames than this limit,
41
+ # we only cross-attend to the temporally closest `max_cond_frames_in_attn` conditioning frames in the encoder when tracking each frame). This gives the model
42
+ # a temporal locality when handling a large number of annotated frames (since closer frames should be more important) and also avoids GPU OOM.
43
+ max_cond_frames_in_attn=-1,
44
+ # on the first frame, whether to directly add the no-memory embedding to the image feature
45
+ # (instead of using the transformer encoder)
46
+ directly_add_no_mem_embed=False,
47
+ # whether to use high-resolution feature maps in the SAM mask decoder
48
+ use_high_res_features_in_sam=False,
49
+ # whether to output multiple (3) masks for the first click on initial conditioning frames
50
+ multimask_output_in_sam=False,
51
+ # the minimum and maximum number of clicks to use multimask_output_in_sam (only relevant when `multimask_output_in_sam=True`;
52
+ # default is 1 for both, meaning that only the first click gives multimask output; also note that a box counts as two points)
53
+ multimask_min_pt_num=1,
54
+ multimask_max_pt_num=1,
55
+ # whether to also use multimask output for tracking (not just for the first click on initial conditioning frames; only relevant when `multimask_output_in_sam=True`)
56
+ multimask_output_for_tracking=False,
57
+ # Whether to use multimask tokens for obj ptr; Only relevant when both
58
+ # use_obj_ptrs_in_encoder=True and multimask_output_for_tracking=True
59
+ use_multimask_token_for_obj_ptr: bool = False,
60
+ # whether to use sigmoid to restrict ious prediction to [0-1]
61
+ iou_prediction_use_sigmoid=False,
62
+ # The memory bank's temporal stride during evaluation (i.e. the `r` parameter in XMem and Cutie; XMem and Cutie use r=5).
63
+ # For r>1, the (self.num_maskmem - 1) non-conditioning memory frames consist of
64
+ # (self.num_maskmem - 2) nearest frames from every r-th frames, plus the last frame.
65
+ memory_temporal_stride_for_eval=1,
66
+ # whether to apply non-overlapping constraints on the object masks in the memory encoder during evaluation (to avoid/alleviate superposing masks)
67
+ non_overlap_masks_for_mem_enc=False,
68
+ # whether to cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder
69
+ use_obj_ptrs_in_encoder=False,
70
+ # the maximum number of object pointers from other frames in encoder cross attention (only relevant when `use_obj_ptrs_in_encoder=True`)
71
+ max_obj_ptrs_in_encoder=16,
72
+ # whether to add temporal positional encoding to the object pointers in the encoder (only relevant when `use_obj_ptrs_in_encoder=True`)
73
+ add_tpos_enc_to_obj_ptrs=True,
74
+ # whether to add an extra linear projection layer for the temporal positional encoding in the object pointers to avoid potential interference
75
+ # with spatial positional encoding (only relevant when both `use_obj_ptrs_in_encoder=True` and `add_tpos_enc_to_obj_ptrs=True`)
76
+ proj_tpos_enc_in_obj_ptrs=False,
77
+ # whether to use signed distance (instead of unsigned absolute distance) in the temporal positional encoding in the object pointers
78
+ # (only relevant when both `use_obj_ptrs_in_encoder=True` and `add_tpos_enc_to_obj_ptrs=True`)
79
+ use_signed_tpos_enc_to_obj_ptrs=False,
80
+ # whether to only attend to object pointers in the past (before the current frame) in the encoder during evaluation
81
+ # (only relevant when `use_obj_ptrs_in_encoder=True`; this might avoid pointer information too far in the future to distract the initial tracking)
82
+ only_obj_ptrs_in_the_past_for_eval=False,
83
+ # Whether to predict if there is an object in the frame
84
+ pred_obj_scores: bool = False,
85
+ # Whether to use an MLP to predict object scores
86
+ pred_obj_scores_mlp: bool = False,
87
+ # Only relevant if pred_obj_scores=True and use_obj_ptrs_in_encoder=True;
88
+ # Whether to have a fixed no obj pointer when there is no object present
89
+ # or to use it as an additive embedding with obj_ptr produced by decoder
90
+ fixed_no_obj_ptr: bool = False,
91
+ # Soft no object, i.e. mix in no_obj_ptr softly,
92
+ # hope to make recovery easier if there is a mistake and mitigate accumulation of errors
93
+ soft_no_obj_ptr: bool = False,
94
+ use_mlp_for_obj_ptr_proj: bool = False,
95
+ # add no obj embedding to spatial frames
96
+ no_obj_embed_spatial: bool = False,
97
+ # extra arguments used to construct the SAM mask decoder; if not None, it should be a dict of kwargs to be passed into `MaskDecoder` class.
98
+ sam_mask_decoder_extra_args=None,
99
+ compile_image_encoder: bool = False,
100
+ ):
101
+ super().__init__()
102
+
103
+ # Part 1: the image backbone
104
+ self.image_encoder = image_encoder
105
+ self.use_high_res_features_in_sam = False
106
+ self.num_feature_levels = 1
107
+ self.use_obj_ptrs_in_encoder = use_obj_ptrs_in_encoder
108
+ self.max_obj_ptrs_in_encoder = max_obj_ptrs_in_encoder
109
+ if use_obj_ptrs_in_encoder:
110
+ # A conv layer to downsample the mask prompt to stride 4 (the same stride as
111
+ # low-res SAM mask logits) and to change its scales from 0~1 to SAM logit scale,
112
+ # so that it can be fed into the SAM mask decoder to generate a pointer.
113
+ self.mask_downsample = torch.nn.Conv2d(1, 1, kernel_size=4, stride=4)
114
+ self.add_tpos_enc_to_obj_ptrs = add_tpos_enc_to_obj_ptrs
115
+ if proj_tpos_enc_in_obj_ptrs:
116
+ assert add_tpos_enc_to_obj_ptrs # these options need to be used together
117
+ self.proj_tpos_enc_in_obj_ptrs = proj_tpos_enc_in_obj_ptrs
118
+ self.use_signed_tpos_enc_to_obj_ptrs = use_signed_tpos_enc_to_obj_ptrs
119
+ self.only_obj_ptrs_in_the_past_for_eval = only_obj_ptrs_in_the_past_for_eval
120
+
121
+ # Part 2: memory attention to condition current frame's visual features
122
+ # with memories (and obj ptrs) from past frames
123
+ self.memory_attention = memory_attention
124
+ self.hidden_dim = image_encoder.neck.d_model
125
+
126
+ # Part 3: memory encoder for the previous frame's outputs
127
+ self.memory_encoder = memory_encoder
128
+ self.mem_dim = self.hidden_dim
129
+ if hasattr(self.memory_encoder, "out_proj") and hasattr(
130
+ self.memory_encoder.out_proj, "weight"
131
+ ):
132
+ # if there is compression of memories along channel dim
133
+ self.mem_dim = self.memory_encoder.out_proj.weight.shape[0]
134
+ self.num_maskmem = num_maskmem # Number of memories accessible
135
+ # Temporal encoding of the memories
136
+ self.maskmem_tpos_enc = torch.nn.Parameter(
137
+ torch.zeros(num_maskmem, 1, 1, self.mem_dim)
138
+ )
139
+ trunc_normal_(self.maskmem_tpos_enc, std=0.02)
140
+ # a single token to indicate no memory embedding from previous frames
141
+ self.no_mem_embed = torch.nn.Parameter(torch.zeros(1, 1, self.hidden_dim))
142
+ self.no_mem_pos_enc = torch.nn.Parameter(torch.zeros(1, 1, self.hidden_dim))
143
+ trunc_normal_(self.no_mem_embed, std=0.02)
144
+ trunc_normal_(self.no_mem_pos_enc, std=0.02)
145
+ self.directly_add_no_mem_embed = directly_add_no_mem_embed
146
+ # Apply sigmoid to the output raw mask logits (to turn them from
147
+ # range (-inf, +inf) to range (0, 1)) before feeding them into the memory encoder
148
+ self.sigmoid_scale_for_mem_enc = sigmoid_scale_for_mem_enc
149
+ self.sigmoid_bias_for_mem_enc = sigmoid_bias_for_mem_enc
150
+ self.binarize_mask_from_pts_for_mem_enc = binarize_mask_from_pts_for_mem_enc
151
+ self.non_overlap_masks_for_mem_enc = non_overlap_masks_for_mem_enc
152
+ self.memory_temporal_stride_for_eval = memory_temporal_stride_for_eval
153
+ # On frames with mask input, whether to directly output the input mask without
154
+ # using a SAM prompt encoder + mask decoder
155
+ self.use_mask_input_as_output_without_sam = use_mask_input_as_output_without_sam
156
+ self.multimask_output_in_sam = multimask_output_in_sam
157
+ self.multimask_min_pt_num = multimask_min_pt_num
158
+ self.multimask_max_pt_num = multimask_max_pt_num
159
+ self.multimask_output_for_tracking = multimask_output_for_tracking
160
+ self.use_multimask_token_for_obj_ptr = use_multimask_token_for_obj_ptr
161
+ self.iou_prediction_use_sigmoid = iou_prediction_use_sigmoid
162
+
163
+ # Part 4: SAM-style prompt encoder (for both mask and point inputs)
164
+ # and SAM-style mask decoder for the final mask output
165
+ self.image_size = image_size
166
+ self.backbone_stride = backbone_stride
167
+ self.sam_mask_decoder_extra_args = sam_mask_decoder_extra_args
168
+ self.pred_obj_scores = pred_obj_scores
169
+ self.pred_obj_scores_mlp = pred_obj_scores_mlp
170
+ self.fixed_no_obj_ptr = fixed_no_obj_ptr
171
+ self.soft_no_obj_ptr = soft_no_obj_ptr
172
+ if self.fixed_no_obj_ptr:
173
+ assert self.pred_obj_scores
174
+ assert self.use_obj_ptrs_in_encoder
175
+ if self.pred_obj_scores and self.use_obj_ptrs_in_encoder:
176
+ self.no_obj_ptr = torch.nn.Parameter(torch.zeros(1, self.hidden_dim))
177
+ trunc_normal_(self.no_obj_ptr, std=0.02)
178
+ self.use_mlp_for_obj_ptr_proj = use_mlp_for_obj_ptr_proj
179
+ self.no_obj_embed_spatial = None
180
+ if no_obj_embed_spatial:
181
+ self.no_obj_embed_spatial = torch.nn.Parameter(torch.zeros(1, self.mem_dim))
182
+ trunc_normal_(self.no_obj_embed_spatial, std=0.02)
183
+
184
+ self._build_sam_heads()
185
+ self.max_cond_frames_in_attn = max_cond_frames_in_attn
186
+
187
+ # Model compilation
188
+ if compile_image_encoder:
189
+ # Compile the forward function (not the full module) to allow loading checkpoints.
190
+ print(
191
+ "Image encoder compilation is enabled. First forward pass will be slow."
192
+ )
193
+ self.image_encoder.forward = torch.compile(
194
+ self.image_encoder.forward,
195
+ mode="max-autotune",
196
+ fullgraph=True,
197
+ dynamic=False,
198
+ )
199
+
200
+ @property
201
+ def device(self):
202
+ return next(self.parameters()).device
203
+
204
+ def forward(self, *args, **kwargs):
205
+ raise NotImplementedError(
206
+ "Please use the corresponding methods in EfficientTAMVideoPredictor for inference"
207
+ )
208
+
209
+ def _build_sam_heads(self):
210
+ """Build SAM-style prompt encoder and mask decoder."""
211
+ self.sam_prompt_embed_dim = self.hidden_dim
212
+ self.sam_image_embedding_size = self.image_size // self.backbone_stride
213
+
214
+ # build PromptEncoder and MaskDecoder from SAM
215
+ # (their hyperparameters like `mask_in_chans=16` are from SAM code)
216
+ self.sam_prompt_encoder = PromptEncoder(
217
+ embed_dim=self.sam_prompt_embed_dim,
218
+ image_embedding_size=(
219
+ self.sam_image_embedding_size,
220
+ self.sam_image_embedding_size,
221
+ ),
222
+ input_image_size=(self.image_size, self.image_size),
223
+ mask_in_chans=16,
224
+ )
225
+ self.sam_mask_decoder = MaskDecoder(
226
+ num_multimask_outputs=3,
227
+ transformer=TwoWayTransformer(
228
+ depth=2,
229
+ embedding_dim=self.sam_prompt_embed_dim,
230
+ mlp_dim=2048,
231
+ num_heads=8,
232
+ ),
233
+ transformer_dim=self.sam_prompt_embed_dim,
234
+ iou_head_depth=3,
235
+ iou_head_hidden_dim=256,
236
+ use_high_res_features=self.use_high_res_features_in_sam,
237
+ iou_prediction_use_sigmoid=self.iou_prediction_use_sigmoid,
238
+ pred_obj_scores=self.pred_obj_scores,
239
+ pred_obj_scores_mlp=self.pred_obj_scores_mlp,
240
+ use_multimask_token_for_obj_ptr=self.use_multimask_token_for_obj_ptr,
241
+ **(self.sam_mask_decoder_extra_args or {}),
242
+ )
243
+ if self.use_obj_ptrs_in_encoder:
244
+ # a linear projection on SAM output tokens to turn them into object pointers
245
+ self.obj_ptr_proj = torch.nn.Linear(self.hidden_dim, self.hidden_dim)
246
+ if self.use_mlp_for_obj_ptr_proj:
247
+ self.obj_ptr_proj = MLP(
248
+ self.hidden_dim, self.hidden_dim, self.hidden_dim, 3
249
+ )
250
+ else:
251
+ self.obj_ptr_proj = torch.nn.Identity()
252
+ if self.proj_tpos_enc_in_obj_ptrs:
253
+ # a linear projection on temporal positional encoding in object pointers to
254
+ # avoid potential interference with spatial positional encoding
255
+ self.obj_ptr_tpos_proj = torch.nn.Linear(self.hidden_dim, self.mem_dim)
256
+ else:
257
+ self.obj_ptr_tpos_proj = torch.nn.Identity()
258
+
259
+ def _forward_sam_heads(
260
+ self,
261
+ backbone_features,
262
+ point_inputs=None,
263
+ mask_inputs=None,
264
+ high_res_features=None,
265
+ multimask_output=False,
266
+ ):
267
+ """
268
+ Forward SAM prompt encoders and mask heads.
269
+
270
+ Inputs:
271
+ - backbone_features: image features of [B, C, H, W] shape
272
+ - point_inputs: a dictionary with "point_coords" and "point_labels", where
273
+ 1) "point_coords" has [B, P, 2] shape and float32 dtype and contains the
274
+ absolute pixel-unit coordinate in (x, y) format of the P input points
275
+ 2) "point_labels" has shape [B, P] and int32 dtype, where 1 means
276
+ positive clicks, 0 means negative clicks, and -1 means padding
277
+ - mask_inputs: a mask of [B, 1, H*16, W*16] shape, float or bool, with the
278
+ same spatial size as the image.
279
+ - high_res_features: either 1) None or 2) or a list of length 2 containing
280
+ two feature maps of [B, C, 4*H, 4*W] and [B, C, 2*H, 2*W] shapes respectively,
281
+ which will be used as high-resolution feature maps for SAM decoder.
282
+ - multimask_output: if it's True, we output 3 candidate masks and their 3
283
+ corresponding IoU estimates, and if it's False, we output only 1 mask and
284
+ its corresponding IoU estimate.
285
+
286
+ Outputs:
287
+ - low_res_multimasks: [B, M, H*4, W*4] shape (where M = 3 if
288
+ `multimask_output=True` and M = 1 if `multimask_output=False`), the SAM
289
+ output mask logits (before sigmoid) for the low-resolution masks, with 4x
290
+ the resolution (1/4 stride) of the input backbone_features.
291
+ - high_res_multimasks: [B, M, H*16, W*16] shape (where M = 3
292
+ if `multimask_output=True` and M = 1 if `multimask_output=False`),
293
+ upsampled from the low-resolution masks, with shape size as the image
294
+ (stride is 1 pixel).
295
+ - ious, [B, M] shape, where (where M = 3 if `multimask_output=True` and M = 1
296
+ if `multimask_output=False`), the estimated IoU of each output mask.
297
+ - low_res_masks: [B, 1, H*4, W*4] shape, the best mask in `low_res_multimasks`.
298
+ If `multimask_output=True`, it's the mask with the highest IoU estimate.
299
+ If `multimask_output=False`, it's the same as `low_res_multimasks`.
300
+ - high_res_masks: [B, 1, H*16, W*16] shape, the best mask in `high_res_multimasks`.
301
+ If `multimask_output=True`, it's the mask with the highest IoU estimate.
302
+ If `multimask_output=False`, it's the same as `high_res_multimasks`.
303
+ - obj_ptr: [B, C] shape, the object pointer vector for the output mask, extracted
304
+ based on the output token from the SAM mask decoder.
305
+ """
306
+ B = backbone_features.size(0)
307
+ device = backbone_features.device
308
+ assert backbone_features.size(1) == self.sam_prompt_embed_dim
309
+ assert backbone_features.size(2) == self.sam_image_embedding_size
310
+ assert backbone_features.size(3) == self.sam_image_embedding_size
311
+
312
+ # a) Handle point prompts
313
+ if point_inputs is not None:
314
+ sam_point_coords = point_inputs["point_coords"]
315
+ sam_point_labels = point_inputs["point_labels"]
316
+ assert sam_point_coords.size(0) == B and sam_point_labels.size(0) == B
317
+ else:
318
+ # If no points are provide, pad with an empty point (with label -1)
319
+ sam_point_coords = torch.zeros(B, 1, 2, device=device)
320
+ sam_point_labels = -torch.ones(B, 1, dtype=torch.int32, device=device)
321
+
322
+ # b) Handle mask prompts
323
+ if mask_inputs is not None:
324
+ # If mask_inputs is provided, downsize it into low-res mask input if needed
325
+ # and feed it as a dense mask prompt into the SAM mask encoder
326
+ assert len(mask_inputs.shape) == 4 and mask_inputs.shape[:2] == (B, 1)
327
+ if mask_inputs.shape[-2:] != self.sam_prompt_encoder.mask_input_size:
328
+ sam_mask_prompt = F.interpolate(
329
+ mask_inputs.float(),
330
+ size=self.sam_prompt_encoder.mask_input_size,
331
+ align_corners=False,
332
+ mode="bilinear",
333
+ antialias=True, # use antialias for downsampling
334
+ )
335
+ else:
336
+ sam_mask_prompt = mask_inputs
337
+ else:
338
+ # Otherwise, simply feed None (and SAM's prompt encoder will add
339
+ # a learned `no_mask_embed` to indicate no mask input in this case).
340
+ sam_mask_prompt = None
341
+
342
+ sparse_embeddings, dense_embeddings = self.sam_prompt_encoder(
343
+ points=(sam_point_coords, sam_point_labels),
344
+ boxes=None,
345
+ masks=sam_mask_prompt,
346
+ )
347
+ (
348
+ low_res_multimasks,
349
+ ious,
350
+ sam_output_tokens,
351
+ object_score_logits,
352
+ ) = self.sam_mask_decoder(
353
+ image_embeddings=backbone_features,
354
+ image_pe=self.sam_prompt_encoder.get_dense_pe(),
355
+ sparse_prompt_embeddings=sparse_embeddings,
356
+ dense_prompt_embeddings=dense_embeddings,
357
+ multimask_output=multimask_output,
358
+ repeat_image=False, # the image is already batched
359
+ high_res_features=high_res_features,
360
+ )
361
+ if self.pred_obj_scores:
362
+ is_obj_appearing = object_score_logits > 0
363
+
364
+ # Mask used for spatial memories is always a *hard* choice between obj and no obj,
365
+ # consistent with the actual mask prediction
366
+ low_res_multimasks = torch.where(
367
+ is_obj_appearing[:, None, None],
368
+ low_res_multimasks,
369
+ NO_OBJ_SCORE,
370
+ )
371
+
372
+ # convert masks from possibly bfloat16 (or float16) to float32
373
+ # (older PyTorch versions before 2.1 don't support `interpolate` on bf16)
374
+ low_res_multimasks = low_res_multimasks.float()
375
+ high_res_multimasks = F.interpolate(
376
+ low_res_multimasks,
377
+ size=(self.image_size, self.image_size),
378
+ mode="bilinear",
379
+ align_corners=False,
380
+ )
381
+
382
+ sam_output_token = sam_output_tokens[:, 0]
383
+ if multimask_output:
384
+ # take the best mask prediction (with the highest IoU estimation)
385
+ best_iou_inds = torch.argmax(ious, dim=-1)
386
+ batch_inds = torch.arange(B, device=device)
387
+ low_res_masks = low_res_multimasks[batch_inds, best_iou_inds].unsqueeze(1)
388
+ high_res_masks = high_res_multimasks[batch_inds, best_iou_inds].unsqueeze(1)
389
+ if sam_output_tokens.size(1) > 1:
390
+ sam_output_token = sam_output_tokens[batch_inds, best_iou_inds]
391
+ else:
392
+ low_res_masks, high_res_masks = low_res_multimasks, high_res_multimasks
393
+
394
+ # Extract object pointer from the SAM output token (with occlusion handling)
395
+ obj_ptr = self.obj_ptr_proj(sam_output_token)
396
+ if self.pred_obj_scores:
397
+ # Allow *soft* no obj ptr, unlike for masks
398
+ if self.soft_no_obj_ptr:
399
+ lambda_is_obj_appearing = object_score_logits.sigmoid()
400
+ else:
401
+ lambda_is_obj_appearing = is_obj_appearing.float()
402
+
403
+ if self.fixed_no_obj_ptr:
404
+ obj_ptr = lambda_is_obj_appearing * obj_ptr
405
+ obj_ptr = obj_ptr + (1 - lambda_is_obj_appearing) * self.no_obj_ptr
406
+
407
+ return (
408
+ low_res_multimasks,
409
+ high_res_multimasks,
410
+ ious,
411
+ low_res_masks,
412
+ high_res_masks,
413
+ obj_ptr,
414
+ object_score_logits,
415
+ )
416
+
417
+ def _use_mask_as_output(self, backbone_features, high_res_features, mask_inputs):
418
+ """
419
+ Directly turn binary `mask_inputs` into a output mask logits without using SAM.
420
+ (same input and output shapes as in _forward_sam_heads above).
421
+ """
422
+ # Use -10/+10 as logits for neg/pos pixels (very close to 0/1 in prob after sigmoid).
423
+ out_scale, out_bias = 20.0, -10.0 # sigmoid(-10.0)=4.5398e-05
424
+ mask_inputs_float = mask_inputs.float()
425
+ high_res_masks = mask_inputs_float * out_scale + out_bias
426
+ low_res_masks = F.interpolate(
427
+ high_res_masks,
428
+ size=(high_res_masks.size(-2) // 4, high_res_masks.size(-1) // 4),
429
+ align_corners=False,
430
+ mode="bilinear",
431
+ antialias=True, # use antialias for downsampling
432
+ )
433
+ # a dummy IoU prediction of all 1's under mask input
434
+ ious = mask_inputs.new_ones(mask_inputs.size(0), 1).float()
435
+ if not self.use_obj_ptrs_in_encoder:
436
+ # all zeros as a dummy object pointer (of shape [B, C])
437
+ obj_ptr = torch.zeros(
438
+ mask_inputs.size(0), self.hidden_dim, device=mask_inputs.device
439
+ )
440
+ else:
441
+ # produce an object pointer using the SAM decoder from the mask input
442
+ _, _, _, _, _, obj_ptr, _ = self._forward_sam_heads(
443
+ backbone_features=backbone_features,
444
+ mask_inputs=self.mask_downsample(mask_inputs_float),
445
+ high_res_features=high_res_features,
446
+ )
447
+ # In this method, we are treating mask_input as output, e.g. using it directly to create spatial mem;
448
+ # Below, we follow the same design axiom to use mask_input to decide if obj appears or not instead of relying
449
+ # on the object_scores from the SAM decoder.
450
+ is_obj_appearing = torch.any(mask_inputs.flatten(1).float() > 0.0, dim=1)
451
+ is_obj_appearing = is_obj_appearing[..., None]
452
+ lambda_is_obj_appearing = is_obj_appearing.float()
453
+ object_score_logits = out_scale * lambda_is_obj_appearing + out_bias
454
+ if self.pred_obj_scores:
455
+ if self.fixed_no_obj_ptr:
456
+ obj_ptr = lambda_is_obj_appearing * obj_ptr
457
+ obj_ptr = obj_ptr + (1 - lambda_is_obj_appearing) * self.no_obj_ptr
458
+
459
+ return (
460
+ low_res_masks,
461
+ high_res_masks,
462
+ ious,
463
+ low_res_masks,
464
+ high_res_masks,
465
+ obj_ptr,
466
+ object_score_logits,
467
+ )
468
+
469
+ def forward_image(self, img_batch: torch.Tensor):
470
+ """Get the image feature on the input batch."""
471
+ backbone_out = self.image_encoder(img_batch)
472
+ if self.use_high_res_features_in_sam:
473
+ # precompute projected level 0 and level 1 features in SAM decoder
474
+ # to avoid running it again on every SAM click
475
+ backbone_out["backbone_fpn"][0] = self.sam_mask_decoder.conv_s0(
476
+ backbone_out["backbone_fpn"][0]
477
+ )
478
+ backbone_out["backbone_fpn"][1] = self.sam_mask_decoder.conv_s1(
479
+ backbone_out["backbone_fpn"][1]
480
+ )
481
+ return backbone_out
482
+
483
+ def _prepare_backbone_features(self, backbone_out):
484
+ """Prepare and flatten visual features."""
485
+ backbone_out = backbone_out.copy()
486
+ assert len(backbone_out["backbone_fpn"]) == len(backbone_out["vision_pos_enc"])
487
+ assert len(backbone_out["backbone_fpn"]) >= self.num_feature_levels
488
+
489
+ feature_maps = backbone_out["backbone_fpn"][-self.num_feature_levels :]
490
+ vision_pos_embeds = backbone_out["vision_pos_enc"][-self.num_feature_levels :]
491
+
492
+ feat_sizes = [(x.shape[-2], x.shape[-1]) for x in vision_pos_embeds]
493
+ # flatten NxCxHxW to HWxNxC
494
+ vision_feats = [x.flatten(2).permute(2, 0, 1) for x in feature_maps]
495
+ vision_pos_embeds = [x.flatten(2).permute(2, 0, 1) for x in vision_pos_embeds]
496
+
497
+ return backbone_out, vision_feats, vision_pos_embeds, feat_sizes
498
+
499
+ def _prepare_memory_conditioned_features(
500
+ self,
501
+ frame_idx,
502
+ is_init_cond_frame,
503
+ current_vision_feats,
504
+ current_vision_pos_embeds,
505
+ feat_sizes,
506
+ output_dict,
507
+ num_frames,
508
+ track_in_reverse=False, # tracking in reverse time order (for demo usage)
509
+ ):
510
+ """Fuse the current frame's visual feature map with previous memory."""
511
+ B = current_vision_feats[-1].size(1) # batch size on this frame
512
+ C = self.hidden_dim
513
+ H, W = feat_sizes[-1] # top-level (lowest-resolution) feature size
514
+ device = current_vision_feats[-1].device
515
+ # The case of `self.num_maskmem == 0` below is primarily used for reproducing SAM on images.
516
+ # In this case, we skip the fusion with any memory.
517
+ if self.num_maskmem == 0: # Disable memory and skip fusion
518
+ pix_feat = current_vision_feats[-1].permute(1, 2, 0).view(B, C, H, W)
519
+ return pix_feat
520
+
521
+ num_obj_ptr_tokens = 0
522
+ tpos_sign_mul = -1 if track_in_reverse else 1
523
+ # Step 1: condition the visual features of the current frame on previous memories
524
+ if not is_init_cond_frame:
525
+ # Retrieve the memories encoded with the maskmem backbone
526
+ to_cat_memory, to_cat_memory_pos_embed = [], []
527
+ # Add conditioning frames's output first (all cond frames have t_pos=0 for
528
+ # when getting temporal positional embedding below)
529
+ assert len(output_dict["cond_frame_outputs"]) > 0
530
+ # Select a maximum number of temporally closest cond frames for cross attention
531
+ cond_outputs = output_dict["cond_frame_outputs"]
532
+ selected_cond_outputs, unselected_cond_outputs = select_closest_cond_frames(
533
+ frame_idx, cond_outputs, self.max_cond_frames_in_attn
534
+ )
535
+ t_pos_and_prevs = [(0, out) for out in selected_cond_outputs.values()]
536
+ # Add last (self.num_maskmem - 1) frames before current frame for non-conditioning memory
537
+ # the earliest one has t_pos=1 and the latest one has t_pos=self.num_maskmem-1
538
+ # We also allow taking the memory frame non-consecutively (with stride>1), in which case
539
+ # we take (self.num_maskmem - 2) frames among every stride-th frames plus the last frame.
540
+ stride = 1 if self.training else self.memory_temporal_stride_for_eval
541
+ for t_pos in range(1, self.num_maskmem):
542
+ t_rel = self.num_maskmem - t_pos # how many frames before current frame
543
+ if t_rel == 1:
544
+ # for t_rel == 1, we take the last frame (regardless of r)
545
+ if not track_in_reverse:
546
+ # the frame immediately before this frame (i.e. frame_idx - 1)
547
+ prev_frame_idx = frame_idx - t_rel
548
+ else:
549
+ # the frame immediately after this frame (i.e. frame_idx + 1)
550
+ prev_frame_idx = frame_idx + t_rel
551
+ else:
552
+ # for t_rel >= 2, we take the memory frame from every r-th frames
553
+ if not track_in_reverse:
554
+ # first find the nearest frame among every r-th frames before this frame
555
+ # for r=1, this would be (frame_idx - 2)
556
+ prev_frame_idx = ((frame_idx - 2) // stride) * stride
557
+ # then seek further among every r-th frames
558
+ prev_frame_idx = prev_frame_idx - (t_rel - 2) * stride
559
+ else:
560
+ # first find the nearest frame among every r-th frames after this frame
561
+ # for r=1, this would be (frame_idx + 2)
562
+ prev_frame_idx = -(-(frame_idx + 2) // stride) * stride
563
+ # then seek further among every r-th frames
564
+ prev_frame_idx = prev_frame_idx + (t_rel - 2) * stride
565
+ out = output_dict["non_cond_frame_outputs"].get(prev_frame_idx, None)
566
+ if out is None:
567
+ # If an unselected conditioning frame is among the last (self.num_maskmem - 1)
568
+ # frames, we still attend to it as if it's a non-conditioning frame.
569
+ out = unselected_cond_outputs.get(prev_frame_idx, None)
570
+ t_pos_and_prevs.append((t_pos, out))
571
+
572
+ for t_pos, prev in t_pos_and_prevs:
573
+ if prev is None:
574
+ continue # skip padding frames
575
+ # "maskmem_features" might have been offloaded to CPU in demo use cases,
576
+ # so we load it back to GPU (it's a no-op if it's already on GPU).
577
+ feats = prev["maskmem_features"].to(device, non_blocking=True)
578
+ to_cat_memory.append(feats.flatten(2).permute(2, 0, 1))
579
+ # Spatial positional encoding (it might have been offloaded to CPU in eval)
580
+ maskmem_enc = prev["maskmem_pos_enc"][-1].to(device)
581
+ maskmem_enc = maskmem_enc.flatten(2).permute(2, 0, 1)
582
+ # Temporal positional encoding
583
+ maskmem_enc = (
584
+ maskmem_enc + self.maskmem_tpos_enc[self.num_maskmem - t_pos - 1]
585
+ )
586
+ to_cat_memory_pos_embed.append(maskmem_enc)
587
+
588
+ # Construct the list of past object pointers
589
+ if self.use_obj_ptrs_in_encoder:
590
+ max_obj_ptrs_in_encoder = min(num_frames, self.max_obj_ptrs_in_encoder)
591
+ # First add those object pointers from selected conditioning frames
592
+ # (optionally, only include object pointers in the past during evaluation)
593
+ if not self.training and self.only_obj_ptrs_in_the_past_for_eval:
594
+ ptr_cond_outputs = {
595
+ t: out
596
+ for t, out in selected_cond_outputs.items()
597
+ if (t >= frame_idx if track_in_reverse else t <= frame_idx)
598
+ }
599
+ else:
600
+ ptr_cond_outputs = selected_cond_outputs
601
+ pos_and_ptrs = [
602
+ # Temporal pos encoding contains how far away each pointer is from current frame
603
+ (
604
+ (
605
+ (frame_idx - t) * tpos_sign_mul
606
+ if self.use_signed_tpos_enc_to_obj_ptrs
607
+ else abs(frame_idx - t)
608
+ ),
609
+ out["obj_ptr"],
610
+ )
611
+ for t, out in ptr_cond_outputs.items()
612
+ ]
613
+ # Add up to (max_obj_ptrs_in_encoder - 1) non-conditioning frames before current frame
614
+ for t_diff in range(1, max_obj_ptrs_in_encoder):
615
+ t = frame_idx + t_diff if track_in_reverse else frame_idx - t_diff
616
+ if t < 0 or (num_frames is not None and t >= num_frames):
617
+ break
618
+ out = output_dict["non_cond_frame_outputs"].get(
619
+ t, unselected_cond_outputs.get(t, None)
620
+ )
621
+ if out is not None:
622
+ pos_and_ptrs.append((t_diff, out["obj_ptr"]))
623
+ # If we have at least one object pointer, add them to the across attention
624
+ if len(pos_and_ptrs) > 0:
625
+ pos_list, ptrs_list = zip(*pos_and_ptrs)
626
+ # stack object pointers along dim=0 into [ptr_seq_len, B, C] shape
627
+ obj_ptrs = torch.stack(ptrs_list, dim=0)
628
+ # a temporal positional embedding based on how far each object pointer is from
629
+ # the current frame (sine embedding normalized by the max pointer num).
630
+ if self.add_tpos_enc_to_obj_ptrs:
631
+ t_diff_max = max_obj_ptrs_in_encoder - 1
632
+ tpos_dim = C if self.proj_tpos_enc_in_obj_ptrs else self.mem_dim
633
+ obj_pos = torch.tensor(pos_list).to(
634
+ device=device, non_blocking=True
635
+ )
636
+ obj_pos = get_1d_sine_pe(obj_pos / t_diff_max, dim=tpos_dim)
637
+ obj_pos = self.obj_ptr_tpos_proj(obj_pos)
638
+ obj_pos = obj_pos.unsqueeze(1).expand(-1, B, self.mem_dim)
639
+ else:
640
+ obj_pos = obj_ptrs.new_zeros(len(pos_list), B, self.mem_dim)
641
+ if self.mem_dim < C:
642
+ # split a pointer into (C // self.mem_dim) tokens for self.mem_dim < C
643
+ obj_ptrs = obj_ptrs.reshape(
644
+ -1, B, C // self.mem_dim, self.mem_dim
645
+ )
646
+ obj_ptrs = obj_ptrs.permute(0, 2, 1, 3).flatten(0, 1)
647
+ obj_pos = obj_pos.repeat_interleave(C // self.mem_dim, dim=0)
648
+ to_cat_memory.append(obj_ptrs)
649
+ to_cat_memory_pos_embed.append(obj_pos)
650
+ num_obj_ptr_tokens = obj_ptrs.shape[0]
651
+ else:
652
+ num_obj_ptr_tokens = 0
653
+ else:
654
+ # for initial conditioning frames, encode them without using any previous memory
655
+ if self.directly_add_no_mem_embed:
656
+ # directly add no-mem embedding (instead of using the transformer encoder)
657
+ pix_feat_with_mem = current_vision_feats[-1] + self.no_mem_embed
658
+ pix_feat_with_mem = pix_feat_with_mem.permute(1, 2, 0).view(B, C, H, W)
659
+ return pix_feat_with_mem
660
+
661
+ # Use a dummy token on the first frame (to avoid empty memory input to tranformer encoder)
662
+ to_cat_memory = [self.no_mem_embed.expand(1, B, self.mem_dim)]
663
+ to_cat_memory_pos_embed = [self.no_mem_pos_enc.expand(1, B, self.mem_dim)]
664
+
665
+ # Step 2: Concatenate the memories and forward through the transformer encoder
666
+ memory = torch.cat(to_cat_memory, dim=0)
667
+ memory_pos_embed = torch.cat(to_cat_memory_pos_embed, dim=0)
668
+
669
+ pix_feat_with_mem = self.memory_attention(
670
+ curr=current_vision_feats,
671
+ curr_pos=current_vision_pos_embeds,
672
+ memory=memory,
673
+ memory_pos=memory_pos_embed,
674
+ num_obj_ptr_tokens=num_obj_ptr_tokens,
675
+ )
676
+ # reshape the output (HW)BC => BCHW
677
+ pix_feat_with_mem = pix_feat_with_mem.permute(1, 2, 0).view(B, C, H, W)
678
+ return pix_feat_with_mem
679
+
680
+ def _encode_new_memory(
681
+ self,
682
+ current_vision_feats,
683
+ feat_sizes,
684
+ pred_masks_high_res,
685
+ object_score_logits,
686
+ is_mask_from_pts,
687
+ ):
688
+ """Encode the current image and its prediction into a memory feature."""
689
+ B = current_vision_feats[-1].size(1) # batch size on this frame
690
+ C = self.hidden_dim
691
+ H, W = feat_sizes[-1] # top-level (lowest-resolution) feature size
692
+ # top-level feature, (HW)BC => BCHW
693
+ pix_feat = current_vision_feats[-1].permute(1, 2, 0).view(B, C, H, W)
694
+ if self.non_overlap_masks_for_mem_enc and not self.training:
695
+ # optionally, apply non-overlapping constraints to the masks (it's applied
696
+ # in the batch dimension and should only be used during eval, where all
697
+ # the objects come from the same video under batch size 1).
698
+ pred_masks_high_res = self._apply_non_overlapping_constraints(
699
+ pred_masks_high_res
700
+ )
701
+ # scale the raw mask logits with a temperature before applying sigmoid
702
+ binarize = self.binarize_mask_from_pts_for_mem_enc and is_mask_from_pts
703
+ if binarize and not self.training:
704
+ mask_for_mem = (pred_masks_high_res > 0).float()
705
+ else:
706
+ # apply sigmoid on the raw mask logits to turn them into range (0, 1)
707
+ mask_for_mem = torch.sigmoid(pred_masks_high_res)
708
+ # apply scale and bias terms to the sigmoid probabilities
709
+ if self.sigmoid_scale_for_mem_enc != 1.0:
710
+ mask_for_mem = mask_for_mem * self.sigmoid_scale_for_mem_enc
711
+ if self.sigmoid_bias_for_mem_enc != 0.0:
712
+ mask_for_mem = mask_for_mem + self.sigmoid_bias_for_mem_enc
713
+ maskmem_out = self.memory_encoder(
714
+ pix_feat, mask_for_mem, skip_mask_sigmoid=True # sigmoid already applied
715
+ )
716
+ maskmem_features = maskmem_out["vision_features"]
717
+ maskmem_pos_enc = maskmem_out["vision_pos_enc"]
718
+ # add a no-object embedding to the spatial memory to indicate that the frame
719
+ # is predicted to be occluded (i.e. no object is appearing in the frame)
720
+ if self.no_obj_embed_spatial is not None:
721
+ is_obj_appearing = (object_score_logits > 0).float()
722
+ maskmem_features += (
723
+ 1 - is_obj_appearing[..., None, None]
724
+ ) * self.no_obj_embed_spatial[..., None, None].expand(
725
+ *maskmem_features.shape
726
+ )
727
+
728
+ return maskmem_features, maskmem_pos_enc
729
+
730
+ def _track_step(
731
+ self,
732
+ frame_idx,
733
+ is_init_cond_frame,
734
+ current_vision_feats,
735
+ current_vision_pos_embeds,
736
+ feat_sizes,
737
+ point_inputs,
738
+ mask_inputs,
739
+ output_dict,
740
+ num_frames,
741
+ track_in_reverse,
742
+ prev_sam_mask_logits,
743
+ ):
744
+ current_out = {"point_inputs": point_inputs, "mask_inputs": mask_inputs}
745
+ # High-resolution feature maps for the SAM head, reshape (HW)BC => BCHW
746
+ if len(current_vision_feats) > 1:
747
+ high_res_features = [
748
+ x.permute(1, 2, 0).view(x.size(1), x.size(2), *s)
749
+ for x, s in zip(current_vision_feats[:-1], feat_sizes[:-1])
750
+ ]
751
+ else:
752
+ high_res_features = None
753
+ if mask_inputs is not None and self.use_mask_input_as_output_without_sam:
754
+ # When use_mask_input_as_output_without_sam=True, we directly output the mask input
755
+ # (see it as a GT mask) without using a SAM prompt encoder + mask decoder.
756
+ pix_feat = current_vision_feats[-1].permute(1, 2, 0)
757
+ pix_feat = pix_feat.view(-1, self.hidden_dim, *feat_sizes[-1])
758
+ sam_outputs = self._use_mask_as_output(
759
+ pix_feat, high_res_features, mask_inputs
760
+ )
761
+ else:
762
+ # fused the visual feature with previous memory features in the memory bank
763
+ pix_feat = self._prepare_memory_conditioned_features(
764
+ frame_idx=frame_idx,
765
+ is_init_cond_frame=is_init_cond_frame,
766
+ current_vision_feats=current_vision_feats[-1:],
767
+ current_vision_pos_embeds=current_vision_pos_embeds[-1:],
768
+ feat_sizes=feat_sizes[-1:],
769
+ output_dict=output_dict,
770
+ num_frames=num_frames,
771
+ track_in_reverse=track_in_reverse,
772
+ )
773
+ # apply SAM-style segmentation head
774
+ # here we might feed previously predicted low-res SAM mask logits into the SAM mask decoder,
775
+ # e.g. in demo where such logits come from earlier interaction instead of correction sampling
776
+ # (in this case, any `mask_inputs` shouldn't reach here as they are sent to _use_mask_as_output instead)
777
+ if prev_sam_mask_logits is not None:
778
+ assert point_inputs is not None and mask_inputs is None
779
+ mask_inputs = prev_sam_mask_logits
780
+ multimask_output = self._use_multimask(is_init_cond_frame, point_inputs)
781
+ sam_outputs = self._forward_sam_heads(
782
+ backbone_features=pix_feat,
783
+ point_inputs=point_inputs,
784
+ mask_inputs=mask_inputs,
785
+ high_res_features=high_res_features,
786
+ multimask_output=multimask_output,
787
+ )
788
+
789
+ return current_out, sam_outputs, high_res_features, pix_feat
790
+
791
+ def _encode_memory_in_output(
792
+ self,
793
+ current_vision_feats,
794
+ feat_sizes,
795
+ point_inputs,
796
+ run_mem_encoder,
797
+ high_res_masks,
798
+ object_score_logits,
799
+ current_out,
800
+ ):
801
+ if run_mem_encoder and self.num_maskmem > 0:
802
+ high_res_masks_for_mem_enc = high_res_masks
803
+ maskmem_features, maskmem_pos_enc = self._encode_new_memory(
804
+ current_vision_feats=current_vision_feats,
805
+ feat_sizes=feat_sizes,
806
+ pred_masks_high_res=high_res_masks_for_mem_enc,
807
+ object_score_logits=object_score_logits,
808
+ is_mask_from_pts=(point_inputs is not None),
809
+ )
810
+ current_out["maskmem_features"] = maskmem_features
811
+ current_out["maskmem_pos_enc"] = maskmem_pos_enc
812
+ else:
813
+ current_out["maskmem_features"] = None
814
+ current_out["maskmem_pos_enc"] = None
815
+
816
+ def track_step(
817
+ self,
818
+ frame_idx,
819
+ is_init_cond_frame,
820
+ current_vision_feats,
821
+ current_vision_pos_embeds,
822
+ feat_sizes,
823
+ point_inputs,
824
+ mask_inputs,
825
+ output_dict,
826
+ num_frames,
827
+ track_in_reverse=False, # tracking in reverse time order (for demo usage)
828
+ # Whether to run the memory encoder on the predicted masks. Sometimes we might want
829
+ # to skip the memory encoder with `run_mem_encoder=False`. For example,
830
+ # in demo we might call `track_step` multiple times for each user click,
831
+ # and only encode the memory when the user finalizes their clicks. And in ablation
832
+ # settings like SAM training on static images, we don't need the memory encoder.
833
+ run_mem_encoder=True,
834
+ # The previously predicted SAM mask logits (which can be fed together with new clicks in demo).
835
+ prev_sam_mask_logits=None,
836
+ ):
837
+ current_out, sam_outputs, _, _ = self._track_step(
838
+ frame_idx,
839
+ is_init_cond_frame,
840
+ current_vision_feats,
841
+ current_vision_pos_embeds,
842
+ feat_sizes,
843
+ point_inputs,
844
+ mask_inputs,
845
+ output_dict,
846
+ num_frames,
847
+ track_in_reverse,
848
+ prev_sam_mask_logits,
849
+ )
850
+
851
+ (
852
+ _,
853
+ _,
854
+ _,
855
+ low_res_masks,
856
+ high_res_masks,
857
+ obj_ptr,
858
+ object_score_logits,
859
+ ) = sam_outputs
860
+
861
+ current_out["pred_masks"] = low_res_masks
862
+ current_out["pred_masks_high_res"] = high_res_masks
863
+ current_out["obj_ptr"] = obj_ptr
864
+ if not self.training:
865
+ # Only add this in inference (to avoid unused param in activation checkpointing;
866
+ # it's mainly used in the demo to encode spatial memories w/ consolidated masks)
867
+ current_out["object_score_logits"] = object_score_logits
868
+
869
+ # Finally run the memory encoder on the predicted mask to encode
870
+ # it into a new memory feature (that can be used in future frames)
871
+ self._encode_memory_in_output(
872
+ current_vision_feats,
873
+ feat_sizes,
874
+ point_inputs,
875
+ run_mem_encoder,
876
+ high_res_masks,
877
+ object_score_logits,
878
+ current_out,
879
+ )
880
+
881
+ return current_out
882
+
883
+ def _use_multimask(self, is_init_cond_frame, point_inputs):
884
+ """Whether to use multimask output in the SAM head."""
885
+ num_pts = 0 if point_inputs is None else point_inputs["point_labels"].size(1)
886
+ multimask_output = (
887
+ self.multimask_output_in_sam
888
+ and (is_init_cond_frame or self.multimask_output_for_tracking)
889
+ and (self.multimask_min_pt_num <= num_pts <= self.multimask_max_pt_num)
890
+ )
891
+ return multimask_output
892
+
893
+ def _apply_non_overlapping_constraints(self, pred_masks):
894
+ """
895
+ Apply non-overlapping constraints to the object scores in pred_masks. Here we
896
+ keep only the highest scoring object at each spatial location in pred_masks.
897
+ """
898
+ batch_size = pred_masks.size(0)
899
+ if batch_size == 1:
900
+ return pred_masks
901
+
902
+ device = pred_masks.device
903
+ # "max_obj_inds": object index of the object with the highest score at each location
904
+ max_obj_inds = torch.argmax(pred_masks, dim=0, keepdim=True)
905
+ # "batch_obj_inds": object index of each object slice (along dim 0) in `pred_masks`
906
+ batch_obj_inds = torch.arange(batch_size, device=device)[:, None, None, None]
907
+ keep = max_obj_inds == batch_obj_inds
908
+ # suppress overlapping regions' scores below -10.0 so that the foreground regions
909
+ # don't overlap (here sigmoid(-10.0)=4.5398e-05)
910
+ pred_masks = torch.where(keep, pred_masks, torch.clamp(pred_masks, max=-10.0))
911
+ return pred_masks
MedSAM2/efficient_track_anything/modeling/efficienttam_utils.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+
8
+ import copy
9
+ from typing import Tuple, Union
10
+
11
+ import numpy as np
12
+ import torch
13
+ import torch.nn as nn
14
+ import torch.nn.functional as F
15
+
16
+ from efficient_track_anything.utils.misc import mask_to_box
17
+
18
+
19
+ def select_closest_cond_frames(frame_idx, cond_frame_outputs, max_cond_frame_num):
20
+ """
21
+ Select up to `max_cond_frame_num` conditioning frames from `cond_frame_outputs`
22
+ that are temporally closest to the current frame at `frame_idx`. Here, we take
23
+ - a) the closest conditioning frame before `frame_idx` (if any);
24
+ - b) the closest conditioning frame after `frame_idx` (if any);
25
+ - c) any other temporally closest conditioning frames until reaching a total
26
+ of `max_cond_frame_num` conditioning frames.
27
+
28
+ Outputs:
29
+ - selected_outputs: selected items (keys & values) from `cond_frame_outputs`.
30
+ - unselected_outputs: items (keys & values) not selected in `cond_frame_outputs`.
31
+ """
32
+ if max_cond_frame_num == -1 or len(cond_frame_outputs) <= max_cond_frame_num:
33
+ selected_outputs = cond_frame_outputs
34
+ unselected_outputs = {}
35
+ else:
36
+ assert max_cond_frame_num >= 2, "we should allow using 2+ conditioning frames"
37
+ selected_outputs = {}
38
+
39
+ # the closest conditioning frame before `frame_idx` (if any)
40
+ idx_before = max((t for t in cond_frame_outputs if t < frame_idx), default=None)
41
+ if idx_before is not None:
42
+ selected_outputs[idx_before] = cond_frame_outputs[idx_before]
43
+
44
+ # the closest conditioning frame after `frame_idx` (if any)
45
+ idx_after = min((t for t in cond_frame_outputs if t >= frame_idx), default=None)
46
+ if idx_after is not None:
47
+ selected_outputs[idx_after] = cond_frame_outputs[idx_after]
48
+
49
+ # add other temporally closest conditioning frames until reaching a total
50
+ # of `max_cond_frame_num` conditioning frames.
51
+ num_remain = max_cond_frame_num - len(selected_outputs)
52
+ inds_remain = sorted(
53
+ (t for t in cond_frame_outputs if t not in selected_outputs),
54
+ key=lambda x: abs(x - frame_idx),
55
+ )[:num_remain]
56
+ selected_outputs.update((t, cond_frame_outputs[t]) for t in inds_remain)
57
+ unselected_outputs = {
58
+ t: v for t, v in cond_frame_outputs.items() if t not in selected_outputs
59
+ }
60
+
61
+ return selected_outputs, unselected_outputs
62
+
63
+
64
+ def get_1d_sine_pe(pos_inds, dim, temperature=10000):
65
+ """
66
+ Get 1D sine positional embedding as in the original Transformer paper.
67
+ """
68
+ pe_dim = dim // 2
69
+ dim_t = torch.arange(pe_dim, dtype=torch.float32, device=pos_inds.device)
70
+ dim_t = temperature ** (2 * (dim_t // 2) / pe_dim)
71
+
72
+ pos_embed = pos_inds.unsqueeze(-1) / dim_t
73
+ pos_embed = torch.cat([pos_embed.sin(), pos_embed.cos()], dim=-1)
74
+ return pos_embed
75
+
76
+
77
+ def get_activation_fn(activation):
78
+ """Return an activation function given a string"""
79
+ if activation == "relu":
80
+ return F.relu
81
+ if activation == "gelu":
82
+ return F.gelu
83
+ if activation == "glu":
84
+ return F.glu
85
+ raise RuntimeError(f"activation should be relu/gelu, not {activation}.")
86
+
87
+
88
+ def get_clones(module, N):
89
+ return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
90
+
91
+
92
+ class DropPath(nn.Module):
93
+ # adapted from https://github.com/huggingface/pytorch-image-models/blob/main/timm/layers/drop.py
94
+ def __init__(self, drop_prob=0.0, scale_by_keep=True):
95
+ super(DropPath, self).__init__()
96
+ self.drop_prob = drop_prob
97
+ self.scale_by_keep = scale_by_keep
98
+
99
+ def forward(self, x):
100
+ if self.drop_prob == 0.0 or not self.training:
101
+ return x
102
+ keep_prob = 1 - self.drop_prob
103
+ shape = (x.shape[0],) + (1,) * (x.ndim - 1)
104
+ random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
105
+ if keep_prob > 0.0 and self.scale_by_keep:
106
+ random_tensor.div_(keep_prob)
107
+ return x * random_tensor
108
+
109
+
110
+ # Lightly adapted from
111
+ # https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py # noqa
112
+ class MLP(nn.Module):
113
+ def __init__(
114
+ self,
115
+ input_dim: int,
116
+ hidden_dim: int,
117
+ output_dim: int,
118
+ num_layers: int,
119
+ activation: nn.Module = nn.ReLU,
120
+ sigmoid_output: bool = False,
121
+ ) -> None:
122
+ super().__init__()
123
+ self.num_layers = num_layers
124
+ h = [hidden_dim] * (num_layers - 1)
125
+ self.layers = nn.ModuleList(
126
+ nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim])
127
+ )
128
+ self.sigmoid_output = sigmoid_output
129
+ self.act = activation()
130
+
131
+ def forward(self, x):
132
+ for i, layer in enumerate(self.layers):
133
+ x = self.act(layer(x)) if i < self.num_layers - 1 else layer(x)
134
+ if self.sigmoid_output:
135
+ x = F.sigmoid(x)
136
+ return x
137
+
138
+
139
+ # From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa
140
+ # Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa
141
+ class LayerNorm2d(nn.Module):
142
+ def __init__(self, num_channels: int, eps: float = 1e-6) -> None:
143
+ super().__init__()
144
+ self.weight = nn.Parameter(torch.ones(num_channels))
145
+ self.bias = nn.Parameter(torch.zeros(num_channels))
146
+ self.eps = eps
147
+
148
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
149
+ u = x.mean(1, keepdim=True)
150
+ s = (x - u).pow(2).mean(1, keepdim=True)
151
+ x = (x - u) / torch.sqrt(s + self.eps)
152
+ x = self.weight[:, None, None] * x + self.bias[:, None, None]
153
+ return x
154
+
155
+
156
+ def sample_box_points(
157
+ masks: torch.Tensor,
158
+ noise: float = 0.1, # SAM default
159
+ noise_bound: int = 20, # SAM default
160
+ top_left_label: int = 2,
161
+ bottom_right_label: int = 3,
162
+ ) -> Tuple[np.array, np.array]:
163
+ """
164
+ Sample a noised version of the top left and bottom right corners of a given `bbox`
165
+
166
+ Inputs:
167
+ - masks: [B, 1, H,W] boxes, dtype=torch.Tensor
168
+ - noise: noise as a fraction of box width and height, dtype=float
169
+ - noise_bound: maximum amount of noise (in pure pixesl), dtype=int
170
+
171
+ Returns:
172
+ - box_coords: [B, num_pt, 2], contains (x, y) coordinates of top left and bottom right box corners, dtype=torch.float
173
+ - box_labels: [B, num_pt], label 2 is reserverd for top left and 3 for bottom right corners, dtype=torch.int32
174
+ """
175
+ device = masks.device
176
+ box_coords = mask_to_box(masks)
177
+ B, _, H, W = masks.shape
178
+ box_labels = torch.tensor(
179
+ [top_left_label, bottom_right_label], dtype=torch.int, device=device
180
+ ).repeat(B)
181
+ if noise > 0.0:
182
+ if not isinstance(noise_bound, torch.Tensor):
183
+ noise_bound = torch.tensor(noise_bound, device=device)
184
+ bbox_w = box_coords[..., 2] - box_coords[..., 0]
185
+ bbox_h = box_coords[..., 3] - box_coords[..., 1]
186
+ max_dx = torch.min(bbox_w * noise, noise_bound)
187
+ max_dy = torch.min(bbox_h * noise, noise_bound)
188
+ box_noise = 2 * torch.rand(B, 1, 4, device=device) - 1
189
+ box_noise = box_noise * torch.stack((max_dx, max_dy, max_dx, max_dy), dim=-1)
190
+
191
+ box_coords = box_coords + box_noise
192
+ img_bounds = (
193
+ torch.tensor([W, H, W, H], device=device) - 1
194
+ ) # uncentered pixel coords
195
+ box_coords.clamp_(torch.zeros_like(img_bounds), img_bounds) # In place clamping
196
+
197
+ box_coords = box_coords.reshape(-1, 2, 2) # always 2 points
198
+ box_labels = box_labels.reshape(-1, 2)
199
+ return box_coords, box_labels
200
+
201
+
202
+ def sample_random_points_from_errors(gt_masks, pred_masks, num_pt=1):
203
+ """
204
+ Sample `num_pt` random points (along with their labels) independently from the error regions.
205
+
206
+ Inputs:
207
+ - gt_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool
208
+ - pred_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool or None
209
+ - num_pt: int, number of points to sample independently for each of the B error maps
210
+
211
+ Outputs:
212
+ - points: [B, num_pt, 2], dtype=torch.float, contains (x, y) coordinates of each sampled point
213
+ - labels: [B, num_pt], dtype=torch.int32, where 1 means positive clicks and 0 means
214
+ negative clicks
215
+ """
216
+ if pred_masks is None: # if pred_masks is not provided, treat it as empty
217
+ pred_masks = torch.zeros_like(gt_masks)
218
+ assert gt_masks.dtype == torch.bool and gt_masks.size(1) == 1
219
+ assert pred_masks.dtype == torch.bool and pred_masks.shape == gt_masks.shape
220
+ assert num_pt >= 0
221
+
222
+ B, _, H_im, W_im = gt_masks.shape
223
+ device = gt_masks.device
224
+
225
+ # false positive region, a new point sampled in this region should have
226
+ # negative label to correct the FP error
227
+ fp_masks = ~gt_masks & pred_masks
228
+ # false negative region, a new point sampled in this region should have
229
+ # positive label to correct the FN error
230
+ fn_masks = gt_masks & ~pred_masks
231
+ # whether the prediction completely match the ground-truth on each mask
232
+ all_correct = torch.all((gt_masks == pred_masks).flatten(2), dim=2)
233
+ all_correct = all_correct[..., None, None]
234
+
235
+ # channel 0 is FP map, while channel 1 is FN map
236
+ pts_noise = torch.rand(B, num_pt, H_im, W_im, 2, device=device)
237
+ # sample a negative new click from FP region or a positive new click
238
+ # from FN region, depend on where the maximum falls,
239
+ # and in case the predictions are all correct (no FP or FN), we just
240
+ # sample a negative click from the background region
241
+ pts_noise[..., 0] *= fp_masks | (all_correct & ~gt_masks)
242
+ pts_noise[..., 1] *= fn_masks
243
+ pts_idx = pts_noise.flatten(2).argmax(dim=2)
244
+ labels = (pts_idx % 2).to(torch.int32)
245
+ pts_idx = pts_idx // 2
246
+ pts_x = pts_idx % W_im
247
+ pts_y = pts_idx // W_im
248
+ points = torch.stack([pts_x, pts_y], dim=2).to(torch.float)
249
+ return points, labels
250
+
251
+
252
+ def sample_one_point_from_error_center(gt_masks, pred_masks, padding=True):
253
+ """
254
+ Sample 1 random point (along with its label) from the center of each error region,
255
+ that is, the point with the largest distance to the boundary of each error region.
256
+ This is the RITM sampling method from https://github.com/saic-vul/ritm_interactive_segmentation/blob/master/isegm/inference/clicker.py
257
+
258
+ Inputs:
259
+ - gt_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool
260
+ - pred_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool or None
261
+ - padding: if True, pad with boundary of 1 px for distance transform
262
+
263
+ Outputs:
264
+ - points: [B, 1, 2], dtype=torch.float, contains (x, y) coordinates of each sampled point
265
+ - labels: [B, 1], dtype=torch.int32, where 1 means positive clicks and 0 means negative clicks
266
+ """
267
+ import cv2
268
+
269
+ if pred_masks is None:
270
+ pred_masks = torch.zeros_like(gt_masks)
271
+ assert gt_masks.dtype == torch.bool and gt_masks.size(1) == 1
272
+ assert pred_masks.dtype == torch.bool and pred_masks.shape == gt_masks.shape
273
+
274
+ B, _, _, W_im = gt_masks.shape
275
+ device = gt_masks.device
276
+
277
+ # false positive region, a new point sampled in this region should have
278
+ # negative label to correct the FP error
279
+ fp_masks = ~gt_masks & pred_masks
280
+ # false negative region, a new point sampled in this region should have
281
+ # positive label to correct the FN error
282
+ fn_masks = gt_masks & ~pred_masks
283
+
284
+ fp_masks = fp_masks.cpu().numpy()
285
+ fn_masks = fn_masks.cpu().numpy()
286
+ points = torch.zeros(B, 1, 2, dtype=torch.float)
287
+ labels = torch.ones(B, 1, dtype=torch.int32)
288
+ for b in range(B):
289
+ fn_mask = fn_masks[b, 0]
290
+ fp_mask = fp_masks[b, 0]
291
+ if padding:
292
+ fn_mask = np.pad(fn_mask, ((1, 1), (1, 1)), "constant")
293
+ fp_mask = np.pad(fp_mask, ((1, 1), (1, 1)), "constant")
294
+ # compute the distance of each point in FN/FP region to its boundary
295
+ fn_mask_dt = cv2.distanceTransform(fn_mask.astype(np.uint8), cv2.DIST_L2, 0)
296
+ fp_mask_dt = cv2.distanceTransform(fp_mask.astype(np.uint8), cv2.DIST_L2, 0)
297
+ if padding:
298
+ fn_mask_dt = fn_mask_dt[1:-1, 1:-1]
299
+ fp_mask_dt = fp_mask_dt[1:-1, 1:-1]
300
+
301
+ # take the point in FN/FP region with the largest distance to its boundary
302
+ fn_mask_dt_flat = fn_mask_dt.reshape(-1)
303
+ fp_mask_dt_flat = fp_mask_dt.reshape(-1)
304
+ fn_argmax = np.argmax(fn_mask_dt_flat)
305
+ fp_argmax = np.argmax(fp_mask_dt_flat)
306
+ is_positive = fn_mask_dt_flat[fn_argmax] > fp_mask_dt_flat[fp_argmax]
307
+ pt_idx = fn_argmax if is_positive else fp_argmax
308
+ points[b, 0, 0] = pt_idx % W_im # x
309
+ points[b, 0, 1] = pt_idx // W_im # y
310
+ labels[b, 0] = int(is_positive)
311
+
312
+ points = points.to(device)
313
+ labels = labels.to(device)
314
+ return points, labels
315
+
316
+
317
+ def get_next_point(gt_masks, pred_masks, method):
318
+ if method == "uniform":
319
+ return sample_random_points_from_errors(gt_masks, pred_masks)
320
+ elif method == "center":
321
+ return sample_one_point_from_error_center(gt_masks, pred_masks)
322
+ else:
323
+ raise ValueError(f"unknown sampling method {method}")
324
+
325
+
326
+ class LayerScale(nn.Module):
327
+ def __init__(
328
+ self,
329
+ dim: int,
330
+ init_values: Union[float, torch.Tensor] = 1e-5,
331
+ inplace: bool = False,
332
+ ) -> None:
333
+ super().__init__()
334
+ self.inplace = inplace
335
+ self.gamma = nn.Parameter(init_values * torch.ones(dim))
336
+
337
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
338
+ return x.mul_(self.gamma) if self.inplace else x * self.gamma
MedSAM2/efficient_track_anything/modeling/memory_attention.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from typing import Optional
8
+
9
+ import torch
10
+
11
+ from efficient_track_anything.modeling.efficienttam_utils import (
12
+ get_activation_fn,
13
+ get_clones,
14
+ )
15
+
16
+ from efficient_track_anything.modeling.sam.transformer import (
17
+ EfficientRoPEAttention1,
18
+ EfficientRoPEAttention2,
19
+ RoPEAttention,
20
+ )
21
+ from torch import nn, Tensor
22
+
23
+
24
+ class MemoryAttentionLayer(nn.Module):
25
+
26
+ def __init__(
27
+ self,
28
+ activation: str,
29
+ cross_attention: nn.Module,
30
+ d_model: int,
31
+ dim_feedforward: int,
32
+ dropout: float,
33
+ pos_enc_at_attn: bool,
34
+ pos_enc_at_cross_attn_keys: bool,
35
+ pos_enc_at_cross_attn_queries: bool,
36
+ self_attention: nn.Module,
37
+ ):
38
+ super().__init__()
39
+ self.d_model = d_model
40
+ self.dim_feedforward = dim_feedforward
41
+ self.dropout_value = dropout
42
+ self.self_attn = self_attention
43
+ self.cross_attn_image = cross_attention
44
+
45
+ # Implementation of Feedforward model
46
+ self.linear1 = nn.Linear(d_model, dim_feedforward)
47
+ self.dropout = nn.Dropout(dropout)
48
+ self.linear2 = nn.Linear(dim_feedforward, d_model)
49
+
50
+ self.norm1 = nn.LayerNorm(d_model)
51
+ self.norm2 = nn.LayerNorm(d_model)
52
+ self.norm3 = nn.LayerNorm(d_model)
53
+ self.dropout1 = nn.Dropout(dropout)
54
+ self.dropout2 = nn.Dropout(dropout)
55
+ self.dropout3 = nn.Dropout(dropout)
56
+
57
+ self.activation_str = activation
58
+ self.activation = get_activation_fn(activation)
59
+
60
+ # Where to add pos enc
61
+ self.pos_enc_at_attn = pos_enc_at_attn
62
+ self.pos_enc_at_cross_attn_queries = pos_enc_at_cross_attn_queries
63
+ self.pos_enc_at_cross_attn_keys = pos_enc_at_cross_attn_keys
64
+
65
+ def _forward_sa(self, tgt, query_pos):
66
+ # Self-Attention
67
+ tgt2 = self.norm1(tgt)
68
+ q = k = tgt2 + query_pos if self.pos_enc_at_attn else tgt2
69
+ tgt2 = self.self_attn(q, k, v=tgt2)
70
+ tgt = tgt + self.dropout1(tgt2)
71
+ return tgt
72
+
73
+ def _forward_ca(self, tgt, memory, query_pos, pos, num_k_exclude_rope=0):
74
+ kwds = {}
75
+ if num_k_exclude_rope > 0:
76
+ assert (
77
+ isinstance(self.cross_attn_image, RoPEAttention)
78
+ or isinstance(self.cross_attn_image, EfficientRoPEAttention1)
79
+ or isinstance(self.cross_attn_image, EfficientRoPEAttention2)
80
+ )
81
+ kwds = {"num_k_exclude_rope": num_k_exclude_rope}
82
+
83
+ # Cross-Attention
84
+ tgt2 = self.norm2(tgt)
85
+ tgt2 = self.cross_attn_image(
86
+ q=tgt2 + query_pos if self.pos_enc_at_cross_attn_queries else tgt2,
87
+ k=memory + pos if self.pos_enc_at_cross_attn_keys else memory,
88
+ v=memory,
89
+ **kwds,
90
+ )
91
+ tgt = tgt + self.dropout2(tgt2)
92
+ return tgt
93
+
94
+ def forward(
95
+ self,
96
+ tgt,
97
+ memory,
98
+ pos: Optional[Tensor] = None,
99
+ query_pos: Optional[Tensor] = None,
100
+ num_k_exclude_rope: int = 0,
101
+ ) -> torch.Tensor:
102
+
103
+ # Self-Attn, Cross-Attn
104
+ tgt = self._forward_sa(tgt, query_pos)
105
+ tgt = self._forward_ca(tgt, memory, query_pos, pos, num_k_exclude_rope)
106
+ # MLP
107
+ tgt2 = self.norm3(tgt)
108
+ tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2))))
109
+ tgt = tgt + self.dropout3(tgt2)
110
+ return tgt
111
+
112
+
113
+ class MemoryAttention(nn.Module):
114
+ def __init__(
115
+ self,
116
+ d_model: int,
117
+ pos_enc_at_input: bool,
118
+ layer: nn.Module,
119
+ num_layers: int,
120
+ batch_first: bool = True, # Do layers expect batch first input?
121
+ ):
122
+ super().__init__()
123
+ self.d_model = d_model
124
+ self.layers = get_clones(layer, num_layers)
125
+ self.num_layers = num_layers
126
+ self.norm = nn.LayerNorm(d_model)
127
+ self.pos_enc_at_input = pos_enc_at_input
128
+ self.batch_first = batch_first
129
+
130
+ def forward(
131
+ self,
132
+ curr: torch.Tensor, # self-attention inputs
133
+ memory: torch.Tensor, # cross-attention inputs
134
+ curr_pos: Optional[Tensor] = None, # pos_enc for self-attention inputs
135
+ memory_pos: Optional[Tensor] = None, # pos_enc for cross-attention inputs
136
+ num_obj_ptr_tokens: int = 0, # number of object pointer *tokens*
137
+ ):
138
+ if isinstance(curr, list):
139
+ assert isinstance(curr_pos, list)
140
+ assert len(curr) == len(curr_pos) == 1
141
+ curr, curr_pos = (
142
+ curr[0],
143
+ curr_pos[0],
144
+ )
145
+
146
+ assert (
147
+ curr.shape[1] == memory.shape[1]
148
+ ), "Batch size must be the same for curr and memory"
149
+
150
+ output = curr
151
+ if self.pos_enc_at_input and curr_pos is not None:
152
+ output = output + 0.1 * curr_pos
153
+
154
+ if self.batch_first:
155
+ # Convert to batch first
156
+ output = output.transpose(0, 1)
157
+ curr_pos = curr_pos.transpose(0, 1)
158
+ memory = memory.transpose(0, 1)
159
+ memory_pos = memory_pos.transpose(0, 1)
160
+
161
+ for layer in self.layers:
162
+ kwds = {}
163
+ if (
164
+ isinstance(layer.cross_attn_image, RoPEAttention)
165
+ or isinstance(layer.cross_attn_image, EfficientRoPEAttention1)
166
+ or isinstance(layer.cross_attn_image, EfficientRoPEAttention2)
167
+ ):
168
+ kwds = {"num_k_exclude_rope": num_obj_ptr_tokens}
169
+
170
+ output = layer(
171
+ tgt=output,
172
+ memory=memory,
173
+ pos=memory_pos,
174
+ query_pos=curr_pos,
175
+ **kwds,
176
+ )
177
+ normed_output = self.norm(output)
178
+
179
+ if self.batch_first:
180
+ # Convert back to seq first
181
+ normed_output = normed_output.transpose(0, 1)
182
+ curr_pos = curr_pos.transpose(0, 1)
183
+
184
+ return normed_output
MedSAM2/efficient_track_anything/modeling/memory_encoder.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import math
8
+ from typing import Tuple
9
+
10
+ import torch
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+
14
+ from efficient_track_anything.modeling.efficienttam_utils import (
15
+ DropPath,
16
+ get_clones,
17
+ LayerNorm2d,
18
+ )
19
+
20
+
21
+ class MaskDownSampler(nn.Module):
22
+ """
23
+ Progressively downsample a mask by total_stride, each time by stride.
24
+ Note that LayerNorm is applied per *token*, like in ViT.
25
+
26
+ With each downsample (by a factor stride**2), channel capacity increases by the same factor.
27
+ In the end, we linearly project to embed_dim channels.
28
+ """
29
+
30
+ def __init__(
31
+ self,
32
+ embed_dim=256,
33
+ kernel_size=4,
34
+ stride=4,
35
+ padding=0,
36
+ total_stride=16,
37
+ activation=nn.GELU,
38
+ ):
39
+ super().__init__()
40
+ num_layers = int(math.log2(total_stride) // math.log2(stride))
41
+ assert stride**num_layers == total_stride
42
+ self.encoder = nn.Sequential()
43
+ mask_in_chans, mask_out_chans = 1, 1
44
+ for _ in range(num_layers):
45
+ mask_out_chans = mask_in_chans * (stride**2)
46
+ self.encoder.append(
47
+ nn.Conv2d(
48
+ mask_in_chans,
49
+ mask_out_chans,
50
+ kernel_size=kernel_size,
51
+ stride=stride,
52
+ padding=padding,
53
+ )
54
+ )
55
+ self.encoder.append(LayerNorm2d(mask_out_chans))
56
+ self.encoder.append(activation())
57
+ mask_in_chans = mask_out_chans
58
+
59
+ self.encoder.append(nn.Conv2d(mask_out_chans, embed_dim, kernel_size=1))
60
+
61
+ def forward(self, x):
62
+ return self.encoder(x)
63
+
64
+
65
+ # Lightly adapted from ConvNext (https://github.com/facebookresearch/ConvNeXt)
66
+ class CXBlock(nn.Module):
67
+ r"""ConvNeXt Block. There are two equivalent implementations:
68
+ (1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W)
69
+ (2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back
70
+ We use (2) as we find it slightly faster in PyTorch
71
+
72
+ Args:
73
+ dim (int): Number of input channels.
74
+ drop_path (float): Stochastic depth rate. Default: 0.0
75
+ layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6.
76
+ """
77
+
78
+ def __init__(
79
+ self,
80
+ dim,
81
+ kernel_size=7,
82
+ padding=3,
83
+ drop_path=0.0,
84
+ layer_scale_init_value=1e-6,
85
+ use_dwconv=True,
86
+ ):
87
+ super().__init__()
88
+ self.dwconv = nn.Conv2d(
89
+ dim,
90
+ dim,
91
+ kernel_size=kernel_size,
92
+ padding=padding,
93
+ groups=dim if use_dwconv else 1,
94
+ ) # depthwise conv
95
+ self.norm = LayerNorm2d(dim, eps=1e-6)
96
+ self.pwconv1 = nn.Linear(
97
+ dim, 4 * dim
98
+ ) # pointwise/1x1 convs, implemented with linear layers
99
+ self.act = nn.GELU()
100
+ self.pwconv2 = nn.Linear(4 * dim, dim)
101
+ self.gamma = (
102
+ nn.Parameter(layer_scale_init_value * torch.ones((dim)), requires_grad=True)
103
+ if layer_scale_init_value > 0
104
+ else None
105
+ )
106
+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
107
+
108
+ def forward(self, x):
109
+ input = x
110
+ x = self.dwconv(x)
111
+ x = self.norm(x)
112
+ x = x.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C)
113
+ x = self.pwconv1(x)
114
+ x = self.act(x)
115
+ x = self.pwconv2(x)
116
+ if self.gamma is not None:
117
+ x = self.gamma * x
118
+ x = x.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W)
119
+
120
+ x = input + self.drop_path(x)
121
+ return x
122
+
123
+
124
+ class Fuser(nn.Module):
125
+ def __init__(self, layer, num_layers, dim=None, input_projection=False):
126
+ super().__init__()
127
+ self.proj = nn.Identity()
128
+ self.layers = get_clones(layer, num_layers)
129
+
130
+ if input_projection:
131
+ assert dim is not None
132
+ self.proj = nn.Conv2d(dim, dim, kernel_size=1)
133
+
134
+ def forward(self, x):
135
+ # normally x: (N, C, H, W)
136
+ x = self.proj(x)
137
+ for layer in self.layers:
138
+ x = layer(x)
139
+ return x
140
+
141
+
142
+ class MemoryEncoder(nn.Module):
143
+ def __init__(
144
+ self,
145
+ out_dim,
146
+ mask_downsampler,
147
+ fuser,
148
+ position_encoding,
149
+ in_dim=256, # in_dim of pix_feats
150
+ ):
151
+ super().__init__()
152
+
153
+ self.mask_downsampler = mask_downsampler
154
+
155
+ self.pix_feat_proj = nn.Conv2d(in_dim, in_dim, kernel_size=1)
156
+ self.fuser = fuser
157
+ self.position_encoding = position_encoding
158
+ self.out_proj = nn.Identity()
159
+ if out_dim != in_dim:
160
+ self.out_proj = nn.Conv2d(in_dim, out_dim, kernel_size=1)
161
+
162
+ def forward(
163
+ self,
164
+ pix_feat: torch.Tensor,
165
+ masks: torch.Tensor,
166
+ skip_mask_sigmoid: bool = False,
167
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
168
+ ## Process masks
169
+ # sigmoid, so that less domain shift from gt masks which are bool
170
+ if not skip_mask_sigmoid:
171
+ masks = F.sigmoid(masks)
172
+ masks = self.mask_downsampler(masks)
173
+
174
+ ## Fuse pix_feats and downsampled masks
175
+ # in case the visual features are on CPU, cast them to CUDA
176
+ pix_feat = pix_feat.to(masks.device)
177
+
178
+ x = self.pix_feat_proj(pix_feat)
179
+ x = x + masks
180
+ x = self.fuser(x)
181
+ x = self.out_proj(x)
182
+
183
+ pos = self.position_encoding(x).to(x.dtype)
184
+
185
+ return {"vision_features": x, "vision_pos_enc": [pos]}
MedSAM2/efficient_track_anything/modeling/position_encoding.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import math
8
+ from typing import Any, Optional, Tuple
9
+
10
+ import numpy as np
11
+
12
+ import torch
13
+ from torch import nn
14
+
15
+
16
+ class PositionEmbeddingSine(nn.Module):
17
+ """
18
+ This is a more standard version of the position embedding, very similar to the one
19
+ used by the Attention Is All You Need paper, generalized to work on images.
20
+ """
21
+
22
+ def __init__(
23
+ self,
24
+ num_pos_feats,
25
+ temperature: int = 10000,
26
+ normalize: bool = True,
27
+ scale: Optional[float] = None,
28
+ # Following settings only relevant
29
+ # for warmping up cache for compilation
30
+ warmup_cache: bool = True,
31
+ image_size: int = 1024,
32
+ strides: Tuple[int] = (4, 8, 16, 32),
33
+ ):
34
+ super().__init__()
35
+ assert num_pos_feats % 2 == 0, "Expecting even model width"
36
+ self.num_pos_feats = num_pos_feats // 2
37
+ self.temperature = temperature
38
+ self.normalize = normalize
39
+ if scale is not None and normalize is False:
40
+ raise ValueError("normalize should be True if scale is passed")
41
+ if scale is None:
42
+ scale = 2 * math.pi
43
+ self.scale = scale
44
+
45
+ self.cache = {}
46
+ if warmup_cache and torch.cuda.is_available():
47
+ # Warmup cache for cuda, to help with compilation
48
+ device = torch.device("cuda")
49
+ for stride in strides:
50
+ cache_key = (image_size // stride, image_size // stride)
51
+ self._pe(1, device, *cache_key)
52
+
53
+ def _encode_xy(self, x, y):
54
+ # The positions are expected to be normalized
55
+ assert len(x) == len(y) and x.ndim == y.ndim == 1
56
+ x_embed = x * self.scale
57
+ y_embed = y * self.scale
58
+
59
+ dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device)
60
+ dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)
61
+
62
+ pos_x = x_embed[:, None] / dim_t
63
+ pos_y = y_embed[:, None] / dim_t
64
+ pos_x = torch.stack(
65
+ (pos_x[:, 0::2].sin(), pos_x[:, 1::2].cos()), dim=2
66
+ ).flatten(1)
67
+ pos_y = torch.stack(
68
+ (pos_y[:, 0::2].sin(), pos_y[:, 1::2].cos()), dim=2
69
+ ).flatten(1)
70
+ return pos_x, pos_y
71
+
72
+ @torch.no_grad()
73
+ def encode_boxes(self, x, y, w, h):
74
+ pos_x, pos_y = self._encode_xy(x, y)
75
+ pos = torch.cat((pos_y, pos_x, h[:, None], w[:, None]), dim=1)
76
+ return pos
77
+
78
+ encode = encode_boxes # Backwards compatibility
79
+
80
+ @torch.no_grad()
81
+ def encode_points(self, x, y, labels):
82
+ (bx, nx), (by, ny), (bl, nl) = x.shape, y.shape, labels.shape
83
+ assert bx == by and nx == ny and bx == bl and nx == nl
84
+ pos_x, pos_y = self._encode_xy(x.flatten(), y.flatten())
85
+ pos_x, pos_y = pos_x.reshape(bx, nx, -1), pos_y.reshape(by, ny, -1)
86
+ pos = torch.cat((pos_y, pos_x, labels[:, :, None]), dim=2)
87
+ return pos
88
+
89
+ @torch.no_grad()
90
+ def _pe(self, B, device, *cache_key):
91
+ H, W = cache_key
92
+ if cache_key in self.cache:
93
+ return self.cache[cache_key].to(device)[None].repeat(B, 1, 1, 1)
94
+
95
+ y_embed = (
96
+ torch.arange(1, H + 1, dtype=torch.float32, device=device)
97
+ .view(1, -1, 1)
98
+ .repeat(B, 1, W)
99
+ )
100
+ x_embed = (
101
+ torch.arange(1, W + 1, dtype=torch.float32, device=device)
102
+ .view(1, 1, -1)
103
+ .repeat(B, H, 1)
104
+ )
105
+
106
+ if self.normalize:
107
+ eps = 1e-6
108
+ y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale
109
+ x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale
110
+
111
+ dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=device)
112
+ dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)
113
+
114
+ pos_x = x_embed[:, :, :, None] / dim_t
115
+ pos_y = y_embed[:, :, :, None] / dim_t
116
+ pos_x = torch.stack(
117
+ (pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4
118
+ ).flatten(3)
119
+ pos_y = torch.stack(
120
+ (pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4
121
+ ).flatten(3)
122
+ pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
123
+ self.cache[cache_key] = pos[0]
124
+ return pos
125
+
126
+ @torch.no_grad()
127
+ def forward(self, x: torch.Tensor):
128
+ B = x.shape[0]
129
+ cache_key = (x.shape[-2], x.shape[-1])
130
+ return self._pe(B, x.device, *cache_key)
131
+
132
+
133
+ class PositionEmbeddingRandom(nn.Module):
134
+ """
135
+ Positional encoding using random spatial frequencies.
136
+ """
137
+
138
+ def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None:
139
+ super().__init__()
140
+ if scale is None or scale <= 0.0:
141
+ scale = 1.0
142
+ self.register_buffer(
143
+ "positional_encoding_gaussian_matrix",
144
+ scale * torch.randn((2, num_pos_feats)),
145
+ )
146
+
147
+ def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor:
148
+ """Positionally encode points that are normalized to [0,1]."""
149
+ # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape
150
+ coords = 2 * coords - 1
151
+ coords = coords @ self.positional_encoding_gaussian_matrix
152
+ coords = 2 * np.pi * coords
153
+ # outputs d_1 x ... x d_n x C shape
154
+ return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1)
155
+
156
+ def forward(self, size: Tuple[int, int]) -> torch.Tensor:
157
+ """Generate positional encoding for a grid of the specified size."""
158
+ h, w = size
159
+ device: Any = self.positional_encoding_gaussian_matrix.device
160
+ grid = torch.ones((h, w), device=device, dtype=torch.float32)
161
+ y_embed = grid.cumsum(dim=0) - 0.5
162
+ x_embed = grid.cumsum(dim=1) - 0.5
163
+ y_embed = y_embed / h
164
+ x_embed = x_embed / w
165
+
166
+ pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1))
167
+ return pe.permute(2, 0, 1) # C x H x W
168
+
169
+ def forward_with_coords(
170
+ self, coords_input: torch.Tensor, image_size: Tuple[int, int]
171
+ ) -> torch.Tensor:
172
+ """Positionally encode points that are not normalized to [0,1]."""
173
+ coords = coords_input.clone()
174
+ coords[:, :, 0] = coords[:, :, 0] / image_size[1]
175
+ coords[:, :, 1] = coords[:, :, 1] / image_size[0]
176
+ return self._pe_encoding(coords.to(torch.float)) # B x N x C
177
+
178
+
179
+ # Rotary Positional Encoding, adapted from:
180
+ # 1. https://github.com/meta-llama/codellama/blob/main/llama/model.py
181
+ # 2. https://github.com/naver-ai/rope-vit
182
+ # 3. https://github.com/lucidrains/rotary-embedding-torch
183
+
184
+
185
+ def init_t_xy(end_x: int, end_y: int):
186
+ t = torch.arange(end_x * end_y, dtype=torch.float32)
187
+ t_x = (t % end_x).float()
188
+ t_y = torch.div(t, end_x, rounding_mode="floor").float()
189
+ return t_x, t_y
190
+
191
+
192
+ def compute_axial_cis(dim: int, end_x: int, end_y: int, theta: float = 10000.0):
193
+ freqs_x = 1.0 / (theta ** (torch.arange(0, dim, 4)[: (dim // 4)].float() / dim))
194
+ freqs_y = 1.0 / (theta ** (torch.arange(0, dim, 4)[: (dim // 4)].float() / dim))
195
+
196
+ t_x, t_y = init_t_xy(end_x, end_y)
197
+ freqs_x = torch.outer(t_x, freqs_x)
198
+ freqs_y = torch.outer(t_y, freqs_y)
199
+ freqs_cis_x = torch.polar(torch.ones_like(freqs_x), freqs_x)
200
+ freqs_cis_y = torch.polar(torch.ones_like(freqs_y), freqs_y)
201
+ return torch.cat([freqs_cis_x, freqs_cis_y], dim=-1)
202
+
203
+
204
+ def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor):
205
+ ndim = x.ndim
206
+ assert 0 <= 1 < ndim
207
+ assert freqs_cis.shape == (x.shape[-2], x.shape[-1])
208
+ shape = [d if i >= ndim - 2 else 1 for i, d in enumerate(x.shape)]
209
+ return freqs_cis.view(*shape)
210
+
211
+
212
+ def apply_rotary_enc(
213
+ xq: torch.Tensor,
214
+ xk: torch.Tensor,
215
+ freqs_cis: torch.Tensor,
216
+ repeat_freqs_k: bool = False,
217
+ ):
218
+ xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
219
+ xk_ = (
220
+ torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
221
+ if xk.shape[-2] != 0
222
+ else None
223
+ )
224
+ freqs_cis = reshape_for_broadcast(freqs_cis, xq_)
225
+ xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3)
226
+ if xk_ is None:
227
+ # no keys to rotate, due to dropout
228
+ return xq_out.type_as(xq).to(xq.device), xk
229
+ # repeat freqs along seq_len dim to match k seq_len
230
+ if repeat_freqs_k:
231
+ r = xk_.shape[-2] // xq_.shape[-2]
232
+ if freqs_cis.is_cuda:
233
+ freqs_cis = freqs_cis.repeat(*([1] * (freqs_cis.ndim - 2)), r, 1)
234
+ else:
235
+ # torch.repeat on complex numbers may not be supported on non-CUDA devices
236
+ # (freqs_cis has 4 dims and we repeat on dim 2) so we use expand + flatten
237
+ freqs_cis = freqs_cis.unsqueeze(2).expand(-1, -1, r, -1, -1).flatten(2, 3)
238
+ xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3)
239
+ return xq_out.type_as(xq).to(xq.device), xk_out.type_as(xk).to(xk.device)
MedSAM2/efficient_track_anything/modeling/sam/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
MedSAM2/efficient_track_anything/modeling/sam/mask_decoder.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from typing import List, Optional, Tuple, Type
8
+
9
+ import torch
10
+
11
+ from efficient_track_anything.modeling.efficienttam_utils import LayerNorm2d, MLP
12
+ from torch import nn
13
+
14
+
15
+ class MaskDecoder(nn.Module):
16
+ def __init__(
17
+ self,
18
+ *,
19
+ transformer_dim: int,
20
+ transformer: nn.Module,
21
+ num_multimask_outputs: int = 3,
22
+ activation: Type[nn.Module] = nn.GELU,
23
+ iou_head_depth: int = 3,
24
+ iou_head_hidden_dim: int = 256,
25
+ use_high_res_features: bool = False,
26
+ iou_prediction_use_sigmoid=False,
27
+ dynamic_multimask_via_stability=False,
28
+ dynamic_multimask_stability_delta=0.05,
29
+ dynamic_multimask_stability_thresh=0.98,
30
+ pred_obj_scores: bool = False,
31
+ pred_obj_scores_mlp: bool = False,
32
+ use_multimask_token_for_obj_ptr: bool = False,
33
+ ) -> None:
34
+ """
35
+ Predicts masks given an image and prompt embeddings, using a
36
+ transformer architecture.
37
+
38
+ Arguments:
39
+ transformer_dim (int): the channel dimension of the transformer
40
+ transformer (nn.Module): the transformer used to predict masks
41
+ num_multimask_outputs (int): the number of masks to predict
42
+ when disambiguating masks
43
+ activation (nn.Module): the type of activation to use when
44
+ upscaling masks
45
+ iou_head_depth (int): the depth of the MLP used to predict
46
+ mask quality
47
+ iou_head_hidden_dim (int): the hidden dimension of the MLP
48
+ used to predict mask quality
49
+ """
50
+ super().__init__()
51
+ self.transformer_dim = transformer_dim
52
+ self.transformer = transformer
53
+
54
+ self.num_multimask_outputs = num_multimask_outputs
55
+
56
+ self.iou_token = nn.Embedding(1, transformer_dim)
57
+ self.num_mask_tokens = num_multimask_outputs + 1
58
+ self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim)
59
+
60
+ self.pred_obj_scores = pred_obj_scores
61
+ if self.pred_obj_scores:
62
+ self.obj_score_token = nn.Embedding(1, transformer_dim)
63
+ self.use_multimask_token_for_obj_ptr = use_multimask_token_for_obj_ptr
64
+
65
+ self.output_upscaling = nn.Sequential(
66
+ nn.ConvTranspose2d(
67
+ transformer_dim, transformer_dim // 4, kernel_size=2, stride=2
68
+ ),
69
+ LayerNorm2d(transformer_dim // 4),
70
+ activation(),
71
+ nn.ConvTranspose2d(
72
+ transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2
73
+ ),
74
+ activation(),
75
+ )
76
+ self.use_high_res_features = use_high_res_features
77
+ if use_high_res_features:
78
+ self.conv_s0 = nn.Conv2d(
79
+ transformer_dim, transformer_dim // 8, kernel_size=1, stride=1
80
+ )
81
+ self.conv_s1 = nn.Conv2d(
82
+ transformer_dim, transformer_dim // 4, kernel_size=1, stride=1
83
+ )
84
+
85
+ self.output_hypernetworks_mlps = nn.ModuleList(
86
+ [
87
+ MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3)
88
+ for i in range(self.num_mask_tokens)
89
+ ]
90
+ )
91
+
92
+ self.iou_prediction_head = MLP(
93
+ transformer_dim,
94
+ iou_head_hidden_dim,
95
+ self.num_mask_tokens,
96
+ iou_head_depth,
97
+ sigmoid_output=iou_prediction_use_sigmoid,
98
+ )
99
+ if self.pred_obj_scores:
100
+ self.pred_obj_score_head = nn.Linear(transformer_dim, 1)
101
+ if pred_obj_scores_mlp:
102
+ self.pred_obj_score_head = MLP(transformer_dim, transformer_dim, 1, 3)
103
+
104
+ # When outputting a single mask, optionally we can dynamically fall back to the best
105
+ # multimask output token if the single mask output token gives low stability scores.
106
+ self.dynamic_multimask_via_stability = dynamic_multimask_via_stability
107
+ self.dynamic_multimask_stability_delta = dynamic_multimask_stability_delta
108
+ self.dynamic_multimask_stability_thresh = dynamic_multimask_stability_thresh
109
+
110
+ def forward(
111
+ self,
112
+ image_embeddings: torch.Tensor,
113
+ image_pe: torch.Tensor,
114
+ sparse_prompt_embeddings: torch.Tensor,
115
+ dense_prompt_embeddings: torch.Tensor,
116
+ multimask_output: bool,
117
+ repeat_image: bool,
118
+ high_res_features: Optional[List[torch.Tensor]] = None,
119
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
120
+ """
121
+ Predict masks given image and prompt embeddings.
122
+
123
+ Arguments:
124
+ image_embeddings (torch.Tensor): the embeddings from the image encoder
125
+ image_pe (torch.Tensor): positional encoding with the shape of image_embeddings
126
+ sparse_prompt_embeddings (torch.Tensor): the embeddings of the points and boxes
127
+ dense_prompt_embeddings (torch.Tensor): the embeddings of the mask inputs
128
+ multimask_output (bool): Whether to return multiple masks or a single
129
+ mask.
130
+
131
+ Returns:
132
+ torch.Tensor: batched predicted masks
133
+ torch.Tensor: batched predictions of mask quality
134
+ torch.Tensor: batched SAM token for mask output
135
+ """
136
+ masks, iou_pred, mask_tokens_out, object_score_logits = self.predict_masks(
137
+ image_embeddings=image_embeddings,
138
+ image_pe=image_pe,
139
+ sparse_prompt_embeddings=sparse_prompt_embeddings,
140
+ dense_prompt_embeddings=dense_prompt_embeddings,
141
+ repeat_image=repeat_image,
142
+ high_res_features=high_res_features,
143
+ )
144
+
145
+ # Select the correct mask or masks for output
146
+ if multimask_output:
147
+ masks = masks[:, 1:, :, :]
148
+ iou_pred = iou_pred[:, 1:]
149
+ elif self.dynamic_multimask_via_stability and not self.training:
150
+ masks, iou_pred = self._dynamic_multimask_via_stability(masks, iou_pred)
151
+ else:
152
+ masks = masks[:, 0:1, :, :]
153
+ iou_pred = iou_pred[:, 0:1]
154
+
155
+ if multimask_output and self.use_multimask_token_for_obj_ptr:
156
+ sam_tokens_out = mask_tokens_out[:, 1:] # [b, 3, c] shape
157
+ else:
158
+ # Take the mask output token. Here we *always* use the token for single mask output.
159
+ # At test time, even if we track after 1-click (and using multimask_output=True),
160
+ # we still take the single mask token here. The rationale is that we always track
161
+ # after multiple clicks during training, so the past tokens seen during training
162
+ # are always the single mask token (and we'll let it be the object-memory token).
163
+ sam_tokens_out = mask_tokens_out[:, 0:1] # [b, 1, c] shape
164
+
165
+ # Prepare output
166
+ return masks, iou_pred, sam_tokens_out, object_score_logits
167
+
168
+ def predict_masks(
169
+ self,
170
+ image_embeddings: torch.Tensor,
171
+ image_pe: torch.Tensor,
172
+ sparse_prompt_embeddings: torch.Tensor,
173
+ dense_prompt_embeddings: torch.Tensor,
174
+ repeat_image: bool,
175
+ high_res_features: Optional[List[torch.Tensor]] = None,
176
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
177
+ """Predicts masks. See 'forward' for more details."""
178
+ # Concatenate output tokens
179
+ s = 0
180
+ if self.pred_obj_scores:
181
+ output_tokens = torch.cat(
182
+ [
183
+ self.obj_score_token.weight,
184
+ self.iou_token.weight,
185
+ self.mask_tokens.weight,
186
+ ],
187
+ dim=0,
188
+ )
189
+ s = 1
190
+ else:
191
+ output_tokens = torch.cat(
192
+ [self.iou_token.weight, self.mask_tokens.weight], dim=0
193
+ )
194
+ output_tokens = output_tokens.unsqueeze(0).expand(
195
+ sparse_prompt_embeddings.size(0), -1, -1
196
+ )
197
+ tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1)
198
+
199
+ # Expand per-image data in batch direction to be per-mask
200
+ if repeat_image:
201
+ src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0)
202
+ else:
203
+ assert image_embeddings.shape[0] == tokens.shape[0]
204
+ src = image_embeddings
205
+ src = src + dense_prompt_embeddings
206
+ assert (
207
+ image_pe.size(0) == 1
208
+ ), "image_pe should have size 1 in batch dim (from `get_dense_pe()`)"
209
+ pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0)
210
+ b, c, h, w = src.shape
211
+
212
+ # Run the transformer
213
+ hs, src = self.transformer(src, pos_src, tokens)
214
+ iou_token_out = hs[:, s, :]
215
+ mask_tokens_out = hs[:, s + 1 : (s + 1 + self.num_mask_tokens), :]
216
+
217
+ # Upscale mask embeddings and predict masks using the mask tokens
218
+ src = src.transpose(1, 2).view(b, c, h, w)
219
+ if not self.use_high_res_features:
220
+ upscaled_embedding = self.output_upscaling(src)
221
+ else:
222
+ dc1, ln1, act1, dc2, act2 = self.output_upscaling
223
+ feat_s0, feat_s1 = high_res_features
224
+ upscaled_embedding = act1(ln1(dc1(src) + feat_s1))
225
+ upscaled_embedding = act2(dc2(upscaled_embedding) + feat_s0)
226
+
227
+ hyper_in_list: List[torch.Tensor] = []
228
+ for i in range(self.num_mask_tokens):
229
+ hyper_in_list.append(
230
+ self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :])
231
+ )
232
+ hyper_in = torch.stack(hyper_in_list, dim=1)
233
+ b, c, h, w = upscaled_embedding.shape
234
+ masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w)
235
+
236
+ # Generate mask quality predictions
237
+ iou_pred = self.iou_prediction_head(iou_token_out)
238
+ if self.pred_obj_scores:
239
+ assert s == 1
240
+ object_score_logits = self.pred_obj_score_head(hs[:, 0, :])
241
+ else:
242
+ # Obj scores logits - default to 10.0, i.e. assuming the object is present, sigmoid(10)=1
243
+ object_score_logits = 10.0 * iou_pred.new_ones(iou_pred.shape[0], 1)
244
+
245
+ return masks, iou_pred, mask_tokens_out, object_score_logits
246
+
247
+ def _get_stability_scores(self, mask_logits):
248
+ """
249
+ Compute stability scores of the mask logits based on the IoU between upper and
250
+ lower thresholds.
251
+ """
252
+ mask_logits = mask_logits.flatten(-2)
253
+ stability_delta = self.dynamic_multimask_stability_delta
254
+ area_i = torch.sum(mask_logits > stability_delta, dim=-1).float()
255
+ area_u = torch.sum(mask_logits > -stability_delta, dim=-1).float()
256
+ stability_scores = torch.where(area_u > 0, area_i / area_u, 1.0)
257
+ return stability_scores
258
+
259
+ def _dynamic_multimask_via_stability(self, all_mask_logits, all_iou_scores):
260
+ """
261
+ When outputting a single mask, if the stability score from the current single-mask
262
+ output (based on output token 0) falls below a threshold, we instead select from
263
+ multi-mask outputs (based on output token 1~3) the mask with the highest predicted
264
+ IoU score. This is intended to ensure a valid mask for both clicking and tracking.
265
+ """
266
+ # The best mask from multimask output tokens (1~3)
267
+ multimask_logits = all_mask_logits[:, 1:, :, :]
268
+ multimask_iou_scores = all_iou_scores[:, 1:]
269
+ best_scores_inds = torch.argmax(multimask_iou_scores, dim=-1)
270
+ batch_inds = torch.arange(
271
+ multimask_iou_scores.size(0), device=all_iou_scores.device
272
+ )
273
+ best_multimask_logits = multimask_logits[batch_inds, best_scores_inds]
274
+ best_multimask_logits = best_multimask_logits.unsqueeze(1)
275
+ best_multimask_iou_scores = multimask_iou_scores[batch_inds, best_scores_inds]
276
+ best_multimask_iou_scores = best_multimask_iou_scores.unsqueeze(1)
277
+
278
+ # The mask from singlemask output token 0 and its stability score
279
+ singlemask_logits = all_mask_logits[:, 0:1, :, :]
280
+ singlemask_iou_scores = all_iou_scores[:, 0:1]
281
+ stability_scores = self._get_stability_scores(singlemask_logits)
282
+ is_stable = stability_scores >= self.dynamic_multimask_stability_thresh
283
+
284
+ # Dynamically fall back to best multimask output upon low stability scores.
285
+ mask_logits_out = torch.where(
286
+ is_stable[..., None, None].expand_as(singlemask_logits),
287
+ singlemask_logits,
288
+ best_multimask_logits,
289
+ )
290
+ iou_scores_out = torch.where(
291
+ is_stable.expand_as(singlemask_iou_scores),
292
+ singlemask_iou_scores,
293
+ best_multimask_iou_scores,
294
+ )
295
+ return mask_logits_out, iou_scores_out
MedSAM2/efficient_track_anything/modeling/sam/prompt_encoder.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from typing import Optional, Tuple, Type
8
+
9
+ import torch
10
+
11
+ from efficient_track_anything.modeling.efficienttam_utils import LayerNorm2d
12
+
13
+ from efficient_track_anything.modeling.position_encoding import PositionEmbeddingRandom
14
+ from torch import nn
15
+
16
+
17
+ class PromptEncoder(nn.Module):
18
+ def __init__(
19
+ self,
20
+ embed_dim: int,
21
+ image_embedding_size: Tuple[int, int],
22
+ input_image_size: Tuple[int, int],
23
+ mask_in_chans: int,
24
+ activation: Type[nn.Module] = nn.GELU,
25
+ ) -> None:
26
+ """
27
+ Encodes prompts for input to SAM's mask decoder.
28
+
29
+ Arguments:
30
+ embed_dim (int): The prompts' embedding dimension
31
+ image_embedding_size (tuple(int, int)): The spatial size of the
32
+ image embedding, as (H, W).
33
+ input_image_size (int): The padded size of the image as input
34
+ to the image encoder, as (H, W).
35
+ mask_in_chans (int): The number of hidden channels used for
36
+ encoding input masks.
37
+ activation (nn.Module): The activation to use when encoding
38
+ input masks.
39
+ """
40
+ super().__init__()
41
+ self.embed_dim = embed_dim
42
+ self.input_image_size = input_image_size
43
+ self.image_embedding_size = image_embedding_size
44
+ self.pe_layer = PositionEmbeddingRandom(embed_dim // 2)
45
+
46
+ self.num_point_embeddings: int = 4 # pos/neg point + 2 box corners
47
+ point_embeddings = [
48
+ nn.Embedding(1, embed_dim) for i in range(self.num_point_embeddings)
49
+ ]
50
+ self.point_embeddings = nn.ModuleList(point_embeddings)
51
+ self.not_a_point_embed = nn.Embedding(1, embed_dim)
52
+
53
+ self.mask_input_size = (
54
+ 4 * image_embedding_size[0],
55
+ 4 * image_embedding_size[1],
56
+ )
57
+ self.mask_downscaling = nn.Sequential(
58
+ nn.Conv2d(1, mask_in_chans // 4, kernel_size=2, stride=2),
59
+ LayerNorm2d(mask_in_chans // 4),
60
+ activation(),
61
+ nn.Conv2d(mask_in_chans // 4, mask_in_chans, kernel_size=2, stride=2),
62
+ LayerNorm2d(mask_in_chans),
63
+ activation(),
64
+ nn.Conv2d(mask_in_chans, embed_dim, kernel_size=1),
65
+ )
66
+ self.no_mask_embed = nn.Embedding(1, embed_dim)
67
+
68
+ def get_dense_pe(self) -> torch.Tensor:
69
+ """
70
+ Returns the positional encoding used to encode point prompts,
71
+ applied to a dense set of points the shape of the image encoding.
72
+
73
+ Returns:
74
+ torch.Tensor: Positional encoding with shape
75
+ 1x(embed_dim)x(embedding_h)x(embedding_w)
76
+ """
77
+ return self.pe_layer(self.image_embedding_size).unsqueeze(0)
78
+
79
+ def _embed_points(
80
+ self,
81
+ points: torch.Tensor,
82
+ labels: torch.Tensor,
83
+ pad: bool,
84
+ ) -> torch.Tensor:
85
+ """Embeds point prompts."""
86
+ points = points + 0.5 # Shift to center of pixel
87
+ if pad:
88
+ padding_point = torch.zeros((points.shape[0], 1, 2), device=points.device)
89
+ padding_label = -torch.ones((labels.shape[0], 1), device=labels.device)
90
+ points = torch.cat([points, padding_point], dim=1)
91
+ labels = torch.cat([labels, padding_label], dim=1)
92
+ point_embedding = self.pe_layer.forward_with_coords(
93
+ points, self.input_image_size
94
+ )
95
+
96
+ point_embedding = torch.where(
97
+ (labels == -1).unsqueeze(-1),
98
+ torch.zeros_like(point_embedding) + self.not_a_point_embed.weight,
99
+ point_embedding,
100
+ )
101
+ point_embedding = torch.where(
102
+ (labels == 0).unsqueeze(-1),
103
+ point_embedding + self.point_embeddings[0].weight,
104
+ point_embedding,
105
+ )
106
+ point_embedding = torch.where(
107
+ (labels == 1).unsqueeze(-1),
108
+ point_embedding + self.point_embeddings[1].weight,
109
+ point_embedding,
110
+ )
111
+ point_embedding = torch.where(
112
+ (labels == 2).unsqueeze(-1),
113
+ point_embedding + self.point_embeddings[2].weight,
114
+ point_embedding,
115
+ )
116
+ point_embedding = torch.where(
117
+ (labels == 3).unsqueeze(-1),
118
+ point_embedding + self.point_embeddings[3].weight,
119
+ point_embedding,
120
+ )
121
+ return point_embedding
122
+
123
+ def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor:
124
+ """Embeds box prompts."""
125
+ boxes = boxes + 0.5 # Shift to center of pixel
126
+ coords = boxes.reshape(-1, 2, 2)
127
+ corner_embedding = self.pe_layer.forward_with_coords(
128
+ coords, self.input_image_size
129
+ )
130
+ corner_embedding[:, 0, :] += self.point_embeddings[2].weight
131
+ corner_embedding[:, 1, :] += self.point_embeddings[3].weight
132
+ return corner_embedding
133
+
134
+ def _embed_masks(self, masks: torch.Tensor) -> torch.Tensor:
135
+ """Embeds mask inputs."""
136
+ mask_embedding = self.mask_downscaling(masks)
137
+ return mask_embedding
138
+
139
+ def _get_batch_size(
140
+ self,
141
+ points: Optional[Tuple[torch.Tensor, torch.Tensor]],
142
+ boxes: Optional[torch.Tensor],
143
+ masks: Optional[torch.Tensor],
144
+ ) -> int:
145
+ """
146
+ Gets the batch size of the output given the batch size of the input prompts.
147
+ """
148
+ if points is not None:
149
+ return points[0].shape[0]
150
+ elif boxes is not None:
151
+ return boxes.shape[0]
152
+ elif masks is not None:
153
+ return masks.shape[0]
154
+ else:
155
+ return 1
156
+
157
+ def _get_device(self) -> torch.device:
158
+ return self.point_embeddings[0].weight.device
159
+
160
+ def forward(
161
+ self,
162
+ points: Optional[Tuple[torch.Tensor, torch.Tensor]],
163
+ boxes: Optional[torch.Tensor],
164
+ masks: Optional[torch.Tensor],
165
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
166
+ """
167
+ Embeds different types of prompts, returning both sparse and dense
168
+ embeddings.
169
+
170
+ Arguments:
171
+ points (tuple(torch.Tensor, torch.Tensor) or none): point coordinates
172
+ and labels to embed.
173
+ boxes (torch.Tensor or none): boxes to embed
174
+ masks (torch.Tensor or none): masks to embed
175
+
176
+ Returns:
177
+ torch.Tensor: sparse embeddings for the points and boxes, with shape
178
+ BxNx(embed_dim), where N is determined by the number of input points
179
+ and boxes.
180
+ torch.Tensor: dense embeddings for the masks, in the shape
181
+ Bx(embed_dim)x(embed_H)x(embed_W)
182
+ """
183
+ bs = self._get_batch_size(points, boxes, masks)
184
+ sparse_embeddings = torch.empty(
185
+ (bs, 0, self.embed_dim), device=self._get_device()
186
+ )
187
+ if points is not None:
188
+ coords, labels = points
189
+ point_embeddings = self._embed_points(coords, labels, pad=(boxes is None))
190
+ sparse_embeddings = torch.cat([sparse_embeddings, point_embeddings], dim=1)
191
+ if boxes is not None:
192
+ box_embeddings = self._embed_boxes(boxes)
193
+ sparse_embeddings = torch.cat([sparse_embeddings, box_embeddings], dim=1)
194
+
195
+ if masks is not None:
196
+ dense_embeddings = self._embed_masks(masks)
197
+ else:
198
+ dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1, 1).expand(
199
+ bs, -1, self.image_embedding_size[0], self.image_embedding_size[1]
200
+ )
201
+
202
+ return sparse_embeddings, dense_embeddings
MedSAM2/efficient_track_anything/modeling/sam/transformer.py ADDED
@@ -0,0 +1,532 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import math
8
+ from functools import partial
9
+ from typing import Tuple, Type
10
+
11
+ import torch
12
+ import torch.nn.functional as F
13
+ from efficient_track_anything.modeling.efficienttam_utils import MLP
14
+
15
+ from efficient_track_anything.modeling.position_encoding import (
16
+ apply_rotary_enc,
17
+ compute_axial_cis,
18
+ )
19
+ from torch import nn, Tensor
20
+
21
+
22
+ class TwoWayTransformer(nn.Module):
23
+ def __init__(
24
+ self,
25
+ depth: int,
26
+ embedding_dim: int,
27
+ num_heads: int,
28
+ mlp_dim: int,
29
+ activation: Type[nn.Module] = nn.ReLU,
30
+ attention_downsample_rate: int = 2,
31
+ ) -> None:
32
+ """
33
+ A transformer decoder that attends to an input image using
34
+ queries whose positional embedding is supplied.
35
+
36
+ Args:
37
+ depth (int): number of layers in the transformer
38
+ embedding_dim (int): the channel dimension for the input embeddings
39
+ num_heads (int): the number of heads for multihead attention. Must
40
+ divide embedding_dim
41
+ mlp_dim (int): the channel dimension internal to the MLP block
42
+ activation (nn.Module): the activation to use in the MLP block
43
+ """
44
+ super().__init__()
45
+ self.depth = depth
46
+ self.embedding_dim = embedding_dim
47
+ self.num_heads = num_heads
48
+ self.mlp_dim = mlp_dim
49
+ self.layers = nn.ModuleList()
50
+
51
+ for i in range(depth):
52
+ self.layers.append(
53
+ TwoWayAttentionBlock(
54
+ embedding_dim=embedding_dim,
55
+ num_heads=num_heads,
56
+ mlp_dim=mlp_dim,
57
+ activation=activation,
58
+ attention_downsample_rate=attention_downsample_rate,
59
+ skip_first_layer_pe=(i == 0),
60
+ )
61
+ )
62
+
63
+ self.final_attn_token_to_image = Attention(
64
+ embedding_dim, num_heads, downsample_rate=attention_downsample_rate
65
+ )
66
+ self.norm_final_attn = nn.LayerNorm(embedding_dim)
67
+
68
+ def forward(
69
+ self,
70
+ image_embedding: Tensor,
71
+ image_pe: Tensor,
72
+ point_embedding: Tensor,
73
+ ) -> Tuple[Tensor, Tensor]:
74
+ """
75
+ Args:
76
+ image_embedding (torch.Tensor): image to attend to. Should be shape
77
+ B x embedding_dim x h x w for any h and w.
78
+ image_pe (torch.Tensor): the positional encoding to add to the image. Must
79
+ have the same shape as image_embedding.
80
+ point_embedding (torch.Tensor): the embedding to add to the query points.
81
+ Must have shape B x N_points x embedding_dim for any N_points.
82
+
83
+ Returns:
84
+ torch.Tensor: the processed point_embedding
85
+ torch.Tensor: the processed image_embedding
86
+ """
87
+ # BxCxHxW -> BxHWxC == B x N_image_tokens x C
88
+ bs, c, h, w = image_embedding.shape
89
+ image_embedding = image_embedding.flatten(2).permute(0, 2, 1)
90
+ image_pe = image_pe.flatten(2).permute(0, 2, 1)
91
+
92
+ # Prepare queries
93
+ queries = point_embedding
94
+ keys = image_embedding
95
+
96
+ # Apply transformer blocks and final layernorm
97
+ for layer in self.layers:
98
+ queries, keys = layer(
99
+ queries=queries,
100
+ keys=keys,
101
+ query_pe=point_embedding,
102
+ key_pe=image_pe,
103
+ )
104
+
105
+ # Apply the final attention layer from the points to the image
106
+ q = queries + point_embedding
107
+ k = keys + image_pe
108
+ attn_out = self.final_attn_token_to_image(q=q, k=k, v=keys)
109
+ queries = queries + attn_out
110
+ queries = self.norm_final_attn(queries)
111
+
112
+ return queries, keys
113
+
114
+
115
+ class TwoWayAttentionBlock(nn.Module):
116
+ def __init__(
117
+ self,
118
+ embedding_dim: int,
119
+ num_heads: int,
120
+ mlp_dim: int = 2048,
121
+ activation: Type[nn.Module] = nn.ReLU,
122
+ attention_downsample_rate: int = 2,
123
+ skip_first_layer_pe: bool = False,
124
+ ) -> None:
125
+ """
126
+ A transformer block with four layers: (1) self-attention of sparse
127
+ inputs, (2) cross attention of sparse inputs to dense inputs, (3) mlp
128
+ block on sparse inputs, and (4) cross attention of dense inputs to sparse
129
+ inputs.
130
+
131
+ Arguments:
132
+ embedding_dim (int): the channel dimension of the embeddings
133
+ num_heads (int): the number of heads in the attention layers
134
+ mlp_dim (int): the hidden dimension of the mlp block
135
+ activation (nn.Module): the activation of the mlp block
136
+ skip_first_layer_pe (bool): skip the PE on the first layer
137
+ """
138
+ super().__init__()
139
+ self.self_attn = Attention(embedding_dim, num_heads)
140
+ self.norm1 = nn.LayerNorm(embedding_dim)
141
+
142
+ self.cross_attn_token_to_image = Attention(
143
+ embedding_dim, num_heads, downsample_rate=attention_downsample_rate
144
+ )
145
+ self.norm2 = nn.LayerNorm(embedding_dim)
146
+
147
+ self.mlp = MLP(
148
+ embedding_dim, mlp_dim, embedding_dim, num_layers=2, activation=activation
149
+ )
150
+ self.norm3 = nn.LayerNorm(embedding_dim)
151
+
152
+ self.norm4 = nn.LayerNorm(embedding_dim)
153
+ self.cross_attn_image_to_token = Attention(
154
+ embedding_dim, num_heads, downsample_rate=attention_downsample_rate
155
+ )
156
+
157
+ self.skip_first_layer_pe = skip_first_layer_pe
158
+
159
+ def forward(
160
+ self, queries: Tensor, keys: Tensor, query_pe: Tensor, key_pe: Tensor
161
+ ) -> Tuple[Tensor, Tensor]:
162
+ # Self attention block
163
+ if self.skip_first_layer_pe:
164
+ queries = self.self_attn(q=queries, k=queries, v=queries)
165
+ else:
166
+ q = queries + query_pe
167
+ attn_out = self.self_attn(q=q, k=q, v=queries)
168
+ queries = queries + attn_out
169
+ queries = self.norm1(queries)
170
+
171
+ # Cross attention block, tokens attending to image embedding
172
+ q = queries + query_pe
173
+ k = keys + key_pe
174
+ attn_out = self.cross_attn_token_to_image(q=q, k=k, v=keys)
175
+ queries = queries + attn_out
176
+ queries = self.norm2(queries)
177
+
178
+ # MLP block
179
+ mlp_out = self.mlp(queries)
180
+ queries = queries + mlp_out
181
+ queries = self.norm3(queries)
182
+
183
+ # Cross attention block, image embedding attending to tokens
184
+ q = queries + query_pe
185
+ k = keys + key_pe
186
+ attn_out = self.cross_attn_image_to_token(q=k, k=q, v=queries)
187
+ keys = keys + attn_out
188
+ keys = self.norm4(keys)
189
+
190
+ return queries, keys
191
+
192
+
193
+ class Attention(nn.Module):
194
+ """
195
+ An attention layer that allows for downscaling the size of the embedding
196
+ after projection to queries, keys, and values.
197
+ """
198
+
199
+ def __init__(
200
+ self,
201
+ embedding_dim: int,
202
+ num_heads: int,
203
+ downsample_rate: int = 1,
204
+ dropout: float = 0.0,
205
+ kv_in_dim: int = None,
206
+ ) -> None:
207
+ super().__init__()
208
+ self.embedding_dim = embedding_dim
209
+ self.kv_in_dim = kv_in_dim if kv_in_dim is not None else embedding_dim
210
+ self.internal_dim = embedding_dim // downsample_rate
211
+ self.num_heads = num_heads
212
+ assert (
213
+ self.internal_dim % num_heads == 0
214
+ ), "num_heads must divide embedding_dim."
215
+
216
+ self.q_proj = nn.Linear(embedding_dim, self.internal_dim)
217
+ self.k_proj = nn.Linear(self.kv_in_dim, self.internal_dim)
218
+ self.v_proj = nn.Linear(self.kv_in_dim, self.internal_dim)
219
+ self.out_proj = nn.Linear(self.internal_dim, embedding_dim)
220
+
221
+ self.dropout_p = dropout
222
+
223
+ def _separate_heads(self, x: Tensor, num_heads: int) -> Tensor:
224
+ b, n, c = x.shape
225
+ x = x.reshape(b, n, num_heads, c // num_heads)
226
+ return x.transpose(1, 2) # B x N_heads x N_tokens x C_per_head
227
+
228
+ def _recombine_heads(self, x: Tensor) -> Tensor:
229
+ b, n_heads, n_tokens, c_per_head = x.shape
230
+ x = x.transpose(1, 2)
231
+ return x.reshape(b, n_tokens, n_heads * c_per_head) # B x N_tokens x C
232
+
233
+ def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor:
234
+ # Input projections
235
+ q = self.q_proj(q)
236
+ k = self.k_proj(k)
237
+ v = self.v_proj(v)
238
+
239
+ # Separate into heads
240
+ q = self._separate_heads(q, self.num_heads)
241
+ k = self._separate_heads(k, self.num_heads)
242
+ v = self._separate_heads(v, self.num_heads)
243
+
244
+ dropout_p = self.dropout_p if self.training else 0.0
245
+ # Attention
246
+ out = F.scaled_dot_product_attention(q, k, v, dropout_p=dropout_p)
247
+
248
+ out = self._recombine_heads(out)
249
+ out = self.out_proj(out)
250
+
251
+ return out
252
+
253
+
254
+ class RoPEAttention(Attention):
255
+ """Attention with rotary position encoding."""
256
+
257
+ def __init__(
258
+ self,
259
+ *args,
260
+ rope_theta=10000.0,
261
+ # whether to repeat q rope to match k length
262
+ # this is needed for cross-attention to memories
263
+ rope_k_repeat=False,
264
+ feat_sizes=(64, 64), # [w, h] for stride 16 feats at 1024 resolution
265
+ **kwargs,
266
+ ):
267
+ super().__init__(*args, **kwargs)
268
+
269
+ self.compute_cis = partial(
270
+ compute_axial_cis, dim=self.internal_dim // self.num_heads, theta=rope_theta
271
+ )
272
+ freqs_cis = self.compute_cis(end_x=feat_sizes[0], end_y=feat_sizes[1])
273
+ self.freqs_cis = (
274
+ freqs_cis.to("cuda") if torch.cuda.is_available() else freqs_cis
275
+ )
276
+ self.rope_k_repeat = rope_k_repeat
277
+
278
+ def forward(
279
+ self, q: Tensor, k: Tensor, v: Tensor, num_k_exclude_rope: int = 0
280
+ ) -> Tensor:
281
+ # Input projections
282
+ q = self.q_proj(q)
283
+ k = self.k_proj(k)
284
+ v = self.v_proj(v)
285
+
286
+ # Separate into heads
287
+ q = self._separate_heads(q, self.num_heads)
288
+ k = self._separate_heads(k, self.num_heads)
289
+ v = self._separate_heads(v, self.num_heads)
290
+
291
+ # Apply rotary position encoding
292
+ w = h = math.sqrt(q.shape[-2])
293
+ self.freqs_cis = self.freqs_cis.to(q.device)
294
+ if self.freqs_cis.shape[0] != q.shape[-2]:
295
+ self.freqs_cis = self.compute_cis(end_x=w, end_y=h).to(q.device)
296
+ if q.shape[-2] != k.shape[-2]:
297
+ assert self.rope_k_repeat
298
+
299
+ num_k_rope = k.size(-2) - num_k_exclude_rope
300
+ q, k[:, :, :num_k_rope] = apply_rotary_enc(
301
+ q,
302
+ k[:, :, :num_k_rope],
303
+ freqs_cis=self.freqs_cis,
304
+ repeat_freqs_k=self.rope_k_repeat,
305
+ )
306
+
307
+ dropout_p = self.dropout_p if self.training else 0.0
308
+ # Attention
309
+ out = F.scaled_dot_product_attention(q, k, v, dropout_p=dropout_p)
310
+
311
+ out = self._recombine_heads(out)
312
+ out = self.out_proj(out)
313
+
314
+ return out
315
+
316
+
317
+ class EfficientRoPEAttention1(Attention):
318
+ """Attention with rotary position encoding."""
319
+
320
+ def __init__(
321
+ self,
322
+ *args,
323
+ rope_theta=10000.0,
324
+ # whether to repeat q rope to match k length
325
+ # this is needed for cross-attention to memories
326
+ rope_k_repeat=False,
327
+ feat_sizes=(32, 32), # [w, h] for stride 16 feats at 512 resolution
328
+ **kwargs,
329
+ ):
330
+ super().__init__(*args, **kwargs)
331
+
332
+ self.compute_cis = partial(
333
+ compute_axial_cis, dim=self.internal_dim // self.num_heads, theta=rope_theta
334
+ )
335
+ freqs_cis = self.compute_cis(end_x=feat_sizes[0], end_y=feat_sizes[1])
336
+ self.freqs_cis = freqs_cis
337
+ self.rope_k_repeat = rope_k_repeat
338
+
339
+ def forward(
340
+ self, q: Tensor, k: Tensor, v: Tensor, num_k_exclude_rope: int = 0
341
+ ) -> Tensor:
342
+ # Input projections
343
+ q = self.q_proj(q)
344
+ k = self.k_proj(k)
345
+ v = self.v_proj(v)
346
+
347
+ # Separate into heads
348
+ q = self._separate_heads(q, self.num_heads)
349
+ k = self._separate_heads(k, self.num_heads)
350
+ v = self._separate_heads(v, self.num_heads)
351
+
352
+ # Apply rotary position encoding
353
+ w = h = math.sqrt(q.shape[-2])
354
+ self.freqs_cis = self.freqs_cis.to(q.device)
355
+ if self.freqs_cis.shape[0] != q.shape[-2]:
356
+ self.freqs_cis = self.compute_cis(end_x=w, end_y=h).to(q.device)
357
+ if q.shape[-2] != k.shape[-2]:
358
+ assert self.rope_k_repeat
359
+
360
+ num_k_rope = k.size(-2) - num_k_exclude_rope
361
+ q, k[:, :, :num_k_rope] = apply_rotary_enc(
362
+ q,
363
+ k[:, :, :num_k_rope],
364
+ freqs_cis=self.freqs_cis,
365
+ repeat_freqs_k=self.rope_k_repeat,
366
+ )
367
+
368
+ dropout_p = self.dropout_p if self.training else 0.0
369
+
370
+ if self.rope_k_repeat:
371
+ fs, bs, ns, ds = k.shape
372
+ nq = q.shape[-2]
373
+ if num_k_rope <= nq:
374
+ out = F.scaled_dot_product_attention(q, k, v, dropout_p=dropout_p)
375
+ else:
376
+ s_kernel_size = 2
377
+ intw, inth = int(w), int(h)
378
+ k_landmarks = k[:, :, :num_k_rope, :].reshape(fs, -1, nq, ds)
379
+ k_landmarks = k_landmarks.transpose(-2, -1).reshape(fs, -1, intw, inth)
380
+ k_landmarks = F.avg_pool2d(
381
+ k_landmarks, s_kernel_size, stride=s_kernel_size
382
+ )
383
+ k_landmarks = (
384
+ k_landmarks.reshape(
385
+ fs, -1, ds, nq // (s_kernel_size * s_kernel_size)
386
+ )
387
+ .transpose(-2, -1)
388
+ .reshape(fs, bs, -1, ds)
389
+ )
390
+
391
+ scale_factor = 1 / math.sqrt(ds)
392
+ attn_weight = q @ k_landmarks.transpose(
393
+ -2, -1
394
+ ) * scale_factor + 2 * math.log(s_kernel_size)
395
+ attn_weight = torch.cat(
396
+ [
397
+ attn_weight,
398
+ q @ k[:, :, num_k_rope:, :].transpose(-2, -1) * scale_factor,
399
+ ],
400
+ dim=-1,
401
+ )
402
+ attn_weight = torch.softmax(attn_weight, dim=-1)
403
+ attn_weight = torch.dropout(attn_weight, dropout_p, train=self.training)
404
+
405
+ v_landmarks = v[:, :, :num_k_rope, :].reshape(fs, -1, nq, ds)
406
+ v_landmarks = v_landmarks.transpose(-2, -1).reshape(fs, -1, intw, inth)
407
+ v_landmarks = F.avg_pool2d(
408
+ v_landmarks, s_kernel_size, stride=s_kernel_size
409
+ )
410
+ v_landmarks = v_landmarks.reshape(
411
+ fs, -1, ds, nq // (s_kernel_size * s_kernel_size)
412
+ ).transpose(-2, -1)
413
+ v_landmarks = torch.cat(
414
+ [
415
+ v_landmarks.reshape(fs, bs, -1, ds),
416
+ v[:, :, num_k_rope:, :],
417
+ ],
418
+ dim=-2,
419
+ )
420
+ out = attn_weight @ v_landmarks
421
+ else:
422
+ out = F.scaled_dot_product_attention(q, k, v, dropout_p=dropout_p)
423
+
424
+ out = self._recombine_heads(out)
425
+ out = self.out_proj(out)
426
+
427
+ return out
428
+
429
+
430
+ class EfficientRoPEAttention2(Attention):
431
+ """Attention with rotary position encoding."""
432
+
433
+ def __init__(
434
+ self,
435
+ *args,
436
+ rope_theta=10000.0,
437
+ # whether to repeat q rope to match k length
438
+ # this is needed for cross-attention to memories
439
+ rope_k_repeat=False,
440
+ feat_sizes=(32, 32), # [w, h] for stride 16 feats at 512 resolution
441
+ **kwargs,
442
+ ):
443
+ super().__init__(*args, **kwargs)
444
+
445
+ self.compute_cis = partial(
446
+ compute_axial_cis, dim=self.internal_dim // self.num_heads, theta=rope_theta
447
+ )
448
+ freqs_cis = self.compute_cis(end_x=feat_sizes[0], end_y=feat_sizes[1])
449
+ self.freqs_cis = freqs_cis
450
+ self.rope_k_repeat = rope_k_repeat
451
+
452
+ def forward(
453
+ self, q: Tensor, k: Tensor, v: Tensor, num_k_exclude_rope: int = 0
454
+ ) -> Tensor:
455
+ # Input projections
456
+ q = self.q_proj(q)
457
+ k = self.k_proj(k)
458
+ v = self.v_proj(v)
459
+
460
+ # Separate into heads
461
+ q = self._separate_heads(q, self.num_heads)
462
+ k = self._separate_heads(k, self.num_heads)
463
+ v = self._separate_heads(v, self.num_heads)
464
+
465
+ # Apply rotary position encoding
466
+ w = h = math.sqrt(q.shape[-2])
467
+ self.freqs_cis = self.freqs_cis.to(q.device)
468
+ if self.freqs_cis.shape[0] != q.shape[-2]:
469
+ self.freqs_cis = self.compute_cis(end_x=w, end_y=h).to(q.device)
470
+ if q.shape[-2] != k.shape[-2]:
471
+ assert self.rope_k_repeat
472
+
473
+ num_k_rope = k.size(-2) - num_k_exclude_rope
474
+ q, k[:, :, :num_k_rope] = apply_rotary_enc(
475
+ q,
476
+ k[:, :, :num_k_rope],
477
+ freqs_cis=self.freqs_cis,
478
+ repeat_freqs_k=self.rope_k_repeat,
479
+ )
480
+
481
+ dropout_p = self.dropout_p if self.training else 0.0
482
+
483
+ if self.rope_k_repeat:
484
+ fs, bs, ns, ds = k.shape
485
+ nq = q.shape[-2]
486
+ if num_k_rope <= nq:
487
+ out = F.scaled_dot_product_attention(q, k, v, dropout_p=dropout_p)
488
+ else:
489
+ s_kernel_size = 2
490
+ intw, inth = int(w), int(h)
491
+ k_landmarks = k[:, :, :num_k_rope, :].reshape(fs, -1, nq, ds)
492
+ k_landmarks = k_landmarks.transpose(-2, -1).reshape(fs, -1, intw, inth)
493
+ k_landmarks = F.avg_pool2d(
494
+ k_landmarks, s_kernel_size, stride=s_kernel_size
495
+ )
496
+ k_landmarks = k_landmarks.reshape(
497
+ fs, -1, ds, nq // (s_kernel_size * s_kernel_size)
498
+ ).transpose(-2, -1)
499
+ k_landmarks = torch.cat(
500
+ [
501
+ k_landmarks.reshape(fs, bs, -1, ds)
502
+ + 2 * math.log(s_kernel_size),
503
+ k[:, :, num_k_rope:, :],
504
+ ],
505
+ dim=-2,
506
+ )
507
+
508
+ v_landmarks = v[:, :, :num_k_rope, :].reshape(fs, -1, nq, ds)
509
+ v_landmarks = v_landmarks.transpose(-2, -1).reshape(fs, -1, intw, inth)
510
+ v_landmarks = F.avg_pool2d(
511
+ v_landmarks, s_kernel_size, stride=s_kernel_size
512
+ )
513
+ v_landmarks = v_landmarks.reshape(
514
+ fs, -1, ds, nq // (s_kernel_size * s_kernel_size)
515
+ ).transpose(-2, -1)
516
+ v_landmarks = torch.cat(
517
+ [
518
+ v_landmarks.reshape(fs, bs, -1, ds),
519
+ v[:, :, num_k_rope:, :],
520
+ ],
521
+ dim=-2,
522
+ )
523
+ out = F.scaled_dot_product_attention(
524
+ q, k_landmarks, v_landmarks, dropout_p=dropout_p
525
+ )
526
+ else:
527
+ out = F.scaled_dot_product_attention(q, k, v, dropout_p=dropout_p)
528
+
529
+ out = self._recombine_heads(out)
530
+ out = self.out_proj(out)
531
+
532
+ return out
MedSAM2/efficient_track_anything/utils/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
MedSAM2/efficient_track_anything/utils/amg.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import math
8
+ from copy import deepcopy
9
+ from itertools import product
10
+ from typing import Any, Dict, Generator, ItemsView, List, Tuple
11
+
12
+ import numpy as np
13
+ import torch
14
+
15
+ # Very lightly adapted from https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/utils/amg.py
16
+
17
+
18
+ class MaskData:
19
+ """
20
+ A structure for storing masks and their related data in batched format.
21
+ Implements basic filtering and concatenation.
22
+ """
23
+
24
+ def __init__(self, **kwargs) -> None:
25
+ for v in kwargs.values():
26
+ assert isinstance(
27
+ v, (list, np.ndarray, torch.Tensor)
28
+ ), "MaskData only supports list, numpy arrays, and torch tensors."
29
+ self._stats = dict(**kwargs)
30
+
31
+ def __setitem__(self, key: str, item: Any) -> None:
32
+ assert isinstance(
33
+ item, (list, np.ndarray, torch.Tensor)
34
+ ), "MaskData only supports list, numpy arrays, and torch tensors."
35
+ self._stats[key] = item
36
+
37
+ def __delitem__(self, key: str) -> None:
38
+ del self._stats[key]
39
+
40
+ def __getitem__(self, key: str) -> Any:
41
+ return self._stats[key]
42
+
43
+ def items(self) -> ItemsView[str, Any]:
44
+ return self._stats.items()
45
+
46
+ def filter(self, keep: torch.Tensor) -> None:
47
+ for k, v in self._stats.items():
48
+ if v is None:
49
+ self._stats[k] = None
50
+ elif isinstance(v, torch.Tensor):
51
+ self._stats[k] = v[torch.as_tensor(keep, device=v.device)]
52
+ elif isinstance(v, np.ndarray):
53
+ self._stats[k] = v[keep.detach().cpu().numpy()]
54
+ elif isinstance(v, list) and keep.dtype == torch.bool:
55
+ self._stats[k] = [a for i, a in enumerate(v) if keep[i]]
56
+ elif isinstance(v, list):
57
+ self._stats[k] = [v[i] for i in keep]
58
+ else:
59
+ raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.")
60
+
61
+ def cat(self, new_stats: "MaskData") -> None:
62
+ for k, v in new_stats.items():
63
+ if k not in self._stats or self._stats[k] is None:
64
+ self._stats[k] = deepcopy(v)
65
+ elif isinstance(v, torch.Tensor):
66
+ self._stats[k] = torch.cat([self._stats[k], v], dim=0)
67
+ elif isinstance(v, np.ndarray):
68
+ self._stats[k] = np.concatenate([self._stats[k], v], axis=0)
69
+ elif isinstance(v, list):
70
+ self._stats[k] = self._stats[k] + deepcopy(v)
71
+ else:
72
+ raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.")
73
+
74
+ def to_numpy(self) -> None:
75
+ for k, v in self._stats.items():
76
+ if isinstance(v, torch.Tensor):
77
+ self._stats[k] = v.float().detach().cpu().numpy()
78
+
79
+
80
+ def is_box_near_crop_edge(
81
+ boxes: torch.Tensor, crop_box: List[int], orig_box: List[int], atol: float = 20.0
82
+ ) -> torch.Tensor:
83
+ """Filter masks at the edge of a crop, but not at the edge of the original image."""
84
+ crop_box_torch = torch.as_tensor(crop_box, dtype=torch.float, device=boxes.device)
85
+ orig_box_torch = torch.as_tensor(orig_box, dtype=torch.float, device=boxes.device)
86
+ boxes = uncrop_boxes_xyxy(boxes, crop_box).float()
87
+ near_crop_edge = torch.isclose(boxes, crop_box_torch[None, :], atol=atol, rtol=0)
88
+ near_image_edge = torch.isclose(boxes, orig_box_torch[None, :], atol=atol, rtol=0)
89
+ near_crop_edge = torch.logical_and(near_crop_edge, ~near_image_edge)
90
+ return torch.any(near_crop_edge, dim=1)
91
+
92
+
93
+ def box_xyxy_to_xywh(box_xyxy: torch.Tensor) -> torch.Tensor:
94
+ box_xywh = deepcopy(box_xyxy)
95
+ box_xywh[2] = box_xywh[2] - box_xywh[0]
96
+ box_xywh[3] = box_xywh[3] - box_xywh[1]
97
+ return box_xywh
98
+
99
+
100
+ def batch_iterator(batch_size: int, *args) -> Generator[List[Any], None, None]:
101
+ assert len(args) > 0 and all(
102
+ len(a) == len(args[0]) for a in args
103
+ ), "Batched iteration must have inputs of all the same size."
104
+ n_batches = len(args[0]) // batch_size + int(len(args[0]) % batch_size != 0)
105
+ for b in range(n_batches):
106
+ yield [arg[b * batch_size : (b + 1) * batch_size] for arg in args]
107
+
108
+
109
+ def mask_to_rle_pytorch(tensor: torch.Tensor) -> List[Dict[str, Any]]:
110
+ """
111
+ Encodes masks to an uncompressed RLE, in the format expected by
112
+ pycoco tools.
113
+ """
114
+ # Put in fortran order and flatten h,w
115
+ b, h, w = tensor.shape
116
+ tensor = tensor.permute(0, 2, 1).flatten(1)
117
+
118
+ # Compute change indices
119
+ diff = tensor[:, 1:] ^ tensor[:, :-1]
120
+ change_indices = diff.nonzero()
121
+
122
+ # Encode run length
123
+ out = []
124
+ for i in range(b):
125
+ cur_idxs = change_indices[change_indices[:, 0] == i, 1]
126
+ cur_idxs = torch.cat(
127
+ [
128
+ torch.tensor([0], dtype=cur_idxs.dtype, device=cur_idxs.device),
129
+ cur_idxs + 1,
130
+ torch.tensor([h * w], dtype=cur_idxs.dtype, device=cur_idxs.device),
131
+ ]
132
+ )
133
+ btw_idxs = cur_idxs[1:] - cur_idxs[:-1]
134
+ counts = [] if tensor[i, 0] == 0 else [0]
135
+ counts.extend(btw_idxs.detach().cpu().tolist())
136
+ out.append({"size": [h, w], "counts": counts})
137
+ return out
138
+
139
+
140
+ def rle_to_mask(rle: Dict[str, Any]) -> np.ndarray:
141
+ """Compute a binary mask from an uncompressed RLE."""
142
+ h, w = rle["size"]
143
+ mask = np.empty(h * w, dtype=bool)
144
+ idx = 0
145
+ parity = False
146
+ for count in rle["counts"]:
147
+ mask[idx : idx + count] = parity
148
+ idx += count
149
+ parity ^= True
150
+ mask = mask.reshape(w, h)
151
+ return mask.transpose() # Put in C order
152
+
153
+
154
+ def area_from_rle(rle: Dict[str, Any]) -> int:
155
+ return sum(rle["counts"][1::2])
156
+
157
+
158
+ def calculate_stability_score(
159
+ masks: torch.Tensor, mask_threshold: float, threshold_offset: float
160
+ ) -> torch.Tensor:
161
+ """
162
+ Computes the stability score for a batch of masks. The stability
163
+ score is the IoU between the binary masks obtained by thresholding
164
+ the predicted mask logits at high and low values.
165
+ """
166
+ # One mask is always contained inside the other.
167
+ # Save memory by preventing unnecessary cast to torch.int64
168
+ intersections = (
169
+ (masks > (mask_threshold + threshold_offset))
170
+ .sum(-1, dtype=torch.int16)
171
+ .sum(-1, dtype=torch.int32)
172
+ )
173
+ unions = (
174
+ (masks > (mask_threshold - threshold_offset))
175
+ .sum(-1, dtype=torch.int16)
176
+ .sum(-1, dtype=torch.int32)
177
+ )
178
+ return intersections / unions
179
+
180
+
181
+ def build_point_grid(n_per_side: int) -> np.ndarray:
182
+ """Generates a 2D grid of points evenly spaced in [0,1]x[0,1]."""
183
+ offset = 1 / (2 * n_per_side)
184
+ points_one_side = np.linspace(offset, 1 - offset, n_per_side)
185
+ points_x = np.tile(points_one_side[None, :], (n_per_side, 1))
186
+ points_y = np.tile(points_one_side[:, None], (1, n_per_side))
187
+ points = np.stack([points_x, points_y], axis=-1).reshape(-1, 2)
188
+ return points
189
+
190
+
191
+ def build_all_layer_point_grids(
192
+ n_per_side: int, n_layers: int, scale_per_layer: int
193
+ ) -> List[np.ndarray]:
194
+ """Generates point grids for all crop layers."""
195
+ points_by_layer = []
196
+ for i in range(n_layers + 1):
197
+ n_points = int(n_per_side / (scale_per_layer**i))
198
+ points_by_layer.append(build_point_grid(n_points))
199
+ return points_by_layer
200
+
201
+
202
+ def generate_crop_boxes(
203
+ im_size: Tuple[int, ...], n_layers: int, overlap_ratio: float
204
+ ) -> Tuple[List[List[int]], List[int]]:
205
+ """
206
+ Generates a list of crop boxes of different sizes. Each layer
207
+ has (2**i)**2 boxes for the ith layer.
208
+ """
209
+ crop_boxes, layer_idxs = [], []
210
+ im_h, im_w = im_size
211
+ short_side = min(im_h, im_w)
212
+
213
+ # Original image
214
+ crop_boxes.append([0, 0, im_w, im_h])
215
+ layer_idxs.append(0)
216
+
217
+ def crop_len(orig_len, n_crops, overlap):
218
+ return int(math.ceil((overlap * (n_crops - 1) + orig_len) / n_crops))
219
+
220
+ for i_layer in range(n_layers):
221
+ n_crops_per_side = 2 ** (i_layer + 1)
222
+ overlap = int(overlap_ratio * short_side * (2 / n_crops_per_side))
223
+
224
+ crop_w = crop_len(im_w, n_crops_per_side, overlap)
225
+ crop_h = crop_len(im_h, n_crops_per_side, overlap)
226
+
227
+ crop_box_x0 = [int((crop_w - overlap) * i) for i in range(n_crops_per_side)]
228
+ crop_box_y0 = [int((crop_h - overlap) * i) for i in range(n_crops_per_side)]
229
+
230
+ # Crops in XYWH format
231
+ for x0, y0 in product(crop_box_x0, crop_box_y0):
232
+ box = [x0, y0, min(x0 + crop_w, im_w), min(y0 + crop_h, im_h)]
233
+ crop_boxes.append(box)
234
+ layer_idxs.append(i_layer + 1)
235
+
236
+ return crop_boxes, layer_idxs
237
+
238
+
239
+ def uncrop_boxes_xyxy(boxes: torch.Tensor, crop_box: List[int]) -> torch.Tensor:
240
+ x0, y0, _, _ = crop_box
241
+ offset = torch.tensor([[x0, y0, x0, y0]], device=boxes.device)
242
+ # Check if boxes has a channel dimension
243
+ if len(boxes.shape) == 3:
244
+ offset = offset.unsqueeze(1)
245
+ return boxes + offset
246
+
247
+
248
+ def uncrop_points(points: torch.Tensor, crop_box: List[int]) -> torch.Tensor:
249
+ x0, y0, _, _ = crop_box
250
+ offset = torch.tensor([[x0, y0]], device=points.device)
251
+ # Check if points has a channel dimension
252
+ if len(points.shape) == 3:
253
+ offset = offset.unsqueeze(1)
254
+ return points + offset
255
+
256
+
257
+ def uncrop_masks(
258
+ masks: torch.Tensor, crop_box: List[int], orig_h: int, orig_w: int
259
+ ) -> torch.Tensor:
260
+ x0, y0, x1, y1 = crop_box
261
+ if x0 == 0 and y0 == 0 and x1 == orig_w and y1 == orig_h:
262
+ return masks
263
+ # Coordinate transform masks
264
+ pad_x, pad_y = orig_w - (x1 - x0), orig_h - (y1 - y0)
265
+ pad = (x0, pad_x - x0, y0, pad_y - y0)
266
+ return torch.nn.functional.pad(masks, pad, value=0)
267
+
268
+
269
+ def remove_small_regions(
270
+ mask: np.ndarray, area_thresh: float, mode: str
271
+ ) -> Tuple[np.ndarray, bool]:
272
+ """
273
+ Removes small disconnected regions and holes in a mask. Returns the
274
+ mask and an indicator of if the mask has been modified.
275
+ """
276
+ import cv2 # type: ignore
277
+
278
+ assert mode in ["holes", "islands"]
279
+ correct_holes = mode == "holes"
280
+ working_mask = (correct_holes ^ mask).astype(np.uint8)
281
+ n_labels, regions, stats, _ = cv2.connectedComponentsWithStats(working_mask, 8)
282
+ sizes = stats[:, -1][1:] # Row 0 is background label
283
+ small_regions = [i + 1 for i, s in enumerate(sizes) if s < area_thresh]
284
+ if len(small_regions) == 0:
285
+ return mask, False
286
+ fill_labels = [0] + small_regions
287
+ if not correct_holes:
288
+ fill_labels = [i for i in range(n_labels) if i not in fill_labels]
289
+ # If every region is below threshold, keep largest
290
+ if len(fill_labels) == 0:
291
+ fill_labels = [int(np.argmax(sizes)) + 1]
292
+ mask = np.isin(regions, fill_labels)
293
+ return mask, True
294
+
295
+
296
+ def coco_encode_rle(uncompressed_rle: Dict[str, Any]) -> Dict[str, Any]:
297
+ from pycocotools import mask as mask_utils # type: ignore
298
+
299
+ h, w = uncompressed_rle["size"]
300
+ rle = mask_utils.frPyObjects(uncompressed_rle, h, w)
301
+ rle["counts"] = rle["counts"].decode("utf-8") # Necessary to serialize with json
302
+ return rle
303
+
304
+
305
+ def batched_mask_to_box(masks: torch.Tensor) -> torch.Tensor:
306
+ """
307
+ Calculates boxes in XYXY format around masks. Return [0,0,0,0] for
308
+ an empty mask. For input shape C1xC2x...xHxW, the output shape is C1xC2x...x4.
309
+ """
310
+ # torch.max below raises an error on empty inputs, just skip in this case
311
+ if torch.numel(masks) == 0:
312
+ return torch.zeros(*masks.shape[:-2], 4, device=masks.device)
313
+
314
+ # Normalize shape to CxHxW
315
+ shape = masks.shape
316
+ h, w = shape[-2:]
317
+ if len(shape) > 2:
318
+ masks = masks.flatten(0, -3)
319
+ else:
320
+ masks = masks.unsqueeze(0)
321
+
322
+ # Get top and bottom edges
323
+ in_height, _ = torch.max(masks, dim=-1)
324
+ in_height_coords = in_height * torch.arange(h, device=in_height.device)[None, :]
325
+ bottom_edges, _ = torch.max(in_height_coords, dim=-1)
326
+ in_height_coords = in_height_coords + h * (~in_height)
327
+ top_edges, _ = torch.min(in_height_coords, dim=-1)
328
+
329
+ # Get left and right edges
330
+ in_width, _ = torch.max(masks, dim=-2)
331
+ in_width_coords = in_width * torch.arange(w, device=in_width.device)[None, :]
332
+ right_edges, _ = torch.max(in_width_coords, dim=-1)
333
+ in_width_coords = in_width_coords + w * (~in_width)
334
+ left_edges, _ = torch.min(in_width_coords, dim=-1)
335
+
336
+ # If the mask is empty the right edge will be to the left of the left edge.
337
+ # Replace these boxes with [0, 0, 0, 0]
338
+ empty_filter = (right_edges < left_edges) | (bottom_edges < top_edges)
339
+ out = torch.stack([left_edges, top_edges, right_edges, bottom_edges], dim=-1)
340
+ out = out * (~empty_filter).unsqueeze(-1)
341
+
342
+ # Return to original shape
343
+ if len(shape) > 2:
344
+ out = out.reshape(*shape[:-2], 4)
345
+ else:
346
+ out = out[0]
347
+
348
+ return out
MedSAM2/efficient_track_anything/utils/misc.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import os
8
+ import warnings
9
+ from threading import Thread
10
+
11
+ import numpy as np
12
+ import torch
13
+ from PIL import Image
14
+ from tqdm import tqdm
15
+
16
+
17
+ def get_sdpa_settings():
18
+ if torch.cuda.is_available():
19
+ old_gpu = torch.cuda.get_device_properties(0).major < 7
20
+ # only use Flash Attention on Ampere (8.0) or newer GPUs
21
+ use_flash_attn = torch.cuda.get_device_properties(0).major >= 8
22
+ if not use_flash_attn:
23
+ warnings.warn(
24
+ "Flash Attention is disabled as it requires a GPU with Ampere (8.0) CUDA capability.",
25
+ category=UserWarning,
26
+ stacklevel=2,
27
+ )
28
+ # keep math kernel for PyTorch versions before 2.2 (Flash Attention v2 is only
29
+ # available on PyTorch 2.2+, while Flash Attention v1 cannot handle all cases)
30
+ pytorch_version = tuple(int(v) for v in torch.__version__.split(".")[:2])
31
+ if pytorch_version < (2, 2):
32
+ warnings.warn(
33
+ f"You are using PyTorch {torch.__version__} without Flash Attention v2 support. "
34
+ "Consider upgrading to PyTorch 2.2+ for Flash Attention v2 (which could be faster).",
35
+ category=UserWarning,
36
+ stacklevel=2,
37
+ )
38
+ math_kernel_on = pytorch_version < (2, 2) or not use_flash_attn
39
+ else:
40
+ old_gpu = True
41
+ use_flash_attn = False
42
+ math_kernel_on = True
43
+
44
+ return old_gpu, use_flash_attn, math_kernel_on
45
+
46
+
47
+ def get_connected_components(mask):
48
+ """
49
+ Get the connected components (8-connectivity) of binary masks of shape (N, 1, H, W).
50
+
51
+ Inputs:
52
+ - mask: A binary mask tensor of shape (N, 1, H, W), where 1 is foreground and 0 is
53
+ background.
54
+
55
+ Outputs:
56
+ - labels: A tensor of shape (N, 1, H, W) containing the connected component labels
57
+ for foreground pixels and 0 for background pixels.
58
+ - counts: A tensor of shape (N, 1, H, W) containing the area of the connected
59
+ components for foreground pixels and 0 for background pixels.
60
+ """
61
+ from efficient_track_anything import _C
62
+
63
+ return _C.get_connected_componnets(mask.to(torch.uint8).contiguous())
64
+
65
+
66
+ def mask_to_box(masks: torch.Tensor):
67
+ """
68
+ compute bounding box given an input mask
69
+
70
+ Inputs:
71
+ - masks: [B, 1, H, W] masks, dtype=torch.Tensor
72
+
73
+ Returns:
74
+ - box_coords: [B, 1, 4], contains (x, y) coordinates of top left and bottom right box corners, dtype=torch.Tensor
75
+ """
76
+ B, _, h, w = masks.shape
77
+ device = masks.device
78
+ xs = torch.arange(w, device=device, dtype=torch.int32)
79
+ ys = torch.arange(h, device=device, dtype=torch.int32)
80
+ grid_xs, grid_ys = torch.meshgrid(xs, ys, indexing="xy")
81
+ grid_xs = grid_xs[None, None, ...].expand(B, 1, h, w)
82
+ grid_ys = grid_ys[None, None, ...].expand(B, 1, h, w)
83
+ min_xs, _ = torch.min(torch.where(masks, grid_xs, w).flatten(-2), dim=-1)
84
+ max_xs, _ = torch.max(torch.where(masks, grid_xs, -1).flatten(-2), dim=-1)
85
+ min_ys, _ = torch.min(torch.where(masks, grid_ys, h).flatten(-2), dim=-1)
86
+ max_ys, _ = torch.max(torch.where(masks, grid_ys, -1).flatten(-2), dim=-1)
87
+ bbox_coords = torch.stack((min_xs, min_ys, max_xs, max_ys), dim=-1)
88
+
89
+ return bbox_coords
90
+
91
+
92
+ def _load_img_as_tensor(img_path, image_size):
93
+ img_pil = Image.open(img_path)
94
+ img_np = np.array(img_pil.convert("RGB").resize((image_size, image_size)))
95
+ if img_np.dtype == np.uint8: # np.uint8 is expected for JPEG images
96
+ img_np = img_np / 255.0
97
+ else:
98
+ raise RuntimeError(f"Unknown image dtype: {img_np.dtype} on {img_path}")
99
+ img = torch.from_numpy(img_np).permute(2, 0, 1)
100
+ video_width, video_height = img_pil.size # the original video size
101
+ return img, video_height, video_width
102
+
103
+
104
+ class AsyncVideoFrameLoader:
105
+ """
106
+ A list of video frames to be load asynchronously without blocking session start.
107
+ """
108
+
109
+ def __init__(
110
+ self,
111
+ img_paths,
112
+ image_size,
113
+ offload_video_to_cpu,
114
+ img_mean,
115
+ img_std,
116
+ compute_device,
117
+ ):
118
+ self.img_paths = img_paths
119
+ self.image_size = image_size
120
+ self.offload_video_to_cpu = offload_video_to_cpu
121
+ self.img_mean = img_mean
122
+ self.img_std = img_std
123
+ # items in `self.images` will be loaded asynchronously
124
+ self.images = [None] * len(img_paths)
125
+ # catch and raise any exceptions in the async loading thread
126
+ self.exception = None
127
+ # video_height and video_width be filled when loading the first image
128
+ self.video_height = None
129
+ self.video_width = None
130
+ self.compute_device = compute_device
131
+
132
+ # load the first frame to fill video_height and video_width and also
133
+ # to cache it (since it's most likely where the user will click)
134
+ self.__getitem__(0)
135
+
136
+ # load the rest of frames asynchronously without blocking the session start
137
+ def _load_frames():
138
+ try:
139
+ for n in tqdm(range(len(self.images)), desc="frame loading (JPEG)"):
140
+ self.__getitem__(n)
141
+ except Exception as e:
142
+ self.exception = e
143
+
144
+ self.thread = Thread(target=_load_frames, daemon=True)
145
+ self.thread.start()
146
+
147
+ def __getitem__(self, index):
148
+ if self.exception is not None:
149
+ raise RuntimeError("Failure in frame loading thread") from self.exception
150
+
151
+ img = self.images[index]
152
+ if img is not None:
153
+ return img
154
+
155
+ img, video_height, video_width = _load_img_as_tensor(
156
+ self.img_paths[index], self.image_size
157
+ )
158
+ self.video_height = video_height
159
+ self.video_width = video_width
160
+ # normalize by mean and std
161
+ img -= self.img_mean
162
+ img /= self.img_std
163
+ if not self.offload_video_to_cpu:
164
+ img = img.to(self.compute_device, non_blocking=True)
165
+ self.images[index] = img
166
+ return img
167
+
168
+ def __len__(self):
169
+ return len(self.images)
170
+
171
+
172
+ def load_video_frames(
173
+ video_path,
174
+ image_size,
175
+ offload_video_to_cpu,
176
+ img_mean=(0.485, 0.456, 0.406),
177
+ img_std=(0.229, 0.224, 0.225),
178
+ async_loading_frames=False,
179
+ compute_device=torch.device("cuda"),
180
+ ):
181
+ """
182
+ Load the video frames from video_path. The frames are resized to image_size as in
183
+ the model and are loaded to GPU if offload_video_to_cpu=False. This is used by the demo.
184
+ """
185
+ is_bytes = isinstance(video_path, bytes)
186
+ is_str = isinstance(video_path, str)
187
+ is_mp4_path = is_str and os.path.splitext(video_path)[-1] in [".mp4", ".MP4"]
188
+ if is_bytes or is_mp4_path:
189
+ return load_video_frames_from_video_file(
190
+ video_path=video_path,
191
+ image_size=image_size,
192
+ offload_video_to_cpu=offload_video_to_cpu,
193
+ img_mean=img_mean,
194
+ img_std=img_std,
195
+ compute_device=compute_device,
196
+ )
197
+ elif is_str and os.path.isdir(video_path):
198
+ return load_video_frames_from_jpg_images(
199
+ video_path=video_path,
200
+ image_size=image_size,
201
+ offload_video_to_cpu=offload_video_to_cpu,
202
+ img_mean=img_mean,
203
+ img_std=img_std,
204
+ async_loading_frames=async_loading_frames,
205
+ compute_device=compute_device,
206
+ )
207
+ else:
208
+ raise NotImplementedError(
209
+ "Only MP4 video and JPEG folder are supported at this moment"
210
+ )
211
+
212
+
213
+ def load_video_frames_from_jpg_images(
214
+ video_path,
215
+ image_size,
216
+ offload_video_to_cpu,
217
+ img_mean=(0.485, 0.456, 0.406),
218
+ img_std=(0.229, 0.224, 0.225),
219
+ async_loading_frames=False,
220
+ compute_device=torch.device("cuda"),
221
+ ):
222
+ """
223
+ Load the video frames from a directory of JPEG files ("<frame_index>.jpg" format).
224
+
225
+ The frames are resized to image_size x image_size and are loaded to GPU if
226
+ `offload_video_to_cpu` is `False` and to CPU if `offload_video_to_cpu` is `True`.
227
+
228
+ You can load a frame asynchronously by setting `async_loading_frames` to `True`.
229
+ """
230
+ if isinstance(video_path, str) and os.path.isdir(video_path):
231
+ jpg_folder = video_path
232
+ else:
233
+ raise NotImplementedError(
234
+ "Only JPEG frames are supported at this moment. For video files, you may use "
235
+ "ffmpeg (https://ffmpeg.org/) to extract frames into a folder of JPEG files, such as \n"
236
+ "```\n"
237
+ "ffmpeg -i <your_video>.mp4 -q:v 2 -start_number 0 <output_dir>/'%05d.jpg'\n"
238
+ "```\n"
239
+ "where `-q:v` generates high-quality JPEG frames and `-start_number 0` asks "
240
+ "ffmpeg to start the JPEG file from 00000.jpg."
241
+ )
242
+
243
+ frame_names = [
244
+ p
245
+ for p in os.listdir(jpg_folder)
246
+ if os.path.splitext(p)[-1] in [".jpg", ".jpeg", ".JPG", ".JPEG"]
247
+ ]
248
+ frame_names.sort(key=lambda p: int(os.path.splitext(p)[0]))
249
+ num_frames = len(frame_names)
250
+ if num_frames == 0:
251
+ raise RuntimeError(f"no images found in {jpg_folder}")
252
+ img_paths = [os.path.join(jpg_folder, frame_name) for frame_name in frame_names]
253
+ img_mean = torch.tensor(img_mean, dtype=torch.float32)[:, None, None]
254
+ img_std = torch.tensor(img_std, dtype=torch.float32)[:, None, None]
255
+
256
+ if async_loading_frames:
257
+ lazy_images = AsyncVideoFrameLoader(
258
+ img_paths,
259
+ image_size,
260
+ offload_video_to_cpu,
261
+ img_mean,
262
+ img_std,
263
+ compute_device,
264
+ )
265
+ return lazy_images, lazy_images.video_height, lazy_images.video_width
266
+
267
+ images = torch.zeros(num_frames, 3, image_size, image_size, dtype=torch.float32)
268
+ for n, img_path in enumerate(tqdm(img_paths, desc="frame loading (JPEG)")):
269
+ images[n], video_height, video_width = _load_img_as_tensor(img_path, image_size)
270
+ if not offload_video_to_cpu:
271
+ images = images.to(compute_device)
272
+ img_mean = img_mean.to(compute_device)
273
+ img_std = img_std.to(compute_device)
274
+ # normalize by mean and std
275
+ images -= img_mean
276
+ images /= img_std
277
+ return images, video_height, video_width
278
+
279
+
280
+ def load_video_frames_from_video_file(
281
+ video_path,
282
+ image_size,
283
+ offload_video_to_cpu,
284
+ img_mean=(0.485, 0.456, 0.406),
285
+ img_std=(0.229, 0.224, 0.225),
286
+ compute_device=torch.device("cuda"),
287
+ ):
288
+ """Load the video frames from a video file."""
289
+ import decord
290
+
291
+ img_mean = torch.tensor(img_mean, dtype=torch.float32)[:, None, None]
292
+ img_std = torch.tensor(img_std, dtype=torch.float32)[:, None, None]
293
+ # Get the original video height and width
294
+ decord.bridge.set_bridge("torch")
295
+ video_height, video_width, _ = decord.VideoReader(video_path).next().shape
296
+ # Iterate over all frames in the video
297
+ images = []
298
+ for frame in decord.VideoReader(video_path, width=image_size, height=image_size):
299
+ images.append(frame.permute(2, 0, 1))
300
+
301
+ images = torch.stack(images, dim=0).float() / 255.0
302
+ if not offload_video_to_cpu:
303
+ images = images.to(compute_device)
304
+ img_mean = img_mean.to(compute_device)
305
+ img_std = img_std.to(compute_device)
306
+ # normalize by mean and std
307
+ images -= img_mean
308
+ images /= img_std
309
+ return images, video_height, video_width
310
+
311
+
312
+ def fill_holes_in_mask_scores(mask, max_area):
313
+ """
314
+ A post processor to fill small holes in mask scores with area under `max_area`.
315
+ """
316
+ # Holes are those connected components in background with area <= self.max_area
317
+ # (background regions are those with mask scores <= 0)
318
+ assert max_area > 0, "max_area must be positive"
319
+
320
+ input_mask = mask
321
+ try:
322
+ labels, areas = get_connected_components(mask <= 0)
323
+ is_hole = (labels > 0) & (areas <= max_area)
324
+ # We fill holes with a small positive mask score (0.1) to change them to foreground.
325
+ mask = torch.where(is_hole, 0.1, mask)
326
+ except Exception as e:
327
+ # Following SAM 2, skip the post-processing step on removing small holes if the CUDA kernel fails
328
+ warnings.warn(
329
+ f"{e}\n\nSkipping the post-processing step due to the error above. You can "
330
+ "still use Efficient Track Anything and it's OK to ignore the error above.",
331
+ category=UserWarning,
332
+ stacklevel=2,
333
+ )
334
+ mask = input_mask
335
+
336
+ return mask
337
+
338
+
339
+ def concat_points(old_point_inputs, new_points, new_labels):
340
+ """Add new points and labels to previous point inputs (add at the end)."""
341
+ if old_point_inputs is None:
342
+ points, labels = new_points, new_labels
343
+ else:
344
+ points = torch.cat([old_point_inputs["point_coords"], new_points], dim=1)
345
+ labels = torch.cat([old_point_inputs["point_labels"], new_labels], dim=1)
346
+
347
+ return {"point_coords": points, "point_labels": labels}
MedSAM2/efficient_track_anything/utils/transforms.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import warnings
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+ from torchvision.transforms import Normalize, Resize, ToTensor
13
+
14
+
15
+ class EfficientTAMTransforms(nn.Module):
16
+ def __init__(
17
+ self, resolution, mask_threshold, max_hole_area=0.0, max_sprinkle_area=0.0
18
+ ):
19
+ """
20
+ Transforms for Efficient Track Anything.
21
+ """
22
+ super().__init__()
23
+ self.resolution = resolution
24
+ self.mask_threshold = mask_threshold
25
+ self.max_hole_area = max_hole_area
26
+ self.max_sprinkle_area = max_sprinkle_area
27
+ self.mean = [0.485, 0.456, 0.406]
28
+ self.std = [0.229, 0.224, 0.225]
29
+ self.to_tensor = ToTensor()
30
+ self.transforms = torch.jit.script(
31
+ nn.Sequential(
32
+ Resize((self.resolution, self.resolution)),
33
+ Normalize(self.mean, self.std),
34
+ )
35
+ )
36
+
37
+ def __call__(self, x):
38
+ x = self.to_tensor(x)
39
+ return self.transforms(x)
40
+
41
+ def forward_batch(self, img_list):
42
+ img_batch = [self.transforms(self.to_tensor(img)) for img in img_list]
43
+ img_batch = torch.stack(img_batch, dim=0)
44
+ return img_batch
45
+
46
+ def transform_coords(
47
+ self, coords: torch.Tensor, normalize=False, orig_hw=None
48
+ ) -> torch.Tensor:
49
+ """
50
+ Expects a torch tensor with length 2 in the last dimension. The coordinates can be in absolute image or normalized coordinates,
51
+ If the coords are in absolute image coordinates, normalize should be set to True and original image size is required.
52
+
53
+ Returns
54
+ Un-normalized coordinates in the range of [0, 1] which is expected by the Efficient Track Anything model.
55
+ """
56
+ if normalize:
57
+ assert orig_hw is not None
58
+ h, w = orig_hw
59
+ coords = coords.clone()
60
+ coords[..., 0] = coords[..., 0] / w
61
+ coords[..., 1] = coords[..., 1] / h
62
+
63
+ coords = coords * self.resolution # unnormalize coords
64
+ return coords
65
+
66
+ def transform_boxes(
67
+ self, boxes: torch.Tensor, normalize=False, orig_hw=None
68
+ ) -> torch.Tensor:
69
+ """
70
+ Expects a tensor of shape Bx4. The coordinates can be in absolute image or normalized coordinates,
71
+ if the coords are in absolute image coordinates, normalize should be set to True and original image size is required.
72
+ """
73
+ boxes = self.transform_coords(boxes.reshape(-1, 2, 2), normalize, orig_hw)
74
+ return boxes
75
+
76
+ def postprocess_masks(self, masks: torch.Tensor, orig_hw) -> torch.Tensor:
77
+ """
78
+ Perform PostProcessing on output masks.
79
+ """
80
+ from efficient_track_anything.utils.misc import get_connected_components
81
+
82
+ masks = masks.float()
83
+ input_masks = masks
84
+ mask_flat = masks.flatten(0, 1).unsqueeze(1) # flatten as 1-channel image
85
+ try:
86
+ if self.max_hole_area > 0:
87
+ # Holes are those connected components in background with area <= self.fill_hole_area
88
+ # (background regions are those with mask scores <= self.mask_threshold)
89
+ labels, areas = get_connected_components(
90
+ mask_flat <= self.mask_threshold
91
+ )
92
+ is_hole = (labels > 0) & (areas <= self.max_hole_area)
93
+ is_hole = is_hole.reshape_as(masks)
94
+ # We fill holes with a small positive mask score (10.0) to change them to foreground.
95
+ masks = torch.where(is_hole, self.mask_threshold + 10.0, masks)
96
+
97
+ if self.max_sprinkle_area > 0:
98
+ labels, areas = get_connected_components(
99
+ mask_flat > self.mask_threshold
100
+ )
101
+ is_hole = (labels > 0) & (areas <= self.max_sprinkle_area)
102
+ is_hole = is_hole.reshape_as(masks)
103
+ # We fill holes with negative mask score (-10.0) to change them to background.
104
+ masks = torch.where(is_hole, self.mask_threshold - 10.0, masks)
105
+ except Exception as e:
106
+ # Following SAM 2, skip the post-processing step if the CUDA kernel fails
107
+ warnings.warn(
108
+ f"{e}\n\nSkipping the post-processing step due to the error above. You can "
109
+ "still use Efficient Track Anything and it's OK to ignore the error above.",
110
+ category=UserWarning,
111
+ stacklevel=2,
112
+ )
113
+ masks = input_masks
114
+
115
+ masks = F.interpolate(masks, orig_hw, mode="bilinear", align_corners=False)
116
+ return masks
MedSAM2/sam2/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from hydra import initialize_config_module
8
+ from hydra.core.global_hydra import GlobalHydra
9
+
10
+ if not GlobalHydra.instance().is_initialized():
11
+ initialize_config_module("sam2", version_base="1.2")
MedSAM2/sam2/build_sam.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import logging
8
+
9
+ import torch
10
+ from hydra import compose
11
+ from hydra.utils import instantiate
12
+ from omegaconf import OmegaConf
13
+
14
+ HF_MODEL_ID_TO_FILENAMES = {
15
+ "facebook/sam2-hiera-tiny": (
16
+ "configs/sam2/sam2_hiera_t.yaml",
17
+ "sam2_hiera_tiny.pt",
18
+ ),
19
+ "facebook/sam2-hiera-small": (
20
+ "configs/sam2/sam2_hiera_s.yaml",
21
+ "sam2_hiera_small.pt",
22
+ ),
23
+ "facebook/sam2-hiera-base-plus": (
24
+ "configs/sam2/sam2_hiera_b+.yaml",
25
+ "sam2_hiera_base_plus.pt",
26
+ ),
27
+ "facebook/sam2-hiera-large": (
28
+ "configs/sam2/sam2_hiera_l.yaml",
29
+ "sam2_hiera_large.pt",
30
+ ),
31
+ "facebook/sam2.1-hiera-tiny": (
32
+ "configs/sam2.1/sam2.1_hiera_t.yaml",
33
+ "sam2.1_hiera_tiny.pt",
34
+ ),
35
+ "facebook/sam2.1-hiera-small": (
36
+ "configs/sam2.1/sam2.1_hiera_s.yaml",
37
+ "sam2.1_hiera_small.pt",
38
+ ),
39
+ "facebook/sam2.1-hiera-base-plus": (
40
+ "configs/sam2.1/sam2.1_hiera_b+.yaml",
41
+ "sam2.1_hiera_base_plus.pt",
42
+ ),
43
+ "facebook/sam2.1-hiera-large": (
44
+ "configs/sam2.1/sam2.1_hiera_l.yaml",
45
+ "sam2.1_hiera_large.pt",
46
+ ),
47
+ }
48
+
49
+
50
+ def get_best_available_device():
51
+ """
52
+ Get the best available device in the order: CUDA, MPS, CPU
53
+ Returns: device string for torch.device
54
+ """
55
+ if torch.cuda.is_available():
56
+ return "cuda"
57
+ elif hasattr(torch.backends, 'mps') and torch.backends.mps.is_available():
58
+ return "mps"
59
+ else:
60
+ return "cpu"
61
+
62
+
63
+ def build_sam2(
64
+ config_file,
65
+ ckpt_path=None,
66
+ device=None,
67
+ mode="eval",
68
+ hydra_overrides_extra=[],
69
+ apply_postprocessing=True,
70
+ **kwargs,
71
+ ):
72
+ # Use the provided device or get the best available one
73
+ device = device or get_best_available_device()
74
+ logging.info(f"Using device: {device}")
75
+
76
+ if apply_postprocessing:
77
+ hydra_overrides_extra = hydra_overrides_extra.copy()
78
+ hydra_overrides_extra += [
79
+ # dynamically fall back to multi-mask if the single mask is not stable
80
+ "++model.sam_mask_decoder_extra_args.dynamic_multimask_via_stability=true",
81
+ "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_delta=0.05",
82
+ "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_thresh=0.98",
83
+ ]
84
+ # Read config and init model
85
+ cfg = compose(config_name=config_file, overrides=hydra_overrides_extra)
86
+ OmegaConf.resolve(cfg)
87
+ model = instantiate(cfg.model, _recursive_=True)
88
+ _load_checkpoint(model, ckpt_path)
89
+ model = model.to(device)
90
+ if mode == "eval":
91
+ model.eval()
92
+ return model
93
+
94
+
95
+ def build_sam2_video_predictor(
96
+ config_file,
97
+ ckpt_path=None,
98
+ device=None,
99
+ mode="eval",
100
+ hydra_overrides_extra=[],
101
+ apply_postprocessing=True,
102
+ **kwargs,
103
+ ):
104
+ # Use the provided device or get the best available one
105
+ device = device or get_best_available_device()
106
+ logging.info(f"Using device: {device}")
107
+
108
+ hydra_overrides = [
109
+ "++model._target_=sam2.sam2_video_predictor.SAM2VideoPredictor",
110
+ ]
111
+ if apply_postprocessing:
112
+ hydra_overrides_extra = hydra_overrides_extra.copy()
113
+ hydra_overrides_extra += [
114
+ # dynamically fall back to multi-mask if the single mask is not stable
115
+ "++model.sam_mask_decoder_extra_args.dynamic_multimask_via_stability=true",
116
+ "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_delta=0.05",
117
+ "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_thresh=0.98",
118
+ # the sigmoid mask logits on interacted frames with clicks in the memory encoder so that the encoded masks are exactly as what users see from clicking
119
+ "++model.binarize_mask_from_pts_for_mem_enc=true",
120
+ # fill small holes in the low-res masks up to `fill_hole_area` (before resizing them to the original video resolution)
121
+ "++model.fill_hole_area=8",
122
+ ]
123
+ hydra_overrides.extend(hydra_overrides_extra)
124
+
125
+ # Read config and init model
126
+ cfg = compose(config_name=config_file, overrides=hydra_overrides)
127
+ OmegaConf.resolve(cfg)
128
+ model = instantiate(cfg.model, _recursive_=True)
129
+ _load_checkpoint(model, ckpt_path)
130
+ model = model.to(device)
131
+ if mode == "eval":
132
+ model.eval()
133
+ return model
134
+
135
+ def build_sam2_video_predictor_npz(
136
+ config_file,
137
+ ckpt_path=None,
138
+ device=None,
139
+ mode="eval",
140
+ hydra_overrides_extra=[],
141
+ apply_postprocessing=True,
142
+ **kwargs,
143
+ ):
144
+ # Use the provided device or get the best available one
145
+ device = device or get_best_available_device()
146
+ logging.info(f"Using device: {device}")
147
+
148
+ hydra_overrides = [
149
+ "++model._target_=sam2.sam2_video_predictor_npz.SAM2VideoPredictorNPZ",
150
+ ]
151
+ if apply_postprocessing:
152
+ hydra_overrides_extra = hydra_overrides_extra.copy()
153
+ hydra_overrides_extra += [
154
+ # dynamically fall back to multi-mask if the single mask is not stable
155
+ "++model.sam_mask_decoder_extra_args.dynamic_multimask_via_stability=true",
156
+ "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_delta=0.05",
157
+ "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_thresh=0.98",
158
+ # the sigmoid mask logits on interacted frames with clicks in the memory encoder so that the encoded masks are exactly as what users see from clicking
159
+ "++model.binarize_mask_from_pts_for_mem_enc=true",
160
+ # fill small holes in the low-res masks up to `fill_hole_area` (before resizing them to the original video resolution)
161
+ "++model.fill_hole_area=8",
162
+ ]
163
+ hydra_overrides.extend(hydra_overrides_extra)
164
+
165
+ # Read config and init model
166
+ cfg = compose(config_name=config_file, overrides=hydra_overrides)
167
+ OmegaConf.resolve(cfg)
168
+ model = instantiate(cfg.model, _recursive_=True)
169
+ _load_checkpoint(model, ckpt_path)
170
+ model = model.to(device)
171
+ if mode == "eval":
172
+ model.eval()
173
+ return model
174
+
175
+
176
+
177
+ def _hf_download(model_id):
178
+ from huggingface_hub import hf_hub_download
179
+
180
+ config_name, checkpoint_name = HF_MODEL_ID_TO_FILENAMES[model_id]
181
+ ckpt_path = hf_hub_download(repo_id=model_id, filename=checkpoint_name)
182
+ return config_name, ckpt_path
183
+
184
+
185
+ def build_sam2_hf(model_id, **kwargs):
186
+ config_name, ckpt_path = _hf_download(model_id)
187
+ return build_sam2(config_file=config_name, ckpt_path=ckpt_path, **kwargs)
188
+
189
+
190
+ def build_sam2_video_predictor_hf(model_id, **kwargs):
191
+ config_name, ckpt_path = _hf_download(model_id)
192
+ return build_sam2_video_predictor(
193
+ config_file=config_name, ckpt_path=ckpt_path, **kwargs
194
+ )
195
+
196
+
197
+ def _load_checkpoint(model, ckpt_path):
198
+ if ckpt_path is not None:
199
+ sd = torch.load(ckpt_path, map_location="cpu", weights_only=True)["model"]
200
+ missing_keys, unexpected_keys = model.load_state_dict(sd)
201
+ if missing_keys:
202
+ logging.error(missing_keys)
203
+ raise RuntimeError()
204
+ if unexpected_keys:
205
+ logging.error(unexpected_keys)
206
+ raise RuntimeError()
207
+ logging.info("Loaded checkpoint sucessfully")
MedSAM2/sam2/configs/efficientmedsam_s_512_FLARE_RECIST.yaml ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+
3
+ scratch:
4
+ resolution: 512
5
+ train_batch_size: 4
6
+ num_train_workers: 15
7
+ num_frames: 8
8
+ max_num_objects: 5
9
+ base_lr: 5.0e-6
10
+ vision_lr: 3.0e-06
11
+ phases_per_epoch: 1
12
+ num_epochs: 100
13
+
14
+ dataset:
15
+ # PATHS to Dataset
16
+ folder: data # PATH to Med NPZ folder
17
+ multiplier: 2
18
+
19
+ # Video transforms
20
+ vos:
21
+ train_transforms:
22
+ - _target_: training.dataset.transforms.ComposeAPI
23
+ transforms:
24
+ - _target_: training.dataset.transforms.RandomHorizontalFlip
25
+ consistent_transform: True
26
+ - _target_: training.dataset.transforms.RandomVerticalFlip
27
+ consistent_transform: True
28
+ - _target_: training.dataset.transforms.RandomAffine
29
+ degrees: 25
30
+ shear: 20
31
+ scale: [0.7, 1.4]
32
+ image_interpolation: bilinear
33
+ consistent_transform: True
34
+ - _target_: training.dataset.transforms.RandomAffine
35
+ degrees: 5
36
+ shear: 5
37
+ scale: [0.95, 1.05]
38
+ translate: [0.05, 0.05]
39
+ image_interpolation: bilinear
40
+ consistent_transform: False
41
+ p: 0.1
42
+ - _target_: training.dataset.transforms.RandomResizeAPI
43
+ sizes: ${scratch.resolution}
44
+ square: true
45
+ consistent_transform: True
46
+ - _target_: training.dataset.transforms.RandomGaussianNoise
47
+ consistent_transform: True
48
+ p: 0.1
49
+ - _target_: training.dataset.transforms.RandomGaussianBlur
50
+ consistent_transform: True
51
+ kernel_size: 5
52
+ sigma: [0.5, 1.0]
53
+ p: 0.2
54
+ - _target_: training.dataset.transforms.ColorJitter
55
+ consistent_transform: True
56
+ brightness: 0.2
57
+ contrast: 0.2
58
+ saturation: 0.03
59
+ hue: null
60
+ - _target_: training.dataset.transforms.ColorJitter
61
+ consistent_transform: False
62
+ brightness: 0.1
63
+ contrast: 0.05
64
+ saturation: 0.05
65
+ hue: null
66
+ - _target_: training.dataset.transforms.ToTensorAPI
67
+ - _target_: training.dataset.transforms.NormalizeAPI
68
+ mean: [0.485, 0.456, 0.406]
69
+ std: [0.229, 0.224, 0.225]
70
+
71
+ trainer:
72
+ _target_: training.trainer.Trainer
73
+ mode: train_only
74
+ max_epochs: ${times:${scratch.num_epochs},${scratch.phases_per_epoch}}
75
+ accelerator: cuda
76
+ seed_value: 123
77
+
78
+ model:
79
+ _target_: training.model.efficienttam.EfficientTAMTrain
80
+ image_encoder:
81
+ _target_: sam2.modeling.backbones.image_encoder.ImageEncoder
82
+ scalp: 0
83
+ trunk:
84
+ _target_: sam2.modeling.backbones.vitdet.ViT
85
+ patch_size: 16
86
+ embed_dim: 384
87
+ depth: 12
88
+ num_heads: 6
89
+ mlp_ratio: 4.0
90
+ qkv_bias: true
91
+ drop_path_rate: 0.0
92
+ use_rel_pos: false
93
+ window_size: 14
94
+ window_block_indexes: [0, 1, 3, 4, 6, 7, 9, 10]
95
+ neck:
96
+ _target_: sam2.modeling.backbones.image_encoder.ViTDetNeck
97
+ position_encoding:
98
+ _target_: sam2.modeling.position_encoding.PositionEmbeddingSine
99
+ num_pos_feats: 256
100
+ normalize: true
101
+ scale: null
102
+ temperature: 10000
103
+ d_model: 256
104
+ backbone_channel_list: [384,]
105
+ neck_norm: LN
106
+
107
+ memory_attention:
108
+ _target_: sam2.modeling.memory_attention.MemoryAttention
109
+ d_model: 256
110
+ pos_enc_at_input: true
111
+ layer:
112
+ _target_: sam2.modeling.memory_attention.MemoryAttentionLayer
113
+ activation: relu
114
+ dim_feedforward: 2048
115
+ dropout: 0.1
116
+ pos_enc_at_attn: false
117
+ self_attention:
118
+ _target_: sam2.modeling.sam.transformer.RoPEAttention
119
+ rope_theta: 10000.0
120
+ feat_sizes: [32, 32]
121
+ embedding_dim: 256
122
+ num_heads: 1
123
+ downsample_rate: 1
124
+ dropout: 0.1
125
+ d_model: 256
126
+ pos_enc_at_cross_attn_keys: true
127
+ pos_enc_at_cross_attn_queries: false
128
+ cross_attention:
129
+ _target_: sam2.modeling.sam.transformer.RoPEAttention
130
+ rope_theta: 10000.0
131
+ feat_sizes: [32, 32]
132
+ rope_k_repeat: True
133
+ embedding_dim: 256
134
+ num_heads: 1
135
+ downsample_rate: 1
136
+ dropout: 0.1
137
+ kv_in_dim: 64
138
+ num_layers: 4
139
+
140
+ memory_encoder:
141
+ _target_: sam2.modeling.memory_encoder.MemoryEncoder
142
+ out_dim: 64
143
+ position_encoding:
144
+ _target_: sam2.modeling.position_encoding.PositionEmbeddingSine
145
+ num_pos_feats: 64
146
+ normalize: true
147
+ scale: null
148
+ temperature: 10000
149
+ mask_downsampler:
150
+ _target_: sam2.modeling.memory_encoder.MaskDownSampler
151
+ kernel_size: 3
152
+ stride: 2
153
+ padding: 1
154
+ fuser:
155
+ _target_: sam2.modeling.memory_encoder.Fuser
156
+ layer:
157
+ _target_: sam2.modeling.memory_encoder.CXBlock
158
+ dim: 256
159
+ kernel_size: 7
160
+ padding: 3
161
+ layer_scale_init_value: 1e-6
162
+ use_dwconv: True # depth-wise convs
163
+ num_layers: 2
164
+
165
+ num_maskmem: 7
166
+ image_size: ${scratch.resolution}
167
+ # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask
168
+ # SAM decoder
169
+ sigmoid_scale_for_mem_enc: 20.0
170
+ sigmoid_bias_for_mem_enc: -10.0
171
+ use_mask_input_as_output_without_sam: true
172
+ # Memory
173
+ directly_add_no_mem_embed: true
174
+ use_high_res_features_in_sam: false
175
+ # output 3 masks on the first click on initial conditioning frames
176
+ multimask_output_in_sam: true
177
+ # SAM heads
178
+ iou_prediction_use_sigmoid: True
179
+ # cross-attend to object pointers from other frames in the ViT encoder
180
+ use_obj_ptrs_in_encoder: true
181
+ add_tpos_enc_to_obj_ptrs: false
182
+ only_obj_ptrs_in_the_past_for_eval: true
183
+ # object occlusion prediction
184
+ pred_obj_scores: true
185
+ pred_obj_scores_mlp: true
186
+ fixed_no_obj_ptr: true
187
+ # multimask tracking settings
188
+ multimask_output_for_tracking: true
189
+ use_multimask_token_for_obj_ptr: true
190
+ multimask_min_pt_num: 0
191
+ multimask_max_pt_num: 1
192
+ use_mlp_for_obj_ptr_proj: true
193
+ # Compilation flag
194
+ # compile_image_encoder: False
195
+
196
+ ####### Training specific params #######
197
+ # box/point input and corrections
198
+ prob_to_use_pt_input_for_train: 0.5
199
+ prob_to_use_pt_input_for_eval: 0.0
200
+ prob_to_use_box_input_for_train: 0.5 # 0.5*0.5 = 0.25 prob to use box instead of points
201
+ prob_to_use_box_input_for_eval: 0.0
202
+ prob_to_sample_from_gt_for_train: 0.1 # with a small prob, sampling correction points from GT mask instead of prediction errors
203
+ num_frames_to_correct_for_train: 2 # iteratively sample on random 1~2 frames (always include the first frame)
204
+ num_frames_to_correct_for_eval: 1 # only iteratively sample on first frame
205
+ rand_frames_to_correct_for_train: True # random #init-cond-frame ~ 2
206
+ add_all_frames_to_correct_as_cond: True # when a frame receives a correction click, it becomes a conditioning frame (even if it's not initially a conditioning frame)
207
+ # maximum 2 initial conditioning frames
208
+ num_init_cond_frames_for_train: 2
209
+ rand_init_cond_frames_for_train: True # random 1~2
210
+ num_correction_pt_per_frame: 7
211
+ use_act_ckpt_iterative_pt_sampling: false
212
+
213
+ num_init_cond_frames_for_eval: 1 # only mask on the first frame
214
+ forward_backbone_per_frame_for_eval: True
215
+
216
+
217
+ data:
218
+ train:
219
+ _target_: training.dataset.sam2_datasets.TorchTrainMixedDataset
220
+ phases_per_epoch: ${scratch.phases_per_epoch}
221
+ batch_sizes:
222
+ - ${scratch.train_batch_size}
223
+ datasets:
224
+ # Video Datasets
225
+ - _target_: training.dataset.utils.RepeatFactorWrapper
226
+ dataset:
227
+ _target_: training.dataset.utils.ConcatDataset
228
+ datasets:
229
+ # CT
230
+ - _target_: training.dataset.vos_dataset.VOSDataset
231
+ transforms: ${vos.train_transforms}
232
+ training: true
233
+ video_dataset:
234
+ _target_: training.dataset.vos_raw_dataset.NPZRawDataset
235
+ folder: /home/jma/Documents/MedSAM2/data/RECIST_train_npz
236
+ sampler:
237
+ _target_: training.dataset.vos_sampler.RandomUniformSampler
238
+ num_frames: ${scratch.num_frames}
239
+ max_num_objects: ${scratch.max_num_objects}
240
+ multiplier: 1
241
+
242
+
243
+
244
+
245
+ shuffle: True
246
+ num_workers: ${scratch.num_train_workers}
247
+ pin_memory: True
248
+ drop_last: True
249
+ collate_fn:
250
+ _target_: training.utils.data_utils.collate_fn
251
+ _partial_: true
252
+ dict_key: all
253
+
254
+ optim:
255
+ amp:
256
+ enabled: True
257
+ amp_dtype: bfloat16
258
+
259
+ optimizer:
260
+ _target_: torch.optim.AdamW
261
+
262
+ gradient_clip:
263
+ _target_: training.optimizer.GradientClipper
264
+ max_norm: 0.1
265
+ norm_type: 2
266
+
267
+ param_group_modifiers:
268
+ - _target_: training.optimizer.layer_decay_param_modifier
269
+ _partial_: True
270
+ layer_decay_value: 0.9
271
+ apply_to: 'image_encoder.trunk'
272
+ overrides:
273
+ - pattern: '*pos_embed*'
274
+ value: 1.0
275
+
276
+ options:
277
+ lr:
278
+ - scheduler:
279
+ _target_: fvcore.common.param_scheduler.CosineParamScheduler
280
+ start_value: ${scratch.base_lr}
281
+ end_value: ${divide:${scratch.base_lr},10}
282
+ - scheduler:
283
+ _target_: fvcore.common.param_scheduler.CosineParamScheduler
284
+ start_value: ${scratch.vision_lr}
285
+ end_value: ${divide:${scratch.vision_lr},10}
286
+ param_names:
287
+ - 'image_encoder.*'
288
+ weight_decay:
289
+ - scheduler:
290
+ _target_: fvcore.common.param_scheduler.ConstantParamScheduler
291
+ value: 0.1
292
+ - scheduler:
293
+ _target_: fvcore.common.param_scheduler.ConstantParamScheduler
294
+ value: 0.0
295
+ param_names:
296
+ - '*bias*'
297
+ module_cls_names: ['torch.nn.LayerNorm']
298
+
299
+ loss:
300
+ all:
301
+ _target_: training.loss_fns.MultiStepMultiMasksAndIous
302
+ weight_dict:
303
+ loss_mask: 20
304
+ loss_dice: 1
305
+ loss_iou: 1
306
+ loss_class: 1
307
+ supervise_all_iou: true
308
+ iou_use_l1_loss: true
309
+ pred_obj_scores: true
310
+ focal_gamma_obj_score: 0.0
311
+ focal_alpha_obj_score: -1.0
312
+
313
+ distributed:
314
+ backend: nccl
315
+ find_unused_parameters: True
316
+
317
+ logging:
318
+ tensorboard_writer:
319
+ _target_: training.utils.logger.make_tensorboard_logger
320
+ log_dir: ${launcher.experiment_log_dir}/tensorboard
321
+ flush_secs: 120
322
+ should_log: True
323
+ log_dir: ${launcher.experiment_log_dir}/logs
324
+ log_freq: 10
325
+
326
+ # initialize from a SAM 2 checkpoint
327
+ checkpoint:
328
+ save_dir: ${launcher.experiment_log_dir}/checkpoints
329
+ save_freq: 10 # 0 only last checkpoint is saved.
330
+ model_weight_initializer:
331
+ _partial_: True
332
+ _target_: training.utils.checkpoint_utils.load_state_dict_into_model
333
+ strict: True
334
+ ignore_unexpected_keys: null
335
+ ignore_missing_keys: null
336
+
337
+ state_dict:
338
+ _target_: training.utils.checkpoint_utils.load_checkpoint_and_apply_kernels
339
+ checkpoint_path: checkpoints/efficienttam_s_512x512.pt
340
+ ckpt_state_dict_keys: ['model']
341
+
342
+ launcher:
343
+ num_nodes: 1
344
+ gpus_per_node: 4
345
+ experiment_log_dir: exp_log # Path to log directory, defaults to ./sam2_logs/${config_name}
346
+
347
+ # SLURM args if running on a cluster
348
+ submitit:
349
+ partition: null
350
+ account: null
351
+ qos: null
352
+ cpus_per_task: 15
353
+ use_cluster: false
354
+ timeout_hour: 24
355
+ name: null
356
+ port_range: [10000, 65000]
357
+
MedSAM2/sam2/configs/efficientmedsam_ti_512_FLARE_RECIST.yaml ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+
3
+ scratch:
4
+ resolution: 512
5
+ train_batch_size: 8
6
+ num_train_workers: 15
7
+ num_frames: 8
8
+ max_num_objects: 5
9
+ base_lr: 5.0e-6
10
+ vision_lr: 3.0e-06
11
+ phases_per_epoch: 1
12
+ num_epochs: 100
13
+
14
+ dataset:
15
+ # PATHS to Dataset
16
+ folder: /cluster/projects/bwanggroup/jma/data_medsam2/npz_train/RECIST_train_npz # PATH to Med NPZ folder
17
+ multiplier: 2
18
+
19
+ # Video transforms
20
+ vos:
21
+ train_transforms:
22
+ - _target_: training.dataset.transforms.ComposeAPI
23
+ transforms:
24
+ - _target_: training.dataset.transforms.RandomHorizontalFlip
25
+ consistent_transform: True
26
+ - _target_: training.dataset.transforms.RandomVerticalFlip
27
+ consistent_transform: True
28
+ - _target_: training.dataset.transforms.RandomAffine
29
+ degrees: 25
30
+ shear: 20
31
+ scale: [0.7, 1.4]
32
+ image_interpolation: bilinear
33
+ consistent_transform: True
34
+ - _target_: training.dataset.transforms.RandomAffine
35
+ degrees: 5
36
+ shear: 5
37
+ scale: [0.95, 1.05]
38
+ translate: [0.05, 0.05]
39
+ image_interpolation: bilinear
40
+ consistent_transform: False
41
+ p: 0.1
42
+ - _target_: training.dataset.transforms.RandomResizeAPI
43
+ sizes: ${scratch.resolution}
44
+ square: true
45
+ consistent_transform: True
46
+ - _target_: training.dataset.transforms.RandomGaussianNoise
47
+ consistent_transform: True
48
+ p: 0.1
49
+ - _target_: training.dataset.transforms.RandomGaussianBlur
50
+ consistent_transform: True
51
+ kernel_size: 5
52
+ sigma: [0.5, 1.0]
53
+ p: 0.2
54
+ - _target_: training.dataset.transforms.ColorJitter
55
+ consistent_transform: True
56
+ brightness: 0.2
57
+ contrast: 0.2
58
+ saturation: 0.03
59
+ hue: null
60
+ - _target_: training.dataset.transforms.ColorJitter
61
+ consistent_transform: False
62
+ brightness: 0.1
63
+ contrast: 0.05
64
+ saturation: 0.05
65
+ hue: null
66
+ - _target_: training.dataset.transforms.ToTensorAPI
67
+ - _target_: training.dataset.transforms.NormalizeAPI
68
+ mean: [0.485, 0.456, 0.406]
69
+ std: [0.229, 0.224, 0.225]
70
+
71
+ trainer:
72
+ _target_: training.trainer.Trainer
73
+ mode: train_only
74
+ max_epochs: ${times:${scratch.num_epochs},${scratch.phases_per_epoch}}
75
+ accelerator: cuda
76
+ seed_value: 123
77
+
78
+ model:
79
+ _target_: training.model.efficienttam.EfficientTAMTrain
80
+ image_encoder:
81
+ _target_: sam2.modeling.backbones.image_encoder.ImageEncoder
82
+ scalp: 0
83
+ trunk:
84
+ _target_: sam2.modeling.backbones.vitdet.ViT
85
+ patch_size: 16
86
+ embed_dim: 192
87
+ depth: 12
88
+ num_heads: 3
89
+ mlp_ratio: 4.0
90
+ qkv_bias: true
91
+ drop_path_rate: 0.0
92
+ use_rel_pos: false
93
+ window_size: 14
94
+ window_block_indexes: [0, 1, 3, 4, 6, 7, 9, 10]
95
+ neck:
96
+ _target_: sam2.modeling.backbones.image_encoder.ViTDetNeck
97
+ position_encoding:
98
+ _target_: sam2.modeling.position_encoding.PositionEmbeddingSine
99
+ num_pos_feats: 256
100
+ normalize: true
101
+ scale: null
102
+ temperature: 10000
103
+ d_model: 256
104
+ backbone_channel_list: [192,]
105
+ neck_norm: LN
106
+
107
+ memory_attention:
108
+ _target_: sam2.modeling.memory_attention.MemoryAttention
109
+ d_model: 256
110
+ pos_enc_at_input: true
111
+ layer:
112
+ _target_: sam2.modeling.memory_attention.MemoryAttentionLayer
113
+ activation: relu
114
+ dim_feedforward: 2048
115
+ dropout: 0.1
116
+ pos_enc_at_attn: false
117
+ self_attention:
118
+ _target_: sam2.modeling.sam.transformer.RoPEAttention
119
+ rope_theta: 10000.0
120
+ feat_sizes: [32, 32]
121
+ embedding_dim: 256
122
+ num_heads: 1
123
+ downsample_rate: 1
124
+ dropout: 0.1
125
+ d_model: 256
126
+ pos_enc_at_cross_attn_keys: true
127
+ pos_enc_at_cross_attn_queries: false
128
+ cross_attention:
129
+ _target_: sam2.modeling.sam.transformer.RoPEAttention
130
+ rope_theta: 10000.0
131
+ feat_sizes: [32, 32]
132
+ rope_k_repeat: True
133
+ embedding_dim: 256
134
+ num_heads: 1
135
+ downsample_rate: 1
136
+ dropout: 0.1
137
+ kv_in_dim: 64
138
+ num_layers: 4
139
+
140
+ memory_encoder:
141
+ _target_: sam2.modeling.memory_encoder.MemoryEncoder
142
+ out_dim: 64
143
+ position_encoding:
144
+ _target_: sam2.modeling.position_encoding.PositionEmbeddingSine
145
+ num_pos_feats: 64
146
+ normalize: true
147
+ scale: null
148
+ temperature: 10000
149
+ mask_downsampler:
150
+ _target_: sam2.modeling.memory_encoder.MaskDownSampler
151
+ kernel_size: 3
152
+ stride: 2
153
+ padding: 1
154
+ fuser:
155
+ _target_: sam2.modeling.memory_encoder.Fuser
156
+ layer:
157
+ _target_: sam2.modeling.memory_encoder.CXBlock
158
+ dim: 256
159
+ kernel_size: 7
160
+ padding: 3
161
+ layer_scale_init_value: 1e-6
162
+ use_dwconv: True # depth-wise convs
163
+ num_layers: 2
164
+
165
+ num_maskmem: 7
166
+ image_size: ${scratch.resolution}
167
+ # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask
168
+ # SAM decoder
169
+ sigmoid_scale_for_mem_enc: 20.0
170
+ sigmoid_bias_for_mem_enc: -10.0
171
+ use_mask_input_as_output_without_sam: true
172
+ # Memory
173
+ directly_add_no_mem_embed: true
174
+ use_high_res_features_in_sam: false
175
+ # output 3 masks on the first click on initial conditioning frames
176
+ multimask_output_in_sam: true
177
+ # SAM heads
178
+ iou_prediction_use_sigmoid: True
179
+ # cross-attend to object pointers from other frames in the ViT encoder
180
+ use_obj_ptrs_in_encoder: true
181
+ add_tpos_enc_to_obj_ptrs: false
182
+ only_obj_ptrs_in_the_past_for_eval: true
183
+ # object occlusion prediction
184
+ pred_obj_scores: true
185
+ pred_obj_scores_mlp: true
186
+ fixed_no_obj_ptr: true
187
+ # multimask tracking settings
188
+ multimask_output_for_tracking: true
189
+ use_multimask_token_for_obj_ptr: true
190
+ multimask_min_pt_num: 0
191
+ multimask_max_pt_num: 1
192
+ use_mlp_for_obj_ptr_proj: true
193
+ # Compilation flag
194
+ # compile_image_encoder: False
195
+
196
+ ####### Training specific params #######
197
+ # box/point input and corrections
198
+ prob_to_use_pt_input_for_train: 0.5
199
+ prob_to_use_pt_input_for_eval: 0.0
200
+ prob_to_use_box_input_for_train: 0.5 # 0.5*0.5 = 0.25 prob to use box instead of points
201
+ prob_to_use_box_input_for_eval: 0.0
202
+ prob_to_sample_from_gt_for_train: 0.1 # with a small prob, sampling correction points from GT mask instead of prediction errors
203
+ num_frames_to_correct_for_train: 2 # iteratively sample on random 1~2 frames (always include the first frame)
204
+ num_frames_to_correct_for_eval: 1 # only iteratively sample on first frame
205
+ rand_frames_to_correct_for_train: True # random #init-cond-frame ~ 2
206
+ add_all_frames_to_correct_as_cond: True # when a frame receives a correction click, it becomes a conditioning frame (even if it's not initially a conditioning frame)
207
+ # maximum 2 initial conditioning frames
208
+ num_init_cond_frames_for_train: 2
209
+ rand_init_cond_frames_for_train: True # random 1~2
210
+ num_correction_pt_per_frame: 7
211
+ use_act_ckpt_iterative_pt_sampling: false
212
+
213
+ num_init_cond_frames_for_eval: 1 # only mask on the first frame
214
+ forward_backbone_per_frame_for_eval: True
215
+
216
+
217
+ data:
218
+ train:
219
+ _target_: training.dataset.sam2_datasets.TorchTrainMixedDataset
220
+ phases_per_epoch: ${scratch.phases_per_epoch}
221
+ batch_sizes:
222
+ - ${scratch.train_batch_size}
223
+ datasets:
224
+ # Video Datasets
225
+ - _target_: training.dataset.utils.RepeatFactorWrapper
226
+ dataset:
227
+ _target_: training.dataset.utils.ConcatDataset
228
+ datasets:
229
+ # CT
230
+ - _target_: training.dataset.vos_dataset.VOSDataset
231
+ transforms: ${vos.train_transforms}
232
+ training: true
233
+ video_dataset:
234
+ _target_: training.dataset.vos_raw_dataset.NPZRawDataset
235
+ folder: /cluster/projects/bwanggroup/jma/data_medsam2/npz_train/RECIST_train_npz
236
+ sampler:
237
+ _target_: training.dataset.vos_sampler.RandomUniformSampler
238
+ num_frames: ${scratch.num_frames}
239
+ max_num_objects: ${scratch.max_num_objects}
240
+ multiplier: 1
241
+
242
+
243
+
244
+ shuffle: True
245
+ num_workers: ${scratch.num_train_workers}
246
+ pin_memory: True
247
+ drop_last: True
248
+ collate_fn:
249
+ _target_: training.utils.data_utils.collate_fn
250
+ _partial_: true
251
+ dict_key: all
252
+
253
+ optim:
254
+ amp:
255
+ enabled: True
256
+ amp_dtype: bfloat16
257
+
258
+ optimizer:
259
+ _target_: torch.optim.AdamW
260
+
261
+ gradient_clip:
262
+ _target_: training.optimizer.GradientClipper
263
+ max_norm: 0.1
264
+ norm_type: 2
265
+
266
+ param_group_modifiers:
267
+ - _target_: training.optimizer.layer_decay_param_modifier
268
+ _partial_: True
269
+ layer_decay_value: 0.9
270
+ apply_to: 'image_encoder.trunk'
271
+ overrides:
272
+ - pattern: '*pos_embed*'
273
+ value: 1.0
274
+
275
+ options:
276
+ lr:
277
+ - scheduler:
278
+ _target_: fvcore.common.param_scheduler.CosineParamScheduler
279
+ start_value: ${scratch.base_lr}
280
+ end_value: ${divide:${scratch.base_lr},10}
281
+ - scheduler:
282
+ _target_: fvcore.common.param_scheduler.CosineParamScheduler
283
+ start_value: ${scratch.vision_lr}
284
+ end_value: ${divide:${scratch.vision_lr},10}
285
+ param_names:
286
+ - 'image_encoder.*'
287
+ weight_decay:
288
+ - scheduler:
289
+ _target_: fvcore.common.param_scheduler.ConstantParamScheduler
290
+ value: 0.1
291
+ - scheduler:
292
+ _target_: fvcore.common.param_scheduler.ConstantParamScheduler
293
+ value: 0.0
294
+ param_names:
295
+ - '*bias*'
296
+ module_cls_names: ['torch.nn.LayerNorm']
297
+
298
+ loss:
299
+ all:
300
+ _target_: training.loss_fns.MultiStepMultiMasksAndIous
301
+ weight_dict:
302
+ loss_mask: 20
303
+ loss_dice: 1
304
+ loss_iou: 1
305
+ loss_class: 1
306
+ supervise_all_iou: true
307
+ iou_use_l1_loss: true
308
+ pred_obj_scores: true
309
+ focal_gamma_obj_score: 0.0
310
+ focal_alpha_obj_score: -1.0
311
+
312
+ distributed:
313
+ backend: nccl
314
+ find_unused_parameters: True
315
+
316
+ logging:
317
+ tensorboard_writer:
318
+ _target_: training.utils.logger.make_tensorboard_logger
319
+ log_dir: ${launcher.experiment_log_dir}/tensorboard
320
+ flush_secs: 120
321
+ should_log: True
322
+ log_dir: ${launcher.experiment_log_dir}/logs
323
+ log_freq: 10
324
+
325
+ # initialize from a SAM 2 checkpoint
326
+ checkpoint:
327
+ save_dir: ${launcher.experiment_log_dir}/checkpoints
328
+ save_freq: 10 # 0 only last checkpoint is saved.
329
+ model_weight_initializer:
330
+ _partial_: True
331
+ _target_: training.utils.checkpoint_utils.load_state_dict_into_model
332
+ strict: True
333
+ ignore_unexpected_keys: null
334
+ ignore_missing_keys: null
335
+
336
+ state_dict:
337
+ _target_: training.utils.checkpoint_utils.load_checkpoint_and_apply_kernels
338
+ checkpoint_path: /cluster/projects/bwanggroup/jma/data_medsam2/checkpoints/efficienttam_ti_512x512.pt # PATH to SAM 2.1 checkpoint
339
+ ckpt_state_dict_keys: ['model']
340
+
341
+ launcher:
342
+ num_nodes: 1
343
+ gpus_per_node: 4
344
+ experiment_log_dir: /cluster/projects/bwanggroup/jma/data_medsam2/exp_log/RECIST-EffTiny # Path to log directory, defaults to ./sam2_logs/${config_name}
345
+
346
+ # SLURM args if running on a cluster
347
+ submitit:
348
+ partition: null
349
+ account: null
350
+ qos: null
351
+ cpus_per_task: 15
352
+ use_cluster: false
353
+ timeout_hour: 24
354
+ name: null
355
+ port_range: [10000, 65000]
356
+
MedSAM2/sam2/configs/efficienttam_ti_512.yaml ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+
3
+ # Model
4
+ model:
5
+ _target_: efficient_track_anything.modeling.efficienttam_base.EfficientTAMBase
6
+ image_encoder:
7
+ _target_: efficient_track_anything.modeling.backbones.image_encoder.ImageEncoder
8
+ scalp: 0
9
+ trunk:
10
+ _target_: efficient_track_anything.modeling.backbones.vitdet.ViT
11
+ patch_size: 16
12
+ embed_dim: 192
13
+ depth: 12
14
+ num_heads: 3
15
+ mlp_ratio: 4.0
16
+ qkv_bias: true
17
+ drop_path_rate: 0.0
18
+ use_rel_pos: false
19
+ window_size: 14
20
+ window_block_indexes: [0, 1, 3, 4, 6, 7, 9, 10]
21
+ neck:
22
+ _target_: efficient_track_anything.modeling.backbones.image_encoder.ViTDetNeck
23
+ position_encoding:
24
+ _target_: efficient_track_anything.modeling.position_encoding.PositionEmbeddingSine
25
+ num_pos_feats: 256
26
+ normalize: true
27
+ scale: null
28
+ temperature: 10000
29
+ d_model: 256
30
+ backbone_channel_list: [192,]
31
+ neck_norm: LN
32
+
33
+ memory_attention:
34
+ _target_: efficient_track_anything.modeling.memory_attention.MemoryAttention
35
+ d_model: 256
36
+ pos_enc_at_input: true
37
+ layer:
38
+ _target_: efficient_track_anything.modeling.memory_attention.MemoryAttentionLayer
39
+ activation: relu
40
+ dim_feedforward: 2048
41
+ dropout: 0.1
42
+ pos_enc_at_attn: false
43
+ self_attention:
44
+ _target_: efficient_track_anything.modeling.sam.transformer.RoPEAttention
45
+ rope_theta: 10000.0
46
+ feat_sizes: [32, 32]
47
+ embedding_dim: 256
48
+ num_heads: 1
49
+ downsample_rate: 1
50
+ dropout: 0.1
51
+ d_model: 256
52
+ pos_enc_at_cross_attn_keys: true
53
+ pos_enc_at_cross_attn_queries: false
54
+ cross_attention:
55
+ _target_: efficient_track_anything.modeling.sam.transformer.RoPEAttention
56
+ rope_theta: 10000.0
57
+ feat_sizes: [32, 32]
58
+ rope_k_repeat: True
59
+ embedding_dim: 256
60
+ num_heads: 1
61
+ downsample_rate: 1
62
+ dropout: 0.1
63
+ kv_in_dim: 64
64
+ num_layers: 4
65
+
66
+ memory_encoder:
67
+ _target_: efficient_track_anything.modeling.memory_encoder.MemoryEncoder
68
+ out_dim: 64
69
+ position_encoding:
70
+ _target_: efficient_track_anything.modeling.position_encoding.PositionEmbeddingSine
71
+ num_pos_feats: 64
72
+ normalize: true
73
+ scale: null
74
+ temperature: 10000
75
+ mask_downsampler:
76
+ _target_: efficient_track_anything.modeling.memory_encoder.MaskDownSampler
77
+ kernel_size: 3
78
+ stride: 2
79
+ padding: 1
80
+ fuser:
81
+ _target_: efficient_track_anything.modeling.memory_encoder.Fuser
82
+ layer:
83
+ _target_: efficient_track_anything.modeling.memory_encoder.CXBlock
84
+ dim: 256
85
+ kernel_size: 7
86
+ padding: 3
87
+ layer_scale_init_value: 1e-6
88
+ use_dwconv: True # depth-wise convs
89
+ num_layers: 2
90
+
91
+ num_maskmem: 7
92
+ image_size: 512
93
+ # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask
94
+ # SAM decoder
95
+ sigmoid_scale_for_mem_enc: 20.0
96
+ sigmoid_bias_for_mem_enc: -10.0
97
+ use_mask_input_as_output_without_sam: true
98
+ # Memory
99
+ directly_add_no_mem_embed: true
100
+ use_high_res_features_in_sam: false
101
+ # output 3 masks on the first click on initial conditioning frames
102
+ multimask_output_in_sam: true
103
+ # SAM heads
104
+ iou_prediction_use_sigmoid: True
105
+ # cross-attend to object pointers from other frames in the ViT encoder
106
+ use_obj_ptrs_in_encoder: true
107
+ add_tpos_enc_to_obj_ptrs: false
108
+ only_obj_ptrs_in_the_past_for_eval: true
109
+ # object occlusion prediction
110
+ pred_obj_scores: true
111
+ pred_obj_scores_mlp: true
112
+ fixed_no_obj_ptr: true
113
+ # multimask tracking settings
114
+ multimask_output_for_tracking: true
115
+ use_multimask_token_for_obj_ptr: true
116
+ multimask_min_pt_num: 0
117
+ multimask_max_pt_num: 1
118
+ use_mlp_for_obj_ptr_proj: true
119
+ # Compilation flag
120
+ compile_image_encoder: true
MedSAM2/sam2/configs/sam2.1_hiera_t512.yaml ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+
3
+ # Model
4
+ model:
5
+ _target_: sam2.modeling.sam2_base.SAM2Base
6
+ image_encoder:
7
+ _target_: sam2.modeling.backbones.image_encoder.ImageEncoder
8
+ scalp: 1
9
+ trunk:
10
+ _target_: sam2.modeling.backbones.hieradet.Hiera
11
+ embed_dim: 96
12
+ num_heads: 1
13
+ stages: [1, 2, 7, 2]
14
+ global_att_blocks: [5, 7, 9]
15
+ window_pos_embed_bkg_spatial_size: [7, 7]
16
+ neck:
17
+ _target_: sam2.modeling.backbones.image_encoder.FpnNeck
18
+ position_encoding:
19
+ _target_: sam2.modeling.position_encoding.PositionEmbeddingSine
20
+ num_pos_feats: 256
21
+ normalize: true
22
+ scale: null
23
+ temperature: 10000
24
+ d_model: 256
25
+ backbone_channel_list: [768, 384, 192, 96]
26
+ fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features
27
+ fpn_interp_model: nearest
28
+
29
+ memory_attention:
30
+ _target_: sam2.modeling.memory_attention.MemoryAttention
31
+ d_model: 256
32
+ pos_enc_at_input: true
33
+ layer:
34
+ _target_: sam2.modeling.memory_attention.MemoryAttentionLayer
35
+ activation: relu
36
+ dim_feedforward: 2048
37
+ dropout: 0.1
38
+ pos_enc_at_attn: false
39
+ self_attention:
40
+ _target_: sam2.modeling.sam.transformer.RoPEAttention
41
+ rope_theta: 10000.0
42
+ feat_sizes: [32, 32]
43
+ embedding_dim: 256
44
+ num_heads: 1
45
+ downsample_rate: 1
46
+ dropout: 0.1
47
+ d_model: 256
48
+ pos_enc_at_cross_attn_keys: true
49
+ pos_enc_at_cross_attn_queries: false
50
+ cross_attention:
51
+ _target_: sam2.modeling.sam.transformer.RoPEAttention
52
+ rope_theta: 10000.0
53
+ feat_sizes: [32, 32]
54
+ rope_k_repeat: True
55
+ embedding_dim: 256
56
+ num_heads: 1
57
+ downsample_rate: 1
58
+ dropout: 0.1
59
+ kv_in_dim: 64
60
+ num_layers: 4
61
+
62
+ memory_encoder:
63
+ _target_: sam2.modeling.memory_encoder.MemoryEncoder
64
+ out_dim: 64
65
+ position_encoding:
66
+ _target_: sam2.modeling.position_encoding.PositionEmbeddingSine
67
+ num_pos_feats: 64
68
+ normalize: true
69
+ scale: null
70
+ temperature: 10000
71
+ mask_downsampler:
72
+ _target_: sam2.modeling.memory_encoder.MaskDownSampler
73
+ kernel_size: 3
74
+ stride: 2
75
+ padding: 1
76
+ fuser:
77
+ _target_: sam2.modeling.memory_encoder.Fuser
78
+ layer:
79
+ _target_: sam2.modeling.memory_encoder.CXBlock
80
+ dim: 256
81
+ kernel_size: 7
82
+ padding: 3
83
+ layer_scale_init_value: 1e-6
84
+ use_dwconv: True # depth-wise convs
85
+ num_layers: 2
86
+
87
+ num_maskmem: 7
88
+ image_size: 512
89
+ # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask
90
+ # SAM decoder
91
+ sigmoid_scale_for_mem_enc: 20.0
92
+ sigmoid_bias_for_mem_enc: -10.0
93
+ use_mask_input_as_output_without_sam: true
94
+ # Memory
95
+ directly_add_no_mem_embed: true
96
+ no_obj_embed_spatial: true
97
+ # use high-resolution feature map in the SAM mask decoder
98
+ use_high_res_features_in_sam: true
99
+ # output 3 masks on the first click on initial conditioning frames
100
+ multimask_output_in_sam: true
101
+ # SAM heads
102
+ iou_prediction_use_sigmoid: True
103
+ # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder
104
+ use_obj_ptrs_in_encoder: true
105
+ add_tpos_enc_to_obj_ptrs: true
106
+ proj_tpos_enc_in_obj_ptrs: true
107
+ use_signed_tpos_enc_to_obj_ptrs: true
108
+ only_obj_ptrs_in_the_past_for_eval: true
109
+ # object occlusion prediction
110
+ pred_obj_scores: true
111
+ pred_obj_scores_mlp: true
112
+ fixed_no_obj_ptr: true
113
+ # multimask tracking settings
114
+ multimask_output_for_tracking: true
115
+ use_multimask_token_for_obj_ptr: true
116
+ multimask_min_pt_num: 0
117
+ multimask_max_pt_num: 1
118
+ use_mlp_for_obj_ptr_proj: true
119
+ # Compilation flag
120
+ # HieraT does not currently support compilation, should always be set to False
121
+ compile_image_encoder: False
MedSAM2/sam2/configs/sam2.1_hiera_tiny512_FLARE_RECIST.yaml ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+
3
+ scratch:
4
+ resolution: 512
5
+ train_video_batch_size: 2 # increase batch size based on your computing
6
+ num_train_workers: 15
7
+ num_frames: 8
8
+ max_num_objects: 3
9
+ base_lr: 5.0e-5
10
+ vision_lr: 3.0e-05
11
+ phases_per_epoch: 1
12
+ num_epochs: 75
13
+
14
+ dataset:
15
+ # PATHS to Dataset
16
+ folder: # PATH to Med NPZ folder
17
+ multiplier: 1
18
+
19
+ # Video transforms
20
+ vos:
21
+ train_transforms:
22
+ - _target_: training.dataset.transforms.ComposeAPI
23
+ transforms:
24
+ - _target_: training.dataset.transforms.RandomHorizontalFlip
25
+ consistent_transform: True
26
+ - _target_: training.dataset.transforms.RandomAffine
27
+ degrees: 25
28
+ shear: 20
29
+ image_interpolation: bilinear
30
+ consistent_transform: True
31
+ - _target_: training.dataset.transforms.RandomResizeAPI
32
+ sizes: ${scratch.resolution}
33
+ square: true
34
+ consistent_transform: True
35
+ - _target_: training.dataset.transforms.ColorJitter
36
+ consistent_transform: True
37
+ brightness: 0.1
38
+ contrast: 0.03
39
+ saturation: 0.03
40
+ hue: null
41
+ - _target_: training.dataset.transforms.RandomGrayscale
42
+ p: 0.05
43
+ consistent_transform: True
44
+ - _target_: training.dataset.transforms.ColorJitter
45
+ consistent_transform: False
46
+ brightness: 0.1
47
+ contrast: 0.05
48
+ saturation: 0.05
49
+ hue: null
50
+ - _target_: training.dataset.transforms.ToTensorAPI
51
+ - _target_: training.dataset.transforms.NormalizeAPI
52
+ mean: [0.485, 0.456, 0.406]
53
+ std: [0.229, 0.224, 0.225]
54
+
55
+
56
+ trainer:
57
+ _target_: training.trainer.Trainer
58
+ mode: train_only
59
+ max_epochs: ${times:${scratch.num_epochs},${scratch.phases_per_epoch}}
60
+ accelerator: cuda
61
+ seed_value: 123
62
+
63
+ model:
64
+ _target_: training.model.sam2.SAM2Train
65
+ image_encoder:
66
+ _target_: sam2.modeling.backbones.image_encoder.ImageEncoder
67
+ scalp: 1
68
+ trunk:
69
+ _target_: sam2.modeling.backbones.hieradet.Hiera
70
+ embed_dim: 96
71
+ num_heads: 1
72
+ stages: [1, 2, 7, 2]
73
+ global_att_blocks: [5, 7, 9]
74
+ window_pos_embed_bkg_spatial_size: [7, 7]
75
+ neck:
76
+ _target_: sam2.modeling.backbones.image_encoder.FpnNeck
77
+ position_encoding:
78
+ _target_: sam2.modeling.position_encoding.PositionEmbeddingSine
79
+ num_pos_feats: 256
80
+ normalize: true
81
+ scale: null
82
+ temperature: 10000
83
+ d_model: 256
84
+ backbone_channel_list: [768, 384, 192, 96]
85
+ fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features
86
+ fpn_interp_model: nearest
87
+
88
+ memory_attention:
89
+ _target_: sam2.modeling.memory_attention.MemoryAttention
90
+ d_model: 256
91
+ pos_enc_at_input: true
92
+ layer:
93
+ _target_: sam2.modeling.memory_attention.MemoryAttentionLayer
94
+ activation: relu
95
+ dim_feedforward: 2048
96
+ dropout: 0.1
97
+ pos_enc_at_attn: false
98
+ self_attention:
99
+ _target_: sam2.modeling.sam.transformer.RoPEAttention
100
+ rope_theta: 10000.0
101
+ feat_sizes: [32, 32]
102
+ embedding_dim: 256
103
+ num_heads: 1
104
+ downsample_rate: 1
105
+ dropout: 0.1
106
+ d_model: 256
107
+ pos_enc_at_cross_attn_keys: true
108
+ pos_enc_at_cross_attn_queries: false
109
+ cross_attention:
110
+ _target_: sam2.modeling.sam.transformer.RoPEAttention
111
+ rope_theta: 10000.0
112
+ feat_sizes: [32, 32]
113
+ rope_k_repeat: True
114
+ embedding_dim: 256
115
+ num_heads: 1
116
+ downsample_rate: 1
117
+ dropout: 0.1
118
+ kv_in_dim: 64
119
+ num_layers: 4
120
+
121
+ memory_encoder:
122
+ _target_: sam2.modeling.memory_encoder.MemoryEncoder
123
+ out_dim: 64
124
+ position_encoding:
125
+ _target_: sam2.modeling.position_encoding.PositionEmbeddingSine
126
+ num_pos_feats: 64
127
+ normalize: true
128
+ scale: null
129
+ temperature: 10000
130
+ mask_downsampler:
131
+ _target_: sam2.modeling.memory_encoder.MaskDownSampler
132
+ kernel_size: 3
133
+ stride: 2
134
+ padding: 1
135
+ fuser:
136
+ _target_: sam2.modeling.memory_encoder.Fuser
137
+ layer:
138
+ _target_: sam2.modeling.memory_encoder.CXBlock
139
+ dim: 256
140
+ kernel_size: 7
141
+ padding: 3
142
+ layer_scale_init_value: 1e-6
143
+ use_dwconv: True # depth-wise convs
144
+ num_layers: 2
145
+
146
+ num_maskmem: 7
147
+ image_size: ${scratch.resolution}
148
+ # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask
149
+ # SAM decoder
150
+ sigmoid_scale_for_mem_enc: 20.0
151
+ sigmoid_bias_for_mem_enc: -10.0
152
+ use_mask_input_as_output_without_sam: true
153
+ # Memory
154
+ directly_add_no_mem_embed: true
155
+ no_obj_embed_spatial: true
156
+ # use high-resolution feature map in the SAM mask decoder
157
+ use_high_res_features_in_sam: true
158
+ # output 3 masks on the first click on initial conditioning frames
159
+ multimask_output_in_sam: true
160
+ # SAM heads
161
+ iou_prediction_use_sigmoid: True
162
+ # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder
163
+ use_obj_ptrs_in_encoder: true
164
+ add_tpos_enc_to_obj_ptrs: true
165
+ proj_tpos_enc_in_obj_ptrs: true
166
+ use_signed_tpos_enc_to_obj_ptrs: true
167
+ only_obj_ptrs_in_the_past_for_eval: true
168
+ # object occlusion prediction
169
+ pred_obj_scores: true
170
+ pred_obj_scores_mlp: true
171
+ fixed_no_obj_ptr: true
172
+ # multimask tracking settings
173
+ multimask_output_for_tracking: true
174
+ use_multimask_token_for_obj_ptr: true
175
+ multimask_min_pt_num: 0
176
+ multimask_max_pt_num: 1
177
+ use_mlp_for_obj_ptr_proj: true
178
+ # Compilation flag
179
+ # compile_image_encoder: False
180
+
181
+ ####### Training specific params #######
182
+ # box/point input and corrections
183
+ prob_to_use_pt_input_for_train: 0.5
184
+ prob_to_use_pt_input_for_eval: 0.0
185
+ prob_to_use_box_input_for_train: 1.0
186
+ prob_to_use_box_input_for_eval: 0.0
187
+ prob_to_sample_from_gt_for_train: 0.1 # with a small prob, sampling correction points from GT mask instead of prediction errors
188
+ num_frames_to_correct_for_train: 2 # iteratively sample on random 1~2 frames (always include the first frame)
189
+ num_frames_to_correct_for_eval: 1 # only iteratively sample on first frame
190
+ rand_frames_to_correct_for_train: True # random #init-cond-frame ~ 2
191
+ add_all_frames_to_correct_as_cond: True # when a frame receives a correction click, it becomes a conditioning frame (even if it's not initially a conditioning frame)
192
+ # maximum 2 initial conditioning frames
193
+ num_init_cond_frames_for_train: 2
194
+ rand_init_cond_frames_for_train: True # random 1~2
195
+ num_correction_pt_per_frame: 7
196
+ use_act_ckpt_iterative_pt_sampling: false
197
+
198
+
199
+
200
+ num_init_cond_frames_for_eval: 1 # only mask on the first frame
201
+ forward_backbone_per_frame_for_eval: True
202
+
203
+
204
+ data:
205
+ train:
206
+ _target_: training.dataset.sam2_datasets.TorchTrainMixedDataset
207
+ phases_per_epoch: ${scratch.phases_per_epoch}
208
+ batch_sizes:
209
+ - ${scratch.train_video_batch_size}
210
+ datasets:
211
+ - _target_: training.dataset.utils.RepeatFactorWrapper
212
+ dataset:
213
+ _target_: training.dataset.utils.ConcatDataset
214
+ datasets:
215
+ # CT Lesion npz dataset
216
+ - _target_: training.dataset.vos_dataset.VOSDataset
217
+ transforms: ${vos.train_transforms}
218
+ training: true
219
+ video_dataset:
220
+ _target_: training.dataset.vos_raw_dataset.NPZRawDataset
221
+ folder: /home/jma/Documents/MedSAM2/data/RECIST_train_npz # must be absolute path
222
+ sampler:
223
+ _target_: training.dataset.vos_sampler.RandomUniformSampler
224
+ num_frames: ${scratch.num_frames}
225
+ max_num_objects: ${scratch.max_num_objects}
226
+ multiplier: 1
227
+
228
+
229
+ shuffle: True
230
+ num_workers: ${scratch.num_train_workers}
231
+ pin_memory: True
232
+ drop_last: True
233
+ collate_fn:
234
+ _target_: training.utils.data_utils.collate_fn
235
+ _partial_: true
236
+ dict_key: all
237
+
238
+ optim:
239
+ amp:
240
+ enabled: True
241
+ amp_dtype: bfloat16
242
+
243
+ optimizer:
244
+ _target_: torch.optim.AdamW
245
+
246
+ gradient_clip:
247
+ _target_: training.optimizer.GradientClipper
248
+ max_norm: 0.1
249
+ norm_type: 2
250
+
251
+ param_group_modifiers:
252
+ - _target_: training.optimizer.layer_decay_param_modifier
253
+ _partial_: True
254
+ layer_decay_value: 0.9
255
+ apply_to: 'image_encoder.trunk'
256
+ overrides:
257
+ - pattern: '*pos_embed*'
258
+ value: 1.0
259
+
260
+ options:
261
+ lr:
262
+ - scheduler:
263
+ _target_: fvcore.common.param_scheduler.CosineParamScheduler
264
+ start_value: ${scratch.base_lr}
265
+ end_value: ${divide:${scratch.base_lr},10}
266
+ - scheduler:
267
+ _target_: fvcore.common.param_scheduler.CosineParamScheduler
268
+ start_value: ${scratch.vision_lr}
269
+ end_value: ${divide:${scratch.vision_lr},10}
270
+ param_names:
271
+ - 'image_encoder.*'
272
+ weight_decay:
273
+ - scheduler:
274
+ _target_: fvcore.common.param_scheduler.ConstantParamScheduler
275
+ value: 0.1
276
+ - scheduler:
277
+ _target_: fvcore.common.param_scheduler.ConstantParamScheduler
278
+ value: 0.0
279
+ param_names:
280
+ - '*bias*'
281
+ module_cls_names: ['torch.nn.LayerNorm']
282
+
283
+ loss:
284
+ all:
285
+ _target_: training.loss_fns.MultiStepMultiMasksAndIous
286
+ weight_dict:
287
+ loss_mask: 20
288
+ loss_dice: 1
289
+ loss_iou: 1
290
+ loss_class: 1
291
+ supervise_all_iou: true
292
+ iou_use_l1_loss: true
293
+ pred_obj_scores: true
294
+ focal_gamma_obj_score: 0.0
295
+ focal_alpha_obj_score: -1.0
296
+
297
+ distributed:
298
+ backend: nccl # gloo or nccl
299
+ find_unused_parameters: True
300
+
301
+ logging:
302
+ tensorboard_writer:
303
+ _target_: training.utils.logger.make_tensorboard_logger
304
+ log_dir: ${launcher.experiment_log_dir}/tensorboard
305
+ flush_secs: 120
306
+ should_log: True
307
+ log_dir: ${launcher.experiment_log_dir}/logs
308
+ log_freq: 10
309
+
310
+ # initialize from a SAM 2 checkpoint
311
+ checkpoint:
312
+ save_dir: ${launcher.experiment_log_dir}/checkpoints
313
+ save_freq: 10 # 0 only last checkpoint is saved.
314
+ model_weight_initializer:
315
+ _partial_: True
316
+ _target_: training.utils.checkpoint_utils.load_state_dict_into_model
317
+ strict: True
318
+ ignore_unexpected_keys: null
319
+ ignore_missing_keys: null
320
+
321
+ state_dict:
322
+ _target_: training.utils.checkpoint_utils.load_checkpoint_and_apply_kernels
323
+ checkpoint_path: checkpoints/sam2.1_hiera_tiny.pt # PATH to SAM 2.1 checkpoint
324
+ ckpt_state_dict_keys: ['model']
325
+
326
+ launcher:
327
+ num_nodes: 1
328
+ gpus_per_node: 4
329
+ experiment_log_dir: exp_log # Path to log directory, defaults to ./sam2_logs/${config_name}
330
+
331
+ # SLURM args if running on a cluster
332
+ submitit:
333
+ partition: gpu_bwanggroup
334
+ account: null
335
+ qos: null
336
+ cpus_per_task: 10
337
+ use_cluster: false
338
+ timeout_hour: 24
339
+ name: null
340
+ port_range: [10000, 65000]
341
+
342
+
MedSAM2/sam2/configs/sam2.1_hiera_tiny_finetune512.yaml ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+
3
+ scratch:
4
+ resolution: 512
5
+ train_video_batch_size: 8
6
+ num_train_workers: 15
7
+ num_frames: 8
8
+ max_num_objects: 5
9
+ base_lr: 5.0e-5
10
+ vision_lr: 3.0e-05
11
+ phases_per_epoch: 1
12
+ num_epochs: 75
13
+
14
+ dataset:
15
+ # PATHS to Dataset
16
+ folder: # PATH to Med NPZ folder
17
+ multiplier: 1
18
+
19
+ # Video transforms
20
+ vos:
21
+ train_transforms:
22
+ - _target_: training.dataset.transforms.ComposeAPI
23
+ transforms:
24
+ - _target_: training.dataset.transforms.RandomHorizontalFlip
25
+ consistent_transform: True
26
+ - _target_: training.dataset.transforms.RandomAffine
27
+ degrees: 25
28
+ shear: 20
29
+ image_interpolation: bilinear
30
+ consistent_transform: True
31
+ - _target_: training.dataset.transforms.RandomResizeAPI
32
+ sizes: ${scratch.resolution}
33
+ square: true
34
+ consistent_transform: True
35
+ - _target_: training.dataset.transforms.ColorJitter
36
+ consistent_transform: True
37
+ brightness: 0.1
38
+ contrast: 0.03
39
+ saturation: 0.03
40
+ hue: null
41
+ - _target_: training.dataset.transforms.RandomGrayscale
42
+ p: 0.05
43
+ consistent_transform: True
44
+ - _target_: training.dataset.transforms.ColorJitter
45
+ consistent_transform: False
46
+ brightness: 0.1
47
+ contrast: 0.05
48
+ saturation: 0.05
49
+ hue: null
50
+ - _target_: training.dataset.transforms.ToTensorAPI
51
+ - _target_: training.dataset.transforms.NormalizeAPI
52
+ mean: [0.485, 0.456, 0.406]
53
+ std: [0.229, 0.224, 0.225]
54
+
55
+
56
+ trainer:
57
+ _target_: training.trainer.Trainer
58
+ mode: train_only
59
+ max_epochs: ${times:${scratch.num_epochs},${scratch.phases_per_epoch}}
60
+ accelerator: cuda
61
+ seed_value: 123
62
+
63
+ model:
64
+ _target_: training.model.sam2.SAM2Train
65
+ image_encoder:
66
+ _target_: sam2.modeling.backbones.image_encoder.ImageEncoder
67
+ scalp: 1
68
+ trunk:
69
+ _target_: sam2.modeling.backbones.hieradet.Hiera
70
+ embed_dim: 96
71
+ num_heads: 1
72
+ stages: [1, 2, 7, 2]
73
+ global_att_blocks: [5, 7, 9]
74
+ window_pos_embed_bkg_spatial_size: [7, 7]
75
+ neck:
76
+ _target_: sam2.modeling.backbones.image_encoder.FpnNeck
77
+ position_encoding:
78
+ _target_: sam2.modeling.position_encoding.PositionEmbeddingSine
79
+ num_pos_feats: 256
80
+ normalize: true
81
+ scale: null
82
+ temperature: 10000
83
+ d_model: 256
84
+ backbone_channel_list: [768, 384, 192, 96]
85
+ fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features
86
+ fpn_interp_model: nearest
87
+
88
+ memory_attention:
89
+ _target_: sam2.modeling.memory_attention.MemoryAttention
90
+ d_model: 256
91
+ pos_enc_at_input: true
92
+ layer:
93
+ _target_: sam2.modeling.memory_attention.MemoryAttentionLayer
94
+ activation: relu
95
+ dim_feedforward: 2048
96
+ dropout: 0.1
97
+ pos_enc_at_attn: false
98
+ self_attention:
99
+ _target_: sam2.modeling.sam.transformer.RoPEAttention
100
+ rope_theta: 10000.0
101
+ feat_sizes: [32, 32]
102
+ embedding_dim: 256
103
+ num_heads: 1
104
+ downsample_rate: 1
105
+ dropout: 0.1
106
+ d_model: 256
107
+ pos_enc_at_cross_attn_keys: true
108
+ pos_enc_at_cross_attn_queries: false
109
+ cross_attention:
110
+ _target_: sam2.modeling.sam.transformer.RoPEAttention
111
+ rope_theta: 10000.0
112
+ feat_sizes: [32, 32]
113
+ rope_k_repeat: True
114
+ embedding_dim: 256
115
+ num_heads: 1
116
+ downsample_rate: 1
117
+ dropout: 0.1
118
+ kv_in_dim: 64
119
+ num_layers: 4
120
+
121
+ memory_encoder:
122
+ _target_: sam2.modeling.memory_encoder.MemoryEncoder
123
+ out_dim: 64
124
+ position_encoding:
125
+ _target_: sam2.modeling.position_encoding.PositionEmbeddingSine
126
+ num_pos_feats: 64
127
+ normalize: true
128
+ scale: null
129
+ temperature: 10000
130
+ mask_downsampler:
131
+ _target_: sam2.modeling.memory_encoder.MaskDownSampler
132
+ kernel_size: 3
133
+ stride: 2
134
+ padding: 1
135
+ fuser:
136
+ _target_: sam2.modeling.memory_encoder.Fuser
137
+ layer:
138
+ _target_: sam2.modeling.memory_encoder.CXBlock
139
+ dim: 256
140
+ kernel_size: 7
141
+ padding: 3
142
+ layer_scale_init_value: 1e-6
143
+ use_dwconv: True # depth-wise convs
144
+ num_layers: 2
145
+
146
+ num_maskmem: 7
147
+ image_size: ${scratch.resolution}
148
+ # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask
149
+ # SAM decoder
150
+ sigmoid_scale_for_mem_enc: 20.0
151
+ sigmoid_bias_for_mem_enc: -10.0
152
+ use_mask_input_as_output_without_sam: true
153
+ # Memory
154
+ directly_add_no_mem_embed: true
155
+ no_obj_embed_spatial: true
156
+ # use high-resolution feature map in the SAM mask decoder
157
+ use_high_res_features_in_sam: true
158
+ # output 3 masks on the first click on initial conditioning frames
159
+ multimask_output_in_sam: true
160
+ # SAM heads
161
+ iou_prediction_use_sigmoid: True
162
+ # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder
163
+ use_obj_ptrs_in_encoder: true
164
+ add_tpos_enc_to_obj_ptrs: true
165
+ proj_tpos_enc_in_obj_ptrs: true
166
+ use_signed_tpos_enc_to_obj_ptrs: true
167
+ only_obj_ptrs_in_the_past_for_eval: true
168
+ # object occlusion prediction
169
+ pred_obj_scores: true
170
+ pred_obj_scores_mlp: true
171
+ fixed_no_obj_ptr: true
172
+ # multimask tracking settings
173
+ multimask_output_for_tracking: true
174
+ use_multimask_token_for_obj_ptr: true
175
+ multimask_min_pt_num: 0
176
+ multimask_max_pt_num: 1
177
+ use_mlp_for_obj_ptr_proj: true
178
+ # Compilation flag
179
+ # compile_image_encoder: False
180
+
181
+ ####### Training specific params #######
182
+ # box/point input and corrections
183
+ prob_to_use_pt_input_for_train: 0.5
184
+ prob_to_use_pt_input_for_eval: 0.0
185
+ prob_to_use_box_input_for_train: 1.0
186
+ prob_to_use_box_input_for_eval: 0.0
187
+ prob_to_sample_from_gt_for_train: 0.1 # with a small prob, sampling correction points from GT mask instead of prediction errors
188
+ num_frames_to_correct_for_train: 2 # iteratively sample on random 1~2 frames (always include the first frame)
189
+ num_frames_to_correct_for_eval: 1 # only iteratively sample on first frame
190
+ rand_frames_to_correct_for_train: True # random #init-cond-frame ~ 2
191
+ add_all_frames_to_correct_as_cond: True # when a frame receives a correction click, it becomes a conditioning frame (even if it's not initially a conditioning frame)
192
+ # maximum 2 initial conditioning frames
193
+ num_init_cond_frames_for_train: 2
194
+ rand_init_cond_frames_for_train: True # random 1~2
195
+ num_correction_pt_per_frame: 7
196
+ use_act_ckpt_iterative_pt_sampling: false
197
+
198
+
199
+
200
+ num_init_cond_frames_for_eval: 1 # only mask on the first frame
201
+ forward_backbone_per_frame_for_eval: True
202
+
203
+
204
+ data:
205
+ train:
206
+ _target_: training.dataset.sam2_datasets.TorchTrainMixedDataset
207
+ phases_per_epoch: ${scratch.phases_per_epoch}
208
+ batch_sizes:
209
+ - ${scratch.train_video_batch_size}
210
+ datasets:
211
+ - _target_: training.dataset.utils.RepeatFactorWrapper
212
+ dataset:
213
+ _target_: training.dataset.utils.ConcatDataset
214
+ datasets:
215
+ # CT
216
+ - _target_: training.dataset.vos_dataset.VOSDataset
217
+ transforms: ${vos.train_transforms}
218
+ training: true
219
+ video_dataset:
220
+ _target_: training.dataset.vos_raw_dataset.NPZRawDataset
221
+ folder: CVPR25/3D_train_npz_random_10percent_16G/CT
222
+ sampler:
223
+ _target_: training.dataset.vos_sampler.RandomUniformSampler
224
+ num_frames: ${scratch.num_frames}
225
+ max_num_objects: ${scratch.max_num_objects}
226
+ multiplier: 1
227
+ # MR
228
+ - _target_: training.dataset.vos_dataset.VOSDataset
229
+ transforms: ${vos.train_transforms}
230
+ training: true
231
+ video_dataset:
232
+ _target_: training.dataset.vos_raw_dataset.NPZRawDataset
233
+ folder: CVPR25/3D_train_npz_random_10percent_16G/MR
234
+ sampler:
235
+ _target_: training.dataset.vos_sampler.RandomUniformSampler
236
+ num_frames: ${scratch.num_frames}
237
+ max_num_objects: ${scratch.max_num_objects}
238
+ multiplier: 1
239
+ # PET
240
+ - _target_: training.dataset.vos_dataset.VOSDataset
241
+ transforms: ${vos.train_transforms}
242
+ training: true
243
+ video_dataset:
244
+ _target_: training.dataset.vos_raw_dataset.NPZRawDataset
245
+ folder: CVPR25/3D_train_npz_random_10percent_16G/PET
246
+ sampler:
247
+ _target_: training.dataset.vos_sampler.RandomUniformSampler
248
+ num_frames: ${scratch.num_frames}
249
+ max_num_objects: ${scratch.max_num_objects}
250
+ multiplier: 10
251
+ # Ultrasound 3D
252
+ - _target_: training.dataset.vos_dataset.VOSDataset
253
+ transforms: ${vos.train_transforms}
254
+ training: true
255
+ video_dataset:
256
+ _target_: training.dataset.vos_raw_dataset.NPZRawDataset
257
+ folder: CVPR25/3D_train_npz_random_10percent_16G/US3D
258
+ sampler:
259
+ _target_: training.dataset.vos_sampler.RandomUniformSampler
260
+ num_frames: ${scratch.num_frames}
261
+ max_num_objects: ${scratch.max_num_objects}
262
+ multiplier: 1
263
+ # Microscopy 3D
264
+ - _target_: training.dataset.vos_dataset.VOSDataset
265
+ transforms: ${vos.train_transforms}
266
+ training: true
267
+ video_dataset:
268
+ _target_: training.dataset.vos_raw_dataset.NPZRawDataset
269
+ folder: CVPR25/3D_train_npz_random_10percent_16G/Microscopy
270
+ sampler:
271
+ _target_: training.dataset.vos_sampler.RandomUniformSampler
272
+ num_frames: ${scratch.num_frames}
273
+ max_num_objects: ${scratch.max_num_objects}
274
+ multiplier: 1
275
+
276
+ shuffle: True
277
+ num_workers: ${scratch.num_train_workers}
278
+ pin_memory: True
279
+ drop_last: True
280
+ collate_fn:
281
+ _target_: training.utils.data_utils.collate_fn
282
+ _partial_: true
283
+ dict_key: all
284
+
285
+ optim:
286
+ amp:
287
+ enabled: True
288
+ amp_dtype: bfloat16
289
+
290
+ optimizer:
291
+ _target_: torch.optim.AdamW
292
+
293
+ gradient_clip:
294
+ _target_: training.optimizer.GradientClipper
295
+ max_norm: 0.1
296
+ norm_type: 2
297
+
298
+ param_group_modifiers:
299
+ - _target_: training.optimizer.layer_decay_param_modifier
300
+ _partial_: True
301
+ layer_decay_value: 0.9
302
+ apply_to: 'image_encoder.trunk'
303
+ overrides:
304
+ - pattern: '*pos_embed*'
305
+ value: 1.0
306
+
307
+ options:
308
+ lr:
309
+ - scheduler:
310
+ _target_: fvcore.common.param_scheduler.CosineParamScheduler
311
+ start_value: ${scratch.base_lr}
312
+ end_value: ${divide:${scratch.base_lr},10}
313
+ - scheduler:
314
+ _target_: fvcore.common.param_scheduler.CosineParamScheduler
315
+ start_value: ${scratch.vision_lr}
316
+ end_value: ${divide:${scratch.vision_lr},10}
317
+ param_names:
318
+ - 'image_encoder.*'
319
+ weight_decay:
320
+ - scheduler:
321
+ _target_: fvcore.common.param_scheduler.ConstantParamScheduler
322
+ value: 0.1
323
+ - scheduler:
324
+ _target_: fvcore.common.param_scheduler.ConstantParamScheduler
325
+ value: 0.0
326
+ param_names:
327
+ - '*bias*'
328
+ module_cls_names: ['torch.nn.LayerNorm']
329
+
330
+ loss:
331
+ all:
332
+ _target_: training.loss_fns.MultiStepMultiMasksAndIous
333
+ weight_dict:
334
+ loss_mask: 20
335
+ loss_dice: 1
336
+ loss_iou: 1
337
+ loss_class: 1
338
+ supervise_all_iou: true
339
+ iou_use_l1_loss: true
340
+ pred_obj_scores: true
341
+ focal_gamma_obj_score: 0.0
342
+ focal_alpha_obj_score: -1.0
343
+
344
+ distributed:
345
+ backend: nccl # gloo or nccl
346
+ find_unused_parameters: True
347
+
348
+ logging:
349
+ tensorboard_writer:
350
+ _target_: training.utils.logger.make_tensorboard_logger
351
+ log_dir: ${launcher.experiment_log_dir}/tensorboard
352
+ flush_secs: 120
353
+ should_log: True
354
+ log_dir: ${launcher.experiment_log_dir}/logs
355
+ log_freq: 10
356
+
357
+ # initialize from a SAM 2 checkpoint
358
+ checkpoint:
359
+ save_dir: ${launcher.experiment_log_dir}/checkpoints
360
+ save_freq: 10 # 0 only last checkpoint is saved.
361
+ model_weight_initializer:
362
+ _partial_: True
363
+ _target_: training.utils.checkpoint_utils.load_state_dict_into_model
364
+ strict: True
365
+ ignore_unexpected_keys: null
366
+ ignore_missing_keys: null
367
+
368
+ state_dict:
369
+ _target_: training.utils.checkpoint_utils.load_checkpoint_and_apply_kernels
370
+ checkpoint_path: checkpoints/sam2.1_hiera_tiny.pt # PATH to SAM 2.1 checkpoint
371
+ ckpt_state_dict_keys: ['model']
372
+
373
+ launcher:
374
+ num_nodes: 1
375
+ gpus_per_node: 4
376
+ experiment_log_dir: exp_log # Path to log directory, defaults to ./sam2_logs/${config_name}
377
+
378
+ # SLURM args if running on a cluster
379
+ submitit:
380
+ partition: gpu_bwanggroup
381
+ account: null
382
+ qos: null
383
+ cpus_per_task: 10
384
+ use_cluster: false
385
+ timeout_hour: 24
386
+ name: null
387
+ port_range: [10000, 65000]
388
+
389
+
MedSAM2/sam2/csrc/connected_components.cu ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ // All rights reserved.
3
+
4
+ // This source code is licensed under the license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ // adapted from https://github.com/zsef123/Connected_components_PyTorch
8
+ // with license found in the LICENSE_cctorch file in the root directory.
9
+ #include <ATen/cuda/CUDAContext.h>
10
+ #include <cuda.h>
11
+ #include <cuda_runtime.h>
12
+ #include <torch/extension.h>
13
+ #include <torch/script.h>
14
+ #include <vector>
15
+
16
+ // 2d
17
+ #define BLOCK_ROWS 16
18
+ #define BLOCK_COLS 16
19
+
20
+ namespace cc2d {
21
+
22
+ template <typename T>
23
+ __device__ __forceinline__ unsigned char hasBit(T bitmap, unsigned char pos) {
24
+ return (bitmap >> pos) & 1;
25
+ }
26
+
27
+ __device__ int32_t find(const int32_t* s_buf, int32_t n) {
28
+ while (s_buf[n] != n)
29
+ n = s_buf[n];
30
+ return n;
31
+ }
32
+
33
+ __device__ int32_t find_n_compress(int32_t* s_buf, int32_t n) {
34
+ const int32_t id = n;
35
+ while (s_buf[n] != n) {
36
+ n = s_buf[n];
37
+ s_buf[id] = n;
38
+ }
39
+ return n;
40
+ }
41
+
42
+ __device__ void union_(int32_t* s_buf, int32_t a, int32_t b) {
43
+ bool done;
44
+ do {
45
+ a = find(s_buf, a);
46
+ b = find(s_buf, b);
47
+
48
+ if (a < b) {
49
+ int32_t old = atomicMin(s_buf + b, a);
50
+ done = (old == b);
51
+ b = old;
52
+ } else if (b < a) {
53
+ int32_t old = atomicMin(s_buf + a, b);
54
+ done = (old == a);
55
+ a = old;
56
+ } else
57
+ done = true;
58
+
59
+ } while (!done);
60
+ }
61
+
62
+ __global__ void
63
+ init_labeling(int32_t* label, const uint32_t W, const uint32_t H) {
64
+ const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y) * 2;
65
+ const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x) * 2;
66
+ const uint32_t idx = row * W + col;
67
+
68
+ if (row < H && col < W)
69
+ label[idx] = idx;
70
+ }
71
+
72
+ __global__ void
73
+ merge(uint8_t* img, int32_t* label, const uint32_t W, const uint32_t H) {
74
+ const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y) * 2;
75
+ const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x) * 2;
76
+ const uint32_t idx = row * W + col;
77
+
78
+ if (row >= H || col >= W)
79
+ return;
80
+
81
+ uint32_t P = 0;
82
+
83
+ if (img[idx])
84
+ P |= 0x777;
85
+ if (row + 1 < H && img[idx + W])
86
+ P |= 0x777 << 4;
87
+ if (col + 1 < W && img[idx + 1])
88
+ P |= 0x777 << 1;
89
+
90
+ if (col == 0)
91
+ P &= 0xEEEE;
92
+ if (col + 1 >= W)
93
+ P &= 0x3333;
94
+ else if (col + 2 >= W)
95
+ P &= 0x7777;
96
+
97
+ if (row == 0)
98
+ P &= 0xFFF0;
99
+ if (row + 1 >= H)
100
+ P &= 0xFF;
101
+
102
+ if (P > 0) {
103
+ // If need check about top-left pixel(if flag the first bit) and hit the
104
+ // top-left pixel
105
+ if (hasBit(P, 0) && img[idx - W - 1]) {
106
+ union_(label, idx, idx - 2 * W - 2); // top left block
107
+ }
108
+
109
+ if ((hasBit(P, 1) && img[idx - W]) || (hasBit(P, 2) && img[idx - W + 1]))
110
+ union_(label, idx, idx - 2 * W); // top bottom block
111
+
112
+ if (hasBit(P, 3) && img[idx + 2 - W])
113
+ union_(label, idx, idx - 2 * W + 2); // top right block
114
+
115
+ if ((hasBit(P, 4) && img[idx - 1]) || (hasBit(P, 8) && img[idx + W - 1]))
116
+ union_(label, idx, idx - 2); // just left block
117
+ }
118
+ }
119
+
120
+ __global__ void compression(int32_t* label, const int32_t W, const int32_t H) {
121
+ const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y) * 2;
122
+ const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x) * 2;
123
+ const uint32_t idx = row * W + col;
124
+
125
+ if (row < H && col < W)
126
+ find_n_compress(label, idx);
127
+ }
128
+
129
+ __global__ void final_labeling(
130
+ const uint8_t* img,
131
+ int32_t* label,
132
+ const int32_t W,
133
+ const int32_t H) {
134
+ const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y) * 2;
135
+ const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x) * 2;
136
+ const uint32_t idx = row * W + col;
137
+
138
+ if (row >= H || col >= W)
139
+ return;
140
+
141
+ int32_t y = label[idx] + 1;
142
+
143
+ if (img[idx])
144
+ label[idx] = y;
145
+ else
146
+ label[idx] = 0;
147
+
148
+ if (col + 1 < W) {
149
+ if (img[idx + 1])
150
+ label[idx + 1] = y;
151
+ else
152
+ label[idx + 1] = 0;
153
+
154
+ if (row + 1 < H) {
155
+ if (img[idx + W + 1])
156
+ label[idx + W + 1] = y;
157
+ else
158
+ label[idx + W + 1] = 0;
159
+ }
160
+ }
161
+
162
+ if (row + 1 < H) {
163
+ if (img[idx + W])
164
+ label[idx + W] = y;
165
+ else
166
+ label[idx + W] = 0;
167
+ }
168
+ }
169
+
170
+ __global__ void init_counting(
171
+ const int32_t* label,
172
+ int32_t* count_init,
173
+ const int32_t W,
174
+ const int32_t H) {
175
+ const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y);
176
+ const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x);
177
+ const uint32_t idx = row * W + col;
178
+
179
+ if (row >= H || col >= W)
180
+ return;
181
+
182
+ int32_t y = label[idx];
183
+ if (y > 0) {
184
+ int32_t count_idx = y - 1;
185
+ atomicAdd(count_init + count_idx, 1);
186
+ }
187
+ }
188
+
189
+ __global__ void final_counting(
190
+ const int32_t* label,
191
+ const int32_t* count_init,
192
+ int32_t* count_final,
193
+ const int32_t W,
194
+ const int32_t H) {
195
+ const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y);
196
+ const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x);
197
+ const uint32_t idx = row * W + col;
198
+
199
+ if (row >= H || col >= W)
200
+ return;
201
+
202
+ int32_t y = label[idx];
203
+ if (y > 0) {
204
+ int32_t count_idx = y - 1;
205
+ count_final[idx] = count_init[count_idx];
206
+ } else {
207
+ count_final[idx] = 0;
208
+ }
209
+ }
210
+
211
+ } // namespace cc2d
212
+
213
+ std::vector<torch::Tensor> get_connected_componnets(
214
+ const torch::Tensor& inputs) {
215
+ AT_ASSERTM(inputs.is_cuda(), "inputs must be a CUDA tensor");
216
+ AT_ASSERTM(inputs.ndimension() == 4, "inputs must be [N, 1, H, W] shape");
217
+ AT_ASSERTM(
218
+ inputs.scalar_type() == torch::kUInt8, "inputs must be a uint8 type");
219
+
220
+ const uint32_t N = inputs.size(0);
221
+ const uint32_t C = inputs.size(1);
222
+ const uint32_t H = inputs.size(2);
223
+ const uint32_t W = inputs.size(3);
224
+
225
+ AT_ASSERTM(C == 1, "inputs must be [N, 1, H, W] shape");
226
+ AT_ASSERTM((H % 2) == 0, "height must be an even number");
227
+ AT_ASSERTM((W % 2) == 0, "width must be an even number");
228
+
229
+ // label must be uint32_t
230
+ auto label_options =
231
+ torch::TensorOptions().dtype(torch::kInt32).device(inputs.device());
232
+ torch::Tensor labels = torch::zeros({N, C, H, W}, label_options);
233
+ torch::Tensor counts_init = torch::zeros({N, C, H, W}, label_options);
234
+ torch::Tensor counts_final = torch::zeros({N, C, H, W}, label_options);
235
+
236
+ dim3 grid = dim3(
237
+ ((W + 1) / 2 + BLOCK_COLS - 1) / BLOCK_COLS,
238
+ ((H + 1) / 2 + BLOCK_ROWS - 1) / BLOCK_ROWS);
239
+ dim3 block = dim3(BLOCK_COLS, BLOCK_ROWS);
240
+ dim3 grid_count =
241
+ dim3((W + BLOCK_COLS) / BLOCK_COLS, (H + BLOCK_ROWS) / BLOCK_ROWS);
242
+ dim3 block_count = dim3(BLOCK_COLS, BLOCK_ROWS);
243
+ cudaStream_t stream = at::cuda::getCurrentCUDAStream();
244
+
245
+ for (int n = 0; n < N; n++) {
246
+ uint32_t offset = n * H * W;
247
+
248
+ cc2d::init_labeling<<<grid, block, 0, stream>>>(
249
+ labels.data_ptr<int32_t>() + offset, W, H);
250
+ cc2d::merge<<<grid, block, 0, stream>>>(
251
+ inputs.data_ptr<uint8_t>() + offset,
252
+ labels.data_ptr<int32_t>() + offset,
253
+ W,
254
+ H);
255
+ cc2d::compression<<<grid, block, 0, stream>>>(
256
+ labels.data_ptr<int32_t>() + offset, W, H);
257
+ cc2d::final_labeling<<<grid, block, 0, stream>>>(
258
+ inputs.data_ptr<uint8_t>() + offset,
259
+ labels.data_ptr<int32_t>() + offset,
260
+ W,
261
+ H);
262
+
263
+ // get the counting of each pixel
264
+ cc2d::init_counting<<<grid_count, block_count, 0, stream>>>(
265
+ labels.data_ptr<int32_t>() + offset,
266
+ counts_init.data_ptr<int32_t>() + offset,
267
+ W,
268
+ H);
269
+ cc2d::final_counting<<<grid_count, block_count, 0, stream>>>(
270
+ labels.data_ptr<int32_t>() + offset,
271
+ counts_init.data_ptr<int32_t>() + offset,
272
+ counts_final.data_ptr<int32_t>() + offset,
273
+ W,
274
+ H);
275
+ }
276
+
277
+ // returned values are [labels, counts]
278
+ std::vector<torch::Tensor> outputs;
279
+ outputs.push_back(labels);
280
+ outputs.push_back(counts_final);
281
+ return outputs;
282
+ }
283
+
284
+ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
285
+ m.def(
286
+ "get_connected_componnets",
287
+ &get_connected_componnets,
288
+ "get_connected_componnets");
289
+ }
MedSAM2/sam2/modeling/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
MedSAM2/sam2/modeling/backbones/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
MedSAM2/sam2/modeling/backbones/hieradet.py ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import logging
8
+ from functools import partial
9
+ from typing import List, Tuple, Union
10
+
11
+ import torch
12
+ import torch.nn as nn
13
+ import torch.nn.functional as F
14
+ from iopath.common.file_io import g_pathmgr
15
+
16
+ from sam2.modeling.backbones.utils import (
17
+ PatchEmbed,
18
+ window_partition,
19
+ window_unpartition,
20
+ )
21
+
22
+ from sam2.modeling.sam2_utils import DropPath, MLP
23
+
24
+
25
+ def do_pool(x: torch.Tensor, pool: nn.Module, norm: nn.Module = None) -> torch.Tensor:
26
+ if pool is None:
27
+ return x
28
+ # (B, H, W, C) -> (B, C, H, W)
29
+ x = x.permute(0, 3, 1, 2)
30
+ x = pool(x)
31
+ # (B, C, H', W') -> (B, H', W', C)
32
+ x = x.permute(0, 2, 3, 1)
33
+ if norm:
34
+ x = norm(x)
35
+
36
+ return x
37
+
38
+
39
+ class MultiScaleAttention(nn.Module):
40
+ def __init__(
41
+ self,
42
+ dim: int,
43
+ dim_out: int,
44
+ num_heads: int,
45
+ q_pool: nn.Module = None,
46
+ ):
47
+ super().__init__()
48
+
49
+ self.dim = dim
50
+ self.dim_out = dim_out
51
+ self.num_heads = num_heads
52
+ self.q_pool = q_pool
53
+ self.qkv = nn.Linear(dim, dim_out * 3)
54
+ self.proj = nn.Linear(dim_out, dim_out)
55
+
56
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
57
+ B, H, W, _ = x.shape
58
+ # qkv with shape (B, H * W, 3, nHead, C)
59
+ qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1)
60
+ # q, k, v with shape (B, H * W, nheads, C)
61
+ q, k, v = torch.unbind(qkv, 2)
62
+
63
+ # Q pooling (for downsample at stage changes)
64
+ if self.q_pool:
65
+ q = do_pool(q.reshape(B, H, W, -1), self.q_pool)
66
+ H, W = q.shape[1:3] # downsampled shape
67
+ q = q.reshape(B, H * W, self.num_heads, -1)
68
+
69
+ # Torch's SDPA expects [B, nheads, H*W, C] so we transpose
70
+ x = F.scaled_dot_product_attention(
71
+ q.transpose(1, 2),
72
+ k.transpose(1, 2),
73
+ v.transpose(1, 2),
74
+ )
75
+ # Transpose back
76
+ x = x.transpose(1, 2)
77
+ x = x.reshape(B, H, W, -1)
78
+
79
+ x = self.proj(x)
80
+
81
+ return x
82
+
83
+
84
+ class MultiScaleBlock(nn.Module):
85
+ def __init__(
86
+ self,
87
+ dim: int,
88
+ dim_out: int,
89
+ num_heads: int,
90
+ mlp_ratio: float = 4.0,
91
+ drop_path: float = 0.0,
92
+ norm_layer: Union[nn.Module, str] = "LayerNorm",
93
+ q_stride: Tuple[int, int] = None,
94
+ act_layer: nn.Module = nn.GELU,
95
+ window_size: int = 0,
96
+ ):
97
+ super().__init__()
98
+
99
+ if isinstance(norm_layer, str):
100
+ norm_layer = partial(getattr(nn, norm_layer), eps=1e-6)
101
+
102
+ self.dim = dim
103
+ self.dim_out = dim_out
104
+ self.norm1 = norm_layer(dim)
105
+
106
+ self.window_size = window_size
107
+
108
+ self.pool, self.q_stride = None, q_stride
109
+ if self.q_stride:
110
+ self.pool = nn.MaxPool2d(
111
+ kernel_size=q_stride, stride=q_stride, ceil_mode=False
112
+ )
113
+
114
+ self.attn = MultiScaleAttention(
115
+ dim,
116
+ dim_out,
117
+ num_heads=num_heads,
118
+ q_pool=self.pool,
119
+ )
120
+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
121
+
122
+ self.norm2 = norm_layer(dim_out)
123
+ self.mlp = MLP(
124
+ dim_out,
125
+ int(dim_out * mlp_ratio),
126
+ dim_out,
127
+ num_layers=2,
128
+ activation=act_layer,
129
+ )
130
+
131
+ if dim != dim_out:
132
+ self.proj = nn.Linear(dim, dim_out)
133
+
134
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
135
+ shortcut = x # B, H, W, C
136
+ x = self.norm1(x)
137
+
138
+ # Skip connection
139
+ if self.dim != self.dim_out:
140
+ shortcut = do_pool(self.proj(x), self.pool)
141
+
142
+ # Window partition
143
+ window_size = self.window_size
144
+ if window_size > 0:
145
+ H, W = x.shape[1], x.shape[2]
146
+ x, pad_hw = window_partition(x, window_size)
147
+
148
+ # Window Attention + Q Pooling (if stage change)
149
+ x = self.attn(x)
150
+ if self.q_stride:
151
+ # Shapes have changed due to Q pooling
152
+ window_size = self.window_size // self.q_stride[0]
153
+ H, W = shortcut.shape[1:3]
154
+
155
+ pad_h = (window_size - H % window_size) % window_size
156
+ pad_w = (window_size - W % window_size) % window_size
157
+ pad_hw = (H + pad_h, W + pad_w)
158
+
159
+ # Reverse window partition
160
+ if self.window_size > 0:
161
+ x = window_unpartition(x, window_size, pad_hw, (H, W))
162
+
163
+ x = shortcut + self.drop_path(x)
164
+ # MLP
165
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
166
+ return x
167
+
168
+
169
+ class Hiera(nn.Module):
170
+ """
171
+ Reference: https://arxiv.org/abs/2306.00989
172
+ """
173
+
174
+ def __init__(
175
+ self,
176
+ embed_dim: int = 96, # initial embed dim
177
+ num_heads: int = 1, # initial number of heads
178
+ drop_path_rate: float = 0.0, # stochastic depth
179
+ q_pool: int = 3, # number of q_pool stages
180
+ q_stride: Tuple[int, int] = (2, 2), # downsample stride bet. stages
181
+ stages: Tuple[int, ...] = (2, 3, 16, 3), # blocks per stage
182
+ dim_mul: float = 2.0, # dim_mul factor at stage shift
183
+ head_mul: float = 2.0, # head_mul factor at stage shift
184
+ window_pos_embed_bkg_spatial_size: Tuple[int, int] = (14, 14),
185
+ # window size per stage, when not using global att.
186
+ window_spec: Tuple[int, ...] = (
187
+ 8,
188
+ 4,
189
+ 14,
190
+ 7,
191
+ ),
192
+ # global attn in these blocks
193
+ global_att_blocks: Tuple[int, ...] = (
194
+ 12,
195
+ 16,
196
+ 20,
197
+ ),
198
+ weights_path=None,
199
+ return_interm_layers=True, # return feats from every stage
200
+ ):
201
+ super().__init__()
202
+
203
+ assert len(stages) == len(window_spec)
204
+ self.window_spec = window_spec
205
+
206
+ depth = sum(stages)
207
+ self.q_stride = q_stride
208
+ self.stage_ends = [sum(stages[:i]) - 1 for i in range(1, len(stages) + 1)]
209
+ assert 0 <= q_pool <= len(self.stage_ends[:-1])
210
+ self.q_pool_blocks = [x + 1 for x in self.stage_ends[:-1]][:q_pool]
211
+ self.return_interm_layers = return_interm_layers
212
+
213
+ self.patch_embed = PatchEmbed(
214
+ embed_dim=embed_dim,
215
+ )
216
+ # Which blocks have global att?
217
+ self.global_att_blocks = global_att_blocks
218
+
219
+ # Windowed positional embedding (https://arxiv.org/abs/2311.05613)
220
+ self.window_pos_embed_bkg_spatial_size = window_pos_embed_bkg_spatial_size
221
+ self.pos_embed = nn.Parameter(
222
+ torch.zeros(1, embed_dim, *self.window_pos_embed_bkg_spatial_size)
223
+ )
224
+ self.pos_embed_window = nn.Parameter(
225
+ torch.zeros(1, embed_dim, self.window_spec[0], self.window_spec[0])
226
+ )
227
+
228
+ dpr = [
229
+ x.item() for x in torch.linspace(0, drop_path_rate, depth)
230
+ ] # stochastic depth decay rule
231
+
232
+ cur_stage = 1
233
+ self.blocks = nn.ModuleList()
234
+
235
+ for i in range(depth):
236
+ dim_out = embed_dim
237
+ # lags by a block, so first block of
238
+ # next stage uses an initial window size
239
+ # of previous stage and final window size of current stage
240
+ window_size = self.window_spec[cur_stage - 1]
241
+
242
+ if self.global_att_blocks is not None:
243
+ window_size = 0 if i in self.global_att_blocks else window_size
244
+
245
+ if i - 1 in self.stage_ends:
246
+ dim_out = int(embed_dim * dim_mul)
247
+ num_heads = int(num_heads * head_mul)
248
+ cur_stage += 1
249
+
250
+ block = MultiScaleBlock(
251
+ dim=embed_dim,
252
+ dim_out=dim_out,
253
+ num_heads=num_heads,
254
+ drop_path=dpr[i],
255
+ q_stride=self.q_stride if i in self.q_pool_blocks else None,
256
+ window_size=window_size,
257
+ )
258
+
259
+ embed_dim = dim_out
260
+ self.blocks.append(block)
261
+
262
+ self.channel_list = (
263
+ [self.blocks[i].dim_out for i in self.stage_ends[::-1]]
264
+ if return_interm_layers
265
+ else [self.blocks[-1].dim_out]
266
+ )
267
+
268
+ if weights_path is not None:
269
+ with g_pathmgr.open(weights_path, "rb") as f:
270
+ chkpt = torch.load(f, map_location="cpu")
271
+ logging.info("loading Hiera", self.load_state_dict(chkpt, strict=False))
272
+
273
+ def _get_pos_embed(self, hw: Tuple[int, int]) -> torch.Tensor:
274
+ h, w = hw
275
+ window_embed = self.pos_embed_window
276
+ pos_embed = F.interpolate(self.pos_embed, size=(h, w), mode="bicubic")
277
+ pos_embed = pos_embed + window_embed.tile(
278
+ [x // y for x, y in zip(pos_embed.shape, window_embed.shape)]
279
+ )
280
+ pos_embed = pos_embed.permute(0, 2, 3, 1)
281
+ return pos_embed
282
+
283
+ def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
284
+ x = self.patch_embed(x)
285
+ # x: (B, H, W, C)
286
+
287
+ # Add pos embed
288
+ x = x + self._get_pos_embed(x.shape[1:3])
289
+
290
+ outputs = []
291
+ for i, blk in enumerate(self.blocks):
292
+ x = blk(x)
293
+ if (i == self.stage_ends[-1]) or (
294
+ i in self.stage_ends and self.return_interm_layers
295
+ ):
296
+ feats = x.permute(0, 3, 1, 2)
297
+ outputs.append(feats)
298
+
299
+ return outputs
300
+
301
+ def get_layer_id(self, layer_name):
302
+ # https://github.com/microsoft/unilm/blob/master/beit/optim_factory.py#L33
303
+ num_layers = self.get_num_layers()
304
+
305
+ if layer_name.find("rel_pos") != -1:
306
+ return num_layers + 1
307
+ elif layer_name.find("pos_embed") != -1:
308
+ return 0
309
+ elif layer_name.find("patch_embed") != -1:
310
+ return 0
311
+ elif layer_name.find("blocks") != -1:
312
+ return int(layer_name.split("blocks")[1].split(".")[1]) + 1
313
+ else:
314
+ return num_layers + 1
315
+
316
+ def get_num_layers(self) -> int:
317
+ return len(self.blocks)
MedSAM2/sam2/modeling/backbones/image_encoder.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from typing import List, Optional
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+ from sam2.modeling.efficienttam_utils import LayerNorm2d
13
+
14
+
15
+
16
+ class ImageEncoder(nn.Module):
17
+ def __init__(
18
+ self,
19
+ trunk: nn.Module,
20
+ neck: nn.Module,
21
+ scalp: int = 0,
22
+ ):
23
+ super().__init__()
24
+ self.trunk = trunk
25
+ self.neck = neck
26
+ self.scalp = scalp
27
+ assert (
28
+ self.trunk.channel_list == self.neck.backbone_channel_list
29
+ ), f"Channel dims of trunk and neck do not match. Trunk: {self.trunk.channel_list}, neck: {self.neck.backbone_channel_list}"
30
+
31
+ def forward(self, sample: torch.Tensor):
32
+ # Forward through backbone
33
+ features, pos = self.neck(self.trunk(sample))
34
+ if self.scalp > 0:
35
+ # Discard the lowest resolution features
36
+ features, pos = features[: -self.scalp], pos[: -self.scalp]
37
+
38
+ src = features[-1]
39
+ output = {
40
+ "vision_features": src,
41
+ "vision_pos_enc": pos,
42
+ "backbone_fpn": features,
43
+ }
44
+ return output
45
+
46
+
47
+ class FpnNeck(nn.Module):
48
+ """
49
+ A modified variant of Feature Pyramid Network (FPN) neck
50
+ (we remove output conv and also do bicubic interpolation similar to ViT
51
+ pos embed interpolation)
52
+ """
53
+
54
+ def __init__(
55
+ self,
56
+ position_encoding: nn.Module,
57
+ d_model: int,
58
+ backbone_channel_list: List[int],
59
+ kernel_size: int = 1,
60
+ stride: int = 1,
61
+ padding: int = 0,
62
+ fpn_interp_model: str = "bilinear",
63
+ fuse_type: str = "sum",
64
+ fpn_top_down_levels: Optional[List[int]] = None,
65
+ ):
66
+ """Initialize the neck
67
+ :param trunk: the backbone
68
+ :param position_encoding: the positional encoding to use
69
+ :param d_model: the dimension of the model
70
+ :param neck_norm: the normalization to use
71
+ """
72
+ super().__init__()
73
+ self.position_encoding = position_encoding
74
+ self.convs = nn.ModuleList()
75
+ self.backbone_channel_list = backbone_channel_list
76
+ self.d_model = d_model
77
+ for dim in backbone_channel_list:
78
+ current = nn.Sequential()
79
+ current.add_module(
80
+ "conv",
81
+ nn.Conv2d(
82
+ in_channels=dim,
83
+ out_channels=d_model,
84
+ kernel_size=kernel_size,
85
+ stride=stride,
86
+ padding=padding,
87
+ ),
88
+ )
89
+
90
+ self.convs.append(current)
91
+ self.fpn_interp_model = fpn_interp_model
92
+ assert fuse_type in ["sum", "avg"]
93
+ self.fuse_type = fuse_type
94
+
95
+ # levels to have top-down features in its outputs
96
+ # e.g. if fpn_top_down_levels is [2, 3], then only outputs of level 2 and 3
97
+ # have top-down propagation, while outputs of level 0 and level 1 have only
98
+ # lateral features from the same backbone level.
99
+ if fpn_top_down_levels is None:
100
+ # default is to have top-down features on all levels
101
+ fpn_top_down_levels = range(len(self.convs))
102
+ self.fpn_top_down_levels = list(fpn_top_down_levels)
103
+
104
+ def forward(self, xs: List[torch.Tensor]):
105
+
106
+ out = [None] * len(self.convs)
107
+ pos = [None] * len(self.convs)
108
+ assert len(xs) == len(self.convs)
109
+ # fpn forward pass
110
+ # see https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/fpn.py
111
+ prev_features = None
112
+ # forward in top-down order (from low to high resolution)
113
+ n = len(self.convs) - 1
114
+ for i in range(n, -1, -1):
115
+ x = xs[i]
116
+ lateral_features = self.convs[n - i](x)
117
+ if i in self.fpn_top_down_levels and prev_features is not None:
118
+ top_down_features = F.interpolate(
119
+ prev_features.to(dtype=torch.float32),
120
+ scale_factor=2.0,
121
+ mode=self.fpn_interp_model,
122
+ align_corners=(
123
+ None if self.fpn_interp_model == "nearest" else False
124
+ ),
125
+ antialias=False,
126
+ )
127
+ prev_features = lateral_features + top_down_features
128
+ if self.fuse_type == "avg":
129
+ prev_features /= 2
130
+ else:
131
+ prev_features = lateral_features
132
+ x_out = prev_features
133
+ out[i] = x_out
134
+ pos[i] = self.position_encoding(x_out).to(x_out.dtype)
135
+
136
+ return out, pos
137
+
138
+
139
+ class ViTDetNeck(nn.Module):
140
+ def __init__(
141
+ self,
142
+ position_encoding: nn.Module,
143
+ d_model: int,
144
+ backbone_channel_list: List[int],
145
+ kernel_size: int = 1,
146
+ stride: int = 1,
147
+ padding: int = 0,
148
+ neck_norm=None,
149
+ ):
150
+ """Initialize the neck
151
+
152
+ :param trunk: the backbone
153
+ :param position_encoding: the positional encoding to use
154
+ :param d_model: the dimension of the model
155
+ :param neck_norm: the normalization to use
156
+ """
157
+ super().__init__()
158
+ self.backbone_channel_list = backbone_channel_list
159
+ self.position_encoding = position_encoding
160
+ self.convs = nn.ModuleList()
161
+ self.d_model = d_model
162
+ use_bias = neck_norm is None
163
+ for dim in self.backbone_channel_list:
164
+ current = nn.Sequential()
165
+ current.add_module(
166
+ "conv_1x1",
167
+ nn.Conv2d(
168
+ in_channels=dim,
169
+ out_channels=d_model,
170
+ kernel_size=1,
171
+ bias=use_bias,
172
+ ),
173
+ )
174
+ if neck_norm is not None:
175
+ current.add_module("norm_0", LayerNorm2d(d_model))
176
+ current.add_module(
177
+ "conv_3x3",
178
+ nn.Conv2d(
179
+ in_channels=d_model,
180
+ out_channels=d_model,
181
+ kernel_size=3,
182
+ padding=1,
183
+ bias=use_bias,
184
+ ),
185
+ )
186
+ if neck_norm is not None:
187
+ current.add_module("norm_1", LayerNorm2d(d_model))
188
+ self.convs.append(current)
189
+
190
+ def forward(self, xs: List[torch.Tensor]):
191
+ out = [None] * len(self.convs)
192
+ pos = [None] * len(self.convs)
193
+ assert len(xs) == len(self.convs)
194
+
195
+ x = xs[0]
196
+ x_out = self.convs[0](x)
197
+ out[0] = x_out
198
+ pos[0] = self.position_encoding(x_out).to(x_out.dtype)
199
+
200
+ return out, pos
201
+
202
+
MedSAM2/sam2/modeling/backbones/utils.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """Some utilities for backbones, in particular for windowing"""
8
+
9
+ from typing import Tuple
10
+
11
+ import torch
12
+ import torch.nn as nn
13
+ import torch.nn.functional as F
14
+
15
+ import math
16
+
17
+ def window_partition(x, window_size):
18
+ """
19
+ Partition into non-overlapping windows with padding if needed.
20
+ Args:
21
+ x (tensor): input tokens with [B, H, W, C].
22
+ window_size (int): window size.
23
+ Returns:
24
+ windows: windows after partition with [B * num_windows, window_size, window_size, C].
25
+ (Hp, Wp): padded height and width before partition
26
+ """
27
+ B, H, W, C = x.shape
28
+
29
+ pad_h = (window_size - H % window_size) % window_size
30
+ pad_w = (window_size - W % window_size) % window_size
31
+ if pad_h > 0 or pad_w > 0:
32
+ x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h))
33
+ Hp, Wp = H + pad_h, W + pad_w
34
+
35
+ x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C)
36
+ windows = x.permute(0, 1, 3, 2, 4, 5).reshape(-1, window_size, window_size, C)
37
+ return windows, (Hp, Wp)
38
+
39
+
40
+ def window_unpartition(windows, window_size, pad_hw, hw):
41
+ """
42
+ Window unpartition into original sequences and removing padding.
43
+ Args:
44
+ x (tensor): input tokens with [B * num_windows, window_size, window_size, C].
45
+ window_size (int): window size.
46
+ pad_hw (Tuple): padded height and width (Hp, Wp).
47
+ hw (Tuple): original height and width (H, W) before padding.
48
+ Returns:
49
+ x: unpartitioned sequences with [B, H, W, C].
50
+ """
51
+ Hp, Wp = pad_hw
52
+ H, W = hw
53
+ B = windows.shape[0] // (Hp * Wp // window_size // window_size)
54
+ x = windows.reshape(
55
+ B, Hp // window_size, Wp // window_size, window_size, window_size, -1
56
+ )
57
+ x = x.permute(0, 1, 3, 2, 4, 5).reshape(B, Hp, Wp, -1)
58
+
59
+ if Hp > H or Wp > W:
60
+ x = x[:, :H, :W, :]
61
+ return x
62
+
63
+
64
+ class PatchEmbed(nn.Module):
65
+ """
66
+ Image to Patch Embedding.
67
+ """
68
+
69
+ def __init__(
70
+ self,
71
+ kernel_size: Tuple[int, ...] = (7, 7),
72
+ stride: Tuple[int, ...] = (4, 4),
73
+ padding: Tuple[int, ...] = (3, 3),
74
+ in_chans: int = 3,
75
+ embed_dim: int = 768,
76
+ ):
77
+ """
78
+ Args:
79
+ kernel_size (Tuple): kernel size of the projection layer.
80
+ stride (Tuple): stride of the projection layer.
81
+ padding (Tuple): padding size of the projection layer.
82
+ in_chans (int): Number of input image channels.
83
+ embed_dim (int): embed_dim (int): Patch embedding dimension.
84
+ """
85
+ super().__init__()
86
+ self.proj = nn.Conv2d(
87
+ in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding
88
+ )
89
+
90
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
91
+ x = self.proj(x)
92
+ # B C H W -> B H W C
93
+ x = x.permute(0, 2, 3, 1)
94
+ return x
95
+
96
+
97
+ def get_abs_pos(abs_pos, has_cls_token, hw):
98
+ """
99
+ Calculate absolute positional embeddings. If needed, resize embeddings and remove cls_token
100
+ dimension for the original embeddings.
101
+ Args:
102
+ abs_pos (Tensor): absolute positional embeddings with (1, num_position, C).
103
+ has_cls_token (bool): If true, has 1 embedding in abs_pos for cls token.
104
+ hw (Tuple): size of input image tokens.
105
+ Returns:
106
+ Absolute positional embeddings after processing with shape (1, H, W, C)
107
+ """
108
+ h, w = hw
109
+ if has_cls_token:
110
+ abs_pos = abs_pos[:, 1:]
111
+ xy_num = abs_pos.shape[1]
112
+ size = int(math.sqrt(xy_num))
113
+ assert size * size == xy_num
114
+
115
+ if size != h or size != w:
116
+ interpolate_mode = "bicubic"
117
+ if not torch.cuda.is_available() and torch.mps.is_available():
118
+ # bicubic is not supported on torch mps
119
+ interpolate_mode = "bilinear"
120
+ new_abs_pos = F.interpolate(
121
+ abs_pos.reshape(1, size, size, -1).permute(0, 3, 1, 2),
122
+ size=(h, w),
123
+ mode=interpolate_mode,
124
+ align_corners=False,
125
+ )
126
+ return new_abs_pos.permute(0, 2, 3, 1)
127
+ else:
128
+ return abs_pos.reshape(1, h, w, -1)
MedSAM2/sam2/modeling/backbones/vitdet.py ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ViTDet backbone adapted from Detectron2"""
2
+
3
+ from functools import partial
4
+ from typing import List, Tuple, Union
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+
10
+ from sam2.modeling.backbones.utils import (
11
+ get_abs_pos,
12
+ PatchEmbed,
13
+ window_partition,
14
+ window_unpartition,
15
+ )
16
+
17
+ from sam2.modeling.efficienttam_utils import (
18
+ DropPath,
19
+ LayerScale,
20
+ MLP,
21
+ )
22
+
23
+
24
+ class Attention(nn.Module):
25
+ """Multi-head Attention block with relative position embeddings."""
26
+
27
+ def __init__(
28
+ self,
29
+ dim,
30
+ num_heads=8,
31
+ qkv_bias=True,
32
+ use_rel_pos=False,
33
+ rel_pos_zero_init=True,
34
+ input_size=None,
35
+ ):
36
+ """
37
+ Args:
38
+ dim (int): Number of input channels.
39
+ num_heads (int): Number of attention heads.
40
+ qkv_bias (bool: If True, add a learnable bias to query, key, value.
41
+ rel_pos (bool): If True, add relative positional embeddings to the attention map.
42
+ rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
43
+ input_size (int or None): Input resolution for calculating the relative positional
44
+ parameter size.
45
+ attn_type: Type of attention operation, e.g. "vanilla", "vanilla-xformer".
46
+ """
47
+ super().__init__()
48
+ self.num_heads = num_heads
49
+ head_dim = dim // num_heads
50
+ self.scale = head_dim**-0.5
51
+
52
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
53
+ self.proj = nn.Linear(dim, dim)
54
+
55
+ self.use_rel_pos = use_rel_pos
56
+
57
+ def forward(self, x):
58
+ B, H, W, _ = x.shape
59
+ # qkv with shape (3, B, nHead, H * W, C)
60
+ qkv = (
61
+ self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
62
+ )
63
+ # q, k, v with shape (B * nHead, H * W, C)
64
+ q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0)
65
+
66
+ q = q.view(B, self.num_heads, H * W, -1)
67
+ k = k.view(B, self.num_heads, H * W, -1)
68
+ v = v.view(B, self.num_heads, H * W, -1)
69
+
70
+ x = F.scaled_dot_product_attention(q, k, v)
71
+
72
+ x = (
73
+ x.view(B, self.num_heads, H, W, -1)
74
+ .permute(0, 2, 3, 1, 4)
75
+ .reshape(B, H, W, -1)
76
+ )
77
+ x = self.proj(x)
78
+
79
+ return x
80
+
81
+
82
+ class Block(nn.Module):
83
+ """Transformer blocks with support of window attention"""
84
+
85
+ def __init__(
86
+ self,
87
+ dim,
88
+ num_heads,
89
+ mlp_ratio=4.0,
90
+ qkv_bias=True,
91
+ drop_path=0.0,
92
+ norm_layer=nn.LayerNorm,
93
+ act_layer=nn.GELU,
94
+ use_rel_pos=False,
95
+ rel_pos_zero_init=True,
96
+ window_size=0,
97
+ input_size=None,
98
+ dropout=0.0,
99
+ init_values=None,
100
+ ):
101
+ """
102
+ Args:
103
+ dim (int): Number of input channels.
104
+ num_heads (int): Number of attention heads in each ViT block.
105
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
106
+ qkv_bias (bool): If True, add a learnable bias to query, key, value.
107
+ drop_path (float): Stochastic depth rate.
108
+ norm_layer (nn.Module): Normalization layer.
109
+ act_layer (nn.Module): Activation layer.
110
+ use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
111
+ rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
112
+ window_size (int): Window size for window attention blocks. If it equals 0, then not
113
+ use window attention.
114
+ input_size (int or None): Input resolution for calculating the relative positional
115
+ parameter size.
116
+ dropout (float): Dropout rate.
117
+ """
118
+ super().__init__()
119
+ self.norm1 = norm_layer(dim)
120
+ self.attn = Attention(
121
+ dim,
122
+ num_heads=num_heads,
123
+ qkv_bias=qkv_bias,
124
+ use_rel_pos=use_rel_pos,
125
+ rel_pos_zero_init=rel_pos_zero_init,
126
+ input_size=input_size if window_size == 0 else (window_size, window_size),
127
+ )
128
+ self.ls1 = (
129
+ LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
130
+ )
131
+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
132
+
133
+ self.norm2 = norm_layer(dim)
134
+ self.mlp = MLP(
135
+ dim,
136
+ int(dim * mlp_ratio),
137
+ dim,
138
+ num_layers=2,
139
+ activation=act_layer,
140
+ )
141
+ self.ls2 = (
142
+ LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
143
+ )
144
+ self.dropout = nn.Dropout(dropout)
145
+ self.window_size = window_size
146
+
147
+ def forward(self, x):
148
+ shortcut = x
149
+ x = self.norm1(x)
150
+ # Window partition
151
+ if self.window_size > 0:
152
+ H, W = x.shape[1], x.shape[2]
153
+ x, pad_hw = window_partition(x, self.window_size)
154
+
155
+ x = self.ls1(self.attn(x))
156
+ # Reverse window partition
157
+ if self.window_size > 0:
158
+ x = window_unpartition(x, self.window_size, pad_hw, (H, W))
159
+
160
+ x = shortcut + self.dropout(self.drop_path(x))
161
+ x = x + self.dropout(self.drop_path(self.ls2(self.mlp(self.norm2(x)))))
162
+
163
+ return x
164
+
165
+
166
+ class ViT(nn.Module):
167
+ """
168
+ This module implements Vision Transformer (ViT) backbone in :paper:`vitdet`.
169
+ "Exploring Plain Vision Transformer Backbones for Object Detection",
170
+ https://arxiv.org/abs/2203.16527
171
+ """
172
+
173
+ def __init__(
174
+ self,
175
+ img_size=1024,
176
+ patch_size=16,
177
+ in_chans=3,
178
+ embed_dim=768,
179
+ depth=12,
180
+ num_heads=12,
181
+ mlp_ratio=4.0,
182
+ qkv_bias=True,
183
+ drop_path_rate=0.0,
184
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
185
+ act_layer=nn.GELU,
186
+ use_abs_pos=True,
187
+ use_rel_pos=False,
188
+ rel_pos_zero_init=True,
189
+ window_size=14,
190
+ window_block_indexes=(0, 1, 3, 4, 6, 7, 9, 10),
191
+ use_act_checkpoint=False,
192
+ pretrain_img_size=224,
193
+ pretrain_use_cls_token=True,
194
+ dropout=0.0,
195
+ weights_path=None,
196
+ return_interm_layers=False,
197
+ init_values=None,
198
+ ):
199
+ """
200
+ Args:
201
+ img_size (int): Input image size. Only relevant for rel pos.
202
+ patch_size (int): Patch size.
203
+ in_chans (int): Number of input image channels.
204
+ embed_dim (int): Patch embedding dimension.
205
+ depth (int): Depth of ViT.
206
+ num_heads (int): Number of attention heads in each ViT block.
207
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
208
+ qkv_bias (bool): If True, add a learnable bias to query, key, value.
209
+ drop_path_rate (float): Stochastic depth rate.
210
+ norm_layer (nn.Module): Normalization layer.
211
+ act_layer (nn.Module): Activation layer.
212
+ use_abs_pos (bool): If True, use absolute positional embeddings.
213
+ use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
214
+ rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
215
+ window_size (int): Window size for window attention blocks.
216
+ window_block_indexes (list): Indexes for blocks using window attention.
217
+ residual_block_indexes (list): Indexes for blocks using conv propagation.
218
+ use_act_checkpoint (bool): If True, use activation checkpointing.
219
+ pretrain_img_size (int): input image size for pretraining models.
220
+ pretrain_use_cls_token (bool): If True, pretrainig models use class token.
221
+ dropout (float): Dropout rate. Applied in residual blocks of attn, mlp and inside the mlp.
222
+ path (str or None): Path to the pretrained weights.
223
+ return_interm_layers (bool): Whether to return intermediate layers (all global attention blocks).
224
+ freezing (BackboneFreezingType): Type of freezing.
225
+ """
226
+ super().__init__()
227
+ self.pretrain_use_cls_token = pretrain_use_cls_token
228
+
229
+ self.patch_embed = PatchEmbed(
230
+ kernel_size=(patch_size, patch_size),
231
+ stride=(patch_size, patch_size),
232
+ padding=(0, 0),
233
+ in_chans=in_chans,
234
+ embed_dim=embed_dim,
235
+ )
236
+
237
+ if use_abs_pos:
238
+ # Initialize absolute positional embedding with pretrain image size.
239
+ num_patches = (pretrain_img_size // patch_size) * (
240
+ pretrain_img_size // patch_size
241
+ )
242
+ num_positions = (num_patches + 1) if pretrain_use_cls_token else num_patches
243
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_positions, embed_dim))
244
+ else:
245
+ self.pos_embed = None
246
+
247
+ # stochastic depth decay rule
248
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)]
249
+
250
+ self.blocks = nn.ModuleList()
251
+ self.full_attn_ids = []
252
+ cur_stage = 1
253
+ for i in range(depth):
254
+ block = Block(
255
+ dim=embed_dim,
256
+ num_heads=num_heads,
257
+ mlp_ratio=mlp_ratio,
258
+ qkv_bias=qkv_bias,
259
+ drop_path=dpr[i],
260
+ norm_layer=norm_layer,
261
+ act_layer=act_layer,
262
+ use_rel_pos=use_rel_pos,
263
+ rel_pos_zero_init=rel_pos_zero_init,
264
+ window_size=window_size if i in window_block_indexes else 0,
265
+ input_size=(img_size // patch_size, img_size // patch_size),
266
+ dropout=dropout,
267
+ init_values=init_values,
268
+ )
269
+ if i not in window_block_indexes:
270
+ self.full_attn_ids.append(i)
271
+ cur_stage += 1
272
+
273
+ self.blocks.append(block)
274
+
275
+ self.return_interm_layers = return_interm_layers
276
+ self.channel_list = (
277
+ [embed_dim] * len(self.full_attn_ids)
278
+ if return_interm_layers
279
+ else [embed_dim]
280
+ )
281
+
282
+ def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
283
+
284
+ x = self.patch_embed(x)
285
+ if self.pos_embed is not None:
286
+ x = x + get_abs_pos(
287
+ self.pos_embed, self.pretrain_use_cls_token, (x.shape[1], x.shape[2])
288
+ )
289
+
290
+ outputs = []
291
+ for i, blk in enumerate(self.blocks):
292
+ x = blk(x)
293
+ if (i == self.full_attn_ids[-1]) or (
294
+ self.return_interm_layers and i in self.full_attn_ids
295
+ ):
296
+ feats = x.permute(0, 3, 1, 2)
297
+ outputs.append(feats)
298
+
299
+ return outputs
300
+
301
+ def get_num_layers(self):
302
+ return len(self.blocks)
303
+
304
+ def get_layer_id(self, layer_name):
305
+ # https://github.com/microsoft/unilm/blob/master/beit/optim_factory.py#L33
306
+ num_layers = self.get_num_layers()
307
+
308
+ if layer_name.find("rel_pos") != -1:
309
+ return num_layers + 1
310
+ elif layer_name.find("pos_embed") != -1:
311
+ return 0
312
+ elif layer_name.find("patch_embed") != -1:
313
+ return 0
314
+ elif layer_name.find("blocks") != -1:
315
+ return int(layer_name.split("blocks")[1].split(".")[1]) + 1
316
+ else:
317
+ return num_layers + 1
MedSAM2/sam2/modeling/efficienttam_base.py ADDED
@@ -0,0 +1,911 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import torch
8
+ import torch.distributed
9
+ import torch.nn.functional as F
10
+ from MedSAM2.sam2.modeling.efficienttam_utils import (
11
+ get_1d_sine_pe,
12
+ MLP,
13
+ select_closest_cond_frames,
14
+ )
15
+
16
+ from MedSAM2.sam2.modeling.sam.mask_decoder import MaskDecoder
17
+ from MedSAM2.sam2.modeling.sam.prompt_encoder import PromptEncoder
18
+ from MedSAM2.sam2.modeling.sam.transformer import TwoWayTransformer
19
+
20
+ from torch.nn.init import trunc_normal_
21
+
22
+ # a large negative value as a placeholder score for missing objects
23
+ NO_OBJ_SCORE = -1024.0
24
+
25
+
26
+ class EfficientTAMBase(torch.nn.Module):
27
+ def __init__(
28
+ self,
29
+ image_encoder,
30
+ memory_attention,
31
+ memory_encoder,
32
+ num_maskmem=7, # default 1 input frame + 6 previous frames
33
+ image_size=512,
34
+ backbone_stride=16, # stride of the image backbone output
35
+ sigmoid_scale_for_mem_enc=1.0, # scale factor for mask sigmoid prob
36
+ sigmoid_bias_for_mem_enc=0.0, # bias factor for mask sigmoid prob
37
+ # During evaluation, whether to binarize the sigmoid mask logits on interacted frames with clicks
38
+ binarize_mask_from_pts_for_mem_enc=False,
39
+ use_mask_input_as_output_without_sam=False, # on frames with mask input, whether to directly output the input mask without using a SAM prompt encoder + mask decoder
40
+ # The maximum number of conditioning frames to participate in the memory attention (-1 means no limit; if there are more conditioning frames than this limit,
41
+ # we only cross-attend to the temporally closest `max_cond_frames_in_attn` conditioning frames in the encoder when tracking each frame). This gives the model
42
+ # a temporal locality when handling a large number of annotated frames (since closer frames should be more important) and also avoids GPU OOM.
43
+ max_cond_frames_in_attn=-1,
44
+ # on the first frame, whether to directly add the no-memory embedding to the image feature
45
+ # (instead of using the transformer encoder)
46
+ directly_add_no_mem_embed=False,
47
+ # whether to use high-resolution feature maps in the SAM mask decoder
48
+ use_high_res_features_in_sam=False,
49
+ # whether to output multiple (3) masks for the first click on initial conditioning frames
50
+ multimask_output_in_sam=False,
51
+ # the minimum and maximum number of clicks to use multimask_output_in_sam (only relevant when `multimask_output_in_sam=True`;
52
+ # default is 1 for both, meaning that only the first click gives multimask output; also note that a box counts as two points)
53
+ multimask_min_pt_num=1,
54
+ multimask_max_pt_num=1,
55
+ # whether to also use multimask output for tracking (not just for the first click on initial conditioning frames; only relevant when `multimask_output_in_sam=True`)
56
+ multimask_output_for_tracking=False,
57
+ # Whether to use multimask tokens for obj ptr; Only relevant when both
58
+ # use_obj_ptrs_in_encoder=True and multimask_output_for_tracking=True
59
+ use_multimask_token_for_obj_ptr: bool = False,
60
+ # whether to use sigmoid to restrict ious prediction to [0-1]
61
+ iou_prediction_use_sigmoid=False,
62
+ # The memory bank's temporal stride during evaluation (i.e. the `r` parameter in XMem and Cutie; XMem and Cutie use r=5).
63
+ # For r>1, the (self.num_maskmem - 1) non-conditioning memory frames consist of
64
+ # (self.num_maskmem - 2) nearest frames from every r-th frames, plus the last frame.
65
+ memory_temporal_stride_for_eval=1,
66
+ # whether to apply non-overlapping constraints on the object masks in the memory encoder during evaluation (to avoid/alleviate superposing masks)
67
+ non_overlap_masks_for_mem_enc=False,
68
+ # whether to cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder
69
+ use_obj_ptrs_in_encoder=False,
70
+ # the maximum number of object pointers from other frames in encoder cross attention (only relevant when `use_obj_ptrs_in_encoder=True`)
71
+ max_obj_ptrs_in_encoder=16,
72
+ # whether to add temporal positional encoding to the object pointers in the encoder (only relevant when `use_obj_ptrs_in_encoder=True`)
73
+ add_tpos_enc_to_obj_ptrs=True,
74
+ # whether to add an extra linear projection layer for the temporal positional encoding in the object pointers to avoid potential interference
75
+ # with spatial positional encoding (only relevant when both `use_obj_ptrs_in_encoder=True` and `add_tpos_enc_to_obj_ptrs=True`)
76
+ proj_tpos_enc_in_obj_ptrs=False,
77
+ # whether to use signed distance (instead of unsigned absolute distance) in the temporal positional encoding in the object pointers
78
+ # (only relevant when both `use_obj_ptrs_in_encoder=True` and `add_tpos_enc_to_obj_ptrs=True`)
79
+ use_signed_tpos_enc_to_obj_ptrs=False,
80
+ # whether to only attend to object pointers in the past (before the current frame) in the encoder during evaluation
81
+ # (only relevant when `use_obj_ptrs_in_encoder=True`; this might avoid pointer information too far in the future to distract the initial tracking)
82
+ only_obj_ptrs_in_the_past_for_eval=False,
83
+ # Whether to predict if there is an object in the frame
84
+ pred_obj_scores: bool = False,
85
+ # Whether to use an MLP to predict object scores
86
+ pred_obj_scores_mlp: bool = False,
87
+ # Only relevant if pred_obj_scores=True and use_obj_ptrs_in_encoder=True;
88
+ # Whether to have a fixed no obj pointer when there is no object present
89
+ # or to use it as an additive embedding with obj_ptr produced by decoder
90
+ fixed_no_obj_ptr: bool = False,
91
+ # Soft no object, i.e. mix in no_obj_ptr softly,
92
+ # hope to make recovery easier if there is a mistake and mitigate accumulation of errors
93
+ soft_no_obj_ptr: bool = False,
94
+ use_mlp_for_obj_ptr_proj: bool = False,
95
+ # add no obj embedding to spatial frames
96
+ no_obj_embed_spatial: bool = False,
97
+ # extra arguments used to construct the SAM mask decoder; if not None, it should be a dict of kwargs to be passed into `MaskDecoder` class.
98
+ sam_mask_decoder_extra_args=None,
99
+ compile_image_encoder: bool = False,
100
+ ):
101
+ super().__init__()
102
+
103
+ # Part 1: the image backbone
104
+ self.image_encoder = image_encoder
105
+ self.use_high_res_features_in_sam = False
106
+ self.num_feature_levels = 1
107
+ self.use_obj_ptrs_in_encoder = use_obj_ptrs_in_encoder
108
+ self.max_obj_ptrs_in_encoder = max_obj_ptrs_in_encoder
109
+ if use_obj_ptrs_in_encoder:
110
+ # A conv layer to downsample the mask prompt to stride 4 (the same stride as
111
+ # low-res SAM mask logits) and to change its scales from 0~1 to SAM logit scale,
112
+ # so that it can be fed into the SAM mask decoder to generate a pointer.
113
+ self.mask_downsample = torch.nn.Conv2d(1, 1, kernel_size=4, stride=4)
114
+ self.add_tpos_enc_to_obj_ptrs = add_tpos_enc_to_obj_ptrs
115
+ if proj_tpos_enc_in_obj_ptrs:
116
+ assert add_tpos_enc_to_obj_ptrs # these options need to be used together
117
+ self.proj_tpos_enc_in_obj_ptrs = proj_tpos_enc_in_obj_ptrs
118
+ self.use_signed_tpos_enc_to_obj_ptrs = use_signed_tpos_enc_to_obj_ptrs
119
+ self.only_obj_ptrs_in_the_past_for_eval = only_obj_ptrs_in_the_past_for_eval
120
+
121
+ # Part 2: memory attention to condition current frame's visual features
122
+ # with memories (and obj ptrs) from past frames
123
+ self.memory_attention = memory_attention
124
+ self.hidden_dim = image_encoder.neck.d_model
125
+
126
+ # Part 3: memory encoder for the previous frame's outputs
127
+ self.memory_encoder = memory_encoder
128
+ self.mem_dim = self.hidden_dim
129
+ if hasattr(self.memory_encoder, "out_proj") and hasattr(
130
+ self.memory_encoder.out_proj, "weight"
131
+ ):
132
+ # if there is compression of memories along channel dim
133
+ self.mem_dim = self.memory_encoder.out_proj.weight.shape[0]
134
+ self.num_maskmem = num_maskmem # Number of memories accessible
135
+ # Temporal encoding of the memories
136
+ self.maskmem_tpos_enc = torch.nn.Parameter(
137
+ torch.zeros(num_maskmem, 1, 1, self.mem_dim)
138
+ )
139
+ trunc_normal_(self.maskmem_tpos_enc, std=0.02)
140
+ # a single token to indicate no memory embedding from previous frames
141
+ self.no_mem_embed = torch.nn.Parameter(torch.zeros(1, 1, self.hidden_dim))
142
+ self.no_mem_pos_enc = torch.nn.Parameter(torch.zeros(1, 1, self.hidden_dim))
143
+ trunc_normal_(self.no_mem_embed, std=0.02)
144
+ trunc_normal_(self.no_mem_pos_enc, std=0.02)
145
+ self.directly_add_no_mem_embed = directly_add_no_mem_embed
146
+ # Apply sigmoid to the output raw mask logits (to turn them from
147
+ # range (-inf, +inf) to range (0, 1)) before feeding them into the memory encoder
148
+ self.sigmoid_scale_for_mem_enc = sigmoid_scale_for_mem_enc
149
+ self.sigmoid_bias_for_mem_enc = sigmoid_bias_for_mem_enc
150
+ self.binarize_mask_from_pts_for_mem_enc = binarize_mask_from_pts_for_mem_enc
151
+ self.non_overlap_masks_for_mem_enc = non_overlap_masks_for_mem_enc
152
+ self.memory_temporal_stride_for_eval = memory_temporal_stride_for_eval
153
+ # On frames with mask input, whether to directly output the input mask without
154
+ # using a SAM prompt encoder + mask decoder
155
+ self.use_mask_input_as_output_without_sam = use_mask_input_as_output_without_sam
156
+ self.multimask_output_in_sam = multimask_output_in_sam
157
+ self.multimask_min_pt_num = multimask_min_pt_num
158
+ self.multimask_max_pt_num = multimask_max_pt_num
159
+ self.multimask_output_for_tracking = multimask_output_for_tracking
160
+ self.use_multimask_token_for_obj_ptr = use_multimask_token_for_obj_ptr
161
+ self.iou_prediction_use_sigmoid = iou_prediction_use_sigmoid
162
+
163
+ # Part 4: SAM-style prompt encoder (for both mask and point inputs)
164
+ # and SAM-style mask decoder for the final mask output
165
+ self.image_size = image_size
166
+ self.backbone_stride = backbone_stride
167
+ self.sam_mask_decoder_extra_args = sam_mask_decoder_extra_args
168
+ self.pred_obj_scores = pred_obj_scores
169
+ self.pred_obj_scores_mlp = pred_obj_scores_mlp
170
+ self.fixed_no_obj_ptr = fixed_no_obj_ptr
171
+ self.soft_no_obj_ptr = soft_no_obj_ptr
172
+ if self.fixed_no_obj_ptr:
173
+ assert self.pred_obj_scores
174
+ assert self.use_obj_ptrs_in_encoder
175
+ if self.pred_obj_scores and self.use_obj_ptrs_in_encoder:
176
+ self.no_obj_ptr = torch.nn.Parameter(torch.zeros(1, self.hidden_dim))
177
+ trunc_normal_(self.no_obj_ptr, std=0.02)
178
+ self.use_mlp_for_obj_ptr_proj = use_mlp_for_obj_ptr_proj
179
+ self.no_obj_embed_spatial = None
180
+ if no_obj_embed_spatial:
181
+ self.no_obj_embed_spatial = torch.nn.Parameter(torch.zeros(1, self.mem_dim))
182
+ trunc_normal_(self.no_obj_embed_spatial, std=0.02)
183
+
184
+ self._build_sam_heads()
185
+ self.max_cond_frames_in_attn = max_cond_frames_in_attn
186
+
187
+ # Model compilation
188
+ if compile_image_encoder:
189
+ # Compile the forward function (not the full module) to allow loading checkpoints.
190
+ print(
191
+ "Image encoder compilation is enabled. First forward pass will be slow."
192
+ )
193
+ self.image_encoder.forward = torch.compile(
194
+ self.image_encoder.forward,
195
+ mode="max-autotune",
196
+ fullgraph=True,
197
+ dynamic=False,
198
+ )
199
+
200
+ @property
201
+ def device(self):
202
+ return next(self.parameters()).device
203
+
204
+ def forward(self, *args, **kwargs):
205
+ raise NotImplementedError(
206
+ "Please use the corresponding methods in EfficientTAMVideoPredictor for inference"
207
+ )
208
+
209
+ def _build_sam_heads(self):
210
+ """Build SAM-style prompt encoder and mask decoder."""
211
+ self.sam_prompt_embed_dim = self.hidden_dim
212
+ self.sam_image_embedding_size = self.image_size // self.backbone_stride
213
+
214
+ # build PromptEncoder and MaskDecoder from SAM
215
+ # (their hyperparameters like `mask_in_chans=16` are from SAM code)
216
+ self.sam_prompt_encoder = PromptEncoder(
217
+ embed_dim=self.sam_prompt_embed_dim,
218
+ image_embedding_size=(
219
+ self.sam_image_embedding_size,
220
+ self.sam_image_embedding_size,
221
+ ),
222
+ input_image_size=(self.image_size, self.image_size),
223
+ mask_in_chans=16,
224
+ )
225
+ self.sam_mask_decoder = MaskDecoder(
226
+ num_multimask_outputs=3,
227
+ transformer=TwoWayTransformer(
228
+ depth=2,
229
+ embedding_dim=self.sam_prompt_embed_dim,
230
+ mlp_dim=2048,
231
+ num_heads=8,
232
+ ),
233
+ transformer_dim=self.sam_prompt_embed_dim,
234
+ iou_head_depth=3,
235
+ iou_head_hidden_dim=256,
236
+ use_high_res_features=self.use_high_res_features_in_sam,
237
+ iou_prediction_use_sigmoid=self.iou_prediction_use_sigmoid,
238
+ pred_obj_scores=self.pred_obj_scores,
239
+ pred_obj_scores_mlp=self.pred_obj_scores_mlp,
240
+ use_multimask_token_for_obj_ptr=self.use_multimask_token_for_obj_ptr,
241
+ **(self.sam_mask_decoder_extra_args or {}),
242
+ )
243
+ if self.use_obj_ptrs_in_encoder:
244
+ # a linear projection on SAM output tokens to turn them into object pointers
245
+ self.obj_ptr_proj = torch.nn.Linear(self.hidden_dim, self.hidden_dim)
246
+ if self.use_mlp_for_obj_ptr_proj:
247
+ self.obj_ptr_proj = MLP(
248
+ self.hidden_dim, self.hidden_dim, self.hidden_dim, 3
249
+ )
250
+ else:
251
+ self.obj_ptr_proj = torch.nn.Identity()
252
+ if self.proj_tpos_enc_in_obj_ptrs:
253
+ # a linear projection on temporal positional encoding in object pointers to
254
+ # avoid potential interference with spatial positional encoding
255
+ self.obj_ptr_tpos_proj = torch.nn.Linear(self.hidden_dim, self.mem_dim)
256
+ else:
257
+ self.obj_ptr_tpos_proj = torch.nn.Identity()
258
+
259
+ def _forward_sam_heads(
260
+ self,
261
+ backbone_features,
262
+ point_inputs=None,
263
+ mask_inputs=None,
264
+ high_res_features=None,
265
+ multimask_output=False,
266
+ ):
267
+ """
268
+ Forward SAM prompt encoders and mask heads.
269
+
270
+ Inputs:
271
+ - backbone_features: image features of [B, C, H, W] shape
272
+ - point_inputs: a dictionary with "point_coords" and "point_labels", where
273
+ 1) "point_coords" has [B, P, 2] shape and float32 dtype and contains the
274
+ absolute pixel-unit coordinate in (x, y) format of the P input points
275
+ 2) "point_labels" has shape [B, P] and int32 dtype, where 1 means
276
+ positive clicks, 0 means negative clicks, and -1 means padding
277
+ - mask_inputs: a mask of [B, 1, H*16, W*16] shape, float or bool, with the
278
+ same spatial size as the image.
279
+ - high_res_features: either 1) None or 2) or a list of length 2 containing
280
+ two feature maps of [B, C, 4*H, 4*W] and [B, C, 2*H, 2*W] shapes respectively,
281
+ which will be used as high-resolution feature maps for SAM decoder.
282
+ - multimask_output: if it's True, we output 3 candidate masks and their 3
283
+ corresponding IoU estimates, and if it's False, we output only 1 mask and
284
+ its corresponding IoU estimate.
285
+
286
+ Outputs:
287
+ - low_res_multimasks: [B, M, H*4, W*4] shape (where M = 3 if
288
+ `multimask_output=True` and M = 1 if `multimask_output=False`), the SAM
289
+ output mask logits (before sigmoid) for the low-resolution masks, with 4x
290
+ the resolution (1/4 stride) of the input backbone_features.
291
+ - high_res_multimasks: [B, M, H*16, W*16] shape (where M = 3
292
+ if `multimask_output=True` and M = 1 if `multimask_output=False`),
293
+ upsampled from the low-resolution masks, with shape size as the image
294
+ (stride is 1 pixel).
295
+ - ious, [B, M] shape, where (where M = 3 if `multimask_output=True` and M = 1
296
+ if `multimask_output=False`), the estimated IoU of each output mask.
297
+ - low_res_masks: [B, 1, H*4, W*4] shape, the best mask in `low_res_multimasks`.
298
+ If `multimask_output=True`, it's the mask with the highest IoU estimate.
299
+ If `multimask_output=False`, it's the same as `low_res_multimasks`.
300
+ - high_res_masks: [B, 1, H*16, W*16] shape, the best mask in `high_res_multimasks`.
301
+ If `multimask_output=True`, it's the mask with the highest IoU estimate.
302
+ If `multimask_output=False`, it's the same as `high_res_multimasks`.
303
+ - obj_ptr: [B, C] shape, the object pointer vector for the output mask, extracted
304
+ based on the output token from the SAM mask decoder.
305
+ """
306
+ B = backbone_features.size(0)
307
+ device = backbone_features.device
308
+ assert backbone_features.size(1) == self.sam_prompt_embed_dim
309
+ assert backbone_features.size(2) == self.sam_image_embedding_size
310
+ assert backbone_features.size(3) == self.sam_image_embedding_size
311
+
312
+ # a) Handle point prompts
313
+ if point_inputs is not None:
314
+ sam_point_coords = point_inputs["point_coords"]
315
+ sam_point_labels = point_inputs["point_labels"]
316
+ assert sam_point_coords.size(0) == B and sam_point_labels.size(0) == B
317
+ else:
318
+ # If no points are provide, pad with an empty point (with label -1)
319
+ sam_point_coords = torch.zeros(B, 1, 2, device=device)
320
+ sam_point_labels = -torch.ones(B, 1, dtype=torch.int32, device=device)
321
+
322
+ # b) Handle mask prompts
323
+ if mask_inputs is not None:
324
+ # If mask_inputs is provided, downsize it into low-res mask input if needed
325
+ # and feed it as a dense mask prompt into the SAM mask encoder
326
+ assert len(mask_inputs.shape) == 4 and mask_inputs.shape[:2] == (B, 1)
327
+ if mask_inputs.shape[-2:] != self.sam_prompt_encoder.mask_input_size:
328
+ sam_mask_prompt = F.interpolate(
329
+ mask_inputs.float(),
330
+ size=self.sam_prompt_encoder.mask_input_size,
331
+ align_corners=False,
332
+ mode="bilinear",
333
+ antialias=True, # use antialias for downsampling
334
+ )
335
+ else:
336
+ sam_mask_prompt = mask_inputs
337
+ else:
338
+ # Otherwise, simply feed None (and SAM's prompt encoder will add
339
+ # a learned `no_mask_embed` to indicate no mask input in this case).
340
+ sam_mask_prompt = None
341
+
342
+ sparse_embeddings, dense_embeddings = self.sam_prompt_encoder(
343
+ points=(sam_point_coords, sam_point_labels),
344
+ boxes=None,
345
+ masks=sam_mask_prompt,
346
+ )
347
+ (
348
+ low_res_multimasks,
349
+ ious,
350
+ sam_output_tokens,
351
+ object_score_logits,
352
+ ) = self.sam_mask_decoder(
353
+ image_embeddings=backbone_features,
354
+ image_pe=self.sam_prompt_encoder.get_dense_pe(),
355
+ sparse_prompt_embeddings=sparse_embeddings,
356
+ dense_prompt_embeddings=dense_embeddings,
357
+ multimask_output=multimask_output,
358
+ repeat_image=False, # the image is already batched
359
+ high_res_features=high_res_features,
360
+ )
361
+ if self.pred_obj_scores:
362
+ is_obj_appearing = object_score_logits > 0
363
+
364
+ # Mask used for spatial memories is always a *hard* choice between obj and no obj,
365
+ # consistent with the actual mask prediction
366
+ low_res_multimasks = torch.where(
367
+ is_obj_appearing[:, None, None],
368
+ low_res_multimasks,
369
+ NO_OBJ_SCORE,
370
+ )
371
+
372
+ # convert masks from possibly bfloat16 (or float16) to float32
373
+ # (older PyTorch versions before 2.1 don't support `interpolate` on bf16)
374
+ low_res_multimasks = low_res_multimasks.float()
375
+ high_res_multimasks = F.interpolate(
376
+ low_res_multimasks,
377
+ size=(self.image_size, self.image_size),
378
+ mode="bilinear",
379
+ align_corners=False,
380
+ )
381
+
382
+ sam_output_token = sam_output_tokens[:, 0]
383
+ if multimask_output:
384
+ # take the best mask prediction (with the highest IoU estimation)
385
+ best_iou_inds = torch.argmax(ious, dim=-1)
386
+ batch_inds = torch.arange(B, device=device)
387
+ low_res_masks = low_res_multimasks[batch_inds, best_iou_inds].unsqueeze(1)
388
+ high_res_masks = high_res_multimasks[batch_inds, best_iou_inds].unsqueeze(1)
389
+ if sam_output_tokens.size(1) > 1:
390
+ sam_output_token = sam_output_tokens[batch_inds, best_iou_inds]
391
+ else:
392
+ low_res_masks, high_res_masks = low_res_multimasks, high_res_multimasks
393
+
394
+ # Extract object pointer from the SAM output token (with occlusion handling)
395
+ obj_ptr = self.obj_ptr_proj(sam_output_token)
396
+ if self.pred_obj_scores:
397
+ # Allow *soft* no obj ptr, unlike for masks
398
+ if self.soft_no_obj_ptr:
399
+ lambda_is_obj_appearing = object_score_logits.sigmoid()
400
+ else:
401
+ lambda_is_obj_appearing = is_obj_appearing.float()
402
+
403
+ if self.fixed_no_obj_ptr:
404
+ obj_ptr = lambda_is_obj_appearing * obj_ptr
405
+ obj_ptr = obj_ptr + (1 - lambda_is_obj_appearing) * self.no_obj_ptr
406
+
407
+ return (
408
+ low_res_multimasks,
409
+ high_res_multimasks,
410
+ ious,
411
+ low_res_masks,
412
+ high_res_masks,
413
+ obj_ptr,
414
+ object_score_logits,
415
+ )
416
+
417
+ def _use_mask_as_output(self, backbone_features, high_res_features, mask_inputs):
418
+ """
419
+ Directly turn binary `mask_inputs` into a output mask logits without using SAM.
420
+ (same input and output shapes as in _forward_sam_heads above).
421
+ """
422
+ # Use -10/+10 as logits for neg/pos pixels (very close to 0/1 in prob after sigmoid).
423
+ out_scale, out_bias = 20.0, -10.0 # sigmoid(-10.0)=4.5398e-05
424
+ mask_inputs_float = mask_inputs.float()
425
+ high_res_masks = mask_inputs_float * out_scale + out_bias
426
+ low_res_masks = F.interpolate(
427
+ high_res_masks,
428
+ size=(high_res_masks.size(-2) // 4, high_res_masks.size(-1) // 4),
429
+ align_corners=False,
430
+ mode="bilinear",
431
+ antialias=True, # use antialias for downsampling
432
+ )
433
+ # a dummy IoU prediction of all 1's under mask input
434
+ ious = mask_inputs.new_ones(mask_inputs.size(0), 1).float()
435
+ if not self.use_obj_ptrs_in_encoder:
436
+ # all zeros as a dummy object pointer (of shape [B, C])
437
+ obj_ptr = torch.zeros(
438
+ mask_inputs.size(0), self.hidden_dim, device=mask_inputs.device
439
+ )
440
+ else:
441
+ # produce an object pointer using the SAM decoder from the mask input
442
+ _, _, _, _, _, obj_ptr, _ = self._forward_sam_heads(
443
+ backbone_features=backbone_features,
444
+ mask_inputs=self.mask_downsample(mask_inputs_float),
445
+ high_res_features=high_res_features,
446
+ )
447
+ # In this method, we are treating mask_input as output, e.g. using it directly to create spatial mem;
448
+ # Below, we follow the same design axiom to use mask_input to decide if obj appears or not instead of relying
449
+ # on the object_scores from the SAM decoder.
450
+ is_obj_appearing = torch.any(mask_inputs.flatten(1).float() > 0.0, dim=1)
451
+ is_obj_appearing = is_obj_appearing[..., None]
452
+ lambda_is_obj_appearing = is_obj_appearing.float()
453
+ object_score_logits = out_scale * lambda_is_obj_appearing + out_bias
454
+ if self.pred_obj_scores:
455
+ if self.fixed_no_obj_ptr:
456
+ obj_ptr = lambda_is_obj_appearing * obj_ptr
457
+ obj_ptr = obj_ptr + (1 - lambda_is_obj_appearing) * self.no_obj_ptr
458
+
459
+ return (
460
+ low_res_masks,
461
+ high_res_masks,
462
+ ious,
463
+ low_res_masks,
464
+ high_res_masks,
465
+ obj_ptr,
466
+ object_score_logits,
467
+ )
468
+
469
+ def forward_image(self, img_batch: torch.Tensor):
470
+ """Get the image feature on the input batch."""
471
+ backbone_out = self.image_encoder(img_batch)
472
+ if self.use_high_res_features_in_sam:
473
+ # precompute projected level 0 and level 1 features in SAM decoder
474
+ # to avoid running it again on every SAM click
475
+ backbone_out["backbone_fpn"][0] = self.sam_mask_decoder.conv_s0(
476
+ backbone_out["backbone_fpn"][0]
477
+ )
478
+ backbone_out["backbone_fpn"][1] = self.sam_mask_decoder.conv_s1(
479
+ backbone_out["backbone_fpn"][1]
480
+ )
481
+ return backbone_out
482
+
483
+ def _prepare_backbone_features(self, backbone_out):
484
+ """Prepare and flatten visual features."""
485
+ backbone_out = backbone_out.copy()
486
+ assert len(backbone_out["backbone_fpn"]) == len(backbone_out["vision_pos_enc"])
487
+ assert len(backbone_out["backbone_fpn"]) >= self.num_feature_levels
488
+
489
+ feature_maps = backbone_out["backbone_fpn"][-self.num_feature_levels :]
490
+ vision_pos_embeds = backbone_out["vision_pos_enc"][-self.num_feature_levels :]
491
+
492
+ feat_sizes = [(x.shape[-2], x.shape[-1]) for x in vision_pos_embeds]
493
+ # flatten NxCxHxW to HWxNxC
494
+ vision_feats = [x.flatten(2).permute(2, 0, 1) for x in feature_maps]
495
+ vision_pos_embeds = [x.flatten(2).permute(2, 0, 1) for x in vision_pos_embeds]
496
+
497
+ return backbone_out, vision_feats, vision_pos_embeds, feat_sizes
498
+
499
+ def _prepare_memory_conditioned_features(
500
+ self,
501
+ frame_idx,
502
+ is_init_cond_frame,
503
+ current_vision_feats,
504
+ current_vision_pos_embeds,
505
+ feat_sizes,
506
+ output_dict,
507
+ num_frames,
508
+ track_in_reverse=False, # tracking in reverse time order (for demo usage)
509
+ ):
510
+ """Fuse the current frame's visual feature map with previous memory."""
511
+ B = current_vision_feats[-1].size(1) # batch size on this frame
512
+ C = self.hidden_dim
513
+ H, W = feat_sizes[-1] # top-level (lowest-resolution) feature size
514
+ device = current_vision_feats[-1].device
515
+ # The case of `self.num_maskmem == 0` below is primarily used for reproducing SAM on images.
516
+ # In this case, we skip the fusion with any memory.
517
+ if self.num_maskmem == 0: # Disable memory and skip fusion
518
+ pix_feat = current_vision_feats[-1].permute(1, 2, 0).view(B, C, H, W)
519
+ return pix_feat
520
+
521
+ num_obj_ptr_tokens = 0
522
+ tpos_sign_mul = -1 if track_in_reverse else 1
523
+ # Step 1: condition the visual features of the current frame on previous memories
524
+ if not is_init_cond_frame:
525
+ # Retrieve the memories encoded with the maskmem backbone
526
+ to_cat_memory, to_cat_memory_pos_embed = [], []
527
+ # Add conditioning frames's output first (all cond frames have t_pos=0 for
528
+ # when getting temporal positional embedding below)
529
+ assert len(output_dict["cond_frame_outputs"]) > 0
530
+ # Select a maximum number of temporally closest cond frames for cross attention
531
+ cond_outputs = output_dict["cond_frame_outputs"]
532
+ selected_cond_outputs, unselected_cond_outputs = select_closest_cond_frames(
533
+ frame_idx, cond_outputs, self.max_cond_frames_in_attn
534
+ )
535
+ t_pos_and_prevs = [(0, out) for out in selected_cond_outputs.values()]
536
+ # Add last (self.num_maskmem - 1) frames before current frame for non-conditioning memory
537
+ # the earliest one has t_pos=1 and the latest one has t_pos=self.num_maskmem-1
538
+ # We also allow taking the memory frame non-consecutively (with stride>1), in which case
539
+ # we take (self.num_maskmem - 2) frames among every stride-th frames plus the last frame.
540
+ stride = 1 if self.training else self.memory_temporal_stride_for_eval
541
+ for t_pos in range(1, self.num_maskmem):
542
+ t_rel = self.num_maskmem - t_pos # how many frames before current frame
543
+ if t_rel == 1:
544
+ # for t_rel == 1, we take the last frame (regardless of r)
545
+ if not track_in_reverse:
546
+ # the frame immediately before this frame (i.e. frame_idx - 1)
547
+ prev_frame_idx = frame_idx - t_rel
548
+ else:
549
+ # the frame immediately after this frame (i.e. frame_idx + 1)
550
+ prev_frame_idx = frame_idx + t_rel
551
+ else:
552
+ # for t_rel >= 2, we take the memory frame from every r-th frames
553
+ if not track_in_reverse:
554
+ # first find the nearest frame among every r-th frames before this frame
555
+ # for r=1, this would be (frame_idx - 2)
556
+ prev_frame_idx = ((frame_idx - 2) // stride) * stride
557
+ # then seek further among every r-th frames
558
+ prev_frame_idx = prev_frame_idx - (t_rel - 2) * stride
559
+ else:
560
+ # first find the nearest frame among every r-th frames after this frame
561
+ # for r=1, this would be (frame_idx + 2)
562
+ prev_frame_idx = -(-(frame_idx + 2) // stride) * stride
563
+ # then seek further among every r-th frames
564
+ prev_frame_idx = prev_frame_idx + (t_rel - 2) * stride
565
+ out = output_dict["non_cond_frame_outputs"].get(prev_frame_idx, None)
566
+ if out is None:
567
+ # If an unselected conditioning frame is among the last (self.num_maskmem - 1)
568
+ # frames, we still attend to it as if it's a non-conditioning frame.
569
+ out = unselected_cond_outputs.get(prev_frame_idx, None)
570
+ t_pos_and_prevs.append((t_pos, out))
571
+
572
+ for t_pos, prev in t_pos_and_prevs:
573
+ if prev is None:
574
+ continue # skip padding frames
575
+ # "maskmem_features" might have been offloaded to CPU in demo use cases,
576
+ # so we load it back to GPU (it's a no-op if it's already on GPU).
577
+ feats = prev["maskmem_features"].to(device, non_blocking=True)
578
+ to_cat_memory.append(feats.flatten(2).permute(2, 0, 1))
579
+ # Spatial positional encoding (it might have been offloaded to CPU in eval)
580
+ maskmem_enc = prev["maskmem_pos_enc"][-1].to(device)
581
+ maskmem_enc = maskmem_enc.flatten(2).permute(2, 0, 1)
582
+ # Temporal positional encoding
583
+ maskmem_enc = (
584
+ maskmem_enc + self.maskmem_tpos_enc[self.num_maskmem - t_pos - 1]
585
+ )
586
+ to_cat_memory_pos_embed.append(maskmem_enc)
587
+
588
+ # Construct the list of past object pointers
589
+ if self.use_obj_ptrs_in_encoder:
590
+ max_obj_ptrs_in_encoder = min(num_frames, self.max_obj_ptrs_in_encoder)
591
+ # First add those object pointers from selected conditioning frames
592
+ # (optionally, only include object pointers in the past during evaluation)
593
+ if not self.training and self.only_obj_ptrs_in_the_past_for_eval:
594
+ ptr_cond_outputs = {
595
+ t: out
596
+ for t, out in selected_cond_outputs.items()
597
+ if (t >= frame_idx if track_in_reverse else t <= frame_idx)
598
+ }
599
+ else:
600
+ ptr_cond_outputs = selected_cond_outputs
601
+ pos_and_ptrs = [
602
+ # Temporal pos encoding contains how far away each pointer is from current frame
603
+ (
604
+ (
605
+ (frame_idx - t) * tpos_sign_mul
606
+ if self.use_signed_tpos_enc_to_obj_ptrs
607
+ else abs(frame_idx - t)
608
+ ),
609
+ out["obj_ptr"],
610
+ )
611
+ for t, out in ptr_cond_outputs.items()
612
+ ]
613
+ # Add up to (max_obj_ptrs_in_encoder - 1) non-conditioning frames before current frame
614
+ for t_diff in range(1, max_obj_ptrs_in_encoder):
615
+ t = frame_idx + t_diff if track_in_reverse else frame_idx - t_diff
616
+ if t < 0 or (num_frames is not None and t >= num_frames):
617
+ break
618
+ out = output_dict["non_cond_frame_outputs"].get(
619
+ t, unselected_cond_outputs.get(t, None)
620
+ )
621
+ if out is not None:
622
+ pos_and_ptrs.append((t_diff, out["obj_ptr"]))
623
+ # If we have at least one object pointer, add them to the across attention
624
+ if len(pos_and_ptrs) > 0:
625
+ pos_list, ptrs_list = zip(*pos_and_ptrs)
626
+ # stack object pointers along dim=0 into [ptr_seq_len, B, C] shape
627
+ obj_ptrs = torch.stack(ptrs_list, dim=0)
628
+ # a temporal positional embedding based on how far each object pointer is from
629
+ # the current frame (sine embedding normalized by the max pointer num).
630
+ if self.add_tpos_enc_to_obj_ptrs:
631
+ t_diff_max = max_obj_ptrs_in_encoder - 1
632
+ tpos_dim = C if self.proj_tpos_enc_in_obj_ptrs else self.mem_dim
633
+ obj_pos = torch.tensor(pos_list).to(
634
+ device=device, non_blocking=True
635
+ )
636
+ obj_pos = get_1d_sine_pe(obj_pos / t_diff_max, dim=tpos_dim)
637
+ obj_pos = self.obj_ptr_tpos_proj(obj_pos)
638
+ obj_pos = obj_pos.unsqueeze(1).expand(-1, B, self.mem_dim)
639
+ else:
640
+ obj_pos = obj_ptrs.new_zeros(len(pos_list), B, self.mem_dim)
641
+ if self.mem_dim < C:
642
+ # split a pointer into (C // self.mem_dim) tokens for self.mem_dim < C
643
+ obj_ptrs = obj_ptrs.reshape(
644
+ -1, B, C // self.mem_dim, self.mem_dim
645
+ )
646
+ obj_ptrs = obj_ptrs.permute(0, 2, 1, 3).flatten(0, 1)
647
+ obj_pos = obj_pos.repeat_interleave(C // self.mem_dim, dim=0)
648
+ to_cat_memory.append(obj_ptrs)
649
+ to_cat_memory_pos_embed.append(obj_pos)
650
+ num_obj_ptr_tokens = obj_ptrs.shape[0]
651
+ else:
652
+ num_obj_ptr_tokens = 0
653
+ else:
654
+ # for initial conditioning frames, encode them without using any previous memory
655
+ if self.directly_add_no_mem_embed:
656
+ # directly add no-mem embedding (instead of using the transformer encoder)
657
+ pix_feat_with_mem = current_vision_feats[-1] + self.no_mem_embed
658
+ pix_feat_with_mem = pix_feat_with_mem.permute(1, 2, 0).view(B, C, H, W)
659
+ return pix_feat_with_mem
660
+
661
+ # Use a dummy token on the first frame (to avoid empty memory input to tranformer encoder)
662
+ to_cat_memory = [self.no_mem_embed.expand(1, B, self.mem_dim)]
663
+ to_cat_memory_pos_embed = [self.no_mem_pos_enc.expand(1, B, self.mem_dim)]
664
+
665
+ # Step 2: Concatenate the memories and forward through the transformer encoder
666
+ memory = torch.cat(to_cat_memory, dim=0)
667
+ memory_pos_embed = torch.cat(to_cat_memory_pos_embed, dim=0)
668
+
669
+ pix_feat_with_mem = self.memory_attention(
670
+ curr=current_vision_feats,
671
+ curr_pos=current_vision_pos_embeds,
672
+ memory=memory,
673
+ memory_pos=memory_pos_embed,
674
+ num_obj_ptr_tokens=num_obj_ptr_tokens,
675
+ )
676
+ # reshape the output (HW)BC => BCHW
677
+ pix_feat_with_mem = pix_feat_with_mem.permute(1, 2, 0).view(B, C, H, W)
678
+ return pix_feat_with_mem
679
+
680
+ def _encode_new_memory(
681
+ self,
682
+ current_vision_feats,
683
+ feat_sizes,
684
+ pred_masks_high_res,
685
+ object_score_logits,
686
+ is_mask_from_pts,
687
+ ):
688
+ """Encode the current image and its prediction into a memory feature."""
689
+ B = current_vision_feats[-1].size(1) # batch size on this frame
690
+ C = self.hidden_dim
691
+ H, W = feat_sizes[-1] # top-level (lowest-resolution) feature size
692
+ # top-level feature, (HW)BC => BCHW
693
+ pix_feat = current_vision_feats[-1].permute(1, 2, 0).view(B, C, H, W)
694
+ if self.non_overlap_masks_for_mem_enc and not self.training:
695
+ # optionally, apply non-overlapping constraints to the masks (it's applied
696
+ # in the batch dimension and should only be used during eval, where all
697
+ # the objects come from the same video under batch size 1).
698
+ pred_masks_high_res = self._apply_non_overlapping_constraints(
699
+ pred_masks_high_res
700
+ )
701
+ # scale the raw mask logits with a temperature before applying sigmoid
702
+ binarize = self.binarize_mask_from_pts_for_mem_enc and is_mask_from_pts
703
+ if binarize and not self.training:
704
+ mask_for_mem = (pred_masks_high_res > 0).float()
705
+ else:
706
+ # apply sigmoid on the raw mask logits to turn them into range (0, 1)
707
+ mask_for_mem = torch.sigmoid(pred_masks_high_res)
708
+ # apply scale and bias terms to the sigmoid probabilities
709
+ if self.sigmoid_scale_for_mem_enc != 1.0:
710
+ mask_for_mem = mask_for_mem * self.sigmoid_scale_for_mem_enc
711
+ if self.sigmoid_bias_for_mem_enc != 0.0:
712
+ mask_for_mem = mask_for_mem + self.sigmoid_bias_for_mem_enc
713
+ maskmem_out = self.memory_encoder(
714
+ pix_feat, mask_for_mem, skip_mask_sigmoid=True # sigmoid already applied
715
+ )
716
+ maskmem_features = maskmem_out["vision_features"]
717
+ maskmem_pos_enc = maskmem_out["vision_pos_enc"]
718
+ # add a no-object embedding to the spatial memory to indicate that the frame
719
+ # is predicted to be occluded (i.e. no object is appearing in the frame)
720
+ if self.no_obj_embed_spatial is not None:
721
+ is_obj_appearing = (object_score_logits > 0).float()
722
+ maskmem_features += (
723
+ 1 - is_obj_appearing[..., None, None]
724
+ ) * self.no_obj_embed_spatial[..., None, None].expand(
725
+ *maskmem_features.shape
726
+ )
727
+
728
+ return maskmem_features, maskmem_pos_enc
729
+
730
+ def _track_step(
731
+ self,
732
+ frame_idx,
733
+ is_init_cond_frame,
734
+ current_vision_feats,
735
+ current_vision_pos_embeds,
736
+ feat_sizes,
737
+ point_inputs,
738
+ mask_inputs,
739
+ output_dict,
740
+ num_frames,
741
+ track_in_reverse,
742
+ prev_sam_mask_logits,
743
+ ):
744
+ current_out = {"point_inputs": point_inputs, "mask_inputs": mask_inputs}
745
+ # High-resolution feature maps for the SAM head, reshape (HW)BC => BCHW
746
+ if len(current_vision_feats) > 1:
747
+ high_res_features = [
748
+ x.permute(1, 2, 0).view(x.size(1), x.size(2), *s)
749
+ for x, s in zip(current_vision_feats[:-1], feat_sizes[:-1])
750
+ ]
751
+ else:
752
+ high_res_features = None
753
+ if mask_inputs is not None and self.use_mask_input_as_output_without_sam:
754
+ # When use_mask_input_as_output_without_sam=True, we directly output the mask input
755
+ # (see it as a GT mask) without using a SAM prompt encoder + mask decoder.
756
+ pix_feat = current_vision_feats[-1].permute(1, 2, 0)
757
+ pix_feat = pix_feat.view(-1, self.hidden_dim, *feat_sizes[-1])
758
+ sam_outputs = self._use_mask_as_output(
759
+ pix_feat, high_res_features, mask_inputs
760
+ )
761
+ else:
762
+ # fused the visual feature with previous memory features in the memory bank
763
+ pix_feat = self._prepare_memory_conditioned_features(
764
+ frame_idx=frame_idx,
765
+ is_init_cond_frame=is_init_cond_frame,
766
+ current_vision_feats=current_vision_feats[-1:],
767
+ current_vision_pos_embeds=current_vision_pos_embeds[-1:],
768
+ feat_sizes=feat_sizes[-1:],
769
+ output_dict=output_dict,
770
+ num_frames=num_frames,
771
+ track_in_reverse=track_in_reverse,
772
+ )
773
+ # apply SAM-style segmentation head
774
+ # here we might feed previously predicted low-res SAM mask logits into the SAM mask decoder,
775
+ # e.g. in demo where such logits come from earlier interaction instead of correction sampling
776
+ # (in this case, any `mask_inputs` shouldn't reach here as they are sent to _use_mask_as_output instead)
777
+ if prev_sam_mask_logits is not None:
778
+ assert point_inputs is not None and mask_inputs is None
779
+ mask_inputs = prev_sam_mask_logits
780
+ multimask_output = self._use_multimask(is_init_cond_frame, point_inputs)
781
+ sam_outputs = self._forward_sam_heads(
782
+ backbone_features=pix_feat,
783
+ point_inputs=point_inputs,
784
+ mask_inputs=mask_inputs,
785
+ high_res_features=high_res_features,
786
+ multimask_output=multimask_output,
787
+ )
788
+
789
+ return current_out, sam_outputs, high_res_features, pix_feat
790
+
791
+ def _encode_memory_in_output(
792
+ self,
793
+ current_vision_feats,
794
+ feat_sizes,
795
+ point_inputs,
796
+ run_mem_encoder,
797
+ high_res_masks,
798
+ object_score_logits,
799
+ current_out,
800
+ ):
801
+ if run_mem_encoder and self.num_maskmem > 0:
802
+ high_res_masks_for_mem_enc = high_res_masks
803
+ maskmem_features, maskmem_pos_enc = self._encode_new_memory(
804
+ current_vision_feats=current_vision_feats,
805
+ feat_sizes=feat_sizes,
806
+ pred_masks_high_res=high_res_masks_for_mem_enc,
807
+ object_score_logits=object_score_logits,
808
+ is_mask_from_pts=(point_inputs is not None),
809
+ )
810
+ current_out["maskmem_features"] = maskmem_features
811
+ current_out["maskmem_pos_enc"] = maskmem_pos_enc
812
+ else:
813
+ current_out["maskmem_features"] = None
814
+ current_out["maskmem_pos_enc"] = None
815
+
816
+ def track_step(
817
+ self,
818
+ frame_idx,
819
+ is_init_cond_frame,
820
+ current_vision_feats,
821
+ current_vision_pos_embeds,
822
+ feat_sizes,
823
+ point_inputs,
824
+ mask_inputs,
825
+ output_dict,
826
+ num_frames,
827
+ track_in_reverse=False, # tracking in reverse time order (for demo usage)
828
+ # Whether to run the memory encoder on the predicted masks. Sometimes we might want
829
+ # to skip the memory encoder with `run_mem_encoder=False`. For example,
830
+ # in demo we might call `track_step` multiple times for each user click,
831
+ # and only encode the memory when the user finalizes their clicks. And in ablation
832
+ # settings like SAM training on static images, we don't need the memory encoder.
833
+ run_mem_encoder=True,
834
+ # The previously predicted SAM mask logits (which can be fed together with new clicks in demo).
835
+ prev_sam_mask_logits=None,
836
+ ):
837
+ current_out, sam_outputs, _, _ = self._track_step(
838
+ frame_idx,
839
+ is_init_cond_frame,
840
+ current_vision_feats,
841
+ current_vision_pos_embeds,
842
+ feat_sizes,
843
+ point_inputs,
844
+ mask_inputs,
845
+ output_dict,
846
+ num_frames,
847
+ track_in_reverse,
848
+ prev_sam_mask_logits,
849
+ )
850
+
851
+ (
852
+ _,
853
+ _,
854
+ _,
855
+ low_res_masks,
856
+ high_res_masks,
857
+ obj_ptr,
858
+ object_score_logits,
859
+ ) = sam_outputs
860
+
861
+ current_out["pred_masks"] = low_res_masks
862
+ current_out["pred_masks_high_res"] = high_res_masks
863
+ current_out["obj_ptr"] = obj_ptr
864
+ if not self.training:
865
+ # Only add this in inference (to avoid unused param in activation checkpointing;
866
+ # it's mainly used in the demo to encode spatial memories w/ consolidated masks)
867
+ current_out["object_score_logits"] = object_score_logits
868
+
869
+ # Finally run the memory encoder on the predicted mask to encode
870
+ # it into a new memory feature (that can be used in future frames)
871
+ self._encode_memory_in_output(
872
+ current_vision_feats,
873
+ feat_sizes,
874
+ point_inputs,
875
+ run_mem_encoder,
876
+ high_res_masks,
877
+ object_score_logits,
878
+ current_out,
879
+ )
880
+
881
+ return current_out
882
+
883
+ def _use_multimask(self, is_init_cond_frame, point_inputs):
884
+ """Whether to use multimask output in the SAM head."""
885
+ num_pts = 0 if point_inputs is None else point_inputs["point_labels"].size(1)
886
+ multimask_output = (
887
+ self.multimask_output_in_sam
888
+ and (is_init_cond_frame or self.multimask_output_for_tracking)
889
+ and (self.multimask_min_pt_num <= num_pts <= self.multimask_max_pt_num)
890
+ )
891
+ return multimask_output
892
+
893
+ def _apply_non_overlapping_constraints(self, pred_masks):
894
+ """
895
+ Apply non-overlapping constraints to the object scores in pred_masks. Here we
896
+ keep only the highest scoring object at each spatial location in pred_masks.
897
+ """
898
+ batch_size = pred_masks.size(0)
899
+ if batch_size == 1:
900
+ return pred_masks
901
+
902
+ device = pred_masks.device
903
+ # "max_obj_inds": object index of the object with the highest score at each location
904
+ max_obj_inds = torch.argmax(pred_masks, dim=0, keepdim=True)
905
+ # "batch_obj_inds": object index of each object slice (along dim 0) in `pred_masks`
906
+ batch_obj_inds = torch.arange(batch_size, device=device)[:, None, None, None]
907
+ keep = max_obj_inds == batch_obj_inds
908
+ # suppress overlapping regions' scores below -10.0 so that the foreground regions
909
+ # don't overlap (here sigmoid(-10.0)=4.5398e-05)
910
+ pred_masks = torch.where(keep, pred_masks, torch.clamp(pred_masks, max=-10.0))
911
+ return pred_masks
MedSAM2/sam2/modeling/efficienttam_utils.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+
8
+ import copy
9
+ from typing import Tuple, Union
10
+
11
+ import numpy as np
12
+ import torch
13
+ import torch.nn as nn
14
+ import torch.nn.functional as F
15
+
16
+ from MedSAM2.sam2.utils.misc import mask_to_box
17
+
18
+
19
+ def select_closest_cond_frames(frame_idx, cond_frame_outputs, max_cond_frame_num):
20
+ """
21
+ Select up to `max_cond_frame_num` conditioning frames from `cond_frame_outputs`
22
+ that are temporally closest to the current frame at `frame_idx`. Here, we take
23
+ - a) the closest conditioning frame before `frame_idx` (if any);
24
+ - b) the closest conditioning frame after `frame_idx` (if any);
25
+ - c) any other temporally closest conditioning frames until reaching a total
26
+ of `max_cond_frame_num` conditioning frames.
27
+
28
+ Outputs:
29
+ - selected_outputs: selected items (keys & values) from `cond_frame_outputs`.
30
+ - unselected_outputs: items (keys & values) not selected in `cond_frame_outputs`.
31
+ """
32
+ if max_cond_frame_num == -1 or len(cond_frame_outputs) <= max_cond_frame_num:
33
+ selected_outputs = cond_frame_outputs
34
+ unselected_outputs = {}
35
+ else:
36
+ assert max_cond_frame_num >= 2, "we should allow using 2+ conditioning frames"
37
+ selected_outputs = {}
38
+
39
+ # the closest conditioning frame before `frame_idx` (if any)
40
+ idx_before = max((t for t in cond_frame_outputs if t < frame_idx), default=None)
41
+ if idx_before is not None:
42
+ selected_outputs[idx_before] = cond_frame_outputs[idx_before]
43
+
44
+ # the closest conditioning frame after `frame_idx` (if any)
45
+ idx_after = min((t for t in cond_frame_outputs if t >= frame_idx), default=None)
46
+ if idx_after is not None:
47
+ selected_outputs[idx_after] = cond_frame_outputs[idx_after]
48
+
49
+ # add other temporally closest conditioning frames until reaching a total
50
+ # of `max_cond_frame_num` conditioning frames.
51
+ num_remain = max_cond_frame_num - len(selected_outputs)
52
+ inds_remain = sorted(
53
+ (t for t in cond_frame_outputs if t not in selected_outputs),
54
+ key=lambda x: abs(x - frame_idx),
55
+ )[:num_remain]
56
+ selected_outputs.update((t, cond_frame_outputs[t]) for t in inds_remain)
57
+ unselected_outputs = {
58
+ t: v for t, v in cond_frame_outputs.items() if t not in selected_outputs
59
+ }
60
+
61
+ return selected_outputs, unselected_outputs
62
+
63
+
64
+ def get_1d_sine_pe(pos_inds, dim, temperature=10000):
65
+ """
66
+ Get 1D sine positional embedding as in the original Transformer paper.
67
+ """
68
+ pe_dim = dim // 2
69
+ dim_t = torch.arange(pe_dim, dtype=torch.float32, device=pos_inds.device)
70
+ dim_t = temperature ** (2 * (dim_t // 2) / pe_dim)
71
+
72
+ pos_embed = pos_inds.unsqueeze(-1) / dim_t
73
+ pos_embed = torch.cat([pos_embed.sin(), pos_embed.cos()], dim=-1)
74
+ return pos_embed
75
+
76
+
77
+ def get_activation_fn(activation):
78
+ """Return an activation function given a string"""
79
+ if activation == "relu":
80
+ return F.relu
81
+ if activation == "gelu":
82
+ return F.gelu
83
+ if activation == "glu":
84
+ return F.glu
85
+ raise RuntimeError(f"activation should be relu/gelu, not {activation}.")
86
+
87
+
88
+ def get_clones(module, N):
89
+ return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
90
+
91
+
92
+ class DropPath(nn.Module):
93
+ # adapted from https://github.com/huggingface/pytorch-image-models/blob/main/timm/layers/drop.py
94
+ def __init__(self, drop_prob=0.0, scale_by_keep=True):
95
+ super(DropPath, self).__init__()
96
+ self.drop_prob = drop_prob
97
+ self.scale_by_keep = scale_by_keep
98
+
99
+ def forward(self, x):
100
+ if self.drop_prob == 0.0 or not self.training:
101
+ return x
102
+ keep_prob = 1 - self.drop_prob
103
+ shape = (x.shape[0],) + (1,) * (x.ndim - 1)
104
+ random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
105
+ if keep_prob > 0.0 and self.scale_by_keep:
106
+ random_tensor.div_(keep_prob)
107
+ return x * random_tensor
108
+
109
+
110
+ # Lightly adapted from
111
+ # https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py # noqa
112
+ class MLP(nn.Module):
113
+ def __init__(
114
+ self,
115
+ input_dim: int,
116
+ hidden_dim: int,
117
+ output_dim: int,
118
+ num_layers: int,
119
+ activation: nn.Module = nn.ReLU,
120
+ sigmoid_output: bool = False,
121
+ ) -> None:
122
+ super().__init__()
123
+ self.num_layers = num_layers
124
+ h = [hidden_dim] * (num_layers - 1)
125
+ self.layers = nn.ModuleList(
126
+ nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim])
127
+ )
128
+ self.sigmoid_output = sigmoid_output
129
+ self.act = activation()
130
+
131
+ def forward(self, x):
132
+ for i, layer in enumerate(self.layers):
133
+ x = self.act(layer(x)) if i < self.num_layers - 1 else layer(x)
134
+ if self.sigmoid_output:
135
+ x = F.sigmoid(x)
136
+ return x
137
+
138
+
139
+ # From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa
140
+ # Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa
141
+ class LayerNorm2d(nn.Module):
142
+ def __init__(self, num_channels: int, eps: float = 1e-6) -> None:
143
+ super().__init__()
144
+ self.weight = nn.Parameter(torch.ones(num_channels))
145
+ self.bias = nn.Parameter(torch.zeros(num_channels))
146
+ self.eps = eps
147
+
148
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
149
+ u = x.mean(1, keepdim=True)
150
+ s = (x - u).pow(2).mean(1, keepdim=True)
151
+ x = (x - u) / torch.sqrt(s + self.eps)
152
+ x = self.weight[:, None, None] * x + self.bias[:, None, None]
153
+ return x
154
+
155
+
156
+ def sample_box_points(
157
+ masks: torch.Tensor,
158
+ noise: float = 0.1, # SAM default
159
+ noise_bound: int = 10, # SAM default
160
+ top_left_label: int = 2,
161
+ bottom_right_label: int = 3,
162
+ ) -> Tuple[np.array, np.array]:
163
+ """
164
+ Sample a noised version of the top left and bottom right corners of a given `bbox`
165
+
166
+ Inputs:
167
+ - masks: [B, 1, H,W] boxes, dtype=torch.Tensor
168
+ - noise: noise as a fraction of box width and height, dtype=float
169
+ - noise_bound: maximum amount of noise (in pure pixesl), dtype=int
170
+
171
+ Returns:
172
+ - box_coords: [B, num_pt, 2], contains (x, y) coordinates of top left and bottom right box corners, dtype=torch.float
173
+ - box_labels: [B, num_pt], label 2 is reserverd for top left and 3 for bottom right corners, dtype=torch.int32
174
+ """
175
+ device = masks.device
176
+ box_coords = mask_to_box(masks)
177
+ B, _, H, W = masks.shape
178
+ box_labels = torch.tensor(
179
+ [top_left_label, bottom_right_label], dtype=torch.int, device=device
180
+ ).repeat(B)
181
+ if noise > 0.0:
182
+ if not isinstance(noise_bound, torch.Tensor):
183
+ noise_bound = torch.tensor(noise_bound, device=device)
184
+ bbox_w = box_coords[..., 2] - box_coords[..., 0]
185
+ bbox_h = box_coords[..., 3] - box_coords[..., 1]
186
+ max_dx = torch.min(bbox_w * noise, noise_bound)
187
+ max_dy = torch.min(bbox_h * noise, noise_bound)
188
+ box_noise = 2 * torch.rand(B, 1, 4, device=device) - 1
189
+ box_noise = box_noise * torch.stack((max_dx, max_dy, max_dx, max_dy), dim=-1)
190
+
191
+ box_coords = box_coords + box_noise
192
+ img_bounds = (
193
+ torch.tensor([W, H, W, H], device=device) - 1
194
+ ) # uncentered pixel coords
195
+ box_coords.clamp_(torch.zeros_like(img_bounds), img_bounds) # In place clamping
196
+
197
+ box_coords = box_coords.reshape(-1, 2, 2) # always 2 points
198
+ box_labels = box_labels.reshape(-1, 2)
199
+ return box_coords, box_labels
200
+
201
+
202
+ def sample_random_points_from_errors(gt_masks, pred_masks, num_pt=1):
203
+ """
204
+ Sample `num_pt` random points (along with their labels) independently from the error regions.
205
+
206
+ Inputs:
207
+ - gt_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool
208
+ - pred_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool or None
209
+ - num_pt: int, number of points to sample independently for each of the B error maps
210
+
211
+ Outputs:
212
+ - points: [B, num_pt, 2], dtype=torch.float, contains (x, y) coordinates of each sampled point
213
+ - labels: [B, num_pt], dtype=torch.int32, where 1 means positive clicks and 0 means
214
+ negative clicks
215
+ """
216
+ if pred_masks is None: # if pred_masks is not provided, treat it as empty
217
+ pred_masks = torch.zeros_like(gt_masks)
218
+ assert gt_masks.dtype == torch.bool and gt_masks.size(1) == 1
219
+ assert pred_masks.dtype == torch.bool and pred_masks.shape == gt_masks.shape
220
+ assert num_pt >= 0
221
+
222
+ B, _, H_im, W_im = gt_masks.shape
223
+ device = gt_masks.device
224
+
225
+ # false positive region, a new point sampled in this region should have
226
+ # negative label to correct the FP error
227
+ fp_masks = ~gt_masks & pred_masks
228
+ # false negative region, a new point sampled in this region should have
229
+ # positive label to correct the FN error
230
+ fn_masks = gt_masks & ~pred_masks
231
+ # whether the prediction completely match the ground-truth on each mask
232
+ all_correct = torch.all((gt_masks == pred_masks).flatten(2), dim=2)
233
+ all_correct = all_correct[..., None, None]
234
+
235
+ # channel 0 is FP map, while channel 1 is FN map
236
+ pts_noise = torch.rand(B, num_pt, H_im, W_im, 2, device=device)
237
+ # sample a negative new click from FP region or a positive new click
238
+ # from FN region, depend on where the maximum falls,
239
+ # and in case the predictions are all correct (no FP or FN), we just
240
+ # sample a negative click from the background region
241
+ pts_noise[..., 0] *= fp_masks | (all_correct & ~gt_masks)
242
+ pts_noise[..., 1] *= fn_masks
243
+ pts_idx = pts_noise.flatten(2).argmax(dim=2)
244
+ labels = (pts_idx % 2).to(torch.int32)
245
+ pts_idx = pts_idx // 2
246
+ pts_x = pts_idx % W_im
247
+ pts_y = pts_idx // W_im
248
+ points = torch.stack([pts_x, pts_y], dim=2).to(torch.float)
249
+ return points, labels
250
+
251
+
252
+ def sample_one_point_from_error_center(gt_masks, pred_masks, padding=True):
253
+ """
254
+ Sample 1 random point (along with its label) from the center of each error region,
255
+ that is, the point with the largest distance to the boundary of each error region.
256
+ This is the RITM sampling method from https://github.com/saic-vul/ritm_interactive_segmentation/blob/master/isegm/inference/clicker.py
257
+
258
+ Inputs:
259
+ - gt_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool
260
+ - pred_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool or None
261
+ - padding: if True, pad with boundary of 1 px for distance transform
262
+
263
+ Outputs:
264
+ - points: [B, 1, 2], dtype=torch.float, contains (x, y) coordinates of each sampled point
265
+ - labels: [B, 1], dtype=torch.int32, where 1 means positive clicks and 0 means negative clicks
266
+ """
267
+ import cv2
268
+
269
+ if pred_masks is None:
270
+ pred_masks = torch.zeros_like(gt_masks)
271
+ assert gt_masks.dtype == torch.bool and gt_masks.size(1) == 1
272
+ assert pred_masks.dtype == torch.bool and pred_masks.shape == gt_masks.shape
273
+
274
+ B, _, _, W_im = gt_masks.shape
275
+ device = gt_masks.device
276
+
277
+ # false positive region, a new point sampled in this region should have
278
+ # negative label to correct the FP error
279
+ fp_masks = ~gt_masks & pred_masks
280
+ # false negative region, a new point sampled in this region should have
281
+ # positive label to correct the FN error
282
+ fn_masks = gt_masks & ~pred_masks
283
+
284
+ fp_masks = fp_masks.cpu().numpy()
285
+ fn_masks = fn_masks.cpu().numpy()
286
+ points = torch.zeros(B, 1, 2, dtype=torch.float)
287
+ labels = torch.ones(B, 1, dtype=torch.int32)
288
+ for b in range(B):
289
+ fn_mask = fn_masks[b, 0]
290
+ fp_mask = fp_masks[b, 0]
291
+ if padding:
292
+ fn_mask = np.pad(fn_mask, ((1, 1), (1, 1)), "constant")
293
+ fp_mask = np.pad(fp_mask, ((1, 1), (1, 1)), "constant")
294
+ # compute the distance of each point in FN/FP region to its boundary
295
+ fn_mask_dt = cv2.distanceTransform(fn_mask.astype(np.uint8), cv2.DIST_L2, 0)
296
+ fp_mask_dt = cv2.distanceTransform(fp_mask.astype(np.uint8), cv2.DIST_L2, 0)
297
+ if padding:
298
+ fn_mask_dt = fn_mask_dt[1:-1, 1:-1]
299
+ fp_mask_dt = fp_mask_dt[1:-1, 1:-1]
300
+
301
+ # take the point in FN/FP region with the largest distance to its boundary
302
+ fn_mask_dt_flat = fn_mask_dt.reshape(-1)
303
+ fp_mask_dt_flat = fp_mask_dt.reshape(-1)
304
+ fn_argmax = np.argmax(fn_mask_dt_flat)
305
+ fp_argmax = np.argmax(fp_mask_dt_flat)
306
+ is_positive = fn_mask_dt_flat[fn_argmax] > fp_mask_dt_flat[fp_argmax]
307
+ pt_idx = fn_argmax if is_positive else fp_argmax
308
+ points[b, 0, 0] = pt_idx % W_im # x
309
+ points[b, 0, 1] = pt_idx // W_im # y
310
+ labels[b, 0] = int(is_positive)
311
+
312
+ points = points.to(device)
313
+ labels = labels.to(device)
314
+ return points, labels
315
+
316
+
317
+ def get_next_point(gt_masks, pred_masks, method):
318
+ if method == "uniform":
319
+ return sample_random_points_from_errors(gt_masks, pred_masks)
320
+ elif method == "center":
321
+ return sample_one_point_from_error_center(gt_masks, pred_masks)
322
+ else:
323
+ raise ValueError(f"unknown sampling method {method}")
324
+
325
+
326
+ class LayerScale(nn.Module):
327
+ def __init__(
328
+ self,
329
+ dim: int,
330
+ init_values: Union[float, torch.Tensor] = 1e-5,
331
+ inplace: bool = False,
332
+ ) -> None:
333
+ super().__init__()
334
+ self.inplace = inplace
335
+ self.gamma = nn.Parameter(init_values * torch.ones(dim))
336
+
337
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
338
+ return x.mul_(self.gamma) if self.inplace else x * self.gamma
MedSAM2/sam2/modeling/memory_attention.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from typing import Optional
8
+
9
+ import torch
10
+ from torch import nn, Tensor
11
+
12
+ from MedSAM2.sam2.modeling.sam.transformer import RoPEAttention
13
+
14
+ from MedSAM2.sam2.modeling.sam2_utils import get_activation_fn, get_clones
15
+
16
+
17
+ class MemoryAttentionLayer(nn.Module):
18
+
19
+ def __init__(
20
+ self,
21
+ activation: str,
22
+ cross_attention: nn.Module,
23
+ d_model: int,
24
+ dim_feedforward: int,
25
+ dropout: float,
26
+ pos_enc_at_attn: bool,
27
+ pos_enc_at_cross_attn_keys: bool,
28
+ pos_enc_at_cross_attn_queries: bool,
29
+ self_attention: nn.Module,
30
+ ):
31
+ super().__init__()
32
+ self.d_model = d_model
33
+ self.dim_feedforward = dim_feedforward
34
+ self.dropout_value = dropout
35
+ self.self_attn = self_attention
36
+ self.cross_attn_image = cross_attention
37
+
38
+ # Implementation of Feedforward model
39
+ self.linear1 = nn.Linear(d_model, dim_feedforward)
40
+ self.dropout = nn.Dropout(dropout)
41
+ self.linear2 = nn.Linear(dim_feedforward, d_model)
42
+
43
+ self.norm1 = nn.LayerNorm(d_model)
44
+ self.norm2 = nn.LayerNorm(d_model)
45
+ self.norm3 = nn.LayerNorm(d_model)
46
+ self.dropout1 = nn.Dropout(dropout)
47
+ self.dropout2 = nn.Dropout(dropout)
48
+ self.dropout3 = nn.Dropout(dropout)
49
+
50
+ self.activation_str = activation
51
+ self.activation = get_activation_fn(activation)
52
+
53
+ # Where to add pos enc
54
+ self.pos_enc_at_attn = pos_enc_at_attn
55
+ self.pos_enc_at_cross_attn_queries = pos_enc_at_cross_attn_queries
56
+ self.pos_enc_at_cross_attn_keys = pos_enc_at_cross_attn_keys
57
+
58
+ def _forward_sa(self, tgt, query_pos):
59
+ # Self-Attention
60
+ tgt2 = self.norm1(tgt)
61
+ q = k = tgt2 + query_pos if self.pos_enc_at_attn else tgt2
62
+ tgt2 = self.self_attn(q, k, v=tgt2)
63
+ tgt = tgt + self.dropout1(tgt2)
64
+ return tgt
65
+
66
+ def _forward_ca(self, tgt, memory, query_pos, pos, num_k_exclude_rope=0):
67
+ kwds = {}
68
+ if num_k_exclude_rope > 0:
69
+ assert isinstance(self.cross_attn_image, RoPEAttention)
70
+ kwds = {"num_k_exclude_rope": num_k_exclude_rope}
71
+
72
+ # Cross-Attention
73
+ tgt2 = self.norm2(tgt)
74
+ tgt2 = self.cross_attn_image(
75
+ q=tgt2 + query_pos if self.pos_enc_at_cross_attn_queries else tgt2,
76
+ k=memory + pos if self.pos_enc_at_cross_attn_keys else memory,
77
+ v=memory,
78
+ **kwds,
79
+ )
80
+ tgt = tgt + self.dropout2(tgt2)
81
+ return tgt
82
+
83
+ def forward(
84
+ self,
85
+ tgt,
86
+ memory,
87
+ pos: Optional[Tensor] = None,
88
+ query_pos: Optional[Tensor] = None,
89
+ num_k_exclude_rope: int = 0,
90
+ ) -> torch.Tensor:
91
+
92
+ # Self-Attn, Cross-Attn
93
+ tgt = self._forward_sa(tgt, query_pos)
94
+ tgt = self._forward_ca(tgt, memory, query_pos, pos, num_k_exclude_rope)
95
+ # MLP
96
+ tgt2 = self.norm3(tgt)
97
+ tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2))))
98
+ tgt = tgt + self.dropout3(tgt2)
99
+ return tgt
100
+
101
+
102
+ class MemoryAttention(nn.Module):
103
+ def __init__(
104
+ self,
105
+ d_model: int,
106
+ pos_enc_at_input: bool,
107
+ layer: nn.Module,
108
+ num_layers: int,
109
+ batch_first: bool = True, # Do layers expect batch first input?
110
+ ):
111
+ super().__init__()
112
+ self.d_model = d_model
113
+ self.layers = get_clones(layer, num_layers)
114
+ self.num_layers = num_layers
115
+ self.norm = nn.LayerNorm(d_model)
116
+ self.pos_enc_at_input = pos_enc_at_input
117
+ self.batch_first = batch_first
118
+
119
+ def forward(
120
+ self,
121
+ curr: torch.Tensor, # self-attention inputs
122
+ memory: torch.Tensor, # cross-attention inputs
123
+ curr_pos: Optional[Tensor] = None, # pos_enc for self-attention inputs
124
+ memory_pos: Optional[Tensor] = None, # pos_enc for cross-attention inputs
125
+ num_obj_ptr_tokens: int = 0, # number of object pointer *tokens*
126
+ ):
127
+ if isinstance(curr, list):
128
+ assert isinstance(curr_pos, list)
129
+ assert len(curr) == len(curr_pos) == 1
130
+ curr, curr_pos = (
131
+ curr[0],
132
+ curr_pos[0],
133
+ )
134
+
135
+ assert (
136
+ curr.shape[1] == memory.shape[1]
137
+ ), "Batch size must be the same for curr and memory"
138
+
139
+ output = curr
140
+ if self.pos_enc_at_input and curr_pos is not None:
141
+ output = output + 0.1 * curr_pos
142
+
143
+ if self.batch_first:
144
+ # Convert to batch first
145
+ output = output.transpose(0, 1)
146
+ curr_pos = curr_pos.transpose(0, 1)
147
+ memory = memory.transpose(0, 1)
148
+ memory_pos = memory_pos.transpose(0, 1)
149
+
150
+ for layer in self.layers:
151
+ kwds = {}
152
+ if isinstance(layer.cross_attn_image, RoPEAttention):
153
+ kwds = {"num_k_exclude_rope": num_obj_ptr_tokens}
154
+
155
+ output = layer(
156
+ tgt=output,
157
+ memory=memory,
158
+ pos=memory_pos,
159
+ query_pos=curr_pos,
160
+ **kwds,
161
+ )
162
+ normed_output = self.norm(output)
163
+
164
+ if self.batch_first:
165
+ # Convert back to seq first
166
+ normed_output = normed_output.transpose(0, 1)
167
+ curr_pos = curr_pos.transpose(0, 1)
168
+
169
+ return normed_output
MedSAM2/sam2/modeling/memory_encoder.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import math
8
+ from typing import Tuple
9
+
10
+ import torch
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+
14
+ from MedSAM2.sam2.modeling.sam2_utils import DropPath, get_clones, LayerNorm2d
15
+
16
+
17
+ class MaskDownSampler(nn.Module):
18
+ """
19
+ Progressively downsample a mask by total_stride, each time by stride.
20
+ Note that LayerNorm is applied per *token*, like in ViT.
21
+
22
+ With each downsample (by a factor stride**2), channel capacity increases by the same factor.
23
+ In the end, we linearly project to embed_dim channels.
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ embed_dim=256,
29
+ kernel_size=4,
30
+ stride=4,
31
+ padding=0,
32
+ total_stride=16,
33
+ activation=nn.GELU,
34
+ ):
35
+ super().__init__()
36
+ num_layers = int(math.log2(total_stride) // math.log2(stride))
37
+ assert stride**num_layers == total_stride
38
+ self.encoder = nn.Sequential()
39
+ mask_in_chans, mask_out_chans = 1, 1
40
+ for _ in range(num_layers):
41
+ mask_out_chans = mask_in_chans * (stride**2)
42
+ self.encoder.append(
43
+ nn.Conv2d(
44
+ mask_in_chans,
45
+ mask_out_chans,
46
+ kernel_size=kernel_size,
47
+ stride=stride,
48
+ padding=padding,
49
+ )
50
+ )
51
+ self.encoder.append(LayerNorm2d(mask_out_chans))
52
+ self.encoder.append(activation())
53
+ mask_in_chans = mask_out_chans
54
+
55
+ self.encoder.append(nn.Conv2d(mask_out_chans, embed_dim, kernel_size=1))
56
+
57
+ def forward(self, x):
58
+ return self.encoder(x)
59
+
60
+
61
+ # Lightly adapted from ConvNext (https://github.com/facebookresearch/ConvNeXt)
62
+ class CXBlock(nn.Module):
63
+ r"""ConvNeXt Block. There are two equivalent implementations:
64
+ (1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W)
65
+ (2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back
66
+ We use (2) as we find it slightly faster in PyTorch
67
+
68
+ Args:
69
+ dim (int): Number of input channels.
70
+ drop_path (float): Stochastic depth rate. Default: 0.0
71
+ layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6.
72
+ """
73
+
74
+ def __init__(
75
+ self,
76
+ dim,
77
+ kernel_size=7,
78
+ padding=3,
79
+ drop_path=0.0,
80
+ layer_scale_init_value=1e-6,
81
+ use_dwconv=True,
82
+ ):
83
+ super().__init__()
84
+ self.dwconv = nn.Conv2d(
85
+ dim,
86
+ dim,
87
+ kernel_size=kernel_size,
88
+ padding=padding,
89
+ groups=dim if use_dwconv else 1,
90
+ ) # depthwise conv
91
+ self.norm = LayerNorm2d(dim, eps=1e-6)
92
+ self.pwconv1 = nn.Linear(
93
+ dim, 4 * dim
94
+ ) # pointwise/1x1 convs, implemented with linear layers
95
+ self.act = nn.GELU()
96
+ self.pwconv2 = nn.Linear(4 * dim, dim)
97
+ self.gamma = (
98
+ nn.Parameter(layer_scale_init_value * torch.ones((dim)), requires_grad=True)
99
+ if layer_scale_init_value > 0
100
+ else None
101
+ )
102
+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
103
+
104
+ def forward(self, x):
105
+ input = x
106
+ x = self.dwconv(x)
107
+ x = self.norm(x)
108
+ x = x.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C)
109
+ x = self.pwconv1(x)
110
+ x = self.act(x)
111
+ x = self.pwconv2(x)
112
+ if self.gamma is not None:
113
+ x = self.gamma * x
114
+ x = x.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W)
115
+
116
+ x = input + self.drop_path(x)
117
+ return x
118
+
119
+
120
+ class Fuser(nn.Module):
121
+ def __init__(self, layer, num_layers, dim=None, input_projection=False):
122
+ super().__init__()
123
+ self.proj = nn.Identity()
124
+ self.layers = get_clones(layer, num_layers)
125
+
126
+ if input_projection:
127
+ assert dim is not None
128
+ self.proj = nn.Conv2d(dim, dim, kernel_size=1)
129
+
130
+ def forward(self, x):
131
+ # normally x: (N, C, H, W)
132
+ x = self.proj(x)
133
+ for layer in self.layers:
134
+ x = layer(x)
135
+ return x
136
+
137
+
138
+ class MemoryEncoder(nn.Module):
139
+ def __init__(
140
+ self,
141
+ out_dim,
142
+ mask_downsampler,
143
+ fuser,
144
+ position_encoding,
145
+ in_dim=256, # in_dim of pix_feats
146
+ ):
147
+ super().__init__()
148
+
149
+ self.mask_downsampler = mask_downsampler
150
+
151
+ self.pix_feat_proj = nn.Conv2d(in_dim, in_dim, kernel_size=1)
152
+ self.fuser = fuser
153
+ self.position_encoding = position_encoding
154
+ self.out_proj = nn.Identity()
155
+ if out_dim != in_dim:
156
+ self.out_proj = nn.Conv2d(in_dim, out_dim, kernel_size=1)
157
+
158
+ def forward(
159
+ self,
160
+ pix_feat: torch.Tensor,
161
+ masks: torch.Tensor,
162
+ skip_mask_sigmoid: bool = False,
163
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
164
+ ## Process masks
165
+ # sigmoid, so that less domain shift from gt masks which are bool
166
+ if not skip_mask_sigmoid:
167
+ masks = F.sigmoid(masks)
168
+ masks = self.mask_downsampler(masks)
169
+
170
+ ## Fuse pix_feats and downsampled masks
171
+ # in case the visual features are on CPU, cast them to CUDA
172
+ pix_feat = pix_feat.to(masks.device)
173
+
174
+ x = self.pix_feat_proj(pix_feat)
175
+ x = x + masks
176
+ x = self.fuser(x)
177
+ x = self.out_proj(x)
178
+
179
+ pos = self.position_encoding(x).to(x.dtype)
180
+
181
+ return {"vision_features": x, "vision_pos_enc": [pos]}
MedSAM2/sam2/modeling/position_encoding.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import math
8
+ from typing import Any, Optional, Tuple
9
+
10
+ import numpy as np
11
+
12
+ import torch
13
+ from torch import nn
14
+
15
+
16
+ class PositionEmbeddingSine(nn.Module):
17
+ """
18
+ This is a more standard version of the position embedding, very similar to the one
19
+ used by the Attention Is All You Need paper, generalized to work on images.
20
+ """
21
+
22
+ def __init__(
23
+ self,
24
+ num_pos_feats,
25
+ temperature: int = 10000,
26
+ normalize: bool = True,
27
+ scale: Optional[float] = None,
28
+ ):
29
+ super().__init__()
30
+ assert num_pos_feats % 2 == 0, "Expecting even model width"
31
+ self.num_pos_feats = num_pos_feats // 2
32
+ self.temperature = temperature
33
+ self.normalize = normalize
34
+ if scale is not None and normalize is False:
35
+ raise ValueError("normalize should be True if scale is passed")
36
+ if scale is None:
37
+ scale = 2 * math.pi
38
+ self.scale = scale
39
+
40
+ self.cache = {}
41
+
42
+ def _encode_xy(self, x, y):
43
+ # The positions are expected to be normalized
44
+ assert len(x) == len(y) and x.ndim == y.ndim == 1
45
+ x_embed = x * self.scale
46
+ y_embed = y * self.scale
47
+
48
+ dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device)
49
+ dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)
50
+
51
+ pos_x = x_embed[:, None] / dim_t
52
+ pos_y = y_embed[:, None] / dim_t
53
+ pos_x = torch.stack(
54
+ (pos_x[:, 0::2].sin(), pos_x[:, 1::2].cos()), dim=2
55
+ ).flatten(1)
56
+ pos_y = torch.stack(
57
+ (pos_y[:, 0::2].sin(), pos_y[:, 1::2].cos()), dim=2
58
+ ).flatten(1)
59
+ return pos_x, pos_y
60
+
61
+ @torch.no_grad()
62
+ def encode_boxes(self, x, y, w, h):
63
+ pos_x, pos_y = self._encode_xy(x, y)
64
+ pos = torch.cat((pos_y, pos_x, h[:, None], w[:, None]), dim=1)
65
+ return pos
66
+
67
+ encode = encode_boxes # Backwards compatibility
68
+
69
+ @torch.no_grad()
70
+ def encode_points(self, x, y, labels):
71
+ (bx, nx), (by, ny), (bl, nl) = x.shape, y.shape, labels.shape
72
+ assert bx == by and nx == ny and bx == bl and nx == nl
73
+ pos_x, pos_y = self._encode_xy(x.flatten(), y.flatten())
74
+ pos_x, pos_y = pos_x.reshape(bx, nx, -1), pos_y.reshape(by, ny, -1)
75
+ pos = torch.cat((pos_y, pos_x, labels[:, :, None]), dim=2)
76
+ return pos
77
+
78
+ @torch.no_grad()
79
+ def forward(self, x: torch.Tensor):
80
+ cache_key = (x.shape[-2], x.shape[-1])
81
+ if cache_key in self.cache:
82
+ return self.cache[cache_key][None].repeat(x.shape[0], 1, 1, 1)
83
+ y_embed = (
84
+ torch.arange(1, x.shape[-2] + 1, dtype=torch.float32, device=x.device)
85
+ .view(1, -1, 1)
86
+ .repeat(x.shape[0], 1, x.shape[-1])
87
+ )
88
+ x_embed = (
89
+ torch.arange(1, x.shape[-1] + 1, dtype=torch.float32, device=x.device)
90
+ .view(1, 1, -1)
91
+ .repeat(x.shape[0], x.shape[-2], 1)
92
+ )
93
+
94
+ if self.normalize:
95
+ eps = 1e-6
96
+ y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale
97
+ x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale
98
+
99
+ dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device)
100
+ dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)
101
+
102
+ pos_x = x_embed[:, :, :, None] / dim_t
103
+ pos_y = y_embed[:, :, :, None] / dim_t
104
+ pos_x = torch.stack(
105
+ (pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4
106
+ ).flatten(3)
107
+ pos_y = torch.stack(
108
+ (pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4
109
+ ).flatten(3)
110
+ pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
111
+ self.cache[cache_key] = pos[0]
112
+ return pos
113
+
114
+
115
+ class PositionEmbeddingRandom(nn.Module):
116
+ """
117
+ Positional encoding using random spatial frequencies.
118
+ """
119
+
120
+ def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None:
121
+ super().__init__()
122
+ if scale is None or scale <= 0.0:
123
+ scale = 1.0
124
+ self.register_buffer(
125
+ "positional_encoding_gaussian_matrix",
126
+ scale * torch.randn((2, num_pos_feats)),
127
+ )
128
+
129
+ def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor:
130
+ """Positionally encode points that are normalized to [0,1]."""
131
+ # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape
132
+ coords = 2 * coords - 1
133
+ coords = coords @ self.positional_encoding_gaussian_matrix
134
+ coords = 2 * np.pi * coords
135
+ # outputs d_1 x ... x d_n x C shape
136
+ return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1)
137
+
138
+ def forward(self, size: Tuple[int, int]) -> torch.Tensor:
139
+ """Generate positional encoding for a grid of the specified size."""
140
+ h, w = size
141
+ device: Any = self.positional_encoding_gaussian_matrix.device
142
+ grid = torch.ones((h, w), device=device, dtype=torch.float32)
143
+ y_embed = grid.cumsum(dim=0) - 0.5
144
+ x_embed = grid.cumsum(dim=1) - 0.5
145
+ y_embed = y_embed / h
146
+ x_embed = x_embed / w
147
+
148
+ pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1))
149
+ return pe.permute(2, 0, 1) # C x H x W
150
+
151
+ def forward_with_coords(
152
+ self, coords_input: torch.Tensor, image_size: Tuple[int, int]
153
+ ) -> torch.Tensor:
154
+ """Positionally encode points that are not normalized to [0,1]."""
155
+ coords = coords_input.clone()
156
+ coords[:, :, 0] = coords[:, :, 0] / image_size[1]
157
+ coords[:, :, 1] = coords[:, :, 1] / image_size[0]
158
+ return self._pe_encoding(coords.to(torch.float)) # B x N x C
159
+
160
+
161
+ # Rotary Positional Encoding, adapted from:
162
+ # 1. https://github.com/meta-llama/codellama/blob/main/llama/model.py
163
+ # 2. https://github.com/naver-ai/rope-vit
164
+ # 3. https://github.com/lucidrains/rotary-embedding-torch
165
+
166
+
167
+ def init_t_xy(end_x: int, end_y: int):
168
+ t = torch.arange(end_x * end_y, dtype=torch.float32)
169
+ t_x = (t % end_x).float()
170
+ t_y = torch.div(t, end_x, rounding_mode="floor").float()
171
+ return t_x, t_y
172
+
173
+
174
+ def compute_axial_cis(dim: int, end_x: int, end_y: int, theta: float = 10000.0):
175
+ freqs_x = 1.0 / (theta ** (torch.arange(0, dim, 4)[: (dim // 4)].float() / dim))
176
+ freqs_y = 1.0 / (theta ** (torch.arange(0, dim, 4)[: (dim // 4)].float() / dim))
177
+
178
+ t_x, t_y = init_t_xy(end_x, end_y)
179
+ freqs_x = torch.outer(t_x, freqs_x)
180
+ freqs_y = torch.outer(t_y, freqs_y)
181
+ freqs_cis_x = torch.polar(torch.ones_like(freqs_x), freqs_x)
182
+ freqs_cis_y = torch.polar(torch.ones_like(freqs_y), freqs_y)
183
+ return torch.cat([freqs_cis_x, freqs_cis_y], dim=-1)
184
+
185
+
186
+ def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor):
187
+ ndim = x.ndim
188
+ assert 0 <= 1 < ndim
189
+ assert freqs_cis.shape == (x.shape[-2], x.shape[-1])
190
+ shape = [d if i >= ndim - 2 else 1 for i, d in enumerate(x.shape)]
191
+ return freqs_cis.view(*shape)
192
+
193
+
194
+ def apply_rotary_enc(
195
+ xq: torch.Tensor,
196
+ xk: torch.Tensor,
197
+ freqs_cis: torch.Tensor,
198
+ repeat_freqs_k: bool = False,
199
+ ):
200
+ xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
201
+ xk_ = (
202
+ torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
203
+ if xk.shape[-2] != 0
204
+ else None
205
+ )
206
+ freqs_cis = reshape_for_broadcast(freqs_cis, xq_)
207
+ xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3)
208
+ if xk_ is None:
209
+ # no keys to rotate, due to dropout
210
+ return xq_out.type_as(xq).to(xq.device), xk
211
+ # repeat freqs along seq_len dim to match k seq_len
212
+ if repeat_freqs_k:
213
+ r = xk_.shape[-2] // xq_.shape[-2]
214
+ if freqs_cis.is_cuda:
215
+ freqs_cis = freqs_cis.repeat(*([1] * (freqs_cis.ndim - 2)), r, 1)
216
+ else:
217
+ # torch.repeat on complex numbers may not be supported on non-CUDA devices
218
+ # (freqs_cis has 4 dims and we repeat on dim 2) so we use expand + flatten
219
+ freqs_cis = freqs_cis.unsqueeze(2).expand(-1, -1, r, -1, -1).flatten(2, 3)
220
+ xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3)
221
+ return xq_out.type_as(xq).to(xq.device), xk_out.type_as(xk).to(xk.device)
MedSAM2/sam2/modeling/sam/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
MedSAM2/sam2/modeling/sam/mask_decoder.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from typing import List, Optional, Tuple, Type
8
+
9
+ import torch
10
+ from torch import nn
11
+
12
+ from MedSAM2.sam2.modeling.sam2_utils import LayerNorm2d, MLP
13
+
14
+
15
+ class MaskDecoder(nn.Module):
16
+ def __init__(
17
+ self,
18
+ *,
19
+ transformer_dim: int,
20
+ transformer: nn.Module,
21
+ num_multimask_outputs: int = 3,
22
+ activation: Type[nn.Module] = nn.GELU,
23
+ iou_head_depth: int = 3,
24
+ iou_head_hidden_dim: int = 256,
25
+ use_high_res_features: bool = False,
26
+ iou_prediction_use_sigmoid=False,
27
+ dynamic_multimask_via_stability=False,
28
+ dynamic_multimask_stability_delta=0.05,
29
+ dynamic_multimask_stability_thresh=0.98,
30
+ pred_obj_scores: bool = False,
31
+ pred_obj_scores_mlp: bool = False,
32
+ use_multimask_token_for_obj_ptr: bool = False,
33
+ ) -> None:
34
+ """
35
+ Predicts masks given an image and prompt embeddings, using a
36
+ transformer architecture.
37
+
38
+ Arguments:
39
+ transformer_dim (int): the channel dimension of the transformer
40
+ transformer (nn.Module): the transformer used to predict masks
41
+ num_multimask_outputs (int): the number of masks to predict
42
+ when disambiguating masks
43
+ activation (nn.Module): the type of activation to use when
44
+ upscaling masks
45
+ iou_head_depth (int): the depth of the MLP used to predict
46
+ mask quality
47
+ iou_head_hidden_dim (int): the hidden dimension of the MLP
48
+ used to predict mask quality
49
+ """
50
+ super().__init__()
51
+ self.transformer_dim = transformer_dim
52
+ self.transformer = transformer
53
+
54
+ self.num_multimask_outputs = num_multimask_outputs
55
+
56
+ self.iou_token = nn.Embedding(1, transformer_dim)
57
+ self.num_mask_tokens = num_multimask_outputs + 1
58
+ self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim)
59
+
60
+ self.pred_obj_scores = pred_obj_scores
61
+ if self.pred_obj_scores:
62
+ self.obj_score_token = nn.Embedding(1, transformer_dim)
63
+ self.use_multimask_token_for_obj_ptr = use_multimask_token_for_obj_ptr
64
+
65
+ self.output_upscaling = nn.Sequential(
66
+ nn.ConvTranspose2d(
67
+ transformer_dim, transformer_dim // 4, kernel_size=2, stride=2
68
+ ),
69
+ LayerNorm2d(transformer_dim // 4),
70
+ activation(),
71
+ nn.ConvTranspose2d(
72
+ transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2
73
+ ),
74
+ activation(),
75
+ )
76
+ self.use_high_res_features = use_high_res_features
77
+ if use_high_res_features:
78
+ self.conv_s0 = nn.Conv2d(
79
+ transformer_dim, transformer_dim // 8, kernel_size=1, stride=1
80
+ )
81
+ self.conv_s1 = nn.Conv2d(
82
+ transformer_dim, transformer_dim // 4, kernel_size=1, stride=1
83
+ )
84
+
85
+ self.output_hypernetworks_mlps = nn.ModuleList(
86
+ [
87
+ MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3)
88
+ for i in range(self.num_mask_tokens)
89
+ ]
90
+ )
91
+
92
+ self.iou_prediction_head = MLP(
93
+ transformer_dim,
94
+ iou_head_hidden_dim,
95
+ self.num_mask_tokens,
96
+ iou_head_depth,
97
+ sigmoid_output=iou_prediction_use_sigmoid,
98
+ )
99
+ if self.pred_obj_scores:
100
+ self.pred_obj_score_head = nn.Linear(transformer_dim, 1)
101
+ if pred_obj_scores_mlp:
102
+ self.pred_obj_score_head = MLP(transformer_dim, transformer_dim, 1, 3)
103
+
104
+ # When outputting a single mask, optionally we can dynamically fall back to the best
105
+ # multimask output token if the single mask output token gives low stability scores.
106
+ self.dynamic_multimask_via_stability = dynamic_multimask_via_stability
107
+ self.dynamic_multimask_stability_delta = dynamic_multimask_stability_delta
108
+ self.dynamic_multimask_stability_thresh = dynamic_multimask_stability_thresh
109
+
110
+ def forward(
111
+ self,
112
+ image_embeddings: torch.Tensor,
113
+ image_pe: torch.Tensor,
114
+ sparse_prompt_embeddings: torch.Tensor,
115
+ dense_prompt_embeddings: torch.Tensor,
116
+ multimask_output: bool,
117
+ repeat_image: bool,
118
+ high_res_features: Optional[List[torch.Tensor]] = None,
119
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
120
+ """
121
+ Predict masks given image and prompt embeddings.
122
+
123
+ Arguments:
124
+ image_embeddings (torch.Tensor): the embeddings from the image encoder
125
+ image_pe (torch.Tensor): positional encoding with the shape of image_embeddings
126
+ sparse_prompt_embeddings (torch.Tensor): the embeddings of the points and boxes
127
+ dense_prompt_embeddings (torch.Tensor): the embeddings of the mask inputs
128
+ multimask_output (bool): Whether to return multiple masks or a single
129
+ mask.
130
+
131
+ Returns:
132
+ torch.Tensor: batched predicted masks
133
+ torch.Tensor: batched predictions of mask quality
134
+ torch.Tensor: batched SAM token for mask output
135
+ """
136
+ masks, iou_pred, mask_tokens_out, object_score_logits = self.predict_masks(
137
+ image_embeddings=image_embeddings,
138
+ image_pe=image_pe,
139
+ sparse_prompt_embeddings=sparse_prompt_embeddings,
140
+ dense_prompt_embeddings=dense_prompt_embeddings,
141
+ repeat_image=repeat_image,
142
+ high_res_features=high_res_features,
143
+ )
144
+
145
+ # Select the correct mask or masks for output
146
+ if multimask_output:
147
+ masks = masks[:, 1:, :, :]
148
+ iou_pred = iou_pred[:, 1:]
149
+ elif self.dynamic_multimask_via_stability and not self.training:
150
+ masks, iou_pred = self._dynamic_multimask_via_stability(masks, iou_pred)
151
+ else:
152
+ masks = masks[:, 0:1, :, :]
153
+ iou_pred = iou_pred[:, 0:1]
154
+
155
+ if multimask_output and self.use_multimask_token_for_obj_ptr:
156
+ sam_tokens_out = mask_tokens_out[:, 1:] # [b, 3, c] shape
157
+ else:
158
+ # Take the mask output token. Here we *always* use the token for single mask output.
159
+ # At test time, even if we track after 1-click (and using multimask_output=True),
160
+ # we still take the single mask token here. The rationale is that we always track
161
+ # after multiple clicks during training, so the past tokens seen during training
162
+ # are always the single mask token (and we'll let it be the object-memory token).
163
+ sam_tokens_out = mask_tokens_out[:, 0:1] # [b, 1, c] shape
164
+
165
+ # Prepare output
166
+ return masks, iou_pred, sam_tokens_out, object_score_logits
167
+
168
+ def predict_masks(
169
+ self,
170
+ image_embeddings: torch.Tensor,
171
+ image_pe: torch.Tensor,
172
+ sparse_prompt_embeddings: torch.Tensor,
173
+ dense_prompt_embeddings: torch.Tensor,
174
+ repeat_image: bool,
175
+ high_res_features: Optional[List[torch.Tensor]] = None,
176
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
177
+ """Predicts masks. See 'forward' for more details."""
178
+ # Concatenate output tokens
179
+ s = 0
180
+ if self.pred_obj_scores:
181
+ output_tokens = torch.cat(
182
+ [
183
+ self.obj_score_token.weight,
184
+ self.iou_token.weight,
185
+ self.mask_tokens.weight,
186
+ ],
187
+ dim=0,
188
+ )
189
+ s = 1
190
+ else:
191
+ output_tokens = torch.cat(
192
+ [self.iou_token.weight, self.mask_tokens.weight], dim=0
193
+ )
194
+ output_tokens = output_tokens.unsqueeze(0).expand(
195
+ sparse_prompt_embeddings.size(0), -1, -1
196
+ )
197
+ tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1)
198
+
199
+ # Expand per-image data in batch direction to be per-mask
200
+ if repeat_image:
201
+ src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0)
202
+ else:
203
+ assert image_embeddings.shape[0] == tokens.shape[0]
204
+ src = image_embeddings
205
+ src = src + dense_prompt_embeddings
206
+ assert (
207
+ image_pe.size(0) == 1
208
+ ), "image_pe should have size 1 in batch dim (from `get_dense_pe()`)"
209
+ pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0)
210
+ b, c, h, w = src.shape
211
+
212
+ # Run the transformer
213
+ hs, src = self.transformer(src, pos_src, tokens)
214
+ iou_token_out = hs[:, s, :]
215
+ mask_tokens_out = hs[:, s + 1 : (s + 1 + self.num_mask_tokens), :]
216
+
217
+ # Upscale mask embeddings and predict masks using the mask tokens
218
+ src = src.transpose(1, 2).view(b, c, h, w)
219
+ if not self.use_high_res_features:
220
+ upscaled_embedding = self.output_upscaling(src)
221
+ else:
222
+ dc1, ln1, act1, dc2, act2 = self.output_upscaling
223
+ feat_s0, feat_s1 = high_res_features
224
+ upscaled_embedding = act1(ln1(dc1(src) + feat_s1))
225
+ upscaled_embedding = act2(dc2(upscaled_embedding) + feat_s0)
226
+
227
+ hyper_in_list: List[torch.Tensor] = []
228
+ for i in range(self.num_mask_tokens):
229
+ hyper_in_list.append(
230
+ self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :])
231
+ )
232
+ hyper_in = torch.stack(hyper_in_list, dim=1)
233
+ b, c, h, w = upscaled_embedding.shape
234
+ masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w)
235
+
236
+ # Generate mask quality predictions
237
+ iou_pred = self.iou_prediction_head(iou_token_out)
238
+ if self.pred_obj_scores:
239
+ assert s == 1
240
+ object_score_logits = self.pred_obj_score_head(hs[:, 0, :])
241
+ else:
242
+ # Obj scores logits - default to 10.0, i.e. assuming the object is present, sigmoid(10)=1
243
+ object_score_logits = 10.0 * iou_pred.new_ones(iou_pred.shape[0], 1)
244
+
245
+ return masks, iou_pred, mask_tokens_out, object_score_logits
246
+
247
+ def _get_stability_scores(self, mask_logits):
248
+ """
249
+ Compute stability scores of the mask logits based on the IoU between upper and
250
+ lower thresholds.
251
+ """
252
+ mask_logits = mask_logits.flatten(-2)
253
+ stability_delta = self.dynamic_multimask_stability_delta
254
+ area_i = torch.sum(mask_logits > stability_delta, dim=-1).float()
255
+ area_u = torch.sum(mask_logits > -stability_delta, dim=-1).float()
256
+ stability_scores = torch.where(area_u > 0, area_i / area_u, 1.0)
257
+ return stability_scores
258
+
259
+ def _dynamic_multimask_via_stability(self, all_mask_logits, all_iou_scores):
260
+ """
261
+ When outputting a single mask, if the stability score from the current single-mask
262
+ output (based on output token 0) falls below a threshold, we instead select from
263
+ multi-mask outputs (based on output token 1~3) the mask with the highest predicted
264
+ IoU score. This is intended to ensure a valid mask for both clicking and tracking.
265
+ """
266
+ # The best mask from multimask output tokens (1~3)
267
+ multimask_logits = all_mask_logits[:, 1:, :, :]
268
+ multimask_iou_scores = all_iou_scores[:, 1:]
269
+ best_scores_inds = torch.argmax(multimask_iou_scores, dim=-1)
270
+ batch_inds = torch.arange(
271
+ multimask_iou_scores.size(0), device=all_iou_scores.device
272
+ )
273
+ best_multimask_logits = multimask_logits[batch_inds, best_scores_inds]
274
+ best_multimask_logits = best_multimask_logits.unsqueeze(1)
275
+ best_multimask_iou_scores = multimask_iou_scores[batch_inds, best_scores_inds]
276
+ best_multimask_iou_scores = best_multimask_iou_scores.unsqueeze(1)
277
+
278
+ # The mask from singlemask output token 0 and its stability score
279
+ singlemask_logits = all_mask_logits[:, 0:1, :, :]
280
+ singlemask_iou_scores = all_iou_scores[:, 0:1]
281
+ stability_scores = self._get_stability_scores(singlemask_logits)
282
+ is_stable = stability_scores >= self.dynamic_multimask_stability_thresh
283
+
284
+ # Dynamically fall back to best multimask output upon low stability scores.
285
+ mask_logits_out = torch.where(
286
+ is_stable[..., None, None].expand_as(singlemask_logits),
287
+ singlemask_logits,
288
+ best_multimask_logits,
289
+ )
290
+ iou_scores_out = torch.where(
291
+ is_stable.expand_as(singlemask_iou_scores),
292
+ singlemask_iou_scores,
293
+ best_multimask_iou_scores,
294
+ )
295
+ return mask_logits_out, iou_scores_out