|
|
| 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 |
|
|
|
|
| class SDNormalize(object): |
| def __call__(self, img): |
| return 2.0 * img - 1.0 |
|
|
|
|
| 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_self_att_raw( |
| ori_img, self_att_raw, token_choosen, output_dir, attn_map_hw=(35, 35), vis_hw=(560, 560) |
| ): |
| """ |
| 可视化self_att_raw中所有注意力图的token choosen位置的结果。 |
| 每幅图单独保存。 |
| :param ori_img: 输入图像 |
| :param self_att_raw: 原始注意力图,形状[10, 1225, 1225] |
| :param token_choosen: 选择的token坐标 (row, col) |
| :param output_dir: 输出文件名前缀 |
| :param attn_map_hw: 注意力图的分辨率 (H, W) |
| :param vis_hw: 可视化图像的分辨率 (H, W) |
| """ |
| |
| if isinstance(ori_img, torch.Tensor): |
| img = ori_img |
| if img.ndim == 4: |
| img = img[0] |
| img = img.cpu().numpy() |
| img = np.transpose(img, (1, 2, 0)) |
| 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: |
| img = img[:, :, :3] |
| img_resized = cv2.resize(img, vis_hw, interpolation=cv2.INTER_LINEAR) |
|
|
| |
| 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=13, color=(0, 0, 0), thickness=-1) |
| cv2.circle(img_with_dot, (x_vis, y_vis), radius=11, color=(255, 0, 0), thickness=-1) |
|
|
| |
| num_layers = self_att_raw.shape[0] |
| for i in range(num_layers): |
| layer_att_map = self_att_raw[i, row * w_attn + col].to(torch.float32).detach().cpu().numpy().reshape(h_attn, w_attn) |
| layer_att_map = (layer_att_map - layer_att_map.min()) / (layer_att_map.max() - layer_att_map.min() + 1e-8) |
| layer_att_map_up = cv2.resize(layer_att_map, vis_hw, interpolation=cv2.INTER_LINEAR) |
|
|
| |
| fig, axs = plt.subplots(1, 2, figsize=(12, 6)) |
| axs[0].imshow(img_with_dot) |
| axs[0].set_title(f"Original (with token) - Layer {i}") |
| axs[0].axis('off') |
|
|
| axs[1].imshow(layer_att_map_up, cmap='jet') |
| axs[1].set_title(f"Self-Attention (Layer {i})") |
| axs[1].axis('off') |
|
|
| plt.tight_layout() |
|
|
| |
| output_path = os.path.join(output_dir,f"layer_{i}.png") |
| plt.savefig(output_path, dpi=200, bbox_inches='tight') |
| plt.close() |
|
|
| 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自相关 |
| """ |
| |
| |
| if isinstance(ori_img, torch.Tensor): |
| img = ori_img |
| if img.ndim == 4: |
| img = img[0] |
| img = img.cpu().numpy() |
| img = np.transpose(img, (1, 2, 0)) |
| 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: |
| img = img[:, :, :3] |
| img_resized = cv2.resize(img, vis_hw, interpolation=cv2.INTER_LINEAR) |
|
|
| |
| 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=13, color=(0, 0, 0), thickness=-1) |
|
|
| |
| cv2.circle(img_with_dot, (x_vis, y_vis), radius=11, color=(255, 0, 0), thickness=-1) |
|
|
| |
| 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) |
|
|
| |
| 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) |
|
|
| |
| 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) |
|
|
| |
| 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() |
|
|
| with torch.no_grad(): |
| attention_layers_to_use= [-4, -6] |
| sd_version='v2.1' |
| time_step=45 |
| device="cuda:6" |
| |
| |
|
|
| |
| |
| dino=build_DINOv2().to(device) |
| sd=diffusion(attention_layers_to_use=attention_layers_to_use,model=sd_version, time_step=time_step, device=device,dtype=torch.float16) |
| |
| |
| |
| image_root='/mnt/SSD8T/home/wjj/dataset/standard_coco/train2017' |
| image_file=os.listdir(image_root)[999] |
| image_name=os.path.join(image_root, image_file) |
| |
| image = Image.open("demo_images/bird.jpg") |
| 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]) |
| sd_transform=transforms.Compose([ResizeLongest(560, fill=0), _convert_to_rgb,ToTensor(), SDNormalize()]) |
| img_transform=transforms.Compose([ResizeLongest(560, fill=0)]) |
| dino_img=DINO_transform(image).unsqueeze(0).to(torch.float16).to(device) |
| sd_img = sd_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 = F.normalize(dino_feats_raw, dim=2) |
| sim_dino = torch.einsum('bic,bjc->bij', dino_feats, dino_feats).squeeze(0) |
| |
| |
| sd.forward_wo_preprocess(sd_img, "") |
| vis_img=img_transform(image) |
| self_att_raw = torch.cat([sd.attention_maps[idx] for idx in attention_layers_to_use]).float() |
|
|
| self_att = self_att_raw / torch.amax(self_att_raw, dim=-2, keepdim=True) + 1e-5 |
| self_att = torch.where(self_att < 0.2, 0, self_att) |
| self_att /= self_att.sum(dim=-1, keepdim=True) + 1e-5 |
| self_att = reduce(torch.matmul, self_att, torch.eye(self_att.shape[-1], device=self_att.device)).to(sim_dino.dtype) |
| refined_sim_dino = self_att @ sim_dino @ self_att.transpose(0, 1) |
| alpha = 0.8 |
| refined_sim_dino = (1 - alpha) * sim_dino + alpha * refined_sim_dino |
|
|
| output_dir = "sd_vis" |
| if not os.path.exists(output_dir): |
| os.mkdir(output_dir) |
|
|
| token_choosen=(12, 20) |
|
|
| visualize_sd_dino_att( |
| ori_img=vis_img, |
| self_att=self_att, |
| sim_dino_soft=sim_dino, |
| sim_dino_refined=refined_sim_dino, |
| token_choosen=token_choosen, |
| filename=os.path.join(output_dir, f"vis.png"), |
| attn_map_hw=(35, 35), |
| vis_hw=(560, 560) |
| ) |
| visualize_self_att_raw( |
| ori_img=vis_img, |
| self_att_raw=self_att_raw, |
| token_choosen=token_choosen, |
| output_dir=output_dir, |
| attn_map_hw=(35, 35), |
| vis_hw=(560, 560) |
| ) |