import h5py from diffusion_model.stable_diffusion import diffusion import torch import numpy as np import os from PIL import Image from pycocotools.coco import COCO from torchvision.transforms import Normalize, Compose, RandomResizedCrop, InterpolationMode, ToTensor, Resize, \ CenterCrop from open_clip.transform import ResizeLongest, _convert_to_rgb from torchvision import transforms import matplotlib.pyplot as plt import cv2 from functools import reduce import torch.nn.functional as F def build_DINOv2(): model_name='dinov2_vitb14_reg' hub_path = '/mnt/SSD8T/home/wjj/.cache/torch/hub/facebookresearch_dinov2_main' try: vfm = torch.hub.load(hub_path, model_name, source='local').half() except Exception as e: raise RuntimeError(f"Failed to load DINOv2 model '{model_name}': {e}") return vfm def visualize_sd_dino_att( ori_img, self_att, sim_dino_soft, sim_dino_refined, token_choosen, filename, attn_map_hw=(64, 64), vis_hw=(512, 512) ): """ 可视化SD传播对DINO自相关的细化效果, 4列分别为: 1. 原图带token 2. SD自注意力传播 3. DINO自相关 4. 细化后的DINO自相关 """ # 1. 原图 # 支持PIL.Image、np.ndarray、tensor三种输入 if isinstance(ori_img, torch.Tensor): img = ori_img if img.ndim == 4: # [1,3,H,W] -> [3,H,W] img = img[0] img = img.cpu().numpy() img = np.transpose(img, (1, 2, 0)) # [H, W, 3] img = (img * 255).clip(0, 255).astype(np.uint8) elif isinstance(ori_img, Image.Image): img = np.array(ori_img) if img.dtype != np.uint8: img = (img * 255).clip(0, 255).astype(np.uint8) elif isinstance(ori_img, np.ndarray): img = ori_img if img.dtype != np.uint8: img = (img * 255).clip(0, 255).astype(np.uint8) else: raise ValueError("ori_img should be torch.Tensor, PIL.Image, or np.ndarray") if img.shape[2] == 4: # RGBA to RGB img = img[:, :, :3] img_resized = cv2.resize(img, vis_hw, interpolation=cv2.INTER_LINEAR) # 2. token坐标 h_attn, w_attn = attn_map_hw row, col = token_choosen y_vis = int((row + 0.5) * vis_hw[0] / h_attn) x_vis = int((col + 0.5) * vis_hw[1] / w_attn) img_with_dot = img_resized.copy() cv2.circle(img_with_dot, (x_vis, y_vis), radius=7, color=(255,0,0), thickness=-1) # 红点 # 3. SD自注意力传播 att_map_sd = self_att[row * w_attn + col].to(torch.float32).detach().cpu().numpy().reshape(h_attn, w_attn) att_map_sd = (att_map_sd - att_map_sd.min()) / (att_map_sd.max() - att_map_sd.min() + 1e-8) att_map_sd_up = cv2.resize(att_map_sd, vis_hw, interpolation=cv2.INTER_LINEAR) # 4. DINO自相关(传播前) att_map_dino = sim_dino_soft[row * w_attn + col].detach().cpu().numpy().reshape(h_attn, w_attn) att_map_dino = (att_map_dino - att_map_dino.min()) / (att_map_dino.max() - att_map_dino.min() + 1e-8) att_map_dino = att_map_dino.astype(np.float32) att_map_dino_up = cv2.resize(att_map_dino, vis_hw, interpolation=cv2.INTER_LINEAR) # 5. DINO传播后 att_map_dino_ref = sim_dino_refined[row * w_attn + col].detach().cpu().numpy().reshape(h_attn, w_attn) att_map_dino_ref = (att_map_dino_ref - att_map_dino_ref.min()) / (att_map_dino_ref.max() - att_map_dino_ref.min() + 1e-8) att_map_dino_ref = att_map_dino_ref.astype(np.float32) att_map_dino_ref_up = cv2.resize(att_map_dino_ref, vis_hw, interpolation=cv2.INTER_LINEAR) # 6. 绘图 fig, axs = plt.subplots(1, 4, figsize=(18, 5)) axs[0].imshow(img_with_dot) axs[0].set_title("Original (with token)") axs[0].axis('off') axs[1].imshow(att_map_sd_up, cmap='jet') axs[1].set_title(f'SD propagation (token {token_choosen})') axs[1].axis('off') axs[2].imshow(att_map_dino_up, cmap='jet') axs[2].set_title(f'DINO sim (pre-propagate)') axs[2].axis('off') axs[3].imshow(att_map_dino_ref_up, cmap='jet') axs[3].set_title(f'DINO sim (post-propagate)') axs[3].axis('off') plt.tight_layout() plt.savefig(filename, dpi=200, bbox_inches='tight') plt.close() attention_layers_to_use= [-4, -6] sd_version='v2.1' time_step=45 device="cuda:2" dino=build_DINOv2().to(device) image_root='/mnt/SSD8T/home/wjj/dataset/standard_coco/train2017' cache=h5py.File("/mnt/SSD8T/home/wjj/code/DeCLIP/sd_self_attn_cache/sd_self_attn_coco.h5", 'r', swmr=True) image_file=os.listdir(image_root)[5] cache_attn=torch.from_numpy(cache[image_file][()]).to(device) image_name=os.path.join(image_root, image_file) # image = Image.open('demo_images/horses.jpg') image = Image.open(image_name) mean=[0.485, 0.456, 0.406] std=[0.229, 0.224, 0.225] normalize = Normalize(mean=mean, std=std) DINO_transform=transforms.Compose([ ResizeLongest(490, fill=0), _convert_to_rgb, ToTensor(), normalize]) img_transform=transforms.Compose([ResizeLongest(560, fill=0)]) dino_img=DINO_transform(image).unsqueeze(0).to(torch.float16).to(device) # dino_feats_raw=dino.get_intermediate_layers(dino_img, reshape=True)[0].flatten(start_dim=-2).transpose(-2,-1) dino_feats_raw=dino.get_intermediate_layers(dino_img, reshape=True)[0].flatten(start_dim=-2).transpose(-2,-1) dino_feats = F.normalize(dino_feats_raw, dim=2) sim_dino = torch.einsum('bic,bjc->bij', dino_feats, dino_feats).squeeze(0) self_att=cache_attn.to(sim_dino.dtype) refined_sim_dino = self_att @ sim_dino @ self_att.transpose(0, 1) # alpha = 0.1 # 你可以把它设置成任意[0,1]的数,逐渐试 # sim_dino_mixed = (1 - alpha) * sim_dino_softmax + alpha * sim_dino_refined output_dir = "sd_vis" if not os.path.exists(output_dir): os.mkdir(output_dir) token_choosen=(15, 15) vis_img = img_transform(image) visualize_sd_dino_att( ori_img=vis_img, # [1,3,H,W],归一化 0-1 float self_att=self_att, # (4096,4096) sim_dino_soft=sim_dino, # (4096,4096) sim_dino_refined=refined_sim_dino, # (4096,4096) token_choosen=token_choosen, filename=os.path.join(output_dir, f"vis.png"), attn_map_hw=(35, 35), vis_hw=(560, 560) ) # visualize_sd_self_att(sd_img, self_att, (30,30), os.path.join(output_dir,"vis.png"),)