VideoWorldmodel commited on
Commit
6f9d7c9
·
verified ·
1 Parent(s): 72cb63f

Upload evaluate_matrix_game_sc.py

Browse files
Files changed (1) hide show
  1. evaluate_matrix_game_sc.py +360 -0
evaluate_matrix_game_sc.py ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Reproduce Matrix-Game 2.0 self-consistency metrics from released videos."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import csv
8
+ import json
9
+ import math
10
+ import re
11
+ import sys
12
+ from collections import defaultdict
13
+ from dataclasses import asdict, dataclass
14
+ from pathlib import Path
15
+ from typing import Sequence
16
+
17
+ import cv2
18
+ import numpy as np
19
+
20
+
21
+ EXPECTED_COUNTS = {"inverse": 448, "loop": 445, "equivalence": 239}
22
+ PAPER_RESULTS = {
23
+ "inverse": {"lpips": 0.71, "psnr": 10.45},
24
+ "loop": {"lpips": 0.72, "psnr": 10.62},
25
+ "equivalence": {"lpips": 0.59, "psnr": 12.57},
26
+ }
27
+ EQUIVALENCE_RE = re.compile(
28
+ r"(?P<run>run_\d+_\d+)__pair_(?P<pair>\d+)_(?P<branch>[AB])_traj_\d+\.mp4$",
29
+ re.IGNORECASE,
30
+ )
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class EvaluationUnit:
35
+ relation: str
36
+ unit: str
37
+ video_a: Path
38
+ video_b: Path | None = None
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class MetricRow:
43
+ relation: str
44
+ unit: str
45
+ video_a: str
46
+ video_b: str
47
+ frame_a: int
48
+ frame_b: int
49
+ width: int
50
+ height: int
51
+ psnr: float
52
+ lpips: float | None
53
+ psnr_exact_match: bool
54
+
55
+
56
+ def is_downloaded_video(path: Path) -> bool:
57
+ if not path.is_file() or path.stat().st_size <= 200:
58
+ return False
59
+ with path.open("rb") as handle:
60
+ return not handle.read(64).startswith(b"version https://git-lfs.github.com/spec/v1")
61
+
62
+
63
+ def discover_units(root: Path, strict_counts: bool = True) -> list[EvaluationUnit]:
64
+ units: list[EvaluationUnit] = []
65
+ for relation in ("inverse", "loop"):
66
+ for difficulty in ("easy", "hard"):
67
+ folder = root / f"{relation}_{difficulty}"
68
+ if not folder.is_dir():
69
+ raise FileNotFoundError(f"missing dataset folder: {folder}")
70
+ for path in sorted(folder.glob("*.mp4")):
71
+ if not is_downloaded_video(path):
72
+ raise RuntimeError(f"missing Git LFS video object: {path}")
73
+ units.append(EvaluationUnit(relation, path.stem, path))
74
+
75
+ equivalence_folder = root / "equivalence"
76
+ if not equivalence_folder.is_dir():
77
+ raise FileNotFoundError(f"missing dataset folder: {equivalence_folder}")
78
+ pairs: dict[str, dict[str, Path]] = defaultdict(dict)
79
+ for path in sorted(equivalence_folder.glob("*.mp4")):
80
+ if not is_downloaded_video(path):
81
+ raise RuntimeError(f"missing Git LFS video object: {path}")
82
+ match = EQUIVALENCE_RE.fullmatch(path.name)
83
+ if not match:
84
+ raise ValueError(f"unrecognized Equivalence filename: {path.name}")
85
+ unit = f"{match.group('run')}__pair_{match.group('pair')}"
86
+ branch = match.group("branch").upper()
87
+ if branch in pairs[unit]:
88
+ raise ValueError(f"duplicate Equivalence branch {branch}: {unit}")
89
+ pairs[unit][branch] = path
90
+ for unit, branches in sorted(pairs.items()):
91
+ if set(branches) != {"A", "B"}:
92
+ raise ValueError(f"incomplete Equivalence pair {unit}: {sorted(branches)}")
93
+ units.append(EvaluationUnit("equivalence", unit, branches["A"], branches["B"]))
94
+
95
+ counts = {relation: sum(unit.relation == relation for unit in units) for relation in EXPECTED_COUNTS}
96
+ if strict_counts and counts != EXPECTED_COUNTS:
97
+ raise RuntimeError(f"unexpected graph counts: found {counts}, expected {EXPECTED_COUNTS}")
98
+ return units
99
+
100
+
101
+ def read_endpoint(path: Path, endpoint: str) -> tuple[np.ndarray, int]:
102
+ capture = cv2.VideoCapture(str(path))
103
+ if not capture.isOpened():
104
+ raise RuntimeError(f"failed to open video: {path}")
105
+ frame_count = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
106
+ if frame_count < 2:
107
+ capture.release()
108
+ raise RuntimeError(f"video has fewer than two frames: {path}")
109
+ frame_index = 0 if endpoint == "first" else frame_count - 1
110
+ capture.set(cv2.CAP_PROP_POS_FRAMES, frame_index)
111
+ ok, frame = capture.read()
112
+ capture.release()
113
+ if not ok:
114
+ raise RuntimeError(f"failed to decode {endpoint} frame: {path}")
115
+ return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB), frame_index
116
+
117
+
118
+ def psnr(reference: np.ndarray, prediction: np.ndarray) -> float:
119
+ if reference.shape != prediction.shape:
120
+ raise ValueError(f"frame shape mismatch: {reference.shape} versus {prediction.shape}")
121
+ mse = np.mean((reference.astype(np.float64) - prediction.astype(np.float64)) ** 2)
122
+ if mse == 0:
123
+ return float("inf")
124
+ return 10.0 * math.log10((255.0**2) / mse)
125
+
126
+
127
+ class LPIPSMetric:
128
+ def __init__(self, device: str) -> None:
129
+ try:
130
+ import lpips
131
+ import torch
132
+ except ImportError as exc:
133
+ raise RuntimeError("install the Python dependencies listed in README.md before using --lpips") from exc
134
+ if device == "auto":
135
+ device = "cuda" if torch.cuda.is_available() else "cpu"
136
+ self.torch = torch
137
+ self.device = torch.device(device)
138
+ self.model = lpips.LPIPS(net="alex").to(self.device).eval()
139
+
140
+ def __call__(self, reference: np.ndarray, prediction: np.ndarray) -> float:
141
+ if reference.shape != prediction.shape:
142
+ raise ValueError(f"frame shape mismatch: {reference.shape} versus {prediction.shape}")
143
+ tensors = []
144
+ for image in (reference, prediction):
145
+ tensor = self.torch.from_numpy(np.ascontiguousarray(image)).permute(2, 0, 1).float()
146
+ tensors.append(tensor.div(127.5).sub(1.0).unsqueeze(0).to(self.device))
147
+ with self.torch.inference_mode():
148
+ value = self.model(tensors[0], tensors[1], normalize=False)
149
+ return float(value.item())
150
+
151
+
152
+ def evaluate(units: Sequence[EvaluationUnit], lpips_metric: LPIPSMetric | None) -> list[MetricRow]:
153
+ rows: list[MetricRow] = []
154
+ for index, unit in enumerate(units, start=1):
155
+ if unit.relation in {"inverse", "loop"}:
156
+ frame_a, index_a = read_endpoint(unit.video_a, "first")
157
+ frame_b, index_b = read_endpoint(unit.video_a, "last")
158
+ video_b = unit.video_a
159
+ else:
160
+ if unit.video_b is None:
161
+ raise AssertionError("Equivalence unit is missing branch B")
162
+ frame_a, index_a = read_endpoint(unit.video_a, "last")
163
+ frame_b, index_b = read_endpoint(unit.video_b, "last")
164
+ video_b = unit.video_b
165
+ value_psnr = psnr(frame_a, frame_b)
166
+ value_lpips = lpips_metric(frame_a, frame_b) if lpips_metric else None
167
+ rows.append(
168
+ MetricRow(
169
+ relation=unit.relation,
170
+ unit=unit.unit,
171
+ video_a=str(unit.video_a),
172
+ video_b=str(video_b),
173
+ frame_a=index_a,
174
+ frame_b=index_b,
175
+ width=int(frame_a.shape[1]),
176
+ height=int(frame_a.shape[0]),
177
+ psnr=value_psnr,
178
+ lpips=value_lpips,
179
+ psnr_exact_match=math.isinf(value_psnr),
180
+ )
181
+ )
182
+ if index % 100 == 0 or index == len(units):
183
+ print(f"evaluated {index}/{len(units)} graph units", flush=True)
184
+ return rows
185
+
186
+
187
+ def bootstrap_ci(values: Sequence[float], seed: int, repetitions: int) -> tuple[float, float]:
188
+ array = np.asarray(values, dtype=np.float64)
189
+ if len(array) < 2:
190
+ return float("nan"), float("nan")
191
+ rng = np.random.default_rng(seed)
192
+ means = np.empty(repetitions, dtype=np.float64)
193
+ for start in range(0, repetitions, 500):
194
+ count = min(500, repetitions - start)
195
+ indices = rng.integers(0, len(array), size=(count, len(array)))
196
+ means[start : start + count] = array[indices].mean(axis=1)
197
+ low, high = np.quantile(means, [0.025, 0.975])
198
+ return float(low), float(high)
199
+
200
+
201
+ def summarize(rows: Sequence[MetricRow], seed: int, repetitions: int) -> list[dict[str, object]]:
202
+ output: list[dict[str, object]] = []
203
+ for relation in ("inverse", "loop", "equivalence"):
204
+ group = [row for row in rows if row.relation == relation]
205
+ summary: dict[str, object] = {
206
+ "relation": relation,
207
+ "n_graphs": len(group),
208
+ "psnr_finite_n": sum(math.isfinite(row.psnr) for row in group),
209
+ "psnr_exact_match_n": sum(row.psnr_exact_match for row in group),
210
+ }
211
+ for metric in ("psnr", "lpips"):
212
+ values = [
213
+ float(value)
214
+ for row in group
215
+ if (value := getattr(row, metric)) is not None and math.isfinite(float(value))
216
+ ]
217
+ if not values:
218
+ continue
219
+ low, high = bootstrap_ci(values, seed, repetitions)
220
+ summary.update(
221
+ {
222
+ metric: float(np.mean(values)),
223
+ f"{metric}_std": float(np.std(values, ddof=1)) if len(values) > 1 else 0.0,
224
+ f"{metric}_ci95_low": low,
225
+ f"{metric}_ci95_high": high,
226
+ }
227
+ )
228
+ output.append(summary)
229
+ return output
230
+
231
+
232
+ def write_csv(path: Path, rows: Sequence[dict[str, object]]) -> None:
233
+ if not rows:
234
+ return
235
+ columns: list[str] = []
236
+ for row in rows:
237
+ for key in row:
238
+ if key not in columns:
239
+ columns.append(key)
240
+ with path.open("w", newline="", encoding="utf-8") as handle:
241
+ writer = csv.DictWriter(handle, fieldnames=columns)
242
+ writer.writeheader()
243
+ writer.writerows(rows)
244
+
245
+
246
+ def paper_check(summaries: Sequence[dict[str, object]]) -> tuple[bool, list[dict[str, object]]]:
247
+ checks: list[dict[str, object]] = []
248
+ passed = True
249
+ for summary in summaries:
250
+ relation = str(summary["relation"])
251
+ for metric in ("lpips", "psnr"):
252
+ value = summary.get(metric)
253
+ expected = PAPER_RESULTS[relation][metric]
254
+ metric_passed = value is not None and round(float(value), 2) == expected
255
+ checks.append(
256
+ {
257
+ "relation": relation,
258
+ "metric": metric,
259
+ "computed": value,
260
+ "paper_rounded": expected,
261
+ "pass_at_2_decimals": metric_passed,
262
+ }
263
+ )
264
+ passed = passed and metric_passed
265
+ return passed, checks
266
+
267
+
268
+ def report(summaries: Sequence[dict[str, object]], check_passed: bool | None) -> str:
269
+ lines = [
270
+ "# Matrix-Game 2.0 SC Reproduction",
271
+ "",
272
+ "| Relation | Graph N | LPIPS (95% CI) | PSNR dB (95% CI) | Exact PSNR pairs |",
273
+ "| --- | ---: | ---: | ---: | ---: |",
274
+ ]
275
+ for row in summaries:
276
+ lpips_text = "not computed"
277
+ if "lpips" in row:
278
+ lpips_text = (
279
+ f"{row['lpips']:.4f} [{row['lpips_ci95_low']:.4f}, "
280
+ f"{row['lpips_ci95_high']:.4f}]"
281
+ )
282
+ psnr_text = f"{row['psnr']:.4f} [{row['psnr_ci95_low']:.4f}, {row['psnr_ci95_high']:.4f}]"
283
+ lines.append(
284
+ f"| {str(row['relation']).title()} | {row['n_graphs']} | {lpips_text} | "
285
+ f"{psnr_text} | {row['psnr_exact_match_n']} |"
286
+ )
287
+ if check_passed is not None:
288
+ lines.extend(["", f"Paper rounded-value check: **{'PASS' if check_passed else 'FAIL'}**."])
289
+ lines.extend(
290
+ [
291
+ "",
292
+ "Inverse/Loop compare the generated first and final frames. Equivalence compares",
293
+ "the generated final frames of paired A/B rollouts. Confidence intervals use",
294
+ "10,000 graph-level bootstrap resamples by default.",
295
+ "",
296
+ ]
297
+ )
298
+ return "\n".join(lines)
299
+
300
+
301
+ def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
302
+ parser = argparse.ArgumentParser(description=__doc__)
303
+ parser.add_argument("--data", type=Path, default=Path("data/Nips_WM_Eval_qzf"))
304
+ parser.add_argument("--output", type=Path, default=Path("results/matrix_game_sc"))
305
+ parser.add_argument("--lpips", action="store_true", help="compute LPIPS 0.1.4 with AlexNet")
306
+ parser.add_argument("--device", default="auto", help="auto, cpu, cuda, or cuda:<index>")
307
+ parser.add_argument("--seed", type=int, default=2026)
308
+ parser.add_argument("--bootstrap-repetitions", type=int, default=10_000)
309
+ parser.add_argument("--allow-partial", action="store_true", help="disable published-count checks")
310
+ parser.add_argument("--check-paper", action="store_true", help="check values at paper precision")
311
+ return parser.parse_args(argv)
312
+
313
+
314
+ def main(argv: Sequence[str] | None = None) -> int:
315
+ args = parse_args(argv)
316
+ if not args.data.is_dir():
317
+ raise SystemExit(f"dataset directory does not exist: {args.data}")
318
+ if args.check_paper and not args.lpips:
319
+ raise SystemExit("--check-paper requires --lpips")
320
+ args.output.mkdir(parents=True, exist_ok=True)
321
+
322
+ units = discover_units(args.data, strict_counts=not args.allow_partial)
323
+ metric = LPIPSMetric(args.device) if args.lpips else None
324
+ rows = evaluate(units, metric)
325
+ summaries = summarize(rows, args.seed, args.bootstrap_repetitions)
326
+ check_passed: bool | None = None
327
+ checks: list[dict[str, object]] = []
328
+ if args.check_paper:
329
+ check_passed, checks = paper_check(summaries)
330
+
331
+ write_csv(args.output / "per_graph.csv", [asdict(row) for row in rows])
332
+ write_csv(args.output / "summary.csv", summaries)
333
+ if checks:
334
+ write_csv(args.output / "paper_check.csv", checks)
335
+ audit = {
336
+ "data": str(args.data.resolve()),
337
+ "definitions": {
338
+ "inverse": "generated first frame versus generated final frame",
339
+ "loop": "generated first frame versus generated final frame",
340
+ "equivalence": "generated branch-A final frame versus generated branch-B final frame",
341
+ },
342
+ "expected_counts": EXPECTED_COUNTS,
343
+ "observed_counts": {row["relation"]: row["n_graphs"] for row in summaries},
344
+ "lpips": "lpips==0.1.4, AlexNet, RGB in [-1,1]" if args.lpips else "not computed",
345
+ "psnr": "RGB uint8, MAX=255; exact matches excluded from finite PSNR mean and counted separately",
346
+ "bootstrap_seed": args.seed,
347
+ "bootstrap_repetitions": args.bootstrap_repetitions,
348
+ "paper_check_passed": check_passed,
349
+ }
350
+ (args.output / "audit.json").write_text(
351
+ json.dumps(audit, indent=2, ensure_ascii=True) + "\n", encoding="utf-8"
352
+ )
353
+ (args.output / "report.md").write_text(report(summaries, check_passed), encoding="utf-8")
354
+ print(report(summaries, check_passed))
355
+ print(f"Outputs: {args.output.resolve()}")
356
+ return 0 if check_passed is not False else 1
357
+
358
+
359
+ if __name__ == "__main__":
360
+ raise SystemExit(main())