so101_wm / tools /validate_cleaned_dataset.py
Samisaliveagain's picture
Add files using upload-large-folder tool
18b1016 verified
Raw
History Blame Contribute Delete
12.6 kB
#!/usr/bin/env python3
"""Validate cleaned SO-101 dataset structure and cross-modal alignment."""
from __future__ import annotations
import argparse
import csv
import hashlib
import json
import subprocess
from pathlib import Path
import numpy as np
import pyarrow.dataset as pads
import pyarrow.parquet as pq
FPS = 30
MODIFIED_FPV = {3, 5, 7, 8, 10}
EXPECTED_STREAM = {
"codec_name": "av1",
"width": 640,
"height": 480,
"pix_fmt": "yuv420p",
"r_frame_rate": "30/1",
"avg_frame_rate": "30/1",
}
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("--source-root", type=Path, default=Path("data/so101_wm"))
parser.add_argument("--clean-root", type=Path, default=Path("data/so101_wm_clean"))
parser.add_argument(
"--blurred-staging",
type=Path,
default=Path("data/so101_wm/videos/observation.images.fpv/copied fixed and blured faces"),
)
parser.add_argument("--report", type=Path, default=Path("artifacts/dataset_qc/clean_release_validation.json"))
return parser.parse_args()
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for block in iter(lambda: handle.read(8 * 1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def probe(path: Path) -> dict[str, object]:
command = [
"ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries",
"stream=codec_name,width,height,pix_fmt,r_frame_rate,avg_frame_rate,time_base,start_time,duration,nb_frames:format=duration",
"-of", "json", str(path),
]
payload = json.loads(subprocess.run(command, check=True, capture_output=True, text=True).stdout)
stream = payload["streams"][0]
stream["format_duration"] = payload["format"]["duration"]
return stream
def frame_pts(path: Path) -> np.ndarray:
command = [
"ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries",
"frame=best_effort_timestamp_time", "-of", "csv=p=0", str(path),
]
output = subprocess.run(command, check=True, capture_output=True, text=True).stdout
return np.asarray([float(line.strip().split(",")[0]) for line in output.splitlines() if line.strip()])
def same_tree_hashes(source: Path, clean: Path, pattern: str) -> tuple[int, list[str]]:
source_files = sorted(source.glob(pattern))
clean_files = sorted(clean.glob(pattern))
source_rel = [path.relative_to(source) for path in source_files]
clean_rel = [path.relative_to(clean) for path in clean_files]
problems = []
if source_rel != clean_rel:
problems.append(f"file lists differ for {pattern}")
return 0, problems
for relative in source_rel:
if sha256(source / relative) != sha256(clean / relative):
problems.append(f"unexpected byte difference: {relative}")
return len(source_rel), problems
def validate() -> tuple[dict[str, object], list[str]]:
args = parse_args()
source = args.source_root.resolve()
clean = args.clean_root.resolve()
staging = args.blurred_staging.resolve()
problems: list[str] = []
report: dict[str, object] = {}
# Every recorded numeric row and immutable metadata record must remain byte-identical.
immutable_checks = [
("data/**/*.parquet", "Parquet data"),
("meta/episodes/**/*.parquet", "episode metadata"),
("meta/tasks.parquet", "task metadata"),
("meta/info.json", "dataset schema"),
("videos/observation.images.left/**/*.mp4", "fixed-camera videos"),
]
immutable_counts = {}
for pattern, label in immutable_checks:
count, issues = same_tree_hashes(source, clean, pattern)
immutable_counts[label] = count
problems.extend(issues)
report["byte_identical_immutable_assets"] = immutable_counts
info = json.loads((clean / "meta/info.json").read_text(encoding="utf-8"))
numeric = pads.dataset(clean / "data", format="parquet").to_table()
total_rows = numeric.num_rows
if total_rows != int(info["total_frames"]):
problems.append(f"Parquet rows {total_rows} != info total_frames {info['total_frames']}")
index = numeric["index"].to_numpy(zero_copy_only=False)
if not np.array_equal(index, np.arange(total_rows, dtype=index.dtype)):
problems.append("global Parquet index is not consecutive")
frame_index = numeric["frame_index"].to_numpy(zero_copy_only=False)
timestamps = numeric["timestamp"].to_numpy(zero_copy_only=False)
if not np.allclose(timestamps, frame_index / FPS, atol=2e-5, rtol=0):
problems.append("timestamps do not equal frame_index / 30 within tolerance")
for feature in ("action", "observation.state"):
values = np.asarray(numeric[feature].to_pylist(), dtype=np.float64)
if not np.isfinite(values).all():
problems.append(f"{feature} contains NaN or infinite values")
# Episode metadata must point to matching Parquet and video spans.
episode_rows = pq.read_table(clean / "meta/episodes/chunk-000/file-000.parquet").to_pylist()
episode_ids = numeric["episode_index"].to_numpy(zero_copy_only=False)
task_ids = numeric["task_index"].to_numpy(zero_copy_only=False)
for row in episode_rows:
episode = int(row["episode_index"])
start = int(row["dataset_from_index"])
end = int(row["dataset_to_index"])
length = int(row["length"])
if end - start != length:
problems.append(f"episode {episode}: dataset range length mismatch")
if not np.all(episode_ids[start:end] == episode):
problems.append(f"episode {episode}: Parquet episode_index mismatch")
if len(set(task_ids[start:end].tolist())) != 1:
problems.append(f"episode {episode}: multiple task_index values")
for view in ("observation.images.left", "observation.images.fpv"):
video_duration = float(row[f"videos/{view}/to_timestamp"]) - float(row[f"videos/{view}/from_timestamp"])
if round(video_duration * FPS) != length:
problems.append(f"episode {episode}: {view} segment length mismatch")
# Every video stream must retain the declared geometry and total frame count.
video_totals = {}
for view in ("observation.images.left", "observation.images.fpv"):
total = 0
files = sorted((clean / "videos" / view / "chunk-000").glob("file-*.mp4"))
for path in files:
stream = probe(path)
for key, expected in EXPECTED_STREAM.items():
if stream.get(key) != expected:
problems.append(f"{path.name}: {key}={stream.get(key)!r}, expected {expected!r}")
total += int(stream["nb_frames"])
video_totals[view] = {"files": len(files), "frames": total}
if total != total_rows:
problems.append(f"{view}: {total} video frames != {total_rows} Parquet rows")
report["video_totals"] = video_totals
# Unmodified FPV files must be byte-identical. Modified files must match the
# validated staging versions and have exactly the same per-frame timestamps
# as the original source files.
pts_results = {}
for clean_path in sorted((clean / "videos/observation.images.fpv/chunk-000").glob("file-*.mp4")):
file_index = int(clean_path.stem.split("-")[-1])
original_path = source / "videos/observation.images.fpv/chunk-000" / clean_path.name
if file_index not in MODIFIED_FPV:
if sha256(clean_path) != sha256(original_path):
problems.append(f"unmodified FPV {clean_path.name} is not byte-identical")
continue
staged_path = staging / clean_path.name
if sha256(clean_path) != sha256(staged_path):
problems.append(f"clean FPV {clean_path.name} does not match blurred staging file")
original_pts = frame_pts(original_path)
clean_pts = frame_pts(clean_path)
if len(original_pts) != len(clean_pts):
problems.append(f"{clean_path.name}: per-frame timestamp count differs")
max_drift = None
else:
max_drift = float(np.max(np.abs(original_pts - clean_pts))) if len(original_pts) else 0.0
if max_drift > 1e-9:
problems.append(f"{clean_path.name}: maximum timestamp drift is {max_drift}s")
pts_results[clean_path.name] = {
"frames": len(clean_pts),
"maximum_pts_drift_s": max_drift,
"bytes_differ_from_original": sha256(clean_path) != sha256(original_path),
}
report["privacy_modified_fpv_timing"] = pts_results
# Supplied split must cover each episode once.
split_payload = json.loads((clean / "meta/cleaning/episode_splits.json").read_text(encoding="utf-8"))
split_sets = {name: set(values) for name, values in split_payload["splits"].items()}
union = set().union(*split_sets.values())
if union != set(range(int(info["total_episodes"]))):
problems.append("episode split does not cover all episodes")
names = list(split_sets)
for left_index, left in enumerate(names):
for right in names[left_index + 1 :]:
if split_sets[left] & split_sets[right]:
problems.append(f"episode split overlap: {left}/{right}")
report["split_sizes"] = {name: len(values) for name, values in split_sets.items()}
# Exclusions must be valid episode-local intervals and select synchronized rows.
with (clean / "meta/cleaning/intervention_exclusions.csv").open(encoding="utf-8") as handle:
exclusions = list(csv.DictReader(handle))
length_by_episode = {int(row["episode_index"]): int(row["length"]) for row in episode_rows}
active_rows = 0
for item in exclusions:
episode = int(item["episode_index"])
start = float(item["episode_start_s"])
end = float(item["episode_end_s"])
duration = length_by_episode[episode] / FPS
if not (0 <= start < end <= duration + 1e-5):
problems.append(f"invalid exclusion {item['review_id']} in episode {episode}")
if item["exclude_from_dynamics"] == "True":
selected = (episode_ids == episode) & (timestamps >= start) & (timestamps < end)
count = int(selected.sum())
active_rows += count
if count == 0:
problems.append(f"active exclusion {item['review_id']} selects no synchronized rows")
report["exclusions"] = {
"mapped_ranges": len(exclusions),
"active_mapped_ranges": sum(item["exclude_from_dynamics"] == "True" for item in exclusions),
"selected_rows_across_all_splits_before_overlap_deduplication": active_rows,
}
# Verify the exact train-only normalization row selection and moments.
train = np.asarray(sorted(split_sets["train"]), dtype=episode_ids.dtype)
keep = np.isin(episode_ids, train)
for item in exclusions:
if item["exclude_from_dynamics"] != "True":
continue
episode = int(item["episode_index"])
start = float(item["episode_start_s"])
end = float(item["episode_end_s"])
keep &= ~((episode_ids == episode) & (timestamps >= start) & (timestamps < end))
normalization = json.loads((clean / "meta/cleaning/normalization_stats.json").read_text(encoding="utf-8"))
if int(keep.sum()) != int(normalization["included_rows"]):
problems.append("normalization included_rows does not match split/exclusion mask")
for feature in ("action", "observation.state"):
values = np.asarray(numeric[feature].to_pylist(), dtype=np.float64)[keep]
stored = normalization["features"][feature]
if not np.allclose(values.mean(axis=0), stored["mean"], atol=1e-12, rtol=0):
problems.append(f"{feature} normalization mean mismatch")
if not np.allclose(values.std(axis=0), stored["std"], atol=1e-12, rtol=0):
problems.append(f"{feature} normalization std mismatch")
report["normalization_rows_verified"] = int(keep.sum())
report["parquet_rows"] = total_rows
report["status"] = "PASS" if not problems else "FAIL"
return report, problems
def main() -> None:
args = parse_args()
report, problems = validate()
args.report.parent.mkdir(parents=True, exist_ok=True)
args.report.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
print(json.dumps(report, indent=2))
if problems:
print("Problems:")
for problem in problems:
print(f"- {problem}")
raise SystemExit(1)
if __name__ == "__main__":
main()