File size: 15,090 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 | from typing import List
import torch
import torch.nn.functional as F
import torch
from torch.cuda.amp import autocast
from torchvision.ops import roi_align
import torch.nn as nn
# ! declip_plus 同时支持region loss,以及sd smoothing
class DeCLIPWithREPAProjector(nn.Module):
def __init__(self, declip_model, clip_dim=768, hidden_dim=1024, vfm_dim=768,args=None):
super().__init__()
self.model = declip_model
self.repa_layer_idx = args.repa_layer_idx
self.projector = nn.Sequential(
nn.Linear(clip_dim, hidden_dim),
nn.SiLU(),
nn.Linear(hidden_dim, hidden_dim),
nn.SiLU(),
nn.Linear(hidden_dim, vfm_dim))
# self.projector = nn.Sequential(nn.Linear(clip_dim, hidden_dim, bias=False),
# nn.GELU(),
# nn.Linear(hidden_dim,vfm_dim, bias=False))
self.initialize_projector_weights()
self.logit_scale=self.model.logit_scale
def initialize_projector_weights(self):
for module in self.projector.modules():
if isinstance(module, nn.Linear):
nn.init.xavier_uniform_(module.weight)
if module.bias is not None:
nn.init.constant_(module.bias, 0)
def encode_image(self, *args, **kwargs):
return self.model.encode_image(*args, **kwargs)
def encode_text(self, *args, **kwargs):
return self.model.encode_text(*args, **kwargs)
def encode_dense(self, *args, **kwargs):
return self.model.encode_dense(*args, **kwargs)
def encode_pseudo_boxes(self, images, rois_list, normalize = False, mode="qq", size=(1, 1)):
student_roi_features, context, intermediate_layer_output = self.model.encode_pseudo_boxes(images,
rois_list,
normalize=normalize,
mode = mode,
size=size,
get_intermediate_layer=[self.repa_layer_idx])
alpha=0.3
residual=intermediate_layer_output[0]
intermediate_layer_output = self.projector(intermediate_layer_output[0])
intermediate_layer_output = alpha * residual + intermediate_layer_output
return student_roi_features, context, intermediate_layer_output
def encode_masks(self, *args, **kwargs):
return self.model.encode_masks(*args, **kwargs)
def train(self, mode=True):
self.model.train(mode)
self.training = self.model.training
return self
def lock_image_tower(self, *args, **kwargs):
return self.model.lock_image_tower(*args, **kwargs)
def lock_text_tower(self, *args, **kwargs):
return self.model.lock_text_tower(*args, **kwargs)
@torch.jit.ignore
def set_grad_checkpointing(self, enable=True):
self.model.set_grad_checkpointing(enable)
@torch.jit.ignore
def no_weight_decay(self):
return self.model.no_weight_decay()
class DeCLIP_PLUS:
def __call__(self, batch, student, teacher, vfm_model, args):
losses = {}
context_weight = args.loss_context_weight
content_weight = args.loss_content_weight
region_weight = args.loss_region_weight
need_repa=args.repa_layer_idx!=-1
if args.distributed:
student = student.module
dtype_map = {"bf16": torch.bfloat16, "amp": torch.float16}
input_dtype = dtype_map.get(args.precision, torch.float32)
images, normed_boxes, image_crops, vfm_image,sd_attn = prepare_inputs(batch, args.device, input_dtype)
loss_ensemble = self.intra_image_distill(student, teacher, vfm_model, images, normed_boxes, image_crops, vfm_image,sd_attn,args)
loss_context, loss_content,loss_region = loss_ensemble[0], loss_ensemble[1], loss_ensemble[2]
losses.update({"loss_context":loss_context * context_weight})
losses.update({"loss_content":loss_content * content_weight})
losses.update({"loss_region":loss_region * region_weight}) # 0.3
if need_repa:
loss_repa=loss_ensemble[2]
losses.update({"loss_repa":loss_repa})
return losses, len(images)
def intra_image_distill(self, student, teacher, vfm_model, images, normed_boxes, image_crops, vfm_image,sd_attn,args):
need_repa = args.repa_layer_idx!=-1
roi_size=(3, 3)
B = images.shape[0]
rois_list = []
crops_list = []
for bboxes_per_image, crops_per_image in zip(normed_boxes, image_crops):
valid = bboxes_per_image[:, -1] > 0.5
rois_list.append(bboxes_per_image[valid, :4])
crops_list.append(crops_per_image[valid])
image_crops = torch.cat(crops_list)
if need_repa:
student_roi_features, context, intermediate_layer_output = student.encode_pseudo_boxes(images, rois_list, normalize=True, mode = args.mode, size=roi_size)
else:
student_roi_features, context = student.encode_pseudo_boxes(images, rois_list, normalize=True, mode = args.mode, size=roi_size)
with torch.no_grad():
teacher_crop_features = teacher.encode_image(image_crops, normalize=True)
intra_vfm_feats = extract_vfm_features(vfm_model, vfm_image,args) # bs,768, h,w
vfm_roi_features= extract_roi_features(intra_vfm_feats,rois_list,normalize=True)
intra_vfm_feats = F.normalize(intra_vfm_feats,dim=1).flatten(start_dim=-2)
intra_vfm_corr = torch.einsum('bci,bcj->bij', intra_vfm_feats, intra_vfm_feats)
refined_intra_vfm_corr = refine_dino(intra_vfm_corr, sd_attn, args.sd_refine_weight)
student_intra_corr = compute_student_intra_image_similarity(images.shape[0], context, args)
loss_context = context_loss(student_intra_corr, refined_intra_vfm_corr, teacher_temp=0.8)
# loss_content = 1.0 - (student_roi_features * teacher_crop_features).sum(-1).mean()
loss_content = soft_content_distill_loss(student_roi_features,teacher_crop_features)
loss_region= region_scd_loss(student_roi_features,vfm_roi_features)
if need_repa:
loss_repa = repa_loss(intermediate_layer_output, intra_vfm_feats)
return loss_context, loss_content, loss_repa
else:
return loss_context, loss_content,loss_region
def context_loss(student_corr, teacher_corr, teacher_temp=1.0, student_temp=1.0):
student_log_prob = F.log_softmax(student_corr / student_temp, dim=-1)
with torch.no_grad():
teacher_prob = F.softmax(teacher_corr / teacher_temp, dim=-1)
kl_loss=F.kl_div(student_log_prob, teacher_prob, reduction='batchmean')* (teacher_temp*student_temp)
return kl_loss
def refine_dino(dino_corr, sd_attn, sd_refine_weight):
"""
dino_corr: (bs,hw,hw)
sd_attn: (bs,hw,hw)
"""
residual = dino_corr
dino_corr = torch.bmm(sd_attn, dino_corr)
# dino_corr = torch.bmm(dino_corr, sd_attn.transpose(-2, -1))
dino_corr_refined = dino_corr * (sd_refine_weight) + residual * (1-sd_refine_weight) # bs, hw,hw
# 强制对角线为1
bs, hw, _ = dino_corr_refined.shape
device = dino_corr_refined.device
eye = torch.eye(hw, dtype=dino_corr_refined.dtype, device=device).unsqueeze(0).expand(bs, -1, -1)
dino_corr_refined = dino_corr_refined * (1 - eye) + eye
return dino_corr_refined
def repa_loss(clip_intermediate_out, vfm_out):
"""
clip_intermediate_out: (bs, nt+1, hs), NOT L2 norm
vfm_out: (bs, hs, nt), ALREADY L2 norm
"""
vfm_out = vfm_out.transpose(1, 2) # (bs, nt, hs)
clip_intermediate_out = clip_intermediate_out[:, 1:] # (bs, nt, hs)
clip_intermediate_out = F.normalize(clip_intermediate_out, dim=-1)
similarity = (clip_intermediate_out * vfm_out).sum(dim=-1) # (bs, nt)
loss = -similarity.mean()
return loss
def soft_content_distill_loss(student_roi_features, teacher_crop_features, T=1.0):
sim = torch.einsum('bpc,bc->bp', student_roi_features, teacher_crop_features)
weights = F.softmax(sim / T, dim=1)
weighted_student = (student_roi_features * weights.unsqueeze(-1)).sum(dim=1)
weighted_student = F.normalize(weighted_student, dim=-1)
cosine_similarity = (weighted_student * teacher_crop_features).sum(dim=-1)
loss = 1.0 - cosine_similarity.mean()
return loss
def region_scd_loss(student_roi_features, intra_vfm_roi_feats, T_teacher=1.0, T_student=1.0):
with torch.no_grad():
intra_vfm_roi_feats=intra_vfm_roi_feats.transpose(-2,-1).contiguous() # bs, L, HS
teacher_corr=torch.einsum('bic,bjc->bij', intra_vfm_roi_feats, intra_vfm_roi_feats) / T_teacher
teacher_prob = F.softmax(teacher_corr, dim=-1)
student_corr=torch.einsum('bic,bjc->bij', student_roi_features, student_roi_features) / T_student
student_log_prob = F.log_softmax(student_corr, dim=-1)
loss = F.kl_div(student_log_prob, teacher_prob, reduction='batchmean') * (T_teacher * T_student)
return loss
# def region_scd_loss(student_intermediate_features, intra_vfm_roi_feats, rois_list, temp=0.3):
# losses = []
# with torch.no_grad():
# intra_vfm_roi_feats=intra_vfm_roi_feats.transpose(-2,-1).contiguous() # bs, L, HS
# intra_vfm_roi_feats=F.normalize(intra_vfm_roi_feats,dim=-1)
# teacher_corr=torch.einsum('bic,bjc->bij', intra_vfm_roi_feats, intra_vfm_roi_feats) / temp
# teacher_prob = F.softmax(teacher_corr, dim=-1)
# for x in student_intermediate_features:
# if x.dim() == 3:
# x = x[:, 1:] # discard cls , # bs, nt, HS
# bs,nt,hs=x.shape
# h=w=int(math.sqrt(nt))
# x=x.transpose(-2,-1).contiguous().view(bs,hs, h,w)
# student_roi_features = extract_roi_features(x,rois_list,size=(5,5))
# student_roi_features=student_roi_features.transpose(-2,-1).contiguous()
# student_roi_features=F.normalize(student_roi_features,dim=-1)
# student_corr=torch.einsum('bic,bjc->bij', student_roi_features, student_roi_features) / temp
# student_log_prob = F.log_softmax(student_corr, dim=-1)
# loss = F.kl_div(student_log_prob, teacher_prob, reduction='batchmean') * (temp ** 2)
# losses.append(loss)
# if len(losses) == 0:
# return torch.zeros([], dtype=student_roi_features.dtype, device=student_roi_features.device)
# return torch.stack(losses).mean()
def extract_roi_features(x, normed_boxes, size=(3,3), normalize=False):
"""
x:(bs,c,h,w)
"""
def _denormalize_boxes(normed_boxes, x):
h, w = x.shape[-2:]
denormed_boxes = []
for boxes in normed_boxes:
new_boxes = boxes.clone() # FIXME: do not change the value in normed_boxes!
new_boxes[:, [0, 2]] *= w
new_boxes[:, [1, 3]] *= h
denormed_boxes.append(new_boxes)
return denormed_boxes
if size==(1, 1):
roi_feats=roi_align(x, _denormalize_boxes(normed_boxes, x), size, 1.0, -1, True)[..., 0, 0]
else:
roi_feats=roi_align(x, _denormalize_boxes(normed_boxes, x), size, 1.0, -1, True).flatten(start_dim=-2)
if normalize:
roi_feats=F.normalize(roi_feats,dim=1)
return roi_feats
def prepare_inputs(batch, device, dtype):
"""
将输入批次中的数据加载到设备,并转换为指定数据类型。
"""
images, normed_boxes, image_crops, vfm_image, sd_attn = batch
images = images.to(device=device, dtype=dtype, non_blocking=True)
normed_boxes = normed_boxes.to(device=device, dtype=dtype, non_blocking=True)
image_crops = image_crops.to(device=device, dtype=dtype, non_blocking=True)
vfm_image = vfm_image.to(device=device, dtype=dtype, non_blocking=True)
sd_attn = sd_attn.to(device=device, dtype=dtype, non_blocking=True)
return images, normed_boxes, image_crops, vfm_image, sd_attn
def extract_vfm_features(vfm_model, image, args):
"""
从 VFM 模型中提取特征,并对其进行归一化。
"""
if "dinov2" in args.use_vfm or "sd_dino" in args.use_vfm or "sam_dino" in args.use_vfm:
vfm_feats = vfm_model.get_intermediate_layers(image, reshape=True)[0]
elif 'sam' in args.use_vfm:
vfm_feats = vfm_model.image_encoder(image)
elif 'dino' in args.use_vfm:
feat = vfm_model.get_intermediate_layers(image)[0]
nb_im = feat.shape[0]
patch_size = vfm_model.patch_embed.patch_size
I, J = image[0].shape[-2] // patch_size, image[0].shape[-2] // patch_size
vfm_feats = feat[:, 1:, :].reshape(nb_im, I, J, -1).permute(0, 3, 1, 2)
else:
raise NotImplementedError(f"VFM mode {args.use_vfm} is not implemented.")
return vfm_feats
def compute_student_intra_image_similarity(B, context, args):
N, _ = context[0].shape[1:] if isinstance(context, tuple) else context.shape[1:]
if args.mode in ["qq_vfm_distill", "kk_vfm_distill", "vv_vfm_distill", "sanity_check"]:
context = context.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1)
context = F.normalize(context, dim=-1).transpose(-2, -1)
student_context_similarity = torch.einsum("b c m, b c n -> b m n", context, context)
elif args.mode == "csa_vfm_distill":
q_feature, k_feature = context
q_feature = q_feature.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1)
k_feature = k_feature.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1)
q_feature = F.normalize(q_feature, dim=-1).transpose(-2, -1)
k_feature = F.normalize(k_feature, dim=-1).transpose(-2, -1)
student_context_similarity = (torch.einsum("b c m, b c n -> b m n", q_feature, q_feature) +
torch.einsum("b c m, b c n -> b m n", k_feature, k_feature)) / 2.0
elif args.mode == "all_vfm_distill":
q_feature, k_feature, v_feature = context
features = [q_feature, k_feature, v_feature]
similarities = []
for feature in features:
feature = feature.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1)
feature = F.normalize(feature, dim=-1).transpose(-2, -1)
similarities.append(torch.einsum("b c m, b c n -> b m n", feature, feature))
student_context_similarity = sum(similarities) / len(features)
else:
raise NotImplementedError(f"Mode '{args.mode}' is not implemented.")
return student_context_similarity |