NL3D commited on
Commit
47805b6
·
verified ·
1 Parent(s): 9a1bbbf

Add feed_forward_benchmark_nvs.py (feed-forward benchmark reference)

Browse files
Files changed (1) hide show
  1. feed_forward_benchmark_nvs.py +372 -0
feed_forward_benchmark_nvs.py ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Feed-forward novel view synthesis (NVS) benchmark — reference implementation
3
+ =============================================================================
4
+
5
+ This script standardizes **per-scene** NVS evaluation for **feed-forward** 3DGS /
6
+ Gaussian splatting style models that follow the AnySplat inference path used in
7
+ ``eval_nvs_full.py``.
8
+
9
+ Dataset layout
10
+ ------------
11
+ - ``--data_root``: directory whose **subfolders** are scene names.
12
+ - Each scene folder contains unordered RGB frames (``.png`` / ``.jpg`` / ``.jpeg``).
13
+ - Optional ``--scene_index``: JSON list of scene folder names to evaluate (subset).
14
+
15
+ Train / hold-out split (LLFF-style)
16
+ -----------------------------------
17
+ Frames are sorted by filename, then indexed ``0..N-1``.
18
+ - **Context** (conditioning): indices where ``idx % llffhold != 0`` (default ``llffhold=8``).
19
+ - **Target** (novel views to render): indices where ``idx % llffhold == 0``.
20
+
21
+ Metrics (on target views only)
22
+ ------------------------------
23
+ - PSNR, SSIM, LPIPS between predicted and ground-truth target images in **[0, 1]**.
24
+
25
+ Outputs
26
+ -------
27
+ - Per-scene folders under ``--output_root/<scene>/{gt,pred}/``.
28
+ - Timestamped summary ``<cwd>/<summary_prefix>_<timestamp>.txt``.
29
+ - Optional JSON of per-scene dicts with ``--save_json``.
30
+
31
+ Dependencies (when vendoring outside this repository)
32
+ -----------------------------------------------------
33
+ You need the same model and utilities as the parent project: ``AnySplat``,
34
+ ``pose_encoding_to_extri_intri``, ``process_image``, and ``src.evaluation.metrics``.
35
+
36
+ ``BENCHMARK_VERSION`` documents the protocol; bump when the split or metrics change.
37
+ """
38
+
39
+ from __future__ import annotations
40
+
41
+ import argparse
42
+ import datetime
43
+ import json
44
+ import os
45
+ import sys
46
+ from collections import defaultdict
47
+ from pathlib import Path
48
+ from typing import Any, TypedDict
49
+
50
+ import torch
51
+
52
+ # Repository root on sys.path (same pattern as legacy eval scripts).
53
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
54
+
55
+ from src.evaluation.metrics import compute_lpips, compute_psnr, compute_ssim
56
+ from src.misc.image_io import save_image
57
+ from src.model.encoder.vggt.utils.pose_enc import pose_encoding_to_extri_intri
58
+ from src.model.model.anysplat import AnySplat
59
+ from src.utils.image import process_image
60
+
61
+ BENCHMARK_VERSION = "1.0.0"
62
+ BENCHMARK_NAME = "feed_forward_nvs_llffhold"
63
+
64
+
65
+ class NVSSceneResult(TypedDict, total=False):
66
+ scene: str
67
+ ok: bool
68
+ psnr: float
69
+ ssim: float
70
+ lpips: float
71
+ error: str
72
+
73
+
74
+ def build_argparser() -> argparse.ArgumentParser:
75
+ parser = argparse.ArgumentParser(
76
+ description=(
77
+ f"{BENCHMARK_NAME} v{BENCHMARK_VERSION}: full NVS evaluation "
78
+ "without video dumping (PSNR / SSIM / LPIPS)."
79
+ )
80
+ )
81
+ parser.add_argument(
82
+ "--data_root",
83
+ type=str,
84
+ required=True,
85
+ help="Root directory containing per-scene image folders.",
86
+ )
87
+ parser.add_argument(
88
+ "--scene_index",
89
+ type=str,
90
+ default="",
91
+ help="Optional JSON file listing scene folder names.",
92
+ )
93
+ parser.add_argument(
94
+ "--llffhold",
95
+ type=int,
96
+ default=8,
97
+ help="LLFF holdout step for context/target split.",
98
+ )
99
+ parser.add_argument(
100
+ "--device",
101
+ type=str,
102
+ default="cuda",
103
+ help='Device, e.g. "cuda" or "cpu".',
104
+ )
105
+ parser.add_argument(
106
+ "--summary_prefix",
107
+ type=str,
108
+ default="nvs_results",
109
+ help="Output summary filename prefix.",
110
+ )
111
+ parser.add_argument(
112
+ "--output_root",
113
+ type=str,
114
+ default="outputs/nvs_full_eval",
115
+ help="Root directory for per-scene artifacts (gt/pred).",
116
+ )
117
+ parser.add_argument(
118
+ "--category_split_token",
119
+ type=str,
120
+ default="__",
121
+ help="Token used to infer category from scene name suffix.",
122
+ )
123
+ parser.add_argument(
124
+ "--save_json",
125
+ action="store_true",
126
+ help="Also save per-scene raw metrics in JSON.",
127
+ )
128
+ parser.add_argument(
129
+ "--pretrained_id",
130
+ type=str,
131
+ default="lhjiang/anysplat",
132
+ help="Hugging Face model id for AnySplat.from_pretrained.",
133
+ )
134
+ return parser
135
+
136
+
137
+ def load_scene_names(data_root: Path, scene_index: str) -> list[str]:
138
+ if scene_index:
139
+ with open(scene_index, "r", encoding="utf-8") as f:
140
+ names = json.load(f)
141
+ return [str(x) for x in names]
142
+ return sorted([p.name for p in data_root.iterdir() if p.is_dir()])
143
+
144
+
145
+ def infer_category(scene_name: str, split_token: str) -> str:
146
+ if split_token and split_token in scene_name:
147
+ return scene_name.rsplit(split_token, 1)[-1]
148
+ return "uncategorized"
149
+
150
+
151
+ @torch.no_grad()
152
+ def evaluate_one_scene(
153
+ model: AnySplat,
154
+ scene_dir: Path,
155
+ llffhold: int,
156
+ device: torch.device,
157
+ output_root: Path,
158
+ ) -> dict[str, Any]:
159
+ image_names = sorted(
160
+ [
161
+ str(p)
162
+ for p in scene_dir.iterdir()
163
+ if p.suffix.lower() in {".png", ".jpg", ".jpeg"}
164
+ ]
165
+ )
166
+ if len(image_names) < 2:
167
+ return {"ok": False, "error": "not enough images"}
168
+
169
+ images = [process_image(p) for p in image_names]
170
+ ctx_indices = [idx for idx in range(len(image_names)) if idx % llffhold != 0]
171
+ tgt_indices = [idx for idx in range(len(image_names)) if idx % llffhold == 0]
172
+ if not ctx_indices or not tgt_indices:
173
+ return {"ok": False, "error": "invalid context/target split"}
174
+
175
+ ctx_images = torch.stack([images[i] for i in ctx_indices], dim=0).unsqueeze(0).to(device)
176
+ tgt_images = torch.stack([images[i] for i in tgt_indices], dim=0).unsqueeze(0).to(device)
177
+ ctx_images = (ctx_images + 1) * 0.5
178
+ tgt_images = (tgt_images + 1) * 0.5
179
+ b, v, _, h, w = tgt_images.shape
180
+
181
+ encoder_output = model.encoder(
182
+ ctx_images,
183
+ global_step=0,
184
+ visualization_dump={},
185
+ )
186
+ gaussians, pred_context_pose = encoder_output.gaussians, encoder_output.pred_context_pose
187
+
188
+ num_context_view = ctx_images.shape[1]
189
+ vggt_input_image = torch.cat((ctx_images, tgt_images), dim=1).to(torch.bfloat16)
190
+ with torch.cuda.amp.autocast(enabled=False, dtype=torch.bfloat16):
191
+ aggregated_tokens_list, _ = model.encoder.aggregator(
192
+ vggt_input_image,
193
+ intermediate_layer_idx=model.encoder.cfg.intermediate_layer_idx,
194
+ )
195
+ with torch.cuda.amp.autocast(enabled=False):
196
+ fp32_tokens = [token.float() for token in aggregated_tokens_list]
197
+ pred_all_pose_enc = model.encoder.camera_head(fp32_tokens)[-1]
198
+ pred_all_extrinsic, pred_all_intrinsic = pose_encoding_to_extri_intri(
199
+ pred_all_pose_enc, vggt_input_image.shape[-2:]
200
+ )
201
+
202
+ extrinsic_padding = (
203
+ torch.tensor([0, 0, 0, 1], device=pred_all_extrinsic.device, dtype=pred_all_extrinsic.dtype)
204
+ .view(1, 1, 1, 4)
205
+ .repeat(b, vggt_input_image.shape[1], 1, 1)
206
+ )
207
+ pred_all_extrinsic = torch.cat([pred_all_extrinsic, extrinsic_padding], dim=2).inverse()
208
+
209
+ pred_all_intrinsic[:, :, 0] = pred_all_intrinsic[:, :, 0] / w
210
+ pred_all_intrinsic[:, :, 1] = pred_all_intrinsic[:, :, 1] / h
211
+ pred_all_context_extrinsic = pred_all_extrinsic[:, :num_context_view]
212
+ pred_all_target_extrinsic = pred_all_extrinsic[:, num_context_view:]
213
+ pred_all_target_intrinsic = pred_all_intrinsic[:, num_context_view:]
214
+
215
+ scale_factor = (
216
+ pred_context_pose["extrinsic"][:, :, :3, 3].mean()
217
+ / pred_all_context_extrinsic[:, :, :3, 3].mean()
218
+ )
219
+ pred_all_target_extrinsic[..., :3, 3] = pred_all_target_extrinsic[..., :3, 3] * scale_factor
220
+
221
+ output = model.decoder.forward(
222
+ gaussians,
223
+ pred_all_target_extrinsic,
224
+ pred_all_target_intrinsic.float(),
225
+ torch.ones(1, v, device=device) * 0.01,
226
+ torch.ones(1, v, device=device) * 100,
227
+ (h, w),
228
+ )
229
+
230
+ psnr = compute_psnr(output.color[0], tgt_images[0]).mean().item()
231
+ ssim = compute_ssim(output.color[0], tgt_images[0]).mean().item()
232
+ lpips = compute_lpips(output.color[0], tgt_images[0]).mean().item()
233
+
234
+ scene_out = output_root / scene_dir.name
235
+ for idx, (gt_image, pred_image) in enumerate(zip(tgt_images[0], output.color[0])):
236
+ save_image(gt_image, scene_out / "gt" / f"{idx:0>6}.jpg")
237
+ save_image(pred_image, scene_out / "pred" / f"{idx:0>6}.jpg")
238
+
239
+ return {"ok": True, "psnr": psnr, "ssim": ssim, "lpips": lpips}
240
+
241
+
242
+ def write_summary(
243
+ output_txt: Path,
244
+ results: list[dict[str, Any]],
245
+ category_split_token: str,
246
+ ) -> None:
247
+ per_category: dict[str, list[dict[str, Any]]] = defaultdict(list)
248
+ for r in results:
249
+ if r.get("ok"):
250
+ c = infer_category(r["scene"], category_split_token)
251
+ per_category[c].append(r)
252
+
253
+ with output_txt.open("w", encoding="utf-8") as f:
254
+ f.write(f"NVS Evaluation Results ({BENCHMARK_NAME} v{BENCHMARK_VERSION})\n")
255
+ f.write("=" * 50 + "\n\n")
256
+ f.write("Per-category results:\n")
257
+ f.write("-" * 50 + "\n")
258
+ for c in sorted(per_category.keys()):
259
+ vals = per_category[c]
260
+ f.write(f"{c:<22} PSNR: {sum(v['psnr'] for v in vals) / len(vals):.4f}\n")
261
+ f.write(f"{c:<22} SSIM: {sum(v['ssim'] for v in vals) / len(vals):.4f}\n")
262
+ f.write(f"{c:<22} LPIPS: {sum(v['lpips'] for v in vals) / len(vals):.4f}\n")
263
+ f.write("\n")
264
+
265
+ ok_vals = [r for r in results if r.get("ok")]
266
+ f.write("-" * 50 + "\n")
267
+ if ok_vals:
268
+ f.write(f"Mean PSNR: {sum(v['psnr'] for v in ok_vals) / len(ok_vals):.4f}\n")
269
+ f.write(f"Mean SSIM: {sum(v['ssim'] for v in ok_vals) / len(ok_vals):.4f}\n")
270
+ f.write(f"Mean LPIPS: {sum(v['lpips'] for v in ok_vals) / len(ok_vals):.4f}\n")
271
+ f.write(f"Num scenes (success): {len(ok_vals)}\n")
272
+
273
+ fail_vals = [r for r in results if not r.get("ok")]
274
+ if fail_vals:
275
+ f.write(f"Num scenes (failed): {len(fail_vals)}\n")
276
+ f.write("\n" + "=" * 50 + "\n")
277
+
278
+
279
+ def run_feed_forward_nvs_benchmark(args: argparse.Namespace) -> list[dict[str, Any]]:
280
+ """
281
+ Run the full benchmark over ``args.data_root`` and return per-scene result dicts.
282
+
283
+ Side effects: writes ``--output_root`` scene folders, summary txt under cwd,
284
+ and optional JSON when ``args.save_json`` is True.
285
+ """
286
+ data_root = Path(args.data_root)
287
+ if not data_root.exists():
288
+ raise FileNotFoundError(f"Data root does not exist: {data_root}")
289
+
290
+ if args.device == "cuda" and not torch.cuda.is_available():
291
+ print("CUDA not available, fallback to CPU.", flush=True)
292
+ device = torch.device("cpu")
293
+ else:
294
+ device = torch.device(args.device)
295
+
296
+ print(
297
+ f"Loading AnySplat ({args.pretrained_id}) [{BENCHMARK_NAME} v{BENCHMARK_VERSION}]...",
298
+ flush=True,
299
+ )
300
+ model = AnySplat.from_pretrained(args.pretrained_id)
301
+ model.to(device)
302
+ model.eval()
303
+ for p in model.parameters():
304
+ p.requires_grad = False
305
+ print(f"Using device: {device}", flush=True)
306
+
307
+ scene_names = load_scene_names(data_root, args.scene_index)
308
+ print(f"Found {len(scene_names)} scenes to evaluate.", flush=True)
309
+ output_root = Path(args.output_root)
310
+ output_root.mkdir(parents=True, exist_ok=True)
311
+
312
+ results: list[dict[str, Any]] = []
313
+ for i, scene_name in enumerate(scene_names, start=1):
314
+ scene_dir = data_root / scene_name
315
+ if not scene_dir.is_dir():
316
+ results.append({"scene": scene_name, "ok": False, "error": "scene folder missing"})
317
+ print(f"[{i}/{len(scene_names)}] FAILED {scene_name}: folder missing", flush=True)
318
+ continue
319
+ try:
320
+ one = evaluate_one_scene(
321
+ model=model,
322
+ scene_dir=scene_dir,
323
+ llffhold=args.llffhold,
324
+ device=device,
325
+ output_root=output_root,
326
+ )
327
+ one["scene"] = scene_name
328
+ results.append(one)
329
+ if one.get("ok"):
330
+ print(
331
+ f"[{i}/{len(scene_names)}] {scene_name} -> "
332
+ f"PSNR {one['psnr']:.2f}, SSIM {one['ssim']:.3f}, LPIPS {one['lpips']:.3f}",
333
+ flush=True,
334
+ )
335
+ else:
336
+ print(f"[{i}/{len(scene_names)}] FAILED {scene_name}: {one.get('error')}", flush=True)
337
+ except Exception as e:
338
+ results.append({"scene": scene_name, "ok": False, "error": str(e)})
339
+ print(f"[{i}/{len(scene_names)}] FAILED {scene_name}: {e}", flush=True)
340
+ finally:
341
+ if torch.cuda.is_available():
342
+ torch.cuda.empty_cache()
343
+
344
+ timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
345
+ summary_path = Path.cwd() / f"{args.summary_prefix}_{timestamp}.txt"
346
+ write_summary(summary_path, results, args.category_split_token)
347
+ print(f"Summary saved to: {summary_path}", flush=True)
348
+
349
+ if args.save_json:
350
+ raw_path = Path.cwd() / f"{args.summary_prefix}_{timestamp}.json"
351
+ payload = {
352
+ "benchmark": BENCHMARK_NAME,
353
+ "version": BENCHMARK_VERSION,
354
+ "pretrained_id": args.pretrained_id,
355
+ "llffhold": args.llffhold,
356
+ "scenes": results,
357
+ }
358
+ with raw_path.open("w", encoding="utf-8") as f:
359
+ json.dump(payload, f, indent=2)
360
+ print(f"Raw scene metrics saved to: {raw_path}", flush=True)
361
+
362
+ return results
363
+
364
+
365
+ def main() -> None:
366
+ parser = build_argparser()
367
+ args = parser.parse_args()
368
+ run_feed_forward_nvs_benchmark(args)
369
+
370
+
371
+ if __name__ == "__main__":
372
+ main()