#!/usr/bin/env python """Record one explicitly requested π0.5 Task 0 demo episode. This script reuses the frozen baseline protocol and rollout helpers, but writes video and demo metadata outside the formal result directory. It refuses to keep a recording unless it reproduces a successful formal episode. """ from __future__ import annotations import argparse import datetime as dt import hashlib import json import os import sys import time from pathlib import Path from typing import Any os.environ.setdefault("MUJOCO_GL", "egl") os.environ.setdefault("PYOPENGL_PLATFORM", "egl") os.environ.setdefault("LIBERO_TYPE", "standard") import imageio.v2 as imageio import numpy as np SCRIPT_DIR = Path(__file__).resolve().parent PROJECT_ROOT = SCRIPT_DIR.parent for import_root in ( PROJECT_ROOT / "third_party" / "RLinf", PROJECT_ROOT / "third_party" / "openpi" / "src", SCRIPT_DIR, ): if str(import_root) not in sys.path: sys.path.insert(0, str(import_root)) from run_task0_pi05_baseline import ( # noqa: E402 LIBERO_COMMIT, OPENPI_COMMIT, RLLINF_COMMIT, _env_observation, _load_model, _make_env, _observation_hash, _reset_and_settle, _seed_everything, _step_result, ) from task0_baseline_common import ( # noqa: E402 atomic_json_dump, episode_seed, load_config, protocol_hash, require_project_path, sha256_file, ) DEFAULT_CONFIG = PROJECT_ROOT / "configs/baseline/libero10_task0_pi05_sft_formal.yaml" DEFAULT_RESULTS = PROJECT_ROOT / "results/baseline/task0_pi05_sft_v2" DEFAULT_OUTPUT = ( PROJECT_ROOT / "videos/demo/libero10_task0_pi05_sft_seed0_trial20_success.mp4" ) def _parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG) parser.add_argument("--formal-results", type=Path, default=DEFAULT_RESULTS) parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT) parser.add_argument("--seed", type=int, default=0) parser.add_argument("--trial-id", type=int, default=20) parser.add_argument("--fps", type=int, default=20) parser.add_argument("--device", default="cuda") parser.add_argument("--overwrite", action="store_true") return parser.parse_args() def _display_frame(raw: dict[str, Any]) -> np.ndarray: """Convert LIBERO's upside-down agent view to an encoder-ready frame.""" return np.asarray(raw["agentview_image"])[::-1].copy().astype(np.uint8) def _load_reference(path: Path) -> dict[str, Any]: if not path.is_file(): raise FileNotFoundError(f"formal episode record does not exist: {path}") value = json.loads(path.read_text(encoding="utf-8")) if not isinstance(value, dict): raise TypeError(f"formal episode record is not an object: {path}") return value def _validate_reference( reference: dict[str, Any], *, seed: int, trial_id: int, cfg_hash: str ) -> None: expected = { "policy_seed": seed, "trial_id": trial_id, "protocol_sha256": cfg_hash, "status": "completed", "success_once": True, } mismatches = { key: {"expected": expected_value, "actual": reference.get(key)} for key, expected_value in expected.items() if reference.get(key) != expected_value } if mismatches: raise RuntimeError( "selected formal episode is not an eligible successful reference: " + json.dumps(mismatches, ensure_ascii=False, sort_keys=True) ) def _encode_video(path: Path, frames: list[np.ndarray], fps: int) -> None: path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(f".{path.stem}.tmp.mp4") temporary.unlink(missing_ok=True) try: imageio.mimsave( temporary, frames, fps=fps, codec="libx264", macro_block_size=1, ffmpeg_params=["-pix_fmt", "yuv420p"], ) os.replace(temporary, path) finally: temporary.unlink(missing_ok=True) def main() -> int: args = _parse_args() if args.seed < 0 or not 0 <= args.trial_id < 50 or args.fps < 1: raise SystemExit("seed/fps must be positive and trial-id must be in 0..49") config_path = require_project_path(args.config, label="config") formal_results = require_project_path(args.formal_results, label="formal results") output_path = require_project_path(args.output, label="demo video") metadata_path = output_path.with_suffix(".json") if output_path.suffix.lower() != ".mp4": raise SystemExit("--output must use the .mp4 extension") if (output_path.exists() or metadata_path.exists()) and not args.overwrite: raise SystemExit("demo output already exists; pass --overwrite to replace it") cfg = load_config(config_path) if str(cfg.benchmark) != "libero_10" or int(cfg.task_id) != 0: raise SystemExit("demo recorder is restricted to libero_10 task_id=0") if bool(cfg.video.enabled): raise SystemExit("the frozen formal config must retain video.enabled=false") cfg_hash = protocol_hash(cfg) reference_path = ( formal_results / "episodes" / f"seed_{args.seed:03d}" / f"trial_{args.trial_id:02d}.json" ) reference = _load_reference(reference_path) _validate_reference( reference, seed=args.seed, trial_id=args.trial_id, cfg_hash=cfg_hash ) model_path = require_project_path(cfg.model.model_path, label="checkpoint") actual_weight_sha = sha256_file(model_path / "model.safetensors") if actual_weight_sha != str(cfg.model.checkpoint_weight_sha256): raise SystemExit( "checkpoint SHA256 mismatch: " f"expected {cfg.model.checkpoint_weight_sha256}, got {actual_weight_sha}" ) if reference.get("checkpoint_weight_sha256") != actual_weight_sha: raise RuntimeError("formal reference and current checkpoint SHA256 differ") import torch from rlinf.envs.libero.utils import quat2axisangle if args.device.startswith("cuda") and not torch.cuda.is_available(): raise SystemExit("CUDA requested but torch.cuda.is_available() is false") started = time.time() model = _load_model(cfg, model_path, args.device) suite, env = _make_env(cfg) task = suite.get_task(int(cfg.task_id)) init_states = suite.get_task_init_states(int(cfg.task_id)) init_state = init_states[args.trial_id] ep_seed = episode_seed( args.seed, args.trial_id, int(cfg.runner.episode_seed_multiplier) ) frames: list[np.ndarray] = [] raw_return = 0.0 env_steps = 0 chunks = 0 success = False done = False first_observation_hash: str | None = None first_action_hash: str | None = None try: _seed_everything(ep_seed) raw = _reset_and_settle(env, init_state, ep_seed, cfg) frames.append(_display_frame(raw)) while ( env_steps < int(cfg.environment.max_episode_steps) and not done and not success ): _seed_everything(ep_seed + chunks) observation = _env_observation(raw, str(task.language), quat2axisangle) if first_observation_hash is None: first_observation_hash = _observation_hash(observation) with torch.inference_mode(): actions, _ = model.predict_action_batch( env_obs=observation, mode="eval", compute_values=False ) action_chunk = actions.detach().cpu().numpy()[0] if first_action_hash is None: first_action_hash = hashlib.sha256( np.asarray( action_chunk[: int(cfg.model.executed_action_chunk)], dtype=np.float32, ).tobytes() ).hexdigest() chunks += 1 for action in action_chunk[: int(cfg.model.executed_action_chunk)]: if env_steps >= int(cfg.environment.max_episode_steps): break raw, reward, done = _step_result( env.step(action.astype(np.float32)) ) raw_return += reward env_steps += 1 frames.append(_display_frame(raw)) if bool(env.check_success()): success = True break finally: env.close() del model if torch.cuda.is_available(): torch.cuda.empty_cache() reproduction_checks = { "success_once": success == bool(reference["success_once"]), "success_step": env_steps == int(reference["success_step"]), "raw_env_return": raw_return == float(reference["raw_env_return"]), "first_observation_sha256": ( first_observation_hash == reference.get("first_observation_sha256") ), "first_action_chunk_sha256": ( first_action_hash == reference.get("first_action_chunk_sha256") ), } if not success or not all(reproduction_checks.values()): raise RuntimeError( "recorded rollout did not exactly reproduce the successful formal episode: " + json.dumps(reproduction_checks, ensure_ascii=False, sort_keys=True) ) _encode_video(output_path, frames, args.fps) height, width = frames[0].shape[:2] metadata = { "schema_version": "task0_pi05_demo_video_v1", "recorded_at": dt.datetime.now(dt.timezone.utc).isoformat(), "benchmark": str(cfg.benchmark), "task_id": int(cfg.task_id), "task_name": str(task.name), "task_language": str(task.language), "policy_role": "baseline_sft", "policy_seed": args.seed, "trial_id": args.trial_id, "episode_seed": ep_seed, "success_once": success, "success_step": env_steps, "raw_env_return": raw_return, "frame_count": len(frames), "fps": args.fps, "duration_seconds": len(frames) / args.fps, "width": width, "height": height, "camera": "agentview", "protocol_sha256": cfg_hash, "checkpoint_repo": str(cfg.model.checkpoint_repo), "checkpoint_revision": str(cfg.model.checkpoint_revision), "checkpoint_weight_sha256": actual_weight_sha, "rlinf_commit": RLLINF_COMMIT, "openpi_commit": OPENPI_COMMIT, "libero_commit": LIBERO_COMMIT, "formal_reference_relative": str(reference_path.relative_to(PROJECT_ROOT)), "reproduction_checks": reproduction_checks, "video_relative": str(output_path.relative_to(PROJECT_ROOT)), "video_bytes": output_path.stat().st_size, "video_sha256": sha256_file(output_path), "elapsed_seconds": round(time.time() - started, 3), "gpu_physical_id_if_known": os.environ.get("BASELINE_PHYSICAL_GPU"), } atomic_json_dump(metadata_path, metadata) print(json.dumps(metadata, ensure_ascii=False, sort_keys=True)) return 0 if __name__ == "__main__": raise SystemExit(main())