Download scripts/validate_recap_data.py from myx160/rl-post-train-artifacts: direct link, hf CLI and curl.
- Browser
- Download file 7.05 kB
-
https://huggingface.co/datasets/myx160/rl-post-train-artifacts/resolve/main/scripts/validate_recap_data.py
- Command line
-
hf download hf://datasets/myx160/rl-post-train-artifacts/scripts/validate_recap_data.py
-
curl -L -o validate_recap_data.py https://huggingface.co/datasets/myx160/rl-post-train-artifacts/resolve/main/scripts/validate_recap_data.py
7.05 kB
| #!/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()) | |