DeCLIP-TPAMI / src /training /utils.py
xiaomoguhzz's picture
Add files using upload-large-folder tool
c50dde6 verified
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',
]