gr1-six-task-mini / tools /evaluate.py
JIAlonglong's picture
Publish GR1 six-task pilot protocol and verified-format results (part 2)
3e0cd9b verified
Raw History Blame Contribute Delete
5.49 kB
"""Generic single-GPU runner: --adapter your_module:create_policy.
Adapter factory takes no arguments; .reset() and .predict(obs) ->16 native action dicts.
Requires GR1 robocasa/robosuite dependencies and assets installed separately.
"""
import argparse,hashlib,importlib,json,random,time,traceback
from copy import deepcopy
from pathlib import Path
import numpy as np
GROUPS={'right_arm':7,'right_hand':6,'left_arm':7,'left_hand':6,'waist':3}
def dump(path,obj):path.write_text(json.dumps(obj,indent=2)+'\n')
def scene_env(root,scene):
import gymnasium as gym,robocasa,robosuite
from robocasa.utils.gym_utils import GrootRoboCasaEnv
from robosuite.environments.base import REGISTERED_ENVS
folder=root/'initial-scenes'/f'{scene["scene_id"]:03d}'
state=np.load(folder/'state.npy',allow_pickle=False)
if hashlib.sha256(state.tobytes()).hexdigest()!=scene['initial_state_sha256']:raise ValueError('Initial state checksum mismatch')
def relocate(text):
for name,module in [('robocasa',robocasa),('robosuite',robosuite)]:
text=text.replace('asset://'+name+'/',str(Path(module.__file__).parent/'models/assets')+'/')
if 'asset://' in text:raise ValueError('Unresolved asset path')
return text
metadata=json.loads(relocate((folder/'metadata.json').read_text()));xml=relocate((folder/'model.xml').read_text())
task=scene['task_name'];base=REGISTERED_ENVS[task]
class SavedScene(base):
def _load_model(self):self._ep_meta=deepcopy(metadata);return super()._load_model()
def _initialize_sim(self,xml_string=None):return super()._initialize_sim(xml_string=self.edit_model_xml(xml) if xml_string is None else xml_string)
def reset(self):
super().reset();self.sim.reset();self.sim.set_state_from_flattened(state);self.sim.forward()
for robot in self.robots:
for controller in robot.composite_controller.part_controllers.values():controller.update(force=True)
if not np.array_equal(self.sim.get_state().flatten(),state):raise ValueError('Simulator initial-state mismatch')
return self._get_observations(force_update=True)
REGISTERED_ENVS[task]=SavedScene
try:return gym.make(f'gr1_unified/{task}_GR1ArmsAndWaistFourierHands_Env',enable_render=True,seed=scene['seed'])
finally:REGISTERED_ENVS[task]=base
def main():
p=argparse.ArgumentParser();p.add_argument('--benchmark',type=Path,required=True);p.add_argument('--output',type=Path,required=True);p.add_argument('--adapter',required=True);p.add_argument('--submission',type=Path,required=True);a=p.parse_args()
import torch,imageio.v2 as imageio
# Metadata is supplied by the model author. It must declare training data and deployment.
info=json.loads(a.submission.read_text());info['protocol_sha256']=hashlib.sha256((a.benchmark/'protocol.json').read_bytes()).hexdigest()
for key in ['model','training_track','training_data','deployment','checkpoint_identity']:
if not info.get(key):raise ValueError('Missing submission field: '+key)
if info['deployment'].get('execute_steps')!=16:raise ValueError('v1 requires execute_steps=16')
a.output.mkdir(parents=True,exist_ok=False);(a.output/'videos').mkdir()
module,factory=a.adapter.split(':');policy=getattr(importlib.import_module(module),factory)()
scenes=json.loads((a.benchmark/'scenes.json').read_text());rows=[]
fixed={min([s for s in scenes if s['task_id']==t],key=lambda s:s['episode_id'])['scene_id'] for t in range(6)}
for scene in scenes:
row=dict(scene,status='running',success=False,steps=0);env=writer=None;times=[]
try:
seed=scene['seed'];random.seed(seed);np.random.seed(seed);torch.manual_seed(seed)
if torch.cuda.is_available():torch.cuda.manual_seed_all(seed)
policy.reset();env=scene_env(a.benchmark,scene);obs,_=env.reset(seed=seed)
if scene['scene_id'] in fixed:
writer=imageio.get_writer(str(a.output/'videos'/f'task-{scene["task_id"]:02d}.mp4'),fps=10,codec='libx264',macro_block_size=1)
writer.append_data(obs['video.ego_view_bg_crop_pad_res256_freq20'])
terminated=truncated=False
while row['steps']<720 and not (terminated or truncated):
current={k:v for k,v in obs.items() if k.startswith(('video.','state.','annotation.','language.'))}
tick=time.perf_counter();actions=policy.predict(current);times.append(time.perf_counter()-tick)
if len(actions)!=16:raise ValueError('Adapter must return16 native action dictionaries')
for action in actions:
for key,size in GROUPS.items():
value=np.asarray(action['action.'+key])
if value.shape!=(size,) or not np.isfinite(value).all():raise ValueError('Invalid action '+key)
obs,_,terminated,truncated,details=env.step(action);row['steps']+=1;row['success']=bool(row['success'] or details['success'])
if writer is not None and row['steps']%2==0:writer.append_data(obs['video.ego_view_bg_crop_pad_res256_freq20'])
if terminated or truncated or row['steps']>=720:break
row['status']='complete';row['mean_policy_seconds']=float(np.mean(times))
except Exception as e:row['status']='error';row['error']=str(e);traceback.print_exc()
finally:
for resource in [writer,env]:
if resource is not None:
try:resource.close()
except Exception as e:row['status']='error';row['error']=str(e)
rows.append(row);dump(a.output/'episodes.json',rows);print(scene['scene_id'],row['status'],row['success'],flush=True)
dump(a.output/'submission.json',info)
if any(row['status']!='complete' for row in rows):raise SystemExit('Incomplete evaluation; not eligible for ranking')
if __name__=='__main__':main()