File size: 14,403 Bytes
7dbe662
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import os
import functools

import torch
from torch import nn
import torch.nn.functional as F

from huggingface_hub import hf_hub_download

from typing import Optional, List, Union, Tuple, Type

from segment_anything import build_sam
from segment_anything.mobile_encoder.tiny_vit_sam import TinyViT
from segment_anything.modeling import PromptEncoder, MaskDecoder, TwoWayTransformer
from segment_anything.modeling.image_encoder import ImageEncoderViT, LayerNorm2d, PatchEmbed, Block, Attention
from segment_anything.mobile_encoder.setup_mobile_sam import load_mobile_sam
from segment_anything.modeling.sam import Sam

from sam_extension.distillation_models.fastertinyvit import FasterTinyViT
from sam_extension.distillation_models.dino import DINO
# from sam_extension.distillation_models.flashvision_transformer import FlashVisionTransformer

SAM_REPO_ID = 'YouLiXiya/YL-SAM'
hf_sam_download = functools.partial(hf_hub_download, repo_id=SAM_REPO_ID, local_dir_use_symlinks=True)


class SAMImageEncoder(nn.Module):
    def __init__(self,
                 sam_checkpoint_path,
                 device='cuda'):
        super(SAMImageEncoder, self).__init__()
        sam = build_sam(sam_checkpoint_path).to(device)
        self.image_encoder = sam.image_encoder
        del sam
        torch.cuda.empty_cache()
    def forward(self, x):
        return self.image_encoder(x)



class MobileSAMImageEncoder(nn.Module):
    def __init__(self,
                 sam_checkpoint_path,
                 device='cuda'):
        super(MobileSAMImageEncoder, self).__init__()
        sam = load_mobile_sam(sam_checkpoint_path, device)
        self.image_encoder = sam.image_encoder
        del sam
        torch.cuda.empty_cache()
    def forward(self, x):
        return self.image_encoder(x)

class SAMEncoderViT(nn.Module):
    def __init__(
        self,
        img_size: int = 1024,
        patch_size: int = 16,
        in_chans: int = 3,
        embed_dim: int = 768,
        depth: int = 12,
        num_heads: int = 12,
        mlp_ratio: float = 4.0,
        out_chans: int = 256,
        qkv_bias: bool = True,
        norm_layer: Type[nn.Module] = nn.LayerNorm,
        act_layer: Type[nn.Module] = nn.GELU,
        use_abs_pos: bool = True,
        use_rel_pos: bool = False,
        rel_pos_zero_init: bool = True,
        window_size: int = 0,
        global_attn_indexes: Tuple[int, ...] = (),
        multi_scale: bool = False,
        output_shape: Union[Tuple, List] = None
    ) -> None:
        """
        Args:
            img_size (int): Input image size.
            patch_size (int): Patch size.
            in_chans (int): Number of input image channels.
            embed_dim (int): Patch embedding dimension.
            depth (int): Depth of ViT.
            num_heads (int): Number of attention heads in each ViT block.
            mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
            qkv_bias (bool): If True, add a learnable bias to query, key, value.
            norm_layer (nn.Module): Normalization layer.
            act_layer (nn.Module): Activation layer.
            use_abs_pos (bool): If True, use absolute positional embeddings.
            use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
            rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
            window_size (int): Window size for window attention blocks.
            global_attn_indexes (list): Indexes for blocks using global attention.
        """
        super().__init__()
        self.img_size = img_size
        self.multi_scale = multi_scale
        self.output_shape = tuple(output_shape) if output_shape else None


        self.patch_embed = PatchEmbed(
            kernel_size=(patch_size, patch_size),
            stride=(patch_size, patch_size),
            in_chans=in_chans,
            embed_dim=embed_dim,
        )

        self.pos_embed: Optional[nn.Parameter] = None
        if use_abs_pos:
            # Initialize absolute positional embedding with pretrain image size.
            self.pos_embed = nn.Parameter(
                torch.zeros(1, img_size // patch_size, img_size // patch_size, embed_dim)
            )

        self.blocks = nn.ModuleList()
        for i in range(depth):
            block = Block(
                dim=embed_dim,
                num_heads=num_heads,
                mlp_ratio=mlp_ratio,
                qkv_bias=qkv_bias,
                norm_layer=norm_layer,
                act_layer=act_layer,
                use_rel_pos=use_rel_pos,
                rel_pos_zero_init=rel_pos_zero_init,
                window_size=window_size if i not in global_attn_indexes else 0,
                input_size=(img_size // patch_size, img_size // patch_size),
            )
            self.blocks.append(block)

        self.neck = nn.Sequential(
            nn.Conv2d(
                embed_dim*depth if self.multi_scale and self.output_shape else embed_dim,
                out_chans,
                kernel_size=1,
                bias=False,
            ),
            LayerNorm2d(out_chans),
            nn.Conv2d(
                out_chans,
                out_chans,
                kernel_size=3,
                padding=1,
                bias=False,
            ),
            LayerNorm2d(out_chans),
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = self.patch_embed(x)
        if self.pos_embed is not None:
            x = x + self.pos_embed

        if self.multi_scale and self.output_shape:
            output_list = []
            for blk in self.blocks:
                x = blk(x)
                output_list.append(F.interpolate(x.permute(0, 3, 1, 2), size=self.output_shape, mode='bilinear'))

            x = self.neck(torch.cat(output_list, dim=1))
        else:
            for blk in self.blocks:
                x = blk(x)
            x = self.neck(x.permute(0, 3, 1, 2))
        return x

class SAMEncoderAdaptor(nn.Module):
    def __init__(self,
                 img_size: int,
                 input_size: Optional[Tuple[int, int]],
                 embed_dim: int = 768,
                 depth: int = 12,
                 num_heads: int = 12,
                 mlp_ratio: float = 4.0,
                 out_chans: int = 256,
                 qkv_bias: bool = True,
                 norm_layer: Type[nn.Module] = nn.LayerNorm,
                 act_layer: Type[nn.Module] = nn.GELU,
                 use_abs_pos: bool = True,
                 use_rel_pos: bool = False,
                 rel_pos_zero_init: bool = True,
                 window_size: int = 0,
                 global_attn_indexes: Tuple[int, ...] = (),
                 multi_scale: bool = False,
                 output_shape: Union[Tuple, List] = None):
        super(SAMEncoderAdaptor, self).__init__()
        self.img_size = img_size
        self.multi_scale = multi_scale
        self.output_shape = tuple(output_shape) if output_shape else None

        self.pos_embed: Optional[nn.Parameter] = None
        if use_abs_pos:
            # Initialize absolute positional embedding with pretrain image size.
            self.pos_embed = nn.Parameter(
                torch.zeros(1, input_size[0], input_size[1], embed_dim)
            )
        self.blocks = nn.ModuleList()
        for i in range(depth):
            block = Block(
                dim=embed_dim,
                num_heads=num_heads,
                mlp_ratio=mlp_ratio,
                qkv_bias=qkv_bias,
                norm_layer=norm_layer,
                act_layer=act_layer,
                use_rel_pos=use_rel_pos,
                rel_pos_zero_init=rel_pos_zero_init,
                window_size=window_size if i not in global_attn_indexes else 0,
                input_size=input_size,
            )
            self.blocks.append(block)

        self.neck = nn.Sequential(
            nn.Conv2d(
                embed_dim * depth if self.multi_scale and self.output_shape else embed_dim,
                out_chans,
                kernel_size=1,
                bias=False,
            ),
            LayerNorm2d(out_chans),
            nn.Conv2d(
                out_chans,
                out_chans,
                kernel_size=3,
                padding=1,
                bias=False,
            ),
            LayerNorm2d(out_chans),
        )

    def forward(self, x: torch.Tensor, original_size: Union[Tuple, List] = None) -> torch.Tensor:
        if original_size:
            original_size = torch.LongTensor(original_size)
            output_shape = x.shape[-2:]
            if original_size.ndim == 1:
                original_size = original_size[None, ...]
            adaptor_inputs = []
            for i in range(original_size.shape[0]):
                h, w = original_size[i]
                if h > w:
                    new_h = output_shape[0]
                    new_w = int(w * new_h / h)
                else:
                    new_w = output_shape[1]
                    new_h = int(h * new_w / w)
                encoder_output = x[0].unsqueeze(0)
                encoder_output = F.interpolate(encoder_output, size=(new_h, new_w), mode='bilinear')
                pad_h = output_shape[0] - new_h
                pad_w = output_shape[1] - new_w
                encoder_output = F.pad(encoder_output, (0, pad_w, 0, pad_h))
                adaptor_inputs.append(encoder_output)
            adaptor_inputs = torch.cat(adaptor_inputs, dim=0)
            x = adaptor_inputs.permute(0, 2, 3, 1)
        if self.pos_embed is not None:
            x = x + self.pos_embed
        if self.multi_scale and self.output_shape:
            output_list = []
            for blk in self.blocks:
                x = blk(x)
                output_list.append(F.interpolate(x.permute(0, 3, 1, 2), size=self.output_shape, mode='bilinear'))

            x = self.neck(torch.cat(output_list, dim=1))
        else:
            for blk in self.blocks:
                x = blk(x)
            x = self.neck(x.permute(0, 3, 1, 2))
        return x


class DINOSAMViT(nn.Module):
    def __init__(self,
                 dino_model_type,
                 device='cuda',
                 pca_dim=None,
                 **kwargs
                 ):
        super(DINOSAMViT, self).__init__()
        self.img_size = kwargs['img_size']
        if not pca_dim:
            pca_dim = None
        self.dino = DINO(dino_model_type, device, self.img_size, pca_dim)
        self.input_size = tuple(kwargs['output_shape'])
        # input_size = self.dino.model.patch_embed.img_size // self.dino.model.patch_embed.img_size
        # self.input_size = (input_size, input_size)
        embed_dim = pca_dim if pca_dim is not None else self.dino.model.embed_dim
        kwargs.update({'input_size': self.input_size, 'embed_dim': embed_dim})
        self.adaptor = SAMEncoderAdaptor(**kwargs).to(device)
    def extract_dino_features(self, x, transform=False, size = None):
        return self.dino.extract_features(x, transform, size)
    def forward(self, x, transform=False, size = None):
        dino_feature = F.normalize(self.extract_dino_features(x, transform, size), dim=3)
        adaptor_input = F.interpolate(dino_feature.permute(0, 3, 1, 2), size=self.input_size, mode='bilinear').permute(0, 2, 3, 1)
        return self.adaptor(adaptor_input)
def setup_model(model_config):
    prompt_embed_dim = 256
    image_size = 1024
    vit_patch_size = 16
    image_embedding_size = image_size // vit_patch_size
    model = eval(model_config.pop('type'))(**model_config)
    if model.__class__.__name__ == 'SAMEncoderAdaptor':
        adaptor = model
        image_encoder = load_sam('weights/sam/mobile_sam.pt', 'mobile_sam', 'cpu').image_encoder
    else:
        adaptor = None
        image_encoder = model
    sam = Sam(
            image_encoder=image_encoder,
            prompt_encoder=PromptEncoder(
            embed_dim=prompt_embed_dim,
            image_embedding_size=(image_embedding_size, image_embedding_size),
            input_image_size=(image_size, image_size),
            mask_in_chans=16,
            ),
            mask_decoder=MaskDecoder(
                    num_multimask_outputs=3,
                    transformer=TwoWayTransformer(
                    depth=2,
                    embedding_dim=prompt_embed_dim,
                    mlp_dim=2048,
                    num_heads=8,
                ),
                transformer_dim=prompt_embed_dim,
                iou_head_depth=3,
                iou_head_hidden_dim=256,
            ),
            adaptor=adaptor,
            pixel_mean=[123.675, 116.28, 103.53],
            pixel_std=[58.395, 57.12, 57.375],
        )
    return sam

def load_distillation_sam(distillation_sam_ckpt_path,
                          device='cuda'):
    ckpt = torch.load(distillation_sam_ckpt_path)
    sam = setup_model(ckpt['model_config'])
    sam.load_state_dict(ckpt['model'])
    return sam.to(device)

def load_sam(sam_ckpt_path, sam_version, device):
    if not os.path.exists(sam_ckpt_path):
        parent_dir = os.path.dirname(sam_ckpt_path)
        os.makedirs(parent_dir, exist_ok=True)
        hf_sam_download(filename=os.path.basename(sam_ckpt_path), local_dir=parent_dir)
    if sam_version == 'sam':
        sam = build_sam(sam_ckpt_path).to(device)
    elif sam_version == 'mobile_sam':
        sam = load_mobile_sam(sam_ckpt_path, device)
    elif sam_version == 'distillation_sam':
        sam = load_distillation_sam(sam_ckpt_path, device)
    else:
        raise ValueError('sam version error, please give sam version in [sam, mobile_sam, distillation_sam]')
    return sam

if __name__ == '__main__':
    from distillation.utils import get_parameter_number
    vit = SAMEncoderViT(depth=3,
                        embed_dim=256,
                        img_size=512,
                        mlp_ratio=4,
                        num_heads=16,
                        patch_size=8,
                        qkv_bias=True,
                        use_rel_pos=True,
                        global_attn_indexes=[1],
                        window_size=16,
                        out_chans=256,
                        multi_scale=False,
                        output_shape='').cuda()
    x = torch.randn((1, 3, 512, 512)).cuda()
    print(vit(x).shape)
    print(get_parameter_number(vit))