File size: 14,557 Bytes
6f9d7c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Reproduce Matrix-Game 2.0 self-consistency metrics from released videos."""

from __future__ import annotations

import argparse
import csv
import json
import math
import re
import sys
from collections import defaultdict
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Sequence

import cv2
import numpy as np


EXPECTED_COUNTS = {"inverse": 448, "loop": 445, "equivalence": 239}
PAPER_RESULTS = {
    "inverse": {"lpips": 0.71, "psnr": 10.45},
    "loop": {"lpips": 0.72, "psnr": 10.62},
    "equivalence": {"lpips": 0.59, "psnr": 12.57},
}
EQUIVALENCE_RE = re.compile(
    r"(?P<run>run_\d+_\d+)__pair_(?P<pair>\d+)_(?P<branch>[AB])_traj_\d+\.mp4$",
    re.IGNORECASE,
)


@dataclass(frozen=True)
class EvaluationUnit:
    relation: str
    unit: str
    video_a: Path
    video_b: Path | None = None


@dataclass(frozen=True)
class MetricRow:
    relation: str
    unit: str
    video_a: str
    video_b: str
    frame_a: int
    frame_b: int
    width: int
    height: int
    psnr: float
    lpips: float | None
    psnr_exact_match: bool


def is_downloaded_video(path: Path) -> bool:
    if not path.is_file() or path.stat().st_size <= 200:
        return False
    with path.open("rb") as handle:
        return not handle.read(64).startswith(b"version https://git-lfs.github.com/spec/v1")


def discover_units(root: Path, strict_counts: bool = True) -> list[EvaluationUnit]:
    units: list[EvaluationUnit] = []
    for relation in ("inverse", "loop"):
        for difficulty in ("easy", "hard"):
            folder = root / f"{relation}_{difficulty}"
            if not folder.is_dir():
                raise FileNotFoundError(f"missing dataset folder: {folder}")
            for path in sorted(folder.glob("*.mp4")):
                if not is_downloaded_video(path):
                    raise RuntimeError(f"missing Git LFS video object: {path}")
                units.append(EvaluationUnit(relation, path.stem, path))

    equivalence_folder = root / "equivalence"
    if not equivalence_folder.is_dir():
        raise FileNotFoundError(f"missing dataset folder: {equivalence_folder}")
    pairs: dict[str, dict[str, Path]] = defaultdict(dict)
    for path in sorted(equivalence_folder.glob("*.mp4")):
        if not is_downloaded_video(path):
            raise RuntimeError(f"missing Git LFS video object: {path}")
        match = EQUIVALENCE_RE.fullmatch(path.name)
        if not match:
            raise ValueError(f"unrecognized Equivalence filename: {path.name}")
        unit = f"{match.group('run')}__pair_{match.group('pair')}"
        branch = match.group("branch").upper()
        if branch in pairs[unit]:
            raise ValueError(f"duplicate Equivalence branch {branch}: {unit}")
        pairs[unit][branch] = path
    for unit, branches in sorted(pairs.items()):
        if set(branches) != {"A", "B"}:
            raise ValueError(f"incomplete Equivalence pair {unit}: {sorted(branches)}")
        units.append(EvaluationUnit("equivalence", unit, branches["A"], branches["B"]))

    counts = {relation: sum(unit.relation == relation for unit in units) for relation in EXPECTED_COUNTS}
    if strict_counts and counts != EXPECTED_COUNTS:
        raise RuntimeError(f"unexpected graph counts: found {counts}, expected {EXPECTED_COUNTS}")
    return units


def read_endpoint(path: Path, endpoint: str) -> tuple[np.ndarray, int]:
    capture = cv2.VideoCapture(str(path))
    if not capture.isOpened():
        raise RuntimeError(f"failed to open video: {path}")
    frame_count = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
    if frame_count < 2:
        capture.release()
        raise RuntimeError(f"video has fewer than two frames: {path}")
    frame_index = 0 if endpoint == "first" else frame_count - 1
    capture.set(cv2.CAP_PROP_POS_FRAMES, frame_index)
    ok, frame = capture.read()
    capture.release()
    if not ok:
        raise RuntimeError(f"failed to decode {endpoint} frame: {path}")
    return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB), frame_index


def psnr(reference: np.ndarray, prediction: np.ndarray) -> float:
    if reference.shape != prediction.shape:
        raise ValueError(f"frame shape mismatch: {reference.shape} versus {prediction.shape}")
    mse = np.mean((reference.astype(np.float64) - prediction.astype(np.float64)) ** 2)
    if mse == 0:
        return float("inf")
    return 10.0 * math.log10((255.0**2) / mse)


class LPIPSMetric:
    def __init__(self, device: str) -> None:
        try:
            import lpips
            import torch
        except ImportError as exc:
            raise RuntimeError("install the Python dependencies listed in README.md before using --lpips") from exc
        if device == "auto":
            device = "cuda" if torch.cuda.is_available() else "cpu"
        self.torch = torch
        self.device = torch.device(device)
        self.model = lpips.LPIPS(net="alex").to(self.device).eval()

    def __call__(self, reference: np.ndarray, prediction: np.ndarray) -> float:
        if reference.shape != prediction.shape:
            raise ValueError(f"frame shape mismatch: {reference.shape} versus {prediction.shape}")
        tensors = []
        for image in (reference, prediction):
            tensor = self.torch.from_numpy(np.ascontiguousarray(image)).permute(2, 0, 1).float()
            tensors.append(tensor.div(127.5).sub(1.0).unsqueeze(0).to(self.device))
        with self.torch.inference_mode():
            value = self.model(tensors[0], tensors[1], normalize=False)
        return float(value.item())


def evaluate(units: Sequence[EvaluationUnit], lpips_metric: LPIPSMetric | None) -> list[MetricRow]:
    rows: list[MetricRow] = []
    for index, unit in enumerate(units, start=1):
        if unit.relation in {"inverse", "loop"}:
            frame_a, index_a = read_endpoint(unit.video_a, "first")
            frame_b, index_b = read_endpoint(unit.video_a, "last")
            video_b = unit.video_a
        else:
            if unit.video_b is None:
                raise AssertionError("Equivalence unit is missing branch B")
            frame_a, index_a = read_endpoint(unit.video_a, "last")
            frame_b, index_b = read_endpoint(unit.video_b, "last")
            video_b = unit.video_b
        value_psnr = psnr(frame_a, frame_b)
        value_lpips = lpips_metric(frame_a, frame_b) if lpips_metric else None
        rows.append(
            MetricRow(
                relation=unit.relation,
                unit=unit.unit,
                video_a=str(unit.video_a),
                video_b=str(video_b),
                frame_a=index_a,
                frame_b=index_b,
                width=int(frame_a.shape[1]),
                height=int(frame_a.shape[0]),
                psnr=value_psnr,
                lpips=value_lpips,
                psnr_exact_match=math.isinf(value_psnr),
            )
        )
        if index % 100 == 0 or index == len(units):
            print(f"evaluated {index}/{len(units)} graph units", flush=True)
    return rows


def bootstrap_ci(values: Sequence[float], seed: int, repetitions: int) -> tuple[float, float]:
    array = np.asarray(values, dtype=np.float64)
    if len(array) < 2:
        return float("nan"), float("nan")
    rng = np.random.default_rng(seed)
    means = np.empty(repetitions, dtype=np.float64)
    for start in range(0, repetitions, 500):
        count = min(500, repetitions - start)
        indices = rng.integers(0, len(array), size=(count, len(array)))
        means[start : start + count] = array[indices].mean(axis=1)
    low, high = np.quantile(means, [0.025, 0.975])
    return float(low), float(high)


def summarize(rows: Sequence[MetricRow], seed: int, repetitions: int) -> list[dict[str, object]]:
    output: list[dict[str, object]] = []
    for relation in ("inverse", "loop", "equivalence"):
        group = [row for row in rows if row.relation == relation]
        summary: dict[str, object] = {
            "relation": relation,
            "n_graphs": len(group),
            "psnr_finite_n": sum(math.isfinite(row.psnr) for row in group),
            "psnr_exact_match_n": sum(row.psnr_exact_match for row in group),
        }
        for metric in ("psnr", "lpips"):
            values = [
                float(value)
                for row in group
                if (value := getattr(row, metric)) is not None and math.isfinite(float(value))
            ]
            if not values:
                continue
            low, high = bootstrap_ci(values, seed, repetitions)
            summary.update(
                {
                    metric: float(np.mean(values)),
                    f"{metric}_std": float(np.std(values, ddof=1)) if len(values) > 1 else 0.0,
                    f"{metric}_ci95_low": low,
                    f"{metric}_ci95_high": high,
                }
            )
        output.append(summary)
    return output


def write_csv(path: Path, rows: Sequence[dict[str, object]]) -> None:
    if not rows:
        return
    columns: list[str] = []
    for row in rows:
        for key in row:
            if key not in columns:
                columns.append(key)
    with path.open("w", newline="", encoding="utf-8") as handle:
        writer = csv.DictWriter(handle, fieldnames=columns)
        writer.writeheader()
        writer.writerows(rows)


def paper_check(summaries: Sequence[dict[str, object]]) -> tuple[bool, list[dict[str, object]]]:
    checks: list[dict[str, object]] = []
    passed = True
    for summary in summaries:
        relation = str(summary["relation"])
        for metric in ("lpips", "psnr"):
            value = summary.get(metric)
            expected = PAPER_RESULTS[relation][metric]
            metric_passed = value is not None and round(float(value), 2) == expected
            checks.append(
                {
                    "relation": relation,
                    "metric": metric,
                    "computed": value,
                    "paper_rounded": expected,
                    "pass_at_2_decimals": metric_passed,
                }
            )
            passed = passed and metric_passed
    return passed, checks


def report(summaries: Sequence[dict[str, object]], check_passed: bool | None) -> str:
    lines = [
        "# Matrix-Game 2.0 SC Reproduction",
        "",
        "| Relation | Graph N | LPIPS (95% CI) | PSNR dB (95% CI) | Exact PSNR pairs |",
        "| --- | ---: | ---: | ---: | ---: |",
    ]
    for row in summaries:
        lpips_text = "not computed"
        if "lpips" in row:
            lpips_text = (
                f"{row['lpips']:.4f} [{row['lpips_ci95_low']:.4f}, "
                f"{row['lpips_ci95_high']:.4f}]"
            )
        psnr_text = f"{row['psnr']:.4f} [{row['psnr_ci95_low']:.4f}, {row['psnr_ci95_high']:.4f}]"
        lines.append(
            f"| {str(row['relation']).title()} | {row['n_graphs']} | {lpips_text} | "
            f"{psnr_text} | {row['psnr_exact_match_n']} |"
        )
    if check_passed is not None:
        lines.extend(["", f"Paper rounded-value check: **{'PASS' if check_passed else 'FAIL'}**."])
    lines.extend(
        [
            "",
            "Inverse/Loop compare the generated first and final frames. Equivalence compares",
            "the generated final frames of paired A/B rollouts. Confidence intervals use",
            "10,000 graph-level bootstrap resamples by default.",
            "",
        ]
    )
    return "\n".join(lines)


def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--data", type=Path, default=Path("data/Nips_WM_Eval_qzf"))
    parser.add_argument("--output", type=Path, default=Path("results/matrix_game_sc"))
    parser.add_argument("--lpips", action="store_true", help="compute LPIPS 0.1.4 with AlexNet")
    parser.add_argument("--device", default="auto", help="auto, cpu, cuda, or cuda:<index>")
    parser.add_argument("--seed", type=int, default=2026)
    parser.add_argument("--bootstrap-repetitions", type=int, default=10_000)
    parser.add_argument("--allow-partial", action="store_true", help="disable published-count checks")
    parser.add_argument("--check-paper", action="store_true", help="check values at paper precision")
    return parser.parse_args(argv)


def main(argv: Sequence[str] | None = None) -> int:
    args = parse_args(argv)
    if not args.data.is_dir():
        raise SystemExit(f"dataset directory does not exist: {args.data}")
    if args.check_paper and not args.lpips:
        raise SystemExit("--check-paper requires --lpips")
    args.output.mkdir(parents=True, exist_ok=True)

    units = discover_units(args.data, strict_counts=not args.allow_partial)
    metric = LPIPSMetric(args.device) if args.lpips else None
    rows = evaluate(units, metric)
    summaries = summarize(rows, args.seed, args.bootstrap_repetitions)
    check_passed: bool | None = None
    checks: list[dict[str, object]] = []
    if args.check_paper:
        check_passed, checks = paper_check(summaries)

    write_csv(args.output / "per_graph.csv", [asdict(row) for row in rows])
    write_csv(args.output / "summary.csv", summaries)
    if checks:
        write_csv(args.output / "paper_check.csv", checks)
    audit = {
        "data": str(args.data.resolve()),
        "definitions": {
            "inverse": "generated first frame versus generated final frame",
            "loop": "generated first frame versus generated final frame",
            "equivalence": "generated branch-A final frame versus generated branch-B final frame",
        },
        "expected_counts": EXPECTED_COUNTS,
        "observed_counts": {row["relation"]: row["n_graphs"] for row in summaries},
        "lpips": "lpips==0.1.4, AlexNet, RGB in [-1,1]" if args.lpips else "not computed",
        "psnr": "RGB uint8, MAX=255; exact matches excluded from finite PSNR mean and counted separately",
        "bootstrap_seed": args.seed,
        "bootstrap_repetitions": args.bootstrap_repetitions,
        "paper_check_passed": check_passed,
    }
    (args.output / "audit.json").write_text(
        json.dumps(audit, indent=2, ensure_ascii=True) + "\n", encoding="utf-8"
    )
    (args.output / "report.md").write_text(report(summaries, check_passed), encoding="utf-8")
    print(report(summaries, check_passed))
    print(f"Outputs: {args.output.resolve()}")
    return 0 if check_passed is not False else 1


if __name__ == "__main__":
    raise SystemExit(main())