File size: 24,977 Bytes
e588892
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
#!/usr/bin/env python
"""Run the project-owned, headless π0.5 LIBERO-10 Task 0 evaluator.

The model is loaded once per invocation. Each completed episode is written to
an atomic JSON file so a later invocation can resume without changing prior
results. Video is intentionally unsupported in this formal baseline runner;
the protocol requires it to remain disabled.
"""

from __future__ import annotations

import argparse
import datetime as dt
import hashlib
import json
import os
import random
import shlex
import sys
import time
import traceback
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 numpy as np
from omegaconf import DictConfig, OmegaConf

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"):
    if str(import_root) not in sys.path:
        sys.path.insert(0, str(import_root))
if str(SCRIPT_DIR) not in sys.path:
    sys.path.insert(0, str(SCRIPT_DIR))

from task0_baseline_common import (  # noqa: E402
    RESULT_SCHEMA_VERSION,
    atomic_json_dump,
    episode_seed,
    expected_keys,
    load_config,
    load_episode_records,
    parse_int_spec,
    protocol_hash,
    require_project_path,
    sha256_file,
    validate_episode_record,
    write_resolved_config,
)


RLLINF_COMMIT = "0505431899574619da86f551bad70b71e0ea2177"
OPENPI_COMMIT = "c5dc4b9296a1a4739bf52828f28a579f12dce763"
LIBERO_COMMIT = "0c5e40cc4ae63e09c14e7df6f74481e9ee8585f7"


def _parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument("--config", type=Path, required=True)
    parser.add_argument("--output-dir", type=Path, required=True)
    parser.add_argument("--seeds", default=None)
    parser.add_argument("--trial-ids", default=None)
    parser.add_argument("--max-episodes-per-invocation", type=int, default=None)
    parser.add_argument("--device", default="cuda")
    parser.add_argument("--resume", action="store_true")
    parser.add_argument("--overwrite", action="store_true")
    parser.add_argument("--dry-run", action="store_true")
    return parser.parse_args()


def _model_option(model: DictConfig, key: str, default: Any) -> Any:
    """Read an option from model.openpi first, then model, preserving old configs."""
    nested = model.get("openpi")
    if nested is not None and key in nested:
        return nested[key]
    return model.get(key, default)


def _model_cfg(cfg: DictConfig, model_path: Path) -> DictConfig:
    model = cfg.model
    model_type = str(model.model_type)
    openpi_cfg = {
        "config_name": str(model.config_name),
        "num_images_in_input": 2,
        "noise_level": float(model.noise_level),
        "action_chunk": int(model.executed_action_chunk),
        "num_steps": int(model.denoise_steps),
        "train_expert_only": bool(_model_option(model, "train_expert_only", model_type != "cfg_model")),
        "action_env_dim": int(model.action_dim),
        "noise_method": str(model.noise_method),
        "add_value_head": False,
        "value_after_vlm": False,
        "value_vlm_mode": "mean_token",
        "detach_critic_input": None,
    }
    # CFG-only fields are ignored by the regular OpenPI builder and are kept
    # here so the same evaluator can load a project-owned cfg_model checkpoint.
    if model_type == "cfg_model":
        openpi_cfg.update(
            {
                "cfgrl_guidance_scale": float(_model_option(model, "cfgrl_guidance_scale", 1.0)),
                "unconditional_prob": float(_model_option(model, "unconditional_prob", 0.1)),
                "guidance_type": str(_model_option(model, "guidance_type", "positive")),
                "positive_only_conditional": bool(_model_option(model, "positive_only_conditional", True)),
            }
        )
    return OmegaConf.create(
        {
            "model_type": model_type,
            "model_path": str(model_path),
            "precision": None,
            "load_to_device": False,
            "is_lora": False,
            "lora_rank": 32,
            "num_action_chunks": int(model.executed_action_chunk),
            "action_dim": int(model.action_dim),
            "use_proprio": bool(model.use_proprio),
            "num_steps": int(model.denoise_steps),
            "add_value_head": False,
            "openpi": openpi_cfg,
        }
    )


def _env_observation(raw: dict[str, Any], prompt: str, quat2axisangle) -> dict[str, Any]:
    main_image = np.asarray(raw["agentview_image"])[::-1, ::-1].copy()
    wrist_image = np.asarray(raw["robot0_eye_in_hand_image"])[::-1, ::-1].copy()
    state = np.concatenate(
        [
            np.asarray(raw["robot0_eef_pos"]),
            quat2axisangle(np.asarray(raw["robot0_eef_quat"]).copy()),
            np.asarray(raw["robot0_gripper_qpos"]),
        ]
    ).astype(np.float32)
    import torch

    return {
        "main_images": torch.from_numpy(main_image[None]),
        "wrist_images": torch.from_numpy(wrist_image[None]),
        "extra_view_images": None,
        "states": torch.from_numpy(state[None]),
        "task_descriptions": [prompt],
    }


def _step_result(result: tuple[Any, ...]) -> tuple[dict[str, Any], float, bool]:
    if len(result) == 4:
        obs, reward, done, _info = result
        return obs, float(reward), bool(done)
    obs, reward, terminated, truncated, _info = result
    return obs, float(reward), bool(terminated or truncated)


def _seed_everything(value: int) -> None:
    random.seed(value)
    np.random.seed(value)
    os.environ["PYTHONHASHSEED"] = str(value)
    import torch

    torch.manual_seed(value)
    if torch.cuda.is_available():
        torch.cuda.manual_seed_all(value)
        torch.backends.cudnn.benchmark = False


def _gpu_memory() -> dict[str, int | None]:
    import torch

    if not torch.cuda.is_available():
        return {"allocated": None, "reserved": None, "peak_allocated": None}
    return {
        "allocated": int(torch.cuda.memory_allocated()),
        "reserved": int(torch.cuda.memory_reserved()),
        "peak_allocated": int(torch.cuda.max_memory_allocated()),
    }


def _observation_hash(observation: dict[str, Any]) -> str:
    digest = hashlib.sha256()
    for key in ("main_images", "wrist_images", "states"):
        value = observation.get(key)
        if value is None:
            continue
        digest.update(key.encode("utf-8"))
        digest.update(value.detach().cpu().contiguous().numpy().tobytes())
    digest.update(json.dumps(observation.get("task_descriptions"), ensure_ascii=False).encode("utf-8"))
    return digest.hexdigest()


def _make_env(cfg: DictConfig):
    from libero.libero.envs import OffScreenRenderEnv

    suite = _make_suite(cfg)
    bddl_file = suite.get_task_bddl_file_path(int(cfg.task_id))
    env = OffScreenRenderEnv(
        bddl_file_name=bddl_file,
        camera_heights=int(cfg.environment.camera_height),
        camera_widths=int(cfg.environment.camera_width),
        camera_names=list(cfg.environment.camera_names),
        horizon=int(cfg.environment.max_episode_steps) + int(cfg.environment.reset_settle_steps) + 2,
    )
    return suite, env


def _make_suite(cfg: DictConfig):
    from libero.libero import benchmark

    return benchmark.get_benchmark_dict()[str(cfg.benchmark)]()


def _reset_and_settle(env, init_state: Any, seed: int, cfg: DictConfig):
    if hasattr(env, "seed"):
        env.seed(seed)
    raw = env.reset()
    raw = env.set_init_state(init_state)
    zero_action = np.zeros(int(cfg.model.action_dim), dtype=np.float32)
    zero_action[-1] = float(cfg.environment.reset_gripper_action)
    for _ in range(int(cfg.environment.reset_settle_steps)):
        raw, _reward, _done = _step_result(env.step(zero_action))
    return raw


def _load_model(cfg: DictConfig, model_path: Path, device_name: str):
    import torch

    if not torch.cuda.is_available() and device_name.startswith("cuda"):
        raise RuntimeError("CUDA requested but torch.cuda.is_available() is false")
    from rlinf.models import get_model

    original_compile = torch.compile
    if not bool(cfg.model.torch_compile_enabled):
        torch.compile = lambda fn, *unused_args, **unused_kwargs: fn  # type: ignore[assignment]
    try:
        model = get_model(_model_cfg(cfg, model_path))
    finally:
        torch.compile = original_compile
    if model is None:
        raise RuntimeError("RLinf model registry returned no model")
    return model.to(torch.device(device_name)).eval()


def _episode_path(root: Path, seed: int, trial_id: int) -> Path:
    return root / "episodes" / f"seed_{seed:03d}" / f"trial_{trial_id:02d}.json"


def _record_error(
    *,
    cfg: DictConfig,
    cfg_hash: str,
    run_id: str,
    seed: int,
    trial_id: int,
    init_state_hash: str,
    retry_count: int,
    started: float,
    exc: BaseException,
    device_name: str,
) -> dict[str, Any]:
    finished = time.time()
    return {
        "schema_version": RESULT_SCHEMA_VERSION,
        "protocol_version": str(cfg.protocol_version),
        "protocol_sha256": cfg_hash,
        "run_id": run_id,
        "policy_role": str(cfg.get("policy_role", "baseline_sft")),
        "benchmark": str(cfg.benchmark),
        "task_id": int(cfg.task_id),
        "task_name": "unknown",
        "trial_id": int(trial_id),
        "init_state_sha256": init_state_hash,
        "policy_seed": int(seed),
        "episode_seed": episode_seed(seed, trial_id, int(cfg.runner.episode_seed_multiplier)),
        "checkpoint_repo": str(cfg.model.checkpoint_repo),
        "checkpoint_revision": str(cfg.model.checkpoint_revision),
        "checkpoint_weight_sha256": str(cfg.model.checkpoint_weight_sha256),
        "checkpoint_local_path_relative": str(Path(cfg.model.model_path).resolve().relative_to(PROJECT_ROOT)),
        "rlinf_commit": RLLINF_COMMIT,
        "openpi_commit": OPENPI_COMMIT,
        "libero_commit": LIBERO_COMMIT,
        "max_episode_steps": int(cfg.environment.max_episode_steps),
        "reset_settle_steps": int(cfg.environment.reset_settle_steps),
        "denoise_steps": int(cfg.model.denoise_steps),
        "noise_level": float(cfg.model.noise_level),
        "num_action_chunks_executed": 0,
        "torch_compile_enabled": bool(cfg.model.torch_compile_enabled),
        "success_once": False,
        "success_step": None,
        "env_steps": 0,
        "raw_env_return": None,
        "rlinf_return": None,
        "status": "error",
        "retry_count": int(retry_count),
        "started_at": dt.datetime.fromtimestamp(started, dt.timezone.utc).isoformat(),
        "finished_at": dt.datetime.fromtimestamp(finished, dt.timezone.utc).isoformat(),
        "elapsed_seconds": round(finished - started, 3),
        "gpu_logical_id": device_name,
        "gpu_physical_id_if_known": os.environ.get("BASELINE_PHYSICAL_GPU"),
        "error_type": type(exc).__name__,
        "error_message": str(exc)[:1000],
        "video_path": None,
        "first_observation_sha256": None,
        "first_action_chunk_sha256": None,
    }


def _run_episode(model, env, init_state: Any, task_name: str, task_prompt: str, seed: int, trial_id: int, cfg: DictConfig, device_name: str, cfg_hash: str, run_id: str, retry_count: int) -> dict[str, Any]:
    import torch
    from rlinf.envs.libero.utils import quat2axisangle

    started = time.time()
    ep_seed = episode_seed(seed, trial_id, int(cfg.runner.episode_seed_multiplier))
    init_state_hash = hashlib.sha256(np.asarray(init_state).tobytes()).hexdigest()
    _seed_everything(ep_seed)
    raw = _reset_and_settle(env, init_state, ep_seed, cfg)
    raw_return = 0.0
    success_step: int | None = None
    env_steps = 0
    chunks = 0
    success = False
    done = False
    first_observation_hash: str | None = None
    first_action_hash: str | None = None
    while env_steps < int(cfg.environment.max_episode_steps) and not done and not success:
        _seed_everything(ep_seed + chunks)
        obs = _env_observation(raw, task_prompt, quat2axisangle)
        if first_observation_hash is None:
            first_observation_hash = _observation_hash(obs)
        with torch.inference_mode():
            actions, _ = model.predict_action_batch(env_obs=obs, mode="eval", compute_values=False)
        if torch.is_tensor(actions):
            action_chunk = actions.detach().cpu().numpy()[0]
        else:
            # cfg_model's public sampler returns a NumPy array, while the
            # regular OpenPI path returns a torch Tensor.
            action_chunk = np.asarray(actions)[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
            if bool(env.check_success()):
                success = True
                success_step = env_steps
                break
    finished = time.time()
    memory = _gpu_memory()
    return {
        "schema_version": RESULT_SCHEMA_VERSION,
        "protocol_version": str(cfg.protocol_version),
        "protocol_sha256": cfg_hash,
        "run_id": run_id,
        "policy_role": str(cfg.get("policy_role", "baseline_sft")),
        "benchmark": str(cfg.benchmark),
        "task_id": int(cfg.task_id),
        "task_name": task_name,
        "trial_id": int(trial_id),
        "init_state_sha256": init_state_hash,
        "policy_seed": int(seed),
        "episode_seed": ep_seed,
        "checkpoint_repo": str(cfg.model.checkpoint_repo),
        "checkpoint_revision": str(cfg.model.checkpoint_revision),
        "checkpoint_weight_sha256": str(cfg.model.checkpoint_weight_sha256),
        "checkpoint_local_path_relative": str(Path(cfg.model.model_path).resolve().relative_to(PROJECT_ROOT)),
        "rlinf_commit": RLLINF_COMMIT,
        "openpi_commit": OPENPI_COMMIT,
        "libero_commit": LIBERO_COMMIT,
        "max_episode_steps": int(cfg.environment.max_episode_steps),
        "reset_settle_steps": int(cfg.environment.reset_settle_steps),
        "denoise_steps": int(cfg.model.denoise_steps),
        "noise_level": float(cfg.model.noise_level),
        "num_action_chunks_executed": chunks,
        "torch_compile_enabled": bool(cfg.model.torch_compile_enabled),
        "success_once": bool(success),
        "success_step": success_step,
        "env_steps": env_steps,
        "raw_env_return": raw_return,
        "rlinf_return": 5.0 if success else 0.0,
        "status": "completed",
        "retry_count": int(retry_count),
        "started_at": dt.datetime.fromtimestamp(started, dt.timezone.utc).isoformat(),
        "finished_at": dt.datetime.fromtimestamp(finished, dt.timezone.utc).isoformat(),
        "elapsed_seconds": round(finished - started, 3),
        "gpu_logical_id": device_name,
        "gpu_physical_id_if_known": os.environ.get("BASELINE_PHYSICAL_GPU"),
        "error_type": None,
        "error_message": None,
        "video_path": None,
        "first_observation_sha256": first_observation_hash,
        "first_action_chunk_sha256": first_action_hash,
        "gpu_memory_bytes": memory,
    }


def _write_run_metadata(root: Path, cfg: DictConfig, cfg_hash: str, run_id: str, expected: list[tuple[int, int]]) -> None:
    root.mkdir(parents=True, exist_ok=True)
    protocol_path = root / "protocol.yaml"
    if protocol_path.exists():
        existing_hash = (root / "protocol.sha256").read_text(encoding="utf-8").strip() if (root / "protocol.sha256").exists() else ""
        if existing_hash and existing_hash != cfg_hash:
            raise RuntimeError("existing result directory uses a different protocol hash")
    else:
        write_resolved_config(protocol_path, cfg)
        (root / "protocol.sha256").write_text(cfg_hash + "\n", encoding="utf-8")
    run_manifest = root / "run_manifest.json"
    if not run_manifest.exists():
        atomic_json_dump(
            run_manifest,
            {
                "protocol_version": str(cfg.protocol_version),
                "protocol_sha256": cfg_hash,
                "first_run_id": run_id,
                "expected_episode_count": len(expected),
                "expected_keys": [list(key) for key in expected],
                "video_enabled": bool(cfg.video.enabled),
            },
        )


def _write_status(root: Path, cfg: DictConfig, cfg_hash: str, expected: list[tuple[int, int]]) -> None:
    records = load_episode_records(root, expected_protocol_hash=cfg_hash)
    planned = expected_keys(
        [int(seed) for seed in cfg.policy_seeds],
        [int(trial) for trial in cfg.trial_ids],
    )
    completed = {
        (int(item["policy_seed"]), int(item["trial_id"]))
        for item in records
        if item["status"] == "completed"
    }
    errors = {(int(item["policy_seed"]), int(item["trial_id"])) for item in records if item["status"] == "error"}
    atomic_json_dump(
        root / "status.json",
        {
            "protocol_version": str(cfg.protocol_version),
            "protocol_sha256": cfg_hash,
            "planned_episode_count": len(planned),
            "completed_episode_count": len(completed),
            "error_episode_count": len(errors),
            "pending_episode_count": len(set(planned) - completed),
            "updated_at": dt.datetime.now(dt.timezone.utc).isoformat(),
        },
    )


def _checkpoint_weight_path(model_path: Path) -> Path:
    """Find a supported local checkpoint weight file without changing old paths."""
    candidates = [
        model_path / "model.safetensors",
        model_path / "model_state_dict" / "full_weights.pt",
        model_path / "actor" / "model_state_dict" / "full_weights.pt",
    ]
    candidates.extend(sorted(model_path.rglob("*.safetensors")))
    candidates.extend(sorted(model_path.rglob("full_weights.pt")))
    for candidate in candidates:
        if candidate.is_file():
            return candidate
    raise FileNotFoundError(f"no supported checkpoint weight file found under {model_path}")


def main() -> int:
    args = _parse_args()
    cfg = load_config(args.config)
    if str(cfg.benchmark) != "libero_10" or int(cfg.task_id) != 0:
        raise SystemExit("formal runner is restricted to libero_10 task_id=0")
    if bool(cfg.video.enabled):
        raise SystemExit("formal baseline runner requires video.enabled=false")
    root = require_project_path(args.output_dir, label="output directory")
    cfg_hash = protocol_hash(cfg)
    seeds = parse_int_spec(args.seeds, label="seeds") if args.seeds else [int(seed) for seed in cfg.policy_seeds]
    trials = parse_int_spec(args.trial_ids, label="trial ids") if args.trial_ids else [int(trial) for trial in cfg.trial_ids]
    expected = expected_keys(seeds, trials)
    if any(trial < 0 or trial >= 50 for trial in trials):
        raise SystemExit("Task 0 trial ids must be in 0..49")
    run_id = dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ") + "_" + cfg_hash[:12]
    _write_run_metadata(root, cfg, cfg_hash, run_id, expected)
    write_resolved_config(root / "resolved_config.yaml", cfg)
    with (root / "commands.txt").open("a", encoding="utf-8") as handle:
        handle.write(
            dt.datetime.now(dt.timezone.utc).isoformat()
            + " "
            + " ".join(shlex.quote(item) for item in sys.argv)
            + "\n"
        )
    _write_status(root, cfg, cfg_hash, expected)

    model_path = require_project_path(cfg.model.model_path, label="checkpoint")
    if not model_path.is_dir():
        raise SystemExit(f"checkpoint directory does not exist: {model_path}")
    if args.dry_run:
        records = load_episode_records(root, expected_protocol_hash=cfg_hash)
        completed = {(int(item["policy_seed"]), int(item["trial_id"])) for item in records if item["status"] == "completed"}
        pending = [key for key in expected if key not in completed]
        print(json.dumps({"protocol_sha256": cfg_hash, "expected_count": len(expected), "completed_count": len(completed), "pending_count": len(pending), "pending_keys": [list(key) for key in pending]}, ensure_ascii=False))
        return 0

    max_episodes = args.max_episodes_per_invocation or int(cfg.runner.default_max_episodes_per_invocation)
    if max_episodes < 1:
        raise SystemExit("--max-episodes-per-invocation must be positive")
    records = load_episode_records(root, expected_protocol_hash=cfg_hash)
    completed = set() if args.overwrite else {
        (int(item["policy_seed"]), int(item["trial_id"]))
        for item in records
        if item["status"] == "completed"
    }
    pending = [key for key in expected if key not in completed]
    pending = pending[:max_episodes]
    if not pending:
        _write_status(root, cfg, cfg_hash, expected)
        print("no pending episodes")
        return 0

    import torch

    if args.device.startswith("cuda") and not torch.cuda.is_available():
        raise SystemExit("CUDA requested but torch.cuda.is_available() is false; do not substitute a GPU run")
    actual_weight_sha = sha256_file(_checkpoint_weight_path(model_path))
    if actual_weight_sha != str(cfg.model.checkpoint_weight_sha256):
        raise SystemExit(f"checkpoint SHA256 mismatch: expected {cfg.model.checkpoint_weight_sha256}, got {actual_weight_sha}")
    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))
    if len(init_states) != 50:
        raise RuntimeError(f"expected 50 Task 0 init states, got {len(init_states)}")
    try:
        for seed, trial_id in pending:
            output_path = _episode_path(root, seed, trial_id)
            if output_path.exists() and not args.overwrite:
                existing = json.loads(output_path.read_text(encoding="utf-8"))
                if existing.get("status") == "completed":
                    continue
            started = time.time()
            last_exc: BaseException | None = None
            record: dict[str, Any] | None = None
            for retry in range(int(cfg.runner.retry_limit) + 1):
                try:
                    record = _run_episode(
                        model,
                        env,
                        init_states[trial_id],
                        str(task.name),
                        str(task.language),
                        seed,
                        trial_id,
                        cfg,
                        args.device,
                        cfg_hash,
                        run_id,
                        retry,
                    )
                    last_exc = None
                    break
                except Exception as exc:  # record failure, then retry once
                    last_exc = exc
                    traceback.print_exc()
                    try:
                        env.close()
                    except Exception:
                        pass
                    suite, env = _make_env(cfg)
            if record is None:
                assert last_exc is not None
                record = _record_error(
                    cfg=cfg,
                    cfg_hash=cfg_hash,
                    run_id=run_id,
                    seed=seed,
                    trial_id=trial_id,
                    init_state_hash=hashlib.sha256(np.asarray(init_states[trial_id]).tobytes()).hexdigest(),
                    retry_count=int(cfg.runner.retry_limit),
                    started=started,
                    exc=last_exc,
                    device_name=args.device,
                )
            validate_episode_record(record, expected_protocol_hash=cfg_hash)
            if record["status"] == "error":
                atomic_json_dump(output_path, record)
                _write_status(root, cfg, cfg_hash, expected)
                raise RuntimeError(f"episode error for seed={seed} trial={trial_id}; see {output_path}")
            atomic_json_dump(output_path, record)
            _write_status(root, cfg, cfg_hash, expected)
            print(json.dumps({"seed": seed, "trial_id": trial_id, "success": record["success_once"], "env_steps": record["env_steps"], "elapsed_seconds": record["elapsed_seconds"]}, ensure_ascii=False))
    finally:
        env.close()
        del model
        if torch.cuda.is_available():
            torch.cuda.empty_cache()
    return 0


if __name__ == "__main__":
    raise SystemExit(main())