#!/usr/bin/env python """Shared protocol, result and statistics helpers for Task 0 baseline runs.""" from __future__ import annotations import hashlib import json import math import os import re import tempfile from pathlib import Path from typing import Any, Iterable from omegaconf import DictConfig, OmegaConf PROJECT_ROOT = Path("/data/myx/RL_post_train").resolve() RESULT_SCHEMA_VERSION = "task0_baseline_episode_v1" _RANGE_RE = re.compile(r"^(?P\d+)(?:-(?P\d+))?$") def require_project_path(path: str | Path, *, label: str) -> Path: """Resolve a path and reject writes outside the project data boundary.""" resolved = Path(path).expanduser().resolve() try: resolved.relative_to(Path("/data/myx").resolve()) except ValueError as exc: raise ValueError(f"{label} must remain under /data/myx/: {resolved}") from exc return resolved def load_config(path: str | Path) -> DictConfig: path = require_project_path(path, label="config") if not path.is_file(): raise FileNotFoundError(path) return OmegaConf.load(path) def resolved_config_container(cfg: DictConfig) -> dict[str, Any]: value = OmegaConf.to_container(cfg, resolve=True) if not isinstance(value, dict): raise TypeError("baseline config must resolve to a mapping") return value def protocol_hash(cfg: DictConfig) -> str: payload = json.dumps( resolved_config_container(cfg), ensure_ascii=False, sort_keys=True, separators=(",", ":"), ).encode("utf-8") return hashlib.sha256(payload).hexdigest() def write_resolved_config(path: str | Path, cfg: DictConfig) -> None: path = require_project_path(path, label="resolved config") path.parent.mkdir(parents=True, exist_ok=True) OmegaConf.save(cfg, path, resolve=True) def parse_int_spec(spec: str | Iterable[int], *, label: str) -> list[int]: """Parse `0,2-4` style integer specifications deterministically.""" if not isinstance(spec, str): values = [int(item) for item in spec] else: values: list[int] = [] for token in (part.strip() for part in spec.split(",")): if not token: continue match = _RANGE_RE.fullmatch(token) if not match: raise ValueError(f"invalid {label} token: {token!r}") start = int(match.group("start")) end = int(match.group("end") or start) if end < start: raise ValueError(f"descending {label} range: {token!r}") values.extend(range(start, end + 1)) if not values: raise ValueError(f"{label} cannot be empty") unique = sorted(set(values)) if len(unique) != len(values): raise ValueError(f"{label} contains duplicates") return unique def expected_keys(seeds: Iterable[int], trial_ids: Iterable[int]) -> list[tuple[int, int]]: return [(int(seed), int(trial)) for seed in seeds for trial in trial_ids] def episode_seed(policy_seed: int, trial_id: int, multiplier: int = 1000) -> int: if policy_seed < 0 or trial_id < 0 or multiplier <= 0: raise ValueError("seed components must be non-negative and multiplier positive") return int(policy_seed) * int(multiplier) + int(trial_id) def sha256_file(path: str | Path) -> str: path = Path(path) 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 atomic_json_dump(path: str | Path, payload: dict[str, Any]) -> None: path = require_project_path(path, label="result") path.parent.mkdir(parents=True, exist_ok=True) fd, temporary = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent) temporary_path = Path(temporary) try: with os.fdopen(fd, "w", encoding="utf-8") as handle: json.dump(payload, handle, ensure_ascii=False, indent=2, sort_keys=True) handle.write("\n") handle.flush() os.fsync(handle.fileno()) os.replace(temporary_path, path) finally: temporary_path.unlink(missing_ok=True) def wilson_interval(successes: int, trials: int, z: float = 1.959963984540054) -> tuple[float, float]: if trials < 0 or successes < 0 or successes > trials: raise ValueError("successes/trials must satisfy 0 <= successes <= trials") if trials == 0: return (math.nan, math.nan) p = successes / trials z2 = z * z denominator = 1.0 + z2 / trials center = (p + z2 / (2.0 * trials)) / denominator half = z * math.sqrt(p * (1.0 - p) / trials + z2 / (4.0 * trials * trials)) / denominator return (max(0.0, center - half), min(1.0, center + half)) REQUIRED_FIELDS = { "schema_version", "protocol_version", "protocol_sha256", "run_id", "policy_role", "benchmark", "task_id", "task_name", "trial_id", "init_state_sha256", "policy_seed", "episode_seed", "checkpoint_repo", "checkpoint_revision", "checkpoint_weight_sha256", "checkpoint_local_path_relative", "rlinf_commit", "openpi_commit", "libero_commit", "max_episode_steps", "reset_settle_steps", "denoise_steps", "noise_level", "num_action_chunks_executed", "torch_compile_enabled", "success_once", "success_step", "env_steps", "raw_env_return", "rlinf_return", "status", "retry_count", "started_at", "finished_at", "elapsed_seconds", "gpu_logical_id", "gpu_physical_id_if_known", "error_type", "error_message", "video_path", } def validate_episode_record(record: dict[str, Any], *, expected_protocol_hash: str | None = None) -> None: missing = sorted(REQUIRED_FIELDS - record.keys()) if missing: raise ValueError(f"episode record missing fields: {', '.join(missing)}") if record["schema_version"] != RESULT_SCHEMA_VERSION: raise ValueError(f"unexpected schema_version: {record['schema_version']!r}") if expected_protocol_hash and record["protocol_sha256"] != expected_protocol_hash: raise ValueError("episode protocol hash does not match config") if record["status"] not in {"completed", "error"}: raise ValueError(f"invalid episode status: {record['status']!r}") if not isinstance(record["trial_id"], int) or record["trial_id"] < 0: raise ValueError("trial_id must be a non-negative integer") if not isinstance(record["policy_seed"], int) or record["policy_seed"] < 0: raise ValueError("policy_seed must be a non-negative integer") if record["status"] == "completed": if not isinstance(record["success_once"], bool): raise ValueError("completed success_once must be bool") if not (1 <= int(record["env_steps"]) <= int(record["max_episode_steps"])): raise ValueError("completed env_steps outside episode horizon") if record["video_path"] is not None: raise ValueError("formal baseline records must not contain video_path") def load_episode_records(input_dir: str | Path, *, expected_protocol_hash: str | None = None) -> list[dict[str, Any]]: root = require_project_path(input_dir, label="result directory") episode_root = root / "episodes" records: list[dict[str, Any]] = [] if not episode_root.is_dir(): return records for path in sorted(episode_root.glob("seed_*/trial_*.json")): with path.open("r", encoding="utf-8") as handle: record = json.load(handle) if not isinstance(record, dict): raise ValueError(f"episode record is not an object: {path}") validate_episode_record(record, expected_protocol_hash=expected_protocol_hash) try: file_seed = int(path.parent.name.removeprefix("seed_")) file_trial = int(path.stem.removeprefix("trial_")) except ValueError as exc: raise ValueError(f"invalid episode result filename: {path}") from exc record_key = (int(record["policy_seed"]), int(record["trial_id"])) if record_key != (file_seed, file_trial): raise ValueError( f"episode path/key mismatch: path={(file_seed, file_trial)}, record={record_key}" ) records.append(record) return records def validate_key_set( records: Iterable[dict[str, Any]], expected: Iterable[tuple[int, int]], ) -> dict[str, Any]: expected_set = {(int(seed), int(trial)) for seed, trial in expected} observed: list[tuple[int, int]] = [] for record in records: observed.append((int(record["policy_seed"]), int(record["trial_id"]))) observed_set = set(observed) duplicates = sorted({key for key in observed if observed.count(key) > 1}) return { "expected_count": len(expected_set), "observed_count": len(observed), "unique_count": len(observed_set), "missing": [list(key) for key in sorted(expected_set - observed_set)], "unexpected": [list(key) for key in sorted(observed_set - expected_set)], "duplicates": [list(key) for key in duplicates], } def summarize_records( records: list[dict[str, Any]], *, expected: list[tuple[int, int]], protocol_version: str, protocol_sha256: str, ) -> dict[str, Any]: key_report = validate_key_set(records, expected) completed = [record for record in records if record["status"] == "completed"] errors = [record for record in records if record["status"] == "error"] successes = [record for record in completed if record["success_once"]] n = len(completed) k = len(successes) ci_low, ci_high = wilson_interval(k, n) def values(field: str, subset: list[dict[str, Any]]) -> list[float]: return [float(item[field]) for item in subset if item[field] is not None] steps = values("env_steps", completed) raw_returns = values("raw_env_return", completed) success_steps = values("success_step", successes) def stats(items: list[float]) -> dict[str, float | None]: if not items: return {"mean": None, "std": None, "median": None} mean = sum(items) / len(items) variance = sum((item - mean) ** 2 for item in items) / len(items) return {"mean": mean, "std": math.sqrt(variance), "median": sorted(items)[len(items) // 2]} per_seed: dict[str, Any] = {} for seed in sorted({seed for seed, _ in expected}): seed_records = [item for item in completed if int(item["policy_seed"]) == seed] seed_successes = sum(bool(item["success_once"]) for item in seed_records) seed_low, seed_high = wilson_interval(seed_successes, len(seed_records)) per_seed[str(seed)] = { "planned": sum(1 for item_seed, _ in expected if item_seed == seed), "completed": len(seed_records), "success_count": seed_successes, "failure_count": len(seed_records) - seed_successes, "error_count": sum(int(item["policy_seed"]) == seed for item in errors), "success_rate": seed_successes / len(seed_records) if seed_records else None, "wilson_95ci": [seed_low, seed_high] if seed_records else [None, None], } status = "baseline_v2_complete" if n == len(expected) and not errors and not key_report["missing"] and not key_report["duplicates"] else "incomplete" if len(expected) == 50 and status == "baseline_v2_complete": status = "baseline_v1_complete" return { "schema_version": RESULT_SCHEMA_VERSION, "protocol_version": protocol_version, "protocol_sha256": protocol_sha256, "planned_episode_count": len(expected), "observed_episode_count": len(records), "unique_episode_count": key_report["unique_count"], "completed_episode_count": n, "error_episode_count": len(errors), "success_count": k, "failure_count": n - k, "success_rate": k / n if n else None, "wilson_95ci": [ci_low, ci_high] if n else [None, None], "key_report": key_report, "episode_steps": stats(steps), "raw_env_return": stats(raw_returns), "success_step": stats(success_steps), "per_policy_seed": per_seed, "videos_present": False, "status": status, }