| """ |
| Medical Image Generation Evaluation |
| Compute FID, Precision, Recall between generated and real images. |
| Supports both CVC-ClinicDB and Kvasir-SEG experiments. |
| |
| Usage: |
| python scripts/evaluate_medical.py --dataset kvasir |
| python scripts/evaluate_medical.py --dataset cvc |
| """ |
| import sys |
| sys.path.insert(0, "/data/sichengli/Code/PixelGen") |
|
|
| import argparse |
| import os |
| import gc |
| import random |
| import numpy as np |
| import torch |
| import torch.nn as nn |
| from torch.utils.data import DataLoader, Dataset |
| from PIL import Image |
| import torchvision.transforms as transforms |
| import torchvision.transforms.functional as TF |
| from torchmetrics.image.fid import FrechetInceptionDistance |
| from torchmetrics.image.inception import InceptionScore |
|
|
| from src.models.transformer.JiT_medical import JiTMedical |
|
|
|
|
| |
| CONFIGS = { |
| "kvasir": { |
| "data_root": "/data2/sichengli/Data/test/Segmentation/Kvasir-SEG/Kvasir-SEG", |
| "img_subdir": "images", |
| "mask_subdir": "masks", |
| "file_ext": (".jpg", ".png", ".jpeg"), |
| "ckpt": "/data/sichengli/Code/PixelGen/medical_workdirs/exp_PixelGen_Medical_Kvasir/epoch=12499-step=100000.ckpt", |
| "out_dir": "/data/sichengli/Code/PixelGen/medical_workdirs/exp_PixelGen_Medical_Kvasir/eval_results", |
| "train_ratio": 0.9, |
| "seed": 42, |
| }, |
| "cvc": { |
| "data_root": "/data2/sichengli/Data/test/Segmentation/CVC-ClinicDB", |
| "img_subdir": "PNG/Original", |
| "mask_subdir": "PNG/Ground Truth", |
| "file_ext": (".png",), |
| "ckpt": "/data/sichengli/Code/PixelGen/medical_workdirs/exp_PixelGen_Medical_CVC/epoch=19999-step=100000.ckpt", |
| "out_dir": "/data/sichengli/Code/PixelGen/medical_workdirs/exp_PixelGen_Medical_CVC/eval_results", |
| "train_ratio": 0.9, |
| "seed": 42, |
| }, |
| "refuge2": { |
| "data_root": "/data2/sichengli/Data/test/Segmentation/REFUGE2", |
| "multi_split": True, |
| "splits": ["train", "val"], |
| "file_ext": (".jpg", ".png", ".jpeg"), |
| "mask_ext": (".bmp", ".png"), |
| "ckpt": "/data/sichengli/Code/PixelGen/medical_workdirs/exp_PixelGen_Medical_REFUGE2/epoch=16666-step=100000.ckpt", |
| "out_dir": "/data/sichengli/Code/PixelGen/medical_workdirs/exp_PixelGen_Medical_REFUGE2/eval_results", |
| "val_ratio": 0.1, |
| "seed": 42, |
| }, |
| } |
|
|
| MODEL_CONFIGS = { |
| "S/8": dict( |
| input_size=256, patch_size=8, in_channels=3, |
| hidden_size=512, depth=8, num_heads=8, mlp_ratio=4.0, |
| attn_drop=0.0, proj_drop=0.1, num_classes=1, |
| use_bottleneck=True, bottleneck_dim=64, |
| in_context_len=64, in_context_start=2, mask_in_channels=1, |
| ), |
| "B/8": dict( |
| input_size=256, patch_size=8, in_channels=3, |
| hidden_size=768, depth=12, num_heads=12, mlp_ratio=4.0, |
| attn_drop=0.0, proj_drop=0.1, num_classes=1, |
| use_bottleneck=True, bottleneck_dim=128, |
| in_context_len=64, in_context_start=4, mask_in_channels=1, |
| ), |
| "B/16": dict( |
| input_size=256, patch_size=16, in_channels=3, |
| hidden_size=768, depth=12, num_heads=12, mlp_ratio=4.0, |
| attn_drop=0.0, proj_drop=0.1, num_classes=1, |
| use_bottleneck=True, bottleneck_dim=128, |
| in_context_len=32, in_context_start=4, mask_in_channels=1, |
| ), |
| "L/16": dict( |
| input_size=256, patch_size=16, in_channels=3, |
| hidden_size=1024, depth=24, num_heads=16, mlp_ratio=4.0, |
| attn_drop=0.0, proj_drop=0.1, num_classes=1, |
| use_bottleneck=True, bottleneck_dim=128, |
| in_context_len=32, in_context_start=8, mask_in_channels=1, |
| ), |
| "XL/16": dict( |
| input_size=256, patch_size=16, in_channels=3, |
| hidden_size=1152, depth=28, num_heads=16, mlp_ratio=4.0, |
| attn_drop=0.0, proj_drop=0.1, num_classes=1, |
| use_bottleneck=True, bottleneck_dim=128, |
| in_context_len=32, in_context_start=8, mask_in_channels=1, |
| ), |
| } |
|
|
| RESOLUTION = 256 |
| BATCH_SIZE = 16 |
| NUM_SAMPLING_STEPS = 50 |
|
|
|
|
| |
| class EvalDataset(Dataset): |
| """Load real images and masks for a given split.""" |
| def __init__(self, cfg, split="train"): |
| if cfg.get("multi_split"): |
| |
| all_pairs = [] |
| for s in cfg["splits"]: |
| img_dir = os.path.join(cfg["data_root"], s, "images") |
| mask_dir = os.path.join(cfg["data_root"], s, "mask") |
| img_files = sorted([f for f in os.listdir(img_dir) if f.endswith(cfg["file_ext"])]) |
| for img_f in img_files: |
| base_name = os.path.splitext(img_f)[0] |
| img_path = os.path.join(img_dir, img_f) |
| for ext in cfg["mask_ext"]: |
| candidate = os.path.join(mask_dir, base_name + ext) |
| if os.path.exists(candidate): |
| all_pairs.append((img_path, candidate)) |
| break |
| |
| random.seed(cfg["seed"]) |
| random.shuffle(all_pairs) |
| split_idx = int(len(all_pairs) * (1 - cfg.get("val_ratio", 0.1))) |
| if split == "train": |
| self.pairs = all_pairs[:split_idx] |
| else: |
| self.pairs = all_pairs[split_idx:] |
| self.multi_split = True |
| else: |
| |
| img_dir = os.path.join(cfg["data_root"], cfg["img_subdir"]) |
| mask_dir = os.path.join(cfg["data_root"], cfg["mask_subdir"]) |
| all_files = sorted([f for f in os.listdir(img_dir) if f.endswith(cfg["file_ext"])]) |
|
|
| random.seed(cfg["seed"]) |
| indices = list(range(len(all_files))) |
| random.shuffle(indices) |
| split_idx = int(len(indices) * cfg["train_ratio"]) |
|
|
| if split == "train": |
| sel = indices[:split_idx] |
| else: |
| sel = indices[split_idx:] |
|
|
| self.files = [all_files[i] for i in sorted(sel)] |
| self.img_dir = img_dir |
| self.mask_dir = mask_dir |
| self.multi_split = False |
|
|
| def __len__(self): |
| return len(self.pairs) if self.multi_split else len(self.files) |
|
|
| def __getitem__(self, idx): |
| if self.multi_split: |
| img_path, mask_path = self.pairs[idx] |
| img = Image.open(img_path).convert("RGB") |
| mask = Image.open(mask_path).convert("L") |
| else: |
| fname = self.files[idx] |
| img = Image.open(os.path.join(self.img_dir, fname)).convert("RGB") |
| mask = Image.open(os.path.join(self.mask_dir, fname)).convert("L") |
|
|
| img = TF.resize(img, (RESOLUTION, RESOLUTION), interpolation=transforms.InterpolationMode.BILINEAR) |
| img_tensor = TF.to_tensor(img) |
|
|
| mask = TF.resize(mask, (RESOLUTION, RESOLUTION), interpolation=transforms.InterpolationMode.NEAREST) |
| mask_tensor = TF.to_tensor(mask) |
|
|
| return img_tensor, mask_tensor |
|
|
|
|
| |
| def shift_respace_fn(t, shift=1.0): |
| return t / (t + (1 - t) * shift) |
|
|
|
|
| @torch.no_grad() |
| def sample_batch(model, noise, mask, num_steps=50, t_eps=0.05): |
| """No-CFG sampling for evaluation (faster, avoids CFG artifacts).""" |
| batch_size = noise.shape[0] |
| timesteps = torch.linspace(0.0, 1 - 1.0 / num_steps, num_steps) |
| timesteps = torch.cat([timesteps, torch.tensor([1.0])], dim=0) |
| timesteps = shift_respace_fn(timesteps, 1.0).to(noise.device) |
| y = torch.zeros(batch_size, dtype=torch.long, device=noise.device) |
| x = noise |
| for i in range(len(timesteps) - 1): |
| t_cur = timesteps[i] |
| t_next = timesteps[i + 1] |
| dt = t_next - t_cur |
| t_batch = t_cur.repeat(batch_size) |
| pred_img = model(x, t_batch, y, mask=mask) |
| v = (pred_img - x) / (1.0 - t_batch.view(-1, 1, 1, 1)).clamp_min(t_eps) |
| x = x + v * dt |
| return x |
|
|
|
|
| @torch.no_grad() |
| def sample_batch_cfg(model, noise, mask, num_steps=50, cfg_scale=2.0, t_eps=0.05): |
| """CFG sampling for evaluation.""" |
| batch_size = noise.shape[0] |
| timesteps = torch.linspace(0.0, 1 - 1.0 / num_steps, num_steps) |
| timesteps = torch.cat([timesteps, torch.tensor([1.0])], dim=0) |
| timesteps = shift_respace_fn(timesteps, 1.0).to(noise.device) |
| y = torch.zeros(batch_size, dtype=torch.long, device=noise.device) |
| x = noise |
| for i in range(len(timesteps) - 1): |
| t_cur = timesteps[i] |
| t_next = timesteps[i + 1] |
| dt = t_next - t_cur |
| t_batch = t_cur.repeat(batch_size) |
| cfg_x = torch.cat([x, x], dim=0) |
| cfg_t = t_batch.repeat(2) |
| cfg_y = torch.cat([y, y], dim=0) |
| cfg_mask = torch.cat([torch.zeros_like(mask), mask], dim=0) |
| pred = model(cfg_x, cfg_t, cfg_y, mask=cfg_mask) |
| pred_v = (pred - cfg_x) / (1.0 - cfg_t.view(-1, 1, 1, 1)).clamp_min(t_eps) |
| v_uncond, v_cond = pred_v.chunk(2) |
| v = v_uncond + cfg_scale * (v_cond - v_uncond) |
| x = x + v * dt |
| return x |
|
|
|
|
| |
| class InceptionV3Features(nn.Module): |
| """Extract Inception V3 pool3 features (2048-d) for P&R computation.""" |
| def __init__(self, device): |
| super().__init__() |
| from torchvision.models import inception_v3, Inception_V3_Weights |
| self.model = inception_v3(weights=Inception_V3_Weights.DEFAULT) |
| self.model.fc = nn.Identity() |
| self.model = self.model.to(device).eval() |
| self.device = device |
| self.transform = transforms.Normalize( |
| mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] |
| ) |
|
|
| @torch.no_grad() |
| def forward(self, images): |
| """images: [N, 3, H, W] in [0, 1], uint8 or float.""" |
| if images.dtype == torch.uint8: |
| images = images.float() / 255.0 |
| |
| images = torch.nn.functional.interpolate(images, size=(299, 299), mode="bilinear", align_corners=False) |
| images = torch.stack([self.transform(img) for img in images]) |
| images = images.to(self.device) |
| features = self.model(images) |
| return features.cpu() |
|
|
|
|
| def compute_precision_recall(real_features, gen_features, k=3): |
| """ |
| Compute Precision and Recall using k-NN manifold estimation. |
| Based on 'Improved Precision and Recall Metric for Assessing Generative Models' (Kynkaanniemi et al.) |
| """ |
| from scipy.spatial.distance import cdist |
|
|
| real_np = real_features.numpy() |
| gen_np = gen_features.numpy() |
|
|
| |
| |
| real_real_dist = cdist(real_np, real_np, metric="euclidean") |
| np.fill_diagonal(real_real_dist, np.inf) |
| real_kth = np.sort(real_real_dist, axis=1)[:, k - 1] |
|
|
| |
| gen_gen_dist = cdist(gen_np, gen_np, metric="euclidean") |
| np.fill_diagonal(gen_gen_dist, np.inf) |
| gen_kth = np.sort(gen_gen_dist, axis=1)[:, k - 1] |
|
|
| |
| gen_real_dist = cdist(gen_np, real_np, metric="euclidean") |
| precision = np.mean(np.min(gen_real_dist, axis=1) <= real_kth[np.argmin(gen_real_dist, axis=1)]) |
|
|
| |
| real_gen_dist = cdist(real_np, gen_np, metric="euclidean") |
| recall = np.mean(np.min(real_gen_dist, axis=1) <= gen_kth[np.argmin(real_gen_dist, axis=1)]) |
|
|
| return precision, recall |
|
|
|
|
| |
| def evaluate(dataset_name, use_cfg=False, cfg_scale=2.0, model_kwargs=None): |
| cfg = CONFIGS[dataset_name] |
| device = torch.device("cuda:0") |
| os.makedirs(cfg["out_dir"], exist_ok=True) |
|
|
| print(f"\n{'='*60}") |
| print(f" Evaluating: {dataset_name.upper()}") |
| print(f" Checkpoint: {os.path.basename(cfg['ckpt'])}") |
| print(f" Sampling: {'CFG=' + str(cfg_scale) if use_cfg else 'No-CFG'}") |
| print(f"{'='*60}\n") |
|
|
| |
| dataset = EvalDataset(cfg, split="train") |
| loader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=False, num_workers=4, pin_memory=True) |
| num_samples = len(dataset) |
| print(f"Dataset: {num_samples} training images") |
|
|
| |
| print("Loading model...") |
| ckpt = torch.load(cfg["ckpt"], map_location="cpu", weights_only=False) |
| state_dict = ckpt["state_dict"] |
| ema_state = {} |
| for k, v in state_dict.items(): |
| if k.startswith("ema_denoiser."): |
| new_k = k.replace("ema_denoiser.", "").replace("_orig_mod.", "") |
| ema_state[new_k] = v |
| model = JiTMedical(**model_kwargs) |
| result = model.load_state_dict(ema_state, strict=False) |
| print(f"Loaded EMA ({len(ema_state)} keys), missing: {result.missing_keys}, unexpected: {result.unexpected_keys}") |
| model = model.to(device).eval().to(torch.float32) |
|
|
| |
| fid_metric = FrechetInceptionDistance(feature=2048, normalize=True).to(device) |
| inception_features = InceptionV3Features(device) |
|
|
| all_real_features = [] |
| all_gen_features = [] |
|
|
| |
| print(f"\nGenerating {num_samples} images and computing features...") |
| torch.manual_seed(0) |
|
|
| batch_idx = 0 |
| for real_imgs, masks in loader: |
| bs = real_imgs.shape[0] |
| batch_idx += 1 |
| print(f" Batch {batch_idx}/{len(loader)} ({bs} samples)...", end="\r") |
|
|
| masks = masks.to(device) |
| noise = torch.randn(bs, 3, RESOLUTION, RESOLUTION, device=device) |
|
|
| |
| if use_cfg: |
| gen = sample_batch_cfg(model, noise, masks, NUM_SAMPLING_STEPS, cfg_scale) |
| else: |
| gen = sample_batch(model, noise, masks, NUM_SAMPLING_STEPS) |
| gen = gen.clamp(-1, 1) * 0.5 + 0.5 |
|
|
| |
| fid_metric.update(real_imgs.to(device), real=True) |
| fid_metric.update(gen, real=False) |
|
|
| |
| real_feat = inception_features(real_imgs) |
| gen_feat = inception_features(gen.cpu()) |
| all_real_features.append(real_feat) |
| all_gen_features.append(gen_feat) |
|
|
| print(f"\n\nComputing FID...") |
| fid_value = fid_metric.compute().item() |
| print(f"FID = {fid_value:.4f}") |
|
|
| |
| print("Computing Precision & Recall...") |
| real_features = torch.cat(all_real_features, dim=0) |
| gen_features = torch.cat(all_gen_features, dim=0) |
| precision, recall = compute_precision_recall(real_features, gen_features, k=3) |
| print(f"Precision = {precision:.4f}") |
| print(f"Recall = {recall:.4f}") |
|
|
| |
| mode_str = f"cfg{cfg_scale}" if use_cfg else "no_cfg" |
| result_file = os.path.join(cfg["out_dir"], f"metrics_{mode_str}.txt") |
| with open(result_file, "w") as f: |
| f.write(f"Dataset: {dataset_name}\n") |
| f.write(f"Checkpoint: {cfg['ckpt']}\n") |
| f.write(f"Sampling: {'CFG=' + str(cfg_scale) if use_cfg else 'No-CFG'}\n") |
| f.write(f"Num samples: {num_samples}\n") |
| f.write(f"Num steps: {NUM_SAMPLING_STEPS}\n") |
| f.write(f"\n") |
| f.write(f"FID: {fid_value:.4f}\n") |
| f.write(f"Precision: {precision:.4f}\n") |
| f.write(f"Recall: {recall:.4f}\n") |
| print(f"\nResults saved: {result_file}") |
|
|
| |
| print(f"\n{'='*40}") |
| print(f" {dataset_name.upper()} Results ({mode_str})") |
| print(f" FID: {fid_value:.4f}") |
| print(f" Precision: {precision:.4f}") |
| print(f" Recall: {recall:.4f}") |
| print(f"{'='*40}\n") |
|
|
| return fid_value, precision, recall |
|
|
|
|
| if __name__ == "__main__": |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--dataset", type=str, required=True, choices=["kvasir", "cvc", "refuge2", "all"]) |
| parser.add_argument("--cfg", action="store_true", help="Use CFG sampling") |
| parser.add_argument("--cfg_scale", type=float, default=2.0) |
| parser.add_argument("--mask_mode", type=str, default="spatial", choices=["global", "spatial", "cross_attention"]) |
| parser.add_argument("--model", type=str, default="B/16", choices=["S/8", "B/8", "B/16", "L/16", "XL/16"]) |
| parser.add_argument("--ckpt", type=str, default=None, help="Override checkpoint path") |
| args = parser.parse_args() |
|
|
| |
| model_kwargs = MODEL_CONFIGS[args.model].copy() |
| model_kwargs["mask_mode"] = args.mask_mode |
|
|
| datasets = ["cvc", "kvasir", "refuge2"] if args.dataset == "all" else [args.dataset] |
|
|
| all_results = {} |
| for ds in datasets: |
| |
| if args.ckpt: |
| CONFIGS[ds]["ckpt"] = args.ckpt |
|
|
| |
| fid_nc, prec_nc, rec_nc = evaluate(ds, use_cfg=False, model_kwargs=model_kwargs) |
| all_results[f"{ds}_no_cfg"] = (fid_nc, prec_nc, rec_nc) |
|
|
| |
| if args.cfg: |
| fid_c, prec_c, rec_c = evaluate(ds, use_cfg=True, cfg_scale=args.cfg_scale, model_kwargs=model_kwargs) |
| all_results[f"{ds}_cfg{args.cfg_scale}"] = (fid_c, prec_c, rec_c) |
|
|
| |
| gc.collect() |
| torch.cuda.empty_cache() |
|
|
| |
| if len(all_results) > 1: |
| print("\n" + "=" * 60) |
| print(" SUMMARY") |
| print("=" * 60) |
| print(f"{'Experiment':<25s} | {'FID':>8s} | {'Precision':>10s} | {'Recall':>8s}") |
| print("-" * 60) |
| for name, (fid, prec, rec) in all_results.items(): |
| print(f"{name:<25s} | {fid:>8.2f} | {prec:>10.4f} | {rec:>8.4f}") |
| print("=" * 60) |
|
|