Download scripts/cfg_model_preflight.py from myx160/rl-post-train-artifacts: direct link, hf CLI and curl.
- Browser
- Download file 9.54 kB
-
https://huggingface.co/datasets/myx160/rl-post-train-artifacts/resolve/main/scripts/cfg_model_preflight.py
- Command line
-
hf download hf://datasets/myx160/rl-post-train-artifacts/scripts/cfg_model_preflight.py
-
curl -L -o cfg_model_preflight.py https://huggingface.co/datasets/myx160/rl-post-train-artifacts/resolve/main/scripts/cfg_model_preflight.py
9.54 kB
| #!/usr/bin/env python | |
| """Single-card CFG model load/forward preflight for RLinf's π0.5 path. | |
| This is deliberately bounded to one transformed fixture batch. It does not | |
| perform an optimizer step and therefore cannot establish training viability. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import logging | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| from omegaconf import OmegaConf | |
| from torch.utils.data import DataLoader | |
| import lerobot.common.datasets.lerobot_dataset as lerobot_dataset | |
| import openpi.training.data_loader as openpi_data_loader | |
| import openpi.transforms as transforms | |
| from rlinf.data.datasets.recap.cfg_model import ( | |
| AdvantagePreservingDataset, | |
| TokenizePromptWithGuidance, | |
| ) | |
| from rlinf.data.datasets.recap.utils import cast_image_features | |
| from rlinf.data.lerobot_paths import resolve_lerobot_dataset_root | |
| from rlinf.models.embodiment.openpi.dataconfig import get_openpi_config | |
| class _LookupLimitedDataset: | |
| def __init__(self, delegate, count: int): | |
| self._delegate = delegate | |
| self.hf_dataset = delegate.hf_dataset.select(range(count)) | |
| def __len__(self): | |
| return len(self.hf_dataset) | |
| def __getitem__(self, index): | |
| return self._delegate[index] | |
| def _move(value, device): | |
| if isinstance(value, torch.Tensor): | |
| return value.to(device, non_blocking=True) | |
| if isinstance(value, dict): | |
| return {key: _move(item, device) for key, item in value.items()} | |
| return value | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument( | |
| "--dataset", | |
| type=Path, | |
| default=Path( | |
| "/data/myx/RL_post_train/datasets/recap_value_smoke/" | |
| "libero10_task0_train" | |
| ), | |
| ) | |
| parser.add_argument( | |
| "--model", | |
| type=Path, | |
| default=Path( | |
| "/data/myx/RL_post_train/checkpoints/base/RLinf-Pi05-LIBERO-SFT" | |
| ), | |
| ) | |
| parser.add_argument("--advantage-tag", default="smoke") | |
| parser.add_argument("--max-samples", type=int, default=8) | |
| parser.add_argument("--device", default="cuda") | |
| return parser.parse_args() | |
| def _build_batch(dataset_path: Path, model_path: Path, advantage_tag: str, max_samples: int): | |
| data_path = str(dataset_path.resolve()) | |
| train_config = get_openpi_config( | |
| "pi05_libero", model_path=str(model_path.resolve()), batch_size=1, repo_id=data_path | |
| ) | |
| data_config = train_config.data.create(train_config.assets_dirs, train_config.model) | |
| dataset_root = resolve_lerobot_dataset_root(data_path) | |
| dataset_meta = lerobot_dataset.LeRobotDatasetMetadata(data_path, root=dataset_root) | |
| base_dataset = lerobot_dataset.LeRobotDataset( | |
| data_path, | |
| root=dataset_root, | |
| delta_timestamps={ | |
| key: [t / dataset_meta.fps for t in range(train_config.model.action_horizon)] | |
| for key in data_config.action_sequence_keys | |
| }, | |
| ) | |
| base_dataset.hf_dataset = cast_image_features(base_dataset.hf_dataset) | |
| base_dataset = _LookupLimitedDataset( | |
| base_dataset, min(max_samples, len(base_dataset.hf_dataset)) | |
| ) | |
| if data_config.prompt_from_task: | |
| base_dataset = openpi_data_loader.TransformedDataset( | |
| base_dataset, | |
| [transforms.PromptFromLeRobotTask(dataset_meta.tasks)], | |
| ) | |
| tokenizer = None | |
| for transform in data_config.model_transforms.inputs: | |
| if hasattr(transform, "tokenizer"): | |
| tokenizer = transform.tokenizer | |
| break | |
| if tokenizer is None: | |
| raise RuntimeError("Could not find tokenizer in pi05_libero transforms") | |
| model_transforms = [] | |
| for transform in data_config.model_transforms.inputs: | |
| if type(transform).__name__ == "TokenizePrompt": | |
| model_transforms.append( | |
| TokenizePromptWithGuidance( | |
| tokenizer=tokenizer, | |
| discrete_state_input=getattr(transform, "discrete_state_input", False), | |
| ) | |
| ) | |
| else: | |
| model_transforms.append(transform) | |
| transformed_dataset = openpi_data_loader.TransformedDataset( | |
| base_dataset, | |
| [ | |
| *data_config.repack_transforms.inputs, | |
| *data_config.data_transforms.inputs, | |
| transforms.Normalize( | |
| data_config.norm_stats, use_quantiles=data_config.use_quantile_norm | |
| ), | |
| *model_transforms, | |
| ], | |
| ) | |
| adv_path = dataset_path / "meta" / f"advantages_{advantage_tag}.parquet" | |
| adv_df = __import__("pandas").read_parquet(adv_path) | |
| lookup = dict( | |
| zip( | |
| zip(adv_df["episode_index"].astype(int), adv_df["frame_index"].astype(int)), | |
| adv_df["advantage"].astype(bool), | |
| ) | |
| ) | |
| final_dataset = AdvantagePreservingDataset( | |
| base_dataset=base_dataset, | |
| transformed_dataset=transformed_dataset, | |
| advantages_lookup=lookup, | |
| ) | |
| batch = next( | |
| iter( | |
| DataLoader( | |
| final_dataset, | |
| batch_size=1, | |
| shuffle=False, | |
| num_workers=0, | |
| drop_last=True, | |
| ) | |
| ) | |
| ) | |
| return train_config, batch | |
| def main() -> int: | |
| args = parse_args() | |
| logging.basicConfig(level=logging.INFO) | |
| if not torch.cuda.is_available() and args.device.startswith("cuda"): | |
| raise RuntimeError("CUDA is required for CFG model preflight") | |
| device = torch.device(args.device) | |
| train_config, batch = _build_batch( | |
| args.dataset, args.model, args.advantage_tag, args.max_samples | |
| ) | |
| # The parent PI0Pytorch constructor compiles sampling even though this | |
| # preflight calls only forward. Eager mode keeps the test deterministic | |
| # and avoids an unbounded compile warm-up. | |
| original_compile = torch.compile | |
| torch.compile = lambda fn, *unused_args, **unused_kwargs: fn # type: ignore[assignment] | |
| try: | |
| from rlinf.models import get_model | |
| cfg = OmegaConf.create( | |
| { | |
| "model_type": "cfg_model", | |
| "model_path": str(args.model.resolve()), | |
| "precision": None, | |
| "load_to_device": False, | |
| "is_lora": False, | |
| "lora_rank": 32, | |
| "num_action_chunks": 10, | |
| "action_dim": 7, | |
| "use_proprio": True, | |
| "num_steps": 5, | |
| "add_value_head": False, | |
| "openpi": { | |
| "config_name": "pi05_libero", | |
| "num_images_in_input": 2, | |
| "noise_level": 0.5, | |
| "action_chunk": 10, | |
| "num_steps": 5, | |
| "train_expert_only": False, | |
| "action_env_dim": 7, | |
| "noise_method": "flow_sde", | |
| "add_value_head": False, | |
| "value_after_vlm": False, | |
| "value_vlm_mode": "mean_token", | |
| "detach_critic_input": None, | |
| "cfgrl_guidance_scale": 1.0, | |
| "unconditional_prob": 0.1, | |
| "guidance_type": "positive", | |
| "positive_only_conditional": True, | |
| }, | |
| } | |
| ) | |
| print("config=", json.dumps(OmegaConf.to_container(cfg, resolve=True), sort_keys=True)) | |
| if device.type == "cuda": | |
| torch.cuda.reset_peak_memory_stats(device) | |
| model = get_model(cfg) | |
| finally: | |
| torch.compile = original_compile | |
| if model is None: | |
| raise RuntimeError("RLinf cfg_model registry returned None") | |
| total_params = sum(parameter.numel() for parameter in model.parameters()) | |
| trainable_params = sum( | |
| parameter.numel() for parameter in model.parameters() if parameter.requires_grad | |
| ) | |
| model = model.to(device).eval() | |
| batch = _move(batch, device) | |
| from rlinf.models.embodiment.openpi_cfg.openpi_cfg_action_model import Observation | |
| observation = Observation.from_dict(batch) | |
| actions = batch["actions"].to(device=device, dtype=torch.float32) | |
| advantage = batch["advantage"].to(device=device, dtype=torch.bool) | |
| time = torch.full((actions.shape[0],), 0.5, dtype=torch.float32, device=device) | |
| noise = torch.zeros_like(actions, dtype=torch.float32, device=device) | |
| with torch.inference_mode(): | |
| loss, metrics = model( | |
| data={"observation": observation, "actions": actions, "advantage": advantage}, | |
| time=time, | |
| noise=noise, | |
| ) | |
| if not torch.isfinite(loss).all(): | |
| raise RuntimeError(f"non-finite CFG loss: {loss}") | |
| print( | |
| "CFG_MODEL_PREFLIGHT_PASS", | |
| json.dumps( | |
| { | |
| "total_params": total_params, | |
| "trainable_params": trainable_params, | |
| "loss": float(loss.detach().float().cpu()), | |
| "actions_shape": list(actions.shape), | |
| "advantage_shape": list(advantage.shape), | |
| "metrics": {key: float(np.mean(value)) for key, value in metrics.items()}, | |
| "cuda_peak_allocated": None | |
| if device.type != "cuda" | |
| else torch.cuda.max_memory_allocated(device), | |
| "cuda_peak_reserved": None | |
| if device.type != "cuda" | |
| else torch.cuda.max_memory_reserved(device), | |
| }, | |
| sort_keys=True, | |
| ), | |
| ) | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |