File size: 18,601 Bytes
01fdb75 | 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 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 | """
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
# βββ Config βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
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
# βββ Dataset ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class EvalDataset(Dataset):
"""Load real images and masks for a given split."""
def __init__(self, cfg, split="train"):
if cfg.get("multi_split"):
# REFUGE2-style: multiple split folders, mask may have different extension
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
# Use val_ratio to split train/val
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:
# CVC/Kvasir-style: single img/mask dirs with train_ratio split
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) # [3, H, W] in [0, 1]
mask = TF.resize(mask, (RESOLUTION, RESOLUTION), interpolation=transforms.InterpolationMode.NEAREST)
mask_tensor = TF.to_tensor(mask) # [1, H, W] in [0, 1]
return img_tensor, mask_tensor
# βββ Sampling βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
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
# βββ Inception Features for Precision/Recall ββββββββββββββββββββββββββ
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
# Resize to 299x299 for Inception
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()
# Compute pairwise distances
# For real manifold: k-th nearest neighbor distance among real samples
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] # k-th NN distance for each real sample
# For generated manifold: k-th nearest neighbor distance among generated samples
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]
# Precision: fraction of generated samples falling within the real manifold
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)])
# Recall: fraction of real samples falling within the generated manifold
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
# βββ Main βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
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")
# Load dataset (train split for FID comparison)
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")
# Load model
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)
# Initialize metrics
fid_metric = FrechetInceptionDistance(feature=2048, normalize=True).to(device)
inception_features = InceptionV3Features(device)
all_real_features = []
all_gen_features = []
# Generate and compute metrics
print(f"\nGenerating {num_samples} images and computing features...")
torch.manual_seed(0) # Reproducible noise
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)
# Generate
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 # [-1,1] -> [0,1]
# FID: update with real and generated (expects [0,1] float with normalize=True)
fid_metric.update(real_imgs.to(device), real=True)
fid_metric.update(gen, real=False)
# Inception features for P&R
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}")
# Compute Precision & Recall
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}")
# Save results
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 summary
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()
# Build model kwargs
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:
# Override checkpoint if provided
if args.ckpt:
CONFIGS[ds]["ckpt"] = args.ckpt
# Always run No-CFG
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)
# Also run CFG if requested
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)
# Clean up
gc.collect()
torch.cuda.empty_cache()
# Final summary
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)
|