swkwon0503's picture
Update cumulative CR3A dataset: 59 baseline + 145 audited runs
73e9354 verified
Raw History Blame Contribute Delete
6.01 kB
"""Offline validation with the real LeRobotDataset loader and original numeric/video data."""
from pathlib import Path
import os,json,argparse,csv,hashlib
os.environ.update(HF_HUB_OFFLINE='1',HF_DATASETS_OFFLINE='1',HF_HUB_DISABLE_TELEMETRY='1')
import numpy as np
import pyarrow.parquet as pq
import pyarrow as pa
import cv2,av,torch
from lerobot.datasets.lerobot_dataset import LeRobotDataset
torch.set_num_threads(2)
def read(p):return json.loads(p.read_text(encoding='utf-8'))
def vectors(table,key):return np.array(table[key].to_pylist()).reshape(len(table),-1)
def main():
p=argparse.ArgumentParser();p.add_argument('--root',type=Path,required=True);p.add_argument('--only',choices=['axis_1000hz','camera_30fps']);args=p.parse_args();root=args.root.resolve();source=root/'source_package';mapping=read(root/'episode_mapping.json')
report={'status':'running','network_mode':'HF_HUB_OFFLINE=1; HF_DATASETS_OFFLINE=1','datasets':{},'uploaded':False}
reportpath=root/(args.only+'_validation.json' if args.only else 'loading_validation.json')
for name,fps,repo in [('axis_1000hz',1000,'movensys/wmx-r2-command-grounded-cr3a-axis-v0'),('camera_30fps',30,'movensys/wmx-r2-command-grounded-cr3a-camera-v0')]:
if args.only and args.only!=name:continue
ds=LeRobotDataset(repo_id=repo,root=root/name,video_backend='pyav')
assert ds.meta.info['codebase_version']=='v3.0';assert ds.num_episodes==len(mapping)==204;assert ds.fps==fps
tables=pa.concat_tables([pq.read_table(f) for f in sorted((root/name/'data').rglob('*.parquet'))])
assert len(ds)==len(tables)
eidx=np.array(tables['episode_index']);samples=[];image_maes=[];total=0
for m in mapping:
ep=m['episode_index'];mask=eidx==ep;ind=np.flatnonzero(mask);t=tables.filter(pa.array(mask));n=len(t)
assert n==m['axis_frames' if name=='axis_1000hz' else 'camera_frames']
np.testing.assert_array_equal(np.array(t['frame_index']),np.arange(n))
np.testing.assert_allclose(np.array(t['timestamp']),np.arange(n)/fps,atol=1e-4,rtol=0)
e=m['original_label'];raw=pq.read_table(source/e['package_axis_logs'][0]['parquet'])
ri=vectors(t,'source.axis_row')[:,0];host=np.array(raw['SYSTEM_TIME'],dtype=np.int64)*100
np.testing.assert_array_equal(vectors(t,'source.cycle')[:,0],np.array(raw['CYCLE'])[ri])
np.testing.assert_array_equal(vectors(t,'source.axis_host_time_ns')[:,0],host[ri])
if name=='axis_1000hz':np.testing.assert_array_equal(ri,np.arange(len(raw)))
command=np.column_stack([np.array(raw[f'{k}{i}']) for k in ('CMDPOS','CMDVEL') for i in range(6)])
fb=np.column_stack([np.array(raw[f'{k}{i}']) for k in ('FBPOS','FBVEL') for i in range(6)])
np.testing.assert_array_equal(vectors(t,'action'),command[ri].astype(np.float32))
np.testing.assert_array_equal(vectors(t,'observation.state'),fb[ri].astype(np.float32))
np.testing.assert_array_equal(vectors(t,'observation.tracking_error'),(command[ri,:6]-fb[ri,:6]).astype(np.float32))
if name=='camera_30fps':
stream=m['source_stream'];rr=list(csv.DictReader((source/stream['timestamps']).open(encoding='utf-8-sig')));rr=[r for r in rr if r.get('stream','color')=='color']
ts=np.array([int(r['host_receive_unix_ns']) for r in rr],np.int64);vi=vectors(t,'source.camera_frame')[:,0];grid=vectors(t,'source.grid_host_time_ns')[:,0]
np.testing.assert_array_equal(grid,int(host[0])+np.rint(np.arange(n)*1e9/30).astype(np.int64))
for stamps,idx in [(ts,vi),(host,ri)]:
hi=np.clip(np.searchsorted(stamps,grid),0,len(stamps)-1);lo=np.maximum(hi-1,0);expected=np.where(np.abs(grid-stamps[lo])<=np.abs(stamps[hi]-grid),lo,hi);np.testing.assert_array_equal(idx,expected)
np.testing.assert_array_equal(vectors(t,'source.camera_host_time_ns')[:,0],ts[vi])
np.testing.assert_array_equal(vectors(t,'source.camera_minus_grid_ns')[:,0],ts[vi]-grid)
np.testing.assert_array_equal(vectors(t,'source.axis_minus_grid_ns')[:,0],host[ri]-grid)
for local in sorted(set([0,n//2,n-1])):
item=ds[int(ind[local])];assert item['action'].shape==(12,) and item['observation.state'].shape==(12,)
assert int(item['source.axis_host_time_ns'].item())==int(host[ri[local]])
assert item['task'];samples.append(int(ind[local]))
if name=='camera_30fps':
rgb=item['observation.images.wrist'];assert rgb.shape==(3,480,640);assert torch.isfinite(rgb).all();assert rgb.min()>=0 and rgb.max()<=1
cap=cv2.VideoCapture(str(source/m['source_stream']['video']));cap.set(cv2.CAP_PROP_POS_FRAMES,int(vi[local]));ok,bgr=cap.read();cap.release();assert ok
original=cv2.cvtColor(bgr,cv2.COLOR_BGR2RGB).astype(np.float32)/255
mae=float(np.abs(rgb.numpy().transpose(1,2,0)-original).mean());image_maes.append(mae);assert mae<.08,(e['episode_id'],local,mae)
total+=n
print(name,ep+1,'loaded+compared',n,flush=True)
batch=next(iter(torch.utils.data.DataLoader(torch.utils.data.Subset(ds,[samples[0],samples[len(samples)//2],samples[-1]]),batch_size=3,num_workers=0)))
assert batch['action'].shape==(3,12)
decoded=0
if name=='camera_30fps':
assert batch['observation.images.wrist'].shape==(3,3,480,640)
for f in (root/name/'videos').rglob('*.mp4'):
with av.open(str(f)) as container:
for frame in container.decode(video=0):assert frame.width==640 and frame.height==480;decoded+=1
assert decoded==total,(decoded,total)
report['datasets'][name]={'episodes':ds.num_episodes,'frames':len(ds),'all_numeric_rows_compared_to_source':total,'loader_samples_first_middle_last_per_episode':len(samples),'dataloader_batch_shape':list(batch['action'].shape),'decoded_video_frames':decoded,'sampled_rgb_source_mae_max':max(image_maes) if image_maes else None,'fps':fps,'codebase_version':ds.meta.info['codebase_version']}
reportpath.write_text(json.dumps(report,indent=2),encoding='utf-8')
report['status']='passed';reportpath.write_text(json.dumps(report,indent=2),encoding='utf-8');print(json.dumps(report,indent=2))
if __name__=='__main__':main()