Download scripts/serve_eval_policy.py from ar-mine/e5-c3-code: direct link, hf CLI and curl.
- Browser
- Download file 9.43 kB
-
https://huggingface.co/datasets/ar-mine/e5-c3-code/resolve/main/scripts/serve_eval_policy.py
- Command line
-
hf download hf://datasets/ar-mine/e5-c3-code/scripts/serve_eval_policy.py
-
curl -L -o serve_eval_policy.py https://huggingface.co/datasets/ar-mine/e5-c3-code/resolve/main/scripts/serve_eval_policy.py
9.43 kB
| #!/usr/bin/env python3 | |
| """Official policy inference, strict streaming load, explicit evaluation precision.""" | |
| import argparse | |
| from collections import Counter | |
| import hashlib | |
| import json | |
| import os | |
| from pathlib import Path | |
| import sys | |
| import time | |
| from eval_diagnostics import emit_startup, record_startup_failure | |
| from eval_model_registry import MODEL_NAMES, verify_checkpoint | |
| ROOT = Path(__file__).resolve().parents[1] | |
| sys.path.insert(0, str(ROOT)) | |
| def main(): | |
| p = argparse.ArgumentParser() | |
| p.add_argument('--model', choices=MODEL_NAMES, required=True) | |
| p.add_argument('--precision', choices=['bf16', 'fp32'], required=True) | |
| p.add_argument('--output', type=Path, required=True) | |
| p.add_argument('--port', type=int, default=9340) | |
| args = p.parse_args() | |
| try: | |
| emit_startup(args.output, 'python_entry', role='policy', model=args.model, | |
| precision=args.precision) | |
| serve_policy(args) | |
| except BaseException as error: | |
| record_startup_failure(args.output, error) | |
| raise | |
| def serve_policy(args): | |
| args.output.mkdir(parents=True, exist_ok=True) | |
| checkpoint_metadata = {} | |
| if args.model == 'e5': | |
| checkpoint, norm, checkpoint_metadata = verify_checkpoint(ROOT) | |
| (args.output / 'checkpoint_verified.json').write_text( | |
| json.dumps(checkpoint_metadata, indent=2) + '\n') | |
| upstream = ROOT / 'third_party/lingbot-vla-v2' | |
| os.environ['QWEN3VL_PATH'] = str(ROOT / 'checkpoints/dependencies/Qwen3-VL-4B-Instruct') | |
| os.environ['HF_HUB_OFFLINE'] = '1' | |
| os.environ['TOKENIZERS_PARALLELISM'] = 'false' | |
| emit_startup(args.output, 'torch_import_started') | |
| import torch | |
| emit_startup(args.output, 'torch_import_complete') | |
| emit_startup(args.output, 'policy_imports_started') | |
| from src.phase4_policy import load_base_policy, streaming_server_class | |
| emit_startup(args.output, 'policy_imports_complete') | |
| torch.set_num_threads(8) | |
| emit_startup(args.output, 'policy_loading', model=args.model, precision=args.precision) | |
| started = time.monotonic() | |
| if args.model == 'base': | |
| norm = ROOT / 'manifests/norm_stats/robotwin_clean_train_s7.json' | |
| policy = load_base_policy(ROOT / 'checkpoints/base/lingbot-vla-v2-6b', | |
| Path(os.environ['QWEN3VL_PATH']), norm, args.output / 'runtime', | |
| use_bf16=args.precision == 'bf16', use_compile=False, use_length=50, chunk_ret=True) | |
| elif args.model == 'robotwin': | |
| # Keep the released post-training config, including its architecture. | |
| # No train-only normalization substitution for this released checkpoint. | |
| norm = upstream / 'assets/norm_stats/robotwin.json' | |
| checkpoint = ROOT / 'checkpoints/official/lingbot-vla-v2-6b-robotwin/checkpoints/global_step_50000/hf_ckpt' | |
| cls = streaming_server_class(upstream) | |
| policy = cls(path_to_pi_model=str(checkpoint), robot_norm_path=str(norm), | |
| use_bf16=args.precision == 'bf16', use_fp32=args.precision == 'fp32', | |
| use_compile=False, use_length=50, chunk_ret=True) | |
| policy.reset('robotwin') | |
| elif args.model == 'e5': | |
| cls = streaming_server_class(upstream) | |
| policy = cls(path_to_pi_model=str(checkpoint), robot_norm_path=str(norm), | |
| use_bf16=args.precision == 'bf16', use_fp32=args.precision == 'fp32', | |
| use_compile=False, use_length=50, chunk_ret=True) | |
| policy.reset('robotwin') | |
| elif args.model == 'lora8': | |
| if args.precision != 'fp32': | |
| raise ValueError('The validated LoRA profile requires FP32 inference') | |
| from src.lora_eval_policy import load_lora_policy | |
| from eval_model_registry import validate_lora_identity | |
| policy, norm, checkpoint_metadata = load_lora_policy(ROOT, args.output) | |
| validate_lora_identity(checkpoint_metadata, ROOT) | |
| else: | |
| raise ValueError('Unknown model: ' + args.model) | |
| # Upstream constructor sets 'high'. Apply the frozen strict-FP32 protocol AFTER loading. | |
| torch.set_float32_matmul_precision('highest') | |
| torch.backends.cuda.matmul.allow_tf32 = False | |
| torch.backends.cudnn.allow_tf32 = False | |
| expected = torch.bfloat16 if args.precision == 'bf16' else torch.float32 | |
| dtypes = Counter(str(x.dtype) for x in policy.vla.parameters()) | |
| if any(x.dtype != expected for x in policy.vla.parameters()): | |
| raise RuntimeError(f'Unexpected parameter dtype: {dtypes}') | |
| original_infer = policy.infer | |
| def controlled_infer(observation): | |
| # A stable per-episode RNG prevents order/retries/warmup from changing actions. | |
| if observation.get('reset'): | |
| from deploy.lingbot_vla_v2_policy import set_seed_everywhere | |
| set_seed_everywhere(int(observation.get('policy_seed', 42))) | |
| with torch.inference_mode(), torch.autocast('cuda', enabled=False): | |
| return original_infer(observation) | |
| policy.infer = controlled_infer | |
| torch.cuda.synchronize() | |
| initialization_seconds = time.monotonic()-started | |
| emit_startup(args.output, 'policy_loaded', initialization_seconds=initialization_seconds) | |
| # Warm inference before starting any simulator. This avoids retaining an | |
| # extra rendered scene just for warmup on a memory-constrained GPU. | |
| emit_startup(args.output, 'warmup_imports_started') | |
| import cv2 | |
| import h5py | |
| import numpy as np | |
| emit_startup(args.output, 'warmup_started') | |
| warm_started = time.monotonic() | |
| with h5py.File(ROOT/'data/raw/adjust_bottle/aloha-agilex_clean_50/data/episode0.hdf5', 'r') as f: | |
| warm = {'task': 'Adjust the bottle.'} | |
| for key, raw in [('cam_high','head_camera'),('cam_left_wrist','left_camera'),('cam_right_wrist','right_camera')]: | |
| encoded = np.frombuffer(f[f'observation/{raw}/rgb'][0], dtype=np.uint8) | |
| warm[f'observation.images.{key}'] = cv2.resize(cv2.imdecode(encoded, cv2.IMREAD_COLOR), (320,240)) | |
| warm['observation.state'] = np.concatenate([np.asarray(f[f'joint_action/{key}'][0]).reshape(-1) | |
| for key in ['left_arm','left_gripper','right_arm','right_gripper']]).astype(np.float32) | |
| if args.model == 'e5': | |
| from e5_rollout_history import empty_history | |
| warm.update(empty_history()) | |
| for _ in range(3): | |
| value = policy.infer(warm)['action'] | |
| assert value.shape == (50,14) and np.isfinite(value).all() | |
| torch.cuda.synchronize() | |
| torch.cuda.empty_cache() | |
| warm_seconds = time.monotonic()-warm_started | |
| emit_startup(args.output, 'warmup_complete', warmup_seconds=warm_seconds) | |
| metadata = {'model': args.model, 'precision': args.precision, 'compile': False, | |
| 'tf32': False, 'matmul_precision': torch.get_float32_matmul_precision(), | |
| 'autocast': False, 'parameter_dtypes': dict(dtypes), | |
| 'parameters': policy.loaded_parameter_count, 'tensors': policy.loaded_tensor_count, | |
| 'initialization_seconds': initialization_seconds, 'warmup_seconds': warm_seconds, | |
| 'warmup': '3 offline clean-observation calls before simulator startup; RNG reset at each evaluated episode', | |
| 'norm_path': str(norm), 'norm_sha256': hashlib.sha256(norm.read_bytes()).hexdigest(), | |
| 'attention_implementation': policy.config.attention_implementation, | |
| 'attn_implementation': getattr(policy.config, 'attn_implementation', None), | |
| 'vit_attn_implementation': getattr(policy.config, 'vit_attn_implementation', None), | |
| 'use_length': 50, 'chunk_ret': True, 'denoising_steps': policy.config.num_steps, | |
| 'vision_attention_precision_note': 'Official FA2 vision patch internally casts FP32 Q/K/V to BF16, then restores output dtype; FP32 here denotes official FP32 parameter/main-path mode, not all operations IEEE FP32.'} | |
| if args.model == 'e5': | |
| assert policy.config.action_history_mode == 'summary' | |
| assert (policy.config.action_history_length, policy.config.action_history_mlp_hidden_size) == (8,1024) | |
| assert policy.config.visual_history_mode == 'none' | |
| assert policy.config.state_history_mode == 'tokens' | |
| assert policy.config.state_history_length == 2 and policy.config.state_history_stride == 50 | |
| metadata.update(action_history_mode='summary', action_history_length=8, action_history_mlp_hidden_size=1024, visual_history_mode='none', state_history_mode='tokens', state_history_length=2, | |
| state_history_stride=50, history_source='public_observation_state', | |
| history_normalization='action offset0 for executed actions; train current-state features for public states', | |
| history_semantics='prior public drive-target observations at policy decisions; not measured qpos') | |
| metadata.update(checkpoint_metadata) | |
| (args.output / 'server_metadata.json').write_text(json.dumps(metadata, indent=2)+'\n') | |
| print(json.dumps({'event': 'ready', **metadata}), flush=True) | |
| emit_startup(args.output, 'websocket_server_constructing', port=args.port) | |
| from deploy.websocket_policy_server import WebsocketPolicyServer | |
| server = WebsocketPolicyServer(policy, host='127.0.0.1', port=args.port, metadata=metadata) | |
| emit_startup(args.output, 'policy_ready', startup_complete=True, port=args.port) | |
| server.serve_forever() | |
| if __name__ == '__main__': | |
| main() | |