Repository navigation
Expand file tree
/
Copy pathdiff_vis.py
More file actions
392 lines (315 loc) · 14.9 KB
/
Copy pathdiff_vis.py
File metadata and controls
392 lines (315 loc) · 14.9 KB
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
import torch
import torch.nn.functional as F
import numpy as np
import argparse
import os
import sys
from glob import glob
from PIL import Image
from tqdm import tqdm
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
# 添加 vae 目录到路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'vae'))
from models import DiT_models
from diffusion import create_diffusion
from torchvision import transforms
from vae.OptimalSkipVAE_orig import OptimalSkipVAE
def preprocess_image(pil_img, target_size=1024):
"""图像预处理:调整大小到 1024 并添加padding"""
w, h = pil_img.size
scale = target_size / max(w, h)
new_w, new_h = int(w * scale), int(h * scale)
resized_img = pil_img.resize((new_w, new_h), resample=Image.BICUBIC)
new_img = Image.new("RGB", (target_size, target_size), (0, 0, 0))
new_img.paste(resized_img, (0, 0))
pixel_mask = np.zeros((target_size, target_size), dtype=np.float32)
pixel_mask[:new_h, :new_w] = 1.0
info = {"new_w": new_w, "new_h": new_h, "orig_w": w, "orig_h": h}
return new_img, torch.from_numpy(pixel_mask), info
def postprocess_image(pil_img, info):
"""图像后处理:裁剪到原始尺寸"""
valid_area = pil_img.crop((0, 0, info['new_w'], info['new_h']))
final_img = valid_area.resize((info['orig_w'], info['orig_h']), resample=Image.BICUBIC)
return final_img
def pca_to_rgb(feature_map, n_components=3):
"""
使用PCA将高维特征降维到3通道RGB
feature_map: [B, C, H, W]
return: [B, 3, H, W] 归一化到 [0, 1]
"""
B, C, H, W = feature_map.shape
# reshape 为 [B*H*W, C]
feat_flat = feature_map.permute(0, 2, 3, 1).reshape(-1, C).cpu().numpy()
# PCA 降维
pca = PCA(n_components=n_components)
feat_pca = pca.fit_transform(feat_flat)
# reshape 回图像格式 [B, H, W, 3]
feat_pca = feat_pca.reshape(B, H, W, n_components)
# 归一化到 [0, 1]
for i in range(n_components):
feat_pca[..., i] = (feat_pca[..., i] - feat_pca[..., i].min()) / \
(feat_pca[..., i].max() - feat_pca[..., i].min() + 1e-8)
# 转为 tensor [B, 3, H, W]
feat_rgb = torch.from_numpy(feat_pca).permute(0, 3, 1, 2).float()
return feat_rgb
def compute_feature_diff_mean(feat1, feat2):
"""
方案1: 计算通道均值的绝对差异
feat1, feat2: [B, C, H, W]
return: [B, 1, H, W]
"""
# 对齐空间尺寸
if feat1.shape[-2:] != feat2.shape[-2:]:
feat2 = F.interpolate(feat2, size=feat1.shape[-2:], mode='bilinear', align_corners=False)
diff = torch.abs(feat1 - feat2).mean(dim=1, keepdim=True)
return diff
def visualize_feature_analysis(input_img, skip_1x, dec_1x, skip_2x, dec_2x, skip_4x, dec_4x,
attention_mask, save_path):
"""
可视化特征差异分析:
- 方案1: 通道均值差异图 (1x, 2x, 4x)
- 方案3: PCA降维可视化 (1x, 2x, 4x)
"""
# 计算差异
diff_1x_mean = compute_feature_diff_mean(skip_1x, dec_1x)
diff_2x_mean = compute_feature_diff_mean(skip_2x, dec_2x)
diff_4x_mean = compute_feature_diff_mean(skip_4x, dec_4x)
# PCA 降维
pca_1x = pca_to_rgb(skip_1x)
pca_dec_1x = pca_to_rgb(dec_1x)
pca_2x = pca_to_rgb(skip_2x)
pca_dec_2x = pca_to_rgb(dec_2x)
pca_4x = pca_to_rgb(skip_4x)
pca_dec_4x = pca_to_rgb(dec_4x)
# 创建 3x4 布局
fig, axes = plt.subplots(3, 4, figsize=(20, 15))
# ========== 第一行: 1x 尺度 ==========
# 输入图像
axes[0, 0].imshow(input_img)
axes[0, 0].set_title('Input Image', fontsize=12)
axes[0, 0].axis('off')
# 1x 均值差异热力图
diff_1x_np = diff_1x_mean.squeeze().cpu().numpy()
im1 = axes[0, 1].imshow(diff_1x_np, cmap='hot')
axes[0, 1].set_title(f'1x Mean Diff (max={diff_1x_np.max():.3f})', fontsize=12)
axes[0, 1].axis('off')
plt.colorbar(im1, ax=axes[0, 1], fraction=0.046)
# Skip 1x PCA
pca_1x_np = pca_1x[0].permute(1, 2, 0).cpu().numpy()
axes[0, 2].imshow(pca_1x_np)
axes[0, 2].set_title(f'Skip 1x PCA (C={skip_1x.shape[1]})', fontsize=12)
axes[0, 2].axis('off')
# Decoder 1x PCA
pca_dec_1x_np = pca_dec_1x[0].permute(1, 2, 0).cpu().numpy()
axes[0, 3].imshow(pca_dec_1x_np)
axes[0, 3].set_title(f'Decoder 1x PCA (C={dec_1x.shape[1]})', fontsize=12)
axes[0, 3].axis('off')
# ========== 第二行: 2x 尺度 ==========
# Attention Mask
mask_np = attention_mask.squeeze().cpu().numpy()
axes[1, 0].imshow(mask_np, cmap='gray')
axes[1, 0].set_title('Predicted Mask', fontsize=12)
axes[1, 0].axis('off')
# 2x 均值差异热力图
diff_2x_np = diff_2x_mean.squeeze().cpu().numpy()
im2 = axes[1, 1].imshow(diff_2x_np, cmap='hot')
axes[1, 1].set_title(f'2x Mean Diff (max={diff_2x_np.max():.3f})', fontsize=12)
axes[1, 1].axis('off')
plt.colorbar(im2, ax=axes[1, 1], fraction=0.046)
# Skip 2x PCA
pca_2x_np = pca_2x[0].permute(1, 2, 0).cpu().numpy()
axes[1, 2].imshow(pca_2x_np)
axes[1, 2].set_title(f'Skip 2x PCA (C={skip_2x.shape[1]})', fontsize=12)
axes[1, 2].axis('off')
# Decoder 2x PCA
pca_dec_2x_np = pca_dec_2x[0].permute(1, 2, 0).cpu().numpy()
axes[1, 3].imshow(pca_dec_2x_np)
axes[1, 3].set_title(f'Decoder 2x PCA (C={dec_2x.shape[1]})', fontsize=12)
axes[1, 3].axis('off')
# ========== 第三行: 4x 尺度 ==========
# 4x 标签
axes[2, 0].text(0.5, 0.5, '4x Scale\n(Latent Level)',
ha='center', va='center', fontsize=14, transform=axes[2, 0].transAxes)
axes[2, 0].set_title('Scale Info', fontsize=12)
axes[2, 0].axis('off')
# 4x 均值差异热力图
diff_4x_np = diff_4x_mean.squeeze().cpu().numpy()
im4 = axes[2, 1].imshow(diff_4x_np, cmap='hot')
axes[2, 1].set_title(f'4x Mean Diff (max={diff_4x_np.max():.3f})', fontsize=12)
axes[2, 1].axis('off')
plt.colorbar(im4, ax=axes[2, 1], fraction=0.046)
# Skip 4x PCA
pca_4x_np = pca_4x[0].permute(1, 2, 0).cpu().numpy()
axes[2, 2].imshow(pca_4x_np)
axes[2, 2].set_title(f'Skip 4x PCA (C={skip_4x.shape[1]})', fontsize=12)
axes[2, 2].axis('off')
# Decoder 4x PCA
pca_dec_4x_np = pca_dec_4x[0].permute(1, 2, 0).cpu().numpy()
axes[2, 3].imshow(pca_dec_4x_np)
axes[2, 3].set_title(f'Decoder 4x PCA (C={dec_4x.shape[1]})', fontsize=12)
axes[2, 3].axis('off')
plt.tight_layout()
plt.savefig(save_path, dpi=150, bbox_inches='tight')
plt.close()
# 打印统计信息
print(f" Feature Diff Stats:")
print(f" 1x: mean={diff_1x_np.mean():.4f}, std={diff_1x_np.std():.4f}, max={diff_1x_np.max():.4f}")
print(f" 2x: mean={diff_2x_np.mean():.4f}, std={diff_2x_np.std():.4f}, max={diff_2x_np.max():.4f}")
print(f" 4x: mean={diff_4x_np.mean():.4f}, std={diff_4x_np.std():.4f}, max={diff_4x_np.max():.4f}")
def extract_features(skip_vae, x_marked_512, z_dit_512):
"""
提取中间层特征用于可视化 (1x, 2x, 4x 三个尺度)
"""
with torch.no_grad():
# ================= 1. Encoder =================
x = skip_vae.vae.encoder.conv_in(x_marked_512)
skip_1x = x
for resnet in skip_vae.vae.encoder.down_blocks[0].resnets:
skip_1x = resnet(skip_1x, temb=None)
x = skip_vae.vae.encoder.down_blocks[0](x)
skip_2x = x
for resnet in skip_vae.vae.encoder.down_blocks[1].resnets:
skip_2x = resnet(skip_2x, temb=None)
# 4x 下采样层级
x = skip_vae.vae.encoder.down_blocks[1](x)
skip_4x = x
for resnet in skip_vae.vae.encoder.down_blocks[2].resnets:
skip_4x = resnet(skip_4x, temb=None)
# ================= 2. Decoder =================
decoder = skip_vae.vae.decoder
x = skip_vae.vae.post_quant_conv(z_dit_512)
x = decoder.conv_in(x)
x = decoder.mid_block(x, temb=None)
# 从 up_blocks 提取不同尺度特征
num_up_blocks = len(decoder.up_blocks)
dec_4x = None
dec_2x = None
for i, block in enumerate(decoder.up_blocks):
# 4x 层级 (倒数第3个block)
if i == num_up_blocks - 3:
temp_x = x
for resnet in block.resnets:
temp_x = resnet(temp_x, temb=None)
dec_4x = temp_x
# 2x 层级 (倒数第2个block)
if i == num_up_blocks - 2:
temp_x = x
for resnet in block.resnets:
temp_x = resnet(temp_x, temb=None)
dec_2x = temp_x
x = block(x)
dec_1x = decoder.conv_norm_out(x)
dec_1x = decoder.conv_act(dec_1x)
return skip_1x, skip_2x, skip_4x, dec_1x, dec_2x, dec_4x
def inference_with_feature_vis(model, skip_vae, diffusion, input_img_path, args, device):
"""推理并可视化特征差异"""
# 1. 加载并处理图像
input_img = Image.open(input_img_path).convert("RGB")
padded_img, pixel_mask, info = preprocess_image(input_img, target_size=args.image_size)
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
])
x_1024 = transform(padded_img).unsqueeze(0).to(device)
pixel_mask = pixel_mask.unsqueeze(0).unsqueeze(0).to(device)
if hasattr(skip_vae.vae, 'dtype'):
target_dtype = skip_vae.vae.dtype
x_1024 = x_1024.to(target_dtype)
pixel_mask = pixel_mask.to(target_dtype)
with torch.no_grad():
# 下采样到 512
x_512 = F.interpolate(x_1024, size=(512, 512), mode='bilinear', align_corners=False)
cond_latent = skip_vae.vae.encode(x_512).latent_dist.mode().mul_(args.mul_num)
B, C, H_lat, W_lat = cond_latent.shape
latent_mask = F.interpolate(pixel_mask, size=(H_lat, W_lat), mode='nearest')
patch_size = model.patch_size if hasattr(model, "patch_size") else 2
H_token, W_token = H_lat // patch_size, W_lat // patch_size
token_mask = F.interpolate(latent_mask, size=(H_token, W_token), mode='nearest')
attention_mask = token_mask.flatten(2).squeeze(1)
z = torch.randn_like(cond_latent)
def model_fn(x_t, t, **kwargs):
out = model(x_t, t, condition=kwargs['cond'], attention_mask=kwargs['mask'])
if out.shape[1] == 8:
out, _ = torch.split(out, 4, dim=1)
return out
samples = diffusion.p_sample_loop(
model_fn, z.shape, z, clip_denoised=False,
model_kwargs=dict(cond=cond_latent, mask=attention_mask),
progress=True, device=device
)
samples = samples / args.mul_num
# 提取特征
skip_1x, skip_2x, skip_4x, dec_1x, dec_2x, dec_4x = extract_features(skip_vae, x_512, samples)
# 获取预测 mask
skip_vae.eval()
_, pred_bg_mask_512, _, _ = skip_vae.forward_2x(x_1024, samples)
pred_mark_mask_512 = 1.0 - pred_bg_mask_512
# 上采样 mask 到 512 用于可视化
pred_mask_512 = F.interpolate(pred_mark_mask_512, size=(512, 512), mode='bilinear')
return input_img, skip_1x, dec_1x, skip_2x, dec_2x, skip_4x, dec_4x, pred_mask_512, info
def main(args):
torch.set_grad_enabled(False)
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using device: {device}")
os.makedirs(args.output_dir, exist_ok=True)
print(f"Loading models...")
skip_vae = OptimalSkipVAE(args.vae_path, device=device)
if args.skip_weights and os.path.exists(args.skip_weights):
print(f" Loading skip weights from {args.skip_weights}...")
skip_vae.load_weights(args.skip_weights)
latent_size = args.image_size // args.vae_scale_factor
model = DiT_models[args.model](input_size=latent_size, in_channels=8, learn_sigma=False).to(device)
ckpt = torch.load(args.checkpoint, map_location=device, weights_only=False)
state_dict = ckpt["ema"] if "ema" in ckpt else ckpt["model"]
model.load_state_dict(state_dict)
model.eval()
diffusion = create_diffusion(str(args.num_sampling_steps), learn_sigma=False)
if os.path.isdir(args.input):
input_files = sorted(glob(os.path.join(args.input, "*.*")))
else:
input_files = [args.input]
print(f"Found {len(input_files)} images to process")
for input_path in tqdm(input_files):
try:
filename = os.path.basename(input_path)
name, _ = os.path.splitext(filename)
print(f"\nProcessing: {filename}")
# 推理并提取特征
input_img, skip_1x, dec_1x, skip_2x, dec_2x, skip_4x, dec_4x, pred_mask, info = \
inference_with_feature_vis(model, skip_vae, diffusion, input_path, args, device)
# 可视化
vis_path = os.path.join(args.output_dir, f"{name}_feature_analysis.png")
visualize_feature_analysis(input_img, skip_1x, dec_1x, skip_2x, dec_2x, skip_4x, dec_4x,
pred_mask, vis_path)
print(f" Saved: {vis_path}")
except Exception as e:
print(f"Error processing {input_path}: {e}")
import traceback
traceback.print_exc()
continue
print("\n[ok] feature analysis complete!")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Feature Difference Visualization")
parser.add_argument("--input", type=str, required=False, default='./example/marked',
help="Input image path or directory")
parser.add_argument("--output-dir", type=str, default="./vis/feature_analysis",
help="Output directory for visualizations")
parser.add_argument("--checkpoint", type=str, default="./DiT_ckpt/epoch_1000.pt",
help="Path to DiT model checkpoint")
parser.add_argument("--vae-path", type=str, default="./vae/mri_vae",
help="Path to base VAE model")
parser.add_argument("--skip-weights", type=str, default="./vae/orig/skip_vae_best_orig.pt",
help="Path to OptimalSkipVAE trained weights")
parser.add_argument("--model", type=str, default="DiT-S/2",
help="DiT model architecture")
parser.add_argument("--image-size", type=int, default=1024,
help="Input image size")
parser.add_argument("--vae-scale-factor", type=int, default=4,
help="VAE downsampling factor")
parser.add_argument("--mul-num", type=float, default=1.551750,
help="VAE latent scaling factor")
parser.add_argument("--num-sampling-steps", type=int, default=10,
help="Number of diffusion sampling steps")
args = parser.parse_args()
main(args)