Download scripts/value_model_preflight.py from myx160/rl-post-train-artifacts: direct link, hf CLI and curl.
- Browser
- Download file 11.6 kB
-
https://huggingface.co/datasets/myx160/rl-post-train-artifacts/resolve/main/scripts/value_model_preflight.py
- Command line
-
hf download hf://datasets/myx160/rl-post-train-artifacts/scripts/value_model_preflight.py
-
curl -L -o value_model_preflight.py https://huggingface.co/datasets/myx160/rl-post-train-artifacts/resolve/main/scripts/value_model_preflight.py
11.6 kB
| #!/usr/bin/env python | |
| """Run a bounded ValueCriticModel data/forward/backward/checkpoint smoke. | |
| This deliberately uses one local RECAP episode and the tiny ``gemma_1m`` value | |
| expert. It validates the wiring and memory envelope; it is not a useful value | |
| model training run and its checkpoint must not be used for a paper result. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import gc | |
| import json | |
| import logging | |
| import os | |
| from pathlib import Path | |
| os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") | |
| import torch | |
| from omegaconf import OmegaConf | |
| from rlinf.data.datasets.recap.value_model import ValueDataset | |
| from rlinf.models.embodiment.value_model import get_model | |
| from rlinf.models.embodiment.value_model.data_collator import ValueDataCollator | |
| from rlinf.models.embodiment.value_model.processing import ValueProcessor | |
| def _move(value, device): | |
| if isinstance(value, torch.Tensor): | |
| return value.to(device) | |
| if isinstance(value, dict): | |
| return {k: _move(v, device) for k, v in value.items()} | |
| return value | |
| def _grad_summary(model: torch.nn.Module) -> tuple[int, float]: | |
| count = 0 | |
| squared = 0.0 | |
| for param in model.parameters(): | |
| if param.grad is None: | |
| continue | |
| count += 1 | |
| squared += float(param.grad.detach().float().pow(2).sum().item()) | |
| return count, squared**0.5 | |
| def parse_args() -> argparse.Namespace: | |
| root = Path(os.environ.get("PROJECT_ROOT", "/data/myx/RL_post_train")) | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument( | |
| "--dataset", | |
| type=Path, | |
| default=root / "datasets/recap_value_smoke/libero10_task0_train", | |
| ) | |
| parser.add_argument( | |
| "--siglip", type=Path, default=root / "checkpoints/pretrained/siglip2-so400m-patch14-224" | |
| ) | |
| parser.add_argument( | |
| "--gemma3", type=Path, default=root / "checkpoints/pretrained/gemma-3-270m" | |
| ) | |
| parser.add_argument( | |
| "--tokenizer", | |
| type=Path, | |
| default=None, | |
| help="Tokenizer directory; defaults to --gemma3 (use SigLIP tokenizer for the random smoke fallback).", | |
| ) | |
| parser.add_argument( | |
| "--output", | |
| type=Path, | |
| default=root / "checkpoints/value/value_smoke_gemma1m", | |
| ) | |
| parser.add_argument("--critic-expert-variant", default="gemma_1m") | |
| parser.add_argument("--max-token-len", type=int, default=64) | |
| parser.add_argument("--freeze-vlm", action="store_true") | |
| parser.add_argument("--freeze-vision", action="store_true") | |
| parser.add_argument("--skip-backward", action="store_true") | |
| parser.add_argument( | |
| "--steps", | |
| type=int, | |
| default=10, | |
| help="Number of repeated steps on the same micro-batch (wiring smoke only).", | |
| ) | |
| parser.add_argument("--device", default="cuda") | |
| return parser.parse_args() | |
| def main() -> int: | |
| args = parse_args() | |
| if args.steps < 1: | |
| raise ValueError("--steps must be >= 1") | |
| logging.basicConfig(level=logging.INFO) | |
| for name, path in (("dataset", args.dataset), ("siglip", args.siglip), ("gemma3", args.gemma3)): | |
| if not path.exists(): | |
| raise FileNotFoundError(f"{name} path does not exist: {path}") | |
| if not torch.cuda.is_available() and args.device.startswith("cuda"): | |
| raise RuntimeError("CUDA is required for this preflight; torch.cuda.is_available() is false") | |
| device = torch.device(args.device) | |
| torch.manual_seed(0) | |
| if device.type == "cuda": | |
| torch.cuda.manual_seed_all(0) | |
| torch.set_float32_matmul_precision("high") | |
| dataset = ValueDataset( | |
| dataset_path=str(args.dataset), | |
| robot_type="libero", | |
| model_type="pi05", | |
| action_horizon=10, | |
| action_dim=7, | |
| return_min=-779.0, | |
| return_max=0.0, | |
| normalize_to_minus_one_zero=True, | |
| tag="formula_v1", | |
| ) | |
| processor = ValueProcessor( | |
| max_token_len=args.max_token_len, | |
| tokenizer_name_or_path=str(args.tokenizer or args.gemma3), | |
| do_augment=False, | |
| ) | |
| collator = ValueDataCollator( | |
| processor=processor, | |
| max_length=args.max_token_len, | |
| train=False, | |
| ) | |
| batch = collator([dataset[0]]) | |
| observation = _move(batch["observation"], device) | |
| target_values = _move(batch["target_values"], device) | |
| print( | |
| "batch=", | |
| json.dumps( | |
| { | |
| "images": {k: list(v.shape) for k, v in observation["images"].items()}, | |
| "image_masks": {k: list(v.shape) for k, v in observation["image_masks"].items()}, | |
| "tokens": list(observation["tokenized_prompt"].shape), | |
| "target_values": target_values.detach().cpu().tolist(), | |
| }, | |
| sort_keys=True, | |
| ), | |
| flush=True, | |
| ) | |
| cfg = OmegaConf.create( | |
| { | |
| "precision": "bf16", | |
| "critic_expert_variant": args.critic_expert_variant, | |
| "num_bins": 201, | |
| "v_min": -1.0, | |
| "v_max": 0.0, | |
| "value_dropout": 0.0, | |
| "action_dim": 7, | |
| "action_horizon": 10, | |
| "max_token_len": args.max_token_len, | |
| "siglip_path": str(args.siglip), | |
| "gemma3_path": str(args.gemma3), | |
| "freeze_vlm": bool(args.freeze_vlm), | |
| "freeze_vision_encoder": bool(args.freeze_vision), | |
| "train_expert_only": bool(args.freeze_vlm), | |
| "forward_mode": "vla", | |
| "stop_gradient_to_vlm": bool(args.freeze_vlm), | |
| } | |
| ) | |
| print( | |
| "config=", | |
| json.dumps(OmegaConf.to_container(cfg, resolve=True), sort_keys=True), | |
| flush=True, | |
| ) | |
| print("constructing model", flush=True) | |
| model = get_model(cfg) | |
| total_params = sum(p.numel() for p in model.parameters()) | |
| trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad) | |
| print( | |
| f"params total={total_params} trainable={trainable_params} " | |
| f"cpu_bytes~={sum(p.numel() * p.element_size() for p in model.parameters())}", | |
| flush=True, | |
| ) | |
| model = model.to(device) | |
| model.train(not args.skip_backward) | |
| if device.type == "cuda": | |
| torch.cuda.reset_peak_memory_stats(device) | |
| reference_prediction = None | |
| optimizer = None | |
| if not args.skip_backward: | |
| optimizer = torch.optim.AdamW( | |
| [p for p in model.parameters() if p.requires_grad], lr=1e-4 | |
| ) | |
| last_grad_count = 0 | |
| last_grad_norm = 0.0 | |
| print(f"pipeline_steps={args.steps}", flush=True) | |
| for step in range(args.steps): | |
| if optimizer is not None: | |
| optimizer.zero_grad(set_to_none=True) | |
| output = model(observation=observation, target_values=target_values) | |
| if output.loss is None or not torch.isfinite(output.loss).all(): | |
| raise RuntimeError(f"non-finite value loss at step {step}: {output.loss}") | |
| if not torch.isfinite(output.predicted_values).all(): | |
| raise RuntimeError( | |
| f"non-finite predicted values at step {step}: {output.predicted_values}" | |
| ) | |
| if optimizer is not None: | |
| output.loss.backward() | |
| last_grad_count, last_grad_norm = _grad_summary(model) | |
| if last_grad_count == 0 or not torch.isfinite(torch.tensor(last_grad_norm)): | |
| raise RuntimeError( | |
| f"no finite gradients at step {step}: " | |
| f"count={last_grad_count}, norm={last_grad_norm}" | |
| ) | |
| optimizer.step() | |
| if step in (0, args.steps - 1): | |
| print( | |
| "step_result=", | |
| json.dumps( | |
| { | |
| "step": step + 1, | |
| "loss": float(output.loss.detach().float().cpu()), | |
| "predicted_values": output.predicted_values.detach() | |
| .float() | |
| .cpu() | |
| .tolist(), | |
| "logits_shape": list(output.logits.shape), | |
| "mae": None | |
| if output.mae is None | |
| else float(output.mae.detach().float().cpu()), | |
| }, | |
| sort_keys=True, | |
| ), | |
| flush=True, | |
| ) | |
| if optimizer is not None: | |
| print( | |
| f"backward_result=grad_tensors:{last_grad_count}," | |
| f"grad_norm:{last_grad_norm:.6f}", | |
| flush=True, | |
| ) | |
| # Evaluate once after the update. The reload check below compares | |
| # against this post-update value (rather than the pre-update forward | |
| # value), making checkpoint restoration an actual numerical check. | |
| model.eval() | |
| with torch.no_grad(): | |
| reference_prediction = model( | |
| observation=observation, target_values=None | |
| ).predicted_values.detach().cpu() | |
| model.train() | |
| # Do not retain the last autograd graph while constructing the fresh model | |
| # below; keeping it alive would unnecessarily raise the reload peak. | |
| if "output" in locals(): | |
| del output | |
| args.output.mkdir(parents=True, exist_ok=True) | |
| state_dir = args.output / "model_state_dict" | |
| state_dir.mkdir(parents=True, exist_ok=True) | |
| full_weights = state_dir / "full_weights.pt" | |
| state_cpu = {k: v.detach().cpu() for k, v in model.state_dict().items()} | |
| torch.save(state_cpu, full_weights) | |
| (args.output / "config.json").write_text( | |
| json.dumps(OmegaConf.to_container(cfg, resolve=True), indent=2, sort_keys=True) + "\n" | |
| ) | |
| print(f"saved_checkpoint={full_weights} bytes={full_weights.stat().st_size}", flush=True) | |
| # A fresh model verifies that the exact checkpoint format can be loaded. | |
| if device.type == "cuda": | |
| model = model.cpu() | |
| torch.cuda.empty_cache() | |
| if not args.skip_backward: | |
| del optimizer | |
| del model | |
| gc.collect() | |
| if device.type == "cuda": | |
| torch.cuda.empty_cache() | |
| print("reloading model", flush=True) | |
| reloaded = get_model(cfg) | |
| missing, unexpected = reloaded.load_state_dict(torch.load(full_weights, map_location="cpu", weights_only=False), strict=False) | |
| if missing or unexpected: | |
| raise RuntimeError(f"checkpoint mismatch: missing={missing}, unexpected={unexpected}") | |
| reloaded = reloaded.to(device).eval() | |
| with torch.no_grad(): | |
| reloaded_output = reloaded(observation=observation, target_values=None) | |
| if not torch.isfinite(reloaded_output.predicted_values).all(): | |
| raise RuntimeError("reloaded model produced non-finite prediction") | |
| if reference_prediction is not None: | |
| reloaded_cpu = reloaded_output.predicted_values.detach().float().cpu() | |
| if not torch.allclose(reloaded_cpu, reference_prediction.float(), atol=1e-5, rtol=1e-4): | |
| raise RuntimeError( | |
| "checkpoint reload prediction differs from post-update reference: " | |
| f"reference={reference_prediction.tolist()} reload={reloaded_cpu.tolist()}" | |
| ) | |
| print( | |
| "reload_result=", | |
| json.dumps( | |
| {"predicted_values": reloaded_output.predicted_values.detach().float().cpu().tolist()}, | |
| sort_keys=True, | |
| ), | |
| flush=True, | |
| ) | |
| if device.type == "cuda": | |
| print( | |
| f"cuda_peak_allocated={torch.cuda.max_memory_allocated(device)} " | |
| f"cuda_peak_reserved={torch.cuda.max_memory_reserved(device)}", | |
| flush=True, | |
| ) | |
| print("VALUE_PREFLIGHT_PASS", flush=True) | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |