File size: 12,399 Bytes
6f003f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
#!/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<start>\d+)(?:-(?P<end>\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,
    }