xiaomoguhzz commited on
Commit
9d792af
·
verified ·
1 Parent(s): 9df6813

Upload code/model_vis_tools/vis_sd_featsv5.py with huggingface_hub

Browse files
code/model_vis_tools/vis_sd_featsv5.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from diffusion_model.stable_diffusion import diffusion
3
+ import torch
4
+ import numpy as np
5
+ import os
6
+ from PIL import Image
7
+ from pycocotools.coco import COCO
8
+ from torchvision.transforms import Normalize, Compose, RandomResizedCrop, InterpolationMode, ToTensor, Resize, \
9
+ CenterCrop
10
+ from open_clip.transform import ResizeLongest, _convert_to_rgb
11
+ from torchvision import transforms
12
+ import matplotlib.pyplot as plt
13
+ import cv2
14
+ from functools import reduce
15
+ import torch.nn.functional as F
16
+
17
+
18
+ class SDNormalize(object):
19
+ def __call__(self, img):
20
+ return 2.0 * img - 1.0
21
+
22
+
23
+ def build_DINOv2():
24
+ model_name='dinov2_vitb14_reg'
25
+ hub_path = '/mnt/SSD8T/home/wjj/.cache/torch/hub/facebookresearch_dinov2_main'
26
+ try:
27
+ vfm = torch.hub.load(hub_path, model_name, source='local').half()
28
+ except Exception as e:
29
+ raise RuntimeError(f"Failed to load DINOv2 model '{model_name}': {e}")
30
+ return vfm
31
+
32
+ def visualize_self_att_raw(
33
+ ori_img, self_att_raw, token_choosen, output_dir, attn_map_hw=(35, 35), vis_hw=(560, 560)
34
+ ):
35
+ """
36
+ 可视化self_att_raw中所有注意力图的token choosen位置的结果。
37
+ 每幅图单独保存。
38
+ :param ori_img: 输入图像
39
+ :param self_att_raw: 原始注意力图,形状[10, 1225, 1225]
40
+ :param token_choosen: 选择的token坐标 (row, col)
41
+ :param output_dir: 输出文件名前缀
42
+ :param attn_map_hw: 注意力图的分辨率 (H, W)
43
+ :param vis_hw: 可视化图像的分辨率 (H, W)
44
+ """
45
+ # 1. 原图
46
+ if isinstance(ori_img, torch.Tensor):
47
+ img = ori_img
48
+ if img.ndim == 4: # [1,3,H,W] -> [3,H,W]
49
+ img = img[0]
50
+ img = img.cpu().numpy()
51
+ img = np.transpose(img, (1, 2, 0)) # [H, W, 3]
52
+ img = (img * 255).clip(0, 255).astype(np.uint8)
53
+ elif isinstance(ori_img, Image.Image):
54
+ img = np.array(ori_img)
55
+ if img.dtype != np.uint8:
56
+ img = (img * 255).clip(0, 255).astype(np.uint8)
57
+ elif isinstance(ori_img, np.ndarray):
58
+ img = ori_img
59
+ if img.dtype != np.uint8:
60
+ img = (img * 255).clip(0, 255).astype(np.uint8)
61
+ else:
62
+ raise ValueError("ori_img should be torch.Tensor, PIL.Image, or np.ndarray")
63
+ if img.shape[2] == 4: # RGBA to RGB
64
+ img = img[:, :, :3]
65
+ img_resized = cv2.resize(img, vis_hw, interpolation=cv2.INTER_LINEAR)
66
+
67
+ # 2. token坐标
68
+ h_attn, w_attn = attn_map_hw
69
+ row, col = token_choosen
70
+ y_vis = int((row + 0.5) * vis_hw[0] / h_attn)
71
+ x_vis = int((col + 0.5) * vis_hw[1] / w_attn)
72
+
73
+ img_with_dot = img_resized.copy()
74
+ cv2.circle(img_with_dot, (x_vis, y_vis), radius=13, color=(0, 0, 0), thickness=-1) # 黑色圆
75
+ cv2.circle(img_with_dot, (x_vis, y_vis), radius=11, color=(255, 0, 0), thickness=-1) # 红色圆
76
+
77
+ # 3. 遍历 self_att_raw
78
+ num_layers = self_att_raw.shape[0]
79
+ for i in range(num_layers):
80
+ layer_att_map = self_att_raw[i, row * w_attn + col].to(torch.float32).detach().cpu().numpy().reshape(h_attn, w_attn)
81
+ layer_att_map = (layer_att_map - layer_att_map.min()) / (layer_att_map.max() - layer_att_map.min() + 1e-8)
82
+ layer_att_map_up = cv2.resize(layer_att_map, vis_hw, interpolation=cv2.INTER_LINEAR)
83
+
84
+ # 绘制图像
85
+ fig, axs = plt.subplots(1, 2, figsize=(12, 6))
86
+ axs[0].imshow(img_with_dot)
87
+ axs[0].set_title(f"Original (with token) - Layer {i}")
88
+ axs[0].axis('off')
89
+
90
+ axs[1].imshow(layer_att_map_up, cmap='jet')
91
+ axs[1].set_title(f"Self-Attention (Layer {i})")
92
+ axs[1].axis('off')
93
+
94
+ plt.tight_layout()
95
+
96
+ # 保存每一层的可视化结果
97
+ output_path = os.path.join(output_dir,f"layer_{i}.png")
98
+ plt.savefig(output_path, dpi=200, bbox_inches='tight')
99
+ plt.close()
100
+
101
+ def visualize_sd_dino_att(
102
+ ori_img, self_att, sim_dino_soft, sim_dino_refined,
103
+ token_choosen, filename, attn_map_hw=(64, 64), vis_hw=(512, 512)
104
+ ):
105
+ """
106
+ 可视化SD传播对DINO自相关的细化效果, 4列分别为:
107
+ 1. 原图带token
108
+ 2. SD自注意力传播
109
+ 3. DINO自相关
110
+ 4. 细化后的DINO自相关
111
+ """
112
+ # 1. 原图
113
+ # 支持PIL.Image、np.ndarray、tensor三种输入
114
+ if isinstance(ori_img, torch.Tensor):
115
+ img = ori_img
116
+ if img.ndim == 4: # [1,3,H,W] -> [3,H,W]
117
+ img = img[0]
118
+ img = img.cpu().numpy()
119
+ img = np.transpose(img, (1, 2, 0)) # [H, W, 3]
120
+ img = (img * 255).clip(0, 255).astype(np.uint8)
121
+ elif isinstance(ori_img, Image.Image):
122
+ img = np.array(ori_img)
123
+ if img.dtype != np.uint8:
124
+ img = (img * 255).clip(0, 255).astype(np.uint8)
125
+ elif isinstance(ori_img, np.ndarray):
126
+ img = ori_img
127
+ if img.dtype != np.uint8:
128
+ img = (img * 255).clip(0, 255).astype(np.uint8)
129
+ else:
130
+ raise ValueError("ori_img should be torch.Tensor, PIL.Image, or np.ndarray")
131
+ if img.shape[2] == 4: # RGBA to RGB
132
+ img = img[:, :, :3]
133
+ img_resized = cv2.resize(img, vis_hw, interpolation=cv2.INTER_LINEAR)
134
+
135
+ # 2. token坐标
136
+ h_attn, w_attn = attn_map_hw
137
+ row, col = token_choosen
138
+ y_vis = int((row + 0.5) * vis_hw[0] / h_attn)
139
+ x_vis = int((col + 0.5) * vis_hw[1] / w_attn)
140
+ img_with_dot = img_resized.copy()
141
+ # 绘制黑色边缘的圆
142
+ cv2.circle(img_with_dot, (x_vis, y_vis), radius=13, color=(0, 0, 0), thickness=-1) # 黑色圆
143
+
144
+ # 绘制红点
145
+ cv2.circle(img_with_dot, (x_vis, y_vis), radius=11, color=(255, 0, 0), thickness=-1) # 红色圆
146
+
147
+ # 3. SD自注意力传播
148
+ att_map_sd = self_att[row * w_attn + col].to(torch.float32).detach().cpu().numpy().reshape(h_attn, w_attn)
149
+ att_map_sd = (att_map_sd - att_map_sd.min()) / (att_map_sd.max() - att_map_sd.min() + 1e-8)
150
+ att_map_sd_up = cv2.resize(att_map_sd, vis_hw, interpolation=cv2.INTER_LINEAR)
151
+
152
+ # 4. DINO自相关(传播前)
153
+ att_map_dino = sim_dino_soft[row * w_attn + col].detach().cpu().numpy().reshape(h_attn, w_attn)
154
+ att_map_dino = (att_map_dino - att_map_dino.min()) / (att_map_dino.max() - att_map_dino.min() + 1e-8)
155
+ att_map_dino = att_map_dino.astype(np.float32)
156
+ att_map_dino_up = cv2.resize(att_map_dino, vis_hw, interpolation=cv2.INTER_LINEAR)
157
+
158
+ # 5. DINO传播后
159
+ att_map_dino_ref = sim_dino_refined[row * w_attn + col].detach().cpu().numpy().reshape(h_attn, w_attn)
160
+ 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)
161
+ att_map_dino_ref = att_map_dino_ref.astype(np.float32)
162
+ att_map_dino_ref_up = cv2.resize(att_map_dino_ref, vis_hw, interpolation=cv2.INTER_LINEAR)
163
+
164
+ # 6. 绘图
165
+ fig, axs = plt.subplots(1, 4, figsize=(18, 5))
166
+
167
+ axs[0].imshow(img_with_dot)
168
+ axs[0].set_title("Original (with token)")
169
+ axs[0].axis('off')
170
+
171
+ axs[1].imshow(att_map_sd_up, cmap='jet')
172
+ axs[1].set_title(f'SD propagation (token {token_choosen})')
173
+ axs[1].axis('off')
174
+
175
+ axs[2].imshow(att_map_dino_up, cmap='jet')
176
+ axs[2].set_title(f'DINO sim (pre-propagate)')
177
+ axs[2].axis('off')
178
+
179
+ axs[3].imshow(att_map_dino_ref_up, cmap='jet')
180
+ axs[3].set_title(f'DINO sim (post-propagate)')
181
+ axs[3].axis('off')
182
+
183
+ plt.tight_layout()
184
+ plt.savefig(filename, dpi=200, bbox_inches='tight')
185
+ plt.close()
186
+
187
+ with torch.no_grad():
188
+ attention_layers_to_use= [-4, -6]
189
+ sd_version='v2.1'
190
+ time_step=45
191
+ device="cuda:6"
192
+ # coco_path='/mnt/SSD8T/home/wjj/dataset/standard_coco/annotations/instances_train2017.json'
193
+ # img_path='/mnt/SSD8T/home/wjj/dataset/standard_coco/train2017'
194
+
195
+ # coco=COCO(coco_path)
196
+ # image_ids=load_data(coco)
197
+ dino=build_DINOv2().to(device)
198
+ sd=diffusion(attention_layers_to_use=attention_layers_to_use,model=sd_version, time_step=time_step, device=device,dtype=torch.float16)
199
+ # image_select=5
200
+ # img_name = coco.loadImgs(image_ids[image_select])[0]['file_name']
201
+ # image_path = os.path.join(img_path, img_name)
202
+ image_root='/mnt/SSD8T/home/wjj/dataset/standard_coco/train2017'
203
+ image_file=os.listdir(image_root)[999]
204
+ image_name=os.path.join(image_root, image_file)
205
+ # image = Image.open('demo_images/horses.jpg')
206
+ image = Image.open("demo_images/bird.jpg")
207
+ mean=[0.485, 0.456, 0.406]
208
+ std=[0.229, 0.224, 0.225]
209
+
210
+ normalize = Normalize(mean=mean, std=std)
211
+ DINO_transform=transforms.Compose([
212
+ ResizeLongest(490, fill=0),
213
+ _convert_to_rgb,
214
+ ToTensor(),
215
+ normalize])
216
+ sd_transform=transforms.Compose([ResizeLongest(560, fill=0), _convert_to_rgb,ToTensor(), SDNormalize()])
217
+ img_transform=transforms.Compose([ResizeLongest(560, fill=0)])
218
+ dino_img=DINO_transform(image).unsqueeze(0).to(torch.float16).to(device)
219
+ sd_img = sd_transform(image).unsqueeze(0).to(torch.float16).to(device)
220
+
221
+ # dino_feats_raw=dino.get_intermediate_layers(dino_img, reshape=True)[0].flatten(start_dim=-2).transpose(-2,-1)
222
+ dino_feats_raw=dino.get_intermediate_layers(dino_img, reshape=True)[0].flatten(start_dim=-2).transpose(-2,-1)
223
+ dino_feats = F.normalize(dino_feats_raw, dim=2)
224
+ sim_dino = torch.einsum('bic,bjc->bij', dino_feats, dino_feats).squeeze(0)
225
+ # sd preprocess
226
+ # 1.
227
+ sd.forward_wo_preprocess(sd_img, "")
228
+ vis_img=img_transform(image)
229
+ self_att_raw = torch.cat([sd.attention_maps[idx] for idx in attention_layers_to_use]).float()
230
+
231
+ self_att = self_att_raw / torch.amax(self_att_raw, dim=-2, keepdim=True) + 1e-5
232
+ self_att = torch.where(self_att < 0.2, 0, self_att)
233
+ self_att /= self_att.sum(dim=-1, keepdim=True) + 1e-5
234
+ self_att = reduce(torch.matmul, self_att, torch.eye(self_att.shape[-1], device=self_att.device)).to(sim_dino.dtype)
235
+ refined_sim_dino = self_att @ sim_dino @ self_att.transpose(0, 1)
236
+ alpha = 0.8
237
+ refined_sim_dino = (1 - alpha) * sim_dino + alpha * refined_sim_dino
238
+
239
+ output_dir = "sd_vis"
240
+ if not os.path.exists(output_dir):
241
+ os.mkdir(output_dir)
242
+
243
+ token_choosen=(12, 20)
244
+
245
+ visualize_sd_dino_att(
246
+ ori_img=vis_img, # [1,3,H,W],归一化 0-1 float
247
+ self_att=self_att, # (4096,4096)
248
+ sim_dino_soft=sim_dino, # (4096,4096)
249
+ sim_dino_refined=refined_sim_dino, # (4096,4096)
250
+ token_choosen=token_choosen,
251
+ filename=os.path.join(output_dir, f"vis.png"),
252
+ attn_map_hw=(35, 35),
253
+ vis_hw=(560, 560)
254
+ )
255
+ visualize_self_att_raw(
256
+ ori_img=vis_img,
257
+ self_att_raw=self_att_raw,
258
+ token_choosen=token_choosen,
259
+ output_dir=output_dir,
260
+ attn_map_hw=(35, 35),
261
+ vis_hw=(560, 560)
262
+ )