File size: 16,387 Bytes
c50dde6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386

import torch
import torch.nn.functional as F
import numpy as np
import os
from contextlib import nullcontext
from src.segment_anything import sam_model_registry
import torch.nn as nn
# 延迟导入 diffusion_model,避免在不需要时触发 diffusers 依赖
# from diffusion_model.stable_diffusion import diffusion
from open_clip.eva_clip.eva_vit_model import Attention

def context_adapter(clip, args):
    last_block_attn=clip.visual.blocks[-1].attn
    attn_config=extract_attention_config(last_block_attn)
    new_attn=CustomAttention(args.mode, **attn_config)
    device = next(last_block_attn.parameters()).device
    new_attn = new_attn.to(device)
    with torch.no_grad():
        for param_name, param_value in last_block_attn.named_parameters():
            if param_name in new_attn.state_dict():
                new_attn.state_dict()[param_name].copy_(param_value)
    clip.visual.blocks[-1].attn = new_attn


class CustomAttention(Attention):
    def __init__(self, mode, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.mode=mode
        if mode=="csa_vfm_distill":
            self.q_adapter = nn.Sequential(
                            nn.Linear(self.proj.in_features, 1024),
                            nn.SiLU(),
                            nn.Linear(1024, 1024),
                            nn.SiLU(),
                            nn.Linear(1024, self.proj.in_features))
            
            self.k_adapter = nn.Sequential(
                            nn.Linear(self.proj.in_features, 1024),
                            nn.SiLU(),
                            nn.Linear(1024, 1024),
                            nn.SiLU(),
                            nn.Linear(1024, self.proj.in_features))
        else:
            self.context_adapter = nn.Sequential(
                            nn.Linear(self.proj.in_features, 1024),
                            nn.SiLU(),
                            nn.Linear(1024, 1024),
                            nn.SiLU(),
                            nn.Linear(1024, self.proj.in_features))
        self.alpha=0.7
        self._reset_mlp_parameters()
        
    def _reset_mlp_parameters(self):
        if self.mode == "csa_vfm_distill":
            for layer in self.q_adapter:
                if isinstance(layer, nn.Linear):
                    nn.init.xavier_uniform_(layer.weight)
                    if layer.bias is not None:
                        nn.init.zeros_(layer.bias)
            for layer in self.k_adapter:
                if isinstance(layer, nn.Linear):
                    nn.init.xavier_uniform_(layer.weight)
                    if layer.bias is not None:
                        nn.init.zeros_(layer.bias)
        else:
            for layer in self.context_adapter:
                if isinstance(layer, nn.Linear):
                    nn.init.xavier_uniform_(layer.weight)
                    if layer.bias is not None:
                        nn.init.zeros_(layer.bias)

    def ss_attn(self, x, mode):
        B, N, C = x.shape
        if self.subln: 
            q = F.linear(input=x, weight=self.q_proj.weight, bias=self.q_bias)
            k = F.linear(input=x, weight=self.k_proj.weight, bias=None)
            v = F.linear(input=x, weight=self.v_proj.weight, bias=self.v_bias)
            if self.mode=="csa_vfm_distill":
                q_distill = self.q_adapter(q)
                k_distill = self.k_adapter(k)
                q_distill=q + q_distill*(self.alpha)
                k_distill=k + k_distill*(self.alpha)

                q_distill=q_distill.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
                k_distill=k_distill.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
                q_distill = q_distill.contiguous().view(B*self.num_heads, N, -1)
                k_distill = k_distill.contiguous().view(B*self.num_heads, N, -1)
            elif self.mode=="qq_vfm_distill":
                q_distill=self.context_adapter(q)
                q_distill=q_distill.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
                q_distill = q_distill.contiguous().view(B*self.num_heads, N, -1)
            else:
                raise NotImplementedError
            
            q = q.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)    # B, num_heads, N, C
            k = k.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)  
            v = v.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) 
        else: 
            qkv_bias = None
            if self.q_bias is not None:
                qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias))
            
            qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias)
            qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)   # 3, B, num_heads, N, C
            q, k, v = qkv[0], qkv[1], qkv[2]

        q = q.contiguous().view(B*self.num_heads, N, -1)
        k = k.contiguous().view(B*self.num_heads, N, -1)
        v = v.contiguous().view(B*self.num_heads, N, -1)
        if 'qq' in mode:
            q_attn = torch.bmm(q, q.transpose(1, 2))  #  self.scale
            attn_weights = F.softmax(q_attn, dim=-1)
        elif 'csa' in mode:
            q_attn = torch.bmm(q, q.transpose(1, 2))  # self.scale
            k_attn = torch.bmm(k, k.transpose(1, 2)) # self.scale
            attn_weights = F.softmax(q_attn + k_attn, dim=-1)
        elif 'vv' in mode:
            v_attn = torch.bmm(v, v.transpose(1, 2)) # self.scale
            attn_weights = F.softmax(v_attn, dim=-1)
        elif 'kk' in mode:
            k_attn = torch.bmm(k, k.transpose(1, 2)) # self.scale
            attn_weights = F.softmax(k_attn, dim=-1)
        elif 'all' in mode:
            q_attn = torch.bmm(q, q.transpose(1, 2))   # self.scale
            k_attn = torch.bmm(k, k.transpose(1, 2))  # self.scale
            v_attn = torch.bmm(v, v.transpose(1, 2))  #  self.scale
            _attn = (q_attn+k_attn+v_attn)/3.0
            attn_weights = F.softmax(_attn, dim=-1)
        else:
            raise NotImplementedError(f"Mode '{mode}' is not implemented.")

        attn_output = torch.bmm(attn_weights, v) 
        attn_output = attn_output.transpose(0, 1).contiguous().view(N, B, C).transpose(0, 1) # B,N,C
        attn_output = self.inner_attn_ln(attn_output)
        attn_output = self.proj(attn_output)
        attn_output = self.proj_drop(attn_output)
        
        if mode=="qq_vfm_distill":
            return attn_output, q_distill[:,1:]
        elif mode=="kk_vfm_distill":
            return attn_output, k[:,1:]
        elif mode=="csa_vfm_distill":
            return attn_output, (q_distill[:,1:], k_distill[:,1:])
        elif mode=="vv_vfm_distill":
            return attn_output, v[:,1:]
        elif mode=="all_vfm_distill":
            return attn_output, (q[:,1:], k[:,1:], v[:,1:])
        else:
            return attn_output


def extract_attention_config(attn_module):
    config = {
        "dim": attn_module.proj.in_features,  # 输入维度
        "num_heads": attn_module.num_heads,  # 多头注意力的头数
        "qkv_bias": attn_module.q_bias is not None,  # QKV 是否使用偏置
        "qk_scale": attn_module.scale,  # QK 的缩放因子
        "attn_drop": attn_module.attn_drop.p,  # Dropout 概率
        "proj_drop": attn_module.proj_drop.p,  # 输出投影的 Dropout 概率
        "subln": attn_module.subln,  # 是否使用 SubLayerNorm
        "rope": attn_module.rope,
        "norm_layer": type(attn_module.inner_attn_ln),  # 使用的归一化层类型
        "xattn": getattr(attn_module, "xattn", False),  # 是否使用 xattn 模式
    }
    return config

def get_autocast(precision):
    if precision == "bf16":
        return lambda: torch.autocast("cuda", dtype=torch.bfloat16) 
    elif precision == "amp":
        return lambda: torch.cuda.amp.autocast() 
    else:
        return lambda: nullcontext() 
    
def mask2box(mask):
    ys, xs = np.where(mask)
    y0, y1 = ys.min(), ys.max()
    x0, x1 = xs.min(), xs.max()
    return x0, y0, x1, y1




def build_vfm(args):
    name=args.use_vfm
    sam_ckpts = {
        "sam-B": "/opt/tiger/xiaomoguhzz/sam/sam_vit_b_01ec64.pth",
        "sam-L": "/opt/tiger/xiaomoguhzz/sam/sam_vit_l_0b3195.pth", 
    }
    
    dinov2_ckpts = {
        "dinov2-L": "dinov2_vitl14_reg",
        "dinov2-B": "dinov2_vitb14_reg",
        "dinov2-B-noreg": "dinov2_vitb14",
        "dinov2-L-noreg": "dinov2_vitl14",
    }

    dino_ckpts = {
        "dino-B-8": "dino_vitb8",
        "dino-B-16": "dino_vitb16",
    }

    vfm = None

    if name.startswith("dinov2"):
        if name in dinov2_ckpts:
            model_name = dinov2_ckpts[name]
            try:
                vfm = torch.hub.load('facebookresearch/dinov2', model_name).half()
            except Exception as e:
                raise RuntimeError(f"Failed to load DINOv2 model '{name}': {e}")
        else:
            raise NotImplementedError(f"VLM model '{name}' not supported under DINOv2 category.")
    
    elif name.startswith("dino"):
        if name in dino_ckpts:
            model_name = dino_ckpts[name]
            try:
                vfm = torch.hub.load('facebookresearch/dino:main', model_name).half()
            except Exception as e:
                raise RuntimeError(f"Failed to load DINO model '{name}': {e}")
        else:
            raise NotImplementedError(f"VLM model '{name}' not supported under DINO category.")
        
    elif name.startswith("sd_dino"):
        model_name = dinov2_ckpts['dinov2-B']
        try:
            dinov2 = torch.hub.load('facebookresearch/dinov2', model_name).half().eval()
        except Exception as e:
            raise RuntimeError(f"Failed to load DINOv2 model '{name}': {e}")
        
        try:
            # 延迟导入:只在 sd_dino 模式下才导入 diffusers 相关依赖
            from diffusion_model.stable_diffusion import diffusion
            sd=diffusion(attention_layers_to_use=[-4, -6],model='v2.1', time_step=45, device=args.device, dtype=torch.float16).eval()
        except Exception as e:
            raise RuntimeError(f"Failed to load diffusion model")
        for p in dinov2.parameters():
            p.requires_grad = False
        for p in sd.parameters():
            p.requires_grad = False
        return [dinov2, sd]
    
    elif name.startswith("sam_dino"):

        name='dinov2-B'
        model_name = dinov2_ckpts[name]
        try:
            dinov2 = torch.hub.load('facebookresearch/dinov2', model_name).half()
        except Exception as e:
            raise RuntimeError(f"Failed to load DINOv2 model '{name}': {e}")
        sam = sam_model_registry['vit_l'](checkpoint="/opt/tiger/xiaomoguhzz/sam/sam_vit_l_0b3195.pth").half()
        for p in dinov2.parameters():
            p.requires_grad = False
        for p in sam.parameters():
            p.requires_grad = False
        return [dinov2, sam]
    
    elif name.startswith("sam"):
        if name in sam_ckpts:
            vit_type = "vit_b" if "B" in name else "vit_l"
            checkpoint_path = sam_ckpts[name]
            try:
                vfm = sam_model_registry[vit_type](checkpoint=checkpoint_path).half()
            except Exception as e:
                raise RuntimeError(f"Failed to load SAM model '{name}' with checkpoint '{checkpoint_path}': {e}")
        else:
            raise NotImplementedError(f"VLM model '{name}' not supported under SAM category.")
    else:
        raise NotImplementedError(f"VLM model '{name}' not supported.")

    for p in vfm.parameters():
        p.requires_grad = False
    
    return vfm
    
def freeze_parameters(model, args):
    freeze_keys = get_freeze_keys(args)
    for name, param in model.named_parameters():
        if name in freeze_keys:
            param.requires_grad = False
    return model

def get_freeze_keys(args):
    if args.model=="ViT-B-16":
        return ViTB_16_freeze_keys
    elif args.model=="ViT-L-14" or args.model=="ViT-L-14-336":
         return ViTL_14_freeze_keys
    elif args.model=="EVA02-CLIP-B-16":
        if args.custom_freeze_para:
            return custom_EVA_ViTB_16_freeze_keys
        if args.mode=="qq_vfm_distill":
            return ViTB_EVA_16_qq_Distill_keys
        elif args.mode=="kk_vfm_distill":
            return ViTB_EVA_16_kk_Distill_keys
        elif args.mode=="sanity_check":
            return sanity_check_freeze_keys
        else: 
            return BASE_EVA_ViTB_16_freeze_keys
    elif args.model=="EVA02-CLIP-L-14-336":
        if args.custom_freeze_para:
            return custom_EVA_ViTL_14_freeze_keys
        if args.mode=="qq_vfm_distill":
            return ViTL_EVA_14_qq_Distill_keys
        elif args.mode=="kk_vfm_distill":
            return ViTL_EVA_14_kk_Distill_keys
        elif args.mode=="sanity_check":
            return sanity_check_freeze_keys
        else: 
            return BASE_EVA_ViTL_14_freeze_keys
    elif args.model=="siglip-so400m-patch14-384":
        return siglip_384_Distill_Freeze_keys
    elif "TinyCLIP" in args.model:
        # TinyCLIP-auto-ViT-63M-32-Text-31M 有12层,最后一个block索引为11
        return TinyCLIP_63M_freeze_keys


TinyCLIP_63M_freeze_keys=[
    '_image_encoder.visual.transformer.resblocks.11.ln_2.weight',
    '_image_encoder.visual.transformer.resblocks.11.ln_2.bias',
    '_image_encoder.visual.transformer.resblocks.11.mlp.c_fc.weight',
    '_image_encoder.visual.transformer.resblocks.11.mlp.c_fc.bias',
    '_image_encoder.visual.transformer.resblocks.11.mlp.c_proj.weight',
    '_image_encoder.visual.transformer.resblocks.11.mlp.c_proj.bias',
]

ViTB_16_freeze_keys=[
             'visual.transformer.resblocks.11.ln_2.weight',
             'visual.transformer.resblocks.11.ln_2.bias',
             'visual.transformer.resblocks.11.mlp.c_fc.weight',
             'visual.transformer.resblocks.11.mlp.c_fc.bias',
             'visual.transformer.resblocks.11.mlp.c_proj.weight',
             'visual.transformer.resblocks.11.mlp.c_proj.bias']

ViTL_14_freeze_keys=[
             'visual.transformer.resblocks.23.ln_2.weight',
             'visual.transformer.resblocks.23.ln_2.bias',
             'visual.transformer.resblocks.23.mlp.c_fc.weight',
             'visual.transformer.resblocks.23.mlp.c_fc.bias',
             'visual.transformer.resblocks.23.mlp.c_proj.weight',
             'visual.transformer.resblocks.23.mlp.c_proj.bias']

BASE_EVA_ViTB_16_freeze_keys=[
            'logit_scale',
             'visual.blocks.11.norm2.weight',
             'visual.blocks.11.norm2.bias',
             'visual.blocks.11.mlp.w1.weight',
             'visual.blocks.11.mlp.w1.bias',
             'visual.blocks.11.mlp.w2.weight',
             'visual.blocks.11.mlp.w2.bias',
             'visual.blocks.11.mlp.w3.weight',
             'visual.blocks.11.mlp.w3.bias',
             'visual.blocks.11.mlp.ffn_ln.weight',
             'visual.blocks.11.mlp.ffn_ln.bias']

BASE_EVA_ViTL_14_freeze_keys=[
             'logit_scale',
             'visual.blocks.23.norm2.weight',
             'visual.blocks.23.norm2.bias',
             'visual.blocks.23.mlp.w1.weight',
             'visual.blocks.23.mlp.w1.bias',
             'visual.blocks.23.mlp.w2.weight',
             'visual.blocks.23.mlp.w2.bias',
             'visual.blocks.23.mlp.w3.weight',
             'visual.blocks.23.mlp.w3.bias',
             'visual.blocks.23.mlp.ffn_ln.weight',
             'visual.blocks.23.mlp.ffn_ln.bias']

custom_EVA_ViTB_16_freeze_keys=['logit_scale']
custom_EVA_ViTL_14_freeze_keys=['logit_scale']

sanity_check_freeze_keys=['logit_scale']
ViTB_EVA_16_qq_Distill_keys=['visual.blocks.11.attn.k_proj.weight',
                             ] + BASE_EVA_ViTB_16_freeze_keys
ViTL_EVA_14_qq_Distill_keys=['visual.blocks.23.attn.k_proj.weight',
                             ] + BASE_EVA_ViTL_14_freeze_keys
ViTB_EVA_16_kk_Distill_keys=['visual.blocks.11.attn.q_proj.weight','visual.blocks.11.attn.q_bias'] + BASE_EVA_ViTB_16_freeze_keys
ViTL_EVA_14_kk_Distill_keys=['visual.blocks.23.attn.q_proj.weight','visual.blocks.23.attn.q_bias'] + BASE_EVA_ViTL_14_freeze_keys

siglip_384_Distill_Freeze_keys=['logit_scale',
                                'logit_bias',
                                'vision_model.head.probe',
                                ]