File size: 4,963 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 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | #!/usr/bin/env python3
"""Generate one deterministic shard of the StatePlay proxy benchmark."""
from __future__ import annotations
import argparse
import json
import os
import sys
from pathlib import Path
import imageio.v3 as iio
import numpy as np
import torch
from PIL import Image
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from stateplay import NEG_PROMPT, StatePlayPipeline # noqa: E402
from stateplay.utils import save_mp4 # noqa: E402
def first_video_frame(path: Path) -> Image.Image:
try:
frame = next(iio.imiter(path, plugin="FFMPEG"))
except StopIteration as exc:
raise RuntimeError(f"Video contains no frames: {path}") from exc
return Image.fromarray(np.asarray(frame, dtype=np.uint8)).convert("RGB")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--manifest", type=Path, default=ROOT / "evaluation/proxy100/selection.json")
parser.add_argument("--checkpoint", type=Path, required=True)
parser.add_argument("--run-name", required=True)
parser.add_argument("--base-model", type=Path, default=ROOT / "base_model")
parser.add_argument("--output-root", type=Path, default=ROOT / "evaluation/proxy100/generated")
parser.add_argument("--device", default="cuda")
parser.add_argument("--shard-index", type=int, default=0)
parser.add_argument("--num-shards", type=int, default=1)
parser.add_argument("--only", nargs="*")
parser.add_argument("--skip-existing", action="store_true")
parser.add_argument("--steps", type=int, default=30)
parser.add_argument("--cfg", type=float, default=5.0)
parser.add_argument("--action-cfg", type=float, default=1.0)
parser.add_argument("--seed", type=int, default=2)
args = parser.parse_args()
if not 0 <= args.shard_index < args.num_shards:
raise ValueError("--shard-index must be in [0, --num-shards)")
data = json.loads(args.manifest.resolve().read_text(encoding="utf-8"))
all_samples = data["samples"]
selected = [sample for index, sample in enumerate(all_samples) if index % args.num_shards == args.shard_index]
if args.only:
wanted = set(args.only)
selected = [sample for sample in selected if sample["id"] in wanted or sample["source_id"] in wanted]
if not selected:
print(f"Shard {args.shard_index} has no selected samples", flush=True)
return
output_dir = (args.output_root / args.run_name).resolve()
output_dir.mkdir(parents=True, exist_ok=True)
print(f"Loading {args.checkpoint} for shard {args.shard_index}/{args.num_shards} ({len(selected)} samples)", flush=True)
pipeline = StatePlayPipeline.from_pretrained(
base_model_dir=str(args.base_model.resolve()),
checkpoint_path=str(args.checkpoint.resolve()),
torch_dtype=torch.bfloat16,
).to(args.device)
records = []
for position, sample in enumerate(selected, start=1):
output = output_dir / sample["output_name"]
state_output = output.with_name(f"{output.stem}_state.txt")
if args.skip_existing and output.is_file() and output.stat().st_size > 0:
print(f"[{position}/{len(selected)}] skip {sample['id']} {output.name}", flush=True)
continue
if sample.get("input_image"):
with Image.open(ROOT / sample["input_image"]) as source:
image = source.convert("RGB")
else:
image = first_video_frame(ROOT / sample["source_video"])
result = pipeline(
image=image,
actions_parquet=str(ROOT / sample["actions"]),
state_parquet=str(ROOT / sample["actions"]),
state_txt=None if pipeline.uses_latent_state else str(state_output),
state_sampling="end",
prompt=sample["prompt"],
negative_prompt=NEG_PROMPT,
num_frames=101,
num_inference_steps=args.steps,
cfg_scale=args.cfg,
state_cfg_scale=1.0,
action_cfg_scale=args.action_cfg,
seed=args.seed,
)
temporary = output.with_name(f"{output.stem}.tmp.mp4")
save_mp4(result.frames[0], str(temporary), fps=20)
temporary.replace(output)
records.append(
{
"id": sample["id"],
"source_id": sample["source_id"],
"label": sample["label"],
"output": os.path.relpath(output, ROOT),
"state_output": None if pipeline.uses_latent_state else os.path.relpath(state_output, ROOT),
}
)
print(f"[{position}/{len(selected)}] saved {sample['id']} {output}", flush=True)
record_path = output_dir / f"run_manifest_shard_{args.shard_index:02d}.json"
record_path.write_text(json.dumps(records, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
if __name__ == "__main__":
main()
|