NL3D commited on
Commit
5f08626
·
verified ·
1 Parent(s): 47805b6

Add feed_forward_benchmark_pose_co3d.py (feed-forward benchmark reference)

Browse files
Files changed (1) hide show
  1. feed_forward_benchmark_pose_co3d.py +759 -0
feed_forward_benchmark_pose_co3d.py ADDED
@@ -0,0 +1,759 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Feed-forward camera pose benchmark on CO3D (multi-backend) — reference implementation
3
+ ======================================================================================
4
+
5
+ This script standardizes **relative pose error** evaluation on the **Common Objects
6
+ in 3D (CO3D)** test annotations, following the protocol in ``eval_pose_vggt.py``.
7
+
8
+ Supported backends (``--backends``)
9
+ -----------------------------------
10
+ - ``anysplat_baseline``: ``AnySplat.from_pretrained`` (feed-forward encoder + pose head path used in ``src.eval_pose.process_sequence``).
11
+ - ``vggt``: ``VGGT.from_pretrained`` with ``pose_enc`` decoded via ``pose_encoding_to_extri_intri``.
12
+ - ``anysplat_finetune``: optional; requires ``--finetune_ckpt``.
13
+
14
+ Sampling & reproducibility
15
+ --------------------------
16
+ - By default, each category builds a **fixed sampling plan**: ``num_frames`` indices per
17
+ sequence, gated by ``min_num_images`` and max image size ``>= 448`` (same gates as the
18
+ legacy script). The plan is written to ``<output>/co3d_sampling_plan.json``.
19
+ - Pass ``--sampling_plan_path`` to reuse a saved plan (recommended for paper numbers).
20
+
21
+ Metrics
22
+ -------
23
+ - Per-frame relative rotation / translation errors vs. GT extrinsics, then **AUC**
24
+ curves at thresholds **5°, 10°, 20°, 30°** (``calculate_auc_np``), aggregated per
25
+ category and mean over categories.
26
+
27
+ Pose alignment (``--pose_postprocess``)
28
+ ---------------------------------------
29
+ - ``legacy``: align GT to the first camera only (AnySplat path flag ``gt_only``; VGGT ``gt_only``).
30
+ - ``align_both``: align **both** predictions and GT to the first camera before error.
31
+
32
+ Outputs
33
+ -------
34
+ - ``co3d_pose_metrics.json``, ``co3d_pose_summary.txt`` under ``--output_dir/<run_tag>/``.
35
+
36
+ Dependencies when vendoring
37
+ ---------------------------
38
+ Requires CO3D images + ``*_test.jgz`` annotations, VGGT / AnySplat code paths under
39
+ ``src.model``, ``src.utils.pose``, and ``src.eval_pose.process_sequence``.
40
+
41
+ ``BENCHMARK_VERSION`` documents the protocol; bump when sampling, AUC definition, or
42
+ alignment semantics change.
43
+ """
44
+
45
+ from __future__ import annotations
46
+
47
+ import os
48
+ import sys
49
+ import json
50
+ import gzip
51
+ import argparse
52
+ import datetime
53
+ import gc
54
+ from pathlib import Path
55
+ from typing import Any, Callable, Dict, List, Optional, Tuple
56
+
57
+ import numpy as np
58
+ from PIL import Image
59
+
60
+ import torch
61
+
62
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
63
+
64
+ from src.model.encoder.vggt.models.vggt import VGGT
65
+ from src.model.encoder.vggt.utils.pose_enc import pose_encoding_to_extri_intri
66
+ from src.model.encoder.vggt.utils.load_fn import load_and_preprocess_images
67
+ from src.model.model.anysplat import AnySplat
68
+ from src.utils.pose import (
69
+ align_to_first_camera,
70
+ calculate_auc_np,
71
+ convert_pt3d_RT_to_opencv,
72
+ se3_to_relative_pose_error,
73
+ )
74
+ from src.eval_pose import process_sequence as process_sequence_anysplat
75
+
76
+ BENCHMARK_VERSION = "1.0.0"
77
+ BENCHMARK_NAME = "feed_forward_pose_co3d_multi_backend"
78
+
79
+
80
+ def setup_args():
81
+ parser = argparse.ArgumentParser(
82
+ description=(
83
+ f"{BENCHMARK_NAME} v{BENCHMARK_VERSION}: CO3D pose eval for feed-forward models "
84
+ "(AnySplat baseline, VGGT, optional finetune; fixed frame ids via sampling plan; "
85
+ "pose postprocess options)."
86
+ )
87
+ )
88
+ parser.add_argument("--debug", action="store_true", help="Enable debug mode (only test on specific category)")
89
+ parser.add_argument("--use_ba", action="store_true", default=False, help="Bundle adjustment (AnySplat backends only)")
90
+ parser.add_argument("--fast_eval", action="store_true", default=False, help="Only evaluate 10 sequences per category")
91
+ parser.add_argument("--min_num_images", type=int, default=50, help="Minimum number of images for a sequence")
92
+ parser.add_argument("--num_frames", type=int, default=10, help="Number of frames to use for testing")
93
+ parser.add_argument("--co3d_dir", type=str, required=True, help="Path to CO3D dataset")
94
+ parser.add_argument("--co3d_anno_dir", type=str, required=True, help="Path to CO3D annotations")
95
+ parser.add_argument(
96
+ "--categories",
97
+ type=str,
98
+ default="auto",
99
+ help='Comma-separated categories, or "auto" to detect from *_test.jgz',
100
+ )
101
+ parser.add_argument("--seed", type=int, default=0, help="Random seed for sampling (scan phase only)")
102
+ parser.add_argument(
103
+ "--vggt_repo_id",
104
+ type=str,
105
+ default="facebook/VGGT-1B",
106
+ help='HuggingFace repo id for VGGT weights (default: "facebook/VGGT-1B")',
107
+ )
108
+ parser.add_argument(
109
+ "--anysplat_pretrained_id",
110
+ type=str,
111
+ default="lhjiang/anysplat",
112
+ help="HuggingFace id for baseline AnySplat",
113
+ )
114
+ parser.add_argument(
115
+ "--finetune_ckpt",
116
+ type=str,
117
+ default=None,
118
+ help="Finetuned weights: .ckpt, run dir with checkpoints/, or HF-style AnySplat folder.",
119
+ )
120
+ parser.add_argument(
121
+ "--output_dir",
122
+ type=str,
123
+ default="output/exp_output2_bench_finetune_singlegpu_gt",
124
+ help="Root directory for this evaluation run.",
125
+ )
126
+ parser.add_argument(
127
+ "--run_tag",
128
+ type=str,
129
+ default=None,
130
+ help='Subfolder under output_dir (default: timestamp "%%Y-%%m-%%d_%%H-%%M-%%S").',
131
+ )
132
+ parser.add_argument(
133
+ "--sampling_plan_path",
134
+ type=str,
135
+ default=None,
136
+ help="If set, load co3d_sampling_plan.json from this path and skip the scan phase (must match categories / annotations).",
137
+ )
138
+ parser.add_argument(
139
+ "--pose_postprocess",
140
+ type=str,
141
+ choices=["legacy", "align_both"],
142
+ default="legacy",
143
+ help="legacy: align GT to first camera only (previous behavior). align_both: align pred and GT to first camera on all backends.",
144
+ )
145
+ parser.add_argument(
146
+ "--backends",
147
+ type=str,
148
+ default="all",
149
+ help='Which models to run, comma-separated: anysplat_baseline, vggt, anysplat_finetune. '
150
+ 'Use "all" to run baseline + VGGT and also anysplat_finetune when --finetune_ckpt is set.',
151
+ )
152
+ return parser.parse_args()
153
+
154
+
155
+ def parse_backends_selection(backends: str, finetune_ckpt: Optional[str]) -> List[str]:
156
+ raw = backends.strip().lower()
157
+ allowed = frozenset({"anysplat_baseline", "vggt", "anysplat_finetune"})
158
+ if raw == "all":
159
+ out = ["anysplat_baseline", "vggt"]
160
+ if finetune_ckpt:
161
+ out.append("anysplat_finetune")
162
+ else:
163
+ print("[info] --backends all: omitting anysplat_finetune (pass --finetune_ckpt to include it)")
164
+ return out
165
+ names = [x.strip().lower() for x in backends.split(",") if x.strip()]
166
+ if not names:
167
+ raise SystemExit("--backends is empty; use e.g. anysplat_finetune or all")
168
+ seen = set()
169
+ deduped: List[str] = []
170
+ for n in names:
171
+ if n in seen:
172
+ continue
173
+ seen.add(n)
174
+ deduped.append(n)
175
+ names = deduped
176
+ for n in names:
177
+ if n not in allowed:
178
+ raise SystemExit(f"Unknown backend {n!r}. Allowed: {sorted(allowed)}")
179
+ if "anysplat_finetune" in names and not finetune_ckpt:
180
+ raise SystemExit("Including anysplat_finetune requires --finetune_ckpt")
181
+ return names
182
+
183
+
184
+ def build_backends_for_eval(
185
+ selected: List[str],
186
+ args: argparse.Namespace,
187
+ device: torch.device,
188
+ ) -> List[Tuple[str, Callable[[], torch.nn.Module], str]]:
189
+ """Return list of (name, loader, kind) in the same order as ``selected``."""
190
+ out: List[Tuple[str, Callable[[], torch.nn.Module], str]] = []
191
+ for name in selected:
192
+ if name == "anysplat_baseline":
193
+ hf = args.anysplat_pretrained_id
194
+ out.append((name, lambda hf=hf: AnySplat.from_pretrained(hf), "anysplat"))
195
+ elif name == "vggt":
196
+ rid = args.vggt_repo_id
197
+ out.append((name, lambda rid=rid: VGGT.from_pretrained(rid), "vggt"))
198
+ elif name == "anysplat_finetune":
199
+ ck = args.finetune_ckpt
200
+ bid = args.anysplat_pretrained_id
201
+ out.append((name, lambda ck=ck, bid=bid: load_finetune_anysplat(ck, device, bid), "anysplat"))
202
+ else:
203
+ raise RuntimeError(f"Unhandled backend: {name}")
204
+ return out
205
+
206
+
207
+ def _anysplat_pose_align_flag(pose_postprocess: str) -> str:
208
+ return "both" if pose_postprocess == "align_both" else "gt_only"
209
+
210
+
211
+ def _vggt_align_mode(pose_postprocess: str) -> str:
212
+ return "both" if pose_postprocess == "align_both" else "gt_only"
213
+
214
+
215
+ def prepare_co3d_views(
216
+ seq_data: list,
217
+ co3d_dir: str,
218
+ min_num_images: int,
219
+ num_frames: int,
220
+ rng: np.random.Generator,
221
+ ) -> Optional[Dict[str, Any]]:
222
+ """
223
+ Same gate + RNG semantics as the original per-sequence eval:
224
+ rng.choice is executed only after a valid metadata list is built; if max_size < 448 after that, returns None but RNG was already consumed.
225
+ """
226
+ if len(seq_data) < min_num_images:
227
+ return None
228
+
229
+ metadata = []
230
+ for data in seq_data:
231
+ if data["T"][0] + data["T"][1] + data["T"][2] > 1e5:
232
+ return None
233
+ extri_opencv = convert_pt3d_RT_to_opencv(data["R"], data["T"])
234
+ metadata.append({"filepath": data["filepath"], "extri": extri_opencv})
235
+
236
+ ids = rng.choice(len(metadata), num_frames, replace=False)
237
+ frame_filepaths = [metadata[int(i)]["filepath"] for i in ids]
238
+ image_names = [os.path.join(co3d_dir, fp) for fp in frame_filepaths]
239
+ gt_extri = np.stack([np.array(metadata[int(i)]["extri"]) for i in ids], axis=0)
240
+
241
+ max_size = max(Image.open(image_names[0]).size)
242
+ if max_size < 448:
243
+ return None
244
+
245
+ return {
246
+ "ids": ids.astype(np.int64),
247
+ "frame_filepaths": frame_filepaths,
248
+ "gt_extri": gt_extri,
249
+ }
250
+
251
+
252
+ def plan_entry_to_json(entry: Dict[str, Any]) -> dict:
253
+ return {
254
+ "seq_name": entry["seq_name"],
255
+ "ids": [int(x) for x in entry["ids"]],
256
+ "frame_filepaths": list(entry["frame_filepaths"]),
257
+ "gt_extri": np.asarray(entry["gt_extri"], dtype=np.float64).tolist(),
258
+ }
259
+
260
+
261
+ def plan_entry_from_json(obj: dict, co3d_dir: str) -> Dict[str, Any]:
262
+ ids = np.asarray(obj["ids"], dtype=np.int64)
263
+ fps = list(obj["frame_filepaths"])
264
+ image_names = [os.path.join(co3d_dir, fp) for fp in fps]
265
+ gt_extri = np.asarray(obj["gt_extri"], dtype=np.float64)
266
+ return {
267
+ "seq_name": obj["seq_name"],
268
+ "ids": ids,
269
+ "frame_filepaths": fps,
270
+ "image_names": image_names,
271
+ "gt_extri": gt_extri,
272
+ }
273
+
274
+
275
+ def build_sampling_plan(
276
+ args: argparse.Namespace,
277
+ categories: List[str],
278
+ ) -> Dict[str, List[dict]]:
279
+ rng = np.random.default_rng(args.seed)
280
+ plan: Dict[str, List[dict]] = {c: [] for c in categories}
281
+
282
+ for category in categories:
283
+ annotation_file = os.path.join(args.co3d_anno_dir, f"{category}_test.jgz")
284
+ try:
285
+ with gzip.open(annotation_file, "r") as fin:
286
+ annotation = json.loads(fin.read())
287
+ except FileNotFoundError:
288
+ print(f"Annotation file not found for {category}, skipping plan")
289
+ continue
290
+
291
+ n_success = 0
292
+ for seq_name, seq_data in annotation.items():
293
+ if args.debug and not os.path.exists(os.path.join(args.co3d_dir, category, seq_name)):
294
+ continue
295
+
296
+ prep = prepare_co3d_views(
297
+ seq_data,
298
+ args.co3d_dir,
299
+ args.min_num_images,
300
+ args.num_frames,
301
+ rng,
302
+ )
303
+ if prep is None:
304
+ continue
305
+
306
+ entry = {"seq_name": seq_name, **prep}
307
+ plan[category].append(plan_entry_to_json(entry))
308
+ n_success += 1
309
+
310
+ if args.fast_eval and n_success >= 10:
311
+ break
312
+
313
+ return plan
314
+
315
+
316
+ def save_sampling_plan(path: Path, plan: Dict[str, List[dict]], meta: dict) -> None:
317
+ payload = {"version": 1, "meta": meta, "plan": plan}
318
+ path.parent.mkdir(parents=True, exist_ok=True)
319
+ with open(path, "w") as f:
320
+ json.dump(payload, f, indent=2)
321
+ print(f"Saved sampling plan to {path}")
322
+
323
+
324
+ def load_sampling_plan(path: Path, co3d_dir: str) -> Dict[str, List[Dict[str, Any]]]:
325
+ with open(path, "r") as f:
326
+ payload = json.load(f)
327
+ raw_plan = payload.get("plan", payload)
328
+ out: Dict[str, List[Dict[str, Any]]] = {}
329
+ for cat, entries in raw_plan.items():
330
+ out[cat] = [plan_entry_from_json(e, co3d_dir) for e in entries]
331
+ print(f"Loaded sampling plan from {path} ({sum(len(v) for v in out.values())} entries)")
332
+ return out
333
+
334
+
335
+ def _relative_pose_errors_from_extrinsics(
336
+ pred_extrinsic: torch.Tensor,
337
+ gt_extri_np: np.ndarray,
338
+ num_frames: int,
339
+ device: torch.device,
340
+ align_mode: str,
341
+ ) -> Tuple[np.ndarray, np.ndarray]:
342
+ gt_extrinsic = torch.from_numpy(gt_extri_np).to(device)
343
+ add_row = torch.tensor([0, 0, 0, 1], device=device).expand(pred_extrinsic.size(0), 1, 4)
344
+ pred_se3 = torch.cat((pred_extrinsic, add_row), dim=1)
345
+ gt_se3 = torch.cat((gt_extrinsic, add_row), dim=1)
346
+
347
+ if align_mode == "gt_only":
348
+ gt_se3 = align_to_first_camera(gt_se3)
349
+ elif align_mode == "both":
350
+ pred_se3 = align_to_first_camera(pred_se3)
351
+ gt_se3 = align_to_first_camera(gt_se3)
352
+ else:
353
+ raise ValueError(f"Unknown align_mode: {align_mode}")
354
+
355
+ rel_rangle_deg, rel_tangle_deg = se3_to_relative_pose_error(pred_se3, gt_se3, num_frames)
356
+ return rel_rangle_deg.cpu().numpy(), rel_tangle_deg.cpu().numpy()
357
+
358
+
359
+ def infer_vggt_on_plan_entry(
360
+ model,
361
+ prepared: Dict[str, Any],
362
+ category: str,
363
+ seq_name: str,
364
+ num_frames: int,
365
+ device: torch.device,
366
+ dtype: torch.dtype,
367
+ align_mode: str,
368
+ ) -> Tuple[np.ndarray, np.ndarray]:
369
+ image_names = prepared["image_names"]
370
+ gt_extri = prepared["gt_extri"]
371
+ images = load_and_preprocess_images(image_names)[None].to(device)
372
+
373
+ with torch.no_grad(), torch.cuda.amp.autocast(dtype=dtype):
374
+ pred = model(images)
375
+ pred_all_pose_enc = pred["pose_enc"]
376
+
377
+ with torch.cuda.amp.autocast(dtype=torch.float32):
378
+ pred_all_extrinsic, _ = pose_encoding_to_extri_intri(pred_all_pose_enc, images.shape[-2:])
379
+ pred_extrinsic = pred_all_extrinsic[0]
380
+
381
+ rel_r, rel_t = _relative_pose_errors_from_extrinsics(
382
+ pred_extrinsic, gt_extri, num_frames, device, align_mode
383
+ )
384
+ print(f"{category} sequence {seq_name} Rot Error: {rel_r.mean():.4f}")
385
+ print(f"{category} sequence {seq_name} Trans Error: {rel_t.mean():.4f}")
386
+ return rel_r, rel_t
387
+
388
+
389
+ def _resolve_checkpoint_file(path: Path) -> Path:
390
+ path = path.expanduser().resolve()
391
+ if path.is_file():
392
+ return path
393
+ if path.is_dir():
394
+ ckpt_dir = path / "checkpoints"
395
+ if ckpt_dir.is_dir():
396
+ ckpts = list(ckpt_dir.glob("*.ckpt"))
397
+ if ckpts:
398
+ ckpts.sort(key=lambda p: p.stat().st_mtime)
399
+ return ckpts[-1]
400
+ ckpts = sorted(path.glob("**/*.ckpt"), key=lambda p: p.stat().st_mtime)
401
+ if ckpts:
402
+ return ckpts[-1]
403
+ if (path / "config.json").exists():
404
+ return path
405
+ raise FileNotFoundError(f"No checkpoint or AnySplat bundle found at: {path}")
406
+
407
+
408
+ def load_finetune_anysplat(ckpt: str, device: torch.device, base_hf_id: str = "lhjiang/anysplat") -> AnySplat:
409
+ resolved = _resolve_checkpoint_file(Path(ckpt))
410
+ if resolved.is_dir():
411
+ model = AnySplat.from_pretrained(str(resolved))
412
+ model.to(device)
413
+ model.eval()
414
+ for p in model.parameters():
415
+ p.requires_grad = False
416
+ return model
417
+
418
+ model = AnySplat.from_pretrained(base_hf_id)
419
+ try:
420
+ blob = torch.load(resolved, map_location="cpu", weights_only=False)
421
+ except TypeError:
422
+ blob = torch.load(resolved, map_location="cpu")
423
+ state = blob["state_dict"] if isinstance(blob, dict) and "state_dict" in blob else blob
424
+ if not isinstance(state, dict):
425
+ raise ValueError(f"Unexpected checkpoint format in {resolved}")
426
+
427
+ stripped: Dict[str, Any] = {}
428
+ for k, v in state.items():
429
+ nk = k
430
+ if nk.startswith("module."):
431
+ nk = nk[len("module.") :]
432
+ if nk.startswith("model."):
433
+ nk = nk[len("model.") :]
434
+ stripped[nk] = v
435
+
436
+ model_keys = set(model.state_dict().keys())
437
+ stripped_keys = set(stripped.keys())
438
+ overlap = len(model_keys & stripped_keys)
439
+ print(
440
+ f"[finetune] ckpt keys={len(stripped)} overlap_with_AnySplat={overlap} / {len(model_keys)} "
441
+ f"(resolved file: {resolved})"
442
+ )
443
+
444
+ missing, unexpected = model.load_state_dict(stripped, strict=False)
445
+ print(f"[finetune] load_state_dict strict=False: missing={len(missing)}, unexpected={len(unexpected)}")
446
+ if missing:
447
+ print(f"[finetune] missing (first 8): {missing[:8]}")
448
+ if unexpected:
449
+ print(f"[finetune] unexpected (first 8): {unexpected[:8]}")
450
+ if overlap < 50 or len(missing) > len(model_keys) * 0.25:
451
+ print(
452
+ "[finetune][warn] Few keys matched the Hub AnySplat — weights may be mostly baseline or load is wrong; "
453
+ "pose metrics can be misleading."
454
+ )
455
+ model.to(device)
456
+ model.eval()
457
+ for p in model.parameters():
458
+ p.requires_grad = False
459
+ return model
460
+
461
+
462
+ def _finalize_category(r_error_list: List[float], t_error_list: List[float]) -> Optional[Dict[str, Any]]:
463
+ if not r_error_list:
464
+ return None
465
+ r_error = np.array(r_error_list)
466
+ t_error = np.array(t_error_list)
467
+ thresholds = [5, 10, 20, 30]
468
+ aucs = {}
469
+ for th in thresholds:
470
+ auc, _ = calculate_auc_np(r_error, t_error, max_threshold=th)
471
+ aucs[th] = auc
472
+ return {
473
+ "rError": r_error,
474
+ "tError": t_error,
475
+ "Auc_5": aucs[5],
476
+ "Auc_10": aucs[10],
477
+ "Auc_20": aucs[20],
478
+ "Auc_30": aucs[30],
479
+ }
480
+
481
+
482
+ def _run_one_backend_on_plan(
483
+ backend_name: str,
484
+ model: torch.nn.Module,
485
+ backend_kind: str,
486
+ plan: Dict[str, List[Dict[str, Any]]],
487
+ args: argparse.Namespace,
488
+ categories: List[str],
489
+ device: torch.device,
490
+ dtype: torch.dtype,
491
+ pose_align_anysplat: str,
492
+ vggt_align_mode: str,
493
+ ) -> Dict[str, Any]:
494
+ per_category: Dict[str, Any] = {}
495
+ _unused_rng = np.random.default_rng(0)
496
+
497
+ for category in categories:
498
+ entries = plan.get(category) or []
499
+ if not entries:
500
+ print(f"[{backend_name}] No cached entries for {category}, skipping")
501
+ continue
502
+
503
+ annotation_file = os.path.join(args.co3d_anno_dir, f"{category}_test.jgz")
504
+ try:
505
+ with gzip.open(annotation_file, "r") as fin:
506
+ annotation = json.loads(fin.read())
507
+ except FileNotFoundError:
508
+ print(f"Annotation file not found for {category}, skipping")
509
+ continue
510
+
511
+ print(f"[{backend_name}] Evaluating {len(entries)} cached sequences for {category}")
512
+ r_err: List[float] = []
513
+ t_err: List[float] = []
514
+
515
+ for prepared in entries:
516
+ seq_name = prepared["seq_name"]
517
+ print("-" * 50)
518
+ print(f"[{backend_name}] {category} / {seq_name}")
519
+
520
+ if args.debug and not os.path.exists(os.path.join(args.co3d_dir, category, seq_name)):
521
+ print(f"Skipping {seq_name} (not found)")
522
+ continue
523
+
524
+ seq_data = annotation.get(seq_name)
525
+ if seq_data is None:
526
+ print(f"No annotation for {seq_name}, skipping")
527
+ continue
528
+
529
+ if backend_kind == "vggt":
530
+ seq_r, seq_t = infer_vggt_on_plan_entry(
531
+ model,
532
+ prepared,
533
+ category,
534
+ seq_name,
535
+ args.num_frames,
536
+ device,
537
+ dtype,
538
+ vggt_align_mode,
539
+ )
540
+ elif backend_kind == "anysplat":
541
+ seq_r, seq_t = process_sequence_anysplat(
542
+ model,
543
+ seq_name,
544
+ seq_data,
545
+ category,
546
+ args.co3d_dir,
547
+ args.min_num_images,
548
+ args.num_frames,
549
+ args.use_ba,
550
+ device,
551
+ dtype,
552
+ _unused_rng,
553
+ frame_ids=prepared["ids"],
554
+ pose_align=pose_align_anysplat,
555
+ )
556
+ else:
557
+ raise ValueError(f"Unknown backend_kind: {backend_kind}")
558
+
559
+ print("-" * 50)
560
+ if seq_r is not None and seq_t is not None:
561
+ r_err.extend(np.asarray(seq_r).reshape(-1).tolist())
562
+ t_err.extend(np.asarray(seq_t).reshape(-1).tolist())
563
+
564
+ fin = _finalize_category(r_err, t_err)
565
+ if fin is None:
566
+ print(f"No valid results for {category} ({backend_name}), skipping")
567
+ continue
568
+
569
+ print("=" * 80)
570
+ print(f"[{backend_name}] AUC of {category} test set: {fin['Auc_30']:.4f}")
571
+ print("=" * 80)
572
+ per_category[category] = fin
573
+
574
+ return per_category
575
+
576
+
577
+ def _print_and_collect_means(per_category: Dict[str, Any]) -> Dict[str, float]:
578
+ means = {}
579
+ if not per_category:
580
+ return means
581
+ for key in ["Auc_5", "Auc_10", "Auc_20", "Auc_30"]:
582
+ means[key] = float(np.mean([per_category[c][key] for c in per_category]))
583
+ print("\nSummary of AUC results:")
584
+ print("-" * 50)
585
+ for category in sorted(per_category.keys()):
586
+ print(f"{category:<15} AUC_5: {per_category[category]['Auc_5']:.4f}")
587
+ print(f"{category:<15} AUC_30: {per_category[category]['Auc_30']:.4f}")
588
+ print(f"{category:<15} AUC_20: {per_category[category]['Auc_20']:.4f}")
589
+ print(f"{category:<15} AUC_10: {per_category[category]['Auc_10']:.4f}")
590
+ print("-" * 50)
591
+ print(f"Mean AUC_5: {means['Auc_5']:.4f}")
592
+ print(f"Mean AUC_30: {means['Auc_30']:.4f}")
593
+ print(f"Mean AUC_20: {means['Auc_20']:.4f}")
594
+ print(f"Mean AUC_10: {means['Auc_10']:.4f}")
595
+ return means
596
+
597
+
598
+ def _save_results(
599
+ out_root: Path,
600
+ args: argparse.Namespace,
601
+ all_backends: Dict[str, Dict[str, Any]],
602
+ all_means: Dict[str, Dict[str, float]],
603
+ ):
604
+ out_root.mkdir(parents=True, exist_ok=True)
605
+
606
+ serializable = {}
607
+ for bname, per_cat in all_backends.items():
608
+ serializable[bname] = {}
609
+ for cat, d in per_cat.items():
610
+ serializable[bname][cat] = {
611
+ "Auc_5": float(d["Auc_5"]),
612
+ "Auc_10": float(d["Auc_10"]),
613
+ "Auc_20": float(d["Auc_20"]),
614
+ "Auc_30": float(d["Auc_30"]),
615
+ }
616
+
617
+ payload = {
618
+ "benchmark": BENCHMARK_NAME,
619
+ "version": BENCHMARK_VERSION,
620
+ "args": vars(args),
621
+ "per_category_auc": serializable,
622
+ "mean_auc": {k: v for k, v in all_means.items()},
623
+ }
624
+ with open(out_root / "co3d_pose_metrics.json", "w") as f:
625
+ json.dump(payload, f, indent=2)
626
+
627
+ lines = [
628
+ f"CO3D pose evaluation — {BENCHMARK_NAME} v{BENCHMARK_VERSION} (AnySplat / VGGT / finetune)",
629
+ "=" * 60,
630
+ json.dumps(vars(args), indent=2),
631
+ "",
632
+ ]
633
+ for bname in sorted(all_backends.keys()):
634
+ lines.append(f"### {bname}")
635
+ lines.append("-" * 40)
636
+ pc = all_backends[bname]
637
+ for cat in sorted(pc.keys()):
638
+ lines.append(
639
+ f"{cat:<15} AUC_5/10/20/30: {pc[cat]['Auc_5']:.4f} / {pc[cat]['Auc_10']:.4f} / "
640
+ f"{pc[cat]['Auc_20']:.4f} / {pc[cat]['Auc_30']:.4f}"
641
+ )
642
+ if bname in all_means and all_means[bname]:
643
+ m = all_means[bname]
644
+ lines.append(
645
+ f"MEAN AUC_5/10/20/30: {m['Auc_5']:.4f} / {m['Auc_10']:.4f} / "
646
+ f"{m['Auc_20']:.4f} / {m['Auc_30']:.4f}"
647
+ )
648
+ lines.append("")
649
+
650
+ with open(out_root / "co3d_pose_summary.txt", "w") as f:
651
+ f.write("\n".join(lines))
652
+
653
+ print(f"Wrote {out_root / 'co3d_pose_metrics.json'} and {out_root / 'co3d_pose_summary.txt'}")
654
+
655
+
656
+ def run_feed_forward_co3d_pose_benchmark(args: argparse.Namespace) -> None:
657
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
658
+ dtype = torch.bfloat16
659
+
660
+ if args.categories.strip().lower() == "auto":
661
+ anno_dir = Path(args.co3d_anno_dir)
662
+ categories = sorted(p.name[:-9] for p in anno_dir.glob("*_test.jgz") if p.name.endswith("_test.jgz"))
663
+ else:
664
+ categories = [c.strip() for c in args.categories.split(",") if c.strip()]
665
+
666
+ if not categories:
667
+ raise RuntimeError(f"No categories found to evaluate in {args.co3d_anno_dir}")
668
+
669
+ if args.debug:
670
+ categories = categories[:1]
671
+ print(f"Debug mode on, only evaluating category: {categories[0]}")
672
+
673
+ tag = args.run_tag or datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
674
+ out_root = Path(args.output_dir).expanduser().resolve() / tag
675
+ out_root.mkdir(parents=True, exist_ok=True)
676
+ print(f"Results directory: {out_root}")
677
+
678
+ pose_align_anysplat = _anysplat_pose_align_flag(args.pose_postprocess)
679
+ vggt_align = _vggt_align_mode(args.pose_postprocess)
680
+
681
+ if args.sampling_plan_path:
682
+ plan_path = Path(args.sampling_plan_path).expanduser().resolve()
683
+ hydrated_full = load_sampling_plan(plan_path, args.co3d_dir)
684
+ hydrated = {c: hydrated_full.get(c, []) for c in categories}
685
+ unknown = [c for c in categories if c not in hydrated_full]
686
+ if unknown:
687
+ print(f"[warn] No entries in loaded plan for categories (empty lists): {unknown}")
688
+ else:
689
+ raw_plan = build_sampling_plan(args, categories)
690
+ plan_serializable = {cat: list(raw_plan.get(cat, [])) for cat in categories}
691
+ meta = {
692
+ "benchmark": BENCHMARK_NAME,
693
+ "version": BENCHMARK_VERSION,
694
+ "seed": args.seed,
695
+ "co3d_dir": os.path.abspath(args.co3d_dir),
696
+ "co3d_anno_dir": os.path.abspath(args.co3d_anno_dir),
697
+ "num_frames": args.num_frames,
698
+ "min_num_images": args.min_num_images,
699
+ "fast_eval": args.fast_eval,
700
+ "categories": categories,
701
+ }
702
+ save_sampling_plan(out_root / "co3d_sampling_plan.json", plan_serializable, meta)
703
+ hydrated = {cat: [plan_entry_from_json(e, args.co3d_dir) for e in plan_serializable[cat]] for cat in categories}
704
+
705
+ total_entries = sum(len(hydrated.get(c, [])) for c in categories)
706
+ if total_entries == 0:
707
+ raise RuntimeError("Sampling plan is empty — no valid sequences. Check CO3D paths and filters.")
708
+
709
+ selected = parse_backends_selection(args.backends, args.finetune_ckpt)
710
+ print(f"Backends to evaluate (in order): {selected}")
711
+ backends = build_backends_for_eval(selected, args, device)
712
+
713
+ all_backends: Dict[str, Dict[str, Any]] = {}
714
+ all_means: Dict[str, Dict[str, float]] = {}
715
+
716
+ for backend_name, loader, kind in backends:
717
+ print("\n" + "#" * 80)
718
+ print(f"Loading backend: {backend_name}")
719
+ print("#" * 80)
720
+ model = loader()
721
+ model.to(device)
722
+ model.eval()
723
+ for p in model.parameters():
724
+ p.requires_grad = False
725
+
726
+ per_cat = _run_one_backend_on_plan(
727
+ backend_name,
728
+ model,
729
+ kind,
730
+ hydrated,
731
+ args,
732
+ categories,
733
+ device,
734
+ dtype,
735
+ pose_align_anysplat,
736
+ vggt_align,
737
+ )
738
+ all_backends[backend_name] = per_cat
739
+ all_means[backend_name] = _print_and_collect_means(per_cat)
740
+
741
+ del model
742
+ gc.collect()
743
+ if torch.cuda.is_available():
744
+ torch.cuda.empty_cache()
745
+
746
+ _save_results(out_root, args, all_backends, all_means)
747
+
748
+
749
+ def main() -> None:
750
+ args = setup_args()
751
+ run_feed_forward_co3d_pose_benchmark(args)
752
+
753
+
754
+ # Backward-compatible name for callers that imported ``evaluate`` from ``eval_pose_vggt``.
755
+ evaluate = run_feed_forward_co3d_pose_benchmark
756
+
757
+
758
+ if __name__ == "__main__":
759
+ main()