ultralytics 8.2.68__py3-none-any.whl → 8.2.70__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.
Potentially problematic release.
This version of ultralytics might be problematic. Click here for more details.
- tests/test_cli.py +4 -16
- ultralytics/__init__.py +3 -2
- ultralytics/cfg/__init__.py +4 -0
- ultralytics/data/augment.py +1 -1
- ultralytics/hub/google/__init__.py +3 -3
- ultralytics/models/__init__.py +2 -1
- ultralytics/models/fastsam/__init__.py +1 -2
- ultralytics/models/fastsam/model.py +18 -0
- ultralytics/models/fastsam/predict.py +116 -1
- ultralytics/models/sam/build.py +2 -2
- ultralytics/models/sam/model.py +10 -2
- ultralytics/models/sam/modules/decoders.py +1 -42
- ultralytics/models/sam/modules/encoders.py +3 -1
- ultralytics/models/sam/modules/sam.py +5 -7
- ultralytics/models/sam/modules/transformer.py +4 -3
- ultralytics/models/sam/predict.py +12 -6
- ultralytics/models/sam2/__init__.py +6 -0
- ultralytics/models/sam2/build.py +156 -0
- ultralytics/models/sam2/model.py +97 -0
- ultralytics/models/sam2/modules/__init__.py +1 -0
- ultralytics/models/sam2/modules/decoders.py +305 -0
- ultralytics/models/sam2/modules/encoders.py +332 -0
- ultralytics/models/sam2/modules/memory_attention.py +170 -0
- ultralytics/models/sam2/modules/sam2.py +804 -0
- ultralytics/models/sam2/modules/sam2_blocks.py +715 -0
- ultralytics/models/sam2/modules/utils.py +191 -0
- ultralytics/models/sam2/predict.py +182 -0
- ultralytics/nn/modules/transformer.py +5 -3
- ultralytics/utils/ops.py +1 -1
- ultralytics/utils/torch_utils.py +9 -6
- {ultralytics-8.2.68.dist-info → ultralytics-8.2.70.dist-info}/METADATA +1 -1
- {ultralytics-8.2.68.dist-info → ultralytics-8.2.70.dist-info}/RECORD +36 -26
- {ultralytics-8.2.68.dist-info → ultralytics-8.2.70.dist-info}/WHEEL +1 -1
- ultralytics/models/fastsam/prompt.py +0 -352
- {ultralytics-8.2.68.dist-info → ultralytics-8.2.70.dist-info}/LICENSE +0 -0
- {ultralytics-8.2.68.dist-info → ultralytics-8.2.70.dist-info}/entry_points.txt +0 -0
- {ultralytics-8.2.68.dist-info → ultralytics-8.2.70.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
# Ultralytics YOLO 🚀, AGPL-3.0 license
|
|
2
|
+
|
|
3
|
+
import torch
|
|
4
|
+
|
|
5
|
+
from ultralytics.utils.downloads import attempt_download_asset
|
|
6
|
+
|
|
7
|
+
from .modules.encoders import FpnNeck, Hiera, ImageEncoder, MemoryEncoder
|
|
8
|
+
from .modules.memory_attention import MemoryAttention, MemoryAttentionLayer
|
|
9
|
+
from .modules.sam2 import SAM2Model
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def build_sam2_t(checkpoint=None):
|
|
13
|
+
"""Build and return a Segment Anything Model (SAM2) tiny-size model with specified architecture parameters."""
|
|
14
|
+
return _build_sam2(
|
|
15
|
+
encoder_embed_dim=96,
|
|
16
|
+
encoder_stages=[1, 2, 7, 2],
|
|
17
|
+
encoder_num_heads=1,
|
|
18
|
+
encoder_global_att_blocks=[5, 7, 9],
|
|
19
|
+
encoder_window_spec=[8, 4, 14, 7],
|
|
20
|
+
encoder_backbone_channel_list=[768, 384, 192, 96],
|
|
21
|
+
checkpoint=checkpoint,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def build_sam2_s(checkpoint=None):
|
|
26
|
+
"""Builds and returns a small-size Segment Anything Model (SAM2) with specified architecture parameters."""
|
|
27
|
+
return _build_sam2(
|
|
28
|
+
encoder_embed_dim=96,
|
|
29
|
+
encoder_stages=[1, 2, 11, 2],
|
|
30
|
+
encoder_num_heads=1,
|
|
31
|
+
encoder_global_att_blocks=[7, 10, 13],
|
|
32
|
+
encoder_window_spec=[8, 4, 14, 7],
|
|
33
|
+
encoder_backbone_channel_list=[768, 384, 192, 96],
|
|
34
|
+
checkpoint=checkpoint,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def build_sam2_b(checkpoint=None):
|
|
39
|
+
"""Builds and returns a Segment Anything Model (SAM2) base-size model with specified architecture parameters."""
|
|
40
|
+
return _build_sam2(
|
|
41
|
+
encoder_embed_dim=112,
|
|
42
|
+
encoder_stages=[2, 3, 16, 3],
|
|
43
|
+
encoder_num_heads=2,
|
|
44
|
+
encoder_global_att_blocks=[12, 16, 20],
|
|
45
|
+
encoder_window_spec=[8, 4, 14, 7],
|
|
46
|
+
encoder_window_spatial_size=[14, 14],
|
|
47
|
+
encoder_backbone_channel_list=[896, 448, 224, 112],
|
|
48
|
+
checkpoint=checkpoint,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def build_sam2_l(checkpoint=None):
|
|
53
|
+
"""Build and return a Segment Anything Model (SAM2) large-size model with specified architecture parameters."""
|
|
54
|
+
return _build_sam2(
|
|
55
|
+
encoder_embed_dim=144,
|
|
56
|
+
encoder_stages=[2, 6, 36, 4],
|
|
57
|
+
encoder_num_heads=2,
|
|
58
|
+
encoder_global_att_blocks=[23, 33, 43],
|
|
59
|
+
encoder_window_spec=[8, 4, 16, 8],
|
|
60
|
+
encoder_backbone_channel_list=[1152, 576, 288, 144],
|
|
61
|
+
checkpoint=checkpoint,
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _build_sam2(
|
|
66
|
+
encoder_embed_dim=1280,
|
|
67
|
+
encoder_stages=[2, 6, 36, 4],
|
|
68
|
+
encoder_num_heads=2,
|
|
69
|
+
encoder_global_att_blocks=[7, 15, 23, 31],
|
|
70
|
+
encoder_backbone_channel_list=[1152, 576, 288, 144],
|
|
71
|
+
encoder_window_spatial_size=[7, 7],
|
|
72
|
+
encoder_window_spec=[8, 4, 16, 8],
|
|
73
|
+
checkpoint=None,
|
|
74
|
+
):
|
|
75
|
+
"""Builds a SAM2 model with specified architecture parameters and optional checkpoint loading."""
|
|
76
|
+
image_encoder = ImageEncoder(
|
|
77
|
+
trunk=Hiera(
|
|
78
|
+
embed_dim=encoder_embed_dim,
|
|
79
|
+
num_heads=encoder_num_heads,
|
|
80
|
+
stages=encoder_stages,
|
|
81
|
+
global_att_blocks=encoder_global_att_blocks,
|
|
82
|
+
window_pos_embed_bkg_spatial_size=encoder_window_spatial_size,
|
|
83
|
+
window_spec=encoder_window_spec,
|
|
84
|
+
),
|
|
85
|
+
neck=FpnNeck(
|
|
86
|
+
d_model=256,
|
|
87
|
+
backbone_channel_list=encoder_backbone_channel_list,
|
|
88
|
+
fpn_top_down_levels=[2, 3],
|
|
89
|
+
fpn_interp_model="nearest",
|
|
90
|
+
),
|
|
91
|
+
scalp=1,
|
|
92
|
+
)
|
|
93
|
+
memory_attention = MemoryAttention(d_model=256, pos_enc_at_input=True, num_layers=4, layer=MemoryAttentionLayer())
|
|
94
|
+
memory_encoder = MemoryEncoder(out_dim=64)
|
|
95
|
+
|
|
96
|
+
sam2 = SAM2Model(
|
|
97
|
+
image_encoder=image_encoder,
|
|
98
|
+
memory_attention=memory_attention,
|
|
99
|
+
memory_encoder=memory_encoder,
|
|
100
|
+
num_maskmem=7,
|
|
101
|
+
image_size=1024,
|
|
102
|
+
sigmoid_scale_for_mem_enc=20.0,
|
|
103
|
+
sigmoid_bias_for_mem_enc=-10.0,
|
|
104
|
+
use_mask_input_as_output_without_sam=True,
|
|
105
|
+
directly_add_no_mem_embed=True,
|
|
106
|
+
use_high_res_features_in_sam=True,
|
|
107
|
+
multimask_output_in_sam=True,
|
|
108
|
+
iou_prediction_use_sigmoid=True,
|
|
109
|
+
use_obj_ptrs_in_encoder=True,
|
|
110
|
+
add_tpos_enc_to_obj_ptrs=True,
|
|
111
|
+
only_obj_ptrs_in_the_past_for_eval=True,
|
|
112
|
+
pred_obj_scores=True,
|
|
113
|
+
pred_obj_scores_mlp=True,
|
|
114
|
+
fixed_no_obj_ptr=True,
|
|
115
|
+
multimask_output_for_tracking=True,
|
|
116
|
+
use_multimask_token_for_obj_ptr=True,
|
|
117
|
+
multimask_min_pt_num=0,
|
|
118
|
+
multimask_max_pt_num=1,
|
|
119
|
+
use_mlp_for_obj_ptr_proj=True,
|
|
120
|
+
compile_image_encoder=False,
|
|
121
|
+
sam_mask_decoder_extra_args=dict(
|
|
122
|
+
dynamic_multimask_via_stability=True,
|
|
123
|
+
dynamic_multimask_stability_delta=0.05,
|
|
124
|
+
dynamic_multimask_stability_thresh=0.98,
|
|
125
|
+
),
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
if checkpoint is not None:
|
|
129
|
+
checkpoint = attempt_download_asset(checkpoint)
|
|
130
|
+
with open(checkpoint, "rb") as f:
|
|
131
|
+
state_dict = torch.load(f)["model"]
|
|
132
|
+
sam2.load_state_dict(state_dict)
|
|
133
|
+
sam2.eval()
|
|
134
|
+
return sam2
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
sam_model_map = {
|
|
138
|
+
"sam2_t.pt": build_sam2_t,
|
|
139
|
+
"sam2_s.pt": build_sam2_s,
|
|
140
|
+
"sam2_b.pt": build_sam2_b,
|
|
141
|
+
"sam2_l.pt": build_sam2_l,
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def build_sam2(ckpt="sam_b.pt"):
|
|
146
|
+
"""Constructs a Segment Anything Model (SAM2) based on the specified checkpoint, with various size options."""
|
|
147
|
+
model_builder = None
|
|
148
|
+
ckpt = str(ckpt) # to allow Path ckpt types
|
|
149
|
+
for k in sam_model_map.keys():
|
|
150
|
+
if ckpt.endswith(k):
|
|
151
|
+
model_builder = sam_model_map.get(k)
|
|
152
|
+
|
|
153
|
+
if not model_builder:
|
|
154
|
+
raise FileNotFoundError(f"{ckpt} is not a supported SAM model. Available models are: \n {sam_model_map.keys()}")
|
|
155
|
+
|
|
156
|
+
return model_builder(ckpt)
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# Ultralytics YOLO 🚀, AGPL-3.0 license
|
|
2
|
+
"""
|
|
3
|
+
SAM2 model interface.
|
|
4
|
+
|
|
5
|
+
This module provides an interface to the Segment Anything Model (SAM2) from Ultralytics, designed for real-time image
|
|
6
|
+
segmentation tasks. The SAM2 model allows for promptable segmentation with unparalleled versatility in image analysis,
|
|
7
|
+
and has been trained on the SA-1B dataset. It features zero-shot performance capabilities, enabling it to adapt to new
|
|
8
|
+
image distributions and tasks without prior knowledge.
|
|
9
|
+
|
|
10
|
+
Key Features:
|
|
11
|
+
- Promptable segmentation
|
|
12
|
+
- Real-time performance
|
|
13
|
+
- Zero-shot transfer capabilities
|
|
14
|
+
- Trained on SA-1B dataset
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from ultralytics.models.sam import SAM
|
|
18
|
+
|
|
19
|
+
from .build import build_sam2
|
|
20
|
+
from .predict import SAM2Predictor
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class SAM2(SAM):
|
|
24
|
+
"""
|
|
25
|
+
SAM2 class for real-time image segmentation using the Segment Anything Model (SAM2).
|
|
26
|
+
|
|
27
|
+
This class extends the SAM base class, providing an interface to the SAM2 model for promptable segmentation
|
|
28
|
+
tasks. It supports loading pre-trained weights and offers zero-shot performance capabilities.
|
|
29
|
+
|
|
30
|
+
Attributes:
|
|
31
|
+
model (torch.nn.Module): The loaded SAM2 model.
|
|
32
|
+
task_map (Dict[str, Type[SAM2Predictor]]): Mapping of 'segment' task to SAM2Predictor.
|
|
33
|
+
|
|
34
|
+
Methods:
|
|
35
|
+
__init__: Initializes the SAM2 model with pre-trained weights.
|
|
36
|
+
_load: Loads specified weights into the SAM2 model.
|
|
37
|
+
|
|
38
|
+
Examples:
|
|
39
|
+
>>> sam2 = SAM2("sam2_b.pt")
|
|
40
|
+
>>> sam2._load('path/to/sam2_weights.pt')
|
|
41
|
+
>>> task_map = sam2.task_map
|
|
42
|
+
>>> print(task_map)
|
|
43
|
+
{'segment': SAM2Predictor}
|
|
44
|
+
|
|
45
|
+
Notes:
|
|
46
|
+
- Supports .pt and .pth file extensions for model weights.
|
|
47
|
+
- Offers zero-shot transfer capabilities for new image distributions and tasks.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
def __init__(self, model="sam2_b.pt") -> None:
|
|
51
|
+
"""
|
|
52
|
+
Initializes the SAM2 model with a pre-trained model file.
|
|
53
|
+
|
|
54
|
+
Args:
|
|
55
|
+
model (str): Path to the pre-trained SAM2 model file. File should have a .pt or .pth extension.
|
|
56
|
+
|
|
57
|
+
Raises:
|
|
58
|
+
NotImplementedError: If the model file extension is not .pt or .pth.
|
|
59
|
+
|
|
60
|
+
Examples:
|
|
61
|
+
>>> sam2 = SAM2("sam2_b.pt")
|
|
62
|
+
"""
|
|
63
|
+
super().__init__(model=model)
|
|
64
|
+
|
|
65
|
+
def _load(self, weights: str, task=None):
|
|
66
|
+
"""
|
|
67
|
+
Loads the specified weights into the SAM2 model.
|
|
68
|
+
|
|
69
|
+
This method is responsible for loading pre-trained weights into the SAM2 model. It supports loading
|
|
70
|
+
weights from files with .pt or .pth extensions.
|
|
71
|
+
|
|
72
|
+
Args:
|
|
73
|
+
weights (str): Path to the weights file. Should be a file with .pt or .pth extension.
|
|
74
|
+
task (str | None): Task name. If provided, it may be used to configure model-specific settings.
|
|
75
|
+
|
|
76
|
+
Examples:
|
|
77
|
+
>>> sam2_model = SAM2()
|
|
78
|
+
>>> sam2_model._load('path/to/sam2_weights.pt')
|
|
79
|
+
"""
|
|
80
|
+
self.model = build_sam2(weights)
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def task_map(self):
|
|
84
|
+
"""
|
|
85
|
+
Provides a mapping from the 'segment' task to its corresponding 'Predictor'.
|
|
86
|
+
|
|
87
|
+
Returns:
|
|
88
|
+
(Dict[str, Type[SAM2Predictor]]): A dictionary mapping the 'segment' task to its corresponding
|
|
89
|
+
SAM2Predictor class.
|
|
90
|
+
|
|
91
|
+
Examples:
|
|
92
|
+
>>> sam2 = SAM2()
|
|
93
|
+
>>> task_map = sam2.task_map
|
|
94
|
+
>>> print(task_map)
|
|
95
|
+
{'segment': SAM2Predictor}
|
|
96
|
+
"""
|
|
97
|
+
return {"segment": {"predictor": SAM2Predictor}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# Ultralytics YOLO 🚀, AGPL-3.0 license
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
# Ultralytics YOLO 🚀, AGPL-3.0 license
|
|
2
|
+
|
|
3
|
+
from typing import List, Optional, Tuple, Type
|
|
4
|
+
|
|
5
|
+
import torch
|
|
6
|
+
from torch import nn
|
|
7
|
+
|
|
8
|
+
from ultralytics.nn.modules import MLP, LayerNorm2d
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class MaskDecoder(nn.Module):
|
|
12
|
+
"""Transformer-based decoder predicting instance segmentation masks from image and prompt embeddings."""
|
|
13
|
+
|
|
14
|
+
def __init__(
|
|
15
|
+
self,
|
|
16
|
+
transformer_dim: int,
|
|
17
|
+
transformer: nn.Module,
|
|
18
|
+
num_multimask_outputs: int = 3,
|
|
19
|
+
activation: Type[nn.Module] = nn.GELU,
|
|
20
|
+
iou_head_depth: int = 3,
|
|
21
|
+
iou_head_hidden_dim: int = 256,
|
|
22
|
+
use_high_res_features: bool = False,
|
|
23
|
+
iou_prediction_use_sigmoid=False,
|
|
24
|
+
dynamic_multimask_via_stability=False,
|
|
25
|
+
dynamic_multimask_stability_delta=0.05,
|
|
26
|
+
dynamic_multimask_stability_thresh=0.98,
|
|
27
|
+
pred_obj_scores: bool = False,
|
|
28
|
+
pred_obj_scores_mlp: bool = False,
|
|
29
|
+
use_multimask_token_for_obj_ptr: bool = False,
|
|
30
|
+
) -> None:
|
|
31
|
+
"""
|
|
32
|
+
Initializes the MaskDecoder module for predicting instance segmentation masks.
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
transformer_dim (int): Channel dimension of the transformer.
|
|
36
|
+
transformer (nn.Module): Transformer used to predict masks.
|
|
37
|
+
num_multimask_outputs (int): Number of masks to predict when disambiguating masks.
|
|
38
|
+
activation (Type[nn.Module]): Type of activation to use when upscaling masks.
|
|
39
|
+
iou_head_depth (int): Depth of the MLP used to predict mask quality.
|
|
40
|
+
iou_head_hidden_dim (int): Hidden dimension of the MLP used to predict mask quality.
|
|
41
|
+
use_high_res_features (bool): Whether to use high-resolution features.
|
|
42
|
+
iou_prediction_use_sigmoid (bool): Whether to use sigmoid for IOU prediction.
|
|
43
|
+
dynamic_multimask_via_stability (bool): Whether to use dynamic multimask via stability.
|
|
44
|
+
dynamic_multimask_stability_delta (float): Delta value for dynamic multimask stability.
|
|
45
|
+
dynamic_multimask_stability_thresh (float): Threshold for dynamic multimask stability.
|
|
46
|
+
pred_obj_scores (bool): Whether to predict object scores.
|
|
47
|
+
pred_obj_scores_mlp (bool): Whether to use MLP for object score prediction.
|
|
48
|
+
use_multimask_token_for_obj_ptr (bool): Whether to use multimask token for object pointer.
|
|
49
|
+
|
|
50
|
+
Attributes:
|
|
51
|
+
transformer_dim (int): Channel dimension of the transformer.
|
|
52
|
+
transformer (nn.Module): Transformer used to predict masks.
|
|
53
|
+
num_multimask_outputs (int): Number of masks to predict when disambiguating masks.
|
|
54
|
+
iou_token (nn.Embedding): Embedding for IOU token.
|
|
55
|
+
num_mask_tokens (int): Total number of mask tokens.
|
|
56
|
+
mask_tokens (nn.Embedding): Embedding for mask tokens.
|
|
57
|
+
pred_obj_scores (bool): Whether to predict object scores.
|
|
58
|
+
obj_score_token (nn.Embedding): Embedding for object score token.
|
|
59
|
+
use_multimask_token_for_obj_ptr (bool): Whether to use multimask token for object pointer.
|
|
60
|
+
output_upscaling (nn.Sequential): Upscaling layers for output.
|
|
61
|
+
use_high_res_features (bool): Whether to use high-resolution features.
|
|
62
|
+
conv_s0 (nn.Conv2d): Convolutional layer for high-resolution features (s0).
|
|
63
|
+
conv_s1 (nn.Conv2d): Convolutional layer for high-resolution features (s1).
|
|
64
|
+
output_hypernetworks_mlps (nn.ModuleList): List of MLPs for output hypernetworks.
|
|
65
|
+
iou_prediction_head (MLP): MLP for IOU prediction.
|
|
66
|
+
pred_obj_score_head (nn.Linear | MLP): Linear layer or MLP for object score prediction.
|
|
67
|
+
dynamic_multimask_via_stability (bool): Whether to use dynamic multimask via stability.
|
|
68
|
+
dynamic_multimask_stability_delta (float): Delta value for dynamic multimask stability.
|
|
69
|
+
"""
|
|
70
|
+
super().__init__()
|
|
71
|
+
self.transformer_dim = transformer_dim
|
|
72
|
+
self.transformer = transformer
|
|
73
|
+
|
|
74
|
+
self.num_multimask_outputs = num_multimask_outputs
|
|
75
|
+
|
|
76
|
+
self.iou_token = nn.Embedding(1, transformer_dim)
|
|
77
|
+
self.num_mask_tokens = num_multimask_outputs + 1
|
|
78
|
+
self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim)
|
|
79
|
+
|
|
80
|
+
self.pred_obj_scores = pred_obj_scores
|
|
81
|
+
if self.pred_obj_scores:
|
|
82
|
+
self.obj_score_token = nn.Embedding(1, transformer_dim)
|
|
83
|
+
self.use_multimask_token_for_obj_ptr = use_multimask_token_for_obj_ptr
|
|
84
|
+
|
|
85
|
+
self.output_upscaling = nn.Sequential(
|
|
86
|
+
nn.ConvTranspose2d(transformer_dim, transformer_dim // 4, kernel_size=2, stride=2),
|
|
87
|
+
LayerNorm2d(transformer_dim // 4),
|
|
88
|
+
activation(),
|
|
89
|
+
nn.ConvTranspose2d(transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2),
|
|
90
|
+
activation(),
|
|
91
|
+
)
|
|
92
|
+
self.use_high_res_features = use_high_res_features
|
|
93
|
+
if use_high_res_features:
|
|
94
|
+
self.conv_s0 = nn.Conv2d(transformer_dim, transformer_dim // 8, kernel_size=1, stride=1)
|
|
95
|
+
self.conv_s1 = nn.Conv2d(transformer_dim, transformer_dim // 4, kernel_size=1, stride=1)
|
|
96
|
+
|
|
97
|
+
self.output_hypernetworks_mlps = nn.ModuleList(
|
|
98
|
+
[MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3) for _ in range(self.num_mask_tokens)]
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
self.iou_prediction_head = MLP(
|
|
102
|
+
transformer_dim,
|
|
103
|
+
iou_head_hidden_dim,
|
|
104
|
+
self.num_mask_tokens,
|
|
105
|
+
iou_head_depth,
|
|
106
|
+
sigmoid=iou_prediction_use_sigmoid,
|
|
107
|
+
)
|
|
108
|
+
if self.pred_obj_scores:
|
|
109
|
+
self.pred_obj_score_head = nn.Linear(transformer_dim, 1)
|
|
110
|
+
if pred_obj_scores_mlp:
|
|
111
|
+
self.pred_obj_score_head = MLP(transformer_dim, transformer_dim, 1, 3)
|
|
112
|
+
|
|
113
|
+
# When outputting a single mask, optionally we can dynamically fall back to the best
|
|
114
|
+
# multimask output token if the single mask output token gives low stability scores.
|
|
115
|
+
self.dynamic_multimask_via_stability = dynamic_multimask_via_stability
|
|
116
|
+
self.dynamic_multimask_stability_delta = dynamic_multimask_stability_delta
|
|
117
|
+
self.dynamic_multimask_stability_thresh = dynamic_multimask_stability_thresh
|
|
118
|
+
|
|
119
|
+
def forward(
|
|
120
|
+
self,
|
|
121
|
+
image_embeddings: torch.Tensor,
|
|
122
|
+
image_pe: torch.Tensor,
|
|
123
|
+
sparse_prompt_embeddings: torch.Tensor,
|
|
124
|
+
dense_prompt_embeddings: torch.Tensor,
|
|
125
|
+
multimask_output: bool,
|
|
126
|
+
repeat_image: bool,
|
|
127
|
+
high_res_features: Optional[List[torch.Tensor]] = None,
|
|
128
|
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
129
|
+
"""
|
|
130
|
+
Predicts masks given image and prompt embeddings.
|
|
131
|
+
|
|
132
|
+
Args:
|
|
133
|
+
image_embeddings (torch.Tensor): Embeddings from the image encoder.
|
|
134
|
+
image_pe (torch.Tensor): Positional encoding with the shape of image_embeddings.
|
|
135
|
+
sparse_prompt_embeddings (torch.Tensor): Embeddings of the points and boxes.
|
|
136
|
+
dense_prompt_embeddings (torch.Tensor): Embeddings of the mask inputs.
|
|
137
|
+
multimask_output (bool): Whether to return multiple masks or a single mask.
|
|
138
|
+
repeat_image (bool): Flag to repeat the image embeddings.
|
|
139
|
+
high_res_features (List[torch.Tensor] | None): Optional high-resolution features.
|
|
140
|
+
|
|
141
|
+
Returns:
|
|
142
|
+
(Tuple[torch.Tensor, torch.Tensor, torch.Tensor]): A tuple containing:
|
|
143
|
+
- masks (torch.Tensor): Batched predicted masks.
|
|
144
|
+
- iou_pred (torch.Tensor): Batched predictions of mask quality.
|
|
145
|
+
- sam_tokens_out (torch.Tensor): Batched SAM token for mask output.
|
|
146
|
+
|
|
147
|
+
Examples:
|
|
148
|
+
>>> image_embeddings = torch.rand(1, 256, 64, 64)
|
|
149
|
+
>>> image_pe = torch.rand(1, 256, 64, 64)
|
|
150
|
+
>>> sparse_prompt_embeddings = torch.rand(1, 2, 256)
|
|
151
|
+
>>> dense_prompt_embeddings = torch.rand(1, 256, 64, 64)
|
|
152
|
+
>>> decoder = MaskDecoder(256, transformer)
|
|
153
|
+
>>> masks, iou_pred, sam_tokens_out = decoder.forward(image_embeddings, image_pe,
|
|
154
|
+
... sparse_prompt_embeddings, dense_prompt_embeddings, True, False)
|
|
155
|
+
"""
|
|
156
|
+
masks, iou_pred, mask_tokens_out, object_score_logits = self.predict_masks(
|
|
157
|
+
image_embeddings=image_embeddings,
|
|
158
|
+
image_pe=image_pe,
|
|
159
|
+
sparse_prompt_embeddings=sparse_prompt_embeddings,
|
|
160
|
+
dense_prompt_embeddings=dense_prompt_embeddings,
|
|
161
|
+
repeat_image=repeat_image,
|
|
162
|
+
high_res_features=high_res_features,
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
# Select the correct mask or masks for output
|
|
166
|
+
if multimask_output:
|
|
167
|
+
masks = masks[:, 1:, :, :]
|
|
168
|
+
iou_pred = iou_pred[:, 1:]
|
|
169
|
+
elif self.dynamic_multimask_via_stability and not self.training:
|
|
170
|
+
masks, iou_pred = self._dynamic_multimask_via_stability(masks, iou_pred)
|
|
171
|
+
else:
|
|
172
|
+
masks = masks[:, 0:1, :, :]
|
|
173
|
+
iou_pred = iou_pred[:, 0:1]
|
|
174
|
+
|
|
175
|
+
if multimask_output and self.use_multimask_token_for_obj_ptr:
|
|
176
|
+
sam_tokens_out = mask_tokens_out[:, 1:] # [b, 3, c] shape
|
|
177
|
+
else:
|
|
178
|
+
# Take the mask output token. Here we *always* use the token for single mask output.
|
|
179
|
+
# At test time, even if we track after 1-click (and using multimask_output=True),
|
|
180
|
+
# we still take the single mask token here. The rationale is that we always track
|
|
181
|
+
# after multiple clicks during training, so the past tokens seen during training
|
|
182
|
+
# are always the single mask token (and we'll let it be the object-memory token).
|
|
183
|
+
sam_tokens_out = mask_tokens_out[:, 0:1] # [b, 1, c] shape
|
|
184
|
+
|
|
185
|
+
# Prepare output
|
|
186
|
+
return masks, iou_pred, sam_tokens_out, object_score_logits
|
|
187
|
+
|
|
188
|
+
def predict_masks(
|
|
189
|
+
self,
|
|
190
|
+
image_embeddings: torch.Tensor,
|
|
191
|
+
image_pe: torch.Tensor,
|
|
192
|
+
sparse_prompt_embeddings: torch.Tensor,
|
|
193
|
+
dense_prompt_embeddings: torch.Tensor,
|
|
194
|
+
repeat_image: bool,
|
|
195
|
+
high_res_features: Optional[List[torch.Tensor]] = None,
|
|
196
|
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
197
|
+
"""Predicts instance segmentation masks from image and prompt embeddings using a transformer architecture."""
|
|
198
|
+
# Concatenate output tokens
|
|
199
|
+
s = 0
|
|
200
|
+
if self.pred_obj_scores:
|
|
201
|
+
output_tokens = torch.cat(
|
|
202
|
+
[
|
|
203
|
+
self.obj_score_token.weight,
|
|
204
|
+
self.iou_token.weight,
|
|
205
|
+
self.mask_tokens.weight,
|
|
206
|
+
],
|
|
207
|
+
dim=0,
|
|
208
|
+
)
|
|
209
|
+
s = 1
|
|
210
|
+
else:
|
|
211
|
+
output_tokens = torch.cat([self.iou_token.weight, self.mask_tokens.weight], dim=0)
|
|
212
|
+
output_tokens = output_tokens.unsqueeze(0).expand(sparse_prompt_embeddings.size(0), -1, -1)
|
|
213
|
+
tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1)
|
|
214
|
+
|
|
215
|
+
# Expand per-image data in batch direction to be per-mask
|
|
216
|
+
if repeat_image:
|
|
217
|
+
src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0)
|
|
218
|
+
else:
|
|
219
|
+
assert image_embeddings.shape[0] == tokens.shape[0]
|
|
220
|
+
src = image_embeddings
|
|
221
|
+
src = src + dense_prompt_embeddings
|
|
222
|
+
assert image_pe.size(0) == 1, "image_pe should have size 1 in batch dim (from `get_dense_pe()`)"
|
|
223
|
+
pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0)
|
|
224
|
+
b, c, h, w = src.shape
|
|
225
|
+
|
|
226
|
+
# Run the transformer
|
|
227
|
+
hs, src = self.transformer(src, pos_src, tokens)
|
|
228
|
+
iou_token_out = hs[:, s, :]
|
|
229
|
+
mask_tokens_out = hs[:, s + 1 : (s + 1 + self.num_mask_tokens), :]
|
|
230
|
+
|
|
231
|
+
# Upscale mask embeddings and predict masks using the mask tokens
|
|
232
|
+
src = src.transpose(1, 2).view(b, c, h, w)
|
|
233
|
+
if not self.use_high_res_features:
|
|
234
|
+
upscaled_embedding = self.output_upscaling(src)
|
|
235
|
+
else:
|
|
236
|
+
dc1, ln1, act1, dc2, act2 = self.output_upscaling
|
|
237
|
+
feat_s0, feat_s1 = high_res_features
|
|
238
|
+
upscaled_embedding = act1(ln1(dc1(src) + feat_s1))
|
|
239
|
+
upscaled_embedding = act2(dc2(upscaled_embedding) + feat_s0)
|
|
240
|
+
|
|
241
|
+
hyper_in_list: List[torch.Tensor] = []
|
|
242
|
+
for i in range(self.num_mask_tokens):
|
|
243
|
+
hyper_in_list.append(self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :]))
|
|
244
|
+
hyper_in = torch.stack(hyper_in_list, dim=1)
|
|
245
|
+
b, c, h, w = upscaled_embedding.shape
|
|
246
|
+
masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w)
|
|
247
|
+
|
|
248
|
+
# Generate mask quality predictions
|
|
249
|
+
iou_pred = self.iou_prediction_head(iou_token_out)
|
|
250
|
+
if self.pred_obj_scores:
|
|
251
|
+
assert s == 1
|
|
252
|
+
object_score_logits = self.pred_obj_score_head(hs[:, 0, :])
|
|
253
|
+
else:
|
|
254
|
+
# Obj scores logits - default to 10.0, i.e. assuming the object is present, sigmoid(10)=1
|
|
255
|
+
object_score_logits = 10.0 * iou_pred.new_ones(iou_pred.shape[0], 1)
|
|
256
|
+
|
|
257
|
+
return masks, iou_pred, mask_tokens_out, object_score_logits
|
|
258
|
+
|
|
259
|
+
def _get_stability_scores(self, mask_logits):
|
|
260
|
+
"""Computes mask stability scores based on IoU between upper and lower thresholds."""
|
|
261
|
+
mask_logits = mask_logits.flatten(-2)
|
|
262
|
+
stability_delta = self.dynamic_multimask_stability_delta
|
|
263
|
+
area_i = torch.sum(mask_logits > stability_delta, dim=-1).float()
|
|
264
|
+
area_u = torch.sum(mask_logits > -stability_delta, dim=-1).float()
|
|
265
|
+
stability_scores = torch.where(area_u > 0, area_i / area_u, 1.0)
|
|
266
|
+
return stability_scores
|
|
267
|
+
|
|
268
|
+
def _dynamic_multimask_via_stability(self, all_mask_logits, all_iou_scores):
|
|
269
|
+
"""
|
|
270
|
+
Dynamically selects the most stable mask output based on stability scores and IoU predictions.
|
|
271
|
+
|
|
272
|
+
When outputting a single mask, if the stability score from the current single-mask output (based on output token
|
|
273
|
+
0) falls below a threshold, we instead select from multi-mask outputs (based on output token 1~3) the mask with
|
|
274
|
+
the highest predicted IoU score.
|
|
275
|
+
|
|
276
|
+
This is intended to ensure a valid mask for both clicking and tracking.
|
|
277
|
+
"""
|
|
278
|
+
# The best mask from multimask output tokens (1~3)
|
|
279
|
+
multimask_logits = all_mask_logits[:, 1:, :, :]
|
|
280
|
+
multimask_iou_scores = all_iou_scores[:, 1:]
|
|
281
|
+
best_scores_inds = torch.argmax(multimask_iou_scores, dim=-1)
|
|
282
|
+
batch_inds = torch.arange(multimask_iou_scores.size(0), device=all_iou_scores.device)
|
|
283
|
+
best_multimask_logits = multimask_logits[batch_inds, best_scores_inds]
|
|
284
|
+
best_multimask_logits = best_multimask_logits.unsqueeze(1)
|
|
285
|
+
best_multimask_iou_scores = multimask_iou_scores[batch_inds, best_scores_inds]
|
|
286
|
+
best_multimask_iou_scores = best_multimask_iou_scores.unsqueeze(1)
|
|
287
|
+
|
|
288
|
+
# The mask from singlemask output token 0 and its stability score
|
|
289
|
+
singlemask_logits = all_mask_logits[:, 0:1, :, :]
|
|
290
|
+
singlemask_iou_scores = all_iou_scores[:, 0:1]
|
|
291
|
+
stability_scores = self._get_stability_scores(singlemask_logits)
|
|
292
|
+
is_stable = stability_scores >= self.dynamic_multimask_stability_thresh
|
|
293
|
+
|
|
294
|
+
# Dynamically fall back to best multimask output upon low stability scores.
|
|
295
|
+
mask_logits_out = torch.where(
|
|
296
|
+
is_stable[..., None, None].expand_as(singlemask_logits),
|
|
297
|
+
singlemask_logits,
|
|
298
|
+
best_multimask_logits,
|
|
299
|
+
)
|
|
300
|
+
iou_scores_out = torch.where(
|
|
301
|
+
is_stable.expand_as(singlemask_iou_scores),
|
|
302
|
+
singlemask_iou_scores,
|
|
303
|
+
best_multimask_iou_scores,
|
|
304
|
+
)
|
|
305
|
+
return mask_logits_out, iou_scores_out
|