File size: 9,428 Bytes
36b714d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 | #!/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()
|