rl-post-train-artifacts / scripts /validate_cfg_preflight.py
myx160's picture
Add files using upload-large-folder tool
6f003f2 verified
Raw History Blame Contribute Delete
15.4 kB
#!/usr/bin/env python
"""CPU-only validation for the staged Task 0 CFG configuration.
The validator deliberately checks the project override and canonical sidecars
without constructing a model or touching CUDA. It is intended to fail before
Ray/FSDP is launched when a dangerous override, stale advantage tag, or path
outside the project is present.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
from pathlib import Path
from typing import Any
import numpy as np
import pyarrow.parquet as pq
from omegaconf import DictConfig, OmegaConf
PROJECT_ROOT = Path("/data/myx/RL_post_train").resolve()
DATA_ROOT = PROJECT_ROOT / "datasets/recap_libero10_task0"
ADVANTAGE_TAG = "recap_v1_step4000_full"
ADVANTAGE_MANIFEST = (
PROJECT_ROOT
/ "logs/recap/advantage/recap_v1_step4000_full_sharded/manifest.json"
)
EXPECTED_SIDECARS = {
"libero10_task0_sft": {
"rows": 8005,
"positive": 8005,
"sha256": "33fa2a93ca9221cf1094cc3548e233f61663ca7205e5ca97cb20a065ab5969e8",
},
"libero10_task0_train": {
"rows": 1561874,
"positive": 468465,
"sha256": "c25bab9e771d5f64091c0a43c57db7dcad257a96679f1825f2de2de360e8e8f9",
},
}
def _as_dict(value: Any) -> dict[str, Any]:
if isinstance(value, DictConfig):
return dict(value)
if isinstance(value, dict):
return value
return {}
def _sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def _project_path(raw: Any, label: str, errors: list[str]) -> Path | None:
if raw is None:
errors.append(f"missing path: {label}")
return None
path = Path(str(raw)).expanduser()
if not path.is_absolute():
path = (PROJECT_ROOT / path).resolve()
else:
path = path.resolve()
try:
path.relative_to(PROJECT_ROOT)
except ValueError:
errors.append(f"path outside /data/myx/RL_post_train: {label}={path}")
return None
return path
def _check_sidecar(split: str, errors: list[str]) -> dict[str, Any]:
expected = EXPECTED_SIDECARS[split]
sidecar = DATA_ROOT / split / "meta" / f"advantages_{ADVANTAGE_TAG}.parquet"
if not sidecar.is_file():
errors.append(f"missing canonical sidecar: {sidecar}")
return {"path": str(sidecar), "exists": False}
actual_hash = _sha256(sidecar)
table = pq.read_table(
sidecar, columns=["episode_index", "frame_index", "advantage"]
)
episode = table.column("episode_index").to_numpy()
frame = table.column("frame_index").to_numpy()
keys = np.stack([episode, frame], axis=1)
positive = int(np.asarray(table.column("advantage").to_numpy(), dtype=bool).sum())
report = {
"path": str(sidecar),
"rows": table.num_rows,
"expected_rows": expected["rows"],
"unique_keys": int(np.unique(keys, axis=0).shape[0]),
"positive": positive,
"expected_positive": expected["positive"],
"sha256": actual_hash,
"expected_sha256": expected["sha256"],
}
if table.num_rows != expected["rows"]:
errors.append(f"{split}: row count mismatch")
if report["unique_keys"] != expected["rows"]:
errors.append(f"{split}: duplicate advantage keys")
if positive != expected["positive"]:
errors.append(f"{split}: positive count mismatch")
if actual_hash != expected["sha256"]:
errors.append(f"{split}: canonical sidecar sha256 mismatch")
return report
def _check_manifest(errors: list[str]) -> dict[str, Any]:
if not ADVANTAGE_MANIFEST.is_file():
errors.append(f"missing advantage manifest: {ADVANTAGE_MANIFEST}")
return {"path": str(ADVANTAGE_MANIFEST), "exists": False}
manifest = json.loads(ADVANTAGE_MANIFEST.read_text(encoding="utf-8"))
if manifest.get("status") != "complete":
errors.append("advantage manifest status is not complete")
if manifest.get("tag") != ADVANTAGE_TAG:
errors.append("advantage manifest tag mismatch")
merged = manifest.get("merge", {})
if merged.get("total_rows") != sum(
item["rows"] for item in EXPECTED_SIDECARS.values()
):
errors.append("advantage manifest total_rows mismatch")
if merged.get("unified_threshold") != -0.012778498318443243:
errors.append("advantage manifest unified_threshold mismatch")
return {
"path": str(ADVANTAGE_MANIFEST),
"status": manifest.get("status"),
"tag": manifest.get("tag"),
"total_rows": merged.get("total_rows"),
"unified_threshold": merged.get("unified_threshold"),
}
def validate(
config_path: Path,
mode: str,
require_two_gpus: bool,
effective_max_steps: int | None = None,
effective_save_interval: int | None = None,
effective_micro_batch_size: int | None = None,
effective_global_batch_size: int | None = None,
effective_num_workers: int | None = None,
c4_kind: str = "matrix",
) -> dict[str, Any]:
errors: list[str] = []
config_path = config_path.resolve()
_project_path(config_path, "config", errors)
if not config_path.is_file():
errors.append(f"missing config: {config_path}")
return {"ok": False, "mode": mode, "errors": errors}
cfg = OmegaConf.to_container(OmegaConf.load(config_path), resolve=False)
actor = _as_dict(cfg.get("actor"))
model = _as_dict(actor.get("model"))
openpi = _as_dict(model.get("openpi"))
fsdp = _as_dict(actor.get("fsdp_config"))
runner = _as_dict(cfg.get("runner"))
data = _as_dict(cfg.get("data"))
cluster = _as_dict(cfg.get("cluster"))
placement = _as_dict(cluster.get("component_placement"))
if str(model.get("model_type")) != "cfg_model":
errors.append("actor.model.model_type must be cfg_model")
model_path = _project_path(model.get("model_path"), "model_path", errors)
if model_path is not None and not model_path.exists():
errors.append(f"model_path does not exist: {model_path}")
if str(fsdp.get("strategy")) != "fsdp":
errors.append("actor.fsdp_config.strategy must be fsdp")
if str(fsdp.get("sharding_strategy")) != "full_shard":
errors.append("actor.fsdp_config.sharding_strategy must be full_shard")
if bool(fsdp.get("use_orig_params", True)):
errors.append("actor.fsdp_config.use_orig_params must be false")
if not bool(fsdp.get("gradient_checkpointing", False)):
errors.append("actor.fsdp_config.gradient_checkpointing must be true")
if bool(openpi.get("train_expert_only", True)):
errors.append("CFG must use full parameters: train_expert_only must be false")
if float(openpi.get("cfgrl_guidance_scale", 0.0)) != 1.0:
errors.append("primary CFG guidance scale must be 1.0")
if float(openpi.get("unconditional_prob", -1.0)) != 0.1:
errors.append("primary CFG unconditional_prob must be 0.1")
if str(openpi.get("guidance_type")) != "positive":
errors.append("primary CFG guidance_type must be positive")
if not bool(openpi.get("positive_only_conditional", False)):
errors.append("primary CFG positive_only_conditional must be true")
if int(runner.get("max_epochs", 0)) > 0:
errors.append("runner.max_epochs must be -1 or non-positive")
if str(placement.get("actor")) != "0-1":
errors.append("cluster.component_placement.actor must be logical 0-1")
configured_micro_batch_size = int(actor.get("micro_batch_size", 0))
configured_global_batch_size = int(actor.get("global_batch_size", 0))
configured_num_workers = int(data.get("num_workers", -1))
micro_batch_size = (
configured_micro_batch_size
if effective_micro_batch_size is None
else int(effective_micro_batch_size)
)
global_batch_size = (
configured_global_batch_size
if effective_global_batch_size is None
else int(effective_global_batch_size)
)
num_workers = (
configured_num_workers
if effective_num_workers is None
else int(effective_num_workers)
)
if global_batch_size <= 0 or micro_batch_size <= 0:
errors.append("micro/global batch sizes must be positive")
elif global_batch_size % (micro_batch_size * 2) != 0:
errors.append("global_batch_size must divide micro_batch_size * world_size(2)")
if num_workers < 0:
errors.append("data.num_workers must be non-negative")
if str(data.get("advantage_tag")) != ADVANTAGE_TAG:
errors.append("data.advantage_tag mismatch")
if data.get("balance_dataset_weights") is not True:
errors.append("data.balance_dataset_weights must remain true")
if bool(_as_dict(cfg.get("video")).get("enabled", False)):
errors.append("video must remain disabled for training preflight")
if bool(_as_dict(cfg.get("debug")).get("record_cuda_peak", False)) is not True:
errors.append("debug.record_cuda_peak must be true for C2/C3 evidence")
train_paths = data.get("train_data_paths", [])
if not isinstance(train_paths, (list, tuple)) or len(train_paths) != 2:
errors.append("exactly two train_data_paths (SFT and rollout) are required")
path_reports = []
for entry in train_paths if isinstance(train_paths, (list, tuple)) else []:
entry_dict = _as_dict(entry)
path = _project_path(entry_dict.get("dataset_path"), "dataset_path", errors)
if path is not None:
if not path.exists():
errors.append(f"dataset_path does not exist: {path}")
if "eval" in path.name.lower():
errors.append(f"held-out eval path used for training: {path}")
path_reports.append(
{
"path": str(path) if path is not None else None,
"type": entry_dict.get("type"),
"weight": entry_dict.get("weight"),
}
)
types = [item.get("type") for item in path_reports]
if types != ["sft", "rollout"]:
errors.append(f"train_data_paths types must be [sft, rollout], got {types}")
configured_max_steps = int(runner.get("max_steps", -1))
configured_save_interval = int(runner.get("save_interval", 0))
max_steps = (
configured_max_steps
if effective_max_steps is None
else int(effective_max_steps)
)
save_interval = (
configured_save_interval
if effective_save_interval is None
else int(effective_save_interval)
)
if mode == "c2":
if max_steps != 1:
errors.append("C2 runner.max_steps must be 1")
if save_interval > 0:
errors.append("C2 runner.save_interval must be <= 0")
if int(data.get("num_workers", -1)) != 0:
errors.append("C2 data.num_workers must be 0")
if mode == "c3":
if max_steps != 20:
errors.append("C3 runner.max_steps must be 20")
if save_interval != 20:
errors.append("C3 runner.save_interval must be 20")
if mode == "c3_resume":
if max_steps != 21:
errors.append("C3 resume runner.max_steps must be 21")
if save_interval > 0:
errors.append("C3 resume runner.save_interval must be <= 0")
if mode == "c4":
if max_steps < 1:
errors.append("C4 runner.max_steps must be positive")
if save_interval > 0:
errors.append("C4 runner.save_interval must be <= 0")
if c4_kind == "matrix":
if max_steps < 10:
errors.append("C4 matrix requires at least 10 total steps (2 warmup + 8 timed)")
if global_batch_size != micro_batch_size * 2:
errors.append("C4 matrix requires accumulation=1 (global = micro * world_size)")
elif c4_kind == "accumulation":
if global_batch_size != 512:
errors.append("C4 accumulation benchmark requires global_batch_size=512")
if max_steps != 1:
errors.append("C4 accumulation benchmark requires exactly one optimizer step")
else:
errors.append(f"unknown C4 benchmark kind: {c4_kind}")
if require_two_gpus:
visible = os.environ.get("CUDA_VISIBLE_DEVICES", "")
devices = [item for item in visible.split(",") if item.strip()]
if len(devices) != 2:
errors.append(
"CUDA_VISIBLE_DEVICES must contain exactly two selected physical GPUs"
)
report = {
"config": str(config_path),
"mode": mode,
"ok": not errors,
"errors": errors,
"resolved_checks": {
"model_path": str(model_path) if model_path is not None else None,
"placement": placement.get("actor"),
"sharding_strategy": fsdp.get("sharding_strategy"),
"gradient_checkpointing": fsdp.get("gradient_checkpointing"),
"micro_batch_size": micro_batch_size,
"global_batch_size": global_batch_size,
"num_workers": num_workers,
"configured_max_steps": configured_max_steps,
"effective_max_steps": max_steps,
"max_epochs": runner.get("max_epochs"),
"configured_save_interval": configured_save_interval,
"effective_save_interval": save_interval,
"advantage_tag": data.get("advantage_tag"),
},
"train_data_paths": path_reports,
"advantage_manifest": _check_manifest(errors),
"sidecars": {
split: _check_sidecar(split, errors) for split in EXPECTED_SIDECARS
},
}
report["ok"] = not errors
return report
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument(
"--config",
type=Path,
default=PROJECT_ROOT / "configs/recap/task0_cfg_recap_v1.yaml",
)
parser.add_argument(
"--mode", choices=("c1", "c2", "c3", "c3_resume", "c4", "formal"), default="c1"
)
parser.add_argument("--require-two-gpus", action="store_true")
parser.add_argument(
"--effective-max-steps",
type=int,
help="Expected runner.max_steps after launcher-only Hydra overrides.",
)
parser.add_argument(
"--effective-save-interval",
type=int,
help="Expected runner.save_interval after launcher-only Hydra overrides.",
)
parser.add_argument("--effective-micro-batch-size", type=int)
parser.add_argument("--effective-global-batch-size", type=int)
parser.add_argument("--effective-num-workers", type=int)
parser.add_argument("--c4-kind", choices=("matrix", "accumulation"), default="matrix")
args = parser.parse_args()
report = validate(
args.config,
args.mode,
args.require_two_gpus,
effective_max_steps=args.effective_max_steps,
effective_save_interval=args.effective_save_interval,
effective_micro_batch_size=args.effective_micro_batch_size,
effective_global_batch_size=args.effective_global_batch_size,
effective_num_workers=args.effective_num_workers,
c4_kind=args.c4_kind,
)
print(json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True))
return 0 if report["ok"] else 1
if __name__ == "__main__":
raise SystemExit(main())