File size: 7,050 Bytes
6f003f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""Validate the fixed-revision RECAP LIBERO-10 Task 0 local dataset.

The expected video counts come from the file manifest at the pinned revision,
not from the historical SFT ``info.json`` ``total_videos`` field.
"""

from __future__ import annotations

import argparse
import json
import math
import sys
from pathlib import Path
from typing import Any

import numpy as np
import pyarrow.parquet as pq

SCRIPT_DIR = Path(__file__).resolve().parent
PROJECT_ROOT = SCRIPT_DIR.parent
if str(SCRIPT_DIR) not in sys.path:
    sys.path.insert(0, str(SCRIPT_DIR))

from task0_baseline_common import require_project_path  # noqa: E402


REVISION = "75b382d2c066bcedd8b030285b45c856913f1497"
SPLITS: dict[str, dict[str, int]] = {
    "libero10_task0_sft": {"episodes": 30, "frames": 8005, "image": 30, "wrist_image": 30},
    "libero10_task0_train": {"episodes": 4096, "frames": 1561874, "image": 4096, "wrist_image": 4096},
    "libero10_task0_eval": {"episodes": 64, "frames": 25493, "image": 64, "wrist_image": 64},
}


def _check_video_files(split_path: Path, expected: dict[str, int]) -> dict[str, Any]:
    report: dict[str, Any] = {}
    for key in ("image", "wrist_image"):
        files = sorted((split_path / "videos").glob(f"**/{key}/episode_*.mp4"))
        names = {item.name for item in files}
        expected_names = {f"episode_{index:06d}.mp4" for index in range(expected["episodes"])}
        report[key] = {
            "count": len(files),
            "expected_count": expected[key],
            "missing_names": sorted(expected_names - names)[:20],
            "unexpected_names": sorted(names - expected_names)[:20],
            "bytes": sum(item.stat().st_size for item in files),
        }
    return report


def _check_sidecar(sidecar: Path, expected_rows: int) -> dict[str, Any]:
    table = pq.read_table(sidecar, columns=["episode_index", "frame_index", "return", "reward"])
    episode = table.column("episode_index").to_numpy()
    frame = table.column("frame_index").to_numpy()
    returns = table.column("return").to_numpy()
    rewards = table.column("reward").to_numpy()
    keys = np.stack([episode, frame], axis=1)
    return {
        "rows": table.num_rows,
        "expected_rows": expected_rows,
        "unique_keys": int(np.unique(keys, axis=0).shape[0]),
        "finite": bool(np.isfinite(returns).all() and np.isfinite(rewards).all()),
        "return_min": float(returns.min()) if len(returns) else math.nan,
        "return_max": float(returns.max()) if len(returns) else math.nan,
    }


def _decode_samples(split_path: Path, expected: dict[str, int]) -> list[str]:
    try:
        import av
    except Exception as exc:  # pragma: no cover - environment diagnostic
        return [f"PyAV import failed: {type(exc).__name__}: {exc}"]
    errors: list[str] = []
    sample_indices = sorted({0, expected["episodes"] // 2, expected["episodes"] - 1})
    for key in ("image", "wrist_image"):
        for index in sample_indices:
            chunk = index // 1000
            path = split_path / "videos" / f"chunk-{chunk:03d}" / key / f"episode_{index:06d}.mp4"
            if not path.is_file():
                errors.append(f"missing sample: {path}")
                continue
            try:
                with av.open(str(path)) as container:
                    frame = next(container.decode(video=0), None)
                    if frame is None:
                        errors.append(f"no decodable frame: {path}")
            except Exception as exc:
                errors.append(f"decode failed {path}: {type(exc).__name__}: {exc}")
    return errors


def validate(data_root: Path, *, returns_tag: str | None = None, decode_samples: bool = False) -> dict[str, Any]:
    report: dict[str, Any] = {"data_root": str(data_root), "revision": REVISION, "splits": {}, "errors": []}
    for split, expected in SPLITS.items():
        path = data_root / split
        split_report: dict[str, Any] = {"path": str(path), "expected": expected}
        info_path = path / "meta" / "info.json"
        if not info_path.is_file():
            report["errors"].append(f"missing {info_path}")
            continue
        info = json.loads(info_path.read_text(encoding="utf-8"))
        parquet_files = sorted((path / "data").rglob("*.parquet"))
        rows = sum(int(pq.ParquetFile(item).metadata.num_rows) for item in parquet_files)
        split_report.update(
            {
                "metadata_episodes": info.get("total_episodes"),
                "metadata_frames": info.get("total_frames"),
                "metadata_total_videos": info.get("total_videos"),
                "parquet_files": len(parquet_files),
                "expected_parquet_files": expected["episodes"],
                "parquet_rows": rows,
                "expected_rows": expected["frames"],
                "videos": _check_video_files(path, expected),
            }
        )
        if len(parquet_files) != expected["episodes"]:
            report["errors"].append(f"{split}: parquet file count mismatch")
        if rows != expected["frames"]:
            report["errors"].append(f"{split}: parquet row count mismatch")
        for key, video_report in split_report["videos"].items():
            if video_report["count"] != expected[key] or video_report["missing_names"] or video_report["unexpected_names"]:
                report["errors"].append(f"{split}: {key} video manifest mismatch")
        if decode_samples:
            split_report["decode_sample_errors"] = _decode_samples(path, expected)
            report["errors"].extend(f"{split}: {item}" for item in split_report["decode_sample_errors"])
        if returns_tag:
            sidecar = path / "meta" / f"returns_{returns_tag}.parquet"
            if not sidecar.is_file():
                report["errors"].append(f"{split}: missing {sidecar}")
            else:
                split_report["returns"] = _check_sidecar(sidecar, expected["frames"])
                if (
                    split_report["returns"]["rows"] != expected["frames"]
                    or split_report["returns"]["unique_keys"] != expected["frames"]
                    or not split_report["returns"]["finite"]
                ):
                    report["errors"].append(f"{split}: returns sidecar mismatch")
        report["splits"][split] = split_report
    report["ok"] = not report["errors"]
    return report


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--data-root", type=Path, default=Path("datasets/recap_libero10_task0"))
    parser.add_argument("--returns-tag", default=None)
    parser.add_argument("--decode-samples", action="store_true")
    args = parser.parse_args()
    root = require_project_path(args.data_root, label="data root")
    report = validate(root, returns_tag=args.returns_tag, decode_samples=args.decode_samples)
    print(json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True))
    return 0 if report["ok"] else 1


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