recoilme commited on
Commit
c62f7d0
·
1 Parent(s): 8308d70
eval.py ADDED
@@ -0,0 +1,515 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import random
4
+ from typing import Dict, List, Tuple, Optional, Any
5
+
6
+ import numpy as np
7
+ from PIL import Image
8
+ from tqdm import tqdm
9
+
10
+ import torch
11
+ import torch.nn.functional as F
12
+ from torch.utils.data import Dataset, DataLoader
13
+ from torchvision.transforms import Compose, Resize, ToTensor, CenterCrop
14
+ from torchvision.utils import save_image
15
+ import lpips
16
+
17
+ from diffusers import (
18
+ AutoencoderKL,
19
+ AutoencoderKLWan,
20
+ AutoencoderKLLTXVideo,
21
+ AutoencoderKLQwenImage
22
+ )
23
+
24
+ from scipy.stats import skew, kurtosis
25
+
26
+
27
+ # ========================== Конфиг ==========================
28
+ DEVICE = "cuda"
29
+ DTYPE = torch.float16
30
+ IMAGE_FOLDER = "/home/recoilme/dataset/alchemist"
31
+ MIN_SIZE = 1280
32
+ CROP_SIZE = 512
33
+ BATCH_SIZE = 5
34
+ MAX_IMAGES = 0
35
+ NUM_WORKERS = 4
36
+ SAMPLES_DIR = "test"
37
+
38
+ VAE_LIST = [
39
+ ("SD15 VAE", AutoencoderKL, "stable-diffusion-v1-5/stable-diffusion-v1-5", "vae"),
40
+ ("SDXL VAE fp16 fix", AutoencoderKL, "madebyollin/sdxl-vae-fp16-fix", None),
41
+ ("AiArtLab/sdxl_vae", AutoencoderKL, "AiArtLab/sdxl_vae", "vae"),
42
+ ("LTX-Video VAE", AutoencoderKLLTXVideo, "Lightricks/LTX-Video", "vae"),
43
+ ("Wan2.2-TI2V-5B", AutoencoderKLWan, "Wan-AI/Wan2.2-TI2V-5B-Diffusers", "vae"),
44
+ ("AiArtLab/wan16x_vae", AutoencoderKLWan, "AiArtLab/wan16x_vae", "vae"),
45
+ ("Wan2.2-T2V-A14B", AutoencoderKLWan, "Wan-AI/Wan2.2-T2V-A14B-Diffusers", "vae"),
46
+ ("QwenImage", AutoencoderKLQwenImage, "Qwen/Qwen-Image", "vae"),
47
+ ("AuraDiffusion/16ch-vae", AutoencoderKL, "AuraDiffusion/16ch-vae", None),
48
+ ("FLUX.1-schnell VAE", AutoencoderKL, "black-forest-labs/FLUX.1-schnell", "vae"),
49
+ ("AiArtLab/simplevae", AutoencoderKL, "AiArtLab/simplevae", "vae"),
50
+ ]
51
+
52
+
53
+ # ========================== Утилиты ==========================
54
+ def to_neg1_1(x: torch.Tensor) -> torch.Tensor:
55
+ return x * 2 - 1
56
+
57
+
58
+ def to_0_1(x: torch.Tensor) -> torch.Tensor:
59
+ return (x + 1) * 0.5
60
+
61
+
62
+ def safe_psnr(mse: float) -> float:
63
+ if mse <= 1e-12:
64
+ return float("inf")
65
+ return 10.0 * float(np.log10(1.0 / mse))
66
+
67
+
68
+ def is_video_like_vae(vae) -> bool:
69
+ # Wan и LTX-Video ждут [B, C, T, H, W]
70
+ return isinstance(vae, (AutoencoderKLWan, AutoencoderKLLTXVideo,AutoencoderKLQwenImage))
71
+
72
+
73
+ def add_time_dim_if_needed(x: torch.Tensor, vae) -> torch.Tensor:
74
+ if is_video_like_vae(vae) and x.ndim == 4:
75
+ return x.unsqueeze(2) # -> [B, C, 1, H, W]
76
+ return x
77
+
78
+
79
+ def strip_time_dim_if_possible(x: torch.Tensor, vae) -> torch.Tensor:
80
+ if is_video_like_vae(vae) and x.ndim == 5 and x.shape[2] == 1:
81
+ return x.squeeze(2) # -> [B, C, H, W]
82
+ return x
83
+
84
+
85
+ @torch.no_grad()
86
+ def sobel_edge_l1(real_0_1: torch.Tensor, fake_0_1: torch.Tensor) -> float:
87
+ real = to_neg1_1(real_0_1)
88
+ fake = to_neg1_1(fake_0_1)
89
+ kx = torch.tensor([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], dtype=torch.float32, device=real.device).view(1, 1, 3, 3)
90
+ ky = torch.tensor([[-1, -2, -1], [0, 0, 0], [1, 2, 1]], dtype=torch.float32, device=real.device).view(1, 1, 3, 3)
91
+ C = real.shape[1]
92
+ kx = kx.to(real.dtype).repeat(C, 1, 1, 1)
93
+ ky = ky.to(real.dtype).repeat(C, 1, 1, 1)
94
+
95
+ def grad_mag(x):
96
+ gx = F.conv2d(x, kx, padding=1, groups=C)
97
+ gy = F.conv2d(x, ky, padding=1, groups=C)
98
+ return torch.sqrt(gx * gx + gy * gy + 1e-12)
99
+
100
+ return F.l1_loss(grad_mag(fake), grad_mag(real)).item()
101
+
102
+
103
+ def flatten_channels(x: torch.Tensor) -> torch.Tensor:
104
+ # -> [C, N*H*W] или [C, N*T*H*W]
105
+ if x.ndim == 4:
106
+ return x.permute(1, 0, 2, 3).reshape(x.shape[1], -1)
107
+ elif x.ndim == 5:
108
+ return x.permute(1, 0, 2, 3, 4).reshape(x.shape[1], -1)
109
+ else:
110
+ raise ValueError(f"Unexpected tensor ndim={x.ndim}")
111
+
112
+
113
+ def _to_numpy_1d(x: Any) -> Optional[np.ndarray]:
114
+ if x is None:
115
+ return None
116
+ if isinstance(x, (int, float)):
117
+ return None
118
+ if isinstance(x, torch.Tensor):
119
+ x = x.detach().cpu().float().numpy()
120
+ elif isinstance(x, (list, tuple)):
121
+ x = np.array(x, dtype=np.float32)
122
+ elif isinstance(x, np.ndarray):
123
+ x = x.astype(np.float32, copy=False)
124
+ else:
125
+ return None
126
+ x = x.reshape(-1)
127
+ return x
128
+
129
+
130
+ def _to_float(x: Any) -> Optional[float]:
131
+ if x is None:
132
+ return None
133
+ if isinstance(x, (int, float)):
134
+ return float(x)
135
+ if isinstance(x, np.ndarray) and x.size == 1:
136
+ return float(x.item())
137
+ if isinstance(x, torch.Tensor) and x.numel() == 1:
138
+ return float(x.item())
139
+ return None
140
+
141
+
142
+ def get_norm_tensors_and_summary(vae, latent_like: torch.Tensor):
143
+ """
144
+ Нормализация латентов: глобальная и поканальная.
145
+ Применение: сначала глобальная (scalar), затем поканальная (vector).
146
+ Если в конфиге есть несколько ключей — аккумулируем.
147
+ """
148
+ cfg = getattr(vae, "config", vae)
149
+
150
+ scale_keys = [
151
+ "latents_std"
152
+ ]
153
+ shift_keys = [
154
+ "latents_mean"
155
+ ]
156
+
157
+ C = latent_like.shape[1]
158
+ nd = latent_like.ndim # 4 или 5
159
+ dev = latent_like.device
160
+ dt = latent_like.dtype
161
+
162
+ scale_global = getattr(vae.config, "scaling_factor", 1.0)
163
+ shift_global = getattr(vae.config, "shift_factor", 0.0)
164
+ if scale_global is None:
165
+ scale_global = 1.0
166
+ if shift_global is None:
167
+ shift_global = 0.0
168
+
169
+ scale_channel = np.ones(C, dtype=np.float32)
170
+ shift_channel = np.zeros(C, dtype=np.float32)
171
+
172
+ for k in scale_keys:
173
+ v = getattr(cfg, k, None)
174
+ if v is None:
175
+ continue
176
+ vec = _to_numpy_1d(v)
177
+ if vec is not None and vec.size == C:
178
+ scale_channel *= vec
179
+ else:
180
+ s = _to_float(v)
181
+ if s is not None:
182
+ scale_global *= s
183
+
184
+ for k in shift_keys:
185
+ v = getattr(cfg, k, None)
186
+ if v is None:
187
+ continue
188
+ vec = _to_numpy_1d(v)
189
+ if vec is not None and vec.size == C:
190
+ shift_channel += vec
191
+ else:
192
+ s = _to_float(v)
193
+ if s is not None:
194
+ shift_global += s
195
+
196
+ g_shape = [1] * nd
197
+ c_shape = [1] * nd
198
+ c_shape[1] = C
199
+
200
+ t_scale_g = torch.tensor(scale_global, dtype=dt, device=dev).view(*g_shape)
201
+ t_shift_g = torch.tensor(shift_global, dtype=dt, device=dev).view(*g_shape)
202
+ t_scale_c = torch.from_numpy(scale_channel).to(device=dev, dtype=dt).view(*c_shape)
203
+ t_shift_c = torch.from_numpy(shift_channel).to(device=dev, dtype=dt).view(*c_shape)
204
+
205
+ summary = {
206
+ "scale_global": float(scale_global),
207
+ "shift_global": float(shift_global),
208
+ "scale_channel_min": float(scale_channel.min()),
209
+ "scale_channel_mean": float(scale_channel.mean()),
210
+ "scale_channel_max": float(scale_channel.max()),
211
+ "shift_channel_min": float(shift_channel.min()),
212
+ "shift_channel_mean": float(shift_channel.mean()),
213
+ "shift_channel_max": float(shift_channel.max()),
214
+ }
215
+ return t_shift_g, t_scale_g, t_shift_c, t_scale_c, summary
216
+
217
+
218
+ @torch.no_grad()
219
+ def kl_divergence_per_image(mu: torch.Tensor, logvar: torch.Tensor) -> torch.Tensor:
220
+ kl_map = -0.5 * (1 + logvar - mu.pow(2) - logvar.exp()) # [B, ...]
221
+ return kl_map.float().view(kl_map.shape[0], -1).mean(dim=1) # [B]
222
+
223
+
224
+ def sanitize_filename(name: str) -> str:
225
+ name = name.replace("/", "_").replace("\\", "_").replace(" ", "_")
226
+ return "".join(ch if (ch.isalnum() or ch in "._-") else "_" for ch in name)
227
+
228
+
229
+ # ========================== Датасет ==========================
230
+ class ImageFolderDataset(Dataset):
231
+ def __init__(self, root_dir: str, extensions=(".png", ".jpg", ".jpeg", ".webp"), min_size=1024, crop_size=512, limit=None):
232
+ paths = []
233
+ for root, _, files in os.walk(root_dir):
234
+ for fname in files:
235
+ if fname.lower().endswith(extensions):
236
+ paths.append(os.path.join(root, fname))
237
+ if limit:
238
+ paths = paths[:limit]
239
+
240
+ valid = []
241
+ for p in tqdm(paths, desc="Проверяем файлы"):
242
+ try:
243
+ with Image.open(p) as im:
244
+ im.verify()
245
+ valid.append(p)
246
+ except Exception:
247
+ pass
248
+ if not valid:
249
+ raise RuntimeError(f"Нет валидных изображений в {root_dir}")
250
+ random.shuffle(valid)
251
+ self.paths = valid
252
+ print(f"Найдено {len(self.paths)} изображений")
253
+
254
+ self.transform = Compose([
255
+ Resize(min_size),
256
+ CenterCrop(crop_size),
257
+ ToTensor(), # 0..1, float32
258
+ ])
259
+
260
+ def __len__(self):
261
+ return len(self.paths)
262
+
263
+ def __getitem__(self, idx):
264
+ with Image.open(self.paths[idx]) as img:
265
+ img = img.convert("RGB")
266
+ return self.transform(img)
267
+
268
+
269
+ # ========================== Основное ==========================
270
+ def main():
271
+ torch.set_grad_enabled(False)
272
+ os.makedirs(SAMPLES_DIR, exist_ok=True)
273
+
274
+ dataset = ImageFolderDataset(IMAGE_FOLDER, min_size=MIN_SIZE, crop_size=CROP_SIZE, limit=MAX_IMAGES)
275
+ loader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=False, num_workers=NUM_WORKERS, pin_memory=True)
276
+
277
+ lpips_net = lpips.LPIPS(net="vgg").to(DEVICE).eval()
278
+
279
+ # Загрузка VAE
280
+ vaes: List[Tuple[str, object]] = []
281
+ print("\nЗагрузка VAE...")
282
+ for human_name, vae_class, model_path, subfolder in VAE_LIST:
283
+ try:
284
+ vae = vae_class.from_pretrained(model_path, subfolder=subfolder, torch_dtype=DTYPE)
285
+ vae = vae.to(DEVICE).eval()
286
+ vaes.append((human_name, vae))
287
+ print(f" ✅ {human_name}")
288
+ except Exception as e:
289
+ print(f" ❌ {human_name}: {e}")
290
+
291
+ if not vaes:
292
+ print("Нет успешно загруженных VAE. Выходим.")
293
+ return
294
+
295
+ # Агрегаторы
296
+ per_model_metrics: Dict[str, Dict[str, float]] = {
297
+ name: {"mse": 0.0, "psnr": 0.0, "lpips": 0.0, "edge": 0.0, "kl": 0.0, "count": 0.0}
298
+ for name, _ in vaes
299
+ }
300
+
301
+ buffers_zmodel: Dict[str, List[torch.Tensor]] = {name: [] for name, _ in vaes}
302
+ norm_summaries: Dict[str, Dict[str, float]] = {}
303
+
304
+ # Флаг для сохранения первой картинки
305
+ saved_first_for: Dict[str, bool] = {name: False for name, _ in vaes}
306
+
307
+ for batch_0_1 in tqdm(loader, desc="Батчи"):
308
+ batch_0_1 = batch_0_1.to(DEVICE, torch.float32)
309
+ batch_neg1_1 = to_neg1_1(batch_0_1).to(DTYPE)
310
+
311
+ for model_name, vae in vaes:
312
+ x_in = add_time_dim_if_needed(batch_neg1_1, vae)
313
+
314
+ posterior = vae.encode(x_in).latent_dist
315
+ mu, logvar = posterior.mean, posterior.logvar
316
+
317
+ # Реконструкция (детерминированно)
318
+ z_raw_mode = posterior.mode()
319
+ x_dec = vae.decode(z_raw_mode).sample # [-1, 1]
320
+ x_dec = strip_time_dim_if_possible(x_dec, vae)
321
+ x_rec_0_1 = to_0_1(x_dec.float()).clamp(0, 1)
322
+
323
+ # Латенты для UNet: global -> channelwise
324
+ z_raw_sample = posterior.sample()
325
+ t_shift_g, t_scale_g, t_shift_c, t_scale_c, summary = get_norm_tensors_and_summary(vae, z_raw_sample)
326
+
327
+ if model_name not in norm_summaries:
328
+ norm_summaries[model_name] = summary
329
+
330
+ z_tmp = (z_raw_sample - t_shift_g) * t_scale_g
331
+ z_model = (z_tmp - t_shift_c) * t_scale_c
332
+ z_model = strip_time_dim_if_possible(z_model, vae)
333
+
334
+ buffers_zmodel[model_name].append(z_model.detach().to("cpu", torch.float32))
335
+
336
+ # Сохранить первую картинку (оригинал и реконструкцию) для каждого VAE
337
+ if not saved_first_for[model_name]:
338
+ safe = sanitize_filename(model_name)
339
+ orig_path = os.path.join(SAMPLES_DIR, f"{safe}_original.png")
340
+ dec_path = os.path.join(SAMPLES_DIR, f"{safe}_decoded.png")
341
+ save_image(batch_0_1[0:1].cpu(), orig_path)
342
+ save_image(x_rec_0_1[0:1].cpu(), dec_path)
343
+ saved_first_for[model_name] = True
344
+
345
+ # Метрики по картинкам
346
+ B = batch_0_1.shape[0]
347
+ for i in range(B):
348
+ gt = batch_0_1[i:i+1]
349
+ rec = x_rec_0_1[i:i+1]
350
+
351
+ mse = F.mse_loss(gt, rec).item()
352
+ psnr = safe_psnr(mse)
353
+ lp = float(lpips_net(gt, rec, normalize=True).mean().item())
354
+ edge = sobel_edge_l1(gt, rec)
355
+
356
+ per_model_metrics[model_name]["mse"] += mse
357
+ per_model_metrics[model_name]["psnr"] += psnr
358
+ per_model_metrics[model_name]["lpips"] += lp
359
+ per_model_metrics[model_name]["edge"] += edge
360
+
361
+ # KL per-image
362
+ kl_pi = kl_divergence_per_image(mu, logvar) # [B]
363
+ per_model_metrics[model_name]["kl"] += float(kl_pi.sum().item())
364
+ per_model_metrics[model_name]["count"] += B
365
+
366
+ # Усреднение метрик
367
+ for name in per_model_metrics:
368
+ c = max(1.0, per_model_metrics[name]["count"])
369
+ for k in ["mse", "psnr", "lpips", "edge", "kl"]:
370
+ per_model_metrics[name][k] /= c
371
+
372
+ # Подсчёт статистик латентов и нормальности
373
+ per_model_latent_stats = {}
374
+ for name, _ in vaes:
375
+ if not buffers_zmodel[name]:
376
+ continue
377
+ Z = torch.cat(buffers_zmodel[name], dim=0) # [N, C, H, W]
378
+
379
+ # Глобальные
380
+ z_min = float(Z.min().item())
381
+ z_mean = float(Z.mean().item())
382
+ z_max = float(Z.max().item())
383
+ z_std = float(Z.std(unbiased=True).item())
384
+
385
+ # Пер-канально: skew/kurtosis
386
+ Z_ch = flatten_channels(Z).numpy() # [C, *]
387
+ C = Z_ch.shape[0]
388
+ sk = np.zeros(C, dtype=np.float64)
389
+ ku = np.zeros(C, dtype=np.float64)
390
+ for c in range(C):
391
+ v = Z_ch[c]
392
+ sk[c] = float(skew(v, bias=False))
393
+ ku[c] = float(kurtosis(v, fisher=True, bias=False))
394
+
395
+ skew_min, skew_mean, skew_max = float(sk.min()), float(sk.mean()), float(sk.max())
396
+ kurt_min, kurt_mean, kurt_max = float(ku.min()), float(ku.mean()), float(ku.max())
397
+ mean_abs_skew = float(np.mean(np.abs(sk)))
398
+ mean_abs_kurt = float(np.mean(np.abs(ku)))
399
+
400
+ per_model_latent_stats[name] = {
401
+ "Z_min": z_min, "Z_mean": z_mean, "Z_max": z_max, "Z_std": z_std,
402
+ "skew_min": skew_min, "skew_mean": skew_mean, "skew_max": skew_max,
403
+ "kurt_min": kurt_min, "kurt_mean": kurt_mean, "kurt_max": kurt_max,
404
+ "mean_abs_skew": mean_abs_skew, "mean_abs_kurt": mean_abs_kurt,
405
+ }
406
+
407
+ # Печать параметров нормализации (shift/scale)
408
+ print("\n=== Параметры нормализации латентов (как применялись) ===")
409
+ for name, _ in vaes:
410
+ if name not in norm_summaries:
411
+ continue
412
+ s = norm_summaries[name]
413
+ print(
414
+ f"{name:26s} | "
415
+ f"shift_g={s['shift_global']:.6g} scale_g={s['scale_global']:.6g} | "
416
+ f"shift_c[min/mean/max]=[{s['shift_channel_min']:.6g}, {s['shift_channel_mean']:.6g}, {s['shift_channel_max']:.6g}] | "
417
+ f"scale_c[min/mean/max]=[{s['scale_channel_min']:.6g}, {s['scale_channel_mean']:.6g}, {s['scale_channel_max']:.6g}]"
418
+ )
419
+
420
+ # Абсолютные метрики
421
+ print("\n=== Абсолютные метрики реконструкции и латентов ===")
422
+ for name, _ in vaes:
423
+ if name not in per_model_latent_stats:
424
+ continue
425
+ m = per_model_metrics[name]
426
+ s = per_model_latent_stats[name]
427
+ print(
428
+ f"{name:26s} | "
429
+ f"MSE={m['mse']:.3e} PSNR={m['psnr']:.2f} LPIPS={m['lpips']:.3f} Edge={m['edge']:.3f} KL={m['kl']:.3f} | "
430
+ f"Z[min/mean/max/std]=[{s['Z_min']:.3f}, {s['Z_mean']:.3f}, {s['Z_max']:.3f}, {s['Z_std']:.3f}] | "
431
+ f"Skew[min/mean/max]=[{s['skew_min']:.3f}, {s['skew_mean']:.3f}, {s['skew_max']:.3f}] | "
432
+ f"Kurt[min/mean/max]=[{s['kurt_min']:.3f}, {s['kurt_mean']:.3f}, {s['kurt_max']:.3f}]"
433
+ )
434
+
435
+ # Сравнение с первой моделью
436
+ baseline = vaes[0][0]
437
+ print("\n=== Сравнение с первой моделью (проценты) ===")
438
+ print(f"| {'Модель':26s} | {'MSE':>9s} | {'PSNR':>9s} | {'LPIPS':>9s} | {'Edge':>9s} | {'Skew|0':>9s} | {'Kurt|0':>9s} |")
439
+ print(f"|{'-'*28}|{'-'*11}|{'-'*11}|{'-'*11}|{'-'*11}|{'-'*11}|{'-'*11}|")
440
+
441
+ b_m = per_model_metrics[baseline]
442
+ b_s = per_model_latent_stats[baseline]
443
+
444
+ for name, _ in vaes:
445
+ m = per_model_metrics[name]
446
+ s = per_model_latent_stats[name]
447
+
448
+ mse_pct = (b_m["mse"] / max(1e-12, m["mse"])) * 100.0 # меньше лучше
449
+ psnr_pct = (m["psnr"] / max(1e-12, b_m["psnr"])) * 100.0 # больше лучше
450
+ lpips_pct= (b_m["lpips"] / max(1e-12, m["lpips"])) * 100.0 # меньше лучше
451
+ edge_pct = (b_m["edge"] / max(1e-12, m["edge"])) * 100.0 # меньше лучше
452
+
453
+ skew0_pct = (b_s["mean_abs_skew"] / max(1e-12, s["mean_abs_skew"])) * 100.0
454
+ kurt0_pct = (b_s["mean_abs_kurt"] / max(1e-12, s["mean_abs_kurt"])) * 100.0
455
+
456
+ if name == baseline:
457
+ print(f"| {name:26s} | {'100%':>9s} | {'100%':>9s} | {'100%':>9s} | {'100%':>9s} | {'100%':>9s} | {'100%':>9s} |")
458
+ else:
459
+ print(f"| {name:26s} | {mse_pct:8.1f}% | {psnr_pct:8.1f}% | {lpips_pct:8.1f}% | {edge_pct:8.1f}% | {skew0_pct:8.1f}% | {kurt0_pct:8.1f}% |")
460
+
461
+ # ========================== Коррекции для последнего VAE + сохранение в JSON ==========================
462
+ last_name = vaes[-1][0]
463
+ if buffers_zmodel[last_name]:
464
+ Z = torch.cat(buffers_zmodel[last_name], dim=0) # [N, C, H, W]
465
+
466
+ # Глобальная коррекция (по всем каналам/пикселям)
467
+ z_mean = float(Z.mean().item())
468
+ z_std = float(Z.std(unbiased=True).item())
469
+ correction_global = {
470
+ "shift": -z_mean,
471
+ "scale": (1.0 / z_std) if z_std > 1e-12 else 1.0
472
+ }
473
+
474
+ # Поканальная коррекция
475
+ Z_ch = flatten_channels(Z) # [C, M]
476
+ ch_means_t = Z_ch.mean(dim=1) # [C]
477
+ ch_stds_t = Z_ch.std(dim=1, unbiased=True) + 1e-12 # [C]
478
+ ch_means = [float(x) for x in ch_means_t.tolist()]
479
+ ch_stds = [float(x) for x in ch_stds_t.tolist()]
480
+
481
+ correction_per_channel = [
482
+ {"shift": float(-m), "scale": float(1.0 / s)}
483
+ for m, s in zip(ch_means, ch_stds)
484
+ ]
485
+
486
+ print(f"\n=== Доп. коррекция для {last_name} (поверх VAE-нормализации) ===")
487
+ print(f"global_correction = {correction_global}")
488
+ print(f"channelwise_means = {ch_means}")
489
+ print(f"channelwise_stds = {ch_stds}")
490
+ print(f"channelwise_correction = {correction_per_channel}")
491
+
492
+ # Сохранение в JSON
493
+ json_path = os.path.join(SAMPLES_DIR, f"{sanitize_filename(last_name)}_correction.json")
494
+ to_save = {
495
+ "model_name": last_name,
496
+ "vae_normalization_summary": norm_summaries.get(last_name, {}),
497
+ "global_correction": correction_global,
498
+ "per_channel_means": ch_means,
499
+ "per_channel_stds": ch_stds,
500
+ "per_channel_correction": correction_per_channel,
501
+ "apply_order": {
502
+ "forward": "z_model -> (z - global_shift)*global_scale -> (per-channel: (z - mean_c)/std_c)",
503
+ "inverse": "z_corr -> (per-channel: z*std_c + mean_c) -> (z/global_scale + global_shift)"
504
+ },
505
+ "note": "Эти коэффициенты рассчитаны по z_model (после встроенных VAE shift/scale), чтобы привести распределение к N(0,1)."
506
+ }
507
+ with open(json_path, "w", encoding="utf-8") as f:
508
+ json.dump(to_save, f, ensure_ascii=False, indent=2)
509
+ print("Corrections JSON saved to:", os.path.abspath(json_path))
510
+
511
+ print("\n✅ Готово. Сэмплы сохранены в:", os.path.abspath(SAMPLES_DIR))
512
+
513
+
514
+ if __name__ == "__main__":
515
+ main()
test/AiArtLab_simplevae_correction.json ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_name": "AiArtLab/simplevae",
3
+ "vae_normalization_summary": {
4
+ "scale_global": 1.0,
5
+ "shift_global": 0.0,
6
+ "scale_channel_min": 1.0,
7
+ "scale_channel_mean": 1.0,
8
+ "scale_channel_max": 1.0,
9
+ "shift_channel_min": 0.0,
10
+ "shift_channel_mean": 0.0,
11
+ "shift_channel_max": 0.0
12
+ },
13
+ "global_correction": {
14
+ "shift": 0.060732152312994,
15
+ "scale": 1.035888502366052
16
+ },
17
+ "per_channel_means": [
18
+ -0.17934872210025787,
19
+ 0.08837347477674484,
20
+ -0.18308678269386292,
21
+ 0.2742660641670227,
22
+ 0.002165613230317831,
23
+ 0.03449296951293945,
24
+ -0.16568207740783691,
25
+ -0.26266154646873474,
26
+ -0.1797001212835312,
27
+ -0.12722325325012207,
28
+ -0.03235034644603729,
29
+ -0.04355641081929207,
30
+ -0.0853145644068718,
31
+ 0.08101209998130798,
32
+ -0.12256482243537903,
33
+ -0.07053600996732712
34
+ ],
35
+ "per_channel_stds": [
36
+ 0.9051793217658997,
37
+ 0.8686285614967346,
38
+ 0.8835359811782837,
39
+ 1.3679808378219604,
40
+ 0.889316201210022,
41
+ 1.010545253753662,
42
+ 0.9772343635559082,
43
+ 0.9337192177772522,
44
+ 0.988460123538971,
45
+ 0.9164251685142517,
46
+ 0.8944668769836426,
47
+ 0.9558082222938538,
48
+ 0.9226727485656738,
49
+ 0.8971477746963501,
50
+ 0.9111431837081909,
51
+ 0.8696402907371521
52
+ ],
53
+ "per_channel_correction": [
54
+ {
55
+ "shift": 0.17934872210025787,
56
+ "scale": 1.1047534736532825
57
+ },
58
+ {
59
+ "shift": -0.08837347477674484,
60
+ "scale": 1.1512400631599071
61
+ },
62
+ {
63
+ "shift": 0.18308678269386292,
64
+ "scale": 1.131815818826529
65
+ },
66
+ {
67
+ "shift": -0.2742660641670227,
68
+ "scale": 0.7310043915470018
69
+ },
70
+ {
71
+ "shift": -0.002165613230317831,
72
+ "scale": 1.124459442703708
73
+ },
74
+ {
75
+ "shift": -0.03449296951293945,
76
+ "scale": 0.9895647882027134
77
+ },
78
+ {
79
+ "shift": 0.16568207740783691,
80
+ "scale": 1.023295984354514
81
+ },
82
+ {
83
+ "shift": 0.26266154646873474,
84
+ "scale": 1.0709857749105038
85
+ },
86
+ {
87
+ "shift": 0.1797001212835312,
88
+ "scale": 1.0116745999016257
89
+ },
90
+ {
91
+ "shift": 0.12722325325012207,
92
+ "scale": 1.091196569405927
93
+ },
94
+ {
95
+ "shift": 0.03235034644603729,
96
+ "scale": 1.1179843834712364
97
+ },
98
+ {
99
+ "shift": 0.04355641081929207,
100
+ "scale": 1.046234983833985
101
+ },
102
+ {
103
+ "shift": 0.0853145644068718,
104
+ "scale": 1.0838078848156445
105
+ },
106
+ {
107
+ "shift": -0.08101209998130798,
108
+ "scale": 1.1146435717777503
109
+ },
110
+ {
111
+ "shift": 0.12256482243537903,
112
+ "scale": 1.0975223410333572
113
+ },
114
+ {
115
+ "shift": 0.07053600996732712,
116
+ "scale": 1.1499007240710388
117
+ }
118
+ ],
119
+ "apply_order": {
120
+ "forward": "z_model -> (z - global_shift)*global_scale -> (per-channel: (z - mean_c)/std_c)",
121
+ "inverse": "z_corr -> (per-channel: z*std_c + mean_c) -> (z/global_scale + global_shift)"
122
+ },
123
+ "note": "Эти коэффициенты рассчитаны по z_model (после встроенных VAE shift/scale), чтобы привести распределение к N(0,1)."
124
+ }
test/FLUX.1-schnell_VAE_correction.json ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_name": "FLUX.1-schnell VAE",
3
+ "vae_normalization_summary": {
4
+ "scale_global": 0.3611,
5
+ "shift_global": 0.1159,
6
+ "scale_channel_min": 1.0,
7
+ "scale_channel_mean": 1.0,
8
+ "scale_channel_max": 1.0,
9
+ "shift_channel_min": 0.0,
10
+ "shift_channel_mean": 0.0,
11
+ "shift_channel_max": 0.0
12
+ },
13
+ "global_correction": {
14
+ "shift": 0.033536698669195175,
15
+ "scale": 1.0893412605691914
16
+ },
17
+ "per_channel_means": [
18
+ -0.2011537104845047,
19
+ -0.23432493209838867,
20
+ 0.1418181210756302,
21
+ -0.051936931908130646,
22
+ 0.05777733772993088,
23
+ 0.2514500916004181,
24
+ -0.3927314877510071,
25
+ 0.23873785138130188,
26
+ -0.1971667855978012,
27
+ 0.5086520910263062,
28
+ 0.18148651719093323,
29
+ 0.18726322054862976,
30
+ -0.029747387394309044,
31
+ -0.30456721782684326,
32
+ -0.4305008351802826,
33
+ -0.2616432309150696
34
+ ],
35
+ "per_channel_stds": [
36
+ 0.7963889241218567,
37
+ 1.28511381149292,
38
+ 0.8507877588272095,
39
+ 0.5032204985618591,
40
+ 0.527312159538269,
41
+ 0.6365501284599304,
42
+ 1.104862928390503,
43
+ 0.8536051511764526,
44
+ 0.6959906220436096,
45
+ 1.011374592781067,
46
+ 0.6488218307495117,
47
+ 0.8073245882987976,
48
+ 0.9629114866256714,
49
+ 1.241254448890686,
50
+ 0.7992448806762695,
51
+ 0.9001436829566956
52
+ ],
53
+ "per_channel_correction": [
54
+ {
55
+ "shift": 0.2011537104845047,
56
+ "scale": 1.2556678900358345
57
+ },
58
+ {
59
+ "shift": 0.23432493209838867,
60
+ "scale": 0.7781411973452356
61
+ },
62
+ {
63
+ "shift": -0.1418181210756302,
64
+ "scale": 1.1753812741481802
65
+ },
66
+ {
67
+ "shift": 0.051936931908130646,
68
+ "scale": 1.987200447632547
69
+ },
70
+ {
71
+ "shift": -0.05777733772993088,
72
+ "scale": 1.8964099004954318
73
+ },
74
+ {
75
+ "shift": -0.2514500916004181,
76
+ "scale": 1.5709681850499353
77
+ },
78
+ {
79
+ "shift": 0.3927314877510071,
80
+ "scale": 0.9050896489546799
81
+ },
82
+ {
83
+ "shift": -0.23873785138130188,
84
+ "scale": 1.1715018338652052
85
+ },
86
+ {
87
+ "shift": 0.1971667855978012,
88
+ "scale": 1.4368009687598085
89
+ },
90
+ {
91
+ "shift": -0.5086520910263062,
92
+ "scale": 0.9887533334708467
93
+ },
94
+ {
95
+ "shift": -0.18148651719093323,
96
+ "scale": 1.5412551683792932
97
+ },
98
+ {
99
+ "shift": -0.18726322054862976,
100
+ "scale": 1.2386591644721363
101
+ },
102
+ {
103
+ "shift": 0.029747387394309044,
104
+ "scale": 1.0385170536331412
105
+ },
106
+ {
107
+ "shift": 0.30456721782684326,
108
+ "scale": 0.8056365887700978
109
+ },
110
+ {
111
+ "shift": 0.4305008351802826,
112
+ "scale": 1.2511809886775433
113
+ },
114
+ {
115
+ "shift": 0.2616432309150696,
116
+ "scale": 1.1109337530596306
117
+ }
118
+ ],
119
+ "apply_order": {
120
+ "forward": "z_model -> (z - global_shift)*global_scale -> (per-channel: (z - mean_c)/std_c)",
121
+ "inverse": "z_corr -> (per-channel: z*std_c + mean_c) -> (z/global_scale + global_shift)"
122
+ },
123
+ "note": "Эти коэффициенты рассчитаны по z_model (после встроенных VAE shift/scale), чтобы привести распределение к N(0,1)."
124
+ }