ductai199x commited on
Commit
0f0c271
1 Parent(s): fc63316

add modeling file

Browse files
Files changed (3) hide show
  1. .gitignore +1 -0
  2. modeling_sam_hq_vit_huge.py +1546 -0
  3. preprocessor_config.json +28 -0
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ **__pycache__**
modeling_sam_hq_vit_huge.py ADDED
@@ -0,0 +1,1546 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The Meta AI Authors and The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ PyTorch SAM model."""
16
+
17
+ import collections
18
+ import math
19
+ from dataclasses import dataclass
20
+ from typing import Dict, List, Optional, Tuple, Union
21
+
22
+ import numpy as np
23
+ import torch
24
+ import torch.nn.functional as F
25
+ import torch.utils.checkpoint
26
+ from torch import Tensor, nn
27
+
28
+ from transformers.activations import ACT2FN
29
+ from transformers.modeling_outputs import BaseModelOutput
30
+ from transformers.modeling_utils import PreTrainedModel
31
+ from transformers.utils import (
32
+ ModelOutput,
33
+ add_start_docstrings,
34
+ add_start_docstrings_to_model_forward,
35
+ logging,
36
+ )
37
+ from transformers.models.sam.configuration_sam import SamConfig, SamMaskDecoderConfig, SamPromptEncoderConfig, SamVisionConfig
38
+
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+ _CONFIG_FOR_DOC = "SamConfig"
43
+ _CHECKPOINT_FOR_DOC = "facebook/sam-vit-huge"
44
+
45
+
46
+ @dataclass
47
+ class SamVisionEncoderOutput(ModelOutput):
48
+ """
49
+ Base class for sam vision model's outputs that also contains image embeddings obtained by applying the projection
50
+ layer to the pooler_output.
51
+
52
+ Args:
53
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
54
+ The image embeddings obtained by applying the projection layer to the pooler_output.
55
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
56
+ Sequence of hidden-states at the output of the last layer of the model.
57
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
58
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
59
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
60
+
61
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
62
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
63
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
64
+ sequence_length)`.
65
+
66
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
67
+ heads.
68
+ """
69
+
70
+ image_embeds: Optional[torch.FloatTensor] = None
71
+ last_hidden_state: torch.FloatTensor = None
72
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
73
+ attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
74
+
75
+
76
+ @dataclass
77
+ class SamImageSegmentationOutput(ModelOutput):
78
+ """
79
+ Base class for Segment-Anything model's output
80
+
81
+ Args:
82
+ iou_scores (`torch.FloatTensor` of shape `(batch_size, num_masks)`):
83
+ The iou scores of the predicted masks.
84
+ pred_masks (`torch.FloatTensor` of shape `(batch_size, num_masks, height, width)`):
85
+ The predicted low resolutions masks. Needs to be post-processed by the processor
86
+ vision_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
87
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
88
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
89
+
90
+ Hidden-states of the vision model at the output of each layer plus the optional initial embedding outputs.
91
+ vision_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
92
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
93
+ sequence_length)`.
94
+
95
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
96
+ heads.
97
+ mask_decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
98
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
99
+ sequence_length)`.
100
+
101
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
102
+ heads.
103
+ """
104
+
105
+ iou_scores: torch.FloatTensor = None
106
+ pred_masks: torch.FloatTensor = None
107
+ vision_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
108
+ vision_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
109
+ mask_decoder_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
110
+
111
+
112
+ class SamPatchEmbeddings(nn.Module):
113
+ """
114
+ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
115
+ `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
116
+ Transformer.
117
+ """
118
+
119
+ def __init__(self, config):
120
+ super().__init__()
121
+ image_size, patch_size = config.image_size, config.patch_size
122
+ num_channels, hidden_size = config.num_channels, config.hidden_size
123
+ image_size = (
124
+ image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
125
+ )
126
+ patch_size = (
127
+ patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
128
+ )
129
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
130
+ self.image_size = image_size
131
+ self.patch_size = patch_size
132
+ self.num_channels = num_channels
133
+ self.num_patches = num_patches
134
+
135
+ self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
136
+
137
+ def forward(self, pixel_values):
138
+ batch_size, num_channels, height, width = pixel_values.shape
139
+ if num_channels != self.num_channels:
140
+ raise ValueError(
141
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
142
+ )
143
+ if height != self.image_size[0] or width != self.image_size[1]:
144
+ raise ValueError(
145
+ f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})."
146
+ )
147
+ embeddings = self.projection(pixel_values).permute(0, 2, 3, 1)
148
+ return embeddings
149
+
150
+
151
+ class SamMLPBlock(nn.Module):
152
+ def __init__(self, config):
153
+ super().__init__()
154
+ self.lin1 = nn.Linear(config.hidden_size, config.mlp_dim)
155
+ self.lin2 = nn.Linear(config.mlp_dim, config.hidden_size)
156
+ self.act = ACT2FN[config.hidden_act]
157
+
158
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
159
+ hidden_states = self.lin1(hidden_states)
160
+ hidden_states = self.act(hidden_states)
161
+ hidden_states = self.lin2(hidden_states)
162
+ return hidden_states
163
+
164
+
165
+ # Copied from transformers.models.convnext.modeling_convnext.ConvNextLayerNorm with ConvNext->Sam
166
+ class SamLayerNorm(nn.Module):
167
+ r"""LayerNorm that supports two data formats: channels_last (default) or channels_first.
168
+ The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height,
169
+ width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width).
170
+ """
171
+
172
+ def __init__(self, normalized_shape, eps=1e-6, data_format="channels_last"):
173
+ super().__init__()
174
+ self.weight = nn.Parameter(torch.ones(normalized_shape))
175
+ self.bias = nn.Parameter(torch.zeros(normalized_shape))
176
+ self.eps = eps
177
+ self.data_format = data_format
178
+ if self.data_format not in ["channels_last", "channels_first"]:
179
+ raise NotImplementedError(f"Unsupported data format: {self.data_format}")
180
+ self.normalized_shape = (normalized_shape,)
181
+
182
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
183
+ if self.data_format == "channels_last":
184
+ x = torch.nn.functional.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
185
+ elif self.data_format == "channels_first":
186
+ input_dtype = x.dtype
187
+ x = x.float()
188
+ u = x.mean(1, keepdim=True)
189
+ s = (x - u).pow(2).mean(1, keepdim=True)
190
+ x = (x - u) / torch.sqrt(s + self.eps)
191
+ x = x.to(dtype=input_dtype)
192
+ x = self.weight[:, None, None] * x + self.bias[:, None, None]
193
+ return x
194
+
195
+
196
+ class SamAttention(nn.Module):
197
+ """
198
+ SAM's attention layer that allows for downscaling the size of the embedding after projection to queries, keys, and
199
+ values.
200
+ """
201
+
202
+ def __init__(self, config, downsample_rate=None):
203
+ super().__init__()
204
+ self.hidden_size = config.hidden_size
205
+
206
+ downsample_rate = config.attention_downsample_rate if downsample_rate is None else downsample_rate
207
+
208
+ self.internal_dim = config.hidden_size // downsample_rate
209
+ self.num_attention_heads = config.num_attention_heads
210
+ if self.internal_dim % config.num_attention_heads != 0:
211
+ raise ValueError("num_attention_heads must divide hidden_size.")
212
+
213
+ self.q_proj = nn.Linear(self.hidden_size, self.internal_dim)
214
+ self.k_proj = nn.Linear(self.hidden_size, self.internal_dim)
215
+ self.v_proj = nn.Linear(self.hidden_size, self.internal_dim)
216
+ self.out_proj = nn.Linear(self.internal_dim, self.hidden_size)
217
+
218
+ def _separate_heads(self, hidden_states: Tensor, num_attention_heads: int) -> Tensor:
219
+ batch, point_batch_size, n_tokens, channel = hidden_states.shape
220
+ c_per_head = channel // num_attention_heads
221
+ hidden_states = hidden_states.reshape(
222
+ batch * point_batch_size, n_tokens, num_attention_heads, c_per_head
223
+ )
224
+ return hidden_states.transpose(1, 2)
225
+
226
+ def _recombine_heads(self, hidden_states: Tensor, point_batch_size: int) -> Tensor:
227
+ batch, n_heads, n_tokens, c_per_head = hidden_states.shape
228
+ hidden_states = hidden_states.transpose(1, 2)
229
+ return hidden_states.reshape(
230
+ batch // point_batch_size, point_batch_size, n_tokens, n_heads * c_per_head
231
+ )
232
+
233
+ def forward(
234
+ self, query: Tensor, key: Tensor, value: Tensor, attention_similarity: Tensor = None
235
+ ) -> Tensor:
236
+ # Input projections
237
+ query = self.q_proj(query)
238
+ key = self.k_proj(key)
239
+ value = self.v_proj(value)
240
+
241
+ point_batch_size = query.shape[1]
242
+ # Separate into heads
243
+ query = self._separate_heads(query, self.num_attention_heads)
244
+ key = self._separate_heads(key, self.num_attention_heads)
245
+ value = self._separate_heads(value, self.num_attention_heads)
246
+
247
+ # SamAttention
248
+ _, _, _, c_per_head = query.shape
249
+ attn = query @ key.permute(
250
+ 0, 1, 3, 2
251
+ ) # batch_size * point_batch_size x N_heads x N_tokens x N_tokens
252
+ attn = attn / math.sqrt(c_per_head)
253
+ attn = torch.softmax(attn, dim=-1)
254
+
255
+ if attention_similarity is not None:
256
+ attn = attn + attention_similarity
257
+ attn = torch.softmax(attn, dim=-1)
258
+
259
+ # Get output
260
+ out = attn @ value
261
+ out = self._recombine_heads(out, point_batch_size)
262
+ out = self.out_proj(out)
263
+
264
+ return out
265
+
266
+
267
+ class SamTwoWayAttentionBlock(nn.Module):
268
+ def __init__(self, config, attention_downsample_rate: int = 2, skip_first_layer_pe: bool = False):
269
+ """
270
+ A transformer block with four layers:
271
+ (1) self-attention of sparse inputs (2) cross attention of sparse inputs -> dense inputs (3) mlp block on
272
+ sparse inputs (4) cross attention of dense inputs -> sparse inputs
273
+
274
+ Arguments:
275
+ config (`SamMaskDecoderConfig`):
276
+ The configuration file used to instantiate the block
277
+ attention_downsample_rate (*optionalk*, int, defaults to 2):
278
+ The downsample ratio of the block used to reduce the inner dim of the attention.
279
+ skip_first_layer_pe (*optional*, bool, defaults to `False`):
280
+ Whether or not to skip the addition of the query_point_embedding on the first layer.
281
+ """
282
+ super().__init__()
283
+
284
+ self.hidden_size = config.hidden_size
285
+ self.layer_norm_eps = config.layer_norm_eps
286
+
287
+ self.self_attn = SamAttention(config, downsample_rate=1)
288
+ self.layer_norm1 = nn.LayerNorm(self.hidden_size, eps=self.layer_norm_eps)
289
+
290
+ self.cross_attn_token_to_image = SamAttention(config, downsample_rate=attention_downsample_rate)
291
+ self.layer_norm2 = nn.LayerNorm(self.hidden_size, eps=self.layer_norm_eps)
292
+
293
+ self.mlp = SamMLPBlock(config)
294
+ self.layer_norm3 = nn.LayerNorm(self.hidden_size, eps=self.layer_norm_eps)
295
+
296
+ self.layer_norm4 = nn.LayerNorm(self.hidden_size, eps=self.layer_norm_eps)
297
+ self.cross_attn_image_to_token = SamAttention(config, downsample_rate=attention_downsample_rate)
298
+
299
+ self.skip_first_layer_pe = skip_first_layer_pe
300
+
301
+ def forward(
302
+ self,
303
+ queries: Tensor,
304
+ keys: Tensor,
305
+ query_point_embedding: Tensor,
306
+ key_point_embedding: Tensor,
307
+ attention_similarity: Tensor,
308
+ output_attentions: bool = False,
309
+ ):
310
+ # Self attention block
311
+ if self.skip_first_layer_pe:
312
+ queries = self.self_attn(query=queries, key=queries, value=queries)
313
+ else:
314
+ query = queries + query_point_embedding
315
+ attn_out = self.self_attn(query=query, key=query, value=queries)
316
+ queries = queries + attn_out
317
+ queries = self.layer_norm1(queries)
318
+
319
+ # Cross attention block, tokens attending to image embedding
320
+ query = queries + query_point_embedding
321
+ key = keys + key_point_embedding
322
+
323
+ attn_out = self.cross_attn_token_to_image(
324
+ query=query, key=key, value=keys, attention_similarity=attention_similarity
325
+ )
326
+ queries = queries + attn_out
327
+
328
+ queries = self.layer_norm2(queries)
329
+
330
+ # MLP block
331
+ mlp_out = self.mlp(queries)
332
+ queries = queries + mlp_out
333
+ queries = self.layer_norm3(queries)
334
+
335
+ # Cross attention block, image embedding attending to tokens
336
+ query = queries + query_point_embedding
337
+ key = keys + key_point_embedding
338
+
339
+ attn_out = self.cross_attn_image_to_token(query=key, key=query, value=queries)
340
+ keys = keys + attn_out
341
+
342
+ keys = self.layer_norm4(keys)
343
+
344
+ outputs = (queries, keys)
345
+
346
+ if output_attentions:
347
+ outputs = outputs + (attn_out,)
348
+ else:
349
+ outputs = outputs + (None,)
350
+
351
+ return outputs
352
+
353
+
354
+ class SamTwoWayTransformer(nn.Module):
355
+ def __init__(self, config: SamMaskDecoderConfig):
356
+ super().__init__()
357
+ self.config = config
358
+
359
+ self.num_hidden_layers = config.num_hidden_layers
360
+ self.layers = nn.ModuleList()
361
+
362
+ for i in range(self.num_hidden_layers):
363
+ self.layers.append(SamTwoWayAttentionBlock(config, skip_first_layer_pe=(i == 0)))
364
+
365
+ self.final_attn_token_to_image = SamAttention(config)
366
+ self.layer_norm_final_attn = nn.LayerNorm(config.hidden_size)
367
+
368
+ def forward(
369
+ self,
370
+ point_embeddings: Tensor,
371
+ image_embeddings: Tensor,
372
+ image_positional_embeddings: Tensor,
373
+ attention_similarity: Tensor,
374
+ target_embedding=None,
375
+ output_attentions: Optional[bool] = None,
376
+ output_hidden_states: Optional[bool] = None,
377
+ return_dict: Optional[bool] = None,
378
+ ) -> Union[Tuple, BaseModelOutput]:
379
+ output_attentions = (
380
+ output_attentions if output_attentions is not None else self.config.output_attentions
381
+ )
382
+ output_hidden_states = (
383
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
384
+ )
385
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
386
+
387
+ all_attentions = ()
388
+
389
+ if image_embeddings is None:
390
+ raise ValueError("You have to specify an image_embedding")
391
+
392
+ image_embeddings = image_embeddings.flatten(2).permute(0, 2, 1).unsqueeze(1)
393
+ image_positional_embeddings = image_positional_embeddings.flatten(2).permute(0, 2, 1).unsqueeze(1)
394
+
395
+ # Prepare queries
396
+ queries = point_embeddings
397
+ keys = image_embeddings
398
+
399
+ # Apply transformer blocks and final layernorm
400
+ for layer in self.layers:
401
+ if target_embedding is not None:
402
+ queries += target_embedding
403
+
404
+ queries, keys, attention_outputs = layer(
405
+ queries=queries,
406
+ keys=keys,
407
+ query_point_embedding=point_embeddings,
408
+ key_point_embedding=image_positional_embeddings,
409
+ attention_similarity=attention_similarity,
410
+ output_attentions=output_attentions,
411
+ )
412
+
413
+ if output_attentions:
414
+ all_attentions = all_attentions + (attention_outputs,)
415
+
416
+ # Apply the final attenion layer from the points to the image
417
+ query = queries + point_embeddings
418
+ key = keys + image_positional_embeddings
419
+
420
+ attn_out = self.final_attn_token_to_image(query=query, key=key, value=keys)
421
+
422
+ queries = queries + attn_out
423
+ queries = self.layer_norm_final_attn(queries)
424
+ return queries, keys, all_attentions
425
+
426
+
427
+ class SamFeedForward(nn.Module):
428
+ def __init__(
429
+ self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int, sigmoid_output: bool = False
430
+ ):
431
+ super().__init__()
432
+ self.num_layers = num_layers
433
+ self.activation = nn.ReLU()
434
+ self.proj_in = nn.Linear(input_dim, hidden_dim)
435
+ self.proj_out = nn.Linear(hidden_dim, output_dim)
436
+ self.layers = nn.ModuleList([nn.Linear(hidden_dim, hidden_dim) for _ in range(num_layers - 2)])
437
+ self.sigmoid_output = sigmoid_output
438
+
439
+ def forward(self, hidden_states):
440
+ hidden_states = self.proj_in(hidden_states)
441
+ hidden_states = self.activation(hidden_states)
442
+ for layer in self.layers:
443
+ hidden_states = self.activation(layer(hidden_states))
444
+
445
+ hidden_states = self.proj_out(hidden_states)
446
+ if self.sigmoid_output:
447
+ hidden_states = F.sigmoid(hidden_states)
448
+ return hidden_states
449
+
450
+
451
+ class SamMaskDecoderHQ(nn.Module):
452
+ def __init__(self, config: SamMaskDecoderConfig):
453
+ super().__init__()
454
+
455
+ self.hidden_size = config.hidden_size
456
+ self.vision_encoder_dim = config.vision_encoder_dim
457
+
458
+ self.num_multimask_outputs = config.num_multimask_outputs
459
+ self.num_mask_tokens = config.num_multimask_outputs + 1
460
+
461
+ self.iou_token = nn.Embedding(1, self.hidden_size)
462
+ self.mask_tokens = nn.Embedding(self.num_mask_tokens, self.hidden_size)
463
+
464
+ self.transformer = SamTwoWayTransformer(config)
465
+
466
+ # should we create a new class for this?
467
+ self.upscale_conv1 = nn.ConvTranspose2d(
468
+ self.hidden_size, self.hidden_size // 4, kernel_size=2, stride=2
469
+ )
470
+ self.upscale_conv2 = nn.ConvTranspose2d(
471
+ self.hidden_size // 4, self.hidden_size // 8, kernel_size=2, stride=2
472
+ )
473
+ self.upscale_layer_norm = SamLayerNorm(self.hidden_size // 4, data_format="channels_first")
474
+ self.activation = nn.GELU()
475
+
476
+ mlps_list = []
477
+ for _ in range(self.num_mask_tokens):
478
+ mlps_list += [SamFeedForward(self.hidden_size, self.hidden_size, self.hidden_size // 8, 3)]
479
+ self.output_hypernetworks_mlps = nn.ModuleList(mlps_list)
480
+
481
+ self.iou_prediction_head = SamFeedForward(
482
+ self.hidden_size, config.iou_head_hidden_dim, self.num_mask_tokens, config.iou_head_depth
483
+ )
484
+
485
+ # HQ-SAM parameters
486
+ self.hf_token = nn.Embedding(1, self.hidden_size) # HQ-Ouptput-Token
487
+ self.hf_mlp = SamFeedForward(
488
+ self.hidden_size, self.hidden_size, self.hidden_size // 8, 3
489
+ ) # corresponding new MLP layer for HQ-Ouptput-Token
490
+ self.num_mask_tokens = self.num_mask_tokens + 1
491
+
492
+ # three conv fusion layers for obtaining HQ-Feature
493
+ self.compress_vit_feat = nn.Sequential(
494
+ nn.ConvTranspose2d(self.vision_encoder_dim, self.hidden_size, kernel_size=2, stride=2),
495
+ SamLayerNorm(self.hidden_size, data_format="channels_first"),
496
+ nn.GELU(),
497
+ nn.ConvTranspose2d(self.hidden_size, self.hidden_size // 8, kernel_size=2, stride=2),
498
+ )
499
+
500
+ self.embedding_encoder = nn.Sequential(
501
+ nn.ConvTranspose2d(self.hidden_size, self.hidden_size // 4, kernel_size=2, stride=2),
502
+ SamLayerNorm(self.hidden_size // 4, data_format="channels_first"),
503
+ nn.GELU(),
504
+ nn.ConvTranspose2d(self.hidden_size // 4, self.hidden_size // 8, kernel_size=2, stride=2),
505
+ )
506
+ self.embedding_maskfeature = nn.Sequential(
507
+ nn.Conv2d(self.hidden_size // 8, self.hidden_size // 4, 3, 1, 1),
508
+ SamLayerNorm(self.hidden_size // 4, data_format="channels_first"),
509
+ nn.GELU(),
510
+ nn.Conv2d(self.hidden_size // 4, self.hidden_size // 8, 3, 1, 1),
511
+ )
512
+
513
+ def forward(
514
+ self,
515
+ image_embeddings: torch.Tensor,
516
+ image_positional_embeddings: torch.Tensor,
517
+ sparse_prompt_embeddings: torch.Tensor,
518
+ dense_prompt_embeddings: torch.Tensor,
519
+ multimask_output: bool,
520
+ intermediate_vision_embeddings: torch.Tensor,
521
+ hq_token_only: bool = False,
522
+ output_attentions: Optional[bool] = None,
523
+ attention_similarity: torch.Tensor = None,
524
+ target_embedding: torch.Tensor = None,
525
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
526
+ """
527
+ Predict masks given image and prompt embeddings.
528
+
529
+ Args:
530
+ image_embeddings (`torch.Tensor`):
531
+ the embeddings from the image encoder
532
+ image_positional_embedding (`torch.Tensor`):
533
+ positional encoding with the shape of image_embeddings
534
+ sparse_prompt_embeddings (`torch.Tensor`):
535
+ The embeddings of the points and boxes
536
+ dense_prompt_embeddings (`torch.Tensor`):
537
+ the embeddings of the mask inputs
538
+ multimask_output (bool):
539
+ Whether to return multiple masks or a single mask.
540
+ output_attentions (bool, *optional*):
541
+ Whether or not to return the attentions tensors of all attention layers.
542
+ """
543
+ batch_size, num_channels, height, width = image_embeddings.shape
544
+ point_batch_size = sparse_prompt_embeddings.shape[1]
545
+
546
+ vit_inter_features = intermediate_vision_embeddings[0].permute(
547
+ 0, 3, 1, 2
548
+ ) # early-layer ViT feature, after 1st global attention block in ViT
549
+ hq_features = self.embedding_encoder(image_embeddings) + self.compress_vit_feat(vit_inter_features)
550
+
551
+ # Concatenate output tokens
552
+ output_tokens = torch.cat(
553
+ [self.iou_token.weight, self.mask_tokens.weight, self.hf_token.weight], dim=0
554
+ )
555
+ output_tokens = output_tokens.repeat(batch_size, point_batch_size, 1, 1)
556
+
557
+ if sparse_prompt_embeddings.sum().item() != 0:
558
+ tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=2)
559
+ else:
560
+ tokens = output_tokens
561
+ point_embeddings = tokens.to(self.iou_token.weight.dtype)
562
+
563
+ # Expand per-image data in batch direction to be per-point
564
+ image_embeddings = image_embeddings + dense_prompt_embeddings
565
+ image_embeddings = image_embeddings.repeat_interleave(point_batch_size, 0)
566
+ image_positional_embeddings = image_positional_embeddings.repeat_interleave(point_batch_size, 0)
567
+
568
+ # Run the transformer, image_positional_embedding are consumed
569
+ point_embedding, image_embeddings, attentions = self.transformer(
570
+ point_embeddings=point_embeddings,
571
+ image_embeddings=image_embeddings,
572
+ image_positional_embeddings=image_positional_embeddings,
573
+ attention_similarity=attention_similarity,
574
+ target_embedding=target_embedding,
575
+ output_attentions=output_attentions,
576
+ )
577
+ iou_token_out = point_embedding[:, :, 0, :]
578
+ mask_tokens_out = point_embedding[:, :, 1 : (1 + self.num_mask_tokens), :]
579
+
580
+ # Upscale mask embeddings and predict masks using the mask tokens
581
+ image_embeddings = image_embeddings.transpose(2, 3).reshape(
582
+ batch_size * point_batch_size, num_channels, height, width
583
+ )
584
+
585
+ upscaled_embedding_sam = self.upscale_conv1(image_embeddings)
586
+ upscaled_embedding_sam = self.activation(self.upscale_layer_norm(upscaled_embedding_sam))
587
+ upscaled_embedding_sam = self.activation(self.upscale_conv2(upscaled_embedding_sam))
588
+
589
+ upscaled_embedding_hq = self.embedding_maskfeature(upscaled_embedding_sam) + hq_features.repeat(
590
+ batch_size * point_batch_size, 1, 1, 1
591
+ )
592
+
593
+ hyper_in_list = []
594
+ for i in range(self.num_mask_tokens):
595
+ mask_out_embedding = mask_tokens_out[:, :, i, :]
596
+ if i < self.num_mask_tokens - 1:
597
+ hyper = self.output_hypernetworks_mlps[i](mask_out_embedding)
598
+ else:
599
+ hyper = self.hf_mlp(mask_out_embedding)
600
+ hyper_in_list.append(hyper)
601
+ hyper_in = torch.stack(hyper_in_list, dim=2)
602
+
603
+ _, num_channels, height, width = upscaled_embedding_sam.shape
604
+ upscaled_embedding_sam = upscaled_embedding_sam.reshape(
605
+ batch_size, point_batch_size, num_channels, height * width
606
+ )
607
+ upscaled_embedding_hq = upscaled_embedding_hq.reshape(
608
+ batch_size, point_batch_size, num_channels, height * width
609
+ )
610
+
611
+ masks_sam = (hyper_in[:, :, : self.num_mask_tokens - 1] @ upscaled_embedding_sam).reshape(
612
+ batch_size, point_batch_size, -1, height, width
613
+ )
614
+ masks_hq = (hyper_in[:, :, self.num_mask_tokens - 1 :] @ upscaled_embedding_hq).reshape(
615
+ batch_size, point_batch_size, 1, height, width
616
+ )
617
+ masks = torch.cat([masks_sam, masks_hq], dim=2)
618
+
619
+ # Generate mask quality predictions
620
+ iou_pred = self.iou_prediction_head(iou_token_out)
621
+
622
+ # Select the correct mask or masks for output
623
+ if multimask_output:
624
+ # mask with highest score
625
+ mask_slice = slice(1, self.num_mask_tokens - 1)
626
+ iou_pred = iou_pred[:, :, mask_slice]
627
+ iou_pred, max_iou_idx = torch.max(iou_pred, dim=2)
628
+ masks_multi = masks[:, :, mask_slice, :, :]
629
+ masks_sam = masks_multi[
630
+ torch.arange(batch_size)[:, None, None],
631
+ torch.arange(point_batch_size)[None, :, None],
632
+ max_iou_idx,
633
+ :,
634
+ :,
635
+ ]
636
+ else:
637
+ # single mask output, default
638
+ mask_slice = slice(0, 1)
639
+ iou_pred = iou_pred[:, :, mask_slice]
640
+ masks_sam = masks[:, :, mask_slice, :, :]
641
+ # masks = masks[:, :, mask_slice, :, :]
642
+ # iou_pred = iou_pred[:, :, mask_slice]
643
+ if hq_token_only:
644
+ masks = masks_hq
645
+ else:
646
+ masks = masks_sam + masks_hq
647
+
648
+ outputs = (masks, iou_pred)
649
+
650
+ if output_attentions:
651
+ outputs = outputs + (attentions,)
652
+ else:
653
+ outputs = outputs + (None,)
654
+
655
+ return outputs
656
+
657
+
658
+ class SamPositionalEmbedding(nn.Module):
659
+ def __init__(self, config):
660
+ super().__init__()
661
+ self.scale = config.hidden_size // 2
662
+ self.register_buffer("positional_embedding", self.scale * torch.randn((2, config.num_pos_feats)))
663
+
664
+ def forward(self, input_coords, input_shape=None):
665
+ """Positionally encode points that are normalized to [0,1]."""
666
+ coordinates = input_coords.clone()
667
+
668
+ if input_shape is not None:
669
+ coordinates[:, :, :, 0] = coordinates[:, :, :, 0] / input_shape[1]
670
+ coordinates[:, :, :, 1] = coordinates[:, :, :, 1] / input_shape[0]
671
+
672
+ # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape
673
+ coordinates = 2 * coordinates - 1
674
+ coordinates = coordinates.to(self.positional_embedding.dtype)
675
+ coordinates = coordinates @ self.positional_embedding
676
+ coordinates = 2 * np.pi * coordinates
677
+ # outputs d_1 x ... x d_n x channel shape
678
+ return torch.cat([torch.sin(coordinates), torch.cos(coordinates)], dim=-1)
679
+
680
+
681
+ class SamMaskEmbedding(nn.Module):
682
+ def __init__(self, config: SamPromptEncoderConfig):
683
+ super().__init__()
684
+ self.mask_input_channels = config.mask_input_channels // 4
685
+ self.activation = ACT2FN[config.hidden_act]
686
+ self.conv1 = nn.Conv2d(1, self.mask_input_channels, kernel_size=2, stride=2)
687
+ self.conv2 = nn.Conv2d(self.mask_input_channels, config.mask_input_channels, kernel_size=2, stride=2)
688
+ self.conv3 = nn.Conv2d(config.mask_input_channels, config.hidden_size, kernel_size=1)
689
+ self.layer_norm1 = SamLayerNorm(
690
+ self.mask_input_channels, eps=config.layer_norm_eps, data_format="channels_first"
691
+ )
692
+ self.layer_norm2 = SamLayerNorm(
693
+ self.mask_input_channels * 4, eps=config.layer_norm_eps, data_format="channels_first"
694
+ )
695
+
696
+ def forward(self, masks):
697
+ hidden_states = self.conv1(masks)
698
+ hidden_states = self.layer_norm1(hidden_states)
699
+ hidden_states = self.activation(hidden_states)
700
+
701
+ hidden_states = self.conv2(hidden_states)
702
+ hidden_states = self.layer_norm2(hidden_states)
703
+ hidden_states = self.activation(hidden_states)
704
+ dense_embeddings = self.conv3(hidden_states)
705
+ return dense_embeddings
706
+
707
+
708
+ class SamPromptEncoder(nn.Module):
709
+ def __init__(self, config: SamPromptEncoderConfig, shared_patch_embedding):
710
+ super().__init__()
711
+ self.shared_embedding = shared_patch_embedding
712
+ self.mask_embed = SamMaskEmbedding(config)
713
+ self.no_mask_embed = nn.Embedding(1, config.hidden_size)
714
+
715
+ self.image_embedding_size = (config.image_embedding_size, config.image_embedding_size)
716
+ self.input_image_size = config.image_size
717
+
718
+ self.point_embed = nn.ModuleList(
719
+ [nn.Embedding(1, config.hidden_size) for i in range(config.num_point_embeddings)]
720
+ )
721
+ self.hidden_size = config.hidden_size
722
+ self.not_a_point_embed = nn.Embedding(1, config.hidden_size)
723
+
724
+ def _embed_points(self, points: torch.Tensor, labels: torch.Tensor, pad: bool) -> torch.Tensor:
725
+ """Embeds point prompts."""
726
+ points = points + 0.5 # Shift to center of pixel
727
+ if pad:
728
+ target_point_shape = (points.shape[0], points.shape[1], 1, points.shape[-1])
729
+ target_labels_shape = (points.shape[0], points.shape[1], 1)
730
+ padding_point = torch.zeros(target_point_shape, device=points.device)
731
+ padding_label = -torch.ones(target_labels_shape, device=labels.device)
732
+ points = torch.cat([points, padding_point], dim=2)
733
+ labels = torch.cat([labels, padding_label], dim=2)
734
+ input_shape = (self.input_image_size, self.input_image_size)
735
+ point_embedding = self.shared_embedding(points, input_shape)
736
+
737
+ # torch.where and expanding the labels tensor is required by the ONNX export
738
+ point_embedding = torch.where(labels[..., None] == -1, self.not_a_point_embed.weight, point_embedding)
739
+
740
+ # This is required for the ONNX export. The dtype, device need to be explicitely
741
+ # specificed as otherwise torch.onnx.export interprets as double
742
+ point_embedding = torch.where(
743
+ labels[..., None] != -10,
744
+ point_embedding,
745
+ torch.tensor(0.0, dtype=point_embedding.dtype, device=point_embedding.device),
746
+ )
747
+
748
+ point_embedding = torch.where(
749
+ (labels == 0)[:, :, :, None],
750
+ point_embedding + self.point_embed[0].weight[None, None, :, :],
751
+ point_embedding,
752
+ )
753
+
754
+ point_embedding = torch.where(
755
+ (labels == 1)[:, :, :, None],
756
+ point_embedding + self.point_embed[1].weight[None, None, :, :],
757
+ point_embedding,
758
+ )
759
+
760
+ return point_embedding
761
+
762
+ def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor:
763
+ """Embeds box prompts."""
764
+ boxes = boxes + 0.5 # Shift to center of pixel
765
+ batch_size, nb_boxes = boxes.shape[:2]
766
+ coords = boxes.reshape(batch_size, nb_boxes, 2, 2)
767
+ input_shape = (self.input_image_size, self.input_image_size)
768
+ corner_embedding = self.shared_embedding(coords, input_shape)
769
+ corner_embedding[:, :, 0, :] += self.point_embed[2].weight
770
+ corner_embedding[:, :, 1, :] += self.point_embed[3].weight
771
+ return corner_embedding
772
+
773
+ def forward(
774
+ self,
775
+ input_points: Optional[Tuple[torch.Tensor, torch.Tensor]],
776
+ input_labels: Optional[torch.Tensor],
777
+ input_boxes: Optional[torch.Tensor],
778
+ input_masks: Optional[torch.Tensor],
779
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
780
+ """
781
+ Embeds different types of prompts, returning both sparse and dense embeddings.
782
+
783
+ Args:
784
+ points (`torch.Tensor`, *optional*):
785
+ point coordinates and labels to embed.
786
+ boxes (`torch.Tensor`, *optional*):
787
+ boxes to embed
788
+ masks (`torch.Tensor`, *optional*):
789
+ masks to embed
790
+ """
791
+ sparse_embeddings = None
792
+ batch_size = 1
793
+ target_device = self.shared_embedding.positional_embedding.device
794
+ if input_points is not None:
795
+ batch_size, point_batch_size = input_points.shape[:2]
796
+ if input_labels is None:
797
+ raise ValueError("If points are provided, labels must also be provided.")
798
+ point_embeddings = self._embed_points(input_points, input_labels, pad=(input_boxes is None))
799
+ sparse_embeddings = point_embeddings
800
+ if input_boxes is not None:
801
+ batch_size = input_boxes.shape[0]
802
+ box_embeddings = self._embed_boxes(input_boxes)
803
+ if sparse_embeddings is None:
804
+ sparse_embeddings = box_embeddings
805
+ else:
806
+ sparse_embeddings = torch.cat([sparse_embeddings, box_embeddings], dim=2)
807
+ if input_masks is not None:
808
+ dense_embeddings = self.mask_embed(input_masks)
809
+ else:
810
+ dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1, 1).expand(
811
+ batch_size, -1, self.image_embedding_size[0], self.image_embedding_size[1]
812
+ )
813
+
814
+ if sparse_embeddings is None:
815
+ sparse_embeddings = torch.zeros((batch_size, 1, 1, self.hidden_size), device=target_device)
816
+
817
+ return sparse_embeddings, dense_embeddings
818
+
819
+
820
+ class SamVisionAttention(nn.Module):
821
+ """Multi-head Attention block with relative position embeddings."""
822
+
823
+ def __init__(self, config, window_size):
824
+ super().__init__()
825
+ input_size = (
826
+ (config.image_size // config.patch_size, config.image_size // config.patch_size)
827
+ if window_size == 0
828
+ else (window_size, window_size)
829
+ )
830
+
831
+ self.num_attention_heads = config.num_attention_heads
832
+ head_dim = config.hidden_size // config.num_attention_heads
833
+ self.scale = head_dim**-0.5
834
+ self.dropout = config.attention_dropout
835
+
836
+ self.qkv = nn.Linear(config.hidden_size, config.hidden_size * 3, bias=config.qkv_bias)
837
+ self.proj = nn.Linear(config.hidden_size, config.hidden_size)
838
+
839
+ self.use_rel_pos = config.use_rel_pos
840
+ if self.use_rel_pos:
841
+ if input_size is None:
842
+ raise ValueError("Input size must be provided if using relative positional encoding.")
843
+
844
+ # initialize relative positional embeddings
845
+ self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim))
846
+ self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim))
847
+
848
+ def get_rel_pos(self, q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor:
849
+ """
850
+ Get relative positional embeddings according to the relative positions of
851
+ query and key sizes.
852
+
853
+ Args:
854
+ q_size (int):
855
+ size of the query.
856
+ k_size (int):
857
+ size of key k.
858
+ rel_pos (`torch.Tensor`):
859
+ relative position embeddings (L, channel).
860
+
861
+ Returns:
862
+ Extracted positional embeddings according to relative positions.
863
+ """
864
+ max_rel_dist = int(2 * max(q_size, k_size) - 1)
865
+ # Interpolate rel pos.
866
+ rel_pos_resized = F.interpolate(
867
+ rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1),
868
+ size=max_rel_dist,
869
+ mode="linear",
870
+ )
871
+ rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0)
872
+
873
+ # Scale the coords with short length if shapes for q and k are different.
874
+ q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0)
875
+ k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0)
876
+ relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0)
877
+
878
+ return rel_pos_resized[relative_coords.long()]
879
+
880
+ def add_decomposed_rel_pos(
881
+ self,
882
+ attn: torch.Tensor,
883
+ query: torch.Tensor,
884
+ rel_pos_h: torch.Tensor,
885
+ rel_pos_w: torch.Tensor,
886
+ q_size: Tuple[int, int],
887
+ k_size: Tuple[int, int],
888
+ ) -> torch.Tensor:
889
+ """
890
+ Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`.
891
+ https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py
892
+
893
+ Args:
894
+ attn (`torch.Tensor`):
895
+ attention map.
896
+ query (`torch.Tensor`):
897
+ query q in the attention layer with shape (batch_size, query_height * query_width, channel).
898
+ rel_pos_h (`torch.Tensor`):
899
+ relative position embeddings (Lh, channel) for height axis.
900
+ rel_pos_w (`torch.Tensor`):
901
+ relative position embeddings (Lw, channel) for width axis.
902
+ q_size (tuple):
903
+ spatial sequence size of query q with (query_height, query_width).
904
+ k_size (tuple):
905
+ spatial sequence size of key k with (key_height, key_width).
906
+
907
+ Returns:
908
+ attn (`torch.Tensor`):
909
+ attention map with added relative positional embeddings.
910
+ """
911
+ query_height, query_width = q_size
912
+ key_height, key_width = k_size
913
+ relative_position_height = self.get_rel_pos(query_height, key_height, rel_pos_h)
914
+ relative_position_width = self.get_rel_pos(query_width, key_width, rel_pos_w)
915
+
916
+ batch_size, _, dim = query.shape
917
+ reshaped_query = query.reshape(batch_size, query_height, query_width, dim)
918
+ rel_h = torch.einsum("bhwc,hkc->bhwk", reshaped_query, relative_position_height)
919
+ rel_w = torch.einsum("bhwc,wkc->bhwk", reshaped_query, relative_position_width)
920
+ attn = attn.reshape(batch_size, query_height, query_width, key_height, key_width)
921
+ attn = attn + rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :]
922
+ attn = attn.reshape(batch_size, query_height * query_width, key_height * key_width)
923
+ return attn
924
+
925
+ def forward(self, hidden_states: torch.Tensor, output_attentions=False) -> torch.Tensor:
926
+ batch_size, height, width, _ = hidden_states.shape
927
+ # qkv with shape (3, batch_size, nHead, height * width, channel)
928
+ qkv = (
929
+ self.qkv(hidden_states)
930
+ .reshape(batch_size, height * width, 3, self.num_attention_heads, -1)
931
+ .permute(2, 0, 3, 1, 4)
932
+ )
933
+ # q, k, v with shape (batch_size * nHead, height * width, channel)
934
+ query, key, value = qkv.reshape(3, batch_size * self.num_attention_heads, height * width, -1).unbind(
935
+ 0
936
+ )
937
+
938
+ attn_weights = (query * self.scale) @ key.transpose(-2, -1)
939
+
940
+ if self.use_rel_pos:
941
+ attn_weights = self.add_decomposed_rel_pos(
942
+ attn_weights, query, self.rel_pos_h, self.rel_pos_w, (height, width), (height, width)
943
+ )
944
+
945
+ attn_weights = torch.nn.functional.softmax(attn_weights, dtype=torch.float32, dim=-1).to(query.dtype)
946
+
947
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
948
+
949
+ attn_output = (attn_probs @ value).reshape(batch_size, self.num_attention_heads, height, width, -1)
950
+ attn_output = attn_output.permute(0, 2, 3, 1, 4).reshape(batch_size, height, width, -1)
951
+
952
+ attn_output = self.proj(attn_output)
953
+
954
+ if output_attentions:
955
+ outputs = (attn_output, attn_weights)
956
+ else:
957
+ outputs = (attn_output, None)
958
+
959
+ return outputs
960
+
961
+
962
+ class SamVisionLayer(nn.Module):
963
+ def __init__(self, config, window_size):
964
+ super().__init__()
965
+ self.layer_norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
966
+ self.attn = SamVisionAttention(config, window_size)
967
+ self.layer_norm2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
968
+ self.mlp = SamMLPBlock(config)
969
+ self.window_size = window_size
970
+
971
+ def window_partition(
972
+ self, hidden_states: torch.Tensor, window_size: int
973
+ ) -> Tuple[torch.Tensor, Tuple[int, int]]:
974
+ """
975
+ Args:
976
+ Partition into non-overlapping windows with padding if needed.
977
+ hidden_states (tensor): input tokens with [batch_size, height, width, channel]. window_size (int): window
978
+ size.
979
+
980
+ Returns:
981
+ windows: windows after partition with [batch_size * num_windows, window_size, window_size, channel].
982
+ (pad_height, pad_width): padded height and width before partition
983
+ """
984
+ batch_size, height, width, channel = hidden_states.shape
985
+
986
+ pad_h = (window_size - height % window_size) % window_size
987
+ pad_w = (window_size - width % window_size) % window_size
988
+ hidden_states = F.pad(hidden_states, (0, 0, 0, pad_w, 0, pad_h))
989
+ pad_height, pad_width = height + pad_h, width + pad_w
990
+
991
+ hidden_states = hidden_states.reshape(
992
+ batch_size, pad_height // window_size, window_size, pad_width // window_size, window_size, channel
993
+ )
994
+ windows = (
995
+ hidden_states.permute(0, 1, 3, 2, 4, 5)
996
+ .contiguous()
997
+ .reshape(-1, window_size, window_size, channel)
998
+ )
999
+ return windows, (pad_height, pad_width)
1000
+
1001
+ def window_unpartition(
1002
+ self,
1003
+ windows: torch.Tensor,
1004
+ window_size: int,
1005
+ padding_shape: Tuple[int, int],
1006
+ original_shape: Tuple[int, int],
1007
+ ) -> torch.Tensor:
1008
+ """
1009
+ Args:
1010
+ Window unpartition into original sequences and removing padding.
1011
+ hidden_states (tensor):
1012
+ input tokens with [batch_size * num_windows, window_size, window_size, channel].
1013
+ window_size (int):
1014
+ window size.
1015
+ padding_shape (Tuple):
1016
+ padded height and width (pad_height, pad_width).
1017
+ original_shape (Tuple): original height and width (height, width) before padding.
1018
+
1019
+ Returns:
1020
+ hidden_states: unpartitioned sequences with [batch_size, height, width, channel].
1021
+ """
1022
+ pad_height, pad_width = padding_shape
1023
+ height, width = original_shape
1024
+ batch_size = windows.shape[0] // (pad_height * pad_width // window_size // window_size)
1025
+ hidden_states = windows.reshape(
1026
+ batch_size, pad_height // window_size, pad_width // window_size, window_size, window_size, -1
1027
+ )
1028
+ hidden_states = (
1029
+ hidden_states.permute(0, 1, 3, 2, 4, 5)
1030
+ .contiguous()
1031
+ .reshape(batch_size, pad_height, pad_width, -1)
1032
+ )
1033
+
1034
+ hidden_states = hidden_states[:, :height, :width, :].contiguous()
1035
+ return hidden_states
1036
+
1037
+ def forward(
1038
+ self,
1039
+ hidden_states: torch.Tensor,
1040
+ output_attentions: Optional[bool] = False,
1041
+ ) -> Tuple[torch.FloatTensor]:
1042
+ residual = hidden_states
1043
+
1044
+ hidden_states = self.layer_norm1(hidden_states)
1045
+ # Window partition
1046
+ if self.window_size > 0:
1047
+ height, width = hidden_states.shape[1], hidden_states.shape[2]
1048
+ hidden_states, padding_shape = self.window_partition(hidden_states, self.window_size)
1049
+
1050
+ hidden_states, attn_weights = self.attn(
1051
+ hidden_states=hidden_states,
1052
+ output_attentions=output_attentions,
1053
+ )
1054
+ # Reverse window partition
1055
+ if self.window_size > 0:
1056
+ hidden_states = self.window_unpartition(
1057
+ hidden_states, self.window_size, padding_shape, (height, width)
1058
+ )
1059
+
1060
+ hidden_states = residual + hidden_states
1061
+ layernorm_output = self.layer_norm2(hidden_states)
1062
+ hidden_states = hidden_states + self.mlp(layernorm_output)
1063
+
1064
+ outputs = (hidden_states,)
1065
+ if output_attentions:
1066
+ outputs += (attn_weights,)
1067
+
1068
+ return outputs
1069
+
1070
+
1071
+ class SamVisionNeck(nn.Module):
1072
+ def __init__(self, config: SamVisionConfig):
1073
+ super().__init__()
1074
+ self.config = config
1075
+
1076
+ self.conv1 = nn.Conv2d(config.hidden_size, config.output_channels, kernel_size=1, bias=False)
1077
+ self.layer_norm1 = SamLayerNorm(config.output_channels, data_format="channels_first")
1078
+ self.conv2 = nn.Conv2d(
1079
+ config.output_channels, config.output_channels, kernel_size=3, padding=1, bias=False
1080
+ )
1081
+ self.layer_norm2 = SamLayerNorm(config.output_channels, data_format="channels_first")
1082
+
1083
+ def forward(self, hidden_states):
1084
+ hidden_states = hidden_states.permute(0, 3, 1, 2)
1085
+ hidden_states = self.conv1(hidden_states)
1086
+ hidden_states = self.layer_norm1(hidden_states)
1087
+
1088
+ hidden_states = self.conv2(hidden_states)
1089
+ hidden_states = self.layer_norm2(hidden_states)
1090
+ return hidden_states
1091
+
1092
+
1093
+ class SamVisionEncoder(nn.Module):
1094
+ def __init__(self, config: SamVisionConfig):
1095
+ super().__init__()
1096
+ self.config = config
1097
+ self.image_size = config.image_size
1098
+
1099
+ self.patch_embed = SamPatchEmbeddings(config)
1100
+
1101
+ self.pos_embed = None
1102
+ if config.use_abs_pos:
1103
+ # Initialize absolute positional embedding with pretrain image size.
1104
+ self.pos_embed = nn.Parameter(
1105
+ torch.zeros(
1106
+ 1,
1107
+ config.image_size // config.patch_size,
1108
+ config.image_size // config.patch_size,
1109
+ config.hidden_size,
1110
+ )
1111
+ )
1112
+
1113
+ self.layers = nn.ModuleList()
1114
+ for i in range(config.num_hidden_layers):
1115
+ layer = SamVisionLayer(
1116
+ config,
1117
+ window_size=config.window_size if i not in config.global_attn_indexes else 0,
1118
+ )
1119
+ self.layers.append(layer)
1120
+
1121
+ self.neck = SamVisionNeck(config)
1122
+
1123
+ self.gradient_checkpointing = False
1124
+
1125
+ def get_input_embeddings(self):
1126
+ return self.patch_embed
1127
+
1128
+ def forward(
1129
+ self,
1130
+ pixel_values: Optional[torch.FloatTensor] = None,
1131
+ output_attentions: Optional[bool] = None,
1132
+ output_hidden_states: Optional[bool] = None,
1133
+ return_dict: Optional[bool] = None,
1134
+ ) -> Union[Tuple, SamVisionEncoderOutput]:
1135
+ output_attentions = (
1136
+ output_attentions if output_attentions is not None else self.config.output_attentions
1137
+ )
1138
+ output_hidden_states = (
1139
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1140
+ )
1141
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1142
+
1143
+ if pixel_values is None:
1144
+ raise ValueError("You have to specify pixel_values")
1145
+
1146
+ hidden_states = self.patch_embed(pixel_values)
1147
+ if self.pos_embed is not None:
1148
+ hidden_states = hidden_states + self.pos_embed
1149
+
1150
+ all_hidden_states = () if output_hidden_states else None
1151
+ all_self_attentions = () if output_attentions else None
1152
+
1153
+ for i, layer_module in enumerate(self.layers):
1154
+ if output_hidden_states:
1155
+ all_hidden_states = all_hidden_states + (hidden_states,)
1156
+
1157
+ if self.gradient_checkpointing and self.training:
1158
+ layer_outputs = self._gradient_checkpointing_func(
1159
+ layer_module.__call__,
1160
+ hidden_states,
1161
+ )
1162
+ else:
1163
+ layer_outputs = layer_module(hidden_states, output_attentions=output_attentions)
1164
+
1165
+ hidden_states = layer_outputs[0]
1166
+
1167
+ if output_attentions:
1168
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
1169
+
1170
+ if output_hidden_states:
1171
+ all_hidden_states = all_hidden_states + (hidden_states,)
1172
+
1173
+ hidden_states = self.neck(hidden_states)
1174
+
1175
+ if not return_dict:
1176
+ outputs = (hidden_states,)
1177
+ if output_hidden_states:
1178
+ outputs = outputs + (all_hidden_states,)
1179
+ if output_attentions:
1180
+ outputs = outputs + (all_self_attentions,)
1181
+ return outputs
1182
+
1183
+ return SamVisionEncoderOutput(
1184
+ last_hidden_state=hidden_states,
1185
+ hidden_states=all_hidden_states,
1186
+ attentions=all_self_attentions,
1187
+ )
1188
+
1189
+
1190
+ class SamHQConfig(SamConfig):
1191
+ model_type = "sam_hq"
1192
+
1193
+
1194
+ class SamHQPreTrainedModel(PreTrainedModel):
1195
+ config_class = SamHQConfig
1196
+ base_model_prefix = "sam_hq"
1197
+ main_input_name = "pixel_values"
1198
+ _no_split_modules = ["SamVisionAttention"]
1199
+
1200
+ def _init_weights(self, module):
1201
+ std = self.config.initializer_range
1202
+ if isinstance(module, (nn.Linear, nn.Conv2d, nn.ConvTranspose2d)):
1203
+ module.weight.data.normal_(mean=0.0, std=std)
1204
+ if module.bias is not None:
1205
+ module.bias.data.zero_()
1206
+ elif isinstance(module, nn.Embedding):
1207
+ module.weight.data.normal_(mean=0.0, std=std)
1208
+ if module.padding_idx is not None:
1209
+ module.weight.data[module.padding_idx].zero_()
1210
+
1211
+
1212
+ SAM_START_DOCSTRING = r"""
1213
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1214
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1215
+ etc.)
1216
+
1217
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1218
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1219
+ and behavior.
1220
+
1221
+ Parameters:
1222
+ config ([`SamConfig`]): Model configuration class with all the parameters of the model.
1223
+ Initializing with a config file does not load the weights associated with the model, only the
1224
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1225
+ """
1226
+
1227
+
1228
+ SAM_INPUTS_DOCSTRING = r"""
1229
+ Args:
1230
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
1231
+ Pixel values. Pixel values can be obtained using [`SamProcessor`]. See [`SamProcessor.__call__`] for
1232
+ details.
1233
+ input_points (`torch.FloatTensor` of shape `(batch_size, num_points, 2)`):
1234
+ Input 2D spatial points, this is used by the prompt encoder to encode the prompt. Generally yields to much
1235
+ better results. The points can be obtained by passing a list of list of list to the processor that will
1236
+ create corresponding `torch` tensors of dimension 4. The first dimension is the image batch size, the
1237
+ second dimension is the point batch size (i.e. how many segmentation masks do we want the model to predict
1238
+ per input point), the third dimension is the number of points per segmentation mask (it is possible to pass
1239
+ multiple points for a single mask), and the last dimension is the x (vertical) and y (horizontal)
1240
+ coordinates of the point. If a different number of points is passed either for each image, or for each
1241
+ mask, the processor will create "PAD" points that will correspond to the (0, 0) coordinate, and the
1242
+ computation of the embedding will be skipped for these points using the labels.
1243
+ input_labels (`torch.LongTensor` of shape `(batch_size, point_batch_size, num_points)`):
1244
+ Input labels for the points, this is used by the prompt encoder to encode the prompt. According to the
1245
+ official implementation, there are 3 types of labels
1246
+
1247
+ - `1`: the point is a point that contains the object of interest
1248
+ - `0`: the point is a point that does not contain the object of interest
1249
+ - `-1`: the point corresponds to the background
1250
+
1251
+ We added the label:
1252
+
1253
+ - `-10`: the point is a padding point, thus should be ignored by the prompt encoder
1254
+
1255
+ The padding labels should be automatically done by the processor.
1256
+ input_boxes (`torch.FloatTensor` of shape `(batch_size, num_boxes, 4)`):
1257
+ Input boxes for the points, this is used by the prompt encoder to encode the prompt. Generally yields to
1258
+ much better generated masks. The boxes can be obtained by passing a list of list of list to the processor,
1259
+ that will generate a `torch` tensor, with each dimension corresponding respectively to the image batch
1260
+ size, the number of boxes per image and the coordinates of the top left and botton right point of the box.
1261
+ In the order (`x1`, `y1`, `x2`, `y2`):
1262
+
1263
+ - `x1`: the x coordinate of the top left point of the input box
1264
+ - `y1`: the y coordinate of the top left point of the input box
1265
+ - `x2`: the x coordinate of the bottom right point of the input box
1266
+ - `y2`: the y coordinate of the bottom right point of the input box
1267
+
1268
+ input_masks (`torch.FloatTensor` of shape `(batch_size, image_size, image_size)`):
1269
+ SAM model also accepts segmentation masks as input. The mask will be embedded by the prompt encoder to
1270
+ generate a corresponding embedding, that will be fed later on to the mask decoder. These masks needs to be
1271
+ manually fed by the user, and they need to be of shape (`batch_size`, `image_size`, `image_size`).
1272
+
1273
+ image_embeddings (`torch.FloatTensor` of shape `(batch_size, output_channels, window_size, window_size)`):
1274
+ Image embeddings, this is used by the mask decder to generate masks and iou scores. For more memory
1275
+ efficient computation, users can first retrieve the image embeddings using the `get_image_embeddings`
1276
+ method, and then feed them to the `forward` method instead of feeding the `pixel_values`.
1277
+ multimask_output (`bool`, *optional*):
1278
+ In the original implementation and paper, the model always outputs 3 masks per image (or per point / per
1279
+ bounding box if relevant). However, it is possible to just output a single mask, that corresponds to the
1280
+ "best" mask, by specifying `multimask_output=False`.
1281
+ attention_similarity (`torch.FloatTensor`, *optional*):
1282
+ Attention similarity tensor, to be provided to the mask decoder for target-guided attention in case the
1283
+ model is used for personalization as introduced in [PerSAM](https://arxiv.org/abs/2305.03048).
1284
+ target_embedding (`torch.FloatTensor`, *optional*):
1285
+ Embedding of the target concept, to be provided to the mask decoder for target-semantic prompting in case
1286
+ the model is used for personalization as introduced in [PerSAM](https://arxiv.org/abs/2305.03048).
1287
+ output_attentions (`bool`, *optional*):
1288
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1289
+ tensors for more detail.
1290
+ output_hidden_states (`bool`, *optional*):
1291
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1292
+ more detail.
1293
+ return_dict (`bool`, *optional*):
1294
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1295
+ """
1296
+
1297
+
1298
+ @add_start_docstrings(
1299
+ "Segment Anything Model (SAM) for generating segmentation masks, given an input image and ",
1300
+ " optional 2D location and bounding boxes.",
1301
+ SAM_START_DOCSTRING,
1302
+ )
1303
+ class SamHQModel(SamHQPreTrainedModel):
1304
+ _tied_weights_keys = ["prompt_encoder.shared_embedding.positional_embedding"]
1305
+
1306
+ def __init__(self, config):
1307
+ super().__init__(config)
1308
+ self.shared_image_embedding = SamPositionalEmbedding(config.vision_config)
1309
+
1310
+ self.vision_encoder = SamVisionEncoder(config.vision_config)
1311
+ self.prompt_encoder = SamPromptEncoder(config.prompt_encoder_config, self.shared_image_embedding)
1312
+ if "vision_encoder_dim" not in config.mask_decoder_config.to_dict():
1313
+ config.mask_decoder_config.vision_encoder_dim = config.vision_config.hidden_size
1314
+ self.mask_decoder = SamMaskDecoderHQ(config.mask_decoder_config)
1315
+
1316
+ self.post_init()
1317
+
1318
+ def get_input_embeddings(self):
1319
+ return self.vision_encoder.get_input_embeddings()
1320
+
1321
+ def get_image_wide_positional_embeddings(self):
1322
+ size = self.config.prompt_encoder_config.image_embedding_size
1323
+ target_device = self.shared_image_embedding.positional_embedding.device
1324
+ target_dtype = self.shared_image_embedding.positional_embedding.dtype
1325
+ grid = torch.ones((size, size), device=target_device, dtype=target_dtype)
1326
+ y_embed = grid.cumsum(dim=0) - 0.5
1327
+ x_embed = grid.cumsum(dim=1) - 0.5
1328
+ y_embed = y_embed / size
1329
+ x_embed = x_embed / size
1330
+
1331
+ positional_embedding = self.shared_image_embedding(torch.stack([x_embed, y_embed], dim=-1))
1332
+ return positional_embedding.permute(2, 0, 1).unsqueeze(0) # channel x height x width
1333
+
1334
+ @torch.no_grad()
1335
+ def get_image_embeddings(
1336
+ self,
1337
+ pixel_values,
1338
+ output_attentions: Optional[bool] = None,
1339
+ output_hidden_states: Optional[bool] = None,
1340
+ return_dict: Optional[bool] = None,
1341
+ ):
1342
+ r"""
1343
+ Returns the image embeddings by passing the pixel values through the vision encoder.
1344
+
1345
+ Args:
1346
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
1347
+ Input pixel values
1348
+ output_attentions (`bool`, *optional*):
1349
+ Whether or not to return the attentions tensors of all attention layers.
1350
+ output_hidden_states (`bool`, *optional*):
1351
+ Whether or not to return the hidden states of all layers.
1352
+ return_dict (`bool`, *optional*):
1353
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1354
+
1355
+ """
1356
+ vision_output = self.vision_encoder(
1357
+ pixel_values,
1358
+ output_attentions=output_attentions,
1359
+ output_hidden_states=output_hidden_states,
1360
+ return_dict=return_dict,
1361
+ )
1362
+ image_embeddings = vision_output[0]
1363
+ return image_embeddings
1364
+
1365
+ @torch.no_grad()
1366
+ def get_prompt_embeddings(
1367
+ self,
1368
+ input_points: Optional[torch.FloatTensor] = None,
1369
+ input_labels: Optional[torch.LongTensor] = None,
1370
+ input_boxes: Optional[torch.FloatTensor] = None,
1371
+ input_masks: Optional[torch.LongTensor] = None,
1372
+ ):
1373
+ r"""
1374
+ Returns the prompt embeddings by passing the input points, labels, boxes and masks through the prompt encoder.
1375
+
1376
+ Args:
1377
+ input_points (`torch.FloatTensor` of shape `(batch_size, point_batch_size, num_points_per_image, 2)`):
1378
+ Optional input points for the prompt encoder. The padding of the point is automatically done by the
1379
+ processor. `point_batch_size` refers to the number of masks that we want the model to predict per
1380
+ point. The model will output `point_batch_size` times 3 masks in total.
1381
+ input_labels (`torch.LongTensor` of shape `(batch_size, point_batch_size, num_points_per_image)`):
1382
+ Optional input labels for the prompt encoder. The padding of the labels is automatically done by the
1383
+ processor, or can be fed by the user.
1384
+ input_boxes (`torch.FloatTensor` of shape `(batch_size, num_boxes_per_image, 4)`):
1385
+ Optional input boxes for the prompt encoder. The padding of the boxes is automatically done by the
1386
+ processor. users can also pass manually the input boxes.
1387
+ input_masks (`torch.LongTensor` of shape `(batch_size, image_size, image_size)`):
1388
+ Optional input masks for the prompt encoder.
1389
+ """
1390
+ prompt_output = self.prompt_encoder(
1391
+ input_points=input_points,
1392
+ input_labels=input_labels,
1393
+ input_boxes=input_boxes,
1394
+ input_masks=input_masks,
1395
+ )
1396
+ return prompt_output
1397
+
1398
+ @add_start_docstrings_to_model_forward(SAM_INPUTS_DOCSTRING)
1399
+ def forward(
1400
+ self,
1401
+ pixel_values: Optional[torch.FloatTensor] = None,
1402
+ input_points: Optional[torch.FloatTensor] = None,
1403
+ input_labels: Optional[torch.LongTensor] = None,
1404
+ input_boxes: Optional[torch.FloatTensor] = None,
1405
+ input_masks: Optional[torch.LongTensor] = None,
1406
+ image_embeddings: Optional[torch.FloatTensor] = None,
1407
+ multimask_output: bool = False,
1408
+ hq_token_only: bool = True,
1409
+ attention_similarity: Optional[torch.FloatTensor] = None,
1410
+ target_embedding: Optional[torch.FloatTensor] = None,
1411
+ output_attentions: Optional[bool] = None,
1412
+ output_hidden_states: Optional[bool] = None,
1413
+ return_dict: Optional[bool] = None,
1414
+ **kwargs,
1415
+ ) -> List[Dict[str, torch.Tensor]]:
1416
+ r"""
1417
+ Example:
1418
+
1419
+ ```python
1420
+ >>> from PIL import Image
1421
+ >>> import requests
1422
+ >>> from transformers import AutoModel, AutoProcessor
1423
+
1424
+ >>> model = AutoModel.from_pretrained("facebook/sam-vit-base")
1425
+ >>> processor = AutoProcessor.from_pretrained("facebook/sam-vit-base")
1426
+
1427
+ >>> img_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/sam-car.png"
1428
+ >>> raw_image = Image.open(requests.get(img_url, stream=True).raw).convert("RGB")
1429
+ >>> input_points = [[[400, 650]]] # 2D location of a window on the car
1430
+ >>> inputs = processor(images=raw_image, input_points=input_points, return_tensors="pt")
1431
+
1432
+ >>> # Get segmentation mask
1433
+ >>> outputs = model(**inputs)
1434
+
1435
+ >>> # Postprocess masks
1436
+ >>> masks = processor.post_process_masks(
1437
+ ... outputs.pred_masks, inputs["original_sizes"], inputs["reshaped_input_sizes"]
1438
+ ... )
1439
+ ```
1440
+ """
1441
+ output_attentions = (
1442
+ output_attentions if output_attentions is not None else self.config.output_attentions
1443
+ )
1444
+ output_hidden_states = (
1445
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1446
+ )
1447
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1448
+
1449
+ if pixel_values is None and image_embeddings is None:
1450
+ raise ValueError("Either pixel_values or image_embeddings must be provided.")
1451
+
1452
+ if pixel_values is not None and image_embeddings is not None:
1453
+ raise ValueError("Only one of pixel_values and image_embeddings can be provided.")
1454
+
1455
+ if input_points is not None and len(input_points.shape) != 4:
1456
+ raise ValueError(
1457
+ "The input_points must be a 4D tensor. Of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.",
1458
+ " got {}.".format(input_points.shape),
1459
+ )
1460
+ if input_boxes is not None and len(input_boxes.shape) != 3:
1461
+ raise ValueError(
1462
+ "The input_points must be a 3D tensor. Of shape `batch_size`, `nb_boxes`, `4`.",
1463
+ " got {}.".format(input_boxes.shape),
1464
+ )
1465
+ if input_points is not None and input_boxes is not None:
1466
+ point_batch_size = input_points.shape[1]
1467
+ box_batch_size = input_boxes.shape[1]
1468
+ if point_batch_size != box_batch_size:
1469
+ raise ValueError(
1470
+ "You should provide as many bounding boxes as input points per box. Got {} and {}.".format(
1471
+ point_batch_size, box_batch_size
1472
+ )
1473
+ )
1474
+
1475
+ image_positional_embeddings = self.get_image_wide_positional_embeddings()
1476
+ # repeat with batch size
1477
+ batch_size = pixel_values.shape[0] if pixel_values is not None else image_embeddings.shape[0]
1478
+ image_positional_embeddings = image_positional_embeddings.repeat(batch_size, 1, 1, 1)
1479
+
1480
+ vision_attentions = None
1481
+ vision_hidden_states = None
1482
+
1483
+ if pixel_values is not None:
1484
+ vision_outputs = self.vision_encoder(
1485
+ pixel_values,
1486
+ output_attentions=output_attentions,
1487
+ output_hidden_states=output_hidden_states,
1488
+ return_dict=return_dict,
1489
+ )
1490
+ image_embeddings = vision_outputs[0]
1491
+
1492
+ if output_hidden_states:
1493
+ vision_hidden_states = vision_outputs[1]
1494
+ if output_attentions:
1495
+ vision_attentions = vision_outputs[-1]
1496
+
1497
+ if input_points is not None and input_labels is None:
1498
+ input_labels = torch.ones_like(
1499
+ input_points[:, :, :, 0], dtype=torch.int, device=input_points.device
1500
+ )
1501
+
1502
+ if input_points is not None and image_embeddings.shape[0] != input_points.shape[0]:
1503
+ raise ValueError(
1504
+ "The batch size of the image embeddings and the input points must be the same. ",
1505
+ "Got {} and {} respectively.".format(image_embeddings.shape[0], input_points.shape[0]),
1506
+ " if you want to pass multiple points for the same image, make sure that you passed ",
1507
+ " input_points of shape (batch_size, point_batch_size, num_points_per_image, 3) and ",
1508
+ " input_labels of shape (batch_size, point_batch_size, num_points_per_image)",
1509
+ )
1510
+
1511
+ sparse_embeddings, dense_embeddings = self.prompt_encoder(
1512
+ input_points=input_points,
1513
+ input_labels=input_labels,
1514
+ input_boxes=input_boxes,
1515
+ input_masks=input_masks,
1516
+ )
1517
+
1518
+ low_res_masks, iou_predictions, mask_decoder_attentions = self.mask_decoder(
1519
+ image_embeddings=image_embeddings,
1520
+ image_positional_embeddings=image_positional_embeddings,
1521
+ sparse_prompt_embeddings=sparse_embeddings,
1522
+ dense_prompt_embeddings=dense_embeddings,
1523
+ multimask_output=multimask_output,
1524
+ intermediate_vision_embeddings=vision_hidden_states[1:],
1525
+ hq_token_only=hq_token_only,
1526
+ attention_similarity=attention_similarity,
1527
+ target_embedding=target_embedding,
1528
+ output_attentions=output_attentions,
1529
+ )
1530
+
1531
+ if not return_dict:
1532
+ output = (iou_predictions, low_res_masks)
1533
+ if output_hidden_states:
1534
+ output = output + (vision_hidden_states,)
1535
+
1536
+ if output_attentions:
1537
+ output = output + (vision_attentions, mask_decoder_attentions)
1538
+ return output
1539
+
1540
+ return SamImageSegmentationOutput(
1541
+ iou_scores=iou_predictions,
1542
+ pred_masks=low_res_masks,
1543
+ vision_hidden_states=vision_hidden_states,
1544
+ vision_attentions=vision_attentions,
1545
+ mask_decoder_attentions=mask_decoder_attentions,
1546
+ )
preprocessor_config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "do_convert_rgb": true,
3
+ "do_normalize": true,
4
+ "do_pad": true,
5
+ "do_rescale": true,
6
+ "do_resize": true,
7
+ "image_mean": [
8
+ 0.485,
9
+ 0.456,
10
+ 0.406
11
+ ],
12
+ "image_processor_type": "SamImageProcessor",
13
+ "image_std": [
14
+ 0.229,
15
+ 0.224,
16
+ 0.225
17
+ ],
18
+ "pad_size": {
19
+ "height": 1024,
20
+ "width": 1024
21
+ },
22
+ "processor_class": "SamProcessor",
23
+ "resample": 2,
24
+ "rescale_factor": 0.00392156862745098,
25
+ "size": {
26
+ "longest_edge": 1024
27
+ }
28
+ }