ultralytics 8.1.28__py3-none-any.whl → 8.3.62__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tests/__init__.py +22 -0
- tests/conftest.py +83 -0
- tests/test_cli.py +122 -0
- tests/test_cuda.py +155 -0
- tests/test_engine.py +131 -0
- tests/test_exports.py +216 -0
- tests/test_integrations.py +150 -0
- tests/test_python.py +615 -0
- tests/test_solutions.py +94 -0
- ultralytics/__init__.py +11 -8
- ultralytics/cfg/__init__.py +569 -131
- ultralytics/cfg/datasets/Argoverse.yaml +2 -1
- ultralytics/cfg/datasets/DOTAv1.5.yaml +3 -2
- ultralytics/cfg/datasets/DOTAv1.yaml +3 -2
- ultralytics/cfg/datasets/GlobalWheat2020.yaml +3 -2
- ultralytics/cfg/datasets/ImageNet.yaml +2 -1
- ultralytics/cfg/datasets/Objects365.yaml +5 -4
- ultralytics/cfg/datasets/SKU-110K.yaml +2 -1
- ultralytics/cfg/datasets/VOC.yaml +3 -2
- ultralytics/cfg/datasets/VisDrone.yaml +6 -5
- ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
- ultralytics/cfg/datasets/brain-tumor.yaml +23 -0
- ultralytics/cfg/datasets/carparts-seg.yaml +3 -2
- ultralytics/cfg/datasets/coco-pose.yaml +7 -6
- ultralytics/cfg/datasets/coco.yaml +3 -2
- ultralytics/cfg/datasets/coco128-seg.yaml +4 -3
- ultralytics/cfg/datasets/coco128.yaml +4 -3
- ultralytics/cfg/datasets/coco8-pose.yaml +3 -2
- ultralytics/cfg/datasets/coco8-seg.yaml +3 -2
- ultralytics/cfg/datasets/coco8.yaml +3 -2
- ultralytics/cfg/datasets/crack-seg.yaml +3 -2
- ultralytics/cfg/datasets/dog-pose.yaml +24 -0
- ultralytics/cfg/datasets/dota8.yaml +3 -2
- ultralytics/cfg/datasets/hand-keypoints.yaml +26 -0
- ultralytics/cfg/datasets/lvis.yaml +1236 -0
- ultralytics/cfg/datasets/medical-pills.yaml +22 -0
- ultralytics/cfg/datasets/open-images-v7.yaml +2 -1
- ultralytics/cfg/datasets/package-seg.yaml +5 -4
- ultralytics/cfg/datasets/signature.yaml +21 -0
- ultralytics/cfg/datasets/tiger-pose.yaml +3 -2
- ultralytics/cfg/datasets/xView.yaml +2 -1
- ultralytics/cfg/default.yaml +14 -11
- ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +24 -0
- ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
- ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
- ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
- ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
- ultralytics/cfg/models/11/yolo11.yaml +50 -0
- ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +5 -2
- ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +5 -2
- ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +5 -2
- ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +5 -2
- ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
- ultralytics/cfg/models/v3/yolov3-spp.yaml +5 -2
- ultralytics/cfg/models/v3/yolov3-tiny.yaml +5 -2
- ultralytics/cfg/models/v3/yolov3.yaml +5 -2
- ultralytics/cfg/models/v5/yolov5-p6.yaml +5 -2
- ultralytics/cfg/models/v5/yolov5.yaml +5 -2
- ultralytics/cfg/models/v6/yolov6.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-cls.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +6 -2
- ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +6 -2
- ultralytics/cfg/models/v8/yolov8-ghost.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-obb.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-p2.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-p6.yaml +10 -7
- ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-pose.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-seg.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-world.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8-worldv2.yaml +5 -2
- ultralytics/cfg/models/v8/yolov8.yaml +5 -2
- ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9c.yaml +30 -25
- ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
- ultralytics/cfg/models/v9/yolov9e.yaml +46 -42
- ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
- ultralytics/cfg/solutions/default.yaml +24 -0
- ultralytics/cfg/trackers/botsort.yaml +8 -5
- ultralytics/cfg/trackers/bytetrack.yaml +8 -5
- ultralytics/data/__init__.py +14 -3
- ultralytics/data/annotator.py +37 -15
- ultralytics/data/augment.py +1783 -289
- ultralytics/data/base.py +62 -27
- ultralytics/data/build.py +36 -8
- ultralytics/data/converter.py +196 -36
- ultralytics/data/dataset.py +233 -94
- ultralytics/data/loaders.py +199 -96
- ultralytics/data/split_dota.py +39 -29
- ultralytics/data/utils.py +110 -40
- ultralytics/engine/__init__.py +1 -1
- ultralytics/engine/exporter.py +569 -242
- ultralytics/engine/model.py +604 -252
- ultralytics/engine/predictor.py +22 -11
- ultralytics/engine/results.py +1228 -218
- ultralytics/engine/trainer.py +190 -129
- ultralytics/engine/tuner.py +18 -18
- ultralytics/engine/validator.py +18 -15
- ultralytics/hub/__init__.py +31 -13
- ultralytics/hub/auth.py +11 -7
- ultralytics/hub/google/__init__.py +159 -0
- ultralytics/hub/session.py +128 -94
- ultralytics/hub/utils.py +20 -21
- ultralytics/models/__init__.py +4 -2
- ultralytics/models/fastsam/__init__.py +2 -3
- ultralytics/models/fastsam/model.py +26 -4
- ultralytics/models/fastsam/predict.py +127 -63
- ultralytics/models/fastsam/utils.py +1 -44
- ultralytics/models/fastsam/val.py +1 -1
- ultralytics/models/nas/__init__.py +1 -1
- ultralytics/models/nas/model.py +21 -10
- ultralytics/models/nas/predict.py +3 -6
- ultralytics/models/nas/val.py +4 -4
- ultralytics/models/rtdetr/__init__.py +1 -1
- ultralytics/models/rtdetr/model.py +1 -1
- ultralytics/models/rtdetr/predict.py +6 -8
- ultralytics/models/rtdetr/train.py +6 -2
- ultralytics/models/rtdetr/val.py +3 -3
- ultralytics/models/sam/__init__.py +3 -3
- ultralytics/models/sam/amg.py +29 -23
- ultralytics/models/sam/build.py +211 -13
- ultralytics/models/sam/model.py +91 -30
- ultralytics/models/sam/modules/__init__.py +1 -1
- ultralytics/models/sam/modules/blocks.py +1129 -0
- ultralytics/models/sam/modules/decoders.py +381 -53
- ultralytics/models/sam/modules/encoders.py +515 -324
- ultralytics/models/sam/modules/memory_attention.py +237 -0
- ultralytics/models/sam/modules/sam.py +969 -21
- ultralytics/models/sam/modules/tiny_encoder.py +425 -154
- ultralytics/models/sam/modules/transformer.py +159 -60
- ultralytics/models/sam/modules/utils.py +293 -0
- ultralytics/models/sam/predict.py +1263 -132
- ultralytics/models/utils/__init__.py +1 -1
- ultralytics/models/utils/loss.py +36 -24
- ultralytics/models/utils/ops.py +3 -7
- ultralytics/models/yolo/__init__.py +3 -3
- ultralytics/models/yolo/classify/__init__.py +1 -1
- ultralytics/models/yolo/classify/predict.py +7 -8
- ultralytics/models/yolo/classify/train.py +17 -22
- ultralytics/models/yolo/classify/val.py +8 -4
- ultralytics/models/yolo/detect/__init__.py +1 -1
- ultralytics/models/yolo/detect/predict.py +3 -5
- ultralytics/models/yolo/detect/train.py +11 -4
- ultralytics/models/yolo/detect/val.py +90 -52
- ultralytics/models/yolo/model.py +14 -9
- ultralytics/models/yolo/obb/__init__.py +1 -1
- ultralytics/models/yolo/obb/predict.py +2 -2
- ultralytics/models/yolo/obb/train.py +5 -3
- ultralytics/models/yolo/obb/val.py +41 -23
- ultralytics/models/yolo/pose/__init__.py +1 -1
- ultralytics/models/yolo/pose/predict.py +3 -5
- ultralytics/models/yolo/pose/train.py +2 -2
- ultralytics/models/yolo/pose/val.py +51 -17
- ultralytics/models/yolo/segment/__init__.py +1 -1
- ultralytics/models/yolo/segment/predict.py +3 -5
- ultralytics/models/yolo/segment/train.py +2 -2
- ultralytics/models/yolo/segment/val.py +60 -19
- ultralytics/models/yolo/world/__init__.py +5 -0
- ultralytics/models/yolo/world/train.py +92 -0
- ultralytics/models/yolo/world/train_world.py +109 -0
- ultralytics/nn/__init__.py +1 -1
- ultralytics/nn/autobackend.py +228 -93
- ultralytics/nn/modules/__init__.py +39 -14
- ultralytics/nn/modules/activation.py +21 -0
- ultralytics/nn/modules/block.py +527 -67
- ultralytics/nn/modules/conv.py +24 -7
- ultralytics/nn/modules/head.py +177 -34
- ultralytics/nn/modules/transformer.py +6 -5
- ultralytics/nn/modules/utils.py +1 -2
- ultralytics/nn/tasks.py +225 -77
- ultralytics/solutions/__init__.py +30 -1
- ultralytics/solutions/ai_gym.py +96 -143
- ultralytics/solutions/analytics.py +247 -0
- ultralytics/solutions/distance_calculation.py +78 -135
- ultralytics/solutions/heatmap.py +93 -247
- ultralytics/solutions/object_counter.py +184 -259
- ultralytics/solutions/parking_management.py +246 -0
- ultralytics/solutions/queue_management.py +112 -0
- ultralytics/solutions/region_counter.py +116 -0
- ultralytics/solutions/security_alarm.py +144 -0
- ultralytics/solutions/solutions.py +178 -0
- ultralytics/solutions/speed_estimation.py +86 -174
- ultralytics/solutions/streamlit_inference.py +190 -0
- ultralytics/solutions/trackzone.py +68 -0
- ultralytics/trackers/__init__.py +1 -1
- ultralytics/trackers/basetrack.py +32 -13
- ultralytics/trackers/bot_sort.py +61 -28
- ultralytics/trackers/byte_tracker.py +83 -51
- ultralytics/trackers/track.py +21 -6
- ultralytics/trackers/utils/__init__.py +1 -1
- ultralytics/trackers/utils/gmc.py +62 -48
- ultralytics/trackers/utils/kalman_filter.py +166 -35
- ultralytics/trackers/utils/matching.py +40 -21
- ultralytics/utils/__init__.py +511 -239
- ultralytics/utils/autobatch.py +40 -22
- ultralytics/utils/benchmarks.py +266 -85
- ultralytics/utils/callbacks/__init__.py +1 -1
- ultralytics/utils/callbacks/base.py +1 -3
- ultralytics/utils/callbacks/clearml.py +7 -6
- ultralytics/utils/callbacks/comet.py +39 -17
- ultralytics/utils/callbacks/dvc.py +1 -1
- ultralytics/utils/callbacks/hub.py +16 -16
- ultralytics/utils/callbacks/mlflow.py +28 -24
- ultralytics/utils/callbacks/neptune.py +6 -2
- ultralytics/utils/callbacks/raytune.py +3 -4
- ultralytics/utils/callbacks/tensorboard.py +18 -18
- ultralytics/utils/callbacks/wb.py +27 -20
- ultralytics/utils/checks.py +160 -100
- ultralytics/utils/dist.py +2 -1
- ultralytics/utils/downloads.py +44 -37
- ultralytics/utils/errors.py +1 -1
- ultralytics/utils/files.py +72 -38
- ultralytics/utils/instance.py +41 -19
- ultralytics/utils/loss.py +84 -56
- ultralytics/utils/metrics.py +61 -56
- ultralytics/utils/ops.py +94 -89
- ultralytics/utils/patches.py +30 -14
- ultralytics/utils/plotting.py +600 -269
- ultralytics/utils/tal.py +67 -26
- ultralytics/utils/torch_utils.py +302 -102
- ultralytics/utils/triton.py +2 -1
- ultralytics/utils/tuner.py +21 -12
- ultralytics-8.3.62.dist-info/METADATA +370 -0
- ultralytics-8.3.62.dist-info/RECORD +241 -0
- {ultralytics-8.1.28.dist-info → ultralytics-8.3.62.dist-info}/WHEEL +1 -1
- ultralytics/data/explorer/__init__.py +0 -5
- ultralytics/data/explorer/explorer.py +0 -472
- ultralytics/data/explorer/gui/__init__.py +0 -1
- ultralytics/data/explorer/gui/dash.py +0 -268
- ultralytics/data/explorer/utils.py +0 -166
- ultralytics/models/fastsam/prompt.py +0 -357
- ultralytics-8.1.28.dist-info/METADATA +0 -373
- ultralytics-8.1.28.dist-info/RECORD +0 -197
- {ultralytics-8.1.28.dist-info → ultralytics-8.3.62.dist-info}/LICENSE +0 -0
- {ultralytics-8.1.28.dist-info → ultralytics-8.3.62.dist-info}/entry_points.txt +0 -0
- {ultralytics-8.1.28.dist-info → ultralytics-8.3.62.dist-info}/top_level.txt +0 -0
@@ -1,4 +1,4 @@
|
|
1
|
-
# Ultralytics
|
1
|
+
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
2
2
|
|
3
3
|
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
4
4
|
# All rights reserved.
|
@@ -9,30 +9,49 @@
|
|
9
9
|
from typing import List
|
10
10
|
|
11
11
|
import torch
|
12
|
+
import torch.nn.functional as F
|
12
13
|
from torch import nn
|
14
|
+
from torch.nn.init import trunc_normal_
|
13
15
|
|
14
|
-
from .
|
16
|
+
from ultralytics.nn.modules import MLP
|
17
|
+
|
18
|
+
from .blocks import SAM2TwoWayTransformer
|
19
|
+
from .decoders import MaskDecoder, SAM2MaskDecoder
|
15
20
|
from .encoders import ImageEncoderViT, PromptEncoder
|
21
|
+
from .utils import get_1d_sine_pe, select_closest_cond_frames
|
22
|
+
|
23
|
+
# a large negative value as a placeholder score for missing objects
|
24
|
+
NO_OBJ_SCORE = -1024.0
|
16
25
|
|
17
26
|
|
18
|
-
class
|
27
|
+
class SAMModel(nn.Module):
|
19
28
|
"""
|
20
|
-
|
21
|
-
|
22
|
-
|
29
|
+
Segment Anything Model (SAM) for object segmentation tasks.
|
30
|
+
|
31
|
+
This class combines image encoders, prompt encoders, and mask decoders to predict object masks from images
|
32
|
+
and input prompts.
|
23
33
|
|
24
34
|
Attributes:
|
25
35
|
mask_threshold (float): Threshold value for mask prediction.
|
26
|
-
|
27
|
-
|
28
|
-
|
29
|
-
|
30
|
-
|
31
|
-
|
36
|
+
image_encoder (ImageEncoderViT): Backbone for encoding images into embeddings.
|
37
|
+
prompt_encoder (PromptEncoder): Encoder for various types of input prompts.
|
38
|
+
mask_decoder (MaskDecoder): Predicts object masks from image and prompt embeddings.
|
39
|
+
|
40
|
+
Methods:
|
41
|
+
__init__: Initializes the SAMModel with encoders, decoder, and normalization parameters.
|
42
|
+
|
43
|
+
Examples:
|
44
|
+
>>> image_encoder = ImageEncoderViT(...)
|
45
|
+
>>> prompt_encoder = PromptEncoder(...)
|
46
|
+
>>> mask_decoder = MaskDecoder(...)
|
47
|
+
>>> sam_model = SAMModel(image_encoder, prompt_encoder, mask_decoder)
|
48
|
+
>>> # Further usage depends on SAMPredictor class
|
49
|
+
|
50
|
+
Notes:
|
51
|
+
All forward() operations are implemented in the SAMPredictor class.
|
32
52
|
"""
|
33
53
|
|
34
54
|
mask_threshold: float = 0.0
|
35
|
-
image_format: str = "RGB"
|
36
55
|
|
37
56
|
def __init__(
|
38
57
|
self,
|
@@ -43,19 +62,24 @@ class Sam(nn.Module):
|
|
43
62
|
pixel_std: List[float] = (58.395, 57.12, 57.375),
|
44
63
|
) -> None:
|
45
64
|
"""
|
46
|
-
Initialize the
|
47
|
-
|
48
|
-
Note:
|
49
|
-
All forward() operations moved to SAMPredictor.
|
65
|
+
Initialize the SAMModel class to predict object masks from an image and input prompts.
|
50
66
|
|
51
67
|
Args:
|
52
68
|
image_encoder (ImageEncoderViT): The backbone used to encode the image into image embeddings.
|
53
69
|
prompt_encoder (PromptEncoder): Encodes various types of input prompts.
|
54
70
|
mask_decoder (MaskDecoder): Predicts masks from the image embeddings and encoded prompts.
|
55
|
-
pixel_mean (List[float]
|
56
|
-
|
57
|
-
|
58
|
-
|
71
|
+
pixel_mean (List[float]): Mean values for normalizing pixels in the input image.
|
72
|
+
pixel_std (List[float]): Std values for normalizing pixels in the input image.
|
73
|
+
|
74
|
+
Examples:
|
75
|
+
>>> image_encoder = ImageEncoderViT(...)
|
76
|
+
>>> prompt_encoder = PromptEncoder(...)
|
77
|
+
>>> mask_decoder = MaskDecoder(...)
|
78
|
+
>>> sam_model = SAMModel(image_encoder, prompt_encoder, mask_decoder)
|
79
|
+
>>> # Further usage depends on SAMPredictor class
|
80
|
+
|
81
|
+
Notes:
|
82
|
+
All forward() operations moved to SAMPredictor.
|
59
83
|
"""
|
60
84
|
super().__init__()
|
61
85
|
self.image_encoder = image_encoder
|
@@ -63,3 +87,927 @@ class Sam(nn.Module):
|
|
63
87
|
self.mask_decoder = mask_decoder
|
64
88
|
self.register_buffer("pixel_mean", torch.Tensor(pixel_mean).view(-1, 1, 1), False)
|
65
89
|
self.register_buffer("pixel_std", torch.Tensor(pixel_std).view(-1, 1, 1), False)
|
90
|
+
|
91
|
+
def set_imgsz(self, imgsz):
|
92
|
+
"""
|
93
|
+
Set image size to make model compatible with different image sizes.
|
94
|
+
|
95
|
+
Args:
|
96
|
+
imgsz (Tuple[int, int]): The size of the input image.
|
97
|
+
"""
|
98
|
+
if hasattr(self.image_encoder, "set_imgsz"):
|
99
|
+
self.image_encoder.set_imgsz(imgsz)
|
100
|
+
self.prompt_encoder.input_image_size = imgsz
|
101
|
+
self.prompt_encoder.image_embedding_size = [x // 16 for x in imgsz] # 16 is fixed as patch size of ViT model
|
102
|
+
self.image_encoder.img_size = imgsz[0]
|
103
|
+
|
104
|
+
|
105
|
+
class SAM2Model(torch.nn.Module):
|
106
|
+
"""
|
107
|
+
SAM2Model class for Segment Anything Model 2 with memory-based video object segmentation capabilities.
|
108
|
+
|
109
|
+
This class extends the functionality of SAM to handle video sequences, incorporating memory mechanisms
|
110
|
+
for temporal consistency and efficient tracking of objects across frames.
|
111
|
+
|
112
|
+
Attributes:
|
113
|
+
mask_threshold (float): Threshold value for mask prediction.
|
114
|
+
image_encoder (ImageEncoderViT): Visual encoder for extracting image features.
|
115
|
+
memory_attention (nn.Module): Module for attending to memory features.
|
116
|
+
memory_encoder (nn.Module): Encoder for generating memory representations.
|
117
|
+
num_maskmem (int): Number of accessible memory frames.
|
118
|
+
image_size (int): Size of input images.
|
119
|
+
backbone_stride (int): Stride of the backbone network output.
|
120
|
+
sam_prompt_embed_dim (int): Dimension of SAM prompt embeddings.
|
121
|
+
sam_image_embedding_size (int): Size of SAM image embeddings.
|
122
|
+
sam_prompt_encoder (PromptEncoder): Encoder for processing input prompts.
|
123
|
+
sam_mask_decoder (SAM2MaskDecoder): Decoder for generating object masks.
|
124
|
+
obj_ptr_proj (nn.Module): Projection layer for object pointers.
|
125
|
+
obj_ptr_tpos_proj (nn.Module): Projection for temporal positional encoding in object pointers.
|
126
|
+
|
127
|
+
Methods:
|
128
|
+
forward_image: Processes image batch through encoder to extract multi-level features.
|
129
|
+
track_step: Performs a single tracking step, updating object masks and memory features.
|
130
|
+
|
131
|
+
Examples:
|
132
|
+
>>> model = SAM2Model(image_encoder, memory_attention, memory_encoder)
|
133
|
+
>>> image_batch = torch.rand(1, 3, 512, 512)
|
134
|
+
>>> features = model.forward_image(image_batch)
|
135
|
+
>>> track_results = model.track_step(0, True, features, None, None, None, {})
|
136
|
+
"""
|
137
|
+
|
138
|
+
mask_threshold: float = 0.0
|
139
|
+
|
140
|
+
def __init__(
|
141
|
+
self,
|
142
|
+
image_encoder,
|
143
|
+
memory_attention,
|
144
|
+
memory_encoder,
|
145
|
+
num_maskmem=7,
|
146
|
+
image_size=512,
|
147
|
+
backbone_stride=16,
|
148
|
+
sigmoid_scale_for_mem_enc=1.0,
|
149
|
+
sigmoid_bias_for_mem_enc=0.0,
|
150
|
+
binarize_mask_from_pts_for_mem_enc=False,
|
151
|
+
use_mask_input_as_output_without_sam=False,
|
152
|
+
max_cond_frames_in_attn=-1,
|
153
|
+
directly_add_no_mem_embed=False,
|
154
|
+
use_high_res_features_in_sam=False,
|
155
|
+
multimask_output_in_sam=False,
|
156
|
+
multimask_min_pt_num=1,
|
157
|
+
multimask_max_pt_num=1,
|
158
|
+
multimask_output_for_tracking=False,
|
159
|
+
use_multimask_token_for_obj_ptr: bool = False,
|
160
|
+
iou_prediction_use_sigmoid=False,
|
161
|
+
memory_temporal_stride_for_eval=1,
|
162
|
+
non_overlap_masks_for_mem_enc=False,
|
163
|
+
use_obj_ptrs_in_encoder=False,
|
164
|
+
max_obj_ptrs_in_encoder=16,
|
165
|
+
add_tpos_enc_to_obj_ptrs=True,
|
166
|
+
proj_tpos_enc_in_obj_ptrs=False,
|
167
|
+
use_signed_tpos_enc_to_obj_ptrs=False,
|
168
|
+
only_obj_ptrs_in_the_past_for_eval=False,
|
169
|
+
pred_obj_scores: bool = False,
|
170
|
+
pred_obj_scores_mlp: bool = False,
|
171
|
+
fixed_no_obj_ptr: bool = False,
|
172
|
+
soft_no_obj_ptr: bool = False,
|
173
|
+
use_mlp_for_obj_ptr_proj: bool = False,
|
174
|
+
no_obj_embed_spatial: bool = False,
|
175
|
+
sam_mask_decoder_extra_args=None,
|
176
|
+
compile_image_encoder: bool = False,
|
177
|
+
):
|
178
|
+
"""
|
179
|
+
Initializes the SAM2Model for video object segmentation with memory-based tracking.
|
180
|
+
|
181
|
+
Args:
|
182
|
+
image_encoder (nn.Module): Visual encoder for extracting image features.
|
183
|
+
memory_attention (nn.Module): Module for attending to memory features.
|
184
|
+
memory_encoder (nn.Module): Encoder for generating memory representations.
|
185
|
+
num_maskmem (int): Number of accessible memory frames. Default is 7 (1 input frame + 6 previous frames).
|
186
|
+
image_size (int): Size of input images.
|
187
|
+
backbone_stride (int): Stride of the image backbone output.
|
188
|
+
sigmoid_scale_for_mem_enc (float): Scale factor for mask sigmoid probability.
|
189
|
+
sigmoid_bias_for_mem_enc (float): Bias factor for mask sigmoid probability.
|
190
|
+
binarize_mask_from_pts_for_mem_enc (bool): Whether to binarize sigmoid mask logits on interacted frames
|
191
|
+
with clicks during evaluation.
|
192
|
+
use_mask_input_as_output_without_sam (bool): Whether to directly output the input mask without using SAM
|
193
|
+
prompt encoder and mask decoder on frames with mask input.
|
194
|
+
max_cond_frames_in_attn (int): Maximum number of conditioning frames to participate in memory attention.
|
195
|
+
-1 means no limit.
|
196
|
+
directly_add_no_mem_embed (bool): Whether to directly add no-memory embedding to image feature on the
|
197
|
+
first frame.
|
198
|
+
use_high_res_features_in_sam (bool): Whether to use high-resolution feature maps in the SAM mask decoder.
|
199
|
+
multimask_output_in_sam (bool): Whether to output multiple (3) masks for the first click on initial
|
200
|
+
conditioning frames.
|
201
|
+
multimask_min_pt_num (int): Minimum number of clicks to use multimask output in SAM.
|
202
|
+
multimask_max_pt_num (int): Maximum number of clicks to use multimask output in SAM.
|
203
|
+
multimask_output_for_tracking (bool): Whether to use multimask output for tracking.
|
204
|
+
use_multimask_token_for_obj_ptr (bool): Whether to use multimask tokens for object pointers.
|
205
|
+
iou_prediction_use_sigmoid (bool): Whether to use sigmoid to restrict IoU prediction to [0-1].
|
206
|
+
memory_temporal_stride_for_eval (int): Memory bank's temporal stride during evaluation.
|
207
|
+
non_overlap_masks_for_mem_enc (bool): Whether to apply non-overlapping constraints on object masks in
|
208
|
+
memory encoder during evaluation.
|
209
|
+
use_obj_ptrs_in_encoder (bool): Whether to cross-attend to object pointers from other frames in the encoder.
|
210
|
+
max_obj_ptrs_in_encoder (int): Maximum number of object pointers from other frames in encoder
|
211
|
+
cross-attention.
|
212
|
+
add_tpos_enc_to_obj_ptrs (bool): Whether to add temporal positional encoding to object pointers in
|
213
|
+
the encoder.
|
214
|
+
proj_tpos_enc_in_obj_ptrs (bool): Whether to add an extra linear projection layer for temporal positional
|
215
|
+
encoding in object pointers.
|
216
|
+
use_signed_tpos_enc_to_obj_ptrs (bool): whether to use signed distance (instead of unsigned absolute distance)
|
217
|
+
in the temporal positional encoding in the object pointers, only relevant when both `use_obj_ptrs_in_encoder=True`
|
218
|
+
and `add_tpos_enc_to_obj_ptrs=True`.
|
219
|
+
only_obj_ptrs_in_the_past_for_eval (bool): Whether to only attend to object pointers in the past
|
220
|
+
during evaluation.
|
221
|
+
pred_obj_scores (bool): Whether to predict if there is an object in the frame.
|
222
|
+
pred_obj_scores_mlp (bool): Whether to use an MLP to predict object scores.
|
223
|
+
fixed_no_obj_ptr (bool): Whether to have a fixed no-object pointer when there is no object present.
|
224
|
+
soft_no_obj_ptr (bool): Whether to mix in no-object pointer softly for easier recovery and error mitigation.
|
225
|
+
use_mlp_for_obj_ptr_proj (bool): Whether to use MLP for object pointer projection.
|
226
|
+
no_obj_embed_spatial (bool): Whether add no obj embedding to spatial frames.
|
227
|
+
sam_mask_decoder_extra_args (Dict | None): Extra arguments for constructing the SAM mask decoder.
|
228
|
+
compile_image_encoder (bool): Whether to compile the image encoder for faster inference.
|
229
|
+
|
230
|
+
Examples:
|
231
|
+
>>> image_encoder = ImageEncoderViT(...)
|
232
|
+
>>> memory_attention = SAM2TwoWayTransformer(...)
|
233
|
+
>>> memory_encoder = nn.Sequential(...)
|
234
|
+
>>> model = SAM2Model(image_encoder, memory_attention, memory_encoder)
|
235
|
+
>>> image_batch = torch.rand(1, 3, 512, 512)
|
236
|
+
>>> features = model.forward_image(image_batch)
|
237
|
+
>>> track_results = model.track_step(0, True, features, None, None, None, {})
|
238
|
+
"""
|
239
|
+
super().__init__()
|
240
|
+
|
241
|
+
# Part 1: the image backbone
|
242
|
+
self.image_encoder = image_encoder
|
243
|
+
# Use level 0, 1, 2 for high-res setting, or just level 2 for the default setting
|
244
|
+
self.use_high_res_features_in_sam = use_high_res_features_in_sam
|
245
|
+
self.num_feature_levels = 3 if use_high_res_features_in_sam else 1
|
246
|
+
self.use_obj_ptrs_in_encoder = use_obj_ptrs_in_encoder
|
247
|
+
self.max_obj_ptrs_in_encoder = max_obj_ptrs_in_encoder
|
248
|
+
if use_obj_ptrs_in_encoder:
|
249
|
+
# A conv layer to downsample the mask prompt to stride 4 (the same stride as
|
250
|
+
# low-res SAM mask logits) and to change its scales from 0~1 to SAM logit scale,
|
251
|
+
# so that it can be fed into the SAM mask decoder to generate a pointer.
|
252
|
+
self.mask_downsample = torch.nn.Conv2d(1, 1, kernel_size=4, stride=4)
|
253
|
+
self.add_tpos_enc_to_obj_ptrs = add_tpos_enc_to_obj_ptrs
|
254
|
+
if proj_tpos_enc_in_obj_ptrs:
|
255
|
+
assert add_tpos_enc_to_obj_ptrs # these options need to be used together
|
256
|
+
self.proj_tpos_enc_in_obj_ptrs = proj_tpos_enc_in_obj_ptrs
|
257
|
+
self.use_signed_tpos_enc_to_obj_ptrs = use_signed_tpos_enc_to_obj_ptrs
|
258
|
+
self.only_obj_ptrs_in_the_past_for_eval = only_obj_ptrs_in_the_past_for_eval
|
259
|
+
|
260
|
+
# Part 2: memory attention to condition current frame's visual features
|
261
|
+
# with memories (and obj ptrs) from past frames
|
262
|
+
self.memory_attention = memory_attention
|
263
|
+
self.hidden_dim = memory_attention.d_model
|
264
|
+
|
265
|
+
# Part 3: memory encoder for the previous frame's outputs
|
266
|
+
self.memory_encoder = memory_encoder
|
267
|
+
self.mem_dim = self.hidden_dim
|
268
|
+
if hasattr(self.memory_encoder, "out_proj") and hasattr(self.memory_encoder.out_proj, "weight"):
|
269
|
+
# if there is compression of memories along channel dim
|
270
|
+
self.mem_dim = self.memory_encoder.out_proj.weight.shape[0]
|
271
|
+
self.num_maskmem = num_maskmem # Number of memories accessible
|
272
|
+
# Temporal encoding of the memories
|
273
|
+
self.maskmem_tpos_enc = torch.nn.Parameter(torch.zeros(num_maskmem, 1, 1, self.mem_dim))
|
274
|
+
trunc_normal_(self.maskmem_tpos_enc, std=0.02)
|
275
|
+
# a single token to indicate no memory embedding from previous frames
|
276
|
+
self.no_mem_embed = torch.nn.Parameter(torch.zeros(1, 1, self.hidden_dim))
|
277
|
+
self.no_mem_pos_enc = torch.nn.Parameter(torch.zeros(1, 1, self.hidden_dim))
|
278
|
+
trunc_normal_(self.no_mem_embed, std=0.02)
|
279
|
+
trunc_normal_(self.no_mem_pos_enc, std=0.02)
|
280
|
+
self.directly_add_no_mem_embed = directly_add_no_mem_embed
|
281
|
+
# Apply sigmoid to the output raw mask logits (to turn them from
|
282
|
+
# range (-inf, +inf) to range (0, 1)) before feeding them into the memory encoder
|
283
|
+
self.sigmoid_scale_for_mem_enc = sigmoid_scale_for_mem_enc
|
284
|
+
self.sigmoid_bias_for_mem_enc = sigmoid_bias_for_mem_enc
|
285
|
+
self.binarize_mask_from_pts_for_mem_enc = binarize_mask_from_pts_for_mem_enc
|
286
|
+
self.non_overlap_masks_for_mem_enc = non_overlap_masks_for_mem_enc
|
287
|
+
self.memory_temporal_stride_for_eval = memory_temporal_stride_for_eval
|
288
|
+
# On frames with mask input, whether to directly output the input mask without
|
289
|
+
# using a SAM prompt encoder + mask decoder
|
290
|
+
self.use_mask_input_as_output_without_sam = use_mask_input_as_output_without_sam
|
291
|
+
self.multimask_output_in_sam = multimask_output_in_sam
|
292
|
+
self.multimask_min_pt_num = multimask_min_pt_num
|
293
|
+
self.multimask_max_pt_num = multimask_max_pt_num
|
294
|
+
self.multimask_output_for_tracking = multimask_output_for_tracking
|
295
|
+
self.use_multimask_token_for_obj_ptr = use_multimask_token_for_obj_ptr
|
296
|
+
self.iou_prediction_use_sigmoid = iou_prediction_use_sigmoid
|
297
|
+
|
298
|
+
# Part 4: SAM-style prompt encoder (for both mask and point inputs)
|
299
|
+
# and SAM-style mask decoder for the final mask output
|
300
|
+
self.image_size = image_size
|
301
|
+
self.backbone_stride = backbone_stride
|
302
|
+
self.sam_mask_decoder_extra_args = sam_mask_decoder_extra_args
|
303
|
+
self.pred_obj_scores = pred_obj_scores
|
304
|
+
self.pred_obj_scores_mlp = pred_obj_scores_mlp
|
305
|
+
self.fixed_no_obj_ptr = fixed_no_obj_ptr
|
306
|
+
self.soft_no_obj_ptr = soft_no_obj_ptr
|
307
|
+
if self.fixed_no_obj_ptr:
|
308
|
+
assert self.pred_obj_scores
|
309
|
+
assert self.use_obj_ptrs_in_encoder
|
310
|
+
if self.pred_obj_scores and self.use_obj_ptrs_in_encoder:
|
311
|
+
self.no_obj_ptr = torch.nn.Parameter(torch.zeros(1, self.hidden_dim))
|
312
|
+
trunc_normal_(self.no_obj_ptr, std=0.02)
|
313
|
+
self.use_mlp_for_obj_ptr_proj = use_mlp_for_obj_ptr_proj
|
314
|
+
self.no_obj_embed_spatial = None
|
315
|
+
if no_obj_embed_spatial:
|
316
|
+
self.no_obj_embed_spatial = torch.nn.Parameter(torch.zeros(1, self.mem_dim))
|
317
|
+
trunc_normal_(self.no_obj_embed_spatial, std=0.02)
|
318
|
+
|
319
|
+
self._build_sam_heads()
|
320
|
+
self.max_cond_frames_in_attn = max_cond_frames_in_attn
|
321
|
+
|
322
|
+
# Model compilation
|
323
|
+
if compile_image_encoder:
|
324
|
+
# Compile the forward function (not the full module) to allow loading checkpoints.
|
325
|
+
print("Image encoder compilation is enabled. First forward pass will be slow.")
|
326
|
+
self.image_encoder.forward = torch.compile(
|
327
|
+
self.image_encoder.forward,
|
328
|
+
mode="max-autotune",
|
329
|
+
fullgraph=True,
|
330
|
+
dynamic=False,
|
331
|
+
)
|
332
|
+
|
333
|
+
@property
|
334
|
+
def device(self):
|
335
|
+
"""Returns the device on which the model's parameters are stored."""
|
336
|
+
return next(self.parameters()).device
|
337
|
+
|
338
|
+
def forward(self, *args, **kwargs):
|
339
|
+
"""Processes image and prompt inputs to generate object masks and scores in video sequences."""
|
340
|
+
raise NotImplementedError(
|
341
|
+
"Please use the corresponding methods in SAM2VideoPredictor for inference."
|
342
|
+
"See notebooks/video_predictor_example.ipynb for an example."
|
343
|
+
)
|
344
|
+
|
345
|
+
def _build_sam_heads(self):
|
346
|
+
"""Builds SAM-style prompt encoder and mask decoder for image segmentation tasks."""
|
347
|
+
self.sam_prompt_embed_dim = self.hidden_dim
|
348
|
+
self.sam_image_embedding_size = self.image_size // self.backbone_stride
|
349
|
+
|
350
|
+
# Build PromptEncoder and MaskDecoder from SAM (hyperparameters like `mask_in_chans=16` are from SAM code)
|
351
|
+
self.sam_prompt_encoder = PromptEncoder(
|
352
|
+
embed_dim=self.sam_prompt_embed_dim,
|
353
|
+
image_embedding_size=(
|
354
|
+
self.sam_image_embedding_size,
|
355
|
+
self.sam_image_embedding_size,
|
356
|
+
),
|
357
|
+
input_image_size=(self.image_size, self.image_size),
|
358
|
+
mask_in_chans=16,
|
359
|
+
)
|
360
|
+
self.sam_mask_decoder = SAM2MaskDecoder(
|
361
|
+
num_multimask_outputs=3,
|
362
|
+
transformer=SAM2TwoWayTransformer(
|
363
|
+
depth=2,
|
364
|
+
embedding_dim=self.sam_prompt_embed_dim,
|
365
|
+
mlp_dim=2048,
|
366
|
+
num_heads=8,
|
367
|
+
),
|
368
|
+
transformer_dim=self.sam_prompt_embed_dim,
|
369
|
+
iou_head_depth=3,
|
370
|
+
iou_head_hidden_dim=256,
|
371
|
+
use_high_res_features=self.use_high_res_features_in_sam,
|
372
|
+
iou_prediction_use_sigmoid=self.iou_prediction_use_sigmoid,
|
373
|
+
pred_obj_scores=self.pred_obj_scores,
|
374
|
+
pred_obj_scores_mlp=self.pred_obj_scores_mlp,
|
375
|
+
use_multimask_token_for_obj_ptr=self.use_multimask_token_for_obj_ptr,
|
376
|
+
**(self.sam_mask_decoder_extra_args or {}),
|
377
|
+
)
|
378
|
+
if self.use_obj_ptrs_in_encoder:
|
379
|
+
# a linear projection on SAM output tokens to turn them into object pointers
|
380
|
+
self.obj_ptr_proj = torch.nn.Linear(self.hidden_dim, self.hidden_dim)
|
381
|
+
if self.use_mlp_for_obj_ptr_proj:
|
382
|
+
self.obj_ptr_proj = MLP(self.hidden_dim, self.hidden_dim, self.hidden_dim, 3)
|
383
|
+
else:
|
384
|
+
self.obj_ptr_proj = torch.nn.Identity()
|
385
|
+
if self.proj_tpos_enc_in_obj_ptrs:
|
386
|
+
# a linear projection on temporal positional encoding in object pointers to
|
387
|
+
# avoid potential interference with spatial positional encoding
|
388
|
+
self.obj_ptr_tpos_proj = torch.nn.Linear(self.hidden_dim, self.mem_dim)
|
389
|
+
else:
|
390
|
+
self.obj_ptr_tpos_proj = torch.nn.Identity()
|
391
|
+
|
392
|
+
def _forward_sam_heads(
|
393
|
+
self,
|
394
|
+
backbone_features,
|
395
|
+
point_inputs=None,
|
396
|
+
mask_inputs=None,
|
397
|
+
high_res_features=None,
|
398
|
+
multimask_output=False,
|
399
|
+
):
|
400
|
+
"""
|
401
|
+
Forward pass through SAM prompt encoders and mask heads.
|
402
|
+
|
403
|
+
This method processes image features and optional point/mask inputs to generate object masks and scores.
|
404
|
+
|
405
|
+
Args:
|
406
|
+
backbone_features (torch.Tensor): Image features with shape (B, C, H, W).
|
407
|
+
point_inputs (Dict[str, torch.Tensor] | None): Dictionary containing point prompts.
|
408
|
+
'point_coords': Tensor of shape (B, P, 2) with float32 dtype, containing absolute
|
409
|
+
pixel-unit coordinates in (x, y) format for P input points.
|
410
|
+
'point_labels': Tensor of shape (B, P) with int32 dtype, where 1 means positive clicks,
|
411
|
+
0 means negative clicks, and -1 means padding.
|
412
|
+
mask_inputs (torch.Tensor | None): Mask of shape (B, 1, H*16, W*16), float or bool, with the
|
413
|
+
same spatial size as the image.
|
414
|
+
high_res_features (List[torch.Tensor] | None): List of two feature maps with shapes
|
415
|
+
(B, C, 4*H, 4*W) and (B, C, 2*H, 2*W) respectively, used as high-resolution feature maps
|
416
|
+
for SAM decoder.
|
417
|
+
multimask_output (bool): If True, output 3 candidate masks and their IoU estimates; if False,
|
418
|
+
output only 1 mask and its IoU estimate.
|
419
|
+
|
420
|
+
Returns:
|
421
|
+
(Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]):
|
422
|
+
low_res_multimasks: Tensor of shape (B, M, H*4, W*4) with SAM output mask logits.
|
423
|
+
high_res_multimasks: Tensor of shape (B, M, H*16, W*16) with upsampled mask logits.
|
424
|
+
ious: Tensor of shape (B, M) with estimated IoU for each output mask.
|
425
|
+
low_res_masks: Tensor of shape (B, 1, H*4, W*4) with the best low-resolution mask.
|
426
|
+
high_res_masks: Tensor of shape (B, 1, H*16, W*16) with the best high-resolution mask.
|
427
|
+
obj_ptr: Tensor of shape (B, C) with object pointer vector for the output mask.
|
428
|
+
object_score_logits: Tensor of shape (B) with object score logits.
|
429
|
+
|
430
|
+
Where M is 3 if multimask_output=True, and 1 if multimask_output=False.
|
431
|
+
|
432
|
+
Examples:
|
433
|
+
>>> backbone_features = torch.rand(1, 256, 32, 32)
|
434
|
+
>>> point_inputs = {"point_coords": torch.rand(1, 2, 2), "point_labels": torch.tensor([[1, 0]])}
|
435
|
+
>>> mask_inputs = torch.rand(1, 1, 512, 512)
|
436
|
+
>>> results = model._forward_sam_heads(backbone_features, point_inputs, mask_inputs)
|
437
|
+
>>> (
|
438
|
+
... low_res_multimasks,
|
439
|
+
... high_res_multimasks,
|
440
|
+
... ious,
|
441
|
+
... low_res_masks,
|
442
|
+
... high_res_masks,
|
443
|
+
... obj_ptr,
|
444
|
+
... object_score_logits,
|
445
|
+
... ) = results
|
446
|
+
"""
|
447
|
+
B = backbone_features.size(0)
|
448
|
+
device = backbone_features.device
|
449
|
+
assert backbone_features.size(1) == self.sam_prompt_embed_dim
|
450
|
+
assert backbone_features.size(2) == self.sam_image_embedding_size
|
451
|
+
assert backbone_features.size(3) == self.sam_image_embedding_size
|
452
|
+
|
453
|
+
# a) Handle point prompts
|
454
|
+
if point_inputs is not None:
|
455
|
+
sam_point_coords = point_inputs["point_coords"]
|
456
|
+
sam_point_labels = point_inputs["point_labels"]
|
457
|
+
assert sam_point_coords.size(0) == B and sam_point_labels.size(0) == B
|
458
|
+
else:
|
459
|
+
# If no points are provide, pad with an empty point (with label -1)
|
460
|
+
sam_point_coords = torch.zeros(B, 1, 2, device=device)
|
461
|
+
sam_point_labels = -torch.ones(B, 1, dtype=torch.int32, device=device)
|
462
|
+
|
463
|
+
# b) Handle mask prompts
|
464
|
+
if mask_inputs is not None:
|
465
|
+
# If mask_inputs is provided, downsize it into low-res mask input if needed
|
466
|
+
# and feed it as a dense mask prompt into the SAM mask encoder
|
467
|
+
assert len(mask_inputs.shape) == 4 and mask_inputs.shape[:2] == (B, 1)
|
468
|
+
if mask_inputs.shape[-2:] != self.sam_prompt_encoder.mask_input_size:
|
469
|
+
sam_mask_prompt = F.interpolate(
|
470
|
+
mask_inputs.float(),
|
471
|
+
size=self.sam_prompt_encoder.mask_input_size,
|
472
|
+
align_corners=False,
|
473
|
+
mode="bilinear",
|
474
|
+
antialias=True, # use antialias for downsampling
|
475
|
+
)
|
476
|
+
else:
|
477
|
+
sam_mask_prompt = mask_inputs
|
478
|
+
else:
|
479
|
+
# Otherwise, simply feed None (and SAM's prompt encoder will add
|
480
|
+
# a learned `no_mask_embed` to indicate no mask input in this case).
|
481
|
+
sam_mask_prompt = None
|
482
|
+
|
483
|
+
sparse_embeddings, dense_embeddings = self.sam_prompt_encoder(
|
484
|
+
points=(sam_point_coords, sam_point_labels),
|
485
|
+
boxes=None,
|
486
|
+
masks=sam_mask_prompt,
|
487
|
+
)
|
488
|
+
low_res_multimasks, ious, sam_output_tokens, object_score_logits = self.sam_mask_decoder(
|
489
|
+
image_embeddings=backbone_features,
|
490
|
+
image_pe=self.sam_prompt_encoder.get_dense_pe(),
|
491
|
+
sparse_prompt_embeddings=sparse_embeddings,
|
492
|
+
dense_prompt_embeddings=dense_embeddings,
|
493
|
+
multimask_output=multimask_output,
|
494
|
+
repeat_image=False, # the image is already batched
|
495
|
+
high_res_features=high_res_features,
|
496
|
+
)
|
497
|
+
if self.pred_obj_scores:
|
498
|
+
is_obj_appearing = object_score_logits > 0
|
499
|
+
|
500
|
+
# Spatial memory mask is a *hard* choice between obj and no obj, consistent with actual mask prediction
|
501
|
+
low_res_multimasks = torch.where(is_obj_appearing[:, None, None], low_res_multimasks, NO_OBJ_SCORE)
|
502
|
+
|
503
|
+
# convert masks from possibly bfloat16 (or float16) to float32
|
504
|
+
# (older PyTorch versions before 2.1 don't support `interpolate` on bf16)
|
505
|
+
low_res_multimasks = low_res_multimasks.float()
|
506
|
+
high_res_multimasks = F.interpolate(
|
507
|
+
low_res_multimasks,
|
508
|
+
size=(self.image_size, self.image_size),
|
509
|
+
mode="bilinear",
|
510
|
+
align_corners=False,
|
511
|
+
)
|
512
|
+
|
513
|
+
sam_output_token = sam_output_tokens[:, 0]
|
514
|
+
if multimask_output:
|
515
|
+
# take the best mask prediction (with the highest IoU estimation)
|
516
|
+
best_iou_inds = torch.argmax(ious, dim=-1)
|
517
|
+
batch_inds = torch.arange(B, device=device)
|
518
|
+
low_res_masks = low_res_multimasks[batch_inds, best_iou_inds].unsqueeze(1)
|
519
|
+
high_res_masks = high_res_multimasks[batch_inds, best_iou_inds].unsqueeze(1)
|
520
|
+
if sam_output_tokens.size(1) > 1:
|
521
|
+
sam_output_token = sam_output_tokens[batch_inds, best_iou_inds]
|
522
|
+
else:
|
523
|
+
low_res_masks, high_res_masks = low_res_multimasks, high_res_multimasks
|
524
|
+
|
525
|
+
# Extract object pointer from the SAM output token (with occlusion handling)
|
526
|
+
obj_ptr = self.obj_ptr_proj(sam_output_token)
|
527
|
+
if self.pred_obj_scores:
|
528
|
+
# Allow *soft* no obj ptr, unlike for masks
|
529
|
+
if self.soft_no_obj_ptr:
|
530
|
+
lambda_is_obj_appearing = object_score_logits.sigmoid()
|
531
|
+
else:
|
532
|
+
lambda_is_obj_appearing = is_obj_appearing.float()
|
533
|
+
|
534
|
+
if self.fixed_no_obj_ptr:
|
535
|
+
obj_ptr = lambda_is_obj_appearing * obj_ptr
|
536
|
+
obj_ptr = obj_ptr + (1 - lambda_is_obj_appearing) * self.no_obj_ptr
|
537
|
+
|
538
|
+
return (
|
539
|
+
low_res_multimasks,
|
540
|
+
high_res_multimasks,
|
541
|
+
ious,
|
542
|
+
low_res_masks,
|
543
|
+
high_res_masks,
|
544
|
+
obj_ptr,
|
545
|
+
object_score_logits,
|
546
|
+
)
|
547
|
+
|
548
|
+
def _use_mask_as_output(self, backbone_features, high_res_features, mask_inputs):
|
549
|
+
"""Processes mask inputs directly as output, bypassing SAM encoder/decoder."""
|
550
|
+
# Use -10/+10 as logits for neg/pos pixels (very close to 0/1 in prob after sigmoid).
|
551
|
+
out_scale, out_bias = 20.0, -10.0 # sigmoid(-10.0)=4.5398e-05
|
552
|
+
mask_inputs_float = mask_inputs.float()
|
553
|
+
high_res_masks = mask_inputs_float * out_scale + out_bias
|
554
|
+
low_res_masks = F.interpolate(
|
555
|
+
high_res_masks,
|
556
|
+
size=(high_res_masks.size(-2) // 4, high_res_masks.size(-1) // 4),
|
557
|
+
align_corners=False,
|
558
|
+
mode="bilinear",
|
559
|
+
antialias=True, # use antialias for downsampling
|
560
|
+
)
|
561
|
+
# a dummy IoU prediction of all 1's under mask input
|
562
|
+
ious = mask_inputs.new_ones(mask_inputs.size(0), 1).float()
|
563
|
+
if not self.use_obj_ptrs_in_encoder:
|
564
|
+
# all zeros as a dummy object pointer (of shape [B, C])
|
565
|
+
obj_ptr = torch.zeros(mask_inputs.size(0), self.hidden_dim, device=mask_inputs.device)
|
566
|
+
else:
|
567
|
+
# produce an object pointer using the SAM decoder from the mask input
|
568
|
+
_, _, _, _, _, obj_ptr, _ = self._forward_sam_heads(
|
569
|
+
backbone_features=backbone_features,
|
570
|
+
mask_inputs=self.mask_downsample(mask_inputs_float),
|
571
|
+
high_res_features=high_res_features,
|
572
|
+
)
|
573
|
+
# In this method, we are treating mask_input as output, e.g. using it directly to create spatial mem;
|
574
|
+
# Below, we follow the same design axiom to use mask_input to decide if obj appears or not instead of relying
|
575
|
+
# on the object_scores from the SAM decoder.
|
576
|
+
is_obj_appearing = torch.any(mask_inputs.flatten(1).float() > 0.0, dim=1)
|
577
|
+
is_obj_appearing = is_obj_appearing[..., None]
|
578
|
+
lambda_is_obj_appearing = is_obj_appearing.float()
|
579
|
+
object_score_logits = out_scale * lambda_is_obj_appearing + out_bias
|
580
|
+
if self.pred_obj_scores:
|
581
|
+
if self.fixed_no_obj_ptr:
|
582
|
+
obj_ptr = lambda_is_obj_appearing * obj_ptr
|
583
|
+
obj_ptr = obj_ptr + (1 - lambda_is_obj_appearing) * self.no_obj_ptr
|
584
|
+
|
585
|
+
return (
|
586
|
+
low_res_masks,
|
587
|
+
high_res_masks,
|
588
|
+
ious,
|
589
|
+
low_res_masks,
|
590
|
+
high_res_masks,
|
591
|
+
obj_ptr,
|
592
|
+
object_score_logits,
|
593
|
+
)
|
594
|
+
|
595
|
+
def forward_image(self, img_batch: torch.Tensor):
|
596
|
+
"""Processes image batch through encoder to extract multi-level features for SAM model."""
|
597
|
+
backbone_out = self.image_encoder(img_batch)
|
598
|
+
if self.use_high_res_features_in_sam:
|
599
|
+
# precompute projected level 0 and level 1 features in SAM decoder
|
600
|
+
# to avoid running it again on every SAM click
|
601
|
+
backbone_out["backbone_fpn"][0] = self.sam_mask_decoder.conv_s0(backbone_out["backbone_fpn"][0])
|
602
|
+
backbone_out["backbone_fpn"][1] = self.sam_mask_decoder.conv_s1(backbone_out["backbone_fpn"][1])
|
603
|
+
return backbone_out
|
604
|
+
|
605
|
+
def _prepare_backbone_features(self, backbone_out):
|
606
|
+
"""Prepares and flattens visual features from the image backbone output for further processing."""
|
607
|
+
assert len(backbone_out["backbone_fpn"]) == len(backbone_out["vision_pos_enc"])
|
608
|
+
assert len(backbone_out["backbone_fpn"]) >= self.num_feature_levels
|
609
|
+
|
610
|
+
feature_maps = backbone_out["backbone_fpn"][-self.num_feature_levels :]
|
611
|
+
vision_pos_embeds = backbone_out["vision_pos_enc"][-self.num_feature_levels :]
|
612
|
+
|
613
|
+
feat_sizes = [(x.shape[-2], x.shape[-1]) for x in vision_pos_embeds]
|
614
|
+
# flatten NxCxHxW to HWxNxC
|
615
|
+
vision_feats = [x.flatten(2).permute(2, 0, 1) for x in feature_maps]
|
616
|
+
vision_pos_embeds = [x.flatten(2).permute(2, 0, 1) for x in vision_pos_embeds]
|
617
|
+
|
618
|
+
return backbone_out, vision_feats, vision_pos_embeds, feat_sizes
|
619
|
+
|
620
|
+
def _prepare_memory_conditioned_features(
|
621
|
+
self,
|
622
|
+
frame_idx,
|
623
|
+
is_init_cond_frame,
|
624
|
+
current_vision_feats,
|
625
|
+
current_vision_pos_embeds,
|
626
|
+
feat_sizes,
|
627
|
+
output_dict,
|
628
|
+
num_frames,
|
629
|
+
track_in_reverse=False, # tracking in reverse time order (for demo usage)
|
630
|
+
):
|
631
|
+
"""Prepares memory-conditioned features by fusing current frame's visual features with previous memories."""
|
632
|
+
B = current_vision_feats[-1].size(1) # batch size on this frame
|
633
|
+
C = self.hidden_dim
|
634
|
+
H, W = feat_sizes[-1] # top-level (lowest-resolution) feature size
|
635
|
+
device = current_vision_feats[-1].device
|
636
|
+
# The case of `self.num_maskmem == 0` below is primarily used for reproducing SAM on images.
|
637
|
+
# In this case, we skip the fusion with any memory.
|
638
|
+
if self.num_maskmem == 0: # Disable memory and skip fusion
|
639
|
+
return current_vision_feats[-1].permute(1, 2, 0).view(B, C, H, W)
|
640
|
+
num_obj_ptr_tokens = 0
|
641
|
+
tpos_sign_mul = -1 if track_in_reverse else 1
|
642
|
+
# Step 1: condition the visual features of the current frame on previous memories
|
643
|
+
if not is_init_cond_frame:
|
644
|
+
# Retrieve the memories encoded with the maskmem backbone
|
645
|
+
to_cat_memory, to_cat_memory_pos_embed = [], []
|
646
|
+
# Add conditioning frame's output first (all cond frames have t_pos=0 for
|
647
|
+
# when getting temporal positional embedding below)
|
648
|
+
assert len(output_dict["cond_frame_outputs"]) > 0
|
649
|
+
# Select a maximum number of temporally closest cond frames for cross attention
|
650
|
+
cond_outputs = output_dict["cond_frame_outputs"]
|
651
|
+
selected_cond_outputs, unselected_cond_outputs = select_closest_cond_frames(
|
652
|
+
frame_idx, cond_outputs, self.max_cond_frames_in_attn
|
653
|
+
)
|
654
|
+
t_pos_and_prevs = [(0, out) for out in selected_cond_outputs.values()]
|
655
|
+
# Add last (self.num_maskmem - 1) frames before current frame for non-conditioning memory
|
656
|
+
# the earliest one has t_pos=1 and the latest one has t_pos=self.num_maskmem-1
|
657
|
+
# We also allow taking the memory frame non-consecutively (with r>1), in which case
|
658
|
+
# we take (self.num_maskmem - 2) frames among every r-th frames plus the last frame.
|
659
|
+
r = 1 if self.training else self.memory_temporal_stride_for_eval
|
660
|
+
for t_pos in range(1, self.num_maskmem):
|
661
|
+
t_rel = self.num_maskmem - t_pos # how many frames before current frame
|
662
|
+
if t_rel == 1:
|
663
|
+
# for t_rel == 1, we take the last frame (regardless of r)
|
664
|
+
prev_frame_idx = frame_idx + t_rel if track_in_reverse else frame_idx - t_rel
|
665
|
+
elif not track_in_reverse:
|
666
|
+
# first find the nearest frame among every r-th frames before this frame
|
667
|
+
# for r=1, this would be (frame_idx - 2)
|
668
|
+
prev_frame_idx = ((frame_idx - 2) // r) * r
|
669
|
+
# then seek further among every r-th frames
|
670
|
+
prev_frame_idx = prev_frame_idx - (t_rel - 2) * r
|
671
|
+
else:
|
672
|
+
# first find the nearest frame among every r-th frames after this frame
|
673
|
+
# for r=1, this would be (frame_idx + 2)
|
674
|
+
prev_frame_idx = -(-(frame_idx + 2) // r) * r
|
675
|
+
# then seek further among every r-th frames
|
676
|
+
prev_frame_idx = prev_frame_idx + (t_rel - 2) * r
|
677
|
+
out = output_dict["non_cond_frame_outputs"].get(prev_frame_idx, None)
|
678
|
+
if out is None:
|
679
|
+
# If an unselected conditioning frame is among the last (self.num_maskmem - 1)
|
680
|
+
# frames, we still attend to it as if it's a non-conditioning frame.
|
681
|
+
out = unselected_cond_outputs.get(prev_frame_idx, None)
|
682
|
+
t_pos_and_prevs.append((t_pos, out))
|
683
|
+
|
684
|
+
for t_pos, prev in t_pos_and_prevs:
|
685
|
+
if prev is None:
|
686
|
+
continue # skip padding frames
|
687
|
+
# "maskmem_features" might have been offloaded to CPU in demo use cases,
|
688
|
+
# so we load it back to inference device (it's a no-op if it's already on device).
|
689
|
+
feats = prev["maskmem_features"].to(device=device, non_blocking=True)
|
690
|
+
to_cat_memory.append(feats.flatten(2).permute(2, 0, 1))
|
691
|
+
# Spatial positional encoding (it might have been offloaded to CPU in eval)
|
692
|
+
maskmem_enc = prev["maskmem_pos_enc"][-1].to(device=device)
|
693
|
+
maskmem_enc = maskmem_enc.flatten(2).permute(2, 0, 1)
|
694
|
+
# Temporal positional encoding
|
695
|
+
maskmem_enc = maskmem_enc + self.maskmem_tpos_enc[self.num_maskmem - t_pos - 1]
|
696
|
+
to_cat_memory_pos_embed.append(maskmem_enc)
|
697
|
+
|
698
|
+
# Construct the list of past object pointers
|
699
|
+
if self.use_obj_ptrs_in_encoder:
|
700
|
+
max_obj_ptrs_in_encoder = min(num_frames, self.max_obj_ptrs_in_encoder)
|
701
|
+
# First add those object pointers from selected conditioning frames
|
702
|
+
# (optionally, only include object pointers in the past during evaluation)
|
703
|
+
if not self.training and self.only_obj_ptrs_in_the_past_for_eval:
|
704
|
+
ptr_cond_outputs = {
|
705
|
+
t: out
|
706
|
+
for t, out in selected_cond_outputs.items()
|
707
|
+
if (t >= frame_idx if track_in_reverse else t <= frame_idx)
|
708
|
+
}
|
709
|
+
else:
|
710
|
+
ptr_cond_outputs = selected_cond_outputs
|
711
|
+
pos_and_ptrs = [
|
712
|
+
# Temporal pos encoding contains how far away each pointer is from current frame
|
713
|
+
(
|
714
|
+
(
|
715
|
+
(frame_idx - t) * tpos_sign_mul
|
716
|
+
if self.use_signed_tpos_enc_to_obj_ptrs
|
717
|
+
else abs(frame_idx - t)
|
718
|
+
),
|
719
|
+
out["obj_ptr"],
|
720
|
+
)
|
721
|
+
for t, out in ptr_cond_outputs.items()
|
722
|
+
]
|
723
|
+
# Add up to (max_obj_ptrs_in_encoder - 1) non-conditioning frames before current frame
|
724
|
+
for t_diff in range(1, max_obj_ptrs_in_encoder):
|
725
|
+
t = frame_idx + t_diff if track_in_reverse else frame_idx - t_diff
|
726
|
+
if t < 0 or (num_frames is not None and t >= num_frames):
|
727
|
+
break
|
728
|
+
out = output_dict["non_cond_frame_outputs"].get(t, unselected_cond_outputs.get(t, None))
|
729
|
+
if out is not None:
|
730
|
+
pos_and_ptrs.append((t_diff, out["obj_ptr"]))
|
731
|
+
# If we have at least one object pointer, add them to the across attention
|
732
|
+
if pos_and_ptrs:
|
733
|
+
pos_list, ptrs_list = zip(*pos_and_ptrs)
|
734
|
+
# stack object pointers along dim=0 into [ptr_seq_len, B, C] shape
|
735
|
+
obj_ptrs = torch.stack(ptrs_list, dim=0)
|
736
|
+
# a temporal positional embedding based on how far each object pointer is from
|
737
|
+
# the current frame (sine embedding normalized by the max pointer num).
|
738
|
+
if self.add_tpos_enc_to_obj_ptrs:
|
739
|
+
t_diff_max = max_obj_ptrs_in_encoder - 1
|
740
|
+
tpos_dim = C if self.proj_tpos_enc_in_obj_ptrs else self.mem_dim
|
741
|
+
obj_pos = torch.tensor(pos_list, device=device)
|
742
|
+
obj_pos = get_1d_sine_pe(obj_pos / t_diff_max, dim=tpos_dim)
|
743
|
+
obj_pos = self.obj_ptr_tpos_proj(obj_pos)
|
744
|
+
obj_pos = obj_pos.unsqueeze(1).expand(-1, B, self.mem_dim)
|
745
|
+
else:
|
746
|
+
obj_pos = obj_ptrs.new_zeros(len(pos_list), B, self.mem_dim)
|
747
|
+
if self.mem_dim < C:
|
748
|
+
# split a pointer into (C // self.mem_dim) tokens for self.mem_dim < C
|
749
|
+
obj_ptrs = obj_ptrs.reshape(-1, B, C // self.mem_dim, self.mem_dim)
|
750
|
+
obj_ptrs = obj_ptrs.permute(0, 2, 1, 3).flatten(0, 1)
|
751
|
+
obj_pos = obj_pos.repeat_interleave(C // self.mem_dim, dim=0)
|
752
|
+
to_cat_memory.append(obj_ptrs)
|
753
|
+
to_cat_memory_pos_embed.append(obj_pos)
|
754
|
+
num_obj_ptr_tokens = obj_ptrs.shape[0]
|
755
|
+
else:
|
756
|
+
num_obj_ptr_tokens = 0
|
757
|
+
else:
|
758
|
+
# for initial conditioning frames, encode them without using any previous memory
|
759
|
+
if self.directly_add_no_mem_embed:
|
760
|
+
# directly add no-mem embedding (instead of using the transformer encoder)
|
761
|
+
pix_feat_with_mem = current_vision_feats[-1] + self.no_mem_embed
|
762
|
+
pix_feat_with_mem = pix_feat_with_mem.permute(1, 2, 0).view(B, C, H, W)
|
763
|
+
return pix_feat_with_mem
|
764
|
+
|
765
|
+
# Use a dummy token on the first frame (to avoid empty memory input to transformer encoder)
|
766
|
+
to_cat_memory = [self.no_mem_embed.expand(1, B, self.mem_dim)]
|
767
|
+
to_cat_memory_pos_embed = [self.no_mem_pos_enc.expand(1, B, self.mem_dim)]
|
768
|
+
|
769
|
+
# Step 2: Concatenate the memories and forward through the transformer encoder
|
770
|
+
memory = torch.cat(to_cat_memory, dim=0)
|
771
|
+
memory_pos_embed = torch.cat(to_cat_memory_pos_embed, dim=0)
|
772
|
+
|
773
|
+
pix_feat_with_mem = self.memory_attention(
|
774
|
+
curr=current_vision_feats,
|
775
|
+
curr_pos=current_vision_pos_embeds,
|
776
|
+
memory=memory,
|
777
|
+
memory_pos=memory_pos_embed,
|
778
|
+
num_obj_ptr_tokens=num_obj_ptr_tokens,
|
779
|
+
)
|
780
|
+
# reshape the output (HW)BC => BCHW
|
781
|
+
pix_feat_with_mem = pix_feat_with_mem.permute(1, 2, 0).view(B, C, H, W)
|
782
|
+
return pix_feat_with_mem
|
783
|
+
|
784
|
+
def _encode_new_memory(
|
785
|
+
self,
|
786
|
+
current_vision_feats,
|
787
|
+
feat_sizes,
|
788
|
+
pred_masks_high_res,
|
789
|
+
object_score_logits,
|
790
|
+
is_mask_from_pts,
|
791
|
+
):
|
792
|
+
"""Encodes frame features and masks into a new memory representation for video segmentation."""
|
793
|
+
B = current_vision_feats[-1].size(1) # batch size on this frame
|
794
|
+
C = self.hidden_dim
|
795
|
+
H, W = feat_sizes[-1] # top-level (lowest-resolution) feature size
|
796
|
+
# top-level feature, (HW)BC => BCHW
|
797
|
+
pix_feat = current_vision_feats[-1].permute(1, 2, 0).view(B, C, H, W)
|
798
|
+
if self.non_overlap_masks_for_mem_enc and not self.training:
|
799
|
+
# optionally, apply non-overlapping constraints to the masks (it's applied
|
800
|
+
# in the batch dimension and should only be used during eval, where all
|
801
|
+
# the objects come from the same video under batch size 1).
|
802
|
+
pred_masks_high_res = self._apply_non_overlapping_constraints(pred_masks_high_res)
|
803
|
+
# scale the raw mask logits with a temperature before applying sigmoid
|
804
|
+
binarize = self.binarize_mask_from_pts_for_mem_enc and is_mask_from_pts
|
805
|
+
if binarize and not self.training:
|
806
|
+
mask_for_mem = (pred_masks_high_res > 0).float()
|
807
|
+
else:
|
808
|
+
# apply sigmoid on the raw mask logits to turn them into range (0, 1)
|
809
|
+
mask_for_mem = torch.sigmoid(pred_masks_high_res)
|
810
|
+
# apply scale and bias terms to the sigmoid probabilities
|
811
|
+
if self.sigmoid_scale_for_mem_enc != 1.0:
|
812
|
+
mask_for_mem = mask_for_mem * self.sigmoid_scale_for_mem_enc
|
813
|
+
if self.sigmoid_bias_for_mem_enc != 0.0:
|
814
|
+
mask_for_mem = mask_for_mem + self.sigmoid_bias_for_mem_enc
|
815
|
+
maskmem_out = self.memory_encoder(pix_feat, mask_for_mem, skip_mask_sigmoid=True) # sigmoid already applied
|
816
|
+
maskmem_features = maskmem_out["vision_features"]
|
817
|
+
maskmem_pos_enc = maskmem_out["vision_pos_enc"]
|
818
|
+
# add a no-object embedding to the spatial memory to indicate that the frame
|
819
|
+
# is predicted to be occluded (i.e. no object is appearing in the frame)
|
820
|
+
if self.no_obj_embed_spatial is not None:
|
821
|
+
is_obj_appearing = (object_score_logits > 0).float()
|
822
|
+
maskmem_features += (1 - is_obj_appearing[..., None, None]) * self.no_obj_embed_spatial[
|
823
|
+
..., None, None
|
824
|
+
].expand(*maskmem_features.shape)
|
825
|
+
|
826
|
+
return maskmem_features, maskmem_pos_enc
|
827
|
+
|
828
|
+
def _track_step(
|
829
|
+
self,
|
830
|
+
frame_idx,
|
831
|
+
is_init_cond_frame,
|
832
|
+
current_vision_feats,
|
833
|
+
current_vision_pos_embeds,
|
834
|
+
feat_sizes,
|
835
|
+
point_inputs,
|
836
|
+
mask_inputs,
|
837
|
+
output_dict,
|
838
|
+
num_frames,
|
839
|
+
track_in_reverse,
|
840
|
+
prev_sam_mask_logits,
|
841
|
+
):
|
842
|
+
"""Performs a single tracking step, updating object masks and memory features based on current frame inputs."""
|
843
|
+
current_out = {"point_inputs": point_inputs, "mask_inputs": mask_inputs}
|
844
|
+
# High-resolution feature maps for the SAM head, reshape (HW)BC => BCHW
|
845
|
+
if len(current_vision_feats) > 1:
|
846
|
+
high_res_features = [
|
847
|
+
x.permute(1, 2, 0).view(x.size(1), x.size(2), *s)
|
848
|
+
for x, s in zip(current_vision_feats[:-1], feat_sizes[:-1])
|
849
|
+
]
|
850
|
+
else:
|
851
|
+
high_res_features = None
|
852
|
+
if mask_inputs is not None and self.use_mask_input_as_output_without_sam:
|
853
|
+
# When use_mask_input_as_output_without_sam=True, we directly output the mask input
|
854
|
+
# (see it as a GT mask) without using a SAM prompt encoder + mask decoder.
|
855
|
+
pix_feat = current_vision_feats[-1].permute(1, 2, 0)
|
856
|
+
pix_feat = pix_feat.view(-1, self.hidden_dim, *feat_sizes[-1])
|
857
|
+
sam_outputs = self._use_mask_as_output(pix_feat, high_res_features, mask_inputs)
|
858
|
+
else:
|
859
|
+
# fused the visual feature with previous memory features in the memory bank
|
860
|
+
pix_feat = self._prepare_memory_conditioned_features(
|
861
|
+
frame_idx=frame_idx,
|
862
|
+
is_init_cond_frame=is_init_cond_frame,
|
863
|
+
current_vision_feats=current_vision_feats[-1:],
|
864
|
+
current_vision_pos_embeds=current_vision_pos_embeds[-1:],
|
865
|
+
feat_sizes=feat_sizes[-1:],
|
866
|
+
output_dict=output_dict,
|
867
|
+
num_frames=num_frames,
|
868
|
+
track_in_reverse=track_in_reverse,
|
869
|
+
)
|
870
|
+
# apply SAM-style segmentation head
|
871
|
+
# here we might feed previously predicted low-res SAM mask logits into the SAM mask decoder,
|
872
|
+
# e.g. in demo where such logits come from earlier interaction instead of correction sampling
|
873
|
+
# (in this case, any `mask_inputs` shouldn't reach here as they are sent to _use_mask_as_output instead)
|
874
|
+
if prev_sam_mask_logits is not None:
|
875
|
+
assert point_inputs is not None and mask_inputs is None
|
876
|
+
mask_inputs = prev_sam_mask_logits
|
877
|
+
multimask_output = self._use_multimask(is_init_cond_frame, point_inputs)
|
878
|
+
sam_outputs = self._forward_sam_heads(
|
879
|
+
backbone_features=pix_feat,
|
880
|
+
point_inputs=point_inputs,
|
881
|
+
mask_inputs=mask_inputs,
|
882
|
+
high_res_features=high_res_features,
|
883
|
+
multimask_output=multimask_output,
|
884
|
+
)
|
885
|
+
return current_out, sam_outputs, high_res_features, pix_feat
|
886
|
+
|
887
|
+
def _encode_memory_in_output(
|
888
|
+
self,
|
889
|
+
current_vision_feats,
|
890
|
+
feat_sizes,
|
891
|
+
point_inputs,
|
892
|
+
run_mem_encoder,
|
893
|
+
high_res_masks,
|
894
|
+
object_score_logits,
|
895
|
+
current_out,
|
896
|
+
):
|
897
|
+
"""Finally run the memory encoder on the predicted mask to encode, it into a new memory feature (that can be
|
898
|
+
used in future frames).
|
899
|
+
"""
|
900
|
+
if run_mem_encoder and self.num_maskmem > 0:
|
901
|
+
high_res_masks_for_mem_enc = high_res_masks
|
902
|
+
maskmem_features, maskmem_pos_enc = self._encode_new_memory(
|
903
|
+
current_vision_feats=current_vision_feats,
|
904
|
+
feat_sizes=feat_sizes,
|
905
|
+
pred_masks_high_res=high_res_masks_for_mem_enc,
|
906
|
+
object_score_logits=object_score_logits,
|
907
|
+
is_mask_from_pts=(point_inputs is not None),
|
908
|
+
)
|
909
|
+
current_out["maskmem_features"] = maskmem_features
|
910
|
+
current_out["maskmem_pos_enc"] = maskmem_pos_enc
|
911
|
+
else:
|
912
|
+
current_out["maskmem_features"] = None
|
913
|
+
current_out["maskmem_pos_enc"] = None
|
914
|
+
|
915
|
+
def track_step(
|
916
|
+
self,
|
917
|
+
frame_idx,
|
918
|
+
is_init_cond_frame,
|
919
|
+
current_vision_feats,
|
920
|
+
current_vision_pos_embeds,
|
921
|
+
feat_sizes,
|
922
|
+
point_inputs,
|
923
|
+
mask_inputs,
|
924
|
+
output_dict,
|
925
|
+
num_frames,
|
926
|
+
track_in_reverse=False, # tracking in reverse time order (for demo usage)
|
927
|
+
# Whether to run the memory encoder on the predicted masks. Sometimes we might want
|
928
|
+
# to skip the memory encoder with `run_mem_encoder=False`. For example,
|
929
|
+
# in demo we might call `track_step` multiple times for each user click,
|
930
|
+
# and only encode the memory when the user finalizes their clicks. And in ablation
|
931
|
+
# settings like SAM training on static images, we don't need the memory encoder.
|
932
|
+
run_mem_encoder=True,
|
933
|
+
# The previously predicted SAM mask logits (which can be fed together with new clicks in demo).
|
934
|
+
prev_sam_mask_logits=None,
|
935
|
+
):
|
936
|
+
"""Performs a single tracking step, updating object masks and memory features based on current frame inputs."""
|
937
|
+
current_out, sam_outputs, _, _ = self._track_step(
|
938
|
+
frame_idx,
|
939
|
+
is_init_cond_frame,
|
940
|
+
current_vision_feats,
|
941
|
+
current_vision_pos_embeds,
|
942
|
+
feat_sizes,
|
943
|
+
point_inputs,
|
944
|
+
mask_inputs,
|
945
|
+
output_dict,
|
946
|
+
num_frames,
|
947
|
+
track_in_reverse,
|
948
|
+
prev_sam_mask_logits,
|
949
|
+
)
|
950
|
+
_, _, _, low_res_masks, high_res_masks, obj_ptr, object_score_logits = sam_outputs
|
951
|
+
|
952
|
+
current_out["pred_masks"] = low_res_masks
|
953
|
+
current_out["pred_masks_high_res"] = high_res_masks
|
954
|
+
current_out["obj_ptr"] = obj_ptr
|
955
|
+
if not self.training:
|
956
|
+
# Only add this in inference (to avoid unused param in activation checkpointing;
|
957
|
+
# it's mainly used in the demo to encode spatial memories w/ consolidated masks)
|
958
|
+
current_out["object_score_logits"] = object_score_logits
|
959
|
+
|
960
|
+
# Run memory encoder on the predicted mask to encode it into a new memory feature (for use in future frames)
|
961
|
+
self._encode_memory_in_output(
|
962
|
+
current_vision_feats,
|
963
|
+
feat_sizes,
|
964
|
+
point_inputs,
|
965
|
+
run_mem_encoder,
|
966
|
+
high_res_masks,
|
967
|
+
object_score_logits,
|
968
|
+
current_out,
|
969
|
+
)
|
970
|
+
|
971
|
+
return current_out
|
972
|
+
|
973
|
+
def _use_multimask(self, is_init_cond_frame, point_inputs):
|
974
|
+
"""Determines whether to use multiple mask outputs in the SAM head based on configuration and inputs."""
|
975
|
+
num_pts = 0 if point_inputs is None else point_inputs["point_labels"].size(1)
|
976
|
+
return (
|
977
|
+
self.multimask_output_in_sam
|
978
|
+
and (is_init_cond_frame or self.multimask_output_for_tracking)
|
979
|
+
and (self.multimask_min_pt_num <= num_pts <= self.multimask_max_pt_num)
|
980
|
+
)
|
981
|
+
|
982
|
+
@staticmethod
|
983
|
+
def _apply_non_overlapping_constraints(pred_masks):
|
984
|
+
"""Applies non-overlapping constraints to masks, keeping the highest scoring object per location."""
|
985
|
+
batch_size = pred_masks.size(0)
|
986
|
+
if batch_size == 1:
|
987
|
+
return pred_masks
|
988
|
+
|
989
|
+
device = pred_masks.device
|
990
|
+
# "max_obj_inds": object index of the object with the highest score at each location
|
991
|
+
max_obj_inds = torch.argmax(pred_masks, dim=0, keepdim=True)
|
992
|
+
# "batch_obj_inds": object index of each object slice (along dim 0) in `pred_masks`
|
993
|
+
batch_obj_inds = torch.arange(batch_size, device=device)[:, None, None, None]
|
994
|
+
keep = max_obj_inds == batch_obj_inds
|
995
|
+
# suppress overlapping regions' scores below -10.0 so that the foreground regions
|
996
|
+
# don't overlap (here sigmoid(-10.0)=4.5398e-05)
|
997
|
+
pred_masks = torch.where(keep, pred_masks, torch.clamp(pred_masks, max=-10.0))
|
998
|
+
return pred_masks
|
999
|
+
|
1000
|
+
def set_binarize(self, binarize=False):
|
1001
|
+
"""Set binarize for VideoPredictor."""
|
1002
|
+
self.binarize_mask_from_pts_for_mem_enc = binarize
|
1003
|
+
|
1004
|
+
def set_imgsz(self, imgsz):
|
1005
|
+
"""
|
1006
|
+
Set image size to make model compatible with different image sizes.
|
1007
|
+
|
1008
|
+
Args:
|
1009
|
+
imgsz (Tuple[int, int]): The size of the input image.
|
1010
|
+
"""
|
1011
|
+
self.image_size = imgsz[0]
|
1012
|
+
self.sam_prompt_encoder.input_image_size = imgsz
|
1013
|
+
self.sam_prompt_encoder.image_embedding_size = [x // 16 for x in imgsz] # fixed ViT patch size of 16
|