rl-post-train-artifacts / scripts /attach_cfg_norm_stats.py
myx160's picture
Add files using upload-large-folder tool
6f003f2 verified
Raw History Blame Contribute Delete
3.22 kB
#!/usr/bin/env python
"""Attach the frozen LIBERO norm stats to an RLinf CFG actor checkpoint.
RLinf's training checkpoint writer stores DCP and full weights but does not
copy the small OpenPI norm-statistics tree. This helper adds only that file,
atomically and without duplicating the base model.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import shutil
from pathlib import Path
PROJECT_ROOT = Path("/data/myx/RL_post_train").resolve()
BASE_NORM_STATS = PROJECT_ROOT / "checkpoints/base/RLinf-Pi05-LIBERO-SFT/physical-intelligence/libero/norm_stats.json"
def _sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def _resolve(raw: Path) -> Path:
path = raw.expanduser()
if not path.is_absolute():
path = PROJECT_ROOT / path
path = path.resolve()
try:
path.relative_to(PROJECT_ROOT)
except ValueError as exc:
raise ValueError(f"checkpoint must remain under {PROJECT_ROOT}: {path}") from exc
return path
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument(
"--checkpoint",
type=Path,
required=True,
help="Actor checkpoint directory (the directory containing model_state_dict/).",
)
args = parser.parse_args()
actor_root = _resolve(args.checkpoint)
if not actor_root.is_dir():
raise FileNotFoundError(f"actor checkpoint directory does not exist: {actor_root}")
if not (actor_root / "model_state_dict" / "full_weights.pt").is_file():
raise FileNotFoundError(
f"full_weights.pt is missing below actor checkpoint: {actor_root}"
)
if not BASE_NORM_STATS.is_file():
raise FileNotFoundError(f"frozen base norm stats missing: {BASE_NORM_STATS}")
source_hash = _sha256(BASE_NORM_STATS)
destination = actor_root / "physical-intelligence/libero/norm_stats.json"
destination.parent.mkdir(parents=True, exist_ok=True)
if destination.exists():
destination_hash = _sha256(destination)
if destination_hash != source_hash:
raise RuntimeError(
f"existing norm stats hash differs: {destination_hash} != {source_hash}"
)
action = "already_present"
else:
temporary = destination.with_name(
f".{destination.name}.tmp.{os.getpid()}"
)
try:
shutil.copyfile(BASE_NORM_STATS, temporary)
os.replace(temporary, destination)
finally:
if temporary.exists():
temporary.unlink()
action = "copied"
print(
json.dumps(
{
"ok": True,
"action": action,
"actor_root": str(actor_root),
"norm_stats": str(destination),
"sha256": source_hash,
"bytes": destination.stat().st_size,
},
ensure_ascii=False,
sort_keys=True,
)
)
return 0
if __name__ == "__main__":
raise SystemExit(main())