StatePlay-Reward-2280 / source /project /scripts /prepare_proxy_benchmark.py
lupele's picture
Add files using upload-large-folder tool
4ec41f2 verified
Raw History Blame Contribute Delete
7.56 kB
#!/usr/bin/env python3
"""Build a reproducible 100-sample StatePlay in-sample proxy benchmark."""
from __future__ import annotations
import argparse
import csv
import hashlib
import json
import random
from collections import Counter
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parents[1]
LABELS = ("normal", "macro_success", "macro_fail", "result_win", "result_lose")
def sha256_bytes(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(16 * 1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def repo_path(path: Path) -> str:
return path.resolve().relative_to(ROOT).as_posix()
def normalize_label(value: str) -> str:
label = value.strip().lower().replace("-", "_").replace(" ", "_")
if label not in LABELS:
raise ValueError(f"Unsupported distribution label: {value!r}")
return label
def bundled_examples(examples_manifest: Path) -> list[dict[str, Any]]:
result = []
with examples_manifest.open(newline="", encoding="utf-8-sig") as handle:
rows = list(csv.DictReader(handle))
for row in rows:
input_dir = examples_manifest.parent / row["input_dir"]
metadata_path = input_dir / "metadata.json"
metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
prompt_path = input_dir / "prompt.txt"
actions_path = input_dir / "actions.parquet"
image_path = input_dir / "first_frame.png"
prompt = prompt_path.read_text(encoding="utf-8").strip()
result.append(
{
"source_kind": "bundled_external",
"source_id": f"example_{row['id'].zfill(2)}",
"label": normalize_label(metadata["distribution"]),
"input_image": repo_path(image_path),
"source_video": None,
"reference_video": None,
"actions": repo_path(actions_path),
"prompt": prompt,
"identity": {
"input_image_sha256": sha256_file(image_path),
"actions_sha256": sha256_file(actions_path),
"prompt_sha256": sha256_bytes(prompt.encode("utf-8")),
"metadata_sha256": sha256_file(metadata_path),
},
}
)
return result
def training_examples(
metadata_path: Path,
existing: list[dict[str, Any]],
per_class: int,
seed: int,
) -> list[dict[str, Any]]:
with metadata_path.open(newline="", encoding="utf-8-sig") as handle:
rows = list(csv.DictReader(handle))
by_label: dict[str, list[dict[str, str]]] = {label: [] for label in LABELS}
for row in rows:
by_label[normalize_label(row["distribution"])].append(row)
existing_counts = Counter(item["label"] for item in existing)
rng = random.Random(seed)
selected: list[dict[str, Any]] = []
data_root = metadata_path.parent
for label in LABELS:
needed = per_class - existing_counts[label]
if needed < 0:
raise ValueError(f"Bundled examples exceed target count for {label}: {existing_counts[label]} > {per_class}")
candidates = sorted(by_label[label], key=lambda row: row["video"])
if len(candidates) < needed:
raise ValueError(f"Not enough {label} candidates: need {needed}, found {len(candidates)}")
for row in rng.sample(candidates, needed):
video_path = data_root / row["video"]
actions_path = data_root / row["action"]
clip_id = video_path.parent.name
prompt = row["prompt"].strip()
selected.append(
{
"source_kind": "training_clip",
"source_id": clip_id,
"label": label,
"input_image": None,
"source_video": repo_path(video_path),
"reference_video": repo_path(video_path),
"actions": repo_path(actions_path),
"prompt": prompt,
"identity": {
"video_sha256": sha256_file(video_path),
"video_size": video_path.stat().st_size,
"actions_sha256": sha256_file(actions_path),
"prompt_sha256": sha256_bytes(prompt.encode("utf-8")),
"metadata_video": row["video"],
"metadata_action": row["action"],
},
}
)
return selected
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--metadata", type=Path, default=ROOT / "data/SF3/train/clips_5s/metadata_state_polish.csv")
parser.add_argument("--examples-manifest", type=Path, default=ROOT / "examples/manifest.csv")
parser.add_argument("--output-dir", type=Path, default=ROOT / "evaluation/proxy100")
parser.add_argument("--seed", type=int, default=260726754)
parser.add_argument("--per-class", type=int, default=20)
args = parser.parse_args()
bundled = bundled_examples(args.examples_manifest.resolve())
training = training_examples(args.metadata.resolve(), bundled, args.per_class, args.seed)
samples = bundled + training
samples.sort(key=lambda item: (LABELS.index(item["label"]), item["source_kind"], item["source_id"]))
for index, sample in enumerate(samples, start=1):
sample["id"] = f"proxy_{index:03d}"
sample["output_name"] = f"proxy_{index:03d}_{sample['label']}_{sample['source_id']}.mp4"
counts = Counter(item["label"] for item in samples)
expected_total = args.per_class * len(LABELS)
if len(samples) != expected_total or any(counts[label] != args.per_class for label in LABELS):
raise RuntimeError(f"Invalid selection: total={len(samples)}, counts={dict(counts)}")
output_dir = args.output_dir.resolve()
output_dir.mkdir(parents=True, exist_ok=True)
manifest = {
"benchmark_name": "stateplay_proxy100_mixed_v1",
"warning": "Mixed proxy benchmark: 92 in-sample training clips plus 8 bundled external examples; not the unpublished 100-clip held-out paper test set.",
"selection": {
"seed": args.seed,
"labels": list(LABELS),
"per_class": args.per_class,
"total": len(samples),
"bundled_external": len(bundled),
"training_clips": len(training),
"metadata": repo_path(args.metadata.resolve()),
"metadata_sha256": sha256_file(args.metadata.resolve()),
},
"samples": samples,
}
json_path = output_dir / "selection.json"
json_path.write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
columns = ("id", "source_kind", "source_id", "label", "input_image", "source_video", "reference_video", "actions", "output_name")
with (output_dir / "selection.csv").open("w", newline="", encoding="utf-8") as handle:
writer = csv.DictWriter(handle, fieldnames=columns)
writer.writeheader()
for sample in samples:
writer.writerow({key: sample.get(key) or "" for key in columns})
print(json.dumps({"manifest": str(json_path), "counts": dict(counts), "sources": dict(Counter(x["source_kind"] for x in samples))}, indent=2))
if __name__ == "__main__":
main()