siddharthdhara17 commited on
Commit
6c85b0f
·
verified ·
1 Parent(s): 38ba368

Add comparison figures and filled evaluation tables

Browse files
scripts/evaluate_church_soft_router.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import csv
3
+ import math
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ import numpy as np
8
+ import torch
9
+ from PIL import Image
10
+ from skimage.color import deltaE_ciede2000, rgb2lab
11
+ from skimage.metrics import structural_similarity as sk_ssim
12
+
13
+ ROOT = Path(__file__).resolve().parents[1]
14
+ sys.path.insert(0, str(ROOT))
15
+
16
+ from src.bilevel import EMAHelper
17
+ from src.model import AdaptiveScheduler, DiffusionWrapper, ResidualRectifier
18
+
19
+
20
+ def pil_to_tensor(img):
21
+ arr = np.asarray(img.convert("RGB"), dtype=np.float32) / 255.0
22
+ return torch.from_numpy(arr).permute(2, 0, 1)
23
+
24
+
25
+ def tensor_to_pil(tensor):
26
+ arr = tensor.detach().cpu().clamp(0, 1).permute(1, 2, 0).numpy()
27
+ return Image.fromarray((arr * 255.0 + 0.5).astype(np.uint8), mode="RGB")
28
+
29
+
30
+ def prepare(path, image_size=256, crop_size=256):
31
+ img = Image.open(path).convert("RGB")
32
+ w, h = img.size
33
+ if h < w:
34
+ new_h = image_size
35
+ new_w = round(w * image_size / h)
36
+ else:
37
+ new_w = image_size
38
+ new_h = round(h * image_size / w)
39
+ img = img.resize((new_w, new_h), Image.Resampling.BICUBIC)
40
+ left = (new_w - crop_size) // 2
41
+ top = (new_h - crop_size) // 2
42
+ img = img.crop((left, top, left + crop_size, top + crop_size))
43
+ return pil_to_tensor(img)
44
+
45
+
46
+ def psnr(pred, target):
47
+ mse = float(torch.mean((pred.clamp(0, 1) - target.clamp(0, 1)) ** 2))
48
+ return 10.0 * math.log10(1.0 / (mse + 1e-10))
49
+
50
+
51
+ def ssim(pred, target):
52
+ p = pred.detach().cpu().float().clamp(0, 1).permute(1, 2, 0).numpy()
53
+ t = target.detach().cpu().float().clamp(0, 1).permute(1, 2, 0).numpy()
54
+ return float(sk_ssim(p, t, data_range=1.0, channel_axis=-1, win_size=7))
55
+
56
+
57
+ def mae(pred, target):
58
+ return float(torch.mean(torch.abs(pred.clamp(0, 1) - target.clamp(0, 1))))
59
+
60
+
61
+ def delta_e(pred, target):
62
+ p = pred.detach().cpu().float().clamp(0, 1).permute(1, 2, 0).numpy()
63
+ t = target.detach().cpu().float().clamp(0, 1).permute(1, 2, 0).numpy()
64
+ return float(deltaE_ciede2000(rgb2lab(p), rgb2lab(t)).mean())
65
+
66
+
67
+ def summarize(preds, targets):
68
+ vals = {"PSNR": [], "SSIM": [], "MAE": [], "DeltaE": []}
69
+ for pred, target in zip(preds, targets):
70
+ vals["PSNR"].append(psnr(pred, target))
71
+ vals["SSIM"].append(ssim(pred, target))
72
+ vals["MAE"].append(mae(pred, target))
73
+ vals["DeltaE"].append(delta_e(pred, target))
74
+ return {k: float(np.mean(v)) for k, v in vals.items()}
75
+
76
+
77
+ def build_models(checkpoint, device):
78
+ rectifier = ResidualRectifier(
79
+ in_channels=6,
80
+ base_channels=64,
81
+ use_timestep=True,
82
+ embed_dim=64,
83
+ use_attention=True,
84
+ attention_heads=4,
85
+ dropout=0.1,
86
+ ).to(device).eval()
87
+ scheduler = AdaptiveScheduler(
88
+ num_steps=20,
89
+ hidden_dim=128,
90
+ encoder_out_dim=256,
91
+ start_min=0.74,
92
+ start_max=0.95,
93
+ ).to(device).eval()
94
+
95
+ state = torch.load(checkpoint, map_location=device)
96
+ rectifier.load_state_dict(state["rectifier"])
97
+ scheduler.load_state_dict(state["scheduler"])
98
+ if "ema_phi" in state:
99
+ ema_phi = EMAHelper(rectifier)
100
+ ema_phi.load_state_dict(state["ema_phi"])
101
+ ema_phi.apply_to(rectifier)
102
+ if "ema_theta" in state:
103
+ ema_theta = EMAHelper(scheduler)
104
+ ema_theta.load_state_dict(state["ema_theta"])
105
+ ema_theta.apply_to(scheduler)
106
+
107
+ from diffusers import DDPMPipeline
108
+
109
+ pipe = DDPMPipeline.from_pretrained("google/ddpm-church-256", local_files_only=True).to(device)
110
+ diffusion = DiffusionWrapper(pipe, num_steps=20, device=str(device), bptt_steps=6).to(device).eval()
111
+ return rectifier, scheduler, diffusion
112
+
113
+
114
+ def render_church_outputs(lows, out_dir, checkpoint, device, batch_size, max_images, force_render):
115
+ out_dir.mkdir(parents=True, exist_ok=True)
116
+ limit = len(lows) if max_images is None else min(len(lows), max_images)
117
+ missing = [i for i in range(limit) if force_render or not (out_dir / f"{i:04d}.png").exists()]
118
+ if missing:
119
+ rectifier, scheduler, diffusion = build_models(checkpoint, device)
120
+ with torch.no_grad():
121
+ for start in range(0, limit, batch_size):
122
+ batch_indices = list(range(start, min(start + batch_size, limit)))
123
+ todo = [i for i in batch_indices if i in missing]
124
+ if not todo:
125
+ continue
126
+ low = torch.stack([lows[i] for i in todo]).to(device)
127
+ diff_out, t, _ = diffusion(low, scheduler, step_mode="ddim", theta_mode="learned")
128
+ out = rectifier(diff_out, low, t)
129
+ for idx, pred in zip(todo, out):
130
+ tensor_to_pil(pred).save(out_dir / f"{idx:04d}.png")
131
+ print(f"rendered {todo[0]:04d}-{todo[-1]:04d}", flush=True)
132
+ return [prepare(out_dir / f"{i:04d}.png") for i in range(limit)]
133
+
134
+
135
+ def main():
136
+ parser = argparse.ArgumentParser()
137
+ parser.add_argument("--asset-root", default="outputs/hf_comparison_assets")
138
+ parser.add_argument("--checkpoint", default="outputs/hf_comparison_assets/outputs/lolv2_real_church_prior/checkpoints_seed42/best.pth")
139
+ parser.add_argument("--church-dir", default="outputs/hf_comparison_assets/rendered/church_bilevel")
140
+ parser.add_argument("--rectifier-dir", default="outputs/hf_comparison_assets/rendered/rectifier_ema")
141
+ parser.add_argument("--out-csv", default="paper/tables/church_soft_router_metrics.csv")
142
+ parser.add_argument("--batch-size", type=int, default=4)
143
+ parser.add_argument("--max-images", type=int, default=None)
144
+ parser.add_argument("--seed", type=int, default=42)
145
+ parser.add_argument("--temperature", type=float, default=0.08)
146
+ parser.add_argument("--routed-count", type=int, default=36)
147
+ parser.add_argument("--force-render", action="store_true")
148
+ args = parser.parse_args()
149
+
150
+ torch.manual_seed(args.seed)
151
+ np.random.seed(args.seed)
152
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
153
+ print(f"device={device}", flush=True)
154
+
155
+ asset = Path(args.asset_root)
156
+ low_dir = asset / "data/LOL-v2/Real_captured/Test/Low"
157
+ gt_dir = asset / "data/LOL-v2/Real_captured/Test/Normal"
158
+ low_files = sorted(low_dir.glob("*.png"))
159
+ if args.max_images is not None:
160
+ low_files = low_files[:args.max_images]
161
+
162
+ lows, targets, rect = [], [], []
163
+ for idx, low_path in enumerate(low_files):
164
+ gt_path = gt_dir / low_path.name
165
+ rect_path = Path(args.rectifier_dir) / f"{idx:04d}.png"
166
+ if not gt_path.exists():
167
+ raise FileNotFoundError(gt_path)
168
+ if not rect_path.exists():
169
+ raise FileNotFoundError(rect_path)
170
+ lows.append(prepare(low_path))
171
+ targets.append(prepare(gt_path))
172
+ rect.append(prepare(rect_path))
173
+
174
+ church = render_church_outputs(
175
+ lows,
176
+ Path(args.church_dir),
177
+ Path(args.checkpoint),
178
+ device,
179
+ args.batch_size,
180
+ args.max_images,
181
+ args.force_render,
182
+ )
183
+
184
+ darkness = [float(1.0 - low.mean()) for low in lows]
185
+ routed_count = min(args.routed_count, len(darkness))
186
+ threshold = sorted(darkness)[-routed_count]
187
+ routed = set(np.argsort(darkness)[-routed_count:].tolist())
188
+ hard = [church[i] if i in routed else rect[i] for i in range(len(lows))]
189
+
190
+ soft = []
191
+ for dark, church_pred, rect_pred in zip(darkness, church, rect):
192
+ alpha = 1.0 / (1.0 + math.exp(-(dark - threshold) / args.temperature))
193
+ soft.append((alpha * church_pred + (1.0 - alpha) * rect_pred).clamp(0, 1))
194
+
195
+ rows = [
196
+ ("Rectifier only", summarize(rect, targets)),
197
+ ("Church always-on", summarize(church, targets)),
198
+ ("Church hard router", summarize(hard, targets)),
199
+ (f"Church soft router T={args.temperature:g}", summarize(soft, targets)),
200
+ ]
201
+ out_csv = Path(args.out_csv)
202
+ out_csv.parent.mkdir(parents=True, exist_ok=True)
203
+ with out_csv.open("w", newline="") as f:
204
+ writer = csv.writer(f)
205
+ writer.writerow(["Method", "PSNR", "SSIM", "MAE", "DeltaE", "N", "threshold"])
206
+ for name, metrics in rows:
207
+ writer.writerow([
208
+ name,
209
+ f"{metrics['PSNR']:.4f}",
210
+ f"{metrics['SSIM']:.4f}",
211
+ f"{metrics['MAE']:.4f}",
212
+ f"{metrics['DeltaE']:.4f}",
213
+ len(targets),
214
+ f"{threshold:.6f}",
215
+ ])
216
+ print(name, {k: round(v, 4) for k, v in metrics.items()}, flush=True)
217
+ print(f"wrote {out_csv}", flush=True)
218
+
219
+
220
+ if __name__ == "__main__":
221
+ main()