File size: 3,929 Bytes
4ec41f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Compare explicit StatePlay state traces with the selected dataset states."""
from __future__ import annotations

import argparse
import json
import sys
from collections import defaultdict
from pathlib import Path

import numpy as np
import pandas as pd
import torch


ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from stateplay.utils.state import (  # noqa: E402
    STATE_COLUMNS,
    STATE_NORM_MAX,
    denormalize_state,
    load_true_state,
)


def summarize(distances: np.ndarray) -> dict[str, object]:
    per_state = distances.mean(axis=(0, 1))
    distance = float(per_state.mean())
    return {
        "samples": int(distances.shape[0]),
        "latent_frames_per_sample": int(distances.shape[1]),
        "distance": distance,
        "score": 1.0 - distance,
        "per_state_distance": dict(zip(STATE_COLUMNS, map(float, per_state))),
        "per_state_score": dict(zip(STATE_COLUMNS, map(lambda x: 1.0 - float(x), per_state))),
    }


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--selection", type=Path, required=True)
    parser.add_argument("--predictions", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    samples = json.loads(args.selection.read_text(encoding="utf-8"))["samples"]
    norm_max = STATE_NORM_MAX.numpy()
    all_distances = []
    by_label = defaultdict(list)
    max_true_disagreement = 0.0

    for sample in samples:
        video_name = Path(sample["output_name"])
        state_path = args.predictions / f"{video_name.stem}_state.txt"
        trace = pd.read_csv(state_path, sep=r"\s+")
        frames = len(trace)
        if frames != 26 or not np.array_equal(trace["frame"].to_numpy(), np.arange(frames)):
            raise ValueError(f"Unexpected latent-frame trace in {state_path}: {frames} rows")
        predicted = trace[[f"{name}_pred" for name in STATE_COLUMNS]].to_numpy(dtype=np.float64)
        recorded_true = trace[[f"{name}_true" for name in STATE_COLUMNS]].to_numpy(dtype=np.float64)
        normalized_true = load_true_state(
            sample["actions"], num_frames=101, latent_frames=frames,
            sampling="end", device="cpu", dtype=torch.bfloat16,
        )
        target = denormalize_state(normalized_true.float()).squeeze(0).numpy()
        disagreement = float(np.max(np.abs(recorded_true - target)))
        max_true_disagreement = max(max_true_disagreement, disagreement)
        if disagreement > 0.002:
            raise ValueError(f"Saved true trace differs from source parquet: {state_path} ({disagreement})")
        if not np.isfinite(predicted).all() or not np.isfinite(target).all():
            raise ValueError(f"Non-finite state value in {state_path}")
        distance = np.abs(predicted - target) / norm_max
        all_distances.append(distance)
        by_label[sample["label"]].append(distance)

    distances = np.stack(all_distances)
    report = {
        "selection": str(args.selection.resolve()),
        "predictions": str(args.predictions.resolve()),
        "normalization_max": dict(zip(STATE_COLUMNS, map(float, norm_max))),
        "definition": "1 - mean(abs(predicted_raw - target_raw) / state_max) over samples, latent frames, and five variables",
        "state_sampling": "end",
        "max_saved_true_vs_parquet_difference": max_true_disagreement,
        "all_frames": summarize(distances),
        "excluding_pinned_initial_frame": summarize(distances[:, 1:]),
        "by_label": {label: summarize(np.stack(values)) for label, values in sorted(by_label.items())},
    }
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
    print(json.dumps(report, indent=2))


if __name__ == "__main__":
    main()