diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..6a1b0fdbd5e7cecb77b9d047eb1827577be4ba0f --- /dev/null +++ b/.dockerignore @@ -0,0 +1,15 @@ +.git +__pycache__ +*.pyc +*.pyo +*.pyd +.cache +.venv +venv +.env +.DS_Store +data + +# Exclude vendored LFS pointer assets not needed by the viewer. +cosmos-framework/inputs/omni/01_hammer_nail.png +cosmos-framework/assets/cosmos-logo-thumbnail.png diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..f844a4d4bbbaf7733c8d0b66962e833baab69a40 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,20 @@ +assets/examples/bridge_lerobot_v3/meta/episodes/chunk-000/file-000.parquet filter=lfs diff=lfs merge=lfs -text +assets/examples/bridge_lerobot_v3/videos/observation.images.image_0/chunk-000/file-000.mp4 filter=lfs diff=lfs merge=lfs -text +assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1/meta/episodes/chunk-000/file-000.parquet filter=lfs diff=lfs merge=lfs -text +assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/data/chunk-000/file-000.parquet filter=lfs diff=lfs merge=lfs -text +assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/meta/episodes/chunk-000/file-000.parquet filter=lfs diff=lfs merge=lfs -text +assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/videos/observation.images.camera_front/chunk-000/file-000.mp4 filter=lfs diff=lfs merge=lfs -text +assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/videos/observation.images.camera_left/chunk-000/file-000.mp4 filter=lfs diff=lfs merge=lfs -text +assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/videos/observation.images.camera_right/chunk-000/file-000.mp4 filter=lfs diff=lfs merge=lfs -text +assets/examples/droid_plus_lerobot_640x360_20260412/success/data/chunk-000/file-000.parquet filter=lfs diff=lfs merge=lfs -text +assets/examples/droid_plus_lerobot_640x360_20260412/success/meta/episodes/chunk-000/file-000.parquet filter=lfs diff=lfs merge=lfs -text +assets/examples/droid_plus_lerobot_640x360_20260412/success/videos/observation.image.exterior_image_1_left/chunk-000/file-000.mp4 filter=lfs diff=lfs merge=lfs -text +assets/examples/droid_plus_lerobot_640x360_20260412/success/videos/observation.image.exterior_image_2_left/chunk-000/file-000.mp4 filter=lfs diff=lfs merge=lfs -text +assets/examples/droid_plus_lerobot_640x360_20260412/success/videos/observation.image.wrist_image_left/chunk-000/file-000.mp4 filter=lfs diff=lfs merge=lfs -text +assets/examples/fractal20220817_data/videos/observation.images.image/chunk-000/file-000.mp4 filter=lfs diff=lfs merge=lfs -text +assets/examples/av_v2_03292026_wdinfo/data/00000000.tar filter=lfs diff=lfs merge=lfs -text +assets/examples/fastumi/fastumi_single_arm/pour_coke/videos/observation.image.right_main_camera_rgb/chunk-000/file-000.mp4 filter=lfs diff=lfs merge=lfs -text +assets/examples/AgiBotWorld-GEAR_20260208/agibot-offshelf/20251016_500h/gripper/task_1018/data/chunk-000/file_000.parquet filter=lfs diff=lfs merge=lfs -text +assets/examples/AgiBotWorld-GEAR_20260208/agibot-offshelf/20251016_500h/gripper/task_1018/videos/observation.images.hand_left/chunk-000/file-000.mp4 filter=lfs diff=lfs merge=lfs -text +assets/examples/AgiBotWorld-GEAR_20260208/agibot-offshelf/20251016_500h/gripper/task_1018/videos/observation.images.hand_right/chunk-000/file-000.mp4 filter=lfs diff=lfs merge=lfs -text +assets/examples/AgiBotWorld-GEAR_20260208/agibot-offshelf/20251016_500h/gripper/task_1018/videos/observation.images.top_head/chunk-000/file-000.mp4 filter=lfs diff=lfs merge=lfs -text diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a8bfb9b6d032eb1769ecf8112e48e5f5fd1130a1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +# Local reference copies / scratch files. +_datasets/ + +# Python build/cache artifacts. +__pycache__/ +*.py[cod] +*$py.class diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..870294c2a5f73ed538f302ae3bc4273f840996c9 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,28 @@ +FROM python:3.11-slim + +ENV PYTHONUNBUFFERED=1 \ + PORT=7860 \ + COSMOS_VIEWER_SHARE=0 \ + PIP_NO_CACHE_DIR=1 \ + HF_HUB_DISABLE_XET=1 + +RUN apt-get update && apt-get install -y --no-install-recommends \ + git curl ca-certificates ffmpeg build-essential linux-libc-dev \ + libgl1 libglib2.0-0 libegl1 libosmesa6 libgomp1 + +WORKDIR /app + +COPY cosmos-framework /app/cosmos-framework +COPY assets /app/assets +COPY start.sh /app/start.sh + +RUN python -m pip install --upgrade pip uv \ + && uv pip install --system torch==2.6.0 torchvision==0.21.0 --index-url https://download.pytorch.org/whl/cpu \ + && uv pip install --system \ + accelerate av cattrs diffusers einops hydra-core imageio imageio-ffmpeg loguru msgpack \ + obstore omegaconf pydantic requests scipy termcolor 'transformers>=4.57.1,<5.0.0' tyro websockets \ + boto3 pyyaml lerobot==0.4.4 pandas pyarrow 'datasets>=2.19.0' \ + viser mujoco pin trimesh opencv-python-headless huggingface_hub hf_transfer iopath \ + && uv pip install --system torchcodec==0.2.* --index-url https://download.pytorch.org/whl/cpu + +CMD ["bash", "/app/start.sh"] diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b4613390f0710fc2340dcce91105490e63474ff1 --- /dev/null +++ b/README.md @@ -0,0 +1,53 @@ +--- +title: Cosmos3 Action Viewer +emoji: 🤖 +colorFrom: blue +colorTo: green +sdk: docker +app_port: 7860 +pinned: false +license: other +--- + +# Cosmos3 Action Viewer + +Minimal Docker Space for a standalone Cosmos3 action data viewer. + +Packaged local demo data under `assets/examples/`: + +- Bridge: 2 local episodes +- Fractal: 1 local episode +- DROID: 1 local success episode +- RoboMIND Franka: 1 local episode +- RoboMIND Franka dual: 1 local episode +- AV: 1 local wdinfo/tar shard with 10 samples +- UMI/FastUMI: 1 local episode + +Runtime behavior: no HF dataset download or video streaming by default. The app runs the existing `viser` URDF/action viewer on the Hugging Face Spaces port. + +Environment overrides are still supported for larger mounted datasets: + +- `BRIDGE_LEROBOT_ROOT` +- `FRACTAL_ROOT` +- `DROID_ROOT` +- `ROBOMIND_FRANKA_ROOT` +- `ROBOMIND_FRANKA_DUAL_ROOT` +- `AV_ROOT` +- `UMI_ROOT` + +## Local launch + +Use the repository Dockerfile for local development/testing. + +From the repository root: + +```bash +docker build -t cosmos3-action-viewer . +docker run --rm -p 8020:7860 cosmos3-action-viewer +# or with publicly shared url +docker run --rm -p 8021:7860 -e COSMOS_VIEWER_SHARE=1 cosmos3-action-viewer +``` + +Then open or the publicly shared URL from the logs. + +Rebuild the image after code changes. diff --git a/assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1/data/chunk-000/file-000.parquet b/assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1/data/chunk-000/file-000.parquet new file mode 100644 index 0000000000000000000000000000000000000000..f326e41d69bdb2d346df45446c24dee98fb34b8c Binary files /dev/null and b/assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1/data/chunk-000/file-000.parquet differ diff --git a/assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1/meta/episodes/chunk-000/file-000.parquet b/assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1/meta/episodes/chunk-000/file-000.parquet new file mode 100644 index 0000000000000000000000000000000000000000..76040781e80c0821794074b9bcfcb601e1d24b69 --- /dev/null +++ b/assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1/meta/episodes/chunk-000/file-000.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fdbf9cef8d1a5d04e90459c24f3b2092c598ebf3459fc90740357b340bb08faf +size 123148 diff --git a/assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1/meta/info.json b/assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1/meta/info.json new file mode 100644 index 0000000000000000000000000000000000000000..2cd0c1894397773980643a7406b0e59f124eaf1c --- /dev/null +++ b/assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1/meta/info.json @@ -0,0 +1,174 @@ +{ + "codebase_version": "v3.0", + "robot_type": "franka_3rgb", + "total_episodes": 1, + "total_frames": 120, + "total_tasks": 1, + "chunks_size": 1000, + "data_files_size_in_mb": 100, + "video_files_size_in_mb": 200, + "fps": 30, + "splits": { + "train": "0:1" + }, + "data_path": "data/chunk-{chunk_index:03d}/file-{file_index:03d}.parquet", + "video_path": "videos/{video_key}/chunk-{chunk_index:03d}/file-{file_index:03d}.mp4", + "features": { + "observation.images.camera_top": { + "dtype": "video", + "shape": [ + 720, + 1280, + 3 + ], + "names": [ + "height", + "width", + "rgb" + ], + "info": { + "video.height": 720, + "video.width": 1280, + "video.codec": "av1", + "video.pix_fmt": "yuv420p", + "video.is_depth_map": false, + "video.fps": 30, + "video.channels": 3, + "has_audio": false + } + }, + "observation.images.camera_left": { + "dtype": "video", + "shape": [ + 480, + 640, + 3 + ], + "names": [ + "height", + "width", + "rgb" + ], + "info": { + "video.height": 480, + "video.width": 640, + "video.codec": "av1", + "video.pix_fmt": "yuv420p", + "video.is_depth_map": false, + "video.fps": 30, + "video.channels": 3, + "has_audio": false + } + }, + "observation.images.camera_right": { + "dtype": "video", + "shape": [ + 480, + 640, + 3 + ], + "names": [ + "height", + "width", + "rgb" + ], + "info": { + "video.height": 480, + "video.width": 640, + "video.codec": "av1", + "video.pix_fmt": "yuv420p", + "video.is_depth_map": false, + "video.fps": 30, + "video.channels": 3, + "has_audio": false + } + }, + "observation.states.end_effector": { + "dtype": "float32", + "shape": [ + 6 + ], + "names": { + "motors": [ + "x", + "y", + "z", + "r", + "p", + "y" + ] + } + }, + "observation.states.joint_position": { + "dtype": "float32", + "shape": [ + 8 + ], + "names": { + "motors": [ + "joint_0", + "joint_1", + "joint_2", + "joint_3", + "joint_4", + "joint_5", + "joint_6", + "gripper" + ] + } + }, + "actions.joint_position": { + "dtype": "float32", + "shape": [ + 8 + ], + "names": { + "motors": [ + "joint_0", + "joint_1", + "joint_2", + "joint_3", + "joint_4", + "joint_5", + "joint_6", + "gripper" + ] + } + }, + "timestamp": { + "dtype": "float32", + "shape": [ + 1 + ], + "names": null + }, + "frame_index": { + "dtype": "int64", + "shape": [ + 1 + ], + "names": null + }, + "episode_index": { + "dtype": "int64", + "shape": [ + 1 + ], + "names": null + }, + "index": { + "dtype": "int64", + "shape": [ + 1 + ], + "names": null + }, + "task_index": { + "dtype": "int64", + "shape": [ + 1 + ], + "names": null + } + } +} diff --git a/assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1/meta/stats.json b/assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1/meta/stats.json new file mode 100644 index 0000000000000000000000000000000000000000..6ddb9b8a88e3910f8ebd5f76fc2111cbf002c7e8 --- /dev/null +++ b/assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1/meta/stats.json @@ -0,0 +1,903 @@ +{ + "timestamp": { + "min": [ + 0.0 + ], + "max": [ + 10.933333333333334 + ], + "mean": [ + 1.9684300844334923 + ], + "std": [ + 1.3673979573511015 + ], + "count": [ + 31662 + ], + "q01": [ + 0.02376322090207472 + ], + "q10": [ + 0.37904119386356827 + ], + "q50": [ + 1.959688231107258 + ], + "q90": [ + 3.553989463285689 + ], + "q99": [ + 3.9125398910217504 + ] + }, + "observation.states.end_effector": { + "min": [ + 0.5030578374862671, + -0.39535877108573914, + 0.4033958315849304, + -3.141587972640991, + -0.870353639125824, + -1.7021530866622925 + ], + "max": [ + 0.7792795300483704, + 0.4450030028820038, + 0.6821127533912659, + 3.1415915489196777, + 0.25157487392425537, + 1.1252886056900024 + ], + "mean": [ + 0.6255840464337402, + 0.012989276388556903, + 0.5490484980667585, + 0.1625279631562389, + -0.20268731521655853, + -0.22077285899314192 + ], + "std": [ + 0.06039222410375044, + 0.1449360540909791, + 0.06623187408317564, + 2.991057969862546, + 0.20245307551388686, + 0.5210916269783522 + ], + "count": [ + 31662 + ], + "q01": [ + 0.5561097662572897, + -0.09380602512150898, + 0.4346114056532645, + -1.8705973324493732, + -0.5094947386697036, + -0.6075075655854922 + ], + "q10": [ + 0.5632028311365838, + -0.08542720523581471, + 0.4456098187752242, + -1.6207854327266906, + -0.4610935596481184, + -0.5787010975715685 + ], + "q50": [ + 0.6348575462982353, + 0.015158164848026623, + 0.5696579518852141, + 0.005318343743618634, + -0.19820279019169973, + -0.2654616249987716 + ], + "q90": [ + 0.6865314425143914, + 0.10741322351539781, + 0.6143608893539235, + 2.0985132183140247, + -0.01623157041115065, + 0.15955954879741835 + ], + "q99": [ + 0.6927857513943124, + 0.11675971906958119, + 0.6229099651133552, + 2.696355882965309, + 0.0003145221689061533, + 0.1871979781045757 + ] + }, + "index": { + "min": [ + 0 + ], + "max": [ + 31661 + ], + "mean": [ + 15830.5 + ], + "std": [ + 9140.032106982264 + ], + "count": [ + 31662 + ], + "q01": [ + 15772.159994096948 + ], + "q10": [ + 15782.81833328525 + ], + "q50": [ + 15830.23856370413 + ], + "q90": [ + 15878.066781363226 + ], + "q99": [ + 15888.823294194774 + ] + }, + "observation.images.camera_left": { + "min": [ + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ] + ], + "max": [ + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ] + ], + "mean": [ + [ + [ + 0.5053939524871568 + ] + ], + [ + [ + 0.5129378107679405 + ] + ], + [ + [ + 0.5038425321864779 + ] + ] + ], + "std": [ + [ + [ + 0.006196154475182948 + ] + ], + [ + [ + 0.006291749597368619 + ] + ], + [ + [ + 0.007139137590419621 + ] + ] + ], + "count": [ + 26766 + ], + "q01": [ + [ + [ + 0.050804214742590795 + ] + ], + [ + [ + 0.06535308523113001 + ] + ], + [ + [ + 0.05578779593795524 + ] + ] + ], + "q10": [ + [ + [ + 0.3346875522241501 + ] + ], + [ + [ + 0.3538745545006605 + ] + ], + [ + [ + 0.3279563043968654 + ] + ] + ], + "q50": [ + [ + [ + 0.5512415615575815 + ] + ], + [ + [ + 0.557746025835581 + ] + ], + [ + [ + 0.5442588739492085 + ] + ] + ], + "q90": [ + [ + [ + 0.5930081145488154 + ] + ], + [ + [ + 0.6046346760047809 + ] + ], + [ + [ + 0.6083802395861199 + ] + ] + ], + "q99": [ + [ + [ + 0.6335368100177181 + ] + ], + [ + [ + 0.6387606491834414 + ] + ], + [ + [ + 0.6516727281816006 + ] + ] + ] + }, + "actions.joint_position": { + "min": [ + -0.4739997386932373, + -0.1978835165500641, + -0.5645049214363098, + -1.863785982131958, + -0.5414947271347046, + 1.394435167312622, + -0.8218851685523987, + 0.0 + ], + "max": [ + 0.7025632262229919, + 0.6534756422042847, + 0.23316508531570435, + -1.1949712038040161, + 0.6181789040565491, + 2.988194465637207, + 1.5723140239715576, + 1.0 + ], + "mean": [ + 0.08852916841457183, + 0.20379400446678728, + -0.07347157121414831, + -1.560854356627464, + -0.027502359479121323, + 2.011894774820232, + 0.2276453738724793, + 0.6471313536858972 + ], + "std": [ + 0.18431886493226315, + 0.18677245861500938, + 0.09783784951187993, + 0.10504809264513078, + 0.09190849461431556, + 0.3786779746935214, + 0.4578454919804973, + 0.4530472127902388 + ], + "count": [ + 31662 + ], + "q01": [ + -0.059593112691433844, + -0.03240261068188407, + -0.1217730086501231, + -1.6653622219651423, + -0.10857946302997483, + 1.609264057957687, + -0.13058724798860544, + -1.000000013351432e-10 + ], + "q10": [ + -0.04501642076638965, + -0.00871990155880731, + -0.11709558777130803, + -1.6493733834129907, + -0.09368463558629822, + 1.628428367281585, + -0.10049625833210918, + 0.0002743634253506962 + ], + "q50": [ + 0.09818325634298403, + 0.21136092309578877, + -0.08057754637075476, + -1.5806816619484865, + -0.023714171368019024, + 2.0448558221656024, + 0.28801769232764407, + 0.9181340869801482 + ], + "q90": [ + 0.21040525446981903, + 0.41854284251779594, + -0.023043113030900307, + -1.4390443497453502, + 0.03691071807769244, + 2.4299963875273014, + 0.5117685732510093, + 0.9967792755991135 + ], + "q99": [ + 0.22353138137318673, + 0.45129443785420625, + -0.01353270384012705, + -1.4236844133752204, + 0.05254005867616058, + 2.4802114284864163, + 0.5369015031084761, + 0.9971542697572874 + ] + }, + "observation.images.camera_top": { + "min": [ + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ] + ], + "max": [ + [ + [ + 1.0 + ] + ], + [ + [ + 0.984313725490196 + ] + ], + [ + [ + 1.0 + ] + ] + ], + "mean": [ + [ + [ + 0.4628883239385903 + ] + ], + [ + [ + 0.4678657429689597 + ] + ], + [ + [ + 0.4591371632804239 + ] + ] + ], + "std": [ + [ + [ + 0.005320493668924655 + ] + ], + [ + [ + 0.005264511466064699 + ] + ], + [ + [ + 0.005299951762028905 + ] + ] + ], + "count": [ + 26766 + ], + "q01": [ + [ + [ + 0.048390354929310465 + ] + ], + [ + [ + 0.05576798281595686 + ] + ], + [ + [ + 0.04296608011754174 + ] + ] + ], + "q10": [ + [ + [ + 0.3990018407803951 + ] + ], + [ + [ + 0.39802162530680263 + ] + ], + [ + [ + 0.3742076209782547 + ] + ] + ], + "q50": [ + [ + [ + 0.48167112014209434 + ] + ], + [ + [ + 0.48865381487960363 + ] + ], + [ + [ + 0.481724617238358 + ] + ] + ], + "q90": [ + [ + [ + 0.5398092052009987 + ] + ], + [ + [ + 0.5407023438466012 + ] + ], + [ + [ + 0.5376467137497242 + ] + ] + ], + "q99": [ + [ + [ + 0.5786545035149396 + ] + ], + [ + [ + 0.5749881050131567 + ] + ], + [ + [ + 0.5828155228727975 + ] + ] + ] + }, + "observation.images.camera_right": { + "min": [ + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ] + ], + "max": [ + [ + [ + 0.9568627450980393 + ] + ], + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ] + ], + "mean": [ + [ + [ + 0.4753470970603862 + ] + ], + [ + [ + 0.48258902097804496 + ] + ], + [ + [ + 0.47228931382713346 + ] + ] + ], + "std": [ + [ + [ + 0.007750263540936345 + ] + ], + [ + [ + 0.007283703931002962 + ] + ], + [ + [ + 0.00728236419430919 + ] + ] + ], + "count": [ + 26766 + ], + "q01": [ + [ + [ + 0.06011670652045735 + ] + ], + [ + [ + 0.07469315368796249 + ] + ], + [ + [ + 0.07407955894489102 + ] + ] + ], + "q10": [ + [ + [ + 0.31715286275651944 + ] + ], + [ + [ + 0.3215254711229003 + ] + ], + [ + [ + 0.30353990994166524 + ] + ] + ], + "q50": [ + [ + [ + 0.5199269091079658 + ] + ], + [ + [ + 0.5305114367150816 + ] + ], + [ + [ + 0.5209989345006634 + ] + ] + ], + "q90": [ + [ + [ + 0.5632998346913191 + ] + ], + [ + [ + 0.5666944392017282 + ] + ], + [ + [ + 0.5606875699288839 + ] + ] + ], + "q99": [ + [ + [ + 0.5893329859944269 + ] + ], + [ + [ + 0.5858415383992885 + ] + ], + [ + [ + 0.5841699172349623 + ] + ] + ] + }, + "task_index": { + "min": [ + 0 + ], + "max": [ + 0 + ], + "mean": [ + 0.0 + ], + "std": [ + 0.0 + ], + "count": [ + 31662 + ], + "q01": [ + 3.999999999999416e-16 + ], + "q10": [ + 3.999999999999416e-15 + ], + "q50": [ + 1.999999999999708e-14 + ], + "q90": [ + 3.599999999999475e-14 + ], + "q99": [ + 3.959999999999426e-14 + ] + }, + "observation.states.joint_position": { + "min": [ + -0.4792475700378418, + -0.17303875088691711, + -0.5550373196601868, + -1.7863118648529053, + -0.556555449962616, + 1.4112317562103271, + -0.7897247076034546, + 0.0 + ], + "max": [ + 0.6933449506759644, + 0.6483161449432373, + 0.24008235335350037, + -1.2061364650726318, + 0.5948796272277832, + 2.9671719074249268, + 1.5412038564682007, + 0.9955947399139404 + ], + "mean": [ + 0.08307541985392064, + 0.21595505593653658, + -0.06930492230259129, + -1.5465318743318581, + -0.027131365655145914, + 2.014955148517833, + 0.23194884678556466, + 0.6496123414561716 + ], + "std": [ + 0.18346338992543598, + 0.18525191351178247, + 0.09729970935484367, + 0.09688257543821313, + 0.08885077550896962, + 0.37816230296399816, + 0.4538132280198466, + 0.43788230781758464 + ], + "count": [ + 31662 + ], + "q01": [ + -0.059983247997501, + -0.008089137494155725, + -0.11355956738959826, + -1.6362844787051258, + -0.09748544384830576, + 1.6202775963149094, + -0.107512672453896, + -1.000000013351432e-10 + ], + "q10": [ + -0.046061865426954195, + 0.011928289285986255, + -0.10995279671210136, + -1.6234894199315064, + -0.0875393795698981, + 1.635005122528732, + -0.08487479505434022, + 0.0013078465886770091 + ], + "q50": [ + 0.09312705711493158, + 0.21976722762964496, + -0.07653552368003404, + -1.5617101012725234, + -0.021237679524713282, + 2.0507582705260785, + 0.29536171888560564, + 0.9110621240012867 + ], + "q90": [ + 0.20282499261463963, + 0.42640622785173465, + -0.021370758112509814, + -1.443304358172678, + 0.027971435875220843, + 2.423922345921811, + 0.5012210673780202, + 0.9885988833533259 + ], + "q99": [ + 0.21288423933120867, + 0.44085273069370573, + -0.01217677257791173, + -1.4343831924021644, + 0.036407714533119744, + 2.4646011820637157, + 0.515795658515525, + 0.9889299547353837 + ] + }, + "episode_index": { + "min": [ + 0 + ], + "max": [ + 288 + ], + "mean": [ + 144.28924262522898 + ], + "std": [ + 84.0818915388226 + ], + "count": [ + 31662 + ], + "q01": [ + 144.28924262522898 + ], + "q10": [ + 144.28924262522898 + ], + "q50": [ + 144.28924262522898 + ], + "q90": [ + 144.28924262522898 + ], + "q99": [ + 144.28924262522898 + ] + }, + "frame_index": { + "min": [ + 0 + ], + "max": [ + 328 + ], + "mean": [ + 59.05290253300486 + ], + "std": [ + 41.021938720533086 + ], + "count": [ + 31662 + ], + "q01": [ + 0.7128966299307732 + ], + "q10": [ + 11.371235818250309 + ], + "q50": [ + 58.79025514496828 + ], + "q90": [ + 106.61968389623351 + ], + "q99": [ + 117.37619672778504 + ] + } +} \ No newline at end of file diff --git a/assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1/meta/tasks.parquet b/assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1/meta/tasks.parquet new file mode 100644 index 0000000000000000000000000000000000000000..9066bd7f9cd0a39622b670e1918aff9d612c788d Binary files /dev/null and b/assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1/meta/tasks.parquet differ diff --git a/assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1/videos/observation.images.camera_left/chunk-000/file-000.mp4 b/assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1/videos/observation.images.camera_left/chunk-000/file-000.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..47905c0158a7469609f4612f7e08db05970ec124 Binary files /dev/null and b/assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1/videos/observation.images.camera_left/chunk-000/file-000.mp4 differ diff --git a/assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1/videos/observation.images.camera_right/chunk-000/file-000.mp4 b/assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1/videos/observation.images.camera_right/chunk-000/file-000.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..111035744d30471db537891406bae62f98208507 Binary files /dev/null and b/assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1/videos/observation.images.camera_right/chunk-000/file-000.mp4 differ diff --git a/assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1/videos/observation.images.camera_top/chunk-000/file-000.mp4 b/assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1/videos/observation.images.camera_top/chunk-000/file-000.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..1c0fad196776cc4d56f0c3d94d3ecbc181e6097e Binary files /dev/null and b/assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1/videos/observation.images.camera_top/chunk-000/file-000.mp4 differ diff --git a/assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/data/chunk-000/file-000.parquet b/assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/data/chunk-000/file-000.parquet new file mode 100644 index 0000000000000000000000000000000000000000..7edc84f5f1a3217bcc31634a6f8da80caf7c4c73 --- /dev/null +++ b/assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/data/chunk-000/file-000.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d9053fdb89f8f6990015201d1fc321e1b3999735e575e7c2f35b7fbf12ccbc4e +size 134374 diff --git a/assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/meta/episodes/chunk-000/file-000.parquet b/assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/meta/episodes/chunk-000/file-000.parquet new file mode 100644 index 0000000000000000000000000000000000000000..12a94aa07ae60a89aebbff4080ce039bb1d082a6 --- /dev/null +++ b/assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/meta/episodes/chunk-000/file-000.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0bbb518c7f9c370968278cc3746c3526bd7a09758630773ac4193e33eec7f067 +size 140145 diff --git a/assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/meta/info.json b/assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/meta/info.json new file mode 100644 index 0000000000000000000000000000000000000000..98a9300150c3c9d4ac2ea400a8742e722a9d17e4 --- /dev/null +++ b/assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/meta/info.json @@ -0,0 +1,186 @@ +{ + "codebase_version": "v3.0", + "robot_type": "franka_fr3_dual", + "total_episodes": 1, + "total_frames": 574, + "total_tasks": 1, + "chunks_size": 1000, + "data_files_size_in_mb": 100, + "video_files_size_in_mb": 200, + "fps": 30, + "splits": { + "train": "0:1" + }, + "data_path": "data/chunk-{chunk_index:03d}/file-{file_index:03d}.parquet", + "video_path": "videos/{video_key}/chunk-{chunk_index:03d}/file-{file_index:03d}.mp4", + "features": { + "observation.images.camera_front": { + "dtype": "video", + "shape": [ + 720, + 1280, + 3 + ], + "names": [ + "height", + "width", + "rgb" + ], + "info": { + "video.height": 720, + "video.width": 1280, + "video.codec": "av1", + "video.pix_fmt": "yuv420p", + "video.is_depth_map": false, + "video.fps": 30, + "video.channels": 3, + "has_audio": false + } + }, + "observation.images.camera_left": { + "dtype": "video", + "shape": [ + 480, + 640, + 3 + ], + "names": [ + "height", + "width", + "rgb" + ], + "info": { + "video.height": 480, + "video.width": 640, + "video.codec": "av1", + "video.pix_fmt": "yuv420p", + "video.is_depth_map": false, + "video.fps": 30, + "video.channels": 3, + "has_audio": false + } + }, + "observation.images.camera_right": { + "dtype": "video", + "shape": [ + 480, + 640, + 3 + ], + "names": [ + "height", + "width", + "rgb" + ], + "info": { + "video.height": 480, + "video.width": 640, + "video.codec": "av1", + "video.pix_fmt": "yuv420p", + "video.is_depth_map": false, + "video.fps": 30, + "video.channels": 3, + "has_audio": false + } + }, + "observation.states.end_effector": { + "dtype": "float32", + "shape": [ + 12 + ], + "names": { + "motors": [ + "left_xyzrpy", + "right_xyzrpy" + ] + } + }, + "observation.states.joint_position": { + "dtype": "float32", + "shape": [ + 16 + ], + "names": { + "motors": [ + "left_joint_0", + "left_joint_1", + "left_joint_2", + "left_joint_3", + "left_joint_4", + "left_joint_5", + "left_joint_6", + "left_gripper", + "right_joint_0", + "right_joint_1", + "right_joint_2", + "right_joint_3", + "right_joint_4", + "right_joint_5", + "right_joint_6", + "right_gripper" + ] + } + }, + "actions.joint_position": { + "dtype": "float32", + "shape": [ + 16 + ], + "names": { + "motors": [ + "left_joint_0", + "left_joint_1", + "left_joint_2", + "left_joint_3", + "left_joint_4", + "left_joint_5", + "left_joint_6", + "left_gripper", + "right_joint_0", + "right_joint_1", + "right_joint_2", + "right_joint_3", + "right_joint_4", + "right_joint_5", + "right_joint_6", + "right_gripper" + ] + } + }, + "timestamp": { + "dtype": "float32", + "shape": [ + 1 + ], + "names": null + }, + "frame_index": { + "dtype": "int64", + "shape": [ + 1 + ], + "names": null + }, + "episode_index": { + "dtype": "int64", + "shape": [ + 1 + ], + "names": null + }, + "index": { + "dtype": "int64", + "shape": [ + 1 + ], + "names": null + }, + "task_index": { + "dtype": "int64", + "shape": [ + 1 + ], + "names": null + } + } +} diff --git a/assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/meta/stats.json b/assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/meta/stats.json new file mode 100644 index 0000000000000000000000000000000000000000..b088c8517e90267f193cebfde742a8d21a2a2a60 --- /dev/null +++ b/assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/meta/stats.json @@ -0,0 +1,1259 @@ +{ + "observation.images.camera_top": { + "min": [ + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ] + ], + "max": [ + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ] + ], + "mean": [ + [ + [ + 0.48376929793303225 + ] + ], + [ + [ + 0.4674950063659832 + ] + ], + [ + [ + 0.42110986085802427 + ] + ] + ], + "std": [ + [ + [ + 0.0034515567737140648 + ] + ], + [ + [ + 0.003152313608076121 + ] + ], + [ + [ + 0.0030219598760090854 + ] + ] + ], + "count": [ + 13472 + ], + "q01": [ + [ + [ + 0.09619084794816744 + ] + ], + [ + [ + 0.0870123248734442 + ] + ], + [ + [ + 0.0430602865244451 + ] + ] + ], + "q10": [ + [ + [ + 0.2804504373204744 + ] + ], + [ + [ + 0.2611546733612462 + ] + ], + [ + [ + 0.19861621336452784 + ] + ] + ], + "q50": [ + [ + [ + 0.4573825435387216 + ] + ], + [ + [ + 0.42278935615332147 + ] + ], + [ + [ + 0.37139849968994815 + ] + ] + ], + "q90": [ + [ + [ + 0.7830895781354413 + ] + ], + [ + [ + 0.8220906539922425 + ] + ], + [ + [ + 0.8252257020249846 + ] + ] + ], + "q99": [ + [ + [ + 0.8586179042245964 + ] + ], + [ + [ + 0.9050680340394492 + ] + ], + [ + [ + 0.9365709680791219 + ] + ] + ] + }, + "actions.joint_position": { + "min": [ + -0.5353593230247498, + -0.754718542098999, + -0.777728259563446, + -2.7626993656158447, + -1.0722525119781494, + 1.2210487127304077, + -0.6657305955886841, + 0.0, + -0.36201930046081543, + -0.1242208406329155, + -0.685689389705658, + -1.9895726442337036, + -0.8651651740074158, + 1.334547996520996, + -0.7146927714347839, + 0.00037202381645329297 + ], + "max": [ + 0.859029233455658, + 0.509265661239624, + 0.653475821018219, + -1.3130875825881958, + 0.3420293629169464, + 2.903825521469116, + 1.3529239892959595, + 1.0, + 0.7976546883583069, + 0.9572038650512695, + 0.8713011145591736, + -0.8973791003227234, + 0.5967175960540771, + 2.6613783836364746, + 1.9404549598693848, + 1.0 + ], + "mean": [ + 0.1861865432166611, + -0.017391271701913246, + -0.02958098278051404, + -1.8821133989849286, + -0.25689289227268475, + 2.1217277282727984, + 0.3108133571587931, + 0.6812934040810689, + 0.11169839708835208, + 0.2291464669503562, + 0.12317132691269464, + -1.4440139117058302, + -0.046060681490781845, + 1.781798902100068, + 0.10212216518653346, + 0.2543521764761343 + ], + "std": [ + 0.29527247764323017, + 0.2941846330159817, + 0.22514641919837344, + 0.3761867395993795, + 0.2813910406889975, + 0.34057403940537867, + 0.4628391164924103, + 0.4555740774662373, + 0.18822520803853124, + 0.22782164980246536, + 0.16998464278726325, + 0.10402822172948001, + 0.18946423032995677, + 0.376722385852282, + 0.360779166884318, + 0.40944824170478805 + ], + "count": [ + 58885 + ], + "q01": [ + -0.20556848787213558, + -0.5508892892828418, + -0.2802029428874371, + -2.541712034898689, + -0.8017318025624431, + 1.488068518107089, + -0.23624862588524992, + 0.0006147995589559869, + -0.07258994513304466, + 0.024481408466384767, + -0.006644251635662588, + -1.6272202850076025, + -0.3526667724106083, + 1.4679249908600462, + -0.22860762983618546, + 0.009139926723121927 + ], + "q10": [ + -0.13583602028636654, + -0.4679717799673135, + -0.21758269732104135, + -2.4371744491637686, + -0.7103455442426116, + 1.6071025304281203, + -0.1550291626558284, + 0.0015784068204869187, + -0.012934452240419532, + 0.05992092372297601, + 0.025861471778839268, + -1.5266868434276748, + -0.3071736542346529, + 1.5083107376661646, + -0.12882271449454785, + 0.010191584920591464 + ], + "q50": [ + 0.18507903561119993, + 0.017982969879327675, + -0.055829753724253084, + -1.6899328910829658, + -0.1419832568784388, + 2.214857399388195, + 0.13183062360135028, + 0.992399260574226, + 0.02703344158757793, + 0.08550643413111958, + 0.083286809780891, + -1.4510293805412144, + 0.002452545848371913, + 1.564874178701891, + -0.010616476610398782, + 0.011183737529185007 + ], + "q90": [ + 0.5609048900649231, + 0.33752525622000595, + 0.21219738654312226, + -1.5041547973889244, + 0.012592934232438515, + 2.498023274709365, + 0.9869082449794297, + 0.9957715569370339, + 0.3374210314229987, + 0.5684143291150674, + 0.2897333408268615, + -1.342906272439828, + 0.1256424085184901, + 2.3885623965208724, + 0.7470419269975446, + 0.9970613443241874 + ], + "q99": [ + 0.5904568356868924, + 0.3779781713728937, + 0.27680301146924324, + -1.440851923136264, + 0.09058589083479192, + 2.5634236203261356, + 1.0779513714773268, + 0.9966748272296234, + 0.5223264767471835, + 0.6776964674736506, + 0.3301378429046773, + -1.2880005871811373, + 0.2726828715550844, + 2.4654702589781974, + 1.0866745698876468, + 0.9988248189214447 + ] + }, + "observation.images.camera_right": { + "min": [ + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ] + ], + "max": [ + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ] + ], + "mean": [ + [ + [ + 0.46124731880052827 + ] + ], + [ + [ + 0.4553679300835038 + ] + ], + [ + [ + 0.42334209907828685 + ] + ] + ], + "std": [ + [ + [ + 0.01039969061638479 + ] + ], + [ + [ + 0.010249261818554806 + ] + ], + [ + [ + 0.010057614941827324 + ] + ] + ], + "count": [ + 13472 + ], + "q01": [ + [ + [ + 0.059261110210909615 + ] + ], + [ + [ + 0.07429608369146787 + ] + ], + [ + [ + 0.06033915532354615 + ] + ] + ], + "q10": [ + [ + [ + 0.20528986731553428 + ] + ], + [ + [ + 0.20506945620878664 + ] + ], + [ + [ + 0.1643094107999931 + ] + ] + ], + "q50": [ + [ + [ + 0.5191681591791838 + ] + ], + [ + [ + 0.4810674129951322 + ] + ], + [ + [ + 0.3885047815405505 + ] + ] + ], + "q90": [ + [ + [ + 0.6589198999415846 + ] + ], + [ + [ + 0.6763365405598278 + ] + ], + [ + [ + 0.6761300090592645 + ] + ] + ], + "q99": [ + [ + [ + 0.7465792160987124 + ] + ], + [ + [ + 0.7698546910074944 + ] + ], + [ + [ + 0.7657271498394176 + ] + ] + ] + }, + "episode_index": { + "min": [ + 0 + ], + "max": [ + 128 + ], + "mean": [ + 64.18070815997282 + ], + "std": [ + 36.93854045783521 + ], + "count": [ + 58885 + ], + "q01": [ + 64.18070815997282 + ], + "q10": [ + 64.18070815997282 + ], + "q50": [ + 64.18070815997284 + ], + "q90": [ + 64.18070815997284 + ], + "q99": [ + 64.18070815997284 + ] + }, + "observation.states.joint_position": { + "min": [ + -0.5184276700019836, + -0.7133806943893433, + -0.7727153897285461, + -2.7567901611328125, + -1.0469406843185425, + 1.2608721256256104, + -0.6555339097976685, + 0.0, + -0.3380506634712219, + -0.0967535451054573, + -0.6921591758728027, + -1.9839798212051392, + -0.8350218534469604, + 1.3372937440872192, + -0.678467869758606, + 0.0 + ], + "max": [ + 0.8559838533401489, + 0.5060783624649048, + 0.6553268432617188, + -1.3234312534332275, + 0.3107798099517822, + 2.8862950801849365, + 1.3210870027542114, + 0.37444934248924255, + 0.796474039554596, + 0.9370087385177612, + 0.8579978942871094, + -0.8903438448905945, + 0.5705297589302063, + 2.6416311264038086, + 1.9162824153900146, + 0.9823788404464722 + ], + "mean": [ + 0.1899299091718875, + -0.006983510289951079, + -0.03201154206908776, + -1.8901113197072066, + -0.25972718498829694, + 2.1236042977917977, + 0.3134960712148691, + 0.25232693715584215, + 0.1181601202667235, + 0.2352566502086829, + 0.11865091471510701, + -1.4396272846927078, + -0.050641272852852554, + 1.7804795026374287, + 0.10953031788464111, + 0.24614797891264326 + ], + "std": [ + 0.2920662065860597, + 0.2829727697192382, + 0.2250152383672195, + 0.3739207836802478, + 0.2706061997178126, + 0.32875287858479824, + 0.4545940888251623, + 0.16491406981261394, + 0.18521363874518934, + 0.22110645365448872, + 0.1681570365055575, + 0.10454250863973764, + 0.18296781127883446, + 0.3756805469840582, + 0.354489103177839, + 0.39247840200787726 + ], + "count": [ + 58885 + ], + "q01": [ + -0.17981989779968843, + -0.5091775890358096, + -0.2823747022384176, + -2.5402944887002263, + -0.7772767335767301, + 1.5074242517409697, + -0.22118355190838992, + 0.00019929485039286372, + -0.05811890221630709, + 0.0355534456639416, + -0.014671354686920067, + -1.6166171728649017, + -0.33262037407789363, + 1.4670034437478248, + -0.20856855427653162, + 0.005969670174481924 + ], + "q10": [ + -0.12896930587932032, + -0.4363874933365298, + -0.22108213657540865, + -2.431940673529726, + -0.6917178109339138, + 1.6199445363543552, + -0.14425280902059237, + 0.0006490404603215833, + -0.00465639724748521, + 0.06950417070554113, + 0.020541581682950536, + -1.523574035591159, + -0.2990772907187631, + 1.5087846748431677, + -0.12178478728338077, + 0.006887727973015377 + ], + "q50": [ + 0.19071994481038587, + 0.0225044554622574, + -0.05771964361942917, + -1.7039336205325046, + -0.14714522872126526, + 2.208780027646876, + 0.13614323027627798, + 0.36246706129481615, + 0.03542061717828114, + 0.09949137725052416, + 0.07978819556433957, + -1.4442567729696547, + -0.008123791931469346, + 1.5639312834308705, + 0.0035313031234437474, + 0.008194616957793414 + ], + "q90": [ + 0.5617718208281102, + 0.3372213513062743, + 0.21115642563723888, + -1.5094768909216087, + 0.0005424632975009549, + 2.486585004915233, + 0.9708517327751961, + 0.3625096095467171, + 0.34023178117996594, + 0.5548909313712731, + 0.2865432489812551, + -1.3458676838483008, + 0.11952314656085365, + 2.390689009089357, + 0.7439389258839233, + 0.9444897776717005 + ], + "q99": [ + 0.5846436107029699, + 0.3679246810887602, + 0.2686922162187065, + -1.4478673737392953, + 0.0686222391930825, + 2.548678641847992, + 1.0502165134906425, + 0.3625191829033949, + 0.5200118301008778, + 0.6613513655217865, + 0.3248879353556084, + -1.2781377608963183, + 0.2509619238047111, + 2.454751758136821, + 1.0678813767059858, + 0.9451304795927765 + ] + }, + "index": { + "min": [ + 0 + ], + "max": [ + 58884 + ], + "mean": [ + 29442.0 + ], + "std": [ + 16998.635298164376 + ], + "count": [ + 58885 + ], + "q01": [ + 29212.00052687167 + ], + "q10": [ + 29254.219078618255 + ], + "q50": [ + 29441.779063900824 + ], + "q90": [ + 29629.69858367266 + ], + "q99": [ + 29671.991846398254 + ] + }, + "observation.images.camera_left": { + "min": [ + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ] + ], + "max": [ + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ] + ], + "mean": [ + [ + [ + 0.46247320010372533 + ] + ], + [ + [ + 0.4615624414332364 + ] + ], + [ + [ + 0.42029015289093913 + ] + ] + ], + "std": [ + [ + [ + 0.0032999404373803332 + ] + ], + [ + [ + 0.0027171969210648154 + ] + ], + [ + [ + 0.002928244417570089 + ] + ] + ], + "count": [ + 13472 + ], + "q01": [ + [ + [ + 0.054253433231095896 + ] + ], + [ + [ + 0.07110441821437478 + ] + ], + [ + [ + 0.036649910826101764 + ] + ] + ], + "q10": [ + [ + [ + 0.16653584030201984 + ] + ], + [ + [ + 0.1825803183534302 + ] + ], + [ + [ + 0.14620039681336194 + ] + ] + ], + "q50": [ + [ + [ + 0.4363331616293392 + ] + ], + [ + [ + 0.42586726431636607 + ] + ], + [ + [ + 0.35001359698550183 + ] + ] + ], + "q90": [ + [ + [ + 0.7131412248460454 + ] + ], + [ + [ + 0.7341972090885474 + ] + ], + [ + [ + 0.728190819182643 + ] + ] + ], + "q99": [ + [ + [ + 0.7596985187175224 + ] + ], + [ + [ + 0.7803990377293848 + ] + ], + [ + [ + 0.7760067743886184 + ] + ] + ] + }, + "task_index": { + "min": [ + 0 + ], + "max": [ + 0 + ], + "mean": [ + 0.0 + ], + "std": [ + 0.0 + ], + "count": [ + 58885 + ], + "q01": [ + 3.9999999999994167e-16 + ], + "q10": [ + 3.999999999999418e-15 + ], + "q50": [ + 1.9999999999997094e-14 + ], + "q90": [ + 3.5999999999994754e-14 + ], + "q99": [ + 3.9599999999994235e-14 + ] + }, + "timestamp": { + "min": [ + 0.0 + ], + "max": [ + 21.233333333333334 + ], + "mean": [ + 7.805497721547649 + ], + "std": [ + 4.755558844357094 + ], + "count": [ + 58885 + ], + "q01": [ + 0.13884861717498875 + ], + "q10": [ + 1.5461336754115809 + ], + "q50": [ + 7.798064785372518 + ], + "q90": [ + 14.062117177380546 + ], + "q99": [ + 15.471892601584731 + ] + }, + "frame_index": { + "min": [ + 0 + ], + "max": [ + 637 + ], + "mean": [ + 234.1649316464295 + ], + "std": [ + 142.66676533071268 + ], + "count": [ + 58885 + ], + "q01": [ + 4.1654585180982595 + ], + "q10": [ + 46.384010264673144 + ], + "q50": [ + 233.92680005773957 + ], + "q90": [ + 421.8635153190919 + ], + "q99": [ + 464.1567780446939 + ] + }, + "observation.states.end_effector": { + "min": [ + 0.32554587721824646, + -0.2414933294057846, + 0.3707878589630127, + -3.1415812969207764, + -0.9135556221008301, + -0.44747135043144226, + 0.44667676091194153, + -0.03310394659638405, + 0.3244316279888153, + -3.1415786743164062, + -0.669172465801239, + -0.9677415490150452 + ], + "max": [ + 0.6721678972244263, + 0.401833176612854, + 0.7120418548583984, + 3.1415834426879883, + 0.6720868349075317, + 0.5769774913787842, + 0.7523236274719238, + 0.5960171818733215, + 0.6841686964035034, + 3.1415915489196777, + 0.5525403022766113, + 1.2117595672607422 + ], + "mean": [ + 0.5194264009320351, + 0.10808882922322567, + 0.5197762573383815, + 1.7688925584930815, + -0.29953467956552515, + -0.009040712931030676, + 0.5946066851586347, + 0.1450713845479617, + 0.5655443782999531, + 0.03370911358491344, + -0.06345323249756106, + 0.15650386904123778 + ], + "std": [ + 0.06940804680395932, + 0.21479389958966238, + 0.07987378005717213, + 2.5328884145755013, + 0.37015053086730393, + 0.14033346903287636, + 0.05500649146642034, + 0.15124297160388672, + 0.09363130714884703, + 3.03814882283887, + 0.21562238267324205, + 0.34913428619424713 + ], + "count": [ + 58885 + ], + "q01": [ + 0.389680832056878, + -0.17079152837311037, + 0.39821232917555377, + -3.138355683944816, + -0.7794698389047763, + -0.2292111271434537, + 0.5201355614396355, + 0.010009717834048406, + 0.3473206492241046, + -3.1292262955378995, + -0.4931042039709613, + -0.39392433108198205 + ], + "q10": [ + 0.42069872243959483, + -0.1644398217900128, + 0.40948145367679184, + -2.609507988991038, + -0.7376621670915048, + -0.19173335222881605, + 0.5505130729366431, + 0.031160920484378817, + 0.444289028673263, + -3.0458564102249928, + -0.43339771249706854, + -0.20578126489476734 + ], + "q50": [ + 0.54287060969675, + 0.08208830090982204, + 0.5136938051063558, + 3.0231563729371027, + -0.3334930943115573, + 0.005159299527350032, + 0.5705313177680298, + 0.05576278260510965, + 0.6221501000520611, + 0.08224261688253993, + 0.0023568181324399736, + 0.057234217959009334 + ], + "q90": [ + 0.59671051597898, + 0.36814967665609416, + 0.6259625015535398, + 3.123177169155181, + 0.2582628807072582, + 0.15080460679812915, + 0.6909623712983989, + 0.36407326703235277, + 0.6393178833446403, + 2.811600900308528, + 0.1710100649519071, + 0.6242686543181142 + ], + "q99": [ + 0.6079055905141758, + 0.3797359990109224, + 0.6530560232359751, + 3.138519684929094, + 0.33900879084841173, + 0.25563831616345334, + 0.7036422698800308, + 0.5043118200846742, + 0.6496623410871386, + 3.1286655629008155, + 0.2654963193701809, + 0.7082099434004004 + ] + }, + "observation.images.camera_front": { + "min": [ + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ] + ], + "max": [ + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ] + ], + "mean": [ + [ + [ + 0.5100816380557235 + ] + ], + [ + [ + 0.48797377496665395 + ] + ], + [ + [ + 0.434097923507289 + ] + ] + ], + "std": [ + [ + [ + 0.005841510955391268 + ] + ], + [ + [ + 0.005956098895297586 + ] + ], + [ + [ + 0.0049887549805231225 + ] + ] + ], + "count": [ + 13472 + ], + "q01": [ + [ + [ + 0.1065357721395866 + ] + ], + [ + [ + 0.09551342896686918 + ] + ], + [ + [ + 0.07985796055323706 + ] + ] + ], + "q10": [ + [ + [ + 0.3038424725838036 + ] + ], + [ + [ + 0.262236796069868 + ] + ], + [ + [ + 0.20546917169830345 + ] + ] + ], + "q50": [ + [ + [ + 0.5127494663087449 + ] + ], + [ + [ + 0.5081266972660918 + ] + ], + [ + [ + 0.40105148618602443 + ] + ] + ], + "q90": [ + [ + [ + 0.6909139072635854 + ] + ], + [ + [ + 0.6941647590417448 + ] + ], + [ + [ + 0.6879961139373174 + ] + ] + ], + "q99": [ + [ + [ + 0.8289626568583892 + ] + ], + [ + [ + 0.8531150291535311 + ] + ], + [ + [ + 0.852308856360926 + ] + ] + ] + } +} \ No newline at end of file diff --git a/assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/meta/tasks.parquet b/assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/meta/tasks.parquet new file mode 100644 index 0000000000000000000000000000000000000000..602767a0ee9648be1b068fc83f54844d4ba85ade Binary files /dev/null and b/assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/meta/tasks.parquet differ diff --git a/assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/videos/observation.images.camera_front/chunk-000/file-000.mp4 b/assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/videos/observation.images.camera_front/chunk-000/file-000.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..5417872eb5475e0d9bb3f66bbcd9e73733016404 --- /dev/null +++ b/assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/videos/observation.images.camera_front/chunk-000/file-000.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a1426a6fcb7267b05a233e642b13c676e98c1a8e5829c4c73338240fd126fce0 +size 151427 diff --git a/assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/videos/observation.images.camera_left/chunk-000/file-000.mp4 b/assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/videos/observation.images.camera_left/chunk-000/file-000.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..3413c980c64fc69f9f147ef1838c1bc346e48c14 --- /dev/null +++ b/assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/videos/observation.images.camera_left/chunk-000/file-000.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d991c3eea5cfd358c57f9c6974f8c52d26d94997f584a3c9c8d9a0b9bb5b3dcd +size 240182 diff --git a/assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/videos/observation.images.camera_right/chunk-000/file-000.mp4 b/assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/videos/observation.images.camera_right/chunk-000/file-000.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..0e40a6c12ed974a08ff64376c4a15c094d251d13 --- /dev/null +++ b/assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water/videos/observation.images.camera_right/chunk-000/file-000.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8b029eea41d08036d02a96a0081346f5c8178a7cdd793ed8001bba6ec7dac22c +size 138128 diff --git a/assets/examples/av_v2_03292026_wdinfo/data/00000000.tar b/assets/examples/av_v2_03292026_wdinfo/data/00000000.tar new file mode 100644 index 0000000000000000000000000000000000000000..82482c3c9e15e7cb8537810a3f7afdc2dac138f2 --- /dev/null +++ b/assets/examples/av_v2_03292026_wdinfo/data/00000000.tar @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:417bb12ff755070b342f86a117a6c31489009ee29c8404b9679d32e73c724c0d +size 30556160 diff --git a/assets/examples/av_v2_03292026_wdinfo/wdinfo.json b/assets/examples/av_v2_03292026_wdinfo/wdinfo.json new file mode 100644 index 0000000000000000000000000000000000000000..5cddbe1b12274dcda31a9477e3e24b8f5160b9f7 --- /dev/null +++ b/assets/examples/av_v2_03292026_wdinfo/wdinfo.json @@ -0,0 +1,11 @@ +{ + "data_keys": [ + "pkl" + ], + "chunk_size": 10, + "root": "data", + "data_list": [ + "00000000.tar" + ], + "total_key_count": 10 +} diff --git a/assets/examples/bridge_lerobot_v3/data/chunk-000/file-000.parquet b/assets/examples/bridge_lerobot_v3/data/chunk-000/file-000.parquet new file mode 100644 index 0000000000000000000000000000000000000000..7e4315748d35e213d69d1996c1f3188611dd9711 Binary files /dev/null and b/assets/examples/bridge_lerobot_v3/data/chunk-000/file-000.parquet differ diff --git a/assets/examples/bridge_lerobot_v3/meta/episodes/chunk-000/file-000.parquet b/assets/examples/bridge_lerobot_v3/meta/episodes/chunk-000/file-000.parquet new file mode 100644 index 0000000000000000000000000000000000000000..ada70e27595f411dfcc8088b72fd565e7bb8bd09 --- /dev/null +++ b/assets/examples/bridge_lerobot_v3/meta/episodes/chunk-000/file-000.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d65cf968ca396078256a56da1802e558ff4597f8d0d0e9c413bcb24e9027f6e +size 123838 diff --git a/assets/examples/bridge_lerobot_v3/meta/info.json b/assets/examples/bridge_lerobot_v3/meta/info.json new file mode 100644 index 0000000000000000000000000000000000000000..1be195f5b1b3321ac28984187034edc3b82bb04e --- /dev/null +++ b/assets/examples/bridge_lerobot_v3/meta/info.json @@ -0,0 +1,94 @@ +{ + "codebase_version": "v3.0", + "robot_type": null, + "total_episodes": 2, + "total_frames": 46, + "total_tasks": 1, + "chunks_size": 1000, + "data_files_size_in_mb": 100, + "video_files_size_in_mb": 200, + "fps": 5, + "splits": { + "train": "0:2" + }, + "data_path": "data/chunk-{chunk_index:03d}/file-{file_index:03d}.parquet", + "video_path": "videos/{video_key}/chunk-{chunk_index:03d}/file-{file_index:03d}.mp4", + "features": { + "observation.images.image_0": { + "dtype": "video", + "shape": [ + 480, + 640, + 3 + ], + "names": [ + "height", + "width", + "rgb" + ], + "info": { + "video.height": 480, + "video.width": 640, + "video.codec": "av1", + "video.pix_fmt": "yuv420p", + "video.is_depth_map": false, + "video.fps": 5, + "video.channels": 3, + "has_audio": false + } + }, + "observation.state": { + "dtype": "float32", + "shape": [ + 7 + ], + "names": [ + "state" + ] + }, + "action": { + "dtype": "float32", + "shape": [ + 7 + ], + "names": [ + "action" + ] + }, + "timestamp": { + "dtype": "float32", + "shape": [ + 1 + ], + "names": null + }, + "frame_index": { + "dtype": "int64", + "shape": [ + 1 + ], + "names": null + }, + "episode_index": { + "dtype": "int64", + "shape": [ + 1 + ], + "names": null + }, + "index": { + "dtype": "int64", + "shape": [ + 1 + ], + "names": null + }, + "task_index": { + "dtype": "int64", + "shape": [ + 1 + ], + "names": null + } + } +} diff --git a/assets/examples/bridge_lerobot_v3/meta/stats.json b/assets/examples/bridge_lerobot_v3/meta/stats.json new file mode 100644 index 0000000000000000000000000000000000000000..74046d8bc62b7dc32e6f875410f1f638ce7fd342 --- /dev/null +++ b/assets/examples/bridge_lerobot_v3/meta/stats.json @@ -0,0 +1,966 @@ +{ + "observation.state": { + "min": [ + -0.04167502000927925, + -0.3945816159248352, + -0.15537554025650024, + -3.141592502593994, + -1.4992541074752808, + -3.14153790473938, + 0.04637829214334488 + ], + "max": [ + 0.5862360596656799, + 0.4034728705883026, + 0.36494991183280945, + 1.514088749885559, + 1.570796251296997, + 3.1415255069732666, + 1.1154625415802002 + ], + "mean": [ + 0.3078657070409933, + 0.031129854114640153, + 0.06524272890027896, + 0.010478528822645234, + -0.1153295264240988, + 0.13293259596689477, + 0.7535287298011476 + ], + "std": [ + 0.06390337703414369, + 0.09462637224137227, + 0.053973478626083184, + 0.14631237221965346, + 0.17009178266906624, + 0.6086491420893041, + 0.3311070209320066 + ], + "count": [ + 1801090 + ], + "q01": [ + 0.2463635235491362, + -0.05778863449398043, + 0.016231048745205447, + -0.1276350840652153, + -0.2652197166812523, + -0.17831831795983122, + 0.4352433491416346 + ], + "q10": [ + 0.2558413467940049, + -0.048030725569368646, + 0.021219741154135583, + -0.09136181372777585, + -0.2250875629406645, + -0.12693452700587574, + 0.4425213950537474 + ], + "q50": [ + 0.30547148123085394, + 0.028478191953509382, + 0.061788129019053534, + 0.009242004648470028, + -0.11450417784936784, + 0.12738886565246837, + 0.8525009665260582 + ], + "q90": [ + 0.3599411511270558, + 0.11057157999679051, + 0.11297343197112365, + 0.11136320995120631, + -0.00892123863592227, + 0.3888200032384959, + 0.9973646300570351 + ], + "q99": [ + 0.36770364361385066, + 0.12096997648229695, + 0.12923741839066463, + 0.14542505776055412, + 0.022217630370894997, + 0.43883905381625504, + 1.0043319804665372 + ] + }, + "episode_index": { + "min": [ + 0 + ], + "max": [ + 395 + ], + "mean": [ + 17.263674774719753 + ], + "std": [ + 28.83284715650058 + ], + "count": [ + 1801090 + ], + "q01": [ + 17.263674774719753 + ], + "q10": [ + 17.263674774719753 + ], + "q50": [ + 17.26367477471977 + ], + "q90": [ + 17.263674774719785 + ], + "q99": [ + 17.26367477471979 + ] + }, + "frame_index": { + "min": [ + 0 + ], + "max": [ + 118 + ], + "mean": [ + 19.619974015734915 + ], + "std": [ + 14.763794098949749 + ], + "count": [ + 1801090 + ], + "q01": [ + 0.00030421277553703693 + ], + "q10": [ + 3.4375358736604062 + ], + "q50": [ + 19.329761038813803 + ], + "q90": [ + 35.73429024692172 + ], + "q99": [ + 39.23594070484433 + ] + }, + "action": { + "min": [ + -0.21280786395072937, + -0.22161394357681274, + -0.4670022130012512, + -0.9053626656532288, + -0.728705883026123, + -1.1610136032104492, + 0.0 + ], + "max": [ + 0.14468924701213837, + 0.28896045684814453, + 0.25066766142845154, + 0.9110258221626282, + 0.6760650873184204, + 1.1013237237930298, + 1.0 + ], + "mean": [ + 0.00057356759712255, + 0.00011228985106677395, + 0.00033733821111343496, + -3.2933660066906675e-05, + -0.0018181216694647497, + 0.00010204879316899695, + 0.6233483145627287 + ], + "std": [ + 0.010469277762356712, + 0.01524215121861673, + 0.012821488448696097, + 0.031125604404310805, + 0.032741672740958225, + 0.055620604208622804, + 0.48136517793996136 + ], + "count": [ + 1801090 + ], + "q01": [ + -0.021358451629461966, + -0.029393954179487956, + -0.020992353446725114, + -0.06808332768846173, + -0.07911264819669223, + -0.11372979514314813, + 0.14180975403225513 + ], + "q10": [ + -0.011676061926034044, + -0.017996865470775638, + -0.013541170337680411, + -0.033728621240137514, + -0.041577432476653686, + -0.05835590433099303, + 0.14237743007083528 + ], + "q50": [ + 0.000300881419541358, + -2.5015201984531362e-05, + -0.001233054505179989, + -0.0005056874720216848, + -0.0004731729701556107, + 0.0003401666623676183, + 0.8210043724514866 + ], + "q90": [ + 0.01291656058204435, + 0.01787281343314976, + 0.018174764709341165, + 0.033431397688145396, + 0.033405877348579645, + 0.0560117568652242, + 0.9913997376187794 + ], + "q99": [ + 0.02139908763176426, + 0.029476266857249304, + 0.03265355802175534, + 0.07228712693697929, + 0.06867303567220237, + 0.10840311474445433, + 0.9999937720417067 + ] + }, + "observation.images.image_1": { + "min": [ + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ] + ], + "max": [ + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ] + ], + "mean": [ + [ + [ + 0.23808484892300974 + ] + ], + [ + [ + 0.21420300786234783 + ] + ], + [ + [ + 0.20480729820984775 + ] + ] + ], + "std": [ + [ + [ + 0.24000894290405092 + ] + ], + [ + [ + 0.21610636481161952 + ] + ], + [ + [ + 0.20811969692647148 + ] + ] + ], + "count": [ + 1801038 + ], + "q01": [ + [ + [ + 0.017376900679127255 + ] + ], + [ + [ + 0.01816247306892097 + ] + ], + [ + [ + 0.022169398589928356 + ] + ] + ], + "q10": [ + [ + [ + 0.058939146797035866 + ] + ], + [ + [ + 0.054181793322751755 + ] + ], + [ + [ + 0.05851348748686418 + ] + ] + ], + "q50": [ + [ + [ + 0.24390417350821517 + ] + ], + [ + [ + 0.21150810916563514 + ] + ], + [ + [ + 0.19402058424434335 + ] + ] + ], + "q90": [ + [ + [ + 0.40179968313407505 + ] + ], + [ + [ + 0.37710226136613284 + ] + ], + [ + [ + 0.37200396696903076 + ] + ] + ], + "q99": [ + [ + [ + 0.45799038689270954 + ] + ], + [ + [ + 0.4420613852265376 + ] + ], + [ + [ + 0.44403614462942814 + ] + ] + ] + }, + "timestamp": { + "min": [ + 0.0 + ], + "max": [ + 23.6 + ], + "mean": [ + 3.923994803146983 + ], + "std": [ + 2.9527588197899495 + ], + "count": [ + 1801090 + ], + "q01": [ + 6.0842475107852296e-05 + ], + "q10": [ + 0.6875071746659088 + ], + "q50": [ + 3.866315450153611 + ], + "q90": [ + 7.146858049450175 + ], + "q99": [ + 7.847188141048853 + ] + }, + "task_index": { + "min": [ + 0 + ], + "max": [ + 364 + ], + "mean": [ + 9.508057343053373 + ], + "std": [ + 25.584243677940766 + ], + "count": [ + 1801090 + ], + "q01": [ + 9.508057343053373 + ], + "q10": [ + 9.508057343053375 + ], + "q50": [ + 9.508057343053395 + ], + "q90": [ + 9.508057343053409 + ], + "q99": [ + 9.508057343053412 + ] + }, + "index": { + "min": [ + 0 + ], + "max": [ + 13495 + ], + "mean": [ + 683.7963394388953 + ], + "std": [ + 1011.3259831719954 + ], + "count": [ + 1801090 + ], + "q01": [ + 664.1766696359362 + ], + "q10": [ + 667.6139012968208 + ], + "q50": [ + 683.5079981450107 + ], + "q90": [ + 699.9106556700821 + ], + "q99": [ + 703.4123061280047 + ] + }, + "observation.images.image_0": { + "min": [ + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ] + ], + "max": [ + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ] + ], + "mean": [ + [ + [ + 0.4927899446119918 + ] + ], + [ + [ + 0.43718849912642893 + ] + ], + [ + [ + 0.4049071781276338 + ] + ] + ], + "std": [ + [ + [ + 0.04903922015781917 + ] + ], + [ + [ + 0.054039313949008884 + ] + ], + [ + [ + 0.06398983917342628 + ] + ] + ], + "count": [ + 1801038 + ], + "q01": [ + [ + [ + 0.028015927559851838 + ] + ], + [ + [ + 0.03397041537724499 + ] + ], + [ + [ + 0.034433446895848485 + ] + ] + ], + "q10": [ + [ + [ + 0.11761248327446759 + ] + ], + [ + [ + 0.12180146354404779 + ] + ], + [ + [ + 0.11710207961092006 + ] + ] + ], + "q50": [ + [ + [ + 0.5229947438553765 + ] + ], + [ + [ + 0.44429792190932454 + ] + ], + [ + [ + 0.3921117613148599 + ] + ] + ], + "q90": [ + [ + [ + 0.8008342295803912 + ] + ], + [ + [ + 0.7247795469245689 + ] + ], + [ + [ + 0.7064622418840562 + ] + ] + ], + "q99": [ + [ + [ + 0.9310260844205789 + ] + ], + [ + [ + 0.8931819628452381 + ] + ], + [ + [ + 0.8822519621921744 + ] + ] + ] + }, + "observation.images.image_2": { + "min": [ + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ] + ], + "max": [ + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ] + ], + "mean": [ + [ + [ + 0.22753174550311242 + ] + ], + [ + [ + 0.20561787066183748 + ] + ], + [ + [ + 0.19600823597907133 + ] + ] + ], + "std": [ + [ + [ + 0.2303201611903527 + ] + ], + [ + [ + 0.20878867606799872 + ] + ], + [ + [ + 0.20155566396380575 + ] + ] + ], + "count": [ + 1801038 + ], + "q01": [ + [ + [ + 0.01211383757424793 + ] + ], + [ + [ + 0.012276410483772641 + ] + ], + [ + [ + 0.01321032164222202 + ] + ] + ], + "q10": [ + [ + [ + 0.05121966583649511 + ] + ], + [ + [ + 0.04728960396760485 + ] + ], + [ + [ + 0.0463226160539576 + ] + ] + ], + "q50": [ + [ + [ + 0.2372462692701267 + ] + ], + [ + [ + 0.20519831597920832 + ] + ], + [ + [ + 0.18687017333168612 + ] + ] + ], + "q90": [ + [ + [ + 0.38424357423382227 + ] + ], + [ + [ + 0.36282325690794803 + ] + ], + [ + [ + 0.35931688603448336 + ] + ] + ], + "q99": [ + [ + [ + 0.44992452922757115 + ] + ], + [ + [ + 0.43853143316629245 + ] + ], + [ + [ + 0.4431074246926838 + ] + ] + ] + }, + "observation.images.image_3": { + "min": [ + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ] + ], + "max": [ + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ] + ], + "mean": [ + [ + [ + 0.04973473547975949 + ] + ], + [ + [ + 0.041110336188520565 + ] + ], + [ + [ + 0.03450967238737552 + ] + ] + ], + "std": [ + [ + [ + 0.1369734922735789 + ] + ], + [ + [ + 0.11269590804336074 + ] + ], + [ + [ + 0.09838749201534187 + ] + ] + ], + "count": [ + 1801038 + ], + "q01": [ + [ + [ + 0.0012642076543331999 + ] + ], + [ + [ + 0.0029803378055088445 + ] + ], + [ + [ + 0.0008574280984943751 + ] + ] + ], + "q10": [ + [ + [ + 0.006922960656197909 + ] + ], + [ + [ + 0.00766833310799447 + ] + ], + [ + [ + 0.004724069784713882 + ] + ] + ], + "q50": [ + [ + [ + 0.051436814470232954 + ] + ], + [ + [ + 0.04120058475184378 + ] + ], + [ + [ + 0.03273733587483956 + ] + ] + ], + "q90": [ + [ + [ + 0.08785494596489245 + ] + ], + [ + [ + 0.07315302760390548 + ] + ], + [ + [ + 0.06678022662441209 + ] + ] + ], + "q99": [ + [ + [ + 0.10623778579211848 + ] + ], + [ + [ + 0.09674034260551785 + ] + ], + [ + [ + 0.09280312347382377 + ] + ] + ] + } +} \ No newline at end of file diff --git a/assets/examples/bridge_lerobot_v3/meta/tasks.parquet b/assets/examples/bridge_lerobot_v3/meta/tasks.parquet new file mode 100644 index 0000000000000000000000000000000000000000..a872c0b521e80e9c255e78f1bd05cc740ade7e40 Binary files /dev/null and b/assets/examples/bridge_lerobot_v3/meta/tasks.parquet differ diff --git a/assets/examples/bridge_lerobot_v3/videos/observation.images.image_0/chunk-000/file-000.mp4 b/assets/examples/bridge_lerobot_v3/videos/observation.images.image_0/chunk-000/file-000.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..9930e268df26c27ccdb8437d5abcfcbc4fa725f6 --- /dev/null +++ b/assets/examples/bridge_lerobot_v3/videos/observation.images.image_0/chunk-000/file-000.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d8c90ded6c64a9999f8d79e986a8817617342b1a97db0178ccff5533a7334386 +size 171313 diff --git a/assets/examples/droid_plus_lerobot_640x360_20260412/success/data/chunk-000/file-000.parquet b/assets/examples/droid_plus_lerobot_640x360_20260412/success/data/chunk-000/file-000.parquet new file mode 100644 index 0000000000000000000000000000000000000000..50b64ce771c22f89a579ff0f4fcc9c6b314be1d4 --- /dev/null +++ b/assets/examples/droid_plus_lerobot_640x360_20260412/success/data/chunk-000/file-000.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8726a2a7eafaa6351d61b1f7ce114f764e65d6c212a5350f9a2894f9289c01dc +size 168056 diff --git a/assets/examples/droid_plus_lerobot_640x360_20260412/success/meta/episodes/chunk-000/file-000.parquet b/assets/examples/droid_plus_lerobot_640x360_20260412/success/meta/episodes/chunk-000/file-000.parquet new file mode 100644 index 0000000000000000000000000000000000000000..b3292ec2263d7497c3f5f7f4457e3bfd84d7b085 --- /dev/null +++ b/assets/examples/droid_plus_lerobot_640x360_20260412/success/meta/episodes/chunk-000/file-000.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:473efcf65c4ce7af0afb0e54e304db7d6b79bccbf8d31b2b4e014d992316fe92 +size 212825 diff --git a/assets/examples/droid_plus_lerobot_640x360_20260412/success/meta/info.json b/assets/examples/droid_plus_lerobot_640x360_20260412/success/meta/info.json new file mode 100644 index 0000000000000000000000000000000000000000..a88521957fb467a761baad9c24dbcc453587a96b --- /dev/null +++ b/assets/examples/droid_plus_lerobot_640x360_20260412/success/meta/info.json @@ -0,0 +1,179 @@ +{ + "codebase_version": "v3.0", + "robot_type": "panda", + "total_episodes": 1, + "total_frames": 471, + "total_tasks": 1, + "chunks_size": 1000, + "data_files_size_in_mb": 100, + "video_files_size_in_mb": 200, + "fps": 15, + "splits": { + "train": "0:1" + }, + "data_path": "data/chunk-{chunk_index:03d}/file-{file_index:03d}.parquet", + "video_path": "videos/{video_key}/chunk-{chunk_index:03d}/file-{file_index:03d}.mp4", + "features": { + "observation.image.exterior_image_1_left": { + "dtype": "video", + "shape": [ + 360, + 640, + 3 + ], + "info": { + "video.height": 360, + "video.width": 640, + "video.codec": "av1", + "video.pix_fmt": "yuv420p", + "video.is_depth_map": false, + "video.fps": 15, + "video.channels": 3, + "has_audio": false + } + }, + "observation.image.exterior_image_2_left": { + "dtype": "video", + "shape": [ + 360, + 640, + 3 + ], + "info": { + "video.height": 360, + "video.width": 640, + "video.codec": "av1", + "video.pix_fmt": "yuv420p", + "video.is_depth_map": false, + "video.fps": 15, + "video.channels": 3, + "has_audio": false + } + }, + "observation.image.wrist_image_left": { + "dtype": "video", + "shape": [ + 360, + 640, + 3 + ], + "info": { + "video.height": 360, + "video.width": 640, + "video.codec": "av1", + "video.pix_fmt": "yuv420p", + "video.is_depth_map": false, + "video.fps": 15, + "video.channels": 3, + "has_audio": false + } + }, + "observation.state.joint_positions": { + "dtype": "float32", + "shape": [ + 7 + ] + }, + "observation.state.joint_velocities": { + "dtype": "float32", + "shape": [ + 7 + ] + }, + "observation.state.joint_torques_computed": { + "dtype": "float32", + "shape": [ + 7 + ] + }, + "observation.state.motor_torques_measured": { + "dtype": "float32", + "shape": [ + 7 + ] + }, + "observation.state.cartesian_position": { + "dtype": "float32", + "shape": [ + 6 + ] + }, + "observation.state.gripper_position": { + "dtype": "float32", + "shape": [ + 1 + ] + }, + "action.joint_position": { + "dtype": "float32", + "shape": [ + 7 + ] + }, + "action.joint_velocity": { + "dtype": "float32", + "shape": [ + 7 + ] + }, + "action.cartesian_position": { + "dtype": "float32", + "shape": [ + 6 + ] + }, + "action.cartesian_velocity": { + "dtype": "float32", + "shape": [ + 6 + ] + }, + "action.gripper_position": { + "dtype": "float32", + "shape": [ + 1 + ] + }, + "action.gripper_velocity": { + "dtype": "float32", + "shape": [ + 1 + ] + }, + "timestamp": { + "dtype": "float32", + "shape": [ + 1 + ], + "names": null + }, + "frame_index": { + "dtype": "int64", + "shape": [ + 1 + ], + "names": null + }, + "episode_index": { + "dtype": "int64", + "shape": [ + 1 + ], + "names": null + }, + "index": { + "dtype": "int64", + "shape": [ + 1 + ], + "names": null + }, + "task_index": { + "dtype": "int64", + "shape": [ + 1 + ], + "names": null + } + } +} diff --git a/assets/examples/droid_plus_lerobot_640x360_20260412/success/meta/stats.json b/assets/examples/droid_plus_lerobot_640x360_20260412/success/meta/stats.json new file mode 100644 index 0000000000000000000000000000000000000000..479c0c016836ea9125e971944c08620f88f081b1 --- /dev/null +++ b/assets/examples/droid_plus_lerobot_640x360_20260412/success/meta/stats.json @@ -0,0 +1,1479 @@ +{ + "observation.state.cartesian_position": { + "min": [ + -0.22192564606666565, + -0.8099977970123291, + -0.24001094698905945, + -3.141592502593994, + -1.5703768730163574, + -3.14157772064209 + ], + "max": [ + 0.8575563430786133, + 0.8196876049041748, + 1.0111403465270996, + 3.1415927410125732, + 1.5684677362442017, + 3.1415927410125732 + ], + "mean": [ + 0.5196280976981249, + 0.0009853788756085775, + 0.32100291244511253, + 0.3187035548659042, + -0.09489115560178896, + -0.03782510194329433 + ], + "std": [ + 0.11966269381655047, + 0.1840951537741764, + 0.1660031327090243, + 2.9119070203353057, + 0.360529050389239, + 0.8159590967825275 + ], + "count": [ + 18691281 + ], + "q01": [ + 0.33624007223059466, + -0.18976536914494324, + 0.18393308966044905, + -2.7955397235198975, + -0.4950343184080683, + -0.8581685139966064 + ], + "q10": [ + 0.4017154337495113, + -0.14017804428073918, + 0.20761156135127543, + -2.3101865748721733, + -0.3693534979187698, + -0.6230976434378469 + ], + "q50": [ + 0.5273264945852854, + 0.0008513312644672381, + 0.30696488716482756, + 0.4898543102775791, + -0.09435368128802955, + -0.0375054693853198 + ], + "q90": [ + 0.6203302057398535, + 0.14186639768892967, + 0.460628229890261, + 2.625476859924513, + 0.18064562575296228, + 0.5474490313234763 + ], + "q99": [ + 0.6482050048288891, + 0.1945358777163571, + 0.5423836319291491, + 2.9444948977740983, + 0.3144336584654846, + 0.785962951659008 + ] + }, + "observation.image.exterior_image_2_left": { + "min": [ + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ] + ], + "max": [ + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ] + ], + "mean": [ + [ + [ + 0.39698857248908037 + ] + ], + [ + [ + 0.3937475306292987 + ] + ], + [ + [ + 0.35555214316674105 + ] + ] + ], + "std": [ + [ + [ + 0.061672021015474934 + ] + ], + [ + [ + 0.06194416401814127 + ] + ], + [ + [ + 0.07588382954177514 + ] + ] + ], + "count": [ + 6215443 + ], + "q01": [ + [ + [ + 0.012687200764395137 + ] + ], + [ + [ + 0.015487369328871509 + ] + ], + [ + [ + 0.0076571378838845875 + ] + ] + ], + "q10": [ + [ + [ + 0.08111056896217507 + ] + ], + [ + [ + 0.08284075636323286 + ] + ], + [ + [ + 0.06473367564152509 + ] + ] + ], + "q50": [ + [ + [ + 0.36832910582414286 + ] + ], + [ + [ + 0.3589757621010206 + ] + ], + [ + [ + 0.3108992482705161 + ] + ] + ], + "q90": [ + [ + [ + 0.7630344426080897 + ] + ], + [ + [ + 0.7623061364967888 + ] + ], + [ + [ + 0.7211189014908148 + ] + ] + ], + "q99": [ + [ + [ + 0.9261070922126955 + ] + ], + [ + [ + 0.940775088875296 + ] + ], + [ + [ + 0.9276931167688498 + ] + ] + ] + }, + "observation.image.wrist_image_left": { + "min": [ + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ] + ], + "max": [ + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ] + ], + "mean": [ + [ + [ + 0.39594309896648566 + ] + ], + [ + [ + 0.3836015788399831 + ] + ], + [ + [ + 0.32883697366271997 + ] + ] + ], + "std": [ + [ + [ + 0.08820112155555676 + ] + ], + [ + [ + 0.07983439022468844 + ] + ], + [ + [ + 0.09559483574519906 + ] + ] + ], + "count": [ + 6215443 + ], + "q01": [ + [ + [ + 0.0014113945006799314 + ] + ], + [ + [ + 0.00179868849642481 + ] + ], + [ + [ + 0.0015209398260128302 + ] + ] + ], + "q10": [ + [ + [ + 0.03525048252678373 + ] + ], + [ + [ + 0.035695954052051275 + ] + ], + [ + [ + 0.02578849513959022 + ] + ] + ], + "q50": [ + [ + [ + 0.40446845320818914 + ] + ], + [ + [ + 0.3797765310467597 + ] + ], + [ + [ + 0.30599089191797074 + ] + ] + ], + "q90": [ + [ + [ + 0.7497542348288407 + ] + ], + [ + [ + 0.7403067883982201 + ] + ], + [ + [ + 0.6716269838882366 + ] + ] + ], + "q99": [ + [ + [ + 0.9066662690066858 + ] + ], + [ + [ + 0.912195599992383 + ] + ], + [ + [ + 0.8757491027084656 + ] + ] + ] + }, + "observation.state.joint_velocities": { + "min": [ + -1.2325929403305054, + -1.1620159149169922, + -1.2910404205322266, + -1.1445194482803345, + -1.4311167001724243, + -1.8945889472961426, + -1.8736029863357544 + ], + "max": [ + 1.2808489799499512, + 1.1894278526306152, + 1.2651691436767578, + 1.0335216522216797, + 1.5209081172943115, + 1.4298126697540283, + 1.411964774131775 + ], + "mean": [ + 0.0007668096011207866, + 0.02928915365171192, + -0.0008063308920928154, + 0.016429417973647484, + -0.0015627907447299401, + 0.015991573555231696, + 0.0032758998234802173 + ], + "std": [ + 0.13515408974183327, + 0.2140052912241772, + 0.13556597382102004, + 0.18811877819383568, + 0.1867162168430174, + 0.21122018690081104, + 0.21438512383397482 + ], + "count": [ + 18691281 + ], + "q01": [ + -0.34629224272983733, + -0.4723289554009115, + -0.34824012860091785, + -0.45490254978797284, + -0.4973926538063903, + -0.5160135572878216, + -0.5645107826901703 + ], + "q10": [ + -0.11734571052638743, + -0.21926666450125706, + -0.116485136067324, + -0.18684185966035827, + -0.17172595693671794, + -0.18244989566737269, + -0.20481833845700168 + ], + "q50": [ + 0.00022609332018521527, + 0.01429435363721013, + -0.00022322329741366394, + 0.007950081860874253, + -0.0002005335566592241, + 0.0009510218348768809, + 0.0009504778402937328 + ], + "q90": [ + 0.11891803503242757, + 0.2756342521512834, + 0.11379391555507393, + 0.220554289191697, + 0.16409735451468954, + 0.24523778353038594, + 0.21529678507501568 + ], + "q99": [ + 0.34147168118681376, + 0.5228120580985741, + 0.3516862162535885, + 0.43597715991320773, + 0.4956068911281174, + 0.5959691983814939, + 0.5489515881695498 + ] + }, + "observation.state.gripper_position": { + "min": [ + 0.0 + ], + "max": [ + 1.0 + ], + "mean": [ + 0.3778461710802597 + ], + "std": [ + 0.40871666834322623 + ], + "count": [ + 18691281 + ], + "q01": [ + 3.773488006398992e-05 + ], + "q10": [ + 0.010282849615100587 + ], + "q50": [ + 0.3296462467631541 + ], + "q90": [ + 0.7898515831023881 + ], + "q99": [ + 0.8234262665263168 + ] + }, + "task_index": { + "min": [ + 0 + ], + "max": [ + 17193 + ], + "mean": [ + 3306.827166046032 + ], + "std": [ + 4013.6426122382063 + ], + "count": [ + 18691281 + ], + "q01": [ + 3306.827166046032 + ], + "q10": [ + 3306.827166046032 + ], + "q50": [ + 3306.827166046032 + ], + "q90": [ + 3306.8271660460323 + ], + "q99": [ + 3306.8271660460323 + ] + }, + "action.joint_position": { + "min": [ + -2.781099557876587, + -1.647990107536316, + -2.772181749343872, + -2.9508564472198486, + -2.7826988697052, + 0.17518290877342224, + -2.901715040206909 + ], + "max": [ + 2.751160144805908, + 1.6689813137054443, + 2.769918203353882, + -0.21164260804653168, + 2.781451463699341, + 4.402013778686523, + 2.90183162689209 + ], + "mean": [ + 0.013199600302419347, + 0.24892700740181023, + -0.01293894075853087, + -2.018944157148896, + -0.04106824765025123, + 2.342938950502355, + 0.0623517051785903 + ], + "std": [ + 0.35347317324885785, + 0.5065376421473036, + 0.31662624358528346, + 0.5059683232860253, + 0.5498160977741493, + 0.47372670446560544, + 0.7925113426977689 + ], + "count": [ + 18691281 + ], + "q01": [ + -0.36044010782074737, + -0.6135316974597613, + -0.385181357782481, + -2.5957739609803463, + -0.6027203309453739, + 1.6828812378015896, + -0.6693693583677074 + ], + "q10": [ + -0.23459411447816506, + -0.2627565082526972, + -0.23944974213612572, + -2.4457957966659634, + -0.4243207013452144, + 1.9273194422573392, + -0.4622766051982292 + ], + "q50": [ + 0.009292829825423342, + 0.3014828460271428, + -0.011381819469281053, + -2.0281789913112007, + -0.03687058046149728, + 2.3593059403388486, + 0.06060105749585953 + ], + "q90": [ + 0.26578901397123483, + 0.658817845502543, + 0.21073156426598516, + -1.5823832781172136, + 0.3334117743292958, + 2.7236675646162176, + 0.5875851356970185 + ], + "q99": [ + 0.40981370808200224, + 0.7767221193137215, + 0.347007058174135, + -1.4263037393422948, + 0.5015067841267811, + 2.8618039285988606, + 0.801324502776132 + ] + }, + "action.gripper_position": { + "min": [ + 0.0 + ], + "max": [ + 1.0 + ], + "mean": [ + 0.418297932839273 + ], + "std": [ + 0.4425579088701078 + ], + "count": [ + 18691281 + ], + "q01": [ + 0.00019078585392472987 + ], + "q10": [ + 0.010803643046073442 + ], + "q50": [ + 0.35138024039898136 + ], + "q90": [ + 0.8835301288793914 + ], + "q99": [ + 0.9048730067515455 + ] + }, + "observation.state.motor_torques_measured": { + "min": [ + -25.94832420349121, + -87.83673858642578, + -44.32796096801758, + -16.94495391845703, + -12.420953750610352, + -13.297513008117676, + -6.907970428466797 + ], + "max": [ + 26.754270553588867, + 64.0811538696289, + 50.10732650756836, + 44.767879486083984, + 12.776189804077148, + 15.945478439331055, + 7.04659366607666 + ], + "mean": [ + -0.09045047201312431, + -34.29667075739162, + -0.1185023310644514, + 20.94341909516319, + 0.5291787647890451, + 2.2707021502402833, + 0.013084365002168205 + ], + "std": [ + 1.148625708486322, + 14.784722430062418, + 4.243052099757267, + 4.132280668526913, + 0.7285612021114827, + 1.1053276390348445, + 0.2584544041576275 + ], + "count": [ + 18691281 + ], + "q01": [ + -2.175235539369352, + -49.377647248011534, + -5.826520769201629, + 15.149840095313714, + -0.6673080586285703, + 0.5264886278859034, + -0.3662641382413548 + ], + "q10": [ + -0.9983434446865149, + -45.986515490260174, + -3.458525153816551, + 17.381327260157597, + -0.22691314403367593, + 1.2250490392882252, + -0.25615728114593317 + ], + "q50": [ + -0.0860637464904619, + -36.16392208425017, + -0.08149806138187557, + 21.153030167693032, + 0.5418284713112982, + 2.345815182745681, + 0.019068463717365012 + ], + "q90": [ + 0.8025424046639105, + -18.79532275126766, + 3.138285404521963, + 24.165852188119906, + 1.2618411713323243, + 3.180750154588862, + 0.2733030996939559 + ], + "q99": [ + 1.9839008890842533, + -8.84785670251801, + 5.410357341149311, + 25.550521752397493, + 1.6461261861240115, + 3.6552713771874608, + 0.3841125363687029 + ] + }, + "observation.state.joint_positions": { + "min": [ + -2.664970874786377, + -1.6156227588653564, + -2.680800676345825, + -2.9055848121643066, + -2.6705946922302246, + 0.24893812835216522, + -2.761866807937622 + ], + "max": [ + 2.6687583923339844, + 1.5840554237365723, + 2.6957037448883057, + -0.31610623002052307, + 2.6621792316436768, + 4.28157901763916, + 2.755643367767334 + ], + "mean": [ + 0.013791949786537994, + 0.24427557830341348, + -0.01318882777251663, + -2.026164415286467, + -0.0411291928767819, + 2.341849359205603, + 0.06125256477512789 + ], + "std": [ + 0.3502433042554258, + 0.5105651212980146, + 0.31516304468241213, + 0.5018439625812248, + 0.5442562422655662, + 0.4701331203619676, + 0.7865961326524101 + ], + "count": [ + 18691281 + ], + "q01": [ + -0.35221861487232076, + -0.6151462496261719, + -0.3804700767197909, + -2.5923478694921736, + -0.5854883979097063, + 1.6903565635957598, + -0.6544480001387185 + ], + "q10": [ + -0.23285924999802607, + -0.29010091029711904, + -0.24030863436683778, + -2.457366233444359, + -0.41975775565802553, + 1.9203418059194497, + -0.4623098906029416 + ], + "q50": [ + 0.009929714705934432, + 0.30511215625383054, + -0.01189937068433103, + -2.0319206082102745, + -0.03707056123462397, + 2.361159521249432, + 0.05984592351049138 + ], + "q90": [ + 0.26522281891194416, + 0.6558676369030764, + 0.21141054864193545, + -1.5921684408574053, + 0.3291723967052105, + 2.7202117083474326, + 0.5851309623636093 + ], + "q99": [ + 0.40319962215851335, + 0.7619416500985984, + 0.34202418876395896, + -1.447520622332787, + 0.48483662716734677, + 2.8473429714186076, + 0.7846589029264255 + ] + }, + "index": { + "min": [ + 0 + ], + "max": [ + 5272516 + ], + "mean": [ + 1310808.4007145364 + ], + "std": [ + 1287934.685416825 + ], + "count": [ + 18691281 + ], + "q01": [ + 1310329.4218393876 + ], + "q10": [ + 1310417.362258262 + ], + "q50": [ + 1310808.2273377946 + ], + "q90": [ + 1311199.3589162764 + ], + "q99": [ + 1311287.371586794 + ] + }, + "frame_index": { + "min": [ + 0 + ], + "max": [ + 34362 + ], + "mean": [ + 488.24993787210207 + ], + "std": [ + 1513.8511839233154 + ], + "count": [ + 18691281 + ], + "q01": [ + 9.271062717800033 + ], + "q10": [ + 97.2114816012389 + ], + "q50": [ + 488.0572185069863 + ], + "q90": [ + 879.2007030672643 + ], + "q99": [ + 967.2198291484269 + ] + }, + "timestamp": { + "min": [ + 0.0 + ], + "max": [ + 2290.8 + ], + "mean": [ + 32.54999585814025 + ], + "std": [ + 100.92341226155439 + ], + "count": [ + 18691281 + ], + "q01": [ + 0.6180708477615872 + ], + "q10": [ + 6.480765440007698 + ], + "q50": [ + 32.53720037807416 + ], + "q90": [ + 58.61338020455933 + ], + "q99": [ + 64.48132194332018 + ] + }, + "action.gripper_velocity": { + "min": [ + -1.0 + ], + "max": [ + 1.0 + ], + "mean": [ + 0.15989621464462586 + ], + "std": [ + 0.4462997670679963 + ], + "count": [ + 18691281 + ], + "q01": [ + -0.9094265350632038 + ], + "q10": [ + -0.10910863026177213 + ], + "q50": [ + 0.09722019469380247 + ], + "q90": [ + 0.5471264388836043 + ], + "q99": [ + 0.9430653164581466 + ] + }, + "episode_index": { + "min": [ + 0 + ], + "max": [ + 18101 + ], + "mean": [ + 4006.2060856075004 + ], + "std": [ + 4159.4654856685065 + ], + "count": [ + 18691281 + ], + "q01": [ + 4006.2060856075004 + ], + "q10": [ + 4006.2060856075004 + ], + "q50": [ + 4006.2060856075004 + ], + "q90": [ + 4006.2060856075004 + ], + "q99": [ + 4006.2060856075004 + ] + }, + "observation.image.exterior_image_1_left": { + "min": [ + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ] + ], + "max": [ + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ] + ], + "mean": [ + [ + [ + 0.3935929122066613 + ] + ], + [ + [ + 0.3885335475030728 + ] + ], + [ + [ + 0.3515364706827202 + ] + ] + ], + "std": [ + [ + [ + 0.06012316665802346 + ] + ], + [ + [ + 0.061141097206828955 + ] + ], + [ + [ + 0.07413341557853112 + ] + ] + ], + "count": [ + 6215443 + ], + "q01": [ + [ + [ + 0.012953224073805667 + ] + ], + [ + [ + 0.015152780827787433 + ] + ], + [ + [ + 0.00861166638453724 + ] + ] + ], + "q10": [ + [ + [ + 0.0837700067775019 + ] + ], + [ + [ + 0.08480807433136518 + ] + ], + [ + [ + 0.06764227065612026 + ] + ] + ], + "q50": [ + [ + [ + 0.3558359164636593 + ] + ], + [ + [ + 0.34596424611402693 + ] + ], + [ + [ + 0.3007029392584655 + ] + ] + ], + "q90": [ + [ + [ + 0.7677290626835452 + ] + ], + [ + [ + 0.7620642782848648 + ] + ], + [ + [ + 0.7224838451115285 + ] + ] + ], + "q99": [ + [ + [ + 0.9249874509600575 + ] + ], + [ + [ + 0.9375189969046649 + ] + ], + [ + [ + 0.9227459073014876 + ] + ] + ] + }, + "observation.state.joint_torques_computed": { + "min": [ + -26.771318435668945, + -36.63962936401367, + -26.350133895874023, + -22.278278350830078, + -12.59711742401123, + -9.927318572998047, + -4.382072925567627 + ], + "max": [ + 32.96823501586914, + 35.30547332763672, + 26.816661834716797, + 23.059751510620117, + 12.070505142211914, + 12.110977172851562, + 5.327917575836182 + ], + "mean": [ + -0.08512072409867738, + -0.9065801664123562, + -0.029602630556266114, + 0.6316930784312421, + 0.028903000698396318, + 0.08252977585512208, + 0.01828691355405112 + ], + "std": [ + 1.340606388276152, + 2.159151088702341, + 1.2868917133427562, + 1.6442633846848522, + 0.8135979162429936, + 0.7703853679967682, + 0.382176611925247 + ], + "count": [ + 18691281 + ], + "q01": [ + -2.7177552872546067, + -4.904378796313158, + -2.5081315091150618, + -2.5720827384983997, + -1.4192874231095336, + -1.3427410438961, + -0.6555645736902543 + ], + "q10": [ + -1.310899968811493, + -2.958179523656676, + -1.1391459525021743, + -0.9565310957849424, + -0.9177959289601971, + -0.7609331206774717, + -0.4078647257442235 + ], + "q50": [ + -0.07505141962627339, + -0.8578361638526507, + -0.036068823539492326, + 0.7534932454207656, + 0.023865668207664566, + 0.11707451898045382, + 0.02569371284470846 + ], + "q90": [ + 1.117567076531323, + 1.0702269684319032, + 1.0826402570669635, + 2.032942384706255, + 0.9798880304673434, + 0.8709803494219956, + 0.4328364981780825 + ], + "q99": [ + 2.523812308049357, + 3.3266416108309964, + 2.4765324795080836, + 3.063502020941035, + 1.4644210715130928, + 1.419444457342673, + 0.6832162237967178 + ] + }, + "action.cartesian_velocity": { + "min": [ + -0.9999999403953552, + -0.9999951124191284, + -0.9999960660934448, + -0.9999980330467224, + -0.9999969601631165, + -0.9999998807907104 + ], + "max": [ + 0.9999998211860657, + 0.9999836087226868, + 0.9999973177909851, + 0.9999697208404541, + 0.9999954104423523, + 0.9999998807907104 + ], + "mean": [ + 0.022781586037321677, + -0.002642982246250131, + 0.019422232008431437, + 0.00385024695714588, + -0.030741170113786385, + -0.007221580743078788 + ], + "std": [ + 0.26331051677940037, + 0.1940336807939164, + 0.2320077278617576, + 0.2277295186145981, + 0.23565237235944003, + 0.30079523233833466 + ], + "count": [ + 18691281 + ], + "q01": [ + -0.5621750592318072, + -0.44066103347818825, + -0.410103508551534, + -0.5074656798841014, + -0.560176623050948, + -0.6746580861109687 + ], + "q10": [ + -0.2941247006847527, + -0.2165219671216752, + -0.22198569556668202, + -0.2539858711678539, + -0.3023348467162342, + -0.3539325707069309 + ], + "q50": [ + 0.03167925093387433, + -0.0005856818028497108, + -0.004049419762073512, + 0.0013363499102087182, + -0.024444778635266458, + -0.007232429448076757 + ], + "q90": [ + 0.30944639589367245, + 0.20765986892294552, + 0.3142771570510021, + 0.2638894712537269, + 0.23493938070144402, + 0.33997530700517126 + ], + "q99": [ + 0.5366988428269169, + 0.4283949455663026, + 0.577160869138631, + 0.5241492686975527, + 0.49812821195535767, + 0.6743231345822654 + ] + }, + "action.joint_velocity": { + "min": [ + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0 + ], + "max": [ + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0 + ], + "mean": [ + -0.0032264550712801845, + 0.013372541292925158, + 0.0015260425148475995, + 0.030577660060776682, + 0.000853369159829645, + -0.00030791045007205444, + 0.004324216188539675 + ], + "std": [ + 0.15738005716197367, + 0.29789431140641043, + 0.15267329933136972, + 0.2951536063397572, + 0.21853175444547254, + 0.23759831123238903, + 0.2589575509825406 + ], + "count": [ + 18691281 + ], + "q01": [ + -0.3720953716095578, + -0.6646666966410545, + -0.35537280317155545, + -0.6572392059107256, + -0.5079467301310688, + -0.535227394370355, + -0.6062588965469352 + ], + "q10": [ + -0.16553817347572433, + -0.3784961819192349, + -0.15030858713347564, + -0.3333324914423694, + -0.24241123224105304, + -0.27220791101727304, + -0.2930082969980739 + ], + "q50": [ + -0.0023710144415663072, + 0.031479031390672, + 0.0008277421317488518, + 0.039739343152067036, + 0.0011234450995665334, + -0.00572930901929865, + 0.0057179642953776874 + ], + "q90": [ + 0.1575076632205645, + 0.35038722521032933, + 0.15392283710015325, + 0.35867501730587226, + 0.24204228729362678, + 0.28206719744755376, + 0.2992755165736914 + ], + "q99": [ + 0.3584453109141214, + 0.6165426582109276, + 0.3650701572623211, + 0.596820860066475, + 0.5120463717033935, + 0.5652294579719821, + 0.5868785460202175 + ] + }, + "action.cartesian_position": { + "min": [ + -0.22296355664730072, + -0.8682119250297546, + -0.3079752027988434, + -3.141592502593994, + -1.570475697517395, + -3.1415903568267822 + ], + "max": [ + 0.9279670119285583, + 0.8648782968521118, + 1.074978232383728, + 3.1415927410125732, + 1.5702463388442993, + 3.1415891647338867 + ], + "mean": [ + 0.5217509054840234, + 0.0007883269900035715, + 0.3221104303446512, + 0.30714984136747414, + -0.09803336407639632, + -0.039177217145903054 + ], + "std": [ + 0.12071560629176353, + 0.18503476174786404, + 0.1666573340143361, + 2.9100072713264864, + 0.3633258858590838, + 0.8221708234450337 + ], + "count": [ + 18691281 + ], + "q01": [ + 0.3356816895292364, + -0.19133798527538426, + 0.1801999563371533, + -2.8323461535362444, + -0.5039531064948487, + -0.8696942196827485 + ], + "q10": [ + 0.40801413986337737, + -0.1395284239119436, + 0.2075567910938741, + -2.3230738137233806, + -0.3747761213529591, + -0.6251931005070784 + ], + "q50": [ + 0.5274814798968698, + 0.000745909687968284, + 0.31017238004165865, + 0.47620942748795536, + -0.09728429713123418, + -0.038704636643419714 + ], + "q90": [ + 0.6235519831628223, + 0.14058381794916908, + 0.4583311912346178, + 2.6281921722430055, + 0.1786755079522444, + 0.5456597094824605 + ], + "q99": [ + 0.6542487361445086, + 0.19523494988290416, + 0.5434926045583094, + 2.9609058856482395, + 0.31791269359900076, + 0.7944463373545845 + ] + } +} \ No newline at end of file diff --git a/assets/examples/droid_plus_lerobot_640x360_20260412/success/meta/tasks.parquet b/assets/examples/droid_plus_lerobot_640x360_20260412/success/meta/tasks.parquet new file mode 100644 index 0000000000000000000000000000000000000000..b9db7f91ff31d0e9b9dacae6dba2a8503c9ccf83 Binary files /dev/null and b/assets/examples/droid_plus_lerobot_640x360_20260412/success/meta/tasks.parquet differ diff --git a/assets/examples/droid_plus_lerobot_640x360_20260412/success/videos/observation.image.exterior_image_1_left/chunk-000/file-000.mp4 b/assets/examples/droid_plus_lerobot_640x360_20260412/success/videos/observation.image.exterior_image_1_left/chunk-000/file-000.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..136bac686e849f34cde3c14291badbaa11e284b2 --- /dev/null +++ b/assets/examples/droid_plus_lerobot_640x360_20260412/success/videos/observation.image.exterior_image_1_left/chunk-000/file-000.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fe8cd6fa9e095b557fb4cdf092899ebc28b9653ba8f9b29a745c71e5ae3e48b0 +size 269998 diff --git a/assets/examples/droid_plus_lerobot_640x360_20260412/success/videos/observation.image.exterior_image_2_left/chunk-000/file-000.mp4 b/assets/examples/droid_plus_lerobot_640x360_20260412/success/videos/observation.image.exterior_image_2_left/chunk-000/file-000.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..7037933f3ae8f4ab89d738a137c3f8be014d04f2 --- /dev/null +++ b/assets/examples/droid_plus_lerobot_640x360_20260412/success/videos/observation.image.exterior_image_2_left/chunk-000/file-000.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:afd7a52d61833996792f27150193a7c6cdefb201f3e2ee83f14415dbbc612a32 +size 200842 diff --git a/assets/examples/droid_plus_lerobot_640x360_20260412/success/videos/observation.image.wrist_image_left/chunk-000/file-000.mp4 b/assets/examples/droid_plus_lerobot_640x360_20260412/success/videos/observation.image.wrist_image_left/chunk-000/file-000.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..48f4763bb3d9e0850dbcede957af037e4825ccca --- /dev/null +++ b/assets/examples/droid_plus_lerobot_640x360_20260412/success/videos/observation.image.wrist_image_left/chunk-000/file-000.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:15ac775bcec935c07955c2aaa41c3834c3c846e2b1bc91bf3e0b9b7282733930 +size 316099 diff --git a/assets/examples/fastumi/fastumi_single_arm/pour_coke/data/chunk-000/file-000.parquet b/assets/examples/fastumi/fastumi_single_arm/pour_coke/data/chunk-000/file-000.parquet new file mode 100644 index 0000000000000000000000000000000000000000..6a61fa5cc6aea815ef7564f8d054b74ba46e499b Binary files /dev/null and b/assets/examples/fastumi/fastumi_single_arm/pour_coke/data/chunk-000/file-000.parquet differ diff --git a/assets/examples/fastumi/fastumi_single_arm/pour_coke/meta/episodes/chunk-000/file-000.parquet b/assets/examples/fastumi/fastumi_single_arm/pour_coke/meta/episodes/chunk-000/file-000.parquet new file mode 100644 index 0000000000000000000000000000000000000000..b5a9030ca61cbd0e6a212fc0e03e42bb11207fca Binary files /dev/null and b/assets/examples/fastumi/fastumi_single_arm/pour_coke/meta/episodes/chunk-000/file-000.parquet differ diff --git a/assets/examples/fastumi/fastumi_single_arm/pour_coke/meta/info.json b/assets/examples/fastumi/fastumi_single_arm/pour_coke/meta/info.json new file mode 100644 index 0000000000000000000000000000000000000000..70c21f1ea0a1f7c080a5503dcac80e83c7a890b3 --- /dev/null +++ b/assets/examples/fastumi/fastumi_single_arm/pour_coke/meta/info.json @@ -0,0 +1,113 @@ +{ + "codebase_version": "v3.0", + "robot_type": "XARM6", + "robot_setup_type": "single_arm", + "include_head_camera": false, + "include_body_camera": false, + "third_camera_num": 0, + "has_mirrors": false, + "total_episodes": 1, + "total_frames": 180, + "total_tasks": 1, + "data_files_size_in_mb": 100.0, + "video_files_size_in_mb": 200.0, + "fps": 20.0, + "splits": { + "train": "0:1" + }, + "data_path": "data/chunk-{chunk_index:03d}/file-{file_index:03d}.parquet", + "video_path": "videos/{video_key}/chunk-{chunk_index:03d}/file-{file_index:03d}.mp4", + "features": { + "timestamp": { + "dtype": "float32", + "shape": [ + 1 + ], + "names": null + }, + "frame_index": { + "dtype": "int64", + "shape": [ + 1 + ], + "names": null + }, + "episode_index": { + "dtype": "int64", + "shape": [ + 1 + ], + "names": null + }, + "index": { + "dtype": "int64", + "shape": [ + 1 + ], + "names": null + }, + "task_index": { + "dtype": "int64", + "shape": [ + 1 + ], + "names": null + }, + "observation.state.right_main_camera_trajectory_xyz_wxyz": { + "dtype": "float32", + "shape": [ + 7 + ], + "names": [ + "observation.state.right_main_camera_trajectory_xyz_wxyz_0", + "observation.state.right_main_camera_trajectory_xyz_wxyz_1", + "observation.state.right_main_camera_trajectory_xyz_wxyz_2", + "observation.state.right_main_camera_trajectory_xyz_wxyz_3", + "observation.state.right_main_camera_trajectory_xyz_wxyz_4", + "observation.state.right_main_camera_trajectory_xyz_wxyz_5", + "observation.state.right_main_camera_trajectory_xyz_wxyz_6" + ] + }, + "observation.state.right_gripper_width_m": { + "dtype": "float32", + "shape": [ + 1 + ], + "names": [ + "observation.state.right_gripper_width_m_0" + ] + }, + "observation.image.right_main_camera_rgb": { + "dtype": "video", + "shape": [ + 480, + 480, + 3 + ], + "names": [ + "height", + "width", + "channels" + ] + } + }, + "right_eef_pose_in_main_xyz_wxyz": [ + 0.0, + 0.08579999953508377, + 0.1454000025987625, + 1.0, + 0.0, + 0.0, + 0.0 + ], + "right_main_camera_raw_res": [ + 1080, + 1920 + ], + "right_main_camera_video_pipeline": "ffmpeg -f rawvideo -pix_fmt bgr24 -s {in_w}x{in_h} -r {fps} -i - -loop 1 -i {xpgm} -loop 1 -i {ypgm} -filter_complex '[0:v]format=yuv444p[v];[v][1:v][2:v]remap=format=color,crop={side}:{side},scale={out_w}:{out_h},format=yuv420p[out]' -map [out] -shortest -an -c:v av1_nvenc -preset p4 -cq 23 {output}", + "right_gripper_model": "FastUMI", + "right_gripper_width_m_max": [ + 0.08 + ], + "repo_id": "local/camx/fastumi/fastumi_single_arm/pour_coke" +} diff --git a/assets/examples/fastumi/fastumi_single_arm/pour_coke/meta/stats.json b/assets/examples/fastumi/fastumi_single_arm/pour_coke/meta/stats.json new file mode 100644 index 0000000000000000000000000000000000000000..2aaa8942cb39e8d4fb7171107f6d7cdbdbe85d79 --- /dev/null +++ b/assets/examples/fastumi/fastumi_single_arm/pour_coke/meta/stats.json @@ -0,0 +1,54 @@ +{ + "observation.state.right_gripper_width_m": { + "mean": [ + 0.062415022403001785 + ], + "std": [ + 0.014273382723331451 + ], + "min": [ + 0.04197647050023079 + ], + "max": [ + 0.07999999821186066 + ] + }, + "observation.state.right_main_camera_trajectory_xyz_wxyz": { + "mean": [ + 0.29477229714393616, + 0.17546765506267548, + -0.1128092110157013, + 0.14784009754657745, + 0.01722816191613674, + 0.144368514418602, + -0.025626657530665398 + ], + "std": [ + 0.16135473549365997, + 0.15001733601093292, + 0.1014970913529396, + 0.31992843747138977, + 0.6212483048439026, + 0.5223610401153564, + 0.4417937994003296 + ], + "min": [ + -0.19988380372524261, + -0.19237850606441498, + -0.40376341342926025, + -0.5746796727180481, + -0.6518781185150146, + -0.6542174816131592, + -0.5680083632469177 + ], + "max": [ + 0.5659647583961487, + 0.5889244675636292, + 0.11997988075017929, + 0.5790585875511169, + 0.8479742407798767, + 0.7905207872390747, + 0.6766778230667114 + ] + } +} \ No newline at end of file diff --git a/assets/examples/fastumi/fastumi_single_arm/pour_coke/meta/tasks.jsonl b/assets/examples/fastumi/fastumi_single_arm/pour_coke/meta/tasks.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..95e16b3970abbc53500c9664e6dc770988814217 --- /dev/null +++ b/assets/examples/fastumi/fastumi_single_arm/pour_coke/meta/tasks.jsonl @@ -0,0 +1,460 @@ +{"task_index": 0, "task": "pour_coke", "raw_video_dirs": ["/storage/hdd1/chiling/fastumi_data/raw/pour_coke_v0", "/storage/hdd1/chiling/fastumi_data/raw/pour_coke_v1", "/storage/hdd1/chiling/fastumi_data/raw/pour_coke_v2", "/storage/hdd1/chiling/fastumi_data/raw/pour_coke_v3", "/storage/hdd1/chiling/fastumi_data/raw/pour_coke_v4", "/storage/hdd1/chiling/fastumi_data/raw/pour_coke_v5", "/storage/hdd1/chiling/fastumi_data/raw/pour_coke_v6", "/storage/hdd1/chiling/fastumi_data/raw/pour_coke_v7", "/storage/hdd1/chiling/fastumi_data/raw/pour_coke_v8", "/storage/hdd1/chiling/fastumi_data/raw/pour_coke_v9"]} +{"episode_idx": 0, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_1.hdf5"} +{"episode_idx": 1, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_2.hdf5"} +{"episode_idx": 2, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_3.hdf5"} +{"episode_idx": 3, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_4.hdf5"} +{"episode_idx": 4, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_5.hdf5"} +{"episode_idx": 5, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_6.hdf5"} +{"episode_idx": 6, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_7.hdf5"} +{"episode_idx": 7, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_8.hdf5"} +{"episode_idx": 8, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_9.hdf5"} +{"episode_idx": 9, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_10.hdf5"} +{"episode_idx": 10, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_11.hdf5"} +{"episode_idx": 11, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_12.hdf5"} +{"episode_idx": 12, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_13.hdf5"} +{"episode_idx": 13, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_14.hdf5"} +{"episode_idx": 14, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_15.hdf5"} +{"episode_idx": 15, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_16.hdf5"} +{"episode_idx": 16, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_17.hdf5"} +{"episode_idx": 17, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_18.hdf5"} +{"episode_idx": 18, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_19.hdf5"} +{"episode_idx": 19, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_20.hdf5"} +{"episode_idx": 20, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_21.hdf5"} +{"episode_idx": 21, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_22.hdf5"} +{"episode_idx": 22, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_23.hdf5"} +{"episode_idx": 23, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_24.hdf5"} +{"episode_idx": 24, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_25.hdf5"} +{"episode_idx": 25, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_26.hdf5"} +{"episode_idx": 26, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_27.hdf5"} +{"episode_idx": 27, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_28.hdf5"} +{"episode_idx": 28, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_29.hdf5"} +{"episode_idx": 29, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_30.hdf5"} +{"episode_idx": 30, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_31.hdf5"} +{"episode_idx": 31, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_32.hdf5"} +{"episode_idx": 32, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_33.hdf5"} +{"episode_idx": 33, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_34.hdf5"} +{"episode_idx": 34, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_35.hdf5"} +{"episode_idx": 35, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_36.hdf5"} +{"episode_idx": 36, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_37.hdf5"} +{"episode_idx": 37, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_38.hdf5"} +{"episode_idx": 38, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_39.hdf5"} +{"episode_idx": 39, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_40.hdf5"} +{"episode_idx": 40, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_41.hdf5"} +{"episode_idx": 41, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_42.hdf5"} +{"episode_idx": 42, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_43.hdf5"} +{"episode_idx": 43, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_44.hdf5"} +{"episode_idx": 44, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_45.hdf5"} +{"episode_idx": 45, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_46.hdf5"} +{"episode_idx": 46, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_47.hdf5"} +{"episode_idx": 47, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_48.hdf5"} +{"episode_idx": 48, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_49.hdf5"} +{"episode_idx": 49, "task": "pour_coke", "raw_path": "pour_coke_v0/episode_50.hdf5"} +{"episode_idx": 50, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_1.hdf5"} +{"episode_idx": 51, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_2.hdf5"} +{"episode_idx": 52, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_3.hdf5"} +{"episode_idx": 53, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_4.hdf5"} +{"episode_idx": 54, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_5.hdf5"} +{"episode_idx": 55, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_6.hdf5"} +{"episode_idx": 56, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_7.hdf5"} +{"episode_idx": 57, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_8.hdf5"} +{"episode_idx": 58, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_9.hdf5"} +{"episode_idx": 59, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_10.hdf5"} +{"episode_idx": 60, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_11.hdf5"} +{"episode_idx": 61, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_12.hdf5"} +{"episode_idx": 62, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_13.hdf5"} +{"episode_idx": 63, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_14.hdf5"} +{"episode_idx": 64, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_15.hdf5"} +{"episode_idx": 65, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_16.hdf5"} +{"episode_idx": 66, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_17.hdf5"} +{"episode_idx": 67, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_18.hdf5"} +{"episode_idx": 68, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_19.hdf5"} +{"episode_idx": 69, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_20.hdf5"} +{"episode_idx": 70, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_21.hdf5"} +{"episode_idx": 71, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_22.hdf5"} +{"episode_idx": 72, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_23.hdf5"} +{"episode_idx": 73, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_24.hdf5"} +{"episode_idx": 74, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_25.hdf5"} +{"episode_idx": 75, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_26.hdf5"} +{"episode_idx": 76, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_27.hdf5"} +{"episode_idx": 77, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_28.hdf5"} +{"episode_idx": 78, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_29.hdf5"} +{"episode_idx": 79, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_30.hdf5"} +{"episode_idx": 80, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_31.hdf5"} +{"episode_idx": 81, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_32.hdf5"} +{"episode_idx": 82, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_33.hdf5"} +{"episode_idx": 83, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_34.hdf5"} +{"episode_idx": 84, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_35.hdf5"} +{"episode_idx": 85, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_36.hdf5"} +{"episode_idx": 86, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_37.hdf5"} +{"episode_idx": 87, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_38.hdf5"} +{"episode_idx": 88, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_39.hdf5"} +{"episode_idx": 89, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_40.hdf5"} +{"episode_idx": 90, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_41.hdf5"} +{"episode_idx": 91, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_42.hdf5"} +{"episode_idx": 92, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_43.hdf5"} +{"episode_idx": 93, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_44.hdf5"} +{"episode_idx": 94, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_45.hdf5"} +{"episode_idx": 95, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_46.hdf5"} +{"episode_idx": 96, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_47.hdf5"} +{"episode_idx": 97, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_48.hdf5"} +{"episode_idx": 98, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_49.hdf5"} +{"episode_idx": 99, "task": "pour_coke", "raw_path": "pour_coke_v1/episode_50.hdf5"} +{"episode_idx": 100, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_1.hdf5"} +{"episode_idx": 101, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_2.hdf5"} +{"episode_idx": 102, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_3.hdf5"} +{"episode_idx": 103, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_4.hdf5"} +{"episode_idx": 104, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_5.hdf5"} +{"episode_idx": 105, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_6.hdf5"} +{"episode_idx": 106, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_7.hdf5"} +{"episode_idx": 107, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_8.hdf5"} +{"episode_idx": 108, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_9.hdf5"} +{"episode_idx": 109, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_10.hdf5"} +{"episode_idx": 110, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_11.hdf5"} +{"episode_idx": 111, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_12.hdf5"} +{"episode_idx": 112, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_13.hdf5"} +{"episode_idx": 113, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_14.hdf5"} +{"episode_idx": 114, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_15.hdf5"} +{"episode_idx": 115, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_16.hdf5"} +{"episode_idx": 116, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_17.hdf5"} +{"episode_idx": 117, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_18.hdf5"} +{"episode_idx": 118, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_19.hdf5"} +{"episode_idx": 119, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_20.hdf5"} +{"episode_idx": 120, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_21.hdf5"} +{"episode_idx": 121, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_22.hdf5"} +{"episode_idx": 122, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_23.hdf5"} +{"episode_idx": 123, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_24.hdf5"} +{"episode_idx": 124, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_25.hdf5"} +{"episode_idx": 125, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_26.hdf5"} +{"episode_idx": 126, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_27.hdf5"} +{"episode_idx": 127, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_28.hdf5"} +{"episode_idx": 128, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_29.hdf5"} +{"episode_idx": 129, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_30.hdf5"} +{"episode_idx": 130, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_31.hdf5"} +{"episode_idx": 131, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_32.hdf5"} +{"episode_idx": 132, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_33.hdf5"} +{"episode_idx": 133, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_34.hdf5"} +{"episode_idx": 134, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_35.hdf5"} +{"episode_idx": 135, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_36.hdf5"} +{"episode_idx": 136, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_37.hdf5"} +{"episode_idx": 137, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_38.hdf5"} +{"episode_idx": 138, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_39.hdf5"} +{"episode_idx": 139, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_40.hdf5"} +{"episode_idx": 140, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_41.hdf5"} +{"episode_idx": 141, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_42.hdf5"} +{"episode_idx": 142, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_43.hdf5"} +{"episode_idx": 143, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_44.hdf5"} +{"episode_idx": 144, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_45.hdf5"} +{"episode_idx": 145, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_46.hdf5"} +{"episode_idx": 146, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_47.hdf5"} +{"episode_idx": 147, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_48.hdf5"} +{"episode_idx": 148, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_49.hdf5"} +{"episode_idx": 149, "task": "pour_coke", "raw_path": "pour_coke_v2/episode_50.hdf5"} +{"episode_idx": 150, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_1.hdf5"} +{"episode_idx": 151, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_2.hdf5"} +{"episode_idx": 152, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_3.hdf5"} +{"episode_idx": 153, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_4.hdf5"} +{"episode_idx": 154, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_5.hdf5"} +{"episode_idx": 155, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_6.hdf5"} +{"episode_idx": 156, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_7.hdf5"} +{"episode_idx": 157, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_8.hdf5"} +{"episode_idx": 158, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_9.hdf5"} +{"episode_idx": 159, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_10.hdf5"} +{"episode_idx": 160, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_11.hdf5"} +{"episode_idx": 161, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_12.hdf5"} +{"episode_idx": 162, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_13.hdf5"} +{"episode_idx": 163, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_14.hdf5"} +{"episode_idx": 164, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_15.hdf5"} +{"episode_idx": 165, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_16.hdf5"} +{"episode_idx": 166, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_17.hdf5"} +{"episode_idx": 167, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_18.hdf5"} +{"episode_idx": 168, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_19.hdf5"} +{"episode_idx": 169, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_20.hdf5"} +{"episode_idx": 170, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_21.hdf5"} +{"episode_idx": 171, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_22.hdf5"} +{"episode_idx": 172, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_23.hdf5"} +{"episode_idx": 173, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_24.hdf5"} +{"episode_idx": 174, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_25.hdf5"} +{"episode_idx": 175, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_26.hdf5"} +{"episode_idx": 176, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_27.hdf5"} +{"episode_idx": 177, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_28.hdf5"} +{"episode_idx": 178, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_29.hdf5"} +{"episode_idx": 179, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_30.hdf5"} +{"episode_idx": 180, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_31.hdf5"} +{"episode_idx": 181, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_32.hdf5"} +{"episode_idx": 182, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_33.hdf5"} +{"episode_idx": 183, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_34.hdf5"} +{"episode_idx": 184, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_35.hdf5"} +{"episode_idx": 185, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_36.hdf5"} +{"episode_idx": 186, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_37.hdf5"} +{"episode_idx": 187, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_38.hdf5"} +{"episode_idx": 188, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_39.hdf5"} +{"episode_idx": 189, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_40.hdf5"} +{"episode_idx": 190, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_41.hdf5"} +{"episode_idx": 191, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_42.hdf5"} +{"episode_idx": 192, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_43.hdf5"} +{"episode_idx": 193, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_44.hdf5"} +{"episode_idx": 194, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_45.hdf5"} +{"episode_idx": 195, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_46.hdf5"} +{"episode_idx": 196, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_47.hdf5"} +{"episode_idx": 197, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_48.hdf5"} +{"episode_idx": 198, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_49.hdf5"} +{"episode_idx": 199, "task": "pour_coke", "raw_path": "pour_coke_v3/episode_50.hdf5"} +{"episode_idx": 200, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_1.hdf5"} +{"episode_idx": 201, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_2.hdf5"} +{"episode_idx": 202, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_3.hdf5"} +{"episode_idx": 203, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_4.hdf5"} +{"episode_idx": 204, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_5.hdf5"} +{"episode_idx": 205, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_6.hdf5"} +{"episode_idx": 206, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_7.hdf5"} +{"episode_idx": 207, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_8.hdf5"} +{"episode_idx": 208, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_9.hdf5"} +{"episode_idx": 209, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_10.hdf5"} +{"episode_idx": 210, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_11.hdf5"} +{"episode_idx": 211, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_12.hdf5"} +{"episode_idx": 212, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_13.hdf5"} +{"episode_idx": 213, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_14.hdf5"} +{"episode_idx": 214, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_15.hdf5"} +{"episode_idx": 215, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_16.hdf5"} +{"episode_idx": 216, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_17.hdf5"} +{"episode_idx": 217, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_18.hdf5"} +{"episode_idx": 218, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_19.hdf5"} +{"episode_idx": 219, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_20.hdf5"} +{"episode_idx": 220, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_21.hdf5"} +{"episode_idx": 221, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_22.hdf5"} +{"episode_idx": 222, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_23.hdf5"} +{"episode_idx": 223, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_24.hdf5"} +{"episode_idx": 224, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_25.hdf5"} +{"episode_idx": 225, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_26.hdf5"} +{"episode_idx": 226, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_27.hdf5"} +{"episode_idx": 227, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_28.hdf5"} +{"episode_idx": 228, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_29.hdf5"} +{"episode_idx": 229, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_30.hdf5"} +{"episode_idx": 230, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_31.hdf5"} +{"episode_idx": 231, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_32.hdf5"} +{"episode_idx": 232, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_33.hdf5"} +{"episode_idx": 233, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_34.hdf5"} +{"episode_idx": 234, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_35.hdf5"} +{"episode_idx": 235, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_36.hdf5"} +{"episode_idx": 236, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_37.hdf5"} +{"episode_idx": 237, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_38.hdf5"} +{"episode_idx": 238, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_39.hdf5"} +{"episode_idx": 239, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_40.hdf5"} +{"episode_idx": 240, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_41.hdf5"} +{"episode_idx": 241, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_42.hdf5"} +{"episode_idx": 242, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_43.hdf5"} +{"episode_idx": 243, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_44.hdf5"} +{"episode_idx": 244, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_45.hdf5"} +{"episode_idx": 245, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_46.hdf5"} +{"episode_idx": 246, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_47.hdf5"} +{"episode_idx": 247, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_48.hdf5"} +{"episode_idx": 248, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_49.hdf5"} +{"episode_idx": 249, "task": "pour_coke", "raw_path": "pour_coke_v4/episode_50.hdf5"} +{"episode_idx": 250, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_1.hdf5"} +{"episode_idx": 251, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_2.hdf5"} +{"episode_idx": 252, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_3.hdf5"} +{"episode_idx": 253, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_4.hdf5"} +{"episode_idx": 254, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_5.hdf5"} +{"episode_idx": 255, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_6.hdf5"} +{"episode_idx": 256, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_7.hdf5"} +{"episode_idx": 257, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_8.hdf5"} +{"episode_idx": 258, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_9.hdf5"} +{"episode_idx": 259, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_10.hdf5"} +{"episode_idx": 260, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_11.hdf5"} +{"episode_idx": 261, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_12.hdf5"} +{"episode_idx": 262, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_13.hdf5"} +{"episode_idx": 263, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_14.hdf5"} +{"episode_idx": 264, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_15.hdf5"} +{"episode_idx": 265, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_16.hdf5"} +{"episode_idx": 266, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_17.hdf5"} +{"episode_idx": 267, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_18.hdf5"} +{"episode_idx": 268, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_19.hdf5"} +{"episode_idx": 269, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_20.hdf5"} +{"episode_idx": 270, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_21.hdf5"} +{"episode_idx": 271, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_22.hdf5"} +{"episode_idx": 272, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_23.hdf5"} +{"episode_idx": 273, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_24.hdf5"} +{"episode_idx": 274, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_25.hdf5"} +{"episode_idx": 275, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_26.hdf5"} +{"episode_idx": 276, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_27.hdf5"} +{"episode_idx": 277, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_28.hdf5"} +{"episode_idx": 278, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_29.hdf5"} +{"episode_idx": 279, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_30.hdf5"} +{"episode_idx": 280, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_31.hdf5"} +{"episode_idx": 281, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_32.hdf5"} +{"episode_idx": 282, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_33.hdf5"} +{"episode_idx": 283, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_34.hdf5"} +{"episode_idx": 284, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_35.hdf5"} +{"episode_idx": 285, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_36.hdf5"} +{"episode_idx": 286, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_37.hdf5"} +{"episode_idx": 287, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_38.hdf5"} +{"episode_idx": 288, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_39.hdf5"} +{"episode_idx": 289, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_40.hdf5"} +{"episode_idx": 290, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_41.hdf5"} +{"episode_idx": 291, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_42.hdf5"} +{"episode_idx": 292, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_43.hdf5"} +{"episode_idx": 293, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_44.hdf5"} +{"episode_idx": 294, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_45.hdf5"} +{"episode_idx": 295, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_46.hdf5"} +{"episode_idx": 296, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_47.hdf5"} +{"episode_idx": 297, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_48.hdf5"} +{"episode_idx": 298, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_49.hdf5"} +{"episode_idx": 299, "task": "pour_coke", "raw_path": "pour_coke_v5/episode_50.hdf5"} +{"episode_idx": 300, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_1.hdf5"} +{"episode_idx": 301, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_2.hdf5"} +{"episode_idx": 302, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_3.hdf5"} +{"episode_idx": 303, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_4.hdf5"} +{"episode_idx": 304, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_5.hdf5"} +{"episode_idx": 305, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_6.hdf5"} +{"episode_idx": 306, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_7.hdf5"} +{"episode_idx": 307, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_8.hdf5"} +{"episode_idx": 308, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_9.hdf5"} +{"episode_idx": 309, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_10.hdf5"} +{"episode_idx": 310, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_11.hdf5"} +{"episode_idx": 311, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_12.hdf5"} +{"episode_idx": 312, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_13.hdf5"} +{"episode_idx": 313, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_14.hdf5"} +{"episode_idx": 314, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_15.hdf5"} +{"episode_idx": 315, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_16.hdf5"} +{"episode_idx": 316, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_17.hdf5"} +{"episode_idx": 317, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_18.hdf5"} +{"episode_idx": 318, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_19.hdf5"} +{"episode_idx": 319, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_20.hdf5"} +{"episode_idx": 320, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_21.hdf5"} +{"episode_idx": 321, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_22.hdf5"} +{"episode_idx": 322, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_23.hdf5"} +{"episode_idx": 323, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_24.hdf5"} +{"episode_idx": 324, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_25.hdf5"} +{"episode_idx": 325, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_26.hdf5"} +{"episode_idx": 326, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_27.hdf5"} +{"episode_idx": 327, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_28.hdf5"} +{"episode_idx": 328, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_29.hdf5"} +{"episode_idx": 329, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_30.hdf5"} +{"episode_idx": 330, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_31.hdf5"} +{"episode_idx": 331, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_32.hdf5"} +{"episode_idx": 332, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_33.hdf5"} +{"episode_idx": 333, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_34.hdf5"} +{"episode_idx": 334, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_35.hdf5"} +{"episode_idx": 335, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_36.hdf5"} +{"episode_idx": 336, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_37.hdf5"} +{"episode_idx": 337, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_38.hdf5"} +{"episode_idx": 338, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_39.hdf5"} +{"episode_idx": 339, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_40.hdf5"} +{"episode_idx": 340, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_41.hdf5"} +{"episode_idx": 341, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_42.hdf5"} +{"episode_idx": 342, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_43.hdf5"} +{"episode_idx": 343, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_44.hdf5"} +{"episode_idx": 344, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_45.hdf5"} +{"episode_idx": 345, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_46.hdf5"} +{"episode_idx": 346, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_47.hdf5"} +{"episode_idx": 347, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_48.hdf5"} +{"episode_idx": 348, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_49.hdf5"} +{"episode_idx": 349, "task": "pour_coke", "raw_path": "pour_coke_v6/episode_50.hdf5"} +{"episode_idx": 350, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_1.hdf5"} +{"episode_idx": 351, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_2.hdf5"} +{"episode_idx": 352, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_3.hdf5"} +{"episode_idx": 353, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_4.hdf5"} +{"episode_idx": 354, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_5.hdf5"} +{"episode_idx": 355, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_6.hdf5"} +{"episode_idx": 356, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_7.hdf5"} +{"episode_idx": 357, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_8.hdf5"} +{"episode_idx": 358, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_9.hdf5"} +{"episode_idx": 359, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_10.hdf5"} +{"episode_idx": 360, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_11.hdf5"} +{"episode_idx": 361, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_12.hdf5"} +{"episode_idx": 362, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_13.hdf5"} +{"episode_idx": 363, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_14.hdf5"} +{"episode_idx": 364, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_15.hdf5"} +{"episode_idx": 365, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_16.hdf5"} +{"episode_idx": 366, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_17.hdf5"} +{"episode_idx": 367, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_18.hdf5"} +{"episode_idx": 368, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_19.hdf5"} +{"episode_idx": 369, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_20.hdf5"} +{"episode_idx": 370, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_21.hdf5"} +{"episode_idx": 371, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_22.hdf5"} +{"episode_idx": 372, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_23.hdf5"} +{"episode_idx": 373, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_24.hdf5"} +{"episode_idx": 374, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_25.hdf5"} +{"episode_idx": 375, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_26.hdf5"} +{"episode_idx": 376, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_27.hdf5"} +{"episode_idx": 377, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_28.hdf5"} +{"episode_idx": 378, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_29.hdf5"} +{"episode_idx": 379, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_30.hdf5"} +{"episode_idx": 380, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_31.hdf5"} +{"episode_idx": 381, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_32.hdf5"} +{"episode_idx": 382, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_33.hdf5"} +{"episode_idx": 383, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_34.hdf5"} +{"episode_idx": 384, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_35.hdf5"} +{"episode_idx": 385, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_36.hdf5"} +{"episode_idx": 386, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_37.hdf5"} +{"episode_idx": 387, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_38.hdf5"} +{"episode_idx": 388, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_39.hdf5"} +{"episode_idx": 389, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_40.hdf5"} +{"episode_idx": 390, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_41.hdf5"} +{"episode_idx": 391, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_42.hdf5"} +{"episode_idx": 392, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_43.hdf5"} +{"episode_idx": 393, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_44.hdf5"} +{"episode_idx": 394, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_45.hdf5"} +{"episode_idx": 395, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_46.hdf5"} +{"episode_idx": 396, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_47.hdf5"} +{"episode_idx": 397, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_48.hdf5"} +{"episode_idx": 398, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_49.hdf5"} +{"episode_idx": 399, "task": "pour_coke", "raw_path": "pour_coke_v7/episode_50.hdf5"} +{"episode_idx": 400, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_1.hdf5"} +{"episode_idx": 401, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_2.hdf5"} +{"episode_idx": 402, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_3.hdf5"} +{"episode_idx": 403, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_4.hdf5"} +{"episode_idx": 404, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_5.hdf5"} +{"episode_idx": 405, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_6.hdf5"} +{"episode_idx": 406, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_7.hdf5"} +{"episode_idx": 407, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_8.hdf5"} +{"episode_idx": 408, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_9.hdf5"} +{"episode_idx": 409, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_10.hdf5"} +{"episode_idx": 410, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_11.hdf5"} +{"episode_idx": 411, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_12.hdf5"} +{"episode_idx": 412, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_13.hdf5"} +{"episode_idx": 413, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_14.hdf5"} +{"episode_idx": 414, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_15.hdf5"} +{"episode_idx": 415, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_16.hdf5"} +{"episode_idx": 416, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_17.hdf5"} +{"episode_idx": 417, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_18.hdf5"} +{"episode_idx": 418, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_19.hdf5"} +{"episode_idx": 419, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_20.hdf5"} +{"episode_idx": 420, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_21.hdf5"} +{"episode_idx": 421, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_22.hdf5"} +{"episode_idx": 422, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_23.hdf5"} +{"episode_idx": 423, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_24.hdf5"} +{"episode_idx": 424, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_25.hdf5"} +{"episode_idx": 425, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_26.hdf5"} +{"episode_idx": 426, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_27.hdf5"} +{"episode_idx": 427, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_28.hdf5"} +{"episode_idx": 428, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_29.hdf5"} +{"episode_idx": 429, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_30.hdf5"} +{"episode_idx": 430, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_31.hdf5"} +{"episode_idx": 431, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_32.hdf5"} +{"episode_idx": 432, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_33.hdf5"} +{"episode_idx": 433, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_34.hdf5"} +{"episode_idx": 434, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_35.hdf5"} +{"episode_idx": 435, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_36.hdf5"} +{"episode_idx": 436, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_37.hdf5"} +{"episode_idx": 437, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_38.hdf5"} +{"episode_idx": 438, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_39.hdf5"} +{"episode_idx": 439, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_40.hdf5"} +{"episode_idx": 440, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_41.hdf5"} +{"episode_idx": 441, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_42.hdf5"} +{"episode_idx": 442, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_43.hdf5"} +{"episode_idx": 443, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_44.hdf5"} +{"episode_idx": 444, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_45.hdf5"} +{"episode_idx": 445, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_46.hdf5"} +{"episode_idx": 446, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_47.hdf5"} +{"episode_idx": 447, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_48.hdf5"} +{"episode_idx": 448, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_49.hdf5"} +{"episode_idx": 449, "task": "pour_coke", "raw_path": "pour_coke_v8/episode_50.hdf5"} +{"episode_idx": 450, "task": "pour_coke", "raw_path": "pour_coke_v9/episode_1.hdf5"} +{"episode_idx": 451, "task": "pour_coke", "raw_path": "pour_coke_v9/episode_2.hdf5"} +{"episode_idx": 452, "task": "pour_coke", "raw_path": "pour_coke_v9/episode_3.hdf5"} +{"episode_idx": 453, "task": "pour_coke", "raw_path": "pour_coke_v9/episode_4.hdf5"} +{"episode_idx": 454, "task": "pour_coke", "raw_path": "pour_coke_v9/episode_5.hdf5"} +{"episode_idx": 455, "task": "pour_coke", "raw_path": "pour_coke_v9/episode_6.hdf5"} +{"episode_idx": 456, "task": "pour_coke", "raw_path": "pour_coke_v9/episode_7.hdf5"} +{"episode_idx": 457, "task": "pour_coke", "raw_path": "pour_coke_v9/episode_8.hdf5"} +{"episode_idx": 458, "task": "pour_coke", "raw_path": "pour_coke_v9/episode_9.hdf5"} diff --git a/assets/examples/fastumi/fastumi_single_arm/pour_coke/meta/tasks.parquet b/assets/examples/fastumi/fastumi_single_arm/pour_coke/meta/tasks.parquet new file mode 100644 index 0000000000000000000000000000000000000000..f0f43b451192a95d8863070bd6f041264e649cbf Binary files /dev/null and b/assets/examples/fastumi/fastumi_single_arm/pour_coke/meta/tasks.parquet differ diff --git a/assets/examples/fastumi/fastumi_single_arm/pour_coke/videos/observation.image.right_main_camera_rgb/chunk-000/file-000.mp4 b/assets/examples/fastumi/fastumi_single_arm/pour_coke/videos/observation.image.right_main_camera_rgb/chunk-000/file-000.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..6cac1f60a305209778d67c3e6dc8daf6644aa2e9 --- /dev/null +++ b/assets/examples/fastumi/fastumi_single_arm/pour_coke/videos/observation.image.right_main_camera_rgb/chunk-000/file-000.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:81b3aa9d26f522ef357b575b5fa5c3755a2c1d3d0823004fae166c12268adff1 +size 410211 diff --git a/assets/examples/fractal20220817_data/data/chunk-000/file-000.parquet b/assets/examples/fractal20220817_data/data/chunk-000/file-000.parquet new file mode 100644 index 0000000000000000000000000000000000000000..7b751d27de881df062960dde05c52c0c6679cede Binary files /dev/null and b/assets/examples/fractal20220817_data/data/chunk-000/file-000.parquet differ diff --git a/assets/examples/fractal20220817_data/meta/episodes/chunk-000/file-000.parquet b/assets/examples/fractal20220817_data/meta/episodes/chunk-000/file-000.parquet new file mode 100644 index 0000000000000000000000000000000000000000..f59a6f3e1a883a2a1ce1c1cad8182cde28cc7224 Binary files /dev/null and b/assets/examples/fractal20220817_data/meta/episodes/chunk-000/file-000.parquet differ diff --git a/assets/examples/fractal20220817_data/meta/info.json b/assets/examples/fractal20220817_data/meta/info.json new file mode 100644 index 0000000000000000000000000000000000000000..1aa934d08fedc7dd79b236254f4b1e9fdba70e0f --- /dev/null +++ b/assets/examples/fractal20220817_data/meta/info.json @@ -0,0 +1,111 @@ +{ + "codebase_version": "v3.0", + "robot_type": "google_robot", + "total_episodes": 1, + "total_frames": 25, + "total_tasks": 1, + "chunks_size": 1000, + "data_files_size_in_mb": 100, + "video_files_size_in_mb": 200, + "fps": 3, + "splits": { + "train": "0:1" + }, + "data_path": "data/chunk-{chunk_index:03d}/file-{file_index:03d}.parquet", + "video_path": "videos/{video_key}/chunk-{chunk_index:03d}/file-{file_index:03d}.mp4", + "features": { + "observation.images.image": { + "dtype": "video", + "shape": [ + 256, + 320, + 3 + ], + "names": [ + "height", + "width", + "rgb" + ], + "info": { + "video.height": 256, + "video.width": 320, + "video.codec": "av1", + "video.pix_fmt": "yuv420p", + "video.is_depth_map": false, + "video.fps": 3, + "video.channels": 3, + "has_audio": false + } + }, + "observation.state": { + "dtype": "float32", + "shape": [ + 8 + ], + "names": { + "motors": [ + "x", + "y", + "z", + "rx", + "ry", + "rz", + "rw", + "gripper" + ] + } + }, + "action": { + "dtype": "float32", + "shape": [ + 7 + ], + "names": { + "motors": [ + "x", + "y", + "z", + "roll", + "pitch", + "yaw", + "gripper" + ] + } + }, + "timestamp": { + "dtype": "float32", + "shape": [ + 1 + ], + "names": null + }, + "frame_index": { + "dtype": "int64", + "shape": [ + 1 + ], + "names": null + }, + "episode_index": { + "dtype": "int64", + "shape": [ + 1 + ], + "names": null + }, + "index": { + "dtype": "int64", + "shape": [ + 1 + ], + "names": null + }, + "task_index": { + "dtype": "int64", + "shape": [ + 1 + ], + "names": null + } + } +} diff --git a/assets/examples/fractal20220817_data/meta/stats.json b/assets/examples/fractal20220817_data/meta/stats.json new file mode 100644 index 0000000000000000000000000000000000000000..1eef42cfc5d40ee972fe74b7df833ac81d123584 --- /dev/null +++ b/assets/examples/fractal20220817_data/meta/stats.json @@ -0,0 +1,501 @@ +{ + "episode_index": { + "min": [ + 0 + ], + "max": [ + 87211 + ], + "mean": [ + 43687.47439045023 + ], + "std": [ + 25161.433385824046 + ], + "count": [ + 3786400 + ], + "q01": [ + 43687.47439045023 + ], + "q10": [ + 43687.47439045023 + ], + "q50": [ + 43687.47439045023 + ], + "q90": [ + 43687.47439045023 + ], + "q99": [ + 43687.47439045023 + ] + }, + "timestamp": { + "min": [ + 0.0 + ], + "max": [ + 216.33333333333334 + ], + "mean": [ + 8.793377526582546 + ], + "std": [ + 8.044006875848723 + ], + "count": [ + 3786400 + ], + "q01": [ + 0.019118576965716935 + ], + "q10": [ + 1.6091612757572917 + ], + "q50": [ + 8.711732604248807 + ], + "q90": [ + 15.944715586261385 + ], + "q99": [ + 17.56541885375544 + ] + }, + "frame_index": { + "min": [ + 0 + ], + "max": [ + 649 + ], + "mean": [ + 26.380132579759145 + ], + "std": [ + 24.13202062754607 + ], + "count": [ + 3786400 + ], + "q01": [ + 0.057355731096994454 + ], + "q10": [ + 4.827483827437957 + ], + "q50": [ + 26.133017805039607 + ], + "q90": [ + 47.83414675861042 + ], + "q99": [ + 52.696256561060494 + ] + }, + "observation.state": { + "min": [ + -0.4436439275741577, + -0.9970501065254211, + -0.006579156965017319, + -0.8643477559089661, + -0.7079970240592957, + -0.7688722014427185, + -0.4999994933605194, + 0.0 + ], + "max": [ + 1.0534898042678833, + 0.48018959164619446, + 1.6896663904190063, + 0.9999993443489075, + 0.9999874830245972, + 0.9554369449615479, + 0.9914546012878418, + 1.0 + ], + "mean": [ + 0.5582046028643536, + -0.08324323429555819, + 0.7708198142579612, + -0.24752762586024715, + 0.4959921774813562, + 0.09255771451332732, + 0.2094189021656009, + 0.4261956376121668 + ], + "std": [ + 0.12440319979560374, + 0.11571359396154758, + 0.245894357010222, + 0.5132342575426315, + 0.5223439100950532, + 0.16665986288677848, + 0.27617123861598164, + 0.45387534501253995 + ], + "count": [ + 3786400 + ], + "q01": [ + 0.408963256356151, + -0.23145526982140982, + 0.5935708434664594, + -0.64105388872015, + 0.07054327665810646, + -0.12634555347420393, + -0.09304175200127232, + 2.199466787180472e-05 + ], + "q10": [ + 0.4428541524403959, + -0.19135969252525398, + 0.6060833036444486, + -0.5704538476018918, + 0.17980850596534304, + -0.06904302420001972, + -0.009461047441014432, + 0.007395965520886004 + ], + "q50": [ + 0.5487401925001684, + -0.07700300862678738, + 0.7668444825525346, + -0.2660065536555911, + 0.5238047414960931, + 0.09922105682856339, + 0.22535350104783028, + 0.3058211724179186 + ], + "q90": [ + 0.6841599570198298, + 0.004299989107951686, + 0.9432045306065185, + 0.0771875547069565, + 0.7731956966295638, + 0.23161431007069846, + 0.39114578975783715, + 0.9598732336358585 + ], + "q99": [ + 0.6963673544148412, + 0.01644260025180769, + 1.000799300047394, + 0.16702012495529103, + 0.8204194259313271, + 0.26266766557977766, + 0.42878282571630694, + 0.9689303361079542 + ] + }, + "index": { + "min": [ + 0 + ], + "max": [ + 3786399 + ], + "mean": [ + 1893199.5 + ], + "std": [ + 1093039.5296297753 + ], + "count": [ + 3786400 + ], + "q01": [ + 1893173.1772231467 + ], + "q10": [ + 1893177.9473516669 + ], + "q50": [ + 1893199.2556619933 + ], + "q90": [ + 1893220.9548600307 + ], + "q99": [ + 1893225.8161719302 + ] + }, + "task_index": { + "min": [ + 0 + ], + "max": [ + 598 + ], + "mean": [ + 143.40194855271227 + ], + "std": [ + 132.58829846252522 + ], + "count": [ + 3786400 + ], + "q01": [ + 143.40194855271227 + ], + "q10": [ + 143.40194855271227 + ], + "q50": [ + 143.40194855271227 + ], + "q90": [ + 143.4019485527123 + ], + "q99": [ + 143.4019485527123 + ] + }, + "action": { + "min": [ + -2.0204520225524902, + -5.497899532318115, + -2.031663417816162, + -1.569917917251587, + -1.569892168045044, + -1.570419430732727, + 0.0 + ], + "max": [ + 2.9984593391418457, + 22.09052848815918, + 2.7507524490356445, + 1.570636510848999, + 1.5321086645126343, + 1.5691522359848022, + 1.0 + ], + "mean": [ + 0.006986742172085009, + 0.006266400645656175, + -0.01262561945294701, + 0.0433347717660516, + -0.005755843126369116, + 0.0009133710921551621, + 0.5354204546016359 + ], + "std": [ + 0.06943342817907261, + 0.05987580077761333, + 0.0738429111488631, + 0.15697640193310985, + 0.1319237681096443, + 0.1463219227874845, + 0.49874381422625697 + ], + "count": [ + 3786400 + ], + "q01": [ + -0.12221348527912608, + -0.09609365736658501, + -0.15100898896136394, + -0.2185607741848074, + -0.2965577733895619, + -0.3014479600294951, + 0.027980111681782445 + ], + "q10": [ + -0.0660911694758722, + -0.04637928472530103, + -0.09462124253497246, + -0.1003841425402165, + -0.1575445953883812, + -0.1529437071341076, + 0.030033117533913266 + ], + "q50": [ + 0.004505050576012514, + 0.003205040885008195, + -0.010057818458173608, + 0.01762125013928238, + 0.00035042878599716304, + -0.000527023381541794, + 0.6160485027421297 + ], + "q90": [ + 0.08102828768740676, + 0.06249624540697094, + 0.06695364553140282, + 0.22499897324678897, + 0.129533823452432, + 0.15507156750538909, + 0.9883197184355382 + ], + "q99": [ + 0.1298058026221481, + 0.10786538799511407, + 0.13116332716025397, + 0.4193381877333532, + 0.2438051563655085, + 0.3007432678772545, + 0.9977885722166413 + ] + }, + "observation.images.image": { + "min": [ + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ] + ], + "max": [ + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ] + ], + "mean": [ + [ + [ + 0.3957461965864481 + ] + ], + [ + [ + 0.2862227698842343 + ] + ], + [ + [ + 0.2067759676712127 + ] + ] + ], + "std": [ + [ + [ + 0.03559225425494718 + ] + ], + [ + [ + 0.02675087532213864 + ] + ], + [ + [ + 0.023519621913043576 + ] + ] + ], + "count": [ + 3741992 + ], + "q01": [ + [ + [ + 0.0024661240356684635 + ] + ], + [ + [ + 0.0007401937026290603 + ] + ], + [ + [ + 4.542013660436245e-05 + ] + ] + ], + "q10": [ + [ + [ + 0.04357633479047807 + ] + ], + [ + [ + 0.02722412507799719 + ] + ], + [ + [ + 0.006618760305829143 + ] + ] + ], + "q50": [ + [ + [ + 0.4320693558492684 + ] + ], + [ + [ + 0.30031301324089443 + ] + ], + [ + [ + 0.20738113717924858 + ] + ] + ], + "q90": [ + [ + [ + 0.6783619024719743 + ] + ], + [ + [ + 0.5187178433507462 + ] + ], + [ + [ + 0.40475137588524834 + ] + ] + ], + "q99": [ + [ + [ + 0.8303000355708119 + ] + ], + [ + [ + 0.6617710723529358 + ] + ], + [ + [ + 0.5504632600300524 + ] + ] + ] + } +} \ No newline at end of file diff --git a/assets/examples/fractal20220817_data/meta/tasks.parquet b/assets/examples/fractal20220817_data/meta/tasks.parquet new file mode 100644 index 0000000000000000000000000000000000000000..00801f3a4976976ae261b2ecbb3d39bb877e78d1 Binary files /dev/null and b/assets/examples/fractal20220817_data/meta/tasks.parquet differ diff --git a/assets/examples/fractal20220817_data/videos/observation.images.image/chunk-000/file-000.mp4 b/assets/examples/fractal20220817_data/videos/observation.images.image/chunk-000/file-000.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..64dc701d070f15d8652bbfe1af7363731811b4d3 --- /dev/null +++ b/assets/examples/fractal20220817_data/videos/observation.images.image/chunk-000/file-000.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:942fbfe83173ab9382417208f700a1b6520bc47858cde053ff83c73b78189146 +size 252563 diff --git a/cosmos-framework/cosmos_framework/__init__.py b/cosmos-framework/cosmos_framework/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/cosmos-framework/cosmos_framework/data/__init__.py b/cosmos-framework/cosmos_framework/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/cosmos-framework/cosmos_framework/data/vfm/__init__.py b/cosmos-framework/cosmos_framework/data/vfm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/cosmos-framework/cosmos_framework/data/vfm/action/__init__.py b/cosmos-framework/cosmos_framework/data/vfm/action/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..503ec1b18d584ba1c349360dedbe6951e3216df6 --- /dev/null +++ b/cosmos-framework/cosmos_framework/data/vfm/action/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: OpenMDW-1.1 + diff --git a/cosmos-framework/cosmos_framework/data/vfm/action/_lerobot_local.py b/cosmos-framework/cosmos_framework/data/vfm/action/_lerobot_local.py new file mode 100644 index 0000000000000000000000000000000000000000..7cb505db930f6d97d938db14924e211455a768ea --- /dev/null +++ b/cosmos-framework/cosmos_framework/data/vfm/action/_lerobot_local.py @@ -0,0 +1,286 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: OpenMDW-1.1 + +"""Small local LeRobot helpers for the standalone Action Viewer. + +These helpers intentionally operate on already-packaged local LeRobot shards +(parquet metadata/data plus local MP4s). They avoid the heavier LeRobotDataset +adapter and any Hugging Face dataset download/streaming behavior. +""" + +from __future__ import annotations + +import json +import random +from pathlib import Path +from threading import Lock +from typing import Any + +import numpy as np +import pyarrow.parquet as pq +import torch +from lerobot.datasets.video_utils import decode_video_frames_torchcodec + +_MODE_CHOICES = ("forward_dynamics", "inverse_dynamics", "policy") + + +class _LocalVideoDecoderCache: + """TorchCodec decoder cache that passes local paths directly. + + LeRobot 0.4.x wraps every video path with ``fsspec.open(...)`` before + constructing ``torchcodec.decoders.VideoDecoder``. That produces a + ``LocalFileOpener`` for packaged Space assets, but TorchCodec 0.2 expects + a str/Path/bytes/Tensor source and rejects that opener object. The Space + only reads local packaged MP4s, so use path strings directly. + """ + + def __init__(self) -> None: + self._cache: dict[str, object] = {} + self._lock = Lock() + + def get_decoder(self, video_path: str): + from torchcodec.decoders import VideoDecoder + + path = str(video_path) + with self._lock: + if path not in self._cache: + self._cache[path] = VideoDecoder(path, seek_mode="approximate") + return self._cache[path] + + def clear(self) -> None: + with self._lock: + self._cache.clear() + + def size(self) -> int: + with self._lock: + return len(self._cache) + + +_VIDEO_DECODER_CACHE = _LocalVideoDecoderCache() + + +def choose_mode(mode: str) -> str: + """Resolve one sample mode, matching the old joint-mode behavior.""" + + if mode == "joint": + return random.choice(_MODE_CHOICES) + return mode + + +def load_local_lerobot(root: str | Path) -> tuple[Path, dict[str, Any], dict[int, dict[str, Any]], dict[int, str], list[dict[str, Any]]]: + """Load local LeRobot metadata, tasks, and data rows from one shard root.""" + + root_path = Path(root) + info = json.loads((root_path / "meta" / "info.json").read_text()) + episodes = { + int(row["episode_index"]): row + for path in sorted((root_path / "meta" / "episodes").glob("chunk-*/file-*.parquet")) + for row in pq.read_table(path).to_pylist() + } + + tasks: dict[int, str] = {} + tasks_path = root_path / "meta" / "tasks.parquet" + if tasks_path.exists(): + for row in pq.read_table(tasks_path).to_pylist(): + task = row.get("task", row.get("__index_level_0__", "")) + tasks[int(row.get("task_index", len(tasks)))] = str(task) + + rows = sorted( + ( + row + for path in sorted((root_path / "data").glob("chunk-*/file-*.parquet")) + for row in pq.read_table(path).to_pylist() + ), + key=lambda row: int(row["index"]), + ) + return root_path, info, episodes, tasks, rows + + +def load_local_lerobot_collection(root: str | Path, subroots: list[str] | None = None) -> tuple[ + list[Path], + dict[int, dict[str, Any]], + dict[int, str], + list[dict[str, Any]], +]: + """Load one root or a collection of local LeRobot shard subroots. + + Each returned row gets a private ``_dataset_idx`` field so callers can find + the source root/info for video decoding. + """ + + base = Path(root) + candidates = [base] + if subroots: + candidates = [base / subroot for subroot in subroots] + elif not (base / "meta" / "info.json").exists(): + candidates = sorted(p.parent.parent for p in base.glob("**/meta/info.json")) + + roots: list[Path] = [] + episodes: dict[int, dict[str, Any]] = {} + tasks: dict[int, str] = {} + rows: list[dict[str, Any]] = [] + episode_offset = 0 + task_offset = 0 + + for root_path in candidates: + if not (root_path / "meta" / "info.json").exists(): + continue + dataset_idx = len(roots) + roots.append(root_path) + _, _, shard_episodes, shard_tasks, shard_rows = load_local_lerobot(root_path) + for task_id, task in shard_tasks.items(): + tasks[task_offset + task_id] = task + for episode_id, episode in shard_episodes.items(): + ep = dict(episode) + ep["episode_index"] = episode_offset + episode_id + ep["_dataset_idx"] = dataset_idx + episodes[episode_offset + episode_id] = ep + for row in shard_rows: + r = dict(row) + r["episode_index"] = episode_offset + int(row["episode_index"]) + r["task_index"] = task_offset + int(row.get("task_index", 0)) + r["_dataset_idx"] = dataset_idx + rows.append(r) + episode_offset += max(shard_episodes.keys(), default=-1) + 1 + task_offset += max(shard_tasks.keys(), default=-1) + 1 + + rows.sort(key=lambda row: (int(row["_dataset_idx"]), int(row["index"]))) + return roots, episodes, tasks, rows + + +def sample_count(rows: list[dict[str, Any]], chunk_length: int, sample_stride: int = 1) -> int: + """Number of contiguous local samples that can provide T+1 observations.""" + + return max(0, (len(rows) - int(chunk_length) + int(sample_stride) - 1) // int(sample_stride)) + + +def rows_for_index(rows: list[dict[str, Any]], idx: int, chunk_length: int, sample_stride: int = 1) -> list[dict[str, Any]]: + """Select T+1 contiguous rows for a flat local index.""" + + row_idx = int(idx) * int(sample_stride) + selected = rows[row_idx : row_idx + int(chunk_length) + 1] + if len(selected) < int(chunk_length) + 1: + raise IndexError(f"Index {idx} does not have {chunk_length + 1} rows") + episode_id = int(selected[0]["episode_index"]) + dataset_idx = int(selected[0].get("_dataset_idx", 0)) + if any(int(row["episode_index"]) != episode_id or int(row.get("_dataset_idx", 0)) != dataset_idx for row in selected): + raise IndexError(f"Index {idx} crosses an episode or shard boundary") + return selected + + +def rows_at_fps( + rows: list[dict[str, Any]], + start_idx: int, + chunk_length: int, + fps: float, + sample_stride: int = 1, +) -> list[dict[str, Any]]: + """Select T+1 nearest timestamp rows at target FPS within one episode.""" + + start_row = rows[int(start_idx) * int(sample_stride)] + episode_id = int(start_row["episode_index"]) + dataset_idx = int(start_row.get("_dataset_idx", 0)) + episode_rows = [ + row + for row in rows + if int(row["episode_index"]) == episode_id and int(row.get("_dataset_idx", 0)) == dataset_idx + ] + timestamps = np.asarray([float(row["timestamp"]) for row in episode_rows], dtype=np.float64) + start_ts = float(start_row["timestamp"]) + target_ts = start_ts + np.arange(int(chunk_length) + 1, dtype=np.float64) / float(fps) + indices = np.searchsorted(timestamps, target_ts, side="left") + indices = np.minimum(indices, len(episode_rows) - 1) + prev = np.maximum(indices - 1, 0) + choose_prev = np.abs(timestamps[prev] - target_ts) <= np.abs(timestamps[indices] - target_ts) + indices = np.where(choose_prev, prev, indices) + return [episode_rows[int(i)] for i in indices] + + +def task_text(tasks: dict[int, str], rows: list[dict[str, Any]], fallback: str) -> str: + """Return a task string for a selected row sequence.""" + + if not rows: + return fallback + return tasks.get(int(rows[0].get("task_index", 0)), fallback) + + +def pick_caption(task: str) -> str: + """Pick one non-empty caption from a pipe-separated task string.""" + + parts = [part.strip() for part in str(task).split(" | ") if part.strip()] + return random.choice(parts or [str(task)]) + + +def video_path(root: Path, info: dict[str, Any], episode: dict[str, Any], video_key: str) -> Path: + """Resolve a LeRobot v2/v3 video path for one episode/key.""" + + chunk_idx = int( + episode.get( + f"videos/{video_key}/chunk_index", + episode.get(f"videos/{video_key}/episode_chunk", episode.get("data/chunk_index", 0)), + ) + ) + file_idx = int( + episode.get( + f"videos/{video_key}/file_index", + episode.get(f"videos/{video_key}/episode_file", episode.get("data/file_index", 0)), + ) + ) + rel = info["video_path"].format( + video_key=video_key, + chunk_index=chunk_idx, + file_index=file_idx, + episode_chunk=chunk_idx, + episode_file=file_idx, + ) + return root / rel + + +def load_video_key( + root: Path, + info: dict[str, Any], + episode: dict[str, Any], + rows: list[dict[str, Any]], + key: str, + tolerance_s: float, +) -> torch.Tensor: + """Decode T+1 video frames for one LeRobot video key.""" + + timestamps = [float(row["timestamp"]) for row in rows] + offset = float(episode.get(f"videos/{key}/from_timestamp", 0.0)) + path = video_path(root, info, episode, key) + return decode_video_frames_torchcodec( + str(path), + [offset + ts for ts in timestamps], + tolerance_s, + decoder_cache=_VIDEO_DECODER_CACHE, + ) + + +def format_video(video_tchw: torch.Tensor) -> torch.Tensor: + """Convert LeRobot ``[T,C,H,W]`` float video to viewer ``[C,T,H,W]`` uint8.""" + + return (video_tchw * 255.0).clamp(0.0, 255.0).to(torch.uint8).permute(1, 0, 2, 3) + + +def build_result( + *, + mode: str, + video: torch.Tensor, + action: torch.Tensor, + ai_caption: str, + fps: float, + viewpoint: str, + **extras: Any, +) -> dict[str, Any]: + """Assemble the viewer-facing dataset sample dict.""" + + return { + "ai_caption": ai_caption, + "video": format_video(video), + "action": action, + "conditioning_fps": torch.tensor(float(fps), dtype=torch.float32), + "mode": mode, + "viewpoint": viewpoint, + **extras, + } diff --git a/cosmos-framework/cosmos_framework/data/vfm/action/av_dataset.py b/cosmos-framework/cosmos_framework/data/vfm/action/av_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..4097c37ddbb0e1d7c943b0ae655d9b156799e72c --- /dev/null +++ b/cosmos-framework/cosmos_framework/data/vfm/action/av_dataset.py @@ -0,0 +1,1013 @@ +"""AV Dataset for Action training. + +This module provides an IterableDataset for AV data +that loads S3 storage containing tar files with video, action trajectories, +and route waypoints. + +Data format expected: + s3://bucket/path/*.tar -> pkl files containing: + - video: mp4 bytes + - action: pickled dict with: + - history_xyz: (history_length, 3) tensor - position history + - history_quat: (history_length, 4) tensor - quaternion history + - future_xyz: (future_length, 3) tensor - position future + - future_quat: (future_length, 4) tensor - quaternion future + - route: pickled numpy array of shape (num_waypoints, 3) - route waypoints in ego frame + +Action format: 7D pose per timestep [x, y, z, qw, qx, qy, qz] (3 position + 4 quaternion) +""" + +import io +import json +import math +import pickle +import random +import tarfile +from pathlib import Path +from typing import Iterator, Literal + +import numpy as np +import torch +import torchvision +import torchvision.transforms.functional as F +from scipy.spatial.transform import Rotation +from torch.utils.data import IterableDataset + +# import torch.multiprocessing +# torch.multiprocessing.set_sharing_strategy("file_system") +from cosmos_framework.utils import log +from cosmos_framework.utils.easy_io import easy_io +from cosmos_framework.data.vfm.action.pose_utils import ( + RotationConvention, + build_abs_pose_from_components, + pose_abs_to_rel, +) + + +VIDEO_RES_SIZE_INFO: dict[str, dict[str, tuple[int, int]]] = { + "256": {"1,1": (256, 256), "4,3": (320, 256), "3,4": (256, 320), "16,9": (320, 192), "9,16": (192, 320)}, + "480": {"1,1": (640, 640), "4,3": (736, 544), "3,4": (544, 736), "16,9": (832, 480), "9,16": (480, 832)}, +} + + +def get_target_size_and_crop(resolution: str, current_H: int, current_W: int) -> tuple[int, int, int, int]: + target_resolutions = VIDEO_RES_SIZE_INFO[resolution] + current_ar = current_W / current_H + best_key = min( + target_resolutions, + key=lambda key: abs((int(key.split(",")[0]) / int(key.split(",")[1])) - current_ar), + ) + target_canvas_W, target_canvas_H = target_resolutions[best_key] + scaling_ratio = max(target_canvas_W / current_W, target_canvas_H / current_H) + return int(scaling_ratio * current_H + 0.5), int(scaling_ratio * current_W + 0.5), target_canvas_H, target_canvas_W + + +def decode_video_bytes( + video_bytes: bytes, + resolution: str | None = None, + history_len: float | None = None, + future_len: float | None = None, + original_history_steps: int | None = None, +) -> tuple[torch.Tensor, float]: + """Decode video from mp4 bytes using torchvision.io. + + Args: + video_bytes: Raw mp4 video bytes. + resolution: Target resolution for video frames (e.g. "256", "480"). If None, keeps original resolution. + history_len: Desired history length in seconds. Used with future_len to slice video. + future_len: Desired future length in seconds. Used with history_len to slice video. + original_history_steps: Number of frames in the original history portion of the video. + + Returns: + Tuple of (video tensor in (C, T, H, W) uint8 format, original fps). + + Note: + The video structure is [history_frames | future_frames]. When slicing: + - History portion: take last (history_len * fps) frames from video[:original_history_steps] + - Future portion: take first (future_len * fps) frames from video[original_history_steps:] + This mirrors the slicing in process_action_trajectory. + """ + # Write bytes to a temporary file for torchvision.io.read_video + import tempfile + + with tempfile.NamedTemporaryFile(suffix=".mp4", delete=True) as tmp_file: + tmp_file.write(video_bytes) + tmp_file.flush() + + # Read video using torchvision.io + # Returns: (video_frames, audio_frames, info) + # video_frames shape: (T, H, W, C) uint8 + video_frames, _, info = torchvision.io.read_video(tmp_file.name, pts_unit="sec") + + original_fps = info.get("video_fps", 30.0) + + # Slice video to match history_len and future_len + # Video structure: [history_frames | future_frames] + if original_history_steps is None: + raise ValueError("original_history_steps is required to slice video") + + # Split video at history/future boundary + history_video = video_frames[:original_history_steps] + future_video = video_frames[original_history_steps:] + + # Slice history (take last N frames) + if history_len is not None: + history_steps = int(history_len * original_fps) + if history_steps > history_video.shape[0]: + raise ValueError( + f"Requested history_len={history_len}s ({history_steps} frames at {original_fps}Hz) " + f"exceeds available history video ({history_video.shape[0]} frames)" + ) + history_video = history_video[-history_steps:] + + # Slice future (take first N frames) + if future_len is not None: + future_steps = int(future_len * original_fps) + if future_steps > future_video.shape[0]: + raise ValueError( + f"Requested future_len={future_len}s ({future_steps} frames at {original_fps}Hz) " + f"exceeds available future video ({future_video.shape[0]} frames)" + ) + future_video = future_video[:future_steps] + + # Concatenate sliced portions + video_frames = torch.cat([history_video, future_video], dim=0) # [T,H,W,C] + + # Convert from (T, H, W, C) to (T, C, H, W) + video_tensor = video_frames.permute(0, 3, 1, 2) # [T,C,H,W] + + # Resize and Crop if resolution is provided + if resolution is not None: + T, C, H, W = video_tensor.shape + # get_target_size_and_crop expects (resolution, current_H, current_W) + new_H, new_W, target_canvas_H, target_canvas_W = get_target_size_and_crop(resolution, H, W) + + # Resize if needed + if new_H != H or new_W != W: + video_tensor = F.resize( + video_tensor, [new_H, new_W], interpolation=F.InterpolationMode.BICUBIC, antialias=True + ) + + # Center Crop + if new_H != target_canvas_H or new_W != target_canvas_W: + video_tensor = F.center_crop(video_tensor, [target_canvas_H, target_canvas_W]) + + # Convert to uint8 if not already + if video_tensor.dtype != torch.uint8: + video_tensor = video_tensor.to(torch.uint8) + + # Convert from (T, C, H, W) to (C, T, H, W) + video_tensor = video_tensor.permute(1, 0, 2, 3) # [C,T,H,W] + + return video_tensor, original_fps + + +# 3x3 rotation from car convention (x=forward, y=left, z=up) +# to OpenCV convention (x=right, y=down, z=forward). +# Mapping: new_x = -old_y, new_y = -old_z, new_z = old_x +CAR_TO_OPENCV_ROTATION = np.array( + [[0, -1, 0], [0, 0, -1], [1, 0, 0]], + dtype=np.float32, +) + + +def process_action_trajectory( + action_data: dict, + history_len: float | None = None, + future_len: float | None = None, + fps: int = 10, + rotation_format: Literal["9D", "rot6d", "quat_xyzw", "euler_xyz"] = "9D", + pose_convention: Literal["backward_anchored", "backward_framewise"] = ("backward_framewise"), + scale: float = 1.0, + rotation_scale: float = 1.0, + max_translation_norm: float | None = None, + align_opencv_pose: bool = False, +): + """Process action trajectories from action data dict. + + Args: + action_data: Dict with: + - history_xyz: (T_hist, 3) tensor - position history + - history_quat: (T_hist, 4) tensor - quaternion history + - future_xyz: (T_fut, 3) tensor - position future + - future_quat: (T_fut, 4) tensor - quaternion future + history_len: Desired history length in seconds. + future_len: Desired future length in seconds. + fps: Frames per second, used to compute number of steps from time durations. + align_opencv_pose: If True, transform poses from car convention + (x=forward, y=left, z=up) to OpenCV convention (x=right, y=down, z=forward). + NOTE: av_v2_* data is already in OpenCV convention, DO NOT apply this transformation! + + Returns: + Tuple of (history_action, future_action). + Both actions are torch.Tensor of shape (T, 7) in [x, y, z, qw, qx, qy, qz] format. + + Note: + History steps = history_len * fps, same as future steps = future_len * fps. + For example, with history_len=1.0s and fps=10, we get 10 history steps. + """ + # Extract and ensure tensors + history_xyz = action_data["history_xyz"] + history_quat = action_data["history_quat"] + future_xyz = action_data["future_xyz"] + future_quat = action_data["future_quat"] + + # Convert to tensors if needed + if not isinstance(history_xyz, torch.Tensor): + history_xyz = torch.tensor(history_xyz, dtype=torch.float32) # [T_hist,3] + if not isinstance(history_quat, torch.Tensor): + history_quat = torch.tensor(history_quat, dtype=torch.float32) # [T_hist,4] + if not isinstance(future_xyz, torch.Tensor): + future_xyz = torch.tensor(future_xyz, dtype=torch.float32) # [T_fut,3] + if not isinstance(future_quat, torch.Tensor): + future_quat = torch.tensor(future_quat, dtype=torch.float32) # [T_fut,4] + + # Slice history to desired length (take the last N steps) + if history_len is not None: + history_steps = int(history_len * fps) + available_history = history_xyz.shape[0] + if history_steps > available_history: + raise ValueError( + f"Requested history_len={history_len}s ({history_steps} steps at {fps}Hz) " + f"exceeds available history ({available_history} steps)" + ) + history_xyz = history_xyz[-history_steps:] + history_quat = history_quat[-history_steps:] + + # Slice future to desired length (take the first N steps) + if future_len is not None: + future_steps = int(future_len * fps) + available_future = future_xyz.shape[0] + if future_steps > available_future: + raise ValueError( + f"Requested future_len={future_len}s ({future_steps} steps at {fps}Hz) " + f"exceeds available future ({available_future} steps)" + ) + future_xyz = future_xyz[:future_steps] + future_quat = future_quat[:future_steps] + + # Concatenate to form full trajectory + # history_xyz: (T_hist, 3) + # history_quat: (T_hist, 4) [w, x, y, z] + all_xyz = torch.cat([history_xyz, future_xyz], dim=0) # [T,3] + all_quat = torch.cat([history_quat, future_quat], dim=0) # [T,4] + + poses_abs = build_abs_pose_from_components( + all_xyz, + all_quat, + "quat_wxyz", + ) + + if align_opencv_pose: + poses_abs[:, :3, :3] = poses_abs[:, :3, :3] @ CAR_TO_OPENCV_ROTATION.T + + actions = pose_abs_to_rel( + poses_abs, + rotation_format=rotation_format, + pose_convention=pose_convention, + translation_scale=scale, + rotation_scale=rotation_scale, + ) + + if max_translation_norm is not None: + trans_norms = np.linalg.norm(actions[:, :3], axis=1) + if trans_norms.max() > max_translation_norm: + return None + + actions = torch.from_numpy(actions) # [T-1,action_dim] + + # Split back + # history_action has one less action than history_xyz because the first action is the initial pose + history_action = actions[: len(history_xyz) - 1] + future_action = actions[len(history_xyz) - 1 :] + + return history_action, future_action + + +def add_route_noise( + route: torch.Tensor, + lat_noise_range: float = 0.0, + long_noise_range: float = 0.0, + point_wise_noise: float = 0.0, +) -> torch.Tensor: + """Add noise to route waypoints for data augmentation. + + Applies two types of noise: + 1. Uniform lateral/longitudinal shift (same offset for all waypoints in a sample) + 2. Per-point Gaussian noise (independent per waypoint) + + Both noise types leave the z-axis unchanged. NaN waypoints (padding) are preserved. + + Args: + route: (T, 3) tensor of route waypoints in XYZ. + lat_noise_range: Half-range for uniform lateral (Y) noise. + long_noise_range: Half-range for uniform longitudinal (X) noise. + point_wise_noise: Standard deviation of per-point Gaussian noise. + + Returns: + Noisy route tensor of shape (T, 3). + """ + if lat_noise_range > 0 or long_noise_range > 0: + shift = torch.rand(3) * torch.tensor([2 * long_noise_range, 2 * lat_noise_range, 0.0]) - torch.tensor( # [3] + [long_noise_range, lat_noise_range, 0.0] + ) + route = route + shift[None, :] + + if point_wise_noise > 0: + noise = torch.randn(route.shape[0], 3) * point_wise_noise # [T,3] + noise[..., -1] = 0.0 + route = route + noise + + return route + + +def apply_route_dropout( + route: torch.Tensor, + dropout_rate: float = 0.5, + tail_dropout_rate: float = 0.3, +) -> torch.Tensor: + """Apply dropout masking to route waypoints for data augmentation. + + Three dropout behaviours, applied sequentially: + 1. With probability ``dropout_rate``, mask **all** waypoints. + Otherwise, randomly mask the first K waypoints (K ~ Uniform(0, T)). + 2. With probability ``tail_dropout_rate``, additionally mask waypoints + from a random index in [T//2, T) onward. + + Masked waypoints are set to NaN so downstream code can detect padding + via ``torch.isnan``. + + Args: + route: (T, 3) tensor of route waypoints. + dropout_rate: Probability of fully disabling the route. + tail_dropout_rate: Probability of additional tail dropout. + + Returns: + Route tensor with dropout applied, shape (T, 3). + """ + T = route.shape[0] + mask = torch.isnan(route[..., 0]) # [T] existing padding + + if random.uniform(0, 1) < dropout_rate: + dropout_mask = torch.ones(T, dtype=torch.bool) # [T] + else: + dropout_idx = random.randint(0, T) + dropout_mask = torch.arange(T) < dropout_idx # [T] + + if random.uniform(0, 1) < tail_dropout_rate: + tail_idx = random.randint(T // 2, T - 1) if T > 1 else 0 + tail_dropout_mask = torch.arange(T) >= tail_idx # [T] + dropout_mask = dropout_mask | tail_dropout_mask + + mask = mask | dropout_mask + route = route.clone() + route[mask] = float("nan") + return route + + +def _classify_displacement(dx: float, dy: float, move_threshold: float = 0.1) -> str: + """Classify a 2D displacement vector into a direction label. + + Uses the angle of the displacement in ego frame (X=forward, Y=left) to + determine the driving direction. + + Args: + dx: Forward displacement (positive = forward). + dy: Lateral displacement (positive = left). + move_threshold: Minimum displacement magnitude (meters) to count as movement. + + Returns: + One of: "go forward", "turn left", "turn right", "go backward", "stay". + """ + dist = math.sqrt(dx * dx + dy * dy) + if dist < move_threshold: + return "stay" + + angle_deg = math.degrees(math.atan2(dy, dx)) + + if -45 <= angle_deg <= 45: + return "go forward" + elif 45 < angle_deg <= 135: + return "turn left" + elif -135 <= angle_deg < -45: + return "turn right" + else: + return "go backward" + + +def classify_trajectory_to_text( + trajectory: torch.Tensor, + move_threshold: float = 0.1, + min_segment_steps: int = 2, +) -> str: + """Classify a trajectory in ego frame into a brief semantic text description. + + Classifies each consecutive point pair independently, groups consecutive + identical labels, filters out noisy short groups, and joins distinct + phases with "then". + + Works with any (T, 3) path in ego frame — route waypoints or pose + positions returned by :func:`compute_future_trajectory_in_ego_frame`. + + Args: + trajectory: (T, 3) tensor of positions in ego frame (X=forward, Y=left, Z=up). + The first point is treated as the starting position. + move_threshold: Minimum per-step displacement (meters) to count as movement. + min_segment_steps: Minimum consecutive steps required for a direction label to + be kept; shorter runs are treated as noise and dropped. + + Returns: + A description such as "go forward", "stay then go forward", + "turn left then go forward", or "stay" when the trajectory is empty + or all NaN. + """ + valid_mask = ~torch.isnan(trajectory[:, 0]) + valid_pts = trajectory[valid_mask] + + if len(valid_pts) < 2: + return "stay" + + # Classify every consecutive point pair + step_labels: list[str] = [] + for i in range(len(valid_pts) - 1): + dx = valid_pts[i + 1, 0].item() - valid_pts[i, 0].item() + dy = valid_pts[i + 1, 1].item() - valid_pts[i, 1].item() + step_labels.append(_classify_displacement(dx, dy, move_threshold)) + + # Group consecutive identical labels with their counts + groups: list[tuple[str, int]] = [] + for label in step_labels: + if groups and label == groups[-1][0]: + groups[-1] = (label, groups[-1][1] + 1) + else: + groups.append((label, 1)) + + # Filter out groups shorter than min_segment_steps to suppress noise + if len(groups) > 1: + filtered = [(lbl, cnt) for lbl, cnt in groups if cnt >= min_segment_steps] + if not filtered: + # All groups are short — keep the longest one + filtered = [max(groups, key=lambda g: g[1])] + groups = filtered + + # Deduplicate consecutive identical labels (may arise after filtering) + result = [groups[0][0]] + for label, _ in groups[1:]: + if label != result[-1]: + result.append(label) + + return " then ".join(result) + + +def compute_future_trajectory_in_ego_frame( + action_data: dict, + history_len: float | None = None, + future_len: float | None = None, + fps: int = 10, +) -> torch.Tensor: + """Compute future trajectory positions in the ego coordinate frame. + + Transforms absolute future xyz positions so that the origin is the last + history pose and axes align with ego frame (X=forward, Y=left, Z=up). + + Args: + action_data: Dict with keys ``history_xyz``, ``history_quat``, + ``future_xyz`` (and optionally ``future_quat``). + history_len: History length in seconds for slicing. If *None*, uses all. + future_len: Future length in seconds for slicing. If *None*, uses all. + fps: Frames per second. + + Returns: + (T, 3) float tensor of future positions in ego frame. + """ + history_xyz = action_data["history_xyz"] + history_quat = action_data["history_quat"] + future_xyz = action_data["future_xyz"] + + if not isinstance(history_xyz, torch.Tensor): + history_xyz = torch.tensor(history_xyz, dtype=torch.float32) + if not isinstance(history_quat, torch.Tensor): + history_quat = torch.tensor(history_quat, dtype=torch.float32) + if not isinstance(future_xyz, torch.Tensor): + future_xyz = torch.tensor(future_xyz, dtype=torch.float32) + + # Slice to match the requested durations + if history_len is not None: + history_steps = int(history_len * fps) + history_xyz = history_xyz[-history_steps:] + history_quat = history_quat[-history_steps:] + if future_len is not None: + future_steps = int(future_len * fps) + future_xyz = future_xyz[:future_steps] + + # Current pose = last history frame + current_pos = history_xyz[-1] # (3,) + current_quat_wxyz = history_quat[-1] # (4,) [w, x, y, z] + + # Scipy expects [x, y, z, w] + quat_xyzw = current_quat_wxyz[[1, 2, 3, 0]].numpy() + rot_world_to_ego = Rotation.from_quat(quat_xyzw).inv() + + # Translate then rotate into ego frame + future_rel = (future_xyz - current_pos[None, :]).numpy() + future_ego = rot_world_to_ego.apply(future_rel).astype(np.float32) + + return torch.from_numpy(future_ego) + + +class AVDataset(IterableDataset): + """AV dataset that reads tar files from S3 using wdinfo.json.""" + + def __init__( + self, + root: str | list[str] = "/app/assets/examples/av_v2_03292026_wdinfo", + credential_path: str | None = None, + resolution: str | None = None, + fps: int = 10, + mode: str = "policy", + split: str = "train", + seed: int = 0, + shuffle: bool = True, + history_len: float | None = None, + future_len: float | None = None, + rotation_format: RotationConvention = "rot9d", + pose_convention: Literal["backward_anchored", "backward_framewise"] = ("backward_framewise"), + route_lat_noise_range: float = 0.0, + route_long_noise_range: float = 0.0, + route_point_wise_noise: float = 0.0, + route_dropout: bool = False, + route_dropout_rate: float = 0.0, + route_tail_dropout_rate: float = 0.0, + include_route_in_prompt: bool = True, + use_semantic_route_prompt: bool = False, + translation_scale: float = 1.0, + rotation_scale: float = 1.0, + max_action_translation_norm: float | None = None, + align_opencv_pose: bool = False, + ): + """Initialize AVDataset. + + Args: + root: Local packaged demo root, or an S3/GCS-compatible path to a wdinfo directory. + credential_path: Optional path to a JSON file containing S3 credentials. + resolution: Target resolution for video frames (e.g. "256", "480"). If None, keeps original resolution. + fps: Target frames per second for video and actions. + mode: Training mode ('policy', 'forward_dynamics', 'inverse_dynamics', 'image2video', 'joint'). + split: Dataset split ('train', 'val', or 'full'). + seed: Random seed for shuffling. + shuffle: Whether to shuffle tar files during iteration (for training). + history_len: Desired history length in seconds. If None, uses all available history. + future_len: Desired future length in seconds. If None, uses all available future. + rotation_format: Rotation convention for actions (e.g. "rot9d", "rot6d", "euler_xyz"). + pose_convention: Pose format for actions (e.g. "backward_framewise", "backward_framewise"). + route_lat_noise_range: Half-range for uniform lateral (Y) noise on route waypoints. + route_long_noise_range: Half-range for uniform longitudinal (X) noise on route waypoints. + route_point_wise_noise: Std-dev of per-waypoint Gaussian noise on route. + route_dropout: Whether to apply random waypoint dropout on route during training. + route_dropout_rate: Probability of fully masking the route (used when route_dropout=True). + route_tail_dropout_rate: Probability of additional tail dropout (used when route_dropout=True). + include_route_in_prompt: Whether to include route waypoints as text in the prompt. + use_semantic_route_prompt: When True and include_route_in_prompt is True, replace raw + coordinate waypoints with a brief semantic description (e.g. "go forward then turn left"). + translation_scale: Scale factor applied to the translation block of the encoded action. + rotation_scale: Scale factor applied to the rotation block of the encoded action + (uniform scalar, preserves rotation-block geometry). Pass the same value to + `pose_rel_to_abs` when decoding. + max_action_translation_norm: If set, discard the sample when any per-frame + scaled translation L2 norm exceeds this value. Acts as an outlier + filter to prevent loss spikes from extreme camera motion. + align_opencv_pose: If True, transform pose rotations from car body-frame + convention (x=forward, y=left, z=up) to OpenCV camera convention + (x=right, y=down, z=forward) before computing relative actions. + """ + super().__init__() + + if isinstance(root, str): + root = [root] + self.roots = [r.rstrip("/") for r in root] + self.credential_path = credential_path + self.resolution = resolution + self.fps = fps + self.mode = mode + self.split = split.lower().strip() + self.seed = seed + self.shuffle = shuffle + self._epoch = 0 + self.history_len = history_len + self.future_len = future_len + self.rotation_format: RotationConvention = rotation_format + self.pose_convention: Literal["absolute", "backward_anchored", "backward_framewise"] = pose_convention + self.route_lat_noise_range = route_lat_noise_range + self.route_long_noise_range = route_long_noise_range + self.route_point_wise_noise = route_point_wise_noise + self.route_dropout = route_dropout + self.route_dropout_rate = route_dropout_rate + self.route_tail_dropout_rate = route_tail_dropout_rate + self.include_route_in_prompt = include_route_in_prompt + self.use_semantic_route_prompt = use_semantic_route_prompt + self.translation_scale = translation_scale + self.rotation_scale = rotation_scale + self.max_action_translation_norm = max_action_translation_norm + self.align_opencv_pose = align_opencv_pose + # Validate mode + valid_modes = ["joint", "forward_dynamics", "inverse_dynamics", "policy", "image2video"] + if mode not in valid_modes: + raise ValueError(f"mode must be one of {valid_modes}, got {mode}") + + # Validate split + if self.split not in {"train", "val", "valid", "validation", "eval", "test", "full"}: + raise ValueError(f"Unsupported {split=}. Use train/val/full.") + + # Roots may be S3/GCS-compatible paths or local packaged demo roots. + for r in self.roots: + if not (r.startswith("s3://") or r.startswith("gs://") or Path(r).exists()): + raise ValueError(f"root must be an S3/GCS path or existing local path, got: {r}") + + # Configure S3 backend using easy_io + self._setup_s3_backend() + + # Load tar files from wdinfo.json + self._tar_files: list[str] = [] + self._total_key_count: int = 0 + self._chunk_size: int = 10 + + self._load_wdinfo() + + log.info( + f"Initialized AVDataset: root={self.roots}, split={self.split}, " + f"resolution={resolution}, fps={fps}, mode={mode}, " + f"num_tar_files={len(self._tar_files)}, " + f"total_samples={self._total_key_count}" + ) + + def _setup_s3_backend(self) -> None: + """Configure the easy_io S3 backend. Called in __init__ and __iter__ for worker processes.""" + backend_args = {"backend": "s3", "path_mapping": None} + if self.credential_path: + backend_args["s3_credential_path"] = self.credential_path + easy_io.set_s3_backend(backend_args=backend_args) + + def _load_wdinfo(self) -> None: + """Load wdinfo.json for the current split from all roots and build tar file list. + + Supports two directory layouts per root: + - Split-based: ``{root}/train/wdinfo.json``, ``{root}/val/wdinfo.json`` + - Flat: ``{root}/wdinfo.json`` (treated as train-only) + + Split-based paths are tried first; the flat path is used as a fallback + only when no split-based wdinfo was found and the requested split + includes "train". + """ + self._tar_files = [] + self._total_key_count = 0 + + for root in self.roots: + is_remote = root.startswith(("s3://", "gs://")) + bucket = root.replace("s3://", "").replace("gs://", "").split("/")[0] if is_remote else "" + + # Determine which splits we need + if self.split in {"val", "valid", "validation", "eval", "test"}: + target_splits = ["val"] + elif self.split == "train": + target_splits = ["train"] + elif self.split == "full": + target_splits = ["train", "val"] + else: + raise ValueError(f"Unsupported split: {self.split}") + + # Try split-based layout first ({root}/train/wdinfo.json, {root}/val/wdinfo.json) + wdinfo_entries: list[tuple[str, dict]] = [] + for split_name in target_splits: + split_path = f"{root}/{split_name}/wdinfo.json" + try: + if is_remote: + wdinfo_entries.append((split_path, json.loads(easy_io.get(split_path)))) + else: + path = Path(split_path) + if path.exists(): + wdinfo_entries.append((split_path, json.loads(path.read_text()))) + except Exception: + pass + + # Fall back to flat layout ({root}/wdinfo.json, treated as train-only) + if not wdinfo_entries and "train" in target_splits: + flat_path = f"{root}/wdinfo.json" + try: + if is_remote: + wdinfo_entries.append((flat_path, json.loads(easy_io.get(flat_path)))) + else: + path = Path(flat_path) + if path.exists(): + wdinfo_entries.append((flat_path, json.loads(path.read_text()))) + except Exception: + pass + + if not wdinfo_entries: + log.warning(f"No wdinfo.json found for root={root}, split={self.split}") + + for wdinfo_path, wdinfo in wdinfo_entries: + log.info(f"Loading wdinfo from: {wdinfo_path}") + + # Extract metadata + self._chunk_size = wdinfo.get("chunk_size", 10) + data_root = wdinfo.get("root", "") + data_list = wdinfo.get("data_list", []) + + if not data_list: + log.warning(f"No tar files found in wdinfo: {wdinfo_path}") + continue + + # Reconstruct full tar paths. + if is_remote: + tar_root = f"s3://{bucket}/{data_root}".rstrip("/") + else: + tar_root = str((Path(root) / data_root).resolve()) if data_root else str(Path(root).resolve()) + tar_paths = [f"{tar_root}/{filename}" for filename in data_list] + self._tar_files.extend(tar_paths) + + # Accumulate total sample count + self._total_key_count += wdinfo.get("total_key_count", len(data_list) * self._chunk_size) + + log.info( + f"Loaded {len(data_list)} tar files from wdinfo, " + f"with {wdinfo.get('total_key_count', len(data_list) * self._chunk_size)} samples" + ) + + if not self._tar_files: + raise RuntimeError(f"No tar files found in wdinfo at {self.roots}") + + def __len__(self) -> int: + """Return the estimated number of samples in the current split.""" + return self._total_key_count + + def _process_sample(self, pkl_data: dict, key: str, global_idx: int) -> dict | None: + """Process a single sample from pkl data. + + Args: + pkl_data: Dictionary with 'video' (bytes) and 'action' (pickled dict). + key: Sample key (basename without .pkl). + global_idx: Global sample index for __key__. + + Returns: + Processed sample dictionary, or None if the sample should be discarded. + """ + # Extract video bytes + video_bytes = pkl_data.get("video") + if video_bytes is None: + raise RuntimeError(f"No video found for key {key}") + + # Extract action data + action_bytes = pkl_data.get("action") + if action_bytes is None: + raise RuntimeError(f"Missing action data for key {key}") + + action_data = pickle.loads(action_bytes) + + # Extract route data + route_bytes = pkl_data.get("route") + if route_bytes is not None: + route_data = pickle.loads(route_bytes) + if not isinstance(route_data, torch.Tensor): + route = torch.tensor(route_data, dtype=torch.float32) # [num_waypoints,3] + else: + route = route_data.float() # [num_waypoints,3] + else: + log.warning(f"No route found for key {key}") + route = torch.full((20, 3), float("nan")) # [20,3] + + # Apply route augmentations during training + if self.split == "train": + route = add_route_noise( + route, + lat_noise_range=self.route_lat_noise_range, + long_noise_range=self.route_long_noise_range, + point_wise_noise=self.route_point_wise_noise, + ) + if self.route_dropout: + route = apply_route_dropout( + route, + dropout_rate=self.route_dropout_rate, + tail_dropout_rate=self.route_tail_dropout_rate, + ) + + # Get original history frame count for video slicing + original_history_steps = len(action_data["history_xyz"]) + + # Decode video + video, _ = decode_video_bytes( + video_bytes, + resolution=self.resolution, + history_len=self.history_len, + future_len=self.future_len, + original_history_steps=original_history_steps, + ) + + # Determine mode for this sample + if self.mode == "joint": + mode = random.choice(["forward_dynamics", "inverse_dynamics", "policy"]) + # mode = random.choice(["policy", "image2video"]) + else: + mode = self.mode + + # Process actions + action_result = process_action_trajectory( + action_data, + history_len=self.history_len, + future_len=self.future_len, + fps=self.fps, + rotation_format=self.rotation_format, + pose_convention=self.pose_convention, + scale=self.translation_scale, + rotation_scale=self.rotation_scale, + max_translation_norm=self.max_action_translation_norm, + align_opencv_pose=self.align_opencv_pose, + ) + if action_result is None: + return None + history_action, future_action = action_result + + # Combine and pad actions + combined_action = torch.cat([history_action, future_action], dim=0) # [T_hist+T_fut,action_dim] + + # FPS as tensor + fps_tensor = torch.tensor(self.fps, dtype=torch.long) # scalar + + # Key as tensor + key_tensor = torch.tensor([global_idx], dtype=torch.long) # [1] + + # Compute actual history/future lengths from data + actual_history_length = history_action.shape[0] + actual_future_length = future_action.shape[0] + + # Generate prompt based on actual data lengths + history_duration = actual_history_length / self.fps + future_duration = actual_future_length / self.fps + + prompt = "You are an autonomous vehicle planning system. " + if self.include_route_in_prompt and mode == "policy": # only include route in prompt for policy mode + if self.use_semantic_route_prompt: + future_ego = compute_future_trajectory_in_ego_frame( + action_data, self.history_len, self.future_len, self.fps + ) + trajectory_desc = classify_trajectory_to_text(future_ego) + prompt += f"Please {trajectory_desc}. " + else: + num_waypoints = route.shape[0] + waypoints_str = ", ".join( + "nan" if torch.isnan(wp[0]) else f"({wp[0]:.2f}, {wp[1]:.2f}, {wp[2]:.2f})" for wp in route + ) + prompt += ( + f"The navigation route has {num_waypoints} waypoints " + f"(XYZ in ego frame with X=forward, Y=left, Z=up): " + f"[{waypoints_str}]. A nan waypoint means that waypoint is not available. " + ) + # prompt += f"Predict the future {future_duration:.1f}s action trajectory at {self.fps}Hz." + + + sample = { + "video": video, + "action": combined_action, + "action_history": history_action, + "action_future": future_action, + "route": route, + "conditioning_fps": fps_tensor, + "prompt": prompt, + "ai_caption": prompt, + "mode": mode, + "__key__": key_tensor, + "history_length": actual_history_length, + "future_length": actual_future_length, + "viewpoint": "ego_view", + } + return sample + + def __iter__(self) -> Iterator[dict[str, torch.Tensor | str | int]]: + """Iterate over the dataset, loading tar files from S3.""" + # Re-configure S3 backend in case this is running in a worker process after unpickling + self._setup_s3_backend() + + # Optionally shuffle tar files for training + tar_files = list(self._tar_files) + if self.shuffle: + rng = random.Random(self.seed + self._epoch) + rng.shuffle(tar_files) + self._epoch += 1 + + global_idx = 0 + + for tar_path in tar_files: + try: + # Read tar file bytes. Local packaged demo paths should not be + # decoded as text through easy_io.get(). + if tar_path.startswith(("s3://", "gs://")): + tar_bytes = easy_io.get_bytes(tar_path) + tar_cm = tarfile.open(fileobj=io.BytesIO(tar_bytes), mode="r:*") + else: + tar_cm = tarfile.open(tar_path, mode="r:*") + + with tar_cm as tar: + for member in tar.getmembers(): + if not member.name.endswith(".pkl"): + continue + + try: + # Extract and process the sample + f_member = tar.extractfile(member) + if f_member is None: + log.warning(f"Failed to extract {member.name} from {tar_path}") + continue + + try: + pkl_data = pickle.load(f_member) + finally: + f_member.close() + + key = member.name.rsplit(".", 1)[0] + + sample = self._process_sample(pkl_data, key, global_idx) + if sample is not None: + yield sample + global_idx += 1 + + except Exception as e: + log.warning(f"Failed to process sample {member.name} from {tar_path}: {e}") + continue + + except Exception as e: + log.warning(f"Failed to read tar file {tar_path}: {e}") + continue + + +# PYTHONPATH=. python projects/cosmos3/vfm/datasets/action/av_dataset.py +if __name__ == "__main__": + import json as _json + import os + import time + + import torchvision + + from cosmos_framework.data.vfm.action.pose_utils import pose_rel_to_abs + + _ACTION_SCALE = 1.35 + _ROTATION_SCALE = 1.0 + _ROTATION_FORMAT = "rot6d" + _POSE_CONVENTION = "backward_framewise" + + dataset = AVDataset( + root=["/app/assets/examples/av_v2_03292026_wdinfo"], + split="train", + shuffle=True, + fps=10, + mode="inverse_dynamics", + history_len=0.1, + future_len=6.0, + rotation_format=_ROTATION_FORMAT, + pose_convention=_POSE_CONVENTION, + translation_scale=_ACTION_SCALE, + rotation_scale=_ROTATION_SCALE, + resolution="480", + include_route_in_prompt=False, + use_semantic_route_prompt=False, + # align_opencv_pose=False, + ) + dataset_iter = iter(dataset) + os.makedirs("temp", exist_ok=True) + + for i in range(5): + print(f"==================== Sample {i} ====================") + _t0 = time.time() + data = next(dataset_iter) + _t1 = time.time() + print(f"{'Loading time':<25}: {_t1 - _t0:.2f}s") + + print(f"{'video shape':<25}: {data['video'].shape}") # [C,T,H,W] + print(f"{'action shape':<25}: {data['action'].shape}") # [T,action_dim] + print(f"{'action_history shape':<25}: {data['action_history'].shape}") + print(f"{'action_future shape':<25}: {data['action_future'].shape}") + print(f"{'route shape':<25}: {data['route'].shape}") + print(f"{'history_length':<25}: {data['history_length']}") + print(f"{'future_length':<25}: {data['future_length']}") + print(f"{'conditioning_fps':<25}: {data['conditioning_fps'].item()}") + print(f"{'mode':<25}: {data['mode']}") + print(f"{'prompt':<25}: {data['prompt']}") + + # save video + video = data["video"].permute(1, 0, 2, 3) # [C,T,H,W] -> [T,C,H,W] + video_path = f"temp/av_sample_{i}.mp4" + torchvision.io.write_video( + video_path, video.permute(0, 2, 3, 1).numpy(), fps=data["conditioning_fps"].item() + ) # expects (T, H, W, C) + print(f"Saved video to {video_path}") + + # reconstruct absolute poses from relative actions and save as json + camera_poses = pose_rel_to_abs( + data["action"].float().numpy(), + rotation_format=_ROTATION_FORMAT, + pose_convention=_POSE_CONVENTION, + translation_scale=_ACTION_SCALE, + rotation_scale=_ROTATION_SCALE, + ) + pose_path = f"temp/av_sample_{i}_camera.json" + with open(pose_path, "w") as f: + _json.dump(camera_poses.tolist(), f) + print(f"Saved camera poses to {pose_path}") diff --git a/cosmos-framework/cosmos_framework/data/vfm/action/bridge_orig_lerobot_dataset.py b/cosmos-framework/cosmos_framework/data/vfm/action/bridge_orig_lerobot_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..f53aa0a570706363fda55af915440163fa56a13a --- /dev/null +++ b/cosmos-framework/cosmos_framework/data/vfm/action/bridge_orig_lerobot_dataset.py @@ -0,0 +1,185 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: OpenMDW-1.1 + +"""Minimal Bridge Orig LeRobot dataset for Cosmos Action examples.""" + +from __future__ import annotations + +from typing import Any, Literal + +import numpy as np +import torch +from torch.utils.data import Dataset + +from cosmos_framework.data.vfm.action._lerobot_local import ( + build_result, + choose_mode, + load_local_lerobot, + load_video_key, + pick_caption, + rows_for_index, + sample_count, + task_text, +) +from cosmos_framework.data.vfm.action.pose_utils import ( + build_abs_pose_from_components, + pose_abs_to_rel, +) + +PoseConvention = Literal["backward_framewise"] +Viewpoint = Literal["ego_view"] + +_IMAGE_FEATURE = "observation.images.image_0" +_STATE_FEATURE = "observation.state" +_ACTION_FEATURE = "action" + +# Raw Bridge state -> kinematics frame. The WidowX controller records +# R_state = R_fk @ DEFAULT_ROTATION.T, so R_fk = R_state @ DEFAULT_ROTATION. +_DEFAULT_ROTATION = np.array( + [[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [-1.0, 0.0, 0.0]], + dtype=np.float32, +) + +# Kinematics frame -> OpenCV frame used by Cosmos action training. +_BRIDGE_TO_OPENCV = np.array( + [[0.0, 0.0, 1.0], [-1.0, 0.0, 0.0], [0.0, -1.0, 0.0]], + dtype=np.float32, +) + +# Re-reference from ee_gripper_link to gripper_link in the kinematics frame. +_TCP_TO_FLANGE = np.array( + [ + [1.0, 0.0, 0.0, -0.093575], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, +) + +class BridgeOrigLeRobotDataset(Dataset): + """Bridge Orig LeRobot dataset matching Cosmos Action v1.2 defaults. + + Supported action layout is 10D: + + [pos_delta(3), rot6d_delta(6), gripper(1)] + + This stripped wrapper keeps only the local LeRobot asset path used by the + action cookbook: single `image_0` ego-view video, backward-framewise rot6d + actions, and quantile-rotation normalization. + """ + + def __init__( + self, + root: str = "/app/assets/examples/bridge_lerobot_v3", + fps: float = 5.0, + chunk_length: int = 16, + mode: str = "joint", + pose_convention: PoseConvention = "backward_framewise", + tolerance_s: float = 1e-4, + viewpoint: Viewpoint = "ego_view", + sample_stride: int = 1, + split: str = "full", + split_seed: int = 42, + split_val_ratio: float = 0.02, + enable_fast_init: bool = False, + ) -> None: + super().__init__() + if pose_convention != "backward_framewise": + raise NotImplementedError("This minimal Bridge dataset only supports backward_framewise pose deltas.") + if viewpoint != "ego_view": + raise NotImplementedError("This minimal Bridge dataset only supports ego_view.") + + del split, split_seed, split_val_ratio, enable_fast_init + self._fps = float(fps) + self._dt = 1.0 / self._fps + self._chunk_length = int(chunk_length) + self._sample_stride = int(sample_stride) + if self._sample_stride < 1: + raise ValueError(f"sample_stride must be >= 1, got {self._sample_stride}") + self._mode = mode + self._pose_convention = pose_convention + self._tolerance_s = float(tolerance_s) + self._viewpoint = viewpoint + self._root, self._info, self._episodes, self._tasks, self._rows = load_local_lerobot(root) + + @property + def fps(self) -> float: + return self._fps + + @property + def chunk_length(self) -> int: + return self._chunk_length + + @property + def mode(self) -> str: + return self._mode + + @mode.setter + def mode(self, value: str) -> None: + self._mode = value + + @property + def action_dim(self) -> int: + return 10 + + def __getitem__(self, idx: int) -> dict[str, Any]: + mode = choose_mode(self._mode) + observation_rows = rows_for_index(self._rows, idx, self._chunk_length, self._sample_stride) + episode = self._episodes[int(observation_rows[0]["episode_index"])] + action_rows = observation_rows[: self._chunk_length] + + video = self._load_video(episode, observation_rows) + raw_action, initial_pose = self._build_raw_action(observation_rows, action_rows) + ai_caption = pick_caption(task_text(self._tasks, observation_rows, "Bridge demonstration")) + + return self._build_result( + mode=mode, + video=video, + action=raw_action, + ai_caption=ai_caption, + initial_pose=initial_pose, + ) + + def _load_video(self, episode: dict[str, Any], observation_rows: list[dict[str, Any]]) -> torch.Tensor: + return load_video_key(self._root, self._info, episode, observation_rows, _IMAGE_FEATURE, self._tolerance_s) + + def _build_raw_action( + self, + observation_rows: list[dict[str, Any]], + action_rows: list[dict[str, Any]], + ) -> tuple[torch.Tensor, torch.Tensor]: + state = np.asarray([row[_STATE_FEATURE] for row in observation_rows], dtype=np.float32) + poses_abs = build_abs_pose_from_components(state[:, 0:3], state[:, 3:6], "euler_xyz") + + poses_abs[:, :3, :3] = poses_abs[:, :3, :3] @ _DEFAULT_ROTATION.astype(poses_abs.dtype) + poses_abs = poses_abs @ _TCP_TO_FLANGE.astype(poses_abs.dtype) + poses_abs[:, :3, :3] = poses_abs[:, :3, :3] @ _BRIDGE_TO_OPENCV.astype(poses_abs.dtype) + + initial_pose = torch.from_numpy(poses_abs[0].copy()).float() + poses_rel = pose_abs_to_rel(poses_abs, rotation_format="rot6d", pose_convention=self._pose_convention) + gripper = np.asarray([row[_ACTION_FEATURE][6] for row in action_rows], dtype=np.float32).reshape(-1, 1) + action = np.concatenate([poses_rel[-self._chunk_length :], gripper[-self._chunk_length :]], axis=-1) + return torch.from_numpy(action).float(), initial_pose + + def _build_result( + self, + *, + mode: str, + video: torch.Tensor, + action: torch.Tensor, + ai_caption: str, + **extras: Any, + ) -> dict[str, Any]: + return build_result( + mode=mode, + video=video, + action=action, + ai_caption=ai_caption, + fps=self._fps, + viewpoint=self._viewpoint, + **extras, + ) + + def __len__(self) -> int: + return sample_count(self._rows, self._chunk_length, self._sample_stride) diff --git a/cosmos-framework/cosmos_framework/data/vfm/action/droid_lerobot_dataset.py b/cosmos-framework/cosmos_framework/data/vfm/action/droid_lerobot_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..14338dc484cfb0b95b14e672beecb90fd76b34cf --- /dev/null +++ b/cosmos-framework/cosmos_framework/data/vfm/action/droid_lerobot_dataset.py @@ -0,0 +1,183 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: OpenMDW-1.1 + +"""Minimal DROID LeRobot dataset for Cosmos Action v1.2 defaults.""" + +from __future__ import annotations + +from typing import Any, Literal + +import numpy as np +import torch +import torch.nn.functional as F +from torch.utils.data import Dataset + +from cosmos_framework.data.vfm.action._lerobot_local import ( + build_result, + choose_mode, + load_local_lerobot, + load_video_key, + pick_caption, + rows_for_index, + sample_count, + task_text, +) +from cosmos_framework.data.vfm.action.pose_utils import ( + build_abs_pose_from_components, + pose_abs_to_rel, +) + +PoseConvention = Literal["backward_framewise"] +Viewpoint = Literal["concat_view"] + +_IMAGE_FEATURES = { + "wrist": "observation.image.wrist_image_left", + "left": "observation.image.exterior_image_1_left", + "right": "observation.image.exterior_image_2_left", +} +_STATE_FEATURE = "observation.state.cartesian_position" + +# 90-degree clockwise rotation about the Z axis in the local frame. This matches +# the production DROID wrapper conversion from Franka panda_link8 to OpenCV. +_DROID_TO_OPENCV: np.ndarray = np.array( + [[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]], + dtype=np.float32, +) + +class DROIDLeRobotDataset(Dataset): + """DROID Action dataset matching the v1.2 midtrain config default. + + The supported action layout is 10D ``[pos_delta(3), rot6d_delta(6), gripper(1)]``. + Unsupported branches from the production wrapper, such as joint-space + actions, filter dictionaries, temporal-segment validation, state prefixing, + and image augmentation, are intentionally omitted. + """ + + def __init__( + self, + root: str = "/app/assets/examples/droid_plus_lerobot_640x360_20260412/success", + fps: float = 15.0, + chunk_length: int = 16, + mode: str = "joint", + pose_convention: PoseConvention = "backward_framewise", + tolerance_s: float = 2e-4, + viewpoint: Viewpoint = "concat_view", + sample_stride: int = 1, + split: str = "full", + use_success_only: bool = True, + enable_fast_init: bool = False, + ) -> None: + super().__init__() + if pose_convention != "backward_framewise": + raise NotImplementedError("This minimal DROID dataset only supports backward_framewise pose deltas.") + if viewpoint != "concat_view": + raise NotImplementedError("This minimal DROID dataset only supports concat_view.") + + self._fps = float(fps) + self._dt = 1.0 / self._fps + self._chunk_length = int(chunk_length) + self._sample_stride = int(sample_stride) + if self._sample_stride < 1: + raise ValueError(f"sample_stride must be >= 1, got {self._sample_stride}") + self._mode = mode + self._pose_convention = pose_convention + self._tolerance_s = float(tolerance_s) + self._viewpoint = viewpoint + + del split, use_success_only, enable_fast_init + from pathlib import Path + + root_path = Path(root) + if not (root_path / "meta" / "info.json").exists() and (root_path / "success" / "meta" / "info.json").exists(): + root_path = root_path / "success" + self._root, self._info, self._episodes, self._tasks, self._rows = load_local_lerobot(root_path) + + @property + def fps(self) -> float: + return self._fps + + @property + def chunk_length(self) -> int: + return self._chunk_length + + @property + def mode(self) -> str: + return self._mode + + @mode.setter + def mode(self, value: str) -> None: + self._mode = value + + @property + def action_dim(self) -> int: + return 10 + + def __getitem__(self, idx: int) -> dict[str, Any]: + mode = choose_mode(self._mode) + observation_rows = rows_for_index(self._rows, idx, self._chunk_length, self._sample_stride) + episode = self._episodes[int(observation_rows[0]["episode_index"])] + action_rows = observation_rows[: self._chunk_length] + + video = self._load_concat_video(episode, observation_rows) + raw_action, initial_pose = self._build_raw_action(observation_rows, action_rows) + ai_caption = pick_caption(task_text(self._tasks, observation_rows, "DROID demonstration")) + + return self._build_result( + mode=mode, + video=video, + action=raw_action, + ai_caption=ai_caption, + initial_pose=initial_pose, + additional_view_description=( + "The top row is from the wrist-mounted camera. " + "The bottom row contains two horizontally concatenated third-person perspective views of the scene from opposite sides, with the robot visible." + ), + ) + + def _load_concat_video(self, episode: dict[str, Any], observation_rows: list[dict[str, Any]]) -> torch.Tensor: + wrist = load_video_key(self._root, self._info, episode, observation_rows, _IMAGE_FEATURES["wrist"], self._tolerance_s) + left = load_video_key(self._root, self._info, episode, observation_rows, _IMAGE_FEATURES["left"], self._tolerance_s) + right = load_video_key(self._root, self._info, episode, observation_rows, _IMAGE_FEATURES["right"], self._tolerance_s) + _, _, height_ref, width_ref = wrist.shape + half_h, half_w = height_ref // 2, width_ref // 2 + left = F.interpolate(left, size=(half_h, half_w), mode="bilinear", align_corners=False) + right = F.interpolate(right, size=(half_h, half_w), mode="bilinear", align_corners=False) + return torch.cat([wrist, torch.cat([left, right], dim=-1)], dim=-2) + + def _build_raw_action( + self, + observation_rows: list[dict[str, Any]], + action_rows: list[dict[str, Any]], + ) -> tuple[torch.Tensor, torch.Tensor]: + state = np.asarray([row[_STATE_FEATURE] for row in observation_rows], dtype=np.float32) + poses_abs = build_abs_pose_from_components(state[:, 0:3], state[:, 3:6], "euler_xyz") + poses_abs[:, :3, :3] = poses_abs[:, :3, :3] @ _DROID_TO_OPENCV + + initial_pose = torch.from_numpy(poses_abs[0].copy()).float() + poses_rel = pose_abs_to_rel(poses_abs, rotation_format="rot6d", pose_convention=self._pose_convention) + gripper = np.asarray([row["action.gripper_position"] for row in action_rows], dtype=np.float32).reshape(-1, 1) + gripper = 1.0 - gripper + action = np.concatenate([poses_rel[-self._chunk_length :], gripper[-self._chunk_length :]], axis=-1) + return torch.from_numpy(action).float(), initial_pose + + def _build_result( + self, + *, + mode: str, + video: torch.Tensor, + action: torch.Tensor, + ai_caption: str, + **extras: Any, + ) -> dict[str, Any]: + return build_result( + mode=mode, + video=video, + action=action, + ai_caption=ai_caption, + fps=self._fps, + viewpoint=self._viewpoint, + **extras, + ) + + def __len__(self) -> int: + return sample_count(self._rows, self._chunk_length, self._sample_stride) diff --git a/cosmos-framework/cosmos_framework/data/vfm/action/fractal.py b/cosmos-framework/cosmos_framework/data/vfm/action/fractal.py new file mode 100644 index 0000000000000000000000000000000000000000..cea51ee3637755914be01ce643046202ce06e902 --- /dev/null +++ b/cosmos-framework/cosmos_framework/data/vfm/action/fractal.py @@ -0,0 +1,117 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: OpenMDW-1.1 + +"""Minimal local Fractal/Google Robot LeRobot dataset for the action viewer.""" + +from __future__ import annotations + +from typing import Any, Literal, cast + +import numpy as np +import torch +from torch.utils.data import Dataset + +from cosmos_framework.data.vfm.action._lerobot_local import ( + build_result, + choose_mode, + load_local_lerobot, + load_video_key, + pick_caption, + rows_for_index, + sample_count, + task_text, +) +from cosmos_framework.data.vfm.action.pose_utils import PoseConvention, build_abs_pose_from_components, pose_abs_to_rel + +PoseConventionArg = Literal["backward_anchored", "backward_framewise"] +_GOOGLE_ROBOT_TO_OPENCV = np.array([[0, 1, 0], [-1, 0, 0], [0, 0, 1]], dtype=np.float32) + +_TCP_TO_FLANGE = np.array([ + [+0.9999897671, -0.0008686425, +0.0044397163, -0.0050618476], + [+0.0008745501, +0.9999987346, -0.0013288658, -0.0016717725], + [-0.0044385564, +0.0013327349, +0.9999892615, -0.1635144743], + [+0.0000000000, +0.0000000000, +0.0000000000, +1.0000000000], +], dtype=np.float32) + +_IMAGE_FEATURE = "observation.images.image" +_STATE_FEATURE = "observation.state" +_ACTION_FEATURE = "action" + + +class FractalLeRobotDataset(Dataset): + """Standalone Fractal wrapper backed by packaged local parquet/video files.""" + + def __init__( + self, + root: str = "/app/assets/examples/fractal20220817_data", + fps: float = 3.0, + chunk_length: int = 16, + split_seed: int = 42, + split_val_ratio: float = 0.05, + split: str = "train", + mode: str = "policy", + pose_convention: PoseConventionArg = "backward_framewise", + viewpoint: str = "ego_view", + enable_fast_init: bool = False, + sample_stride: int = 1, + ) -> None: + super().__init__() + del split_seed, split_val_ratio, split, enable_fast_init + self._fps = float(fps) + self._chunk_length = int(chunk_length) + self._mode = mode + self._pose_convention = pose_convention + self._viewpoint = viewpoint + self._sample_stride = int(sample_stride) + self._root, self._info, self._episodes, self._tasks, self._rows = load_local_lerobot(root) + + @property + def fps(self) -> float: + return self._fps + + @property + def chunk_length(self) -> int: + return self._chunk_length + + @property + def mode(self) -> str: + return self._mode + + @mode.setter + def mode(self, value: str) -> None: + self._mode = value + + @property + def action_dim(self) -> int: + return 10 + + def __len__(self) -> int: + return sample_count(self._rows, self._chunk_length, self._sample_stride) + + def __getitem__(self, idx: int) -> dict[str, Any]: + rows = rows_for_index(self._rows, idx, self._chunk_length, self._sample_stride) + episode = self._episodes[int(rows[0]["episode_index"])] + video = load_video_key(self._root, self._info, episode, rows, _IMAGE_FEATURE, tolerance_s=1e-4) + + state = np.asarray([row[_STATE_FEATURE] for row in rows], dtype=np.float32) + raw_action = np.asarray([row[_ACTION_FEATURE] for row in rows[:-1]], dtype=np.float32) + poses_abs = build_abs_pose_from_components(state[:, 0:3], state[:, 3:7], "quat_xyzw") + poses_abs = poses_abs @ _TCP_TO_FLANGE.astype(poses_abs.dtype) + poses_abs[:, :3, :3] = poses_abs[:, :3, :3] @ _GOOGLE_ROBOT_TO_OPENCV.astype(poses_abs.dtype) + initial_pose = torch.from_numpy(poses_abs[0].copy()).float() + poses_rel = pose_abs_to_rel( + poses_abs, + rotation_format="rot6d", + pose_convention=cast(PoseConvention, self._pose_convention), + ) + action = torch.cat([torch.from_numpy(poses_rel).float(), torch.from_numpy(raw_action[:, [6]]).float()], dim=-1) + caption = pick_caption(task_text(self._tasks, rows, "Fractal demonstration")) + return build_result( + mode=choose_mode(self._mode), + video=video, + action=action, + ai_caption=caption, + fps=self._fps, + viewpoint=self._viewpoint, + initial_pose=initial_pose, + ) diff --git a/cosmos-framework/cosmos_framework/data/vfm/action/pose_utils.py b/cosmos-framework/cosmos_framework/data/vfm/action/pose_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fe0014be0cc14a74c3d92786ac4ac3afe27c6691 --- /dev/null +++ b/cosmos-framework/cosmos_framework/data/vfm/action/pose_utils.py @@ -0,0 +1,541 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: OpenMDW-1.1 + +"""Rotation and pose utilities for action datasets. + +This module centralizes three related responsibilities used across the action +dataset stack: + +1. Converting rotations between the conventions used by the datasets and the + action model (`euler_xyz`, quaternion, axis-angle, rot6d, rot9d, matrix). +2. Building absolute homogeneous poses of shape ``(T, 4, 4)`` from per-frame + translation and rotation components. +3. Converting trajectories between absolute-pose form and the relative-pose + action vectors consumed by the datasets. + + The relative-pose action vectors always follow the shared layout + ``[translation(3), rotation(...)]``. The rotation block is encoded with the + requested rotation output convention, and `convert_rotation()` is the + canonical public entrypoint for representation conversion. +""" + +from typing import Literal + +import numpy as np +import torch +from scipy.spatial.transform import Rotation as R + +PoseConvention = Literal["absolute", "backward_anchored", "backward_framewise"] +RotationConvention = Literal["matrix", "euler_xyz", "quat_xyzw", "quat_wxyz", "rot6d", "axisangle", "rot9d"] + + +def _to_numpy_float32(array: torch.Tensor | np.ndarray) -> np.ndarray: + """Convert an input array to a NumPy ``float32`` array. + + Args: + array: A torch tensor or NumPy array with arbitrary leading dimensions. + + Returns: + A NumPy array with dtype ``float32``. Torch tensors are moved to CPU + before conversion. NumPy inputs are converted with ``copy=False`` + semantics when possible. + + Raises: + ValueError: If a torch tensor with ``requires_grad=True`` is passed. + These utilities are non-differentiable; callers must explicitly + detach tensors before conversion. + """ + if isinstance(array, torch.Tensor): + if array.requires_grad: + raise ValueError( + "pose_utils conversion is non-differentiable; call `.detach()` " + "explicitly before passing tensors with requires_grad=True" + ) + return array.cpu().numpy().astype(np.float32, copy=False) + return np.asarray(array, dtype=np.float32) + + +def _normalize_rotation_matrices(rot_matrices: np.ndarray) -> np.ndarray: + """Project approximate matrices onto valid rotation matrices. + + This helper uses an SVD-based projection onto ``SO(3)``. It is mainly used + when decoding rotations from network-like representations such as rot6d or rot9d + where the input may not already be perfectly orthonormal. + + Args: + rot_matrices: Array of shape ``(..., 3, 3)`` containing one or more + approximate rotation matrices. + + Returns: + Array of shape ``(..., 3, 3)`` whose trailing matrices are proper + rotation matrices with determinant ``+1``. + + Raises: + ValueError: If the input does not have trailing shape ``(3, 3)``. + """ + matrices = np.asarray(rot_matrices, dtype=np.float32) + if matrices.ndim < 2 or matrices.shape[-2:] != (3, 3): + raise ValueError(f"Rotation matrices must have shape (..., 3, 3), got {matrices.shape}") + + original_shape = matrices.shape[:-2] + matrices_flat = matrices.reshape(-1, 3, 3) + + # Batched SVD projection to SO(3). + U, _, Vt = np.linalg.svd(matrices_flat) + normalized = U @ Vt + + # Ensure determinant is +1 (proper rotations, no reflections). + det = np.linalg.det(normalized) + reflection_mask = det < 0 + if np.any(reflection_mask): + U_reflect = U.copy() + U_reflect[reflection_mask, :, -1] *= -1 + normalized[reflection_mask] = U_reflect[reflection_mask] @ Vt[reflection_mask] + + return normalized.astype(np.float32, copy=False).reshape(*original_shape, 3, 3) + + +def convert_rotation( + rotation: torch.Tensor | np.ndarray, + input_format: RotationConvention, + output_format: RotationConvention, + normalize_matrix: bool = False, +) -> torch.Tensor | np.ndarray: + """Convert rotations between the conventions used by action datasets. + + The function first maps the input representation to rotation matrices and + then emits the requested output convention. It is the single conversion seam + used by the public pose helpers so that all code paths share the same + convention handling. + + Supported input conventions: + - ``matrix``: rotation matrices with shape ``(..., 3, 3)`` + - ``euler_xyz``: Euler xyz angles in radians with shape ``(..., 3)`` + - ``quat_xyzw``: quaternions in SciPy's xyzw order with shape ``(..., 4)`` + - ``quat_wxyz``: quaternions in wxyz order with shape ``(..., 4)`` + - ``rot6d``: column-based 6D representation with shape ``(..., 6)`` + - ``rot9d``: flattened rotation matrices with shape ``(..., 9)`` + - ``axisangle``: axis-angle vectors with shape ``(..., 3)`` + + Supported output conventions: + - ``matrix`` + - ``euler_xyz`` + - ``quat_xyzw`` + - ``quat_wxyz`` + - ``rot6d`` + - ``axisangle`` + - ``rot9d`` + + Args: + rotation: Input rotations in the representation specified by + ``input_format``. + input_format: Convention used by ``rotation``. + output_format: Convention to return. + normalize_matrix: Whether to project intermediate matrices to a valid + rotation before returning. This is most useful when decoding from + approximate ``rot6d``/``rot9d`` inputs or non-unit quaternions. + + Returns: + Rotations with the same leading shape as the input, expressed in the + requested output convention. Torch inputs return torch outputs on the + same device with the same dtype; NumPy inputs return NumPy arrays. + + Raises: + ValueError: If the input shape is incompatible with ``input_format`` or + if either format is unsupported. + """ + input_is_tensor = isinstance(rotation, torch.Tensor) + input_dtype = rotation.dtype if input_is_tensor else None + input_device = rotation.device if input_is_tensor else None + rotation_np = _to_numpy_float32(rotation) + + if input_format == "matrix": + if rotation_np.ndim < 2 or rotation_np.shape[-2:] != (3, 3): + raise ValueError(f"matrix rotation must have shape (..., 3, 3), got {rotation_np.shape}") + original_shape = rotation_np.shape[:-2] + matrices_flat = rotation_np.reshape(-1, 3, 3) + if normalize_matrix: + matrices_flat = _normalize_rotation_matrices(matrices_flat).reshape(-1, 3, 3) + elif input_format == "euler_xyz": + if rotation_np.ndim < 1 or rotation_np.shape[-1] != 3: + raise ValueError(f"{input_format} rotation must have shape (..., 3), got {rotation_np.shape}") + original_shape = rotation_np.shape[:-1] + matrices_flat = R.from_euler("xyz", rotation_np.reshape(-1, 3), degrees=False).as_matrix().astype(np.float32) + elif input_format in ("quat_xyzw", "quat_wxyz"): + if rotation_np.ndim < 1 or rotation_np.shape[-1] != 4: + raise ValueError(f"{input_format} rotation must have shape (..., 4), got {rotation_np.shape}") + original_shape = rotation_np.shape[:-1] + quaternions = rotation_np.reshape(-1, 4) + if input_format == "quat_wxyz": + quaternions = quaternions[:, [1, 2, 3, 0]] + norms = np.linalg.norm(quaternions, axis=-1) + if np.any(norms < 1e-8): + raise ValueError(f"Found zero-norm quaternion(s) (min norm={norms.min():.2e}).") + if normalize_matrix: + quaternions = quaternions / norms[:, None] + matrices_flat = R.from_quat(quaternions).as_matrix().astype(np.float32) + elif input_format == "rot6d": + if rotation_np.ndim < 1 or rotation_np.shape[-1] != 6: + raise ValueError(f"{input_format} rotation must have shape (..., 6), got {rotation_np.shape}") + original_shape = rotation_np.shape[:-1] + rot6d_flat = rotation_np.reshape(-1, 6) + col0 = rot6d_flat[:, :3] + col1 = rot6d_flat[:, 3:] + col2 = np.cross(col0, col1, axis=-1) + matrices_flat = np.stack((col0, col1, col2), axis=-1).astype(np.float32) + if normalize_matrix: + matrices_flat = _normalize_rotation_matrices(matrices_flat).reshape(-1, 3, 3) + elif input_format == "rot9d": + if rotation_np.ndim < 1 or rotation_np.shape[-1] != 9: + raise ValueError(f"rot9d rotation must have shape (..., 9), got {rotation_np.shape}") + original_shape = rotation_np.shape[:-1] + matrices_flat = rotation_np.reshape(-1, 3, 3) + if normalize_matrix: + matrices_flat = _normalize_rotation_matrices(matrices_flat).reshape(-1, 3, 3) + elif input_format == "axisangle": + if rotation_np.ndim < 1 or rotation_np.shape[-1] != 3: + raise ValueError(f"axisangle rotation must have shape (..., 3), got {rotation_np.shape}") + original_shape = rotation_np.shape[:-1] + matrices_flat = R.from_rotvec(rotation_np.reshape(-1, 3)).as_matrix().astype(np.float32) + else: + raise ValueError(f"Unsupported input_format: {input_format!r}") + + if output_format == "matrix": + converted = matrices_flat.reshape(*original_shape, 3, 3).astype(np.float32) + elif output_format == "rot9d": + converted = matrices_flat.reshape(-1, 9) + elif output_format == "rot6d": + converted = matrices_flat[:, :, :2].transpose(0, 2, 1).reshape(-1, 6) + elif output_format == "quat_xyzw": + converted = R.from_matrix(matrices_flat).as_quat().astype(np.float32) + elif output_format == "quat_wxyz": + converted = R.from_matrix(matrices_flat).as_quat().astype(np.float32) + converted = converted[:, [3, 0, 1, 2]] + elif output_format == "euler_xyz": + converted = R.from_matrix(matrices_flat).as_euler("xyz", degrees=False).astype(np.float32) + elif output_format == "axisangle": + converted = R.from_matrix(matrices_flat).as_rotvec().astype(np.float32) + else: + raise ValueError(f"Unsupported output_format: {output_format!r}") + + if output_format != "matrix": + converted = converted.reshape(*original_shape, converted.shape[-1]) + + if input_is_tensor: + return torch.from_numpy(np.ascontiguousarray(converted)).to(dtype=input_dtype, device=input_device) + return converted + + +# ----------------------------------------------------------------------------- +# Absolute pose construction +# ----------------------------------------------------------------------------- + + +def build_abs_pose_from_components( + xyz: torch.Tensor | np.ndarray, + rotation: torch.Tensor | np.ndarray, + rotation_input_format: Literal["euler_xyz", "quat_xyzw", "quat_wxyz", "axisangle"], + translation_scale: float | None = None, +) -> np.ndarray: + """Build absolute homogeneous poses from per-frame translation and rotation. + + This is the canonical helper for turning dataset-provided pose components + into a sequence of rigid transforms. Each output pose is a homogeneous + transform whose top-left ``3 x 3`` block stores rotation and whose last + column stores translation. + + Args: + xyz: Per-frame translations with shape ``(T, 3)``. + rotation: Per-frame rotations with shape ``(T, 3)`` for ``euler_xyz`` + and ``axisangle``, or ``(T, 4)`` for quaternion conventions. + rotation_input_format: Convention used by ``rotation``. Supported values + are ``euler_xyz``, ``quat_xyzw``, ``quat_wxyz``, and ``axisangle``. + translation_scale: Optional factor used to divide translations before + inserting them into the output poses. This is useful when upstream + data stores translations in a scaled unit. + + Returns: + Absolute poses with shape ``(T, 4, 4)`` and dtype ``float32``. + + Raises: + ValueError: If the translation and rotation arrays have incompatible + lengths or unsupported shapes, or if ``translation_scale`` is zero. + """ + xyz_np = _to_numpy_float32(xyz) + rotation_np = _to_numpy_float32(rotation) + + if xyz_np.ndim != 2 or xyz_np.shape[1] != 3: + raise ValueError(f"xyz must have shape (T, 3), got {xyz_np.shape}") + if rotation_np.ndim != 2: + raise ValueError(f"rotation must be 2D, got {rotation_np.shape}") + if rotation_np.shape[0] != xyz_np.shape[0]: + raise ValueError( + f"xyz and rotation must have the same length, got {xyz_np.shape[0]} and {rotation_np.shape[0]}" + ) + + rot_mats = np.asarray( + convert_rotation(rotation_np, input_format=rotation_input_format, output_format="matrix"), + dtype=np.float32, + ) + + if translation_scale is not None: + if translation_scale == 0: + raise ValueError("translation_scale must be non-zero") + xyz_np = xyz_np / float(translation_scale) + + poses_abs = np.eye(4, dtype=np.float32)[None].repeat(xyz_np.shape[0], axis=0) + poses_abs[:, :3, :3] = rot_mats.astype(np.float32) + poses_abs[:, :3, 3] = xyz_np + return poses_abs + + +# ----------------------------------------------------------------------------- +# Relative pose conversions +# ----------------------------------------------------------------------------- + + +def _delta_transform_to_pose_vector( + delta_T: np.ndarray, + rotation_output_format: RotationConvention, + translation_scale: float = 1.0, + rotation_scale: float = 1.0, +) -> np.ndarray: + """Encode a relative transform as an action vector. + + The shared action-vector layout is always ``[translation(3), rotation(...)]``. + The translation block is multiplied by ``translation_scale`` before concatenation, + and the rotation block is multiplied by ``rotation_scale``. + + Args: + delta_T: Relative transform of shape ``(4, 4)``. + rotation_output_format: Concrete convention used for the output rotation + block. + translation_scale: Scalar multiplier applied to the translation block. + rotation_scale: Scalar multiplier applied to the rotation block. Used to + match the loss scale of the rotation block to the translation block. + The decoder must divide by the same factor before reconstructing the + rotation matrix. + + Returns: + A ``float32`` action vector whose first three values are translation and + whose remaining values are the rotation in ``rotation_output_format``. + """ + delta_np = np.asarray(delta_T, dtype=np.float32) + if delta_np.shape != (4, 4): + raise ValueError(f"delta_T must have shape (4, 4), got {delta_np.shape}") + + translation = delta_np[:3, 3] * translation_scale + rotation = np.asarray( + convert_rotation(delta_np[:3, :3], input_format="matrix", output_format=rotation_output_format), + dtype=np.float32, + ) + rotation = rotation * rotation_scale + return np.concatenate([translation, rotation]).astype(np.float32) + + +def _pose_vector_to_delta_transform( + pose_vector: np.ndarray, + rotation_input_format: RotationConvention, + translation_scale: float, + normalize_rotation: bool, + rotation_scale: float = 1.0, +) -> np.ndarray: + """Decode an action vector back into a relative homogeneous transform. + + This is the inverse of `_delta_transform_to_pose_vector()` when the same + rotation convention and scale are used. + + Args: + pose_vector: Relative-pose action vector with layout + ``[translation(3), rotation(...)]``. + rotation_input_format: Concrete convention used by the rotation block. + translation_scale: Scalar used to undo the translation scaling applied during + encoding. + normalize_rotation: Whether to project the decoded rotation to a valid + matrix before assembling the transform. + rotation_scale: Scalar used to undo the rotation scaling applied during + encoding. Must match the value used by + `_delta_transform_to_pose_vector()`. + + Returns: + A relative homogeneous transform with shape ``(4, 4)`` and dtype + ``float32``. + """ + pose_vector_np = np.asarray(pose_vector, dtype=np.float32) + rotation_block = pose_vector_np[3:] / rotation_scale + + rotation_matrix = np.asarray( + convert_rotation( + rotation_block, + input_format=rotation_input_format, + output_format="matrix", + normalize_matrix=normalize_rotation, + ), + dtype=np.float32, + ) + + delta_T = np.eye(4, dtype=np.float32) + delta_T[:3, 3] = pose_vector_np[:3] / translation_scale + delta_T[:3, :3] = rotation_matrix + return delta_T + + +def _get_relative_delta_transform( + poses_abs: np.ndarray, + inv_poses_abs: np.ndarray, + frame_idx: int, + pose_convention: PoseConvention, +) -> np.ndarray: + """Compute one relative transform from an absolute-pose trajectory. + + Args: + poses_abs: Absolute poses of shape ``(T, 4, 4)``. + inv_poses_abs: Precomputed inverses of ``poses_abs`` with the same shape. + frame_idx: Index of the step to encode, in ``[0, T - 2]``. + pose_convention: Pose convention controlling which two poses + define the delta and whether it is framewise or anchored. + + Returns: + The relative transform ``delta_T`` with shape ``(4, 4)`` for the + requested step and convention. + """ + if pose_convention == "backward_framewise": + return inv_poses_abs[frame_idx] @ poses_abs[frame_idx + 1] + if pose_convention == "backward_anchored": + return inv_poses_abs[0] @ poses_abs[frame_idx + 1] + raise ValueError( + f"Unsupported pose_convention={pose_convention!r}. Expected one of: backward_framewise, backward_anchored." + ) + + +def _apply_relative_delta_transform( + current_pose: np.ndarray, + initial_pose: np.ndarray, + delta_T: np.ndarray, + pose_convention: PoseConvention, +) -> np.ndarray: + """Recover the next absolute pose from a decoded relative transform. + + Args: + current_pose: The current reconstructed pose for framewise modes. + initial_pose: The anchor pose used by anchored modes. + delta_T: Relative transform for the current step. + pose_convention: Pose convention controlling how ``delta_T`` + should be composed back into an absolute pose. + + Returns: + The next absolute pose with shape ``(4, 4)``. + """ + if pose_convention == "backward_framewise": + return current_pose @ delta_T + if pose_convention == "backward_anchored": + return initial_pose @ delta_T + raise ValueError( + f"Unsupported pose_convention={pose_convention!r}. Expected one of: backward_framewise, backward_anchored." + ) + + +def pose_abs_to_rel( + poses_abs: np.ndarray, + rotation_format: RotationConvention = "rot9d", + pose_convention: PoseConvention = "backward_framewise", + translation_scale: float = 1.0, + rotation_scale: float = 1.0, +) -> np.ndarray: + """Convert an absolute-pose trajectory into relative-pose action vectors. + + Args: + poses_abs: Absolute poses with shape ``(T, 4, 4)``. These are typically + object-in-world or camera-to-world transforms. + rotation_format: Rotation convention used for the output rotation block. + Supported values are ``rot9d``, ``rot6d``, ``quat_xyzw``, and + ``euler_xyz``. + pose_convention: Pose convention: + - ``backward_framewise``: ``delta_T = T_i^{-1} @ T_{i+1}`` + - ``backward_anchored``: ``delta_T = T_0^{-1} @ T_{i+1}`` + translation_scale: Scalar multiplier applied to the translation block of each + encoded action vector. + rotation_scale: Scalar multiplier applied to the rotation block of each + encoded action vector. Use this to match the loss scale of rotation + and translation. `pose_rel_to_abs()` must be called with the same + value to invert the scaling. + + Returns: + An array of shape ``(T - 1, D)`` where ``D = 3 + rotation_dim``. + + Raises: + AssertionError: If fewer than two absolute poses are provided. + """ + num_frames = len(poses_abs) + assert num_frames > 1, "At least 2 frames are required to compute relative poses" + + # Compute inverse poses + inv_poses_abs = np.linalg.inv(poses_abs) + + poses_rel = [] + # We produce num_frames - 1 relative poses + for i in range(num_frames - 1): + delta_T = _get_relative_delta_transform(poses_abs, inv_poses_abs, i, pose_convention) + poses_rel.append( + _delta_transform_to_pose_vector( + delta_T, + rotation_output_format=rotation_format, + translation_scale=translation_scale, + rotation_scale=rotation_scale, + ) + ) + + return np.stack(poses_rel).astype(np.float32) # [T-1,D] + + +def pose_rel_to_abs( + poses_rel: np.ndarray, + rotation_format: RotationConvention = "rot9d", + pose_convention: PoseConvention = "backward_framewise", + initial_pose: np.ndarray | None = None, + normalize_rotation: bool = True, + translation_scale: float = 1.0, + rotation_scale: float = 1.0, +) -> np.ndarray: + """Reconstruct an absolute-pose trajectory from relative-pose action vectors. + + Args: + poses_rel: Relative-pose action vectors with shape ``(T - 1, D)`` and + layout ``[translation(3), rotation(...)]``. + rotation_format: Convention used by the rotation block of ``poses_rel``. + pose_convention: Pose convention used when the vectors were + encoded. This must match the convention passed to `pose_abs_to_rel()`. + initial_pose: Absolute pose for the first frame. If ``None``, the + identity transform is used. + normalize_rotation: Whether to project decoded rotations onto ``SO(3)`` + before composing them back into the trajectory. + translation_scale: Scalar used to undo the translation scaling applied during + `pose_abs_to_rel()`. + rotation_scale: Scalar used to undo the rotation scaling applied during + `pose_abs_to_rel()`. Must match the value passed there. + + Returns: + Absolute poses with shape ``(T, 4, 4)`` where ``T = len(poses_rel) + 1``. + """ + if initial_pose is None: + initial_pose = np.eye(4) + + poses_abs = [initial_pose] + current_pose = initial_pose + + num_poses_rel = poses_rel.shape[0] + + for i in range(num_poses_rel): + delta_T = _pose_vector_to_delta_transform( + poses_rel[i], + rotation_input_format=rotation_format, + translation_scale=translation_scale, + normalize_rotation=normalize_rotation, + rotation_scale=rotation_scale, + ) + next_pose = _apply_relative_delta_transform(current_pose, initial_pose, delta_T, pose_convention) + + poses_abs.append(next_pose) + current_pose = next_pose + + return np.stack(poses_abs) # [T,4,4] diff --git a/cosmos-framework/cosmos_framework/data/vfm/action/robomind_franka_dataset.py b/cosmos-framework/cosmos_framework/data/vfm/action/robomind_franka_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..7c6aa82f338ecce3664dc6024a076e7fc644a539 --- /dev/null +++ b/cosmos-framework/cosmos_framework/data/vfm/action/robomind_franka_dataset.py @@ -0,0 +1,171 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: OpenMDW-1.1 + +"""Minimal local RoboMIND Franka LeRobot datasets for the action viewer.""" + +from __future__ import annotations + +from typing import Any, Literal, cast + +import numpy as np +import torch +import torch.nn.functional as F +from torch.utils.data import Dataset + +from cosmos_framework.data.vfm.action._lerobot_local import ( + build_result, + choose_mode, + load_local_lerobot, + load_video_key, + pick_caption, + rows_at_fps, + sample_count, + task_text, +) +from cosmos_framework.data.vfm.action.pose_utils import PoseConvention, build_abs_pose_from_components, pose_abs_to_rel + +_ROBOMIND_FRANKA_TO_OPENCV: np.ndarray = np.array( + [ + [0.0, -1.0, 0.0, 0.0], + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, +) + +_STATE_FEATURE = "observation.states.end_effector" +_ACTION_FEATURE = "actions.joint_position" + + +class RoboMINDFrankaDataset(Dataset): + """Standalone RoboMIND wrapper for packaged single-arm and dual-arm demos.""" + + def __init__( + self, + root: str = "/app/assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1", + fps: float = 10.0, + chunk_length: int = 16, + split_seed: int = 42, + split_val_ratio: float = 0.05, + split: str = "train", + mode: str = "policy", + embodiment_type: Literal["robomind-franka", "robomind-franka-dual"] = "robomind-franka", + pose_convention: PoseConvention = "backward_framewise", + viewpoint: str = "concat_view", + enable_fast_init: bool = False, + sample_stride: int = 1, + ) -> None: + super().__init__() + del split_seed, split_val_ratio, split, enable_fast_init + if embodiment_type not in ("robomind-franka", "robomind-franka-dual"): + raise ValueError(f"Unsupported embodiment_type={embodiment_type!r}") + self._fps = float(fps) + self._chunk_length = int(chunk_length) + self._mode = mode + self._embodiment_type = embodiment_type + self._pose_convention = pose_convention + self._viewpoint = viewpoint + self._sample_stride = int(sample_stride) + self._root, self._info, self._episodes, self._tasks, self._rows = load_local_lerobot(root) + self._to_opencv = _ROBOMIND_FRANKA_TO_OPENCV[:3, :3] + + @property + def fps(self) -> float: + return self._fps + + @property + def chunk_length(self) -> int: + return self._chunk_length + + @property + def mode(self) -> str: + return self._mode + + @mode.setter + def mode(self, value: str) -> None: + self._mode = value + + @property + def action_dim(self) -> int: + return 10 if self._embodiment_type == "robomind-franka" else 20 + + def __len__(self) -> int: + return sample_count(self._rows, self._chunk_length, self._sample_stride) + + def _camera_keys(self) -> tuple[str, str, str]: + primary = "observation.images.camera_top" if self._embodiment_type == "robomind-franka" else "observation.images.camera_front" + return primary, "observation.images.camera_left", "observation.images.camera_right" + + def _load_concat_video(self, episode: dict[str, Any], rows: list[dict[str, Any]]) -> torch.Tensor: + primary_key, left_key, right_key = self._camera_keys() + primary = load_video_key(self._root, self._info, episode, rows, primary_key, tolerance_s=1e-4) + if self._viewpoint != "concat_view": + return primary + left = load_video_key(self._root, self._info, episode, rows, left_key, tolerance_s=1e-4) + right = load_video_key(self._root, self._info, episode, rows, right_key, tolerance_s=1e-4) + _, _, height_ref, width_ref = primary.shape + half_height, half_width = height_ref // 2, width_ref // 2 + left = F.interpolate(left, size=(half_height, half_width), mode="bilinear", align_corners=False) + right = F.interpolate(right, size=(half_height, half_width), mode="bilinear", align_corners=False) + return torch.cat([primary, torch.cat([left, right], dim=-1)], dim=-2) + + def _build_relative_poses(self, positions: np.ndarray, euler_xyz: np.ndarray) -> tuple[np.ndarray, torch.Tensor]: + poses_abs = build_abs_pose_from_components(positions, euler_xyz, "euler_xyz") + poses_abs[:, :3, :3] = poses_abs[:, :3, :3] @ self._to_opencv.astype(poses_abs.dtype) + initial_pose = torch.from_numpy(poses_abs[0].copy()).float() + poses_rel = pose_abs_to_rel( + poses_abs, + rotation_format="rot6d", + pose_convention=cast(PoseConvention, self._pose_convention), + ) + return poses_rel, initial_pose + + def _build_action(self, rows: list[dict[str, Any]]) -> tuple[torch.Tensor, torch.Tensor] | tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + state = np.asarray([row[_STATE_FEATURE] for row in rows], dtype=np.float32) + gripper = np.asarray([row[_ACTION_FEATURE] for row in rows[:-1]], dtype=np.float32) + if self._embodiment_type == "robomind-franka": + poses_rel, initial_pose = self._build_relative_poses(state[:, 0:3], state[:, 3:6]) + action = np.concatenate([poses_rel[-self._chunk_length :], 1.0 - gripper[-self._chunk_length :, [7]]], axis=-1) + return torch.from_numpy(action).float(), initial_pose + + poses_rel_left, initial_pose_left = self._build_relative_poses(state[:, 0:3], state[:, 3:6]) + poses_rel_right, initial_pose_right = self._build_relative_poses(state[:, 6:9], state[:, 9:12]) + action = np.concatenate( + [ + poses_rel_left[-self._chunk_length :], + 1.0 - gripper[-self._chunk_length :, [7]], + poses_rel_right[-self._chunk_length :], + 1.0 - gripper[-self._chunk_length :, [15]], + ], + axis=-1, + ) + return torch.from_numpy(action).float(), initial_pose_left, initial_pose_right + + def __getitem__(self, idx: int) -> dict[str, Any]: + rows = rows_at_fps(self._rows, idx, self._chunk_length, self._fps, self._sample_stride) + episode = self._episodes[int(rows[0]["episode_index"])] + video = self._load_concat_video(episode, rows) + built = self._build_action(rows) + action = built[0] + extras: dict[str, Any] = {} + if len(built) == 3: + extras["initial_pose"] = built[1] + extras["initial_pose_right"] = built[2] + else: + extras["initial_pose"] = built[1] + if self._viewpoint == "concat_view": + extras["additional_view_description"] = ( + "The top row shows a third-person perspective view of the robot. " + "The bottom row contains the left and right third-person camera views." + ) + caption = pick_caption(task_text(self._tasks, rows, "RoboMIND Franka demonstration")) + return build_result( + mode=choose_mode(self._mode), + video=video, + action=action, + ai_caption=caption, + fps=self._fps, + viewpoint=self._viewpoint, + **extras, + ) diff --git a/cosmos-framework/cosmos_framework/data/vfm/action/umi_lerobot_dataset.py b/cosmos-framework/cosmos_framework/data/vfm/action/umi_lerobot_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..3130df2a129bfe76b8c8ccded09c53d6ec67ec2c --- /dev/null +++ b/cosmos-framework/cosmos_framework/data/vfm/action/umi_lerobot_dataset.py @@ -0,0 +1,120 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: OpenMDW-1.1 + +"""Minimal local UMI/FastUMI LeRobot dataset for the action viewer.""" + +from __future__ import annotations + +from typing import Any + +import numpy as np +import torch +from torch.utils.data import Dataset + +from cosmos_framework.data.vfm.action._lerobot_local import ( + build_result, + choose_mode, + load_local_lerobot, + load_video_key, + pick_caption, + rows_for_index, + sample_count, + task_text, +) +from cosmos_framework.data.vfm.action.pose_utils import PoseConvention, build_abs_pose_from_components, pose_abs_to_rel + +_UMI_TO_OPENCV = np.eye(3, dtype=np.float32) +_IMAGE_FEATURE = "observation.image.right_main_camera_rgb" +_POSE_FEATURE = "observation.state.right_main_camera_trajectory_xyz_wxyz" +_GRIPPER_FEATURE = "observation.state.right_gripper_width_m" + + +class UMIFastLeRobotDataset(Dataset): + """Standalone UMI/FastUMI wrapper: 10D = [pos, rot6d, gripper].""" + + def __init__( + self, + root: str = "/app/assets/examples/fastumi/fastumi_single_arm/pour_coke", + fps: float = 20.0, + chunk_length: int = 16, + split_seed: int = 42, + split_val_ratio: float = 0.02, + split: str = "train", + mode: str = "policy", + pose_convention: PoseConvention = "backward_framewise", + viewpoint: str = "ego_view", + enable_fast_init: bool = False, + sample_stride: int = 1, + ) -> None: + super().__init__() + del split_seed, split_val_ratio, split, enable_fast_init + self._fps = float(fps) + self._chunk_length = int(chunk_length) + self._mode = mode + self._pose_convention = pose_convention + self._viewpoint = viewpoint + self._sample_stride = int(sample_stride) + self._root, self._info, self._episodes, self._tasks, self._rows = load_local_lerobot(root) + + # The packaged UMI trajectory is the right main camera trajectory. For + # viewer overlays we want the actual gripper/end-effector pose, so + # compose the camera pose with the fixed camera->EEF calibration stored + # in metadata. + eef_pose_in_main = np.asarray( + self._info.get("right_eef_pose_in_main_xyz_wxyz", [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]), + dtype=np.float32, + ) + self._right_main_to_eef = build_abs_pose_from_components( + eef_pose_in_main[None, :3], + eef_pose_in_main[None, 3:7], + rotation_input_format="quat_wxyz", + )[0] + gripper_width_max = np.asarray(self._info.get("right_gripper_width_m_max", [0.08]), dtype=np.float32).reshape(-1) + self._gripper_width_m_max = float(gripper_width_max[0]) if gripper_width_max.size else 0.08 + + @property + def fps(self) -> float: + return self._fps + + @property + def chunk_length(self) -> int: + return self._chunk_length + + @property + def mode(self) -> str: + return self._mode + + @mode.setter + def mode(self, value: str) -> None: + self._mode = value + + @property + def action_dim(self) -> int: + return 10 + + def __len__(self) -> int: + return sample_count(self._rows, self._chunk_length, self._sample_stride) + + def __getitem__(self, idx: int) -> dict[str, Any]: + rows = rows_for_index(self._rows, idx, self._chunk_length, self._sample_stride) + episode = self._episodes[int(rows[0]["episode_index"])] + video = load_video_key(self._root, self._info, episode, rows, _IMAGE_FEATURE, tolerance_s=1e-4) + pose = np.asarray([row[_POSE_FEATURE] for row in rows], dtype=np.float32) + gripper_width_m = np.asarray([row[_GRIPPER_FEATURE] for row in rows[:-1]], dtype=np.float32).reshape(-1, 1) + poses_abs = build_abs_pose_from_components(pose[:, :3], pose[:, 3:7], rotation_input_format="quat_wxyz") + poses_abs = poses_abs @ self._right_main_to_eef.astype(poses_abs.dtype) + poses_abs[:, :3, :3] = poses_abs[:, :3, :3] @ _UMI_TO_OPENCV.astype(poses_abs.dtype) + initial_pose = torch.from_numpy(poses_abs[0].copy()).float() + rel = pose_abs_to_rel(poses_abs, rotation_format="rot6d", pose_convention=self._pose_convention) + gripper_fraction = np.clip(gripper_width_m / max(self._gripper_width_m_max, 1e-6), 0.0, 1.0) + action = torch.from_numpy(np.concatenate((rel, gripper_fraction), axis=-1)).float() + caption = pick_caption(task_text(self._tasks, rows, "UMI/FastUMI demonstration")) + return build_result( + mode=choose_mode(self._mode), + video=video, + action=action, + ai_caption=caption, + fps=self._fps, + viewpoint=self._viewpoint, + initial_pose=initial_pose, + ) diff --git a/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/README.md b/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3fd87de8bfcc521c4fb2f4e747263593c66f9bbf --- /dev/null +++ b/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/README.md @@ -0,0 +1,45 @@ +# Action Dataset URDF Viewer + +Interactive 3D viewer for release-supported robot action datasets. It renders +RGB frames, end-effector trajectories, and robot meshes/IK with +[`viser`](https://viser.studio/), MuJoCo, and Pinocchio. + +The standalone viewer registry is intentionally scoped to the packaged demo datasets: + +- AV +- Fractal +- Bridge +- DROID +- UMI / FastUMI +- RoboMIND Franka +- RoboMIND Franka dual + +The dataset LazyConfig entries live in: + +```text +cosmos_framework/data/vfm/action/urdf_visualizer/action_datasets.py +``` + +## Dataset roots + +The Docker Space uses packaged examples under `/app/assets/examples`. For local +development, override individual roots only when needed, e.g. `BRIDGE_ROOT`, +`FRACTAL_ROOT`, `DROID_ROOT`, `UMI_ROOT`, `ROBOMIND_FRANKA_ROOT`, +`ROBOMIND_FRANKA_DUAL_ROOT`, or `AV_ROOT`. + +## Local launch + +Use the repository Dockerfile for local development/testing. + +From the repository root: + +```bash +docker build -t cosmos3-action-viewer . +docker run --rm -p 8020:7860 cosmos3-action-viewer +# or with publicly shared url +docker run --rm -p 8021:7860 -e COSMOS_VIEWER_SHARE=1 cosmos3-action-viewer +``` + +Then open or the publicly shared URL from the logs. + +Rebuild the image after code changes. diff --git a/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/__init__.py b/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..503ec1b18d584ba1c349360dedbe6951e3216df6 --- /dev/null +++ b/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: OpenMDW-1.1 + diff --git a/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/action_datasets.py b/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/action_datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..a696700d614e7853be7436541fe5db08e223ede9 --- /dev/null +++ b/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/action_datasets.py @@ -0,0 +1,150 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: OpenMDW-1.1 + +"""Minimal release-supported action dataset configs for the URDF viewer.""" + +from __future__ import annotations + +import os +from dataclasses import dataclass +from typing import Any, Callable + +from cosmos_framework.data.vfm.action.av_dataset import AVDataset +from cosmos_framework.data.vfm.action.bridge_orig_lerobot_dataset import BridgeOrigLeRobotDataset +from cosmos_framework.data.vfm.action.droid_lerobot_dataset import DROIDLeRobotDataset +from cosmos_framework.data.vfm.action.fractal import FractalLeRobotDataset +from cosmos_framework.data.vfm.action.robomind_franka_dataset import RoboMINDFrankaDataset +from cosmos_framework.data.vfm.action.umi_lerobot_dataset import UMIFastLeRobotDataset + +@dataclass +class LazyCall: + """Tiny LazyCall replacement sufficient for the standalone viewer.""" + + target: Callable[..., Any] + + def __call__(self, **kwargs: Any) -> dict[str, Any]: + return {"_target_": self.target, **kwargs} + + +L = LazyCall + + +def dataset_entry(name: str, dataset: Any, ratio: float = 1.0, resolution: str | None = None) -> dict[str, Any]: + return {"name": name, "dataset": dataset, "ratio": ratio, "resolution": resolution} + + +def _env_path(*names: str, default: str) -> str: + for name in names: + value = os.environ.get(name) + if value: + return value + return default + + +BRIDGE_ROOT = _env_path("BRIDGE_LEROBOT_ROOT", "DATASET_PATH", default="/app/assets/examples/bridge_lerobot_v3") + +DATASET_BRIDGE_480 = L(dataset_entry)( + name="bridge_20260501", + dataset=L(BridgeOrigLeRobotDataset)( + chunk_length=16, + enable_fast_init=True, + fps=5.0, + mode="joint", + pose_convention="backward_framewise", + root=BRIDGE_ROOT, + split="full", + split_seed=42, + split_val_ratio=0.02, + viewpoint="ego_view", + ), + ratio=1.0, + resolution="480", +) + + +DATASET_FRACTAL_256 = L(dataset_entry)( + name="fractal_20260501", + dataset=L(FractalLeRobotDataset)( + root=_env_path("FRACTAL_ROOT", default="/app/assets/examples/fractal20220817_data"), + split="train", + mode="joint", + enable_fast_init=False, + ), + ratio=1, + resolution="256", +) + +DATASET_DROID_480 = L(dataset_entry)( + name="droid_20260501", + dataset=L(DROIDLeRobotDataset)( + root=_env_path("DROID_ROOT", default="/app/assets/examples/droid_plus_lerobot_640x360_20260412/success"), + split="train", + use_success_only=True, + mode="joint", + enable_fast_init=False, + ), + ratio=1, + resolution="480", +) + +DATASET_ROBOMIND_FRANKA_480 = L(dataset_entry)( + name="robomind_franka_20260501", + dataset=L(RoboMINDFrankaDataset)( + root=_env_path("ROBOMIND_FRANKA_ROOT", "ROBOMIND_ROOT", default="/app/assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1"), + split="train", + mode="joint", + embodiment_type="robomind-franka", + enable_fast_init=False, + ), + ratio=1, + resolution="480", +) + +DATASET_ROBOMIND_FRANKA_DUAL_480 = L(dataset_entry)( + name="robomind_franka_dual_20260501", + dataset=L(RoboMINDFrankaDataset)( + root=_env_path("ROBOMIND_FRANKA_DUAL_ROOT", "ROBOMIND_ROOT", default="/app/assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water"), + split="train", + mode="joint", + embodiment_type="robomind-franka-dual", + enable_fast_init=False, + ), + ratio=1, + resolution="480", +) + + +DATASET_AV_480 = L(dataset_entry)( + name="av_480_20260501", + dataset=L(AVDataset)( + root=_env_path("AV_ROOT", default="/app/assets/examples/av_v2_03292026_wdinfo"), + split="train", + fps=10, + mode="joint", + history_len=0.1, + future_len=6.0, + rotation_format="rot6d", + pose_convention="backward_framewise", + translation_scale=1.35, + max_action_translation_norm=10, + resolution="480", + shuffle=False, + include_route_in_prompt=True, + use_semantic_route_prompt=True, + align_opencv_pose=False, + ), + ratio=1, + resolution="480", +) + +DATASET_UMI_256 = L(dataset_entry)( + name="umi_20260501", + dataset=L(UMIFastLeRobotDataset)( + root=_env_path("UMI_ROOT", default="/app/assets/examples/fastumi/fastumi_single_arm/pour_coke"), + split="train", + mode="joint", + enable_fast_init=False, + ), + ratio=1, + resolution="256", +) diff --git a/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/droid_franka_robotiq_2f85.xml b/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/droid_franka_robotiq_2f85.xml new file mode 100644 index 0000000000000000000000000000000000000000..795f68b9f7a1b3500688b558a1904f6233596094 --- /dev/null +++ b/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/droid_franka_robotiq_2f85.xml @@ -0,0 +1,377 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/ik_solver.py b/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/ik_solver.py new file mode 100644 index 0000000000000000000000000000000000000000..b4d7b48cc59063d811433484bd3150e5380e340a --- /dev/null +++ b/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/ik_solver.py @@ -0,0 +1,638 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: OpenMDW-1.1 + +"""Robot-agnostic IK solver using pinocchio + MuJoCo. + +Supports any robot loaded from MJCF (Google Robot, Franka Panda, WidowX, etc). +Auto-detects EE frame, arm vs finger joints, and uses multi-start random seeding. + +The solver: +1. Auto-discovers the EE frame from a list of candidate names +2. Determines which joints are "arm" joints (actuated for IK) vs "finger" joints +3. Uses multi-start random sampling to avoid local minima +4. Optionally sets finger joint angles from gripper opening fractions +""" + +from functools import lru_cache +from typing import Any + +import numpy as np + +from cosmos_framework.utils import log +from cosmos_framework.data.vfm.action.urdf_visualizer.robot_scene_model import ( + get_ee_frame_candidates, + get_mujoco_to_pinocchio_world_transform, + get_robot_config, + get_urdf_path, + get_visual_geom_ids, + resolve_robot_name_from_mjcf, +) + +# ── IK Solver ──────────────────────────────────────────────────────────────── + + +def _find_ee_frame(model, robot_name: str | None = None) -> int | None: + """Find the end-effector frame ID by trying candidate names. + + If robot_name is given and its config specifies ``ee_frame``, that name + is tried first before falling through to the generic candidates. + """ + cfg = get_robot_config(robot_name) if robot_name else {} + override = cfg.get("ee_frame") + if override: + fid = model.getFrameId(override) + if fid < model.nframes: + return fid + log.warning(f"Configured ee_frame '{override}' not found in Pinocchio model") + + for name in get_ee_frame_candidates(): + fid = model.getFrameId(name) + if fid < model.nframes: + return fid + log.warning(f"Could not find EE frame by name for robot '{robot_name}', skipping IK") + return None + + +def solve_trajectory_ik( + mjcf_path: str, + world_ee_positions: np.ndarray, + gripper_openings: np.ndarray | None = None, + world_ee_orientations: np.ndarray | None = None, + robot_name: str | None = None, + max_random_samples: int = 50_000, + seed: int = 42, +) -> np.ndarray | None: + """Solve IK for a sequence of world-space EE poses (robot-agnostic). + + Args: + mjcf_path: Path to the MJCF XML file. + world_ee_positions: (T, 3) target EE positions. + gripper_openings: (T,) gripper opening fractions [0=closed, 1=open]. + world_ee_orientations: (T, 3, 3) target EE rotation matrices. + robot_name: Robot name for config lookup (optional, inferred from path). + max_random_samples: Number of random configs to try for initial seed. + seed: Random seed. + + Returns: + (T, nq) joint configurations, or None if IK fails. + """ + import pinocchio as pin + + model, cfg = _build_pinocchio_model(mjcf_path, robot_name) + log.info(f"IK: pinocchio model nq={model.nq}") + data = model.createData() + ee_id = _find_ee_frame(model, robot_name) + if ee_id is None: + return None + ee_name = model.frames[ee_id].name + log.info(f"IK: using EE frame '{ee_name}' (id={ee_id}), nq={model.nq}") + + T = len(world_ee_positions) + use_6dof = world_ee_orientations is not None and len(world_ee_orientations) == T + + # Apply TCP offset: dataset EE poses may be at the TCP (e.g. ee_gripper_link) + # while the Pinocchio frame is at the kinematic link origin (e.g. gripper_link). + # Convert target TCP poses → IK link-frame targets: + # p_link = p_tcp - R_tcp @ tcp_offset + tcp_offset = cfg.get("tcp_offset") + if tcp_offset is not None: + tcp_offset = np.asarray(tcp_offset, dtype=np.float32) + log.info(f"IK: applying TCP offset {tcp_offset} to target positions") + world_ee_positions = world_ee_positions.copy() + for t in range(T): + if use_6dof: + world_ee_positions[t] -= world_ee_orientations[t] @ tcp_offset + else: + world_ee_positions[t] -= tcp_offset + + lower = model.lowerPositionLimit.copy() + upper = model.upperPositionLimit.copy() + + # Determine arm joints vs finger joints + # After model reduction, arm joints are first, fingers follow + n_arm = cfg.get("n_arm_joints", model.nq - 2) # default: all but last 2 are arm + n_finger = model.nq - n_arm + + log.info(f"IK: {n_arm} arm joints + {n_finger} finger joints") + + # ── 6-DoF CLIK (position + orientation) ── + def _ik_6dof(target_pos, target_rot, q_init, max_iter=800, eps_pos=5e-5, eps_rot=1e-3, dt=0.1, damp=1e-4): + q = q_init.copy() + best_q = q.copy() + best_total = float("inf") + stall_count = 0 + rot_weight = 1.0 + + for it in range(max_iter): + pin.forwardKinematics(model, data, q) + pin.updateFramePlacements(model, data) + + pos_err = target_pos - data.oMf[ee_id].translation + pos_norm = np.linalg.norm(pos_err) + R_err = target_rot @ data.oMf[ee_id].rotation.T + rot_err = pin.log3(R_err) + rot_norm = np.linalg.norm(rot_err) + + if pos_norm < eps_pos and rot_norm < eps_rot: + return q, pos_norm, rot_norm, it + 1 + + total = pos_norm + 0.05 * rot_norm + if total < best_total: + best_total = total + best_q = q.copy() + stall_count = 0 + else: + stall_count += 1 + + if stall_count > 50 and rot_weight > 0.1: + rot_weight *= 0.8 + stall_count = 0 + if stall_count > 150: + break + + err6 = np.concatenate([pos_err, rot_weight * rot_err]) + J = pin.computeFrameJacobian(model, data, q, ee_id, pin.LOCAL_WORLD_ALIGNED).copy() + J[3:, :] *= rot_weight + # Zero out finger joint columns + J[:, n_arm:] = 0 + JJt = J @ J.T + damp * np.eye(6) + v = J.T @ np.linalg.solve(JJt, err6) + v[n_arm:] = 0 # don't move finger joints + + q = pin.integrate(model, q, v * dt) + q = np.clip(q, lower, upper) + + pin.forwardKinematics(model, data, best_q) + pin.updateFramePlacements(model, data) + pos_norm = np.linalg.norm(target_pos - data.oMf[ee_id].translation) + rot_norm = np.linalg.norm(pin.log3(target_rot @ data.oMf[ee_id].rotation.T)) + return best_q, pos_norm, rot_norm, max_iter + + # ── 3-DoF CLIK (position only) ── + def _ik_3dof(target_pos, q_init, max_iter=500, eps=5e-5, dt=0.15, damp=1e-4): + q = q_init.copy() + for it in range(max_iter): + pin.forwardKinematics(model, data, q) + pin.updateFramePlacements(model, data) + err = target_pos - data.oMf[ee_id].translation + if np.linalg.norm(err) < eps: + return q, np.linalg.norm(err), it + 1 + J = pin.computeFrameJacobian(model, data, q, ee_id, pin.LOCAL_WORLD_ALIGNED)[:3] + J[:, n_arm:] = 0 + v = J.T @ np.linalg.solve(J @ J.T + damp * np.eye(3), err) + v[n_arm:] = 0 + q = pin.integrate(model, q, v * dt) + q = np.clip(q, lower, upper) + return q, np.linalg.norm(err), max_iter + + def _solve_full_trajectory(seed_q): + configs = [] + max_pe = 0.0 + max_re = 0.0 + q = seed_q.copy() + for t in range(T): + if use_6dof: + q, pe, re, _ = _ik_6dof(world_ee_positions[t], world_ee_orientations[t], q) + max_pe = max(max_pe, float(pe)) + max_re = max(max_re, float(re)) + else: + q, pe, _ = _ik_3dof(world_ee_positions[t], q) + max_pe = max(max_pe, float(pe)) + configs.append(q.copy()) + return np.array(configs), max_pe, max_re + + # ── Multi-start seed search ── + # For robots with a base rotation joint (Google Robot torso, WidowX waist), + # search multiple rotation basins. For Franka (no base rotation freedom), + # use a single wider search. + base_joint_range = upper[0] - lower[0] + if base_joint_range > 4.0: + # Wide base rotation — split into basins (Google Robot, WidowX) + n_basins = 4 + basin_size = base_joint_range / n_basins + basins = [] + for i in range(n_basins): + b_lo = lower[0] + i * basin_size + b_hi = lower[0] + (i + 1) * basin_size + basins.append((b_lo, b_hi)) + else: + # No wide base rotation — single basin (Franka) + basins = [(lower[0], upper[0])] + + samples_per_basin = max_random_samples // len(basins) + target0_pos = world_ee_positions[0] + target0_rot = world_ee_orientations[0] if use_6dof else None + + best_overall_configs = None + best_overall_score = float("inf") + best_basin_info = "" + best_max_pe = 0.0 + best_max_re = 0.0 + + for basin_idx, (b_lo, b_hi) in enumerate(basins): + rng = np.random.RandomState(seed + basin_idx) + basin_lower = lower.copy() + basin_upper = upper.copy() + basin_lower[0] = max(lower[0], b_lo) + basin_upper[0] = min(upper[0], b_hi) + + # Find best seed in this basin + basin_best_q = pin.neutral(model) + basin_best_q[0] = (b_lo + b_hi) / 2 + basin_best_score = float("inf") + + for _ in range(samples_per_basin): + q = rng.uniform(basin_lower, basin_upper) + pin.forwardKinematics(model, data, q) + pin.updateFramePlacements(model, data) + pos_err = np.linalg.norm(data.oMf[ee_id].translation - target0_pos) + + if target0_rot is not None: + rot_err = np.linalg.norm(pin.log3(target0_rot.T @ data.oMf[ee_id].rotation)) + score = pos_err + 0.3 * rot_err + else: + score = pos_err + + if score < basin_best_score: + basin_best_score = score + basin_best_q = q.copy() + if pos_err < 0.005 and (target0_rot is None or rot_err < 0.1): + break + + if basin_best_score > 0.5: + continue + + configs, max_pe, max_re = _solve_full_trajectory(basin_best_q) + traj_score = max_pe + 0.05 * max_re + log.info( + f" Basin [{b_lo:+.1f}, {b_hi:+.1f}]: seed_score={basin_best_score:.4f}, " + f"traj max_pos={max_pe * 1000:.1f}mm, max_rot={np.degrees(max_re):.1f}°, " + f"j0={basin_best_q[0]:+.2f}rad" + ) + + if traj_score < best_overall_score: + best_overall_score = traj_score + best_overall_configs = configs + best_basin_info = f"j0_basin=[{b_lo:+.1f},{b_hi:+.1f}], seed_j0={basin_best_q[0]:+.2f}rad" + best_max_pe = max_pe + best_max_re = max_re + + if best_overall_configs is None: + log.warning("IK failed: no basin converged") + return None + + configs = best_overall_configs + if use_6dof: + log.info( + f"IK solved ({T} frames, 6-DoF): max_pos={best_max_pe * 1000:.2f}mm, max_rot={np.degrees(best_max_re):.1f}° [{best_basin_info}]" + ) + else: + log.info(f"IK solved ({T} frames, 3-DoF): max_pos={best_max_pe * 1000:.2f}mm [{best_basin_info}]") + + # ── Set finger joints from gripper openings ── + if n_finger > 0: + finger_min = cfg.get("finger_min", lower[n_arm]) + finger_max = cfg.get("finger_max", upper[n_arm]) + else: + finger_min = 0.0 + finger_max = 0.0 + close_is_max = cfg.get("finger_close_is_max", True) + finger_joint_names = cfg.get("finger_joint_names") + + if gripper_openings is not None and len(gripper_openings) == T: + # Find finger joint indices by name if specified (e.g., Robotiq driver joints) + if finger_joint_names: + # Use Pinocchio joint name lookup + finger_indices = [] + for fjn in finger_joint_names: + # Pinocchio joint names include the joint name from MJCF + jid = model.getJointId(fjn) + if jid < model.njoints: + # Pinocchio joint index → qpos index + qi = model.idx_qs[jid] + finger_indices.append(qi) + else: + log.warning(f"Finger joint '{fjn}' not found in Pinocchio model") + if not finger_indices: + finger_indices = list(range(n_arm, n_arm + n_finger)) + else: + finger_indices = list(range(n_arm, n_arm + n_finger)) + + for t in range(T): + g = float(np.clip(gripper_openings[t], 0.0, 1.0)) + if close_is_max: + # Robotiq/Google Robot: high angle = closed + angle = finger_max - g * (finger_max - finger_min) + else: + # Franka/WidowX: high value = open + angle = finger_min + g * (finger_max - finger_min) + + for ji in finger_indices: + # WidowX right finger is negative range + if lower[ji] < 0 and upper[ji] < 0: + configs[t, ji] = -(finger_min + g * (finger_max - finger_min)) + else: + configs[t, ji] = angle + log.info( + f"Finger joints set from gripper openings ({gripper_openings.min():.2f} to {gripper_openings.max():.2f})" + ) + + return configs + + +def _build_pinocchio_model(mjcf_path: str, robot_name: str | None = None): + """Build a pinocchio model, reducing to arm+finger joints if configured. + + For URDF models (SimplerEnv), builds from URDF and locks non-arm joints. + For MJCF models (Menagerie), builds from MJCF and locks non-arm joints. + Shared by solve_trajectory_ik and compute_fk_ee_poses. + """ + import pinocchio as pin + + cfg = get_robot_config(robot_name) if robot_name else {} + urdf_path = get_urdf_path(robot_name) if robot_name else None + + if urdf_path: + full_model = pin.buildModelFromUrdf(urdf_path) + else: + full_model = pin.buildModelFromMJCF(mjcf_path) + + # Reduce model to arm + finger joints only (lock base, wheels, etc.) + arm_joint_names = cfg.get("arm_joints", []) + finger_jnames = cfg.get("finger_joint_names", []) + keep_names = set(arm_joint_names) | set(finger_jnames) + + if keep_names: + lock_ids = [ji for ji in range(1, full_model.njoints) if full_model.names[ji] not in keep_names] + if lock_ids: + q_ref = pin.neutral(full_model) + model = pin.buildReducedModel(full_model, lock_ids, q_ref) + else: + model = full_model + else: + model = full_model + + return model, cfg + + +def compute_fk_ee_poses( + mjcf_path: str, + joint_configs: np.ndarray, + robot_name: str | None = None, +) -> tuple[np.ndarray, np.ndarray]: + """Run FK and return EE positions and orientations.""" + import pinocchio as pin + + model, _ = _build_pinocchio_model(mjcf_path, robot_name) + data = model.createData() + ee_id = _find_ee_frame(model, robot_name) + if ee_id is None: + log.warning(f"Skipping FK — no EE frame found for robot '{robot_name}'") + T = len(joint_configs) + return np.zeros((T, 3)), np.zeros((T, 3, 3)) + + T = len(joint_configs) + fk_positions = np.zeros((T, 3)) + fk_orientations = np.zeros((T, 3, 3)) + + for t in range(T): + pin.forwardKinematics(model, data, joint_configs[t]) + pin.updateFramePlacements(model, data) + fk_positions[t] = data.oMf[ee_id].translation.copy() + fk_orientations[t] = data.oMf[ee_id].rotation.copy() + + return fk_positions, fk_orientations + + +def verify_ik_with_fk( + mjcf_path: str, + joint_configs: np.ndarray, + target_positions: np.ndarray, + target_orientations: np.ndarray | None = None, +) -> dict: + """Verify IK solution by running FK and comparing to targets.""" + import pinocchio as pin + + fk_pos, fk_rot = compute_fk_ee_poses(mjcf_path, joint_configs) + if fk_pos is None: + return None + + T = len(joint_configs) + pos_errors_mm = np.linalg.norm(fk_pos - target_positions, axis=1) * 1000 + + rot_errors_deg = None + if target_orientations is not None: + rot_errors_deg = np.zeros(T) + for t in range(T): + R_err = target_orientations[t].T @ fk_rot[t] + angle = np.linalg.norm(pin.log3(R_err)) + rot_errors_deg[t] = np.degrees(angle) + + summary = f"FK Verification ({T} frames): pos mean={pos_errors_mm.mean():.2f}mm max={pos_errors_mm.max():.2f}mm" + if rot_errors_deg is not None: + summary += f", rot mean={rot_errors_deg.mean():.1f}° max={rot_errors_deg.max():.1f}°" + + return { + "fk_positions": fk_pos, + "fk_orientations": fk_rot, + "pos_errors_mm": pos_errors_mm, + "rot_errors_deg": rot_errors_deg, + "summary": summary, + } + + +def compute_mujoco_geom_transforms( + mjcf_path: str, + joint_configs: np.ndarray, +) -> tuple[ + list[list[tuple[np.ndarray, np.ndarray]]], + list[tuple[np.ndarray, np.ndarray]] | None, + list[tuple[np.ndarray, np.ndarray]] | None, + dict[str, list[tuple[np.ndarray, np.ndarray]]] | None, +]: + """Compute MuJoCo geom/body/site transforms in the Pinocchio-aligned world. + + Also extracts camera site pose, EE body pose, and named body/site frames. + + Important: some MJCFs (notably MuJoCo Menagerie's Google Robot) include a + fixed ``worldbody -> root_body`` transform that Pinocchio's + ``buildModelFromMJCF()`` omits. Dataset poses and IK targets already live in + Pinocchio's root-free world, so we explicitly remove that MuJoCo root + transform here before returning any MuJoCo-derived poses. + + Returns: + (all_geom_transforms, camera_poses_or_None, ee_poses_or_None, robot_frames_or_None) + - all_geom_transforms: list of per-frame geom transforms [(pos, mat), ...] + - camera_poses: list of (pos, mat) per frame for 'camera_site', or None if no site. + - ee_poses: list of (pos, mat) per frame for the EE body, or None. + - robot_frames: dict mapping ``body:`` / ``site:`` to per-frame poses. + """ + import mujoco + + model = mujoco.MjModel.from_xml_path(mjcf_path) + data = mujoco.MjData(model) + + visual_geom_ids = get_visual_geom_ids(model) + + # Determine which robot config applies (by matching MJCF filename) + robot_name = resolve_robot_name_from_mjcf(mjcf_path) + cfg = get_robot_config(robot_name) if robot_name is not None else {} + + # Find camera_site if it exists + camera_site_id = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_SITE, "camera_site") + has_camera_site = camera_site_id >= 0 + if has_camera_site: + body_id = model.site_bodyid[camera_site_id] + body_name = mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_BODY, body_id) or "?" + log.info(f"Found camera_site (id={camera_site_id}) on body '{body_name}'") + + # Also look up camera body (e.g. zed_mini for DROID) + camera_body_id = -1 + camera_body_name = cfg.get("camera_body") + if camera_body_name and not has_camera_site: + camera_body_id = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_BODY, camera_body_name) + if camera_body_id >= 0: + log.info(f"Found camera body '{camera_body_name}' (id={camera_body_id})") + + all_transforms = [] + camera_poses = [] if (has_camera_site or camera_body_id >= 0) else None + robot_frame_specs = [] + for body_id in range(1, model.nbody): + body_name = mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_BODY, body_id) or "" + if body_name: + robot_frame_specs.append(("body", body_name, body_id)) + for site_id in range(model.nsite): + site_name = mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_SITE, site_id) or "" + if site_name: + robot_frame_specs.append(("site", site_name, site_id)) + robot_frames = {f"{kind}:{name}": [] for kind, name, _ in robot_frame_specs} if robot_frame_specs else None + + # Find EE body for extracting FK-derived EE pose + ee_body_id = -1 + ee_override = cfg.get("ee_frame") + ee_candidates = get_ee_frame_candidates(robot_name) + for candidate in ee_candidates: + bid = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_BODY, candidate) + if bid >= 0: + ee_body_id = bid + break + ee_poses = [] if ee_body_id >= 0 else None + + # Find driver joint indices for robots with finger_joint_names + finger_joint_names = cfg.get("finger_joint_names", []) + arm_jnames = cfg.get("arm_joints", []) if cfg else [] + # Indices to pin during constraint settling: arm joints + driver joints + n_arm = cfg.get("n_arm_joints", 7) if cfg else 7 + if arm_jnames: + # Use name-based mapping for arm joint indices + pin_indices = [] + for jn in arm_jnames: + jid = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_JOINT, jn) + if jid >= 0: + pin_indices.append(model.jnt_qposadr[jid]) + else: + pin_indices = list(range(n_arm)) + if finger_joint_names: + for fjn in finger_joint_names: + for ji in range(model.njnt): + jname = mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_JOINT, ji) or "" + if jname == fjn: + qi = model.jnt_qposadr[ji] + pin_indices.append(qi) + + # Build mapping from IK output (pinocchio reduced model) to MuJoCo qpos indices. + # When a URDF is used with model reduction, the IK output has only arm+finger + # joints in pinocchio order. We need to map those to MuJoCo's qpos order. + arm_jnames = cfg.get("arm_joints", []) if cfg else [] + pin_to_mj_map = None # None = direct mapping (qpos[:len(q)] = q) + if arm_jnames: + # Build ordered list: arm joints first, then finger joints + ordered_jnames = list(arm_jnames) + list(finger_joint_names) + mj_indices = [] + for jn in ordered_jnames: + jid = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_JOINT, jn) + if jid >= 0: + mj_indices.append(model.jnt_qposadr[jid]) + if mj_indices: + pin_to_mj_map = mj_indices + + # If joint_configs has more columns than n_arm, the extra column is a + # normalized gripper signal (raw UR: 0=open, 1=closed). Robotiq ctrl + # matches: 0=open, 255=closed → ctrl = raw * finger_max (no inversion). + finger_max = cfg.get("finger_max", 0.0) if cfg else 0.0 + has_gripper_ctrl = finger_max > 0.0 and model.nu > n_arm and joint_configs.shape[1] > n_arm + + def _apply_world_correction(pos: np.ndarray, mat: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Map one MuJoCo world pose into the root-free Pinocchio world.""" + corrected_pos = world_correction[:3, :3] @ pos + world_correction[:3, 3] + corrected_mat = world_correction[:3, :3] @ mat + return corrected_pos.astype(np.float32), corrected_mat.astype(np.float32) + + for q in joint_configs: + if pin_to_mj_map and len(q) == len(pin_to_mj_map): + # Full arm+finger mapping from IK (e.g. Franka): use all joints. + data.qpos[:] = 0 + for i, mi in enumerate(pin_to_mj_map): + data.qpos[mi] = q[i] + else: + # For robots with a separate gripper ctrl signal, only write arm + # joints — the extra column is a raw gripper value, + # not a qpos DOF. For other robots the pinocchio output already + # includes finger joints in the trailing columns; write them all. + n_set = n_arm if has_gripper_ctrl else len(q) + data.qpos[:n_set] = q[:n_set] + mujoco.mj_forward(model, data) + + # For robots with equality constraints (e.g., Robotiq 4-bar linkage), + # step physics to let constraints resolve the passive linkage joints. + if model.neq > 0: + data.qvel[:] = 0 + data.ctrl[:] = 0 + # Raw UR gripper maps directly to Robotiq ctrl: 0=open, 255=closed. + if has_gripper_ctrl: + data.ctrl[-1] = float(q[n_arm]) * finger_max + gripper_ctrl_val = float(data.ctrl[-1]) if model.nu > 0 else 0.0 + saved = data.qpos[pin_indices].copy() + for _ in range(200): + mujoco.mj_step(model, data) + data.qpos[pin_indices] = saved + if model.nu > 0: + data.ctrl[-1] = gripper_ctrl_val # keep gripper ctrl during settling + data.qvel[:] = 0 + mujoco.mj_forward(model, data) + world_correction = get_mujoco_to_pinocchio_world_transform(model, data, robot_name) + + frame_transforms = [] + for gi in visual_geom_ids: + pos = data.geom_xpos[gi].copy() + mat = data.geom_xmat[gi].reshape(3, 3).copy() + frame_transforms.append(_apply_world_correction(pos, mat)) + all_transforms.append(frame_transforms) + + # Extract camera site pose + if has_camera_site: + cam_pos = data.site_xpos[camera_site_id].copy() + cam_mat = data.site_xmat[camera_site_id].reshape(3, 3).copy() + camera_poses.append(_apply_world_correction(cam_pos, cam_mat)) + elif camera_body_id >= 0: + cam_pos = data.xpos[camera_body_id].copy() + cam_mat = data.xmat[camera_body_id].reshape(3, 3).copy() + camera_poses.append(_apply_world_correction(cam_pos, cam_mat)) + + # Extract EE body pose + if ee_body_id >= 0: + ee_pos = data.xpos[ee_body_id].copy() + ee_mat = data.xmat[ee_body_id].reshape(3, 3).copy() + ee_poses.append(_apply_world_correction(ee_pos, ee_mat)) + + if robot_frames is not None: + for kind, name, frame_id in robot_frame_specs: + if kind == "body": + pos = data.xpos[frame_id].copy() + mat = data.xmat[frame_id].reshape(3, 3).copy() + else: + pos = data.site_xpos[frame_id].copy() + mat = data.site_xmat[frame_id].reshape(3, 3).copy() + robot_frames[f"{kind}:{name}"].append(_apply_world_correction(pos, mat)) + + return all_transforms, camera_poses, ee_poses, robot_frames diff --git a/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/robot_scene_model.py b/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/robot_scene_model.py new file mode 100644 index 0000000000000000000000000000000000000000..0dfc5c7673d29c00da4407859e3ceb48277dc4c0 --- /dev/null +++ b/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/robot_scene_model.py @@ -0,0 +1,216 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: OpenMDW-1.1 + +"""Public robot-scene abstraction for the action viewer. + +`RobotSceneModel` is the viewer-facing contract for robot assets and +kinematics. It wraps the lower-level MuJoCo / Pinocchio helpers so callers do +not need to coordinate mesh loading, IK, frame extraction, or world-alignment +corrections themselves. +""" + +from __future__ import annotations + +import os +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any + +import numpy as np + +from cosmos_framework.data.vfm.action.urdf_visualizer import urdf_loader + +MeshSpec = tuple[str, object, np.ndarray] +FramePose = tuple[np.ndarray, np.ndarray] +FrameSeries = dict[str, list[FramePose]] + + +@dataclass(frozen=True) +class RobotTrajectory: + """Render-ready robot geometry for one solved trajectory.""" + + mesh_transforms: list[list[FramePose]] + named_frames: FrameSeries + + +def get_robot_config(robot_name: str) -> dict[str, Any]: + """Return the static config for one supported robot.""" + cfg = urdf_loader.ROBOT_CONFIGS.get(robot_name) + if cfg is None: + raise ValueError(f"Unknown robot: {robot_name}. Available: {list(urdf_loader.ROBOT_CONFIGS)}") + return cfg + + +def get_urdf_path(robot_name: str) -> str | None: + """Return the preferred URDF path for one robot, if available.""" + return urdf_loader.get_urdf_path(robot_name) + + +def get_mjcf_path(robot_name: str) -> str: + """Return the canonical MJCF path for one robot.""" + return urdf_loader.get_mjcf_path(robot_name) + + +def get_mujoco_to_pinocchio_world_transform(model: Any, data: Any, robot_name: str | None = None) -> np.ndarray: + """Map MuJoCo world poses into the root-free Pinocchio world.""" + return urdf_loader.get_mujoco_to_pinocchio_world_transform(model, data, robot_name) + + +def get_visual_geom_ids(model: Any) -> list[int]: + """Return the MuJoCo visual geom order used by the viewer.""" + return urdf_loader._get_visual_geom_ids(model) + + +def get_ee_frame_candidates(robot_name: str | None = None) -> list[str]: + """Return the ordered end-effector frame candidates for one robot.""" + if robot_name is None: + return list(urdf_loader._EE_FRAME_CANDIDATES) + cfg = urdf_loader.ROBOT_CONFIGS.get(robot_name, {}) + ee_frame = cfg.get("ee_frame") + if ee_frame is None: + return list(urdf_loader._EE_FRAME_CANDIDATES) + return [str(ee_frame), *urdf_loader._EE_FRAME_CANDIDATES] + + +def get_robot_loaders() -> dict[str, Callable[[], tuple[list[MeshSpec], np.ndarray]]]: + """Return the low-level robot mesh loader registry.""" + return urdf_loader.get_robot_loaders() + + +def resolve_robot_name_from_mjcf(mjcf_path: str) -> str | None: + """Infer a configured robot name from an MJCF filename.""" + filename = os.path.basename(mjcf_path) + for robot_name, cfg in urdf_loader.ROBOT_CONFIGS.items(): + if filename == cfg.get("mjcf"): + return robot_name + return None + + +def _copy_mesh_specs(meshes: list[MeshSpec]) -> list[MeshSpec]: + """Copy mesh transforms while reusing immutable mesh geometry.""" + return [(name, mesh, transform.copy().astype(np.float32)) for name, mesh, transform in meshes] + + +def _transform_mesh_specs(meshes: list[MeshSpec], base_pose: np.ndarray | None) -> list[MeshSpec]: + """Apply one rigid transform to a list of world-space mesh poses.""" + copied = _copy_mesh_specs(meshes) + if base_pose is None: + return copied + transformed: list[MeshSpec] = [] + for name, mesh, transform in copied: + transformed.append((name, mesh, (base_pose @ transform).astype(np.float32))) # [4,4] + return transformed + + +def _remove_pose_base(poses_world: np.ndarray, base_pose: np.ndarray | None) -> np.ndarray: + """Map world-space wrist poses back into one arm-local base frame.""" + if base_pose is None: + return poses_world.astype(np.float32) + base_inv = np.linalg.inv(base_pose).astype(np.float32) # [4,4] + return np.einsum("ij,njk->nik", base_inv, poses_world).astype(np.float32) # [T,4,4] + + +def _apply_base_to_mesh_transforms( + transforms: list[list[FramePose]], + base_pose: np.ndarray | None, +) -> list[list[FramePose]]: + """Apply one rigid base pose to per-geom world transforms.""" + if base_pose is None: + return transforms + base_rot = base_pose[:3, :3].astype(np.float32) # [3,3] + base_pos = base_pose[:3, 3].astype(np.float32) # [3] + transformed: list[list[FramePose]] = [] + for frame_transforms in transforms: + transformed_frame: list[FramePose] = [] + for pos, rot in frame_transforms: + transformed_frame.append((base_rot @ pos + base_pos, base_rot @ rot)) + transformed.append(transformed_frame) + return transformed + + +def _apply_base_to_named_frames( + frames: FrameSeries, + base_pose: np.ndarray | None, +) -> FrameSeries: + """Apply one rigid base pose to named body/site frames.""" + if base_pose is None: + return frames + base_rot = base_pose[:3, :3].astype(np.float32) # [3,3] + base_pos = base_pose[:3, 3].astype(np.float32) # [3] + transformed: FrameSeries = {} + for frame_key, poses in frames.items(): + transformed[frame_key] = [(base_rot @ pos + base_pos, base_rot @ rot) for pos, rot in poses] + return transformed + + +class RobotSceneModel: + """Single public abstraction for robot meshes, IK/FK, and debug frames.""" + + def __init__(self, robot_name: str) -> None: + self.robot_name = robot_name + self._config = get_robot_config(robot_name) + self._mjcf_path = get_mjcf_path(robot_name) + self._home_meshes: list[MeshSpec] | None = None + + @property + def mjcf_path(self) -> str: + """Return the underlying MJCF path for this robot.""" + return self._mjcf_path + + @property + def ee_frame_name(self) -> str: + """Return the canonical IK / debug frame name for this robot.""" + return str(self._config.get("ee_frame", "ee_frame")) + + def get_home_meshes(self, base_pose: np.ndarray | None = None) -> list[MeshSpec]: + """Return home-pose meshes in the requested world frame.""" + if self._home_meshes is None: + loaders = get_robot_loaders() + loader = loaders.get(self.robot_name) + if loader is None: + raise ValueError(f"No robot loader registered for {self.robot_name}") + meshes, _ = loader() + self._home_meshes = _copy_mesh_specs(meshes) + return _transform_mesh_specs(self._home_meshes, base_pose) + + def solve_visual_trajectory( + self, + wrist_poses_world: np.ndarray | None, + gripper_openings: np.ndarray | None = None, + to_opencv: np.ndarray | None = None, + base_pose: np.ndarray | None = None, + ) -> RobotTrajectory | None: + """Solve IK for world-space wrist poses and return render-ready robot state.""" + if wrist_poses_world is None or len(wrist_poses_world) < 2: + return None + + local_wrist_poses = _remove_pose_base(wrist_poses_world, base_pose) # [T,4,4] + target_positions = local_wrist_poses[:, :3, 3].astype(np.float32) # [T,3] + target_rotations = local_wrist_poses[:, :3, :3].astype(np.float32) # [T,3,3] + if to_opencv is not None and not np.allclose(to_opencv, np.eye(3, dtype=np.float32)): + target_rotations = target_rotations @ to_opencv.T[None] # [T,3,3] + + from cosmos_framework.data.vfm.action.urdf_visualizer.ik_solver import ( + compute_fk_ee_poses, + compute_mujoco_geom_transforms, + solve_trajectory_ik, + ) + + joint_configs = solve_trajectory_ik( + self.mjcf_path, + target_positions, + gripper_openings=gripper_openings, + world_ee_orientations=target_rotations, + robot_name=self.robot_name, + ) + if joint_configs is None: + return None + + fk_pos, fk_rot = compute_fk_ee_poses(self.mjcf_path, joint_configs, robot_name=self.robot_name) + mesh_transforms, _, _, named_frames = compute_mujoco_geom_transforms(self.mjcf_path, joint_configs) + public_frames: FrameSeries = {} if named_frames is None else dict(named_frames) + public_frames[f"ik:{self.ee_frame_name}"] = list(zip(fk_pos, fk_rot, strict=True)) + + mesh_transforms = _apply_base_to_mesh_transforms(mesh_transforms, base_pose) + public_frames = _apply_base_to_named_frames(public_frames, base_pose) + return RobotTrajectory(mesh_transforms=mesh_transforms, named_frames=public_frames) diff --git a/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/unified_action.py b/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/unified_action.py new file mode 100644 index 0000000000000000000000000000000000000000..3ede1ae79cd5f73a89da51b19550193362f5995e --- /dev/null +++ b/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/unified_action.py @@ -0,0 +1,249 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: OpenMDW-1.1 + +"""Raw action converters for the standalone action viewer. + +The Space release is raw-action-only. It accepts 9D ego/camera actions, 10D +single-arm actions, and 20D dual-arm actions. The renderer still uses a fixed +57D internal canvas so the downstream drawing code can stay format-agnostic, +but hand-pose/57D datasets are intentionally not part of this release. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from enum import Enum +from typing import Any + +import numpy as np +import torch + +NO_FINGERS = (False, False, False, False, False) + + +class ActionFormat(str, Enum): + """Explicit raw action layouts supported by the viewer pipeline.""" + + EGO_9D = "9d" + SINGLE_ARM_10D = "10d" + DUAL_ARM_20D = "20d" + + @property + def expected_dim(self) -> int: + return {self.EGO_9D: 9, self.SINGLE_ARM_10D: 10, self.DUAL_ARM_20D: 20}[self] + + +@dataclass +class Action57DMask: + """Per-component validity for the internal 57D rendering canvas.""" + + ego: bool = False + right_wrist: bool = False + right_fingers: tuple[bool, ...] = NO_FINGERS + left_wrist: bool = False + left_fingers: tuple[bool, ...] = NO_FINGERS + + +@dataclass +class UnifiedAction: + """Internal 57D action plus scalar gripper side channels.""" + + action: np.ndarray + mask: Action57DMask + gripper_right: np.ndarray | None = None + gripper_left: np.ndarray | None = None + + +@dataclass +class SceneState: + """Renderer-ready reconstructed trajectories for one sample.""" + + mask: Action57DMask + ego_poses: np.ndarray | None = None + right_poses: np.ndarray | None = None + left_poses: np.ndarray | None = None + right_fingers: np.ndarray | None = None + left_fingers: np.ndarray | None = None + gripper_right: np.ndarray | None = None + gripper_left: np.ndarray | None = None + video: np.ndarray | None = None + action_raw: np.ndarray | None = None + T: int = 0 + + +def to_unified_from_9d(action: np.ndarray) -> UnifiedAction: + """9D camera/AV ``[pos(3)+rot6d(6)]`` → ego only.""" + a = np.zeros((action.shape[0], 57), dtype=np.float32) + a[:, 0:9] = action[:, :9] + return UnifiedAction(action=a, mask=Action57DMask(ego=True)) + + +def to_unified_from_10d(action: np.ndarray) -> UnifiedAction: + """10D single arm ``[pos(3)+rot6d(6)+grip(1)]`` → right wrist + gripper.""" + a = np.zeros((action.shape[0], 57), dtype=np.float32) + a[:, 9:18] = action[:, :9] + return UnifiedAction( + action=a, + mask=Action57DMask(right_wrist=True), + gripper_right=action[:, 9].astype(np.float32), + ) + + +def to_unified_from_20d(action: np.ndarray) -> UnifiedAction: + """20D dual arm ``[left(10) | right(10)]`` → both wrists + both grippers.""" + a = np.zeros((action.shape[0], 57), dtype=np.float32) + a[:, 33:42] = action[:, :9] + a[:, 9:18] = action[:, 10:19] + return UnifiedAction( + action=a, + mask=Action57DMask(right_wrist=True, left_wrist=True), + gripper_right=action[:, 19].astype(np.float32), + gripper_left=action[:, 9].astype(np.float32), + ) + + +def _validate_action_shape(action: np.ndarray, action_format: ActionFormat) -> None: + if action.ndim != 2: + raise ValueError(f"Expected a rank-2 action array, got shape {action.shape}") + expected_dim = action_format.expected_dim + actual_dim = int(action.shape[-1]) + if actual_dim != expected_dim: + raise ValueError(f"Action format {action_format.value} expects trailing dim {expected_dim}, got {actual_dim}") + + +def to_unified(action: np.ndarray, action_format: ActionFormat) -> UnifiedAction: + """Convert one supported raw action format into the internal render canvas.""" + _validate_action_shape(action, action_format) + if action_format is ActionFormat.EGO_9D: + return to_unified_from_9d(action) + if action_format is ActionFormat.SINGLE_ARM_10D: + return to_unified_from_10d(action) + if action_format is ActionFormat.DUAL_ARM_20D: + return to_unified_from_20d(action) + raise ValueError(f"Unsupported action format: {action_format}") + + +def _pos_rot6d_to_mat(se3: np.ndarray) -> np.ndarray: + """Convert ``(N, 9)`` pos+rot6d to ``(N, 4, 4)`` SE(3) matrices.""" + n = se3.shape[0] + pos = se3[:, :3] + r6 = se3[:, 3:9] + col0 = r6[:, :3].copy() + col0 = col0 / (np.linalg.norm(col0, axis=-1, keepdims=True) + 1e-8) + col1 = r6[:, 3:6] - np.sum(r6[:, 3:6] * col0, axis=-1, keepdims=True) * col0 + col1 = col1 / (np.linalg.norm(col1, axis=-1, keepdims=True) + 1e-8) + col2 = np.cross(col0, col1) + mats = np.tile(np.eye(4, dtype=np.float32), (n, 1, 1)) + mats[:, :3, 0] = col0 + mats[:, :3, 1] = col1 + mats[:, :3, 2] = col2 + mats[:, :3, 3] = pos + return mats + + +def _chain_se3( + deltas: np.ndarray, + initial_pose: np.ndarray | None = None, + pose_convention: str = "backward_framewise", +) -> np.ndarray: + """Chain ``(T, 9)`` relative deltas into ``(T+1, 4, 4)`` absolute poses.""" + delta_mats = _pos_rot6d_to_mat(deltas) + initial = np.eye(4, dtype=np.float32) if initial_pose is None else initial_pose.astype(np.float32) + poses = np.empty((deltas.shape[0] + 1, 4, 4), dtype=np.float32) + poses[0] = initial + if pose_convention == "absolute": + poses[1:] = delta_mats + else: + for t in range(deltas.shape[0]): + poses[t + 1] = poses[t] @ delta_mats[t] + return poses + + +def _apply_pose_base(poses: np.ndarray | None, base_pose: np.ndarray | None) -> np.ndarray | None: + if poses is None or base_pose is None: + return poses + return np.einsum("ij,tjk->tik", base_pose.astype(np.float32), poses).astype(np.float32) + + +def _align_gripper_to_pose_frames(gripper: np.ndarray | None, poses: np.ndarray | None) -> np.ndarray | None: + """Align per-action gripper commands with ``T+1`` chained pose frames. + + Raw 10D/20D actions provide one gripper value per delta action (``T``), + while ``_chain_se3`` returns one pose per frame (``T+1``). Duplicate the + first command for frame 0 so IK receives a gripper value for every pose. + """ + if gripper is None: + return None + g = np.asarray(gripper, dtype=np.float32) + if poses is None: + return g + n_pose = len(poses) + if len(g) == n_pose: + return g + if len(g) + 1 == n_pose: + return np.concatenate([g[:1], g]).astype(np.float32, copy=False) + if len(g) > n_pose: + return g[:n_pose].astype(np.float32, copy=False) + if len(g) == 0: + return g + pad = np.full((n_pose - len(g),), g[-1], dtype=np.float32) + return np.concatenate([g, pad]).astype(np.float32, copy=False) + + +def build_scene_state( + unified: UnifiedAction, + *, + initial_pose: np.ndarray | None = None, + initial_pose_right: np.ndarray | None = None, + initial_pose_left: np.ndarray | None = None, + right_base_pose: np.ndarray | None = None, + left_base_pose: np.ndarray | None = None, + pose_convention: str = "backward_framewise", + sample: dict[str, Any] | None = None, +) -> SceneState: + """Reconstruct viewer trajectories from raw-action-derived ``UnifiedAction``.""" + del sample + action = unified.action + mask = unified.mask + state = SceneState(mask=mask) + if mask.ego: + state.ego_poses = _chain_se3(action[:, 0:9], initial_pose, pose_convention) + if mask.right_wrist: + state.right_poses = _chain_se3( + action[:, 9:18], + initial_pose_right if initial_pose_right is not None else initial_pose, + pose_convention, + ) + if mask.left_wrist: + state.left_poses = _chain_se3( + action[:, 33:42], + initial_pose_left if initial_pose_left is not None else initial_pose, + pose_convention, + ) + state.right_poses = _apply_pose_base(state.right_poses, right_base_pose) + state.left_poses = _apply_pose_base(state.left_poses, left_base_pose) + state.gripper_right = _align_gripper_to_pose_frames(unified.gripper_right, state.right_poses) + state.gripper_left = _align_gripper_to_pose_frames(unified.gripper_left, state.left_poses) + state.action_raw = action.astype(np.float32) + state.T = action.shape[0] + return state + + +def get_video_from_sample(sample: dict) -> np.ndarray | None: + """Extract video frames from a dataset sample as ``(T+1, H, W, 3)`` uint8.""" + video = sample.get("video") + if video is None: + return None + if isinstance(video, torch.Tensor): + video = video.numpy() + if video.ndim == 4: + c, t_dim, _, _ = video.shape + if c in (1, 3) and t_dim > 3: + video = np.transpose(video, (1, 2, 3, 0)) + elif video.shape[1] in (1, 3) and t_dim <= 3: + video = np.transpose(video, (0, 2, 3, 1)) + if video.dtype in (np.float32, np.float64): + video = np.clip(video * 255, 0, 255).astype(np.uint8) + if video.ndim == 4 and video.shape[-1] == 1: + video = np.repeat(video, 3, axis=-1) + return video diff --git a/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/unified_renderer.py b/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/unified_renderer.py new file mode 100644 index 0000000000000000000000000000000000000000..e045383b031edc917e4867b99a0a76b956b0d135 --- /dev/null +++ b/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/unified_renderer.py @@ -0,0 +1,736 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: OpenMDW-1.1 + +"""Mask-driven renderer for ``SceneState`` — the unified 57D viewer backend. + +Owns all viser scene handles. Draws only what the mask declares valid. +No action-format branching — everything goes through ``SceneState``. +""" + +from __future__ import annotations + +from typing import Any + +import numpy as np + +from cosmos_framework.utils import log +from cosmos_framework.data.vfm.action.urdf_visualizer.robot_scene_model import RobotSceneModel +from cosmos_framework.data.vfm.action.urdf_visualizer.unified_action import SceneState + + +class UnifiedRenderer: + """Mask-driven 3D renderer for the unified 57D action viewer.""" + + # ── Palette ── + TIP_RADIUS = 0.0042 + FRUSTUM_SCALE = 0.10 + EGO_AXIS_LENGTH = 0.04 + EGO_AXIS_RADIUS = 0.002 + EGO_TRAJ_LENGTH_REFERENCE = 0.55 + EGO_TRAJ_SCALE_MIN = 0.35 + EGO_TRAJ_SCALE_MAX = 1.80 + EGO_TRAJ_LINE_WIDTH = 1.0 + EE_TRAJ_LINE_WIDTH = 1.5 + HAND_AXIS_LENGTH = 0.05 + HAND_AXIS_RADIUS = 0.002 + ROBOT_BODY_AXIS_LENGTH = 0.03 + ROBOT_BODY_AXIS_RADIUS = 0.0012 + ROBOT_SITE_AXIS_LENGTH = 0.022 + ROBOT_SITE_AXIS_RADIUS = 0.0009 + COLOR_EGO = (52, 152, 219) # blue + COLOR_EGO_TOP = (231, 76, 60) # red + COLOR_RIGHT = (243, 156, 18) # orange + COLOR_LEFT = (155, 89, 182) # purple + GRIPPER_TIP_COLORS = [(231, 76, 60), (241, 196, 15)] + + @staticmethod + def _soften_color(color: tuple[int, int, int], mix: float = 0.35) -> tuple[int, int, int]: + """Blend a color toward white for less visually dominant trajectories.""" + base = np.asarray(color, dtype=np.float32) + soft = base * (1.0 - mix) + 255.0 * mix + rounded = soft.round() + return int(rounded[0]), int(rounded[1]), int(rounded[2]) + + def _p(self, path: str) -> str: + """Prepend the instance name_prefix to a scene path.""" + return f"{self._name_prefix}{path}" + + def __init__( + self, + server, + name_prefix: str = "", + palette: dict | None = None, + ): + import viser.transforms as vtf + + self.server = server + self.vtf = vtf + self.state: SceneState | None = None + self._entry: Any = None + self._axis_scale = 1.0 + self._name_prefix = name_prefix + + self._ego_frustum_scale_base = self.FRUSTUM_SCALE + self._ego_axis_length_base = self.EGO_AXIS_LENGTH + self._ego_axis_radius_base = self.EGO_AXIS_RADIUS + self._ego_frustum_fov = np.deg2rad(60.0) + self._ego_frustum_aspect = 4 / 3 + + # Per-instance color palette (allows GT and pred to use different colors) + pal = palette or {} + self.COLOR_EGO = pal.get("ego", type(self).COLOR_EGO) + self.COLOR_EGO_TOP = pal.get("ego_top", type(self).COLOR_EGO_TOP) + self.COLOR_RIGHT = pal.get("right", type(self).COLOR_RIGHT) + self.COLOR_LEFT = pal.get("left", type(self).COLOR_LEFT) + + # ── Ego ── + self.ego_frame = server.scene.add_frame( + self._p("/ego/frame"), axes_length=self.EGO_AXIS_LENGTH, axes_radius=self.EGO_AXIS_RADIUS + ) + self.ego_frustum = server.scene.add_line_segments( + self._p("/ego/frustum"), + points=self._make_ego_frustum_wireframe_points(self._ego_frustum_fov, self._ego_frustum_aspect), + colors=np.array(self.COLOR_EGO, dtype=np.uint8), + scale=self.FRUSTUM_SCALE, + line_width=2.0, + wxyz=(1.0, 0.0, 0.0, 0.0), + position=(0.0, 0.0, 0.0), + ) + self.ego_frustum_up = server.scene.add_line_segments( + self._p("/ego/frustum_up"), + points=self._make_ego_frustum_up_points(self._ego_frustum_fov, self._ego_frustum_aspect), + colors=np.array(self.COLOR_EGO_TOP, dtype=np.uint8), + line_width=3.0, + scale=self.FRUSTUM_SCALE, + wxyz=(1.0, 0.0, 0.0, 0.0), + position=(0.0, 0.0, 0.0), + ) + self.ego_traj = server.scene.add_spline_catmull_rom( + self._p("/ego/traj"), + positions=np.zeros([2, 3], dtype=np.float32), + color=self._soften_color(self.COLOR_EGO), + line_width=self.EGO_TRAJ_LINE_WIDTH, + ) + + # ── Right effector ── + self.right_frame = server.scene.add_frame( + self._p("/right/frame"), axes_length=self.HAND_AXIS_LENGTH, axes_radius=self.HAND_AXIS_RADIUS + ) + self.right_traj = server.scene.add_spline_catmull_rom( + self._p("/right/traj"), + positions=np.zeros([2, 3], dtype=np.float32), + color=self._soften_color(self.COLOR_RIGHT), + line_width=self.EE_TRAJ_LINE_WIDTH, + ) + self.right_ee = server.scene.add_point_cloud( + self._p("/right/point"), + points=np.zeros([1, 3], dtype=np.float32), + colors=np.array([self.COLOR_RIGHT], dtype=np.uint8), + point_size=0.015, + point_shape="circle", + ) + self.right_gripper_tips = [ + server.scene.add_icosphere( + self._p(f"/right/gripper_tip_{side}"), + radius=self.TIP_RADIUS, + color=self.GRIPPER_TIP_COLORS[i], + position=(0.0, 0.0, 0.0), + ) + for i, side in enumerate(("left", "right")) + ] + + # ── Left effector ── + self.left_frame = server.scene.add_frame( + self._p("/left/frame"), axes_length=self.HAND_AXIS_LENGTH, axes_radius=self.HAND_AXIS_RADIUS + ) + self.left_traj = server.scene.add_spline_catmull_rom( + self._p("/left/traj"), + positions=np.zeros([2, 3], dtype=np.float32), + color=self._soften_color(self.COLOR_LEFT), + line_width=self.EE_TRAJ_LINE_WIDTH, + ) + self.left_ee = server.scene.add_point_cloud( + self._p("/left/point"), + points=np.zeros([1, 3], dtype=np.float32), + colors=np.array([self.COLOR_LEFT], dtype=np.uint8), + point_size=0.015, + point_shape="circle", + ) + self.left_gripper_tips = [ + server.scene.add_icosphere( + self._p(f"/left/gripper_tip_{side}"), + radius=self.TIP_RADIUS, + color=self.GRIPPER_TIP_COLORS[i], + position=(0.0, 0.0, 0.0), + ) + for i, side in enumerate(("left", "right")) + ] + + # ── IK robot meshes ── + self.robot_right: list = [] + self.robot_left: list = [] + self._robot_frame_handles_right: dict[str, Any] = {} + self._robot_frame_handles_left: dict[str, Any] = {} + self._current_robot: Any | None = None + self._robot_scene_model: RobotSceneModel | None = None + self._ik_right: list | None = None + self._ik_left: list | None = None + self._robot_frames_right: dict[str, list[tuple[np.ndarray, np.ndarray]]] | None = None + self._robot_frames_left: dict[str, list[tuple[np.ndarray, np.ndarray]]] | None = None + self._robot_link_names: list[str] = [] + self._robot_local_transforms: list[np.ndarray] = [] + + # ── Video panel (set by viewer.py) ── + self._cam_handle: Any | None = None + + self.hide_all() + + # ─── Per-Episode ────────────────────────────────────────────────────────── + + def load( + self, + state: SceneState, + entry: Any, + to_opencv: np.ndarray | dict[str, np.ndarray] | None = None, + ): + """Load a new episode. Rebuild trajectories, robot meshes, and IK. + + Args: + state: Reconstructed ``SceneState`` with absolute poses. + entry: ``DatasetEntry`` with robot_name, max_finger_width, etc. + to_opencv: Optional native-to-OpenCV rotation. + """ + self.state = state + self._entry = entry + self._to_opencv = to_opencv if to_opencv is not None else np.eye(3, dtype=np.float32) + self._ego_frustum_fov = np.deg2rad(entry.camera_fov_deg) + self._ego_frustum_aspect = float(entry.camera_aspect) + self.ego_frustum.points = self._make_ego_frustum_wireframe_points( + self._ego_frustum_fov, + self._ego_frustum_aspect, + ) + self.ego_frustum_up.points = self._make_ego_frustum_up_points( + self._ego_frustum_fov, + self._ego_frustum_aspect, + ) + self._update_ego_visual_scale(state.ego_poses if state.mask.ego else None) + self.update_axis_scale(self._axis_scale) + self.hide_all() + + # ── Robot meshes + IK from canonical world-space SceneState ── + self._ik_right = None + self._ik_left = None + self._robot_frames_right = None + self._robot_frames_left = None + if entry.robot_name: + self._load_robot_and_ik(state, entry) + + # Rebuild trajectory splines from canonical world-space SceneState. + if state.mask.ego and state.ego_poses is not None: + self._rebuild_traj(self.ego_traj, state.ego_poses, self.COLOR_EGO) + if state.mask.right_wrist and state.right_poses is not None: + self._rebuild_traj(self.right_traj, state.right_poses, self.COLOR_RIGHT) + if state.mask.left_wrist and state.left_poses is not None: + self._rebuild_traj(self.left_traj, state.left_poses, self.COLOR_LEFT) + + def set_video_panel(self, panel_handle: Any | None) -> None: + """Attach the optional GUI image panel used for episode video.""" + self._cam_handle = panel_handle + + # ─── Per-Frame ──────────────────────────────────────────────────────────── + + def update(self, t: int, show: dict): + """Update all scene elements for time step ``t``. + + Args: + t: Frame index (0-based). + show: Visibility flags: ``frames``, ``traj``, ``fingertips``, ``ego``, ``robot``. + """ + state = self.state + if state is None: + return + mask = state.mask + + # ── Ego ── + self._update_ego(t, state.ego_poses, mask.ego and show.get("ego", False), show) + + # ── Right effector ── + self._update_effector( + t, + state.right_poses, + mask.right_wrist, + self.right_frame, + self.right_ee, + self.right_traj, + show, + ) + self._update_gripper( + t, + state.right_poses, + state.gripper_right, + mask.right_wrist, + mask.right_fingers, + self.right_gripper_tips, + show, + ) + + # ── Left effector ── + self._update_effector( + t, + state.left_poses, + mask.left_wrist, + self.left_frame, + self.left_ee, + self.left_traj, + show, + ) + self._update_gripper( + t, + state.left_poses, + state.gripper_left, + mask.left_wrist, + mask.left_fingers, + self.left_gripper_tips, + show, + ) + + # ── IK robot meshes ── + self._update_robot(t, show) + + # ── Video panel ── + if self._cam_handle is not None and state.video is not None and t < len(state.video): + self._cam_handle.image = state.video[t] + + # ─── Action Text ────────────────────────────────────────────────────────── + + def format_action_text(self, t: int) -> str: + """Return a formatted string showing 57D action values at step ``t``. + + Always shows the full 57D layout. Validity indicator (✓/·) in front of + each component based on the mask. + """ + state = self.state + if state is None or state.action_raw is None: + return "" + if t == 0: + return "*t=0: anchor pose (identity)*" + if (t - 1) >= len(state.action_raw): + return "" + + a = state.action_raw[t - 1] # always 57D (zero-padded) + mask = state.mask + + def _fmt(v): + return " ".join(f"{x:+.4f}" for x in v) + + def _v(active): + return "✓" if active else "·" + + # Gripper auxiliary values (not in 57D vector) + grip_r_str = "" + grip_l_str = "" + if state.gripper_right is not None and t < len(state.gripper_right): + grip_r_str = f" ✓ gripper {state.gripper_right[t]:+.4f}" + if state.gripper_left is not None and t < len(state.gripper_left): + grip_l_str = f" ✓ gripper {state.gripper_left[t]:+.4f}" + + parts = [ + f"step {t - 1} → {t} (57D)", + "═" * 36, + f"{_v(mask.ego)} Ego pos [0:3] {_fmt(a[0:3])}", + f" {' ' * 1} rot [3:9] {_fmt(a[3:9])}", + "", + f"{_v(mask.right_wrist)} R wrist pos [9:12] {_fmt(a[9:12])}", + f" {' ' * 1} rot [12:18] {_fmt(a[12:18])}", + ] + if grip_r_str: + parts.append(grip_r_str) + + parts += [ + "", + f"{_v(mask.left_wrist)} L wrist pos [33:36] {_fmt(a[33:36])}", + f" {' ' * 1} rot [36:42] {_fmt(a[36:42])}", + ] + if grip_l_str: + parts.append(grip_l_str) + + return str("```\n" + "\n".join(parts) + "\n```") + + # ─── Private: Effector ──────────────────────────────────────────────────── + + @staticmethod + def _make_ego_frustum_wireframe_points(fov: float, aspect: float) -> np.ndarray: + """Build wireframe segments for the ego camera frustum.""" + half_height = float(np.tan(fov / 2.0)) + half_width = float(aspect) * half_height + top_left = np.array([-half_width, -half_height, 1.0], dtype=np.float32) + top_right = np.array([half_width, -half_height, 1.0], dtype=np.float32) + bottom_right = np.array([half_width, half_height, 1.0], dtype=np.float32) + bottom_left = np.array([-half_width, half_height, 1.0], dtype=np.float32) + origin = np.array([0.0, 0.0, 0.0], dtype=np.float32) + return np.array( + [ + [origin, top_left], + [origin, top_right], + [origin, bottom_right], + [origin, bottom_left], + [top_left, top_right], + [top_right, bottom_right], + [bottom_right, bottom_left], + [bottom_left, top_left], + ], + dtype=np.float32, + ) + + @staticmethod + def _make_ego_frustum_up_points(fov: float, aspect: float) -> np.ndarray: + """Build a red segment that marks the frustum's far-edge upright tick.""" + half_height = float(np.tan(fov / 2.0)) + _ = aspect + top_y = -half_height + return np.array( + [[[0.0, top_y, 1.0], [0.0, top_y * 1.18, 1.0]]], + dtype=np.float32, + ) + + def _update_ego(self, t: int, poses: np.ndarray | None, active: bool, show: dict) -> None: + if active and poses is not None and t < len(poses): + pos = poses[t, :3, 3] + rot = poses[t, :3, :3] + wxyz = self.vtf.SO3.from_matrix(rot).wxyz + self.ego_frame.position = pos + self.ego_frame.wxyz = wxyz + self.ego_frame.visible = show.get("frames", True) + self.ego_frustum.position = pos + self.ego_frustum.wxyz = wxyz + self.ego_frustum.visible = True + self.ego_frustum_up.position = pos + self.ego_frustum_up.wxyz = wxyz + self.ego_frustum_up.visible = True + self.ego_traj.visible = show.get("traj", True) + else: + self.ego_frame.visible = False + self.ego_frustum.visible = False + self.ego_frustum_up.visible = False + self.ego_traj.visible = False + + def _update_effector(self, t, poses, active, frame, ee, traj, show): + if active and poses is not None and t < len(poses): + pos = poses[t, :3, 3] + rot = poses[t, :3, :3] + frame.position = pos + frame.wxyz = self.vtf.SO3.from_matrix(rot).wxyz + frame.visible = show.get("frames", True) + ee.points = pos[None] + ee.visible = True + traj.visible = show.get("traj", True) + else: + frame.visible = False + ee.visible = False + traj.visible = False + + # ─── Private: Gripper ───────────────────────────────────────────────────── + + def _update_gripper(self, t, poses, gripper, wrist_active, finger_mask, handle, show): + has_fingers = any(finger_mask) + if not wrist_active or has_fingers or gripper is None or poses is None or t >= len(gripper) or t >= len(poses): + for tip_handle in handle: + tip_handle.visible = False + return + if not show.get("fingertips", True): + for tip_handle in handle: + tip_handle.visible = False + return + pos = poses[t, :3, 3].astype(np.float32) + rot = poses[t, :3, :3].astype(np.float32) + g = float(gripper[t]) + mfw = getattr(self._entry, "max_finger_width", 0.05) + half_w = g * mfw / 2.0 + finger_len = 0.06 + tip_l = pos + rot @ np.array([half_w, 0, finger_len], dtype=np.float32) + tip_r = pos + rot @ np.array([-half_w, 0, finger_len], dtype=np.float32) + for tip_handle, tip in zip(handle, (tip_l, tip_r), strict=True): + tip_handle.position = tip + tip_handle.visible = True + + # ─── Private: Trajectory ────────────────────────────────────────────────── + + def _rebuild_traj(self, traj_handle, poses, color): + """Rebuild a trajectory spline from absolute poses.""" + positions = poses[:, :3, 3].astype(np.float32) + if len(positions) < 2: + traj_handle.visible = False + return + # Keep the existing handle alive. Replacing a spline with remove()+add + # can race with GUI callbacks/playback that still hold the old handle, + # causing viser to raise "Cannot assign to 'visible' on a removed ...". + traj_handle.points = positions + traj_handle.color = self._soften_color(color) + traj_handle.line_width = self.EGO_TRAJ_LINE_WIDTH if traj_handle is self.ego_traj else self.EE_TRAJ_LINE_WIDTH + traj_handle.visible = True + + @staticmethod + def _trajectory_length(poses: np.ndarray | None) -> float: + """Compute the total path length of a pose trajectory.""" + if poses is None or len(poses) < 2: + return 0.0 + positions = poses[:, :3, 3].astype(np.float32) + deltas = np.diff(positions, axis=0) + return float(np.linalg.norm(deltas, axis=1).sum()) + + def _update_ego_visual_scale(self, poses: np.ndarray | None) -> None: + """Scale the ego camera frame/frustum from the episode trajectory length.""" + traj_length = self._trajectory_length(poses) + if traj_length <= 0.0: + traj_scale = 1.0 + else: + traj_scale = float( + np.clip( + traj_length / self.EGO_TRAJ_LENGTH_REFERENCE, + self.EGO_TRAJ_SCALE_MIN, + self.EGO_TRAJ_SCALE_MAX, + ) + ) + self._ego_frustum_scale_base = self.FRUSTUM_SCALE * traj_scale + self._ego_axis_length_base = self.EGO_AXIS_LENGTH * traj_scale + self._ego_axis_radius_base = self.EGO_AXIS_RADIUS * traj_scale + + # ─── Private: IK Robot ──────────────────────────────────────────────────── + + @classmethod + def _robot_frame_dims(cls, frame_key: str) -> tuple[float, float]: + """Return axis length/radius for one robot debug frame.""" + if frame_key.startswith("site:"): + return cls.ROBOT_SITE_AXIS_LENGTH, cls.ROBOT_SITE_AXIS_RADIUS + return cls.ROBOT_BODY_AXIS_LENGTH, cls.ROBOT_BODY_AXIS_RADIUS + + @staticmethod + def _clear_robot_frame_handles(handles: dict[str, Any]) -> None: + """Remove all robot debug frame handles in one arm.""" + for handle in handles.values(): + handle.remove() + handles.clear() + + def _robot_frame_selector_key(self, arm: str, frame_key: str) -> str: + """Return the GUI selector key for one robot debug frame.""" + if self._robot_frames_left is None and arm == "right": + return frame_key + return f"{arm}/{frame_key}" + + def get_robot_frame_selectors(self) -> list[tuple[str, str]]: + """Return selector keys and checkbox labels for available robot frames.""" + selectors = [] + for arm, frames in [("right", self._robot_frames_right), ("left", self._robot_frames_left)]: + if frames is None: + continue + for frame_key in sorted(frames): + selector_key = self._robot_frame_selector_key(arm, frame_key) + if self._robot_frames_left is None and arm == "right": + label = frame_key + else: + label = selector_key + selectors.append((selector_key, label)) + return selectors + + def _rebuild_robot_frame_handles( + self, + arm: str, + frames: dict[str, list[tuple[np.ndarray, np.ndarray]]] | None, + ) -> None: + """Recreate robot debug frame handles for one arm.""" + handles = self._robot_frame_handles_right if arm == "right" else self._robot_frame_handles_left + self._clear_robot_frame_handles(handles) + if frames is None: + return + for frame_key in sorted(frames): + kind, name = frame_key.split(":", 1) + axes_length, axes_radius = self._robot_frame_dims(frame_key) + handles[frame_key] = self.server.scene.add_frame( + self._p(f"/robot_{arm}_frames/{kind}/{name}"), + axes_length=axes_length * self._axis_scale, + axes_radius=axes_radius * self._axis_scale, + ) + log.info(f"Loaded {len(handles)} robot debug frames for {arm} arm") + + def _update_robot_debug_frames(self, t: int, show: dict) -> None: + """Update body/site coordinate frame overlays for both arms.""" + filters = show.get("robot_frame_filters", {}) + for arm, handles, frames in [ + ("right", self._robot_frame_handles_right, self._robot_frames_right), + ("left", self._robot_frame_handles_left, self._robot_frames_left), + ]: + for frame_key, handle in handles.items(): + poses = frames.get(frame_key) if frames is not None else None + selector_key = self._robot_frame_selector_key(arm, frame_key) + frame_enabled = bool(filters.get(selector_key, False)) + if poses is not None and t < len(poses) and frame_enabled: + pos, rot = poses[t] + handle.position = pos + handle.wxyz = self.vtf.SO3.from_matrix(rot).wxyz + handle.visible = True + else: + handle.visible = False + + def _load_robot_and_ik(self, state: SceneState, entry: Any): + """Load robot meshes and solve IK for the episode.""" + # Determine robot config key (single vs dual) + is_dual = state.mask.left_wrist and entry.dual_base_left is not None + robot_key = (entry.robot_name, "dual") if is_dual else entry.robot_name + + if self._robot_scene_model is None or self._robot_scene_model.robot_name != entry.robot_name: + try: + self._robot_scene_model = RobotSceneModel(entry.robot_name) + except Exception as e: + log.warning(f"RobotSceneModel unavailable for {entry.robot_name}: {e}") + self._robot_scene_model = None + return + + # Only reload meshes if robot changed + if self._current_robot != robot_key: + for h in self.robot_right + self.robot_left: + h.remove() + self.robot_right = [] + self.robot_left = [] + self._clear_robot_frame_handles(self._robot_frame_handles_right) + self._clear_robot_frame_handles(self._robot_frame_handles_left) + + if self._robot_scene_model is None: + self._current_robot = robot_key + return + + right_meshes = self._robot_scene_model.get_home_meshes(entry.dual_base_right if is_dual else None) + for name, mesh, transform in right_meshes: + h = self.server.scene.add_mesh_trimesh( + self._p(f"/robot_right/{name}"), + mesh=mesh, + ) + h.position = transform[:3, 3] + h.wxyz = self.vtf.SO3.from_matrix(transform[:3, :3]).wxyz + self.robot_right.append(h) + + if is_dual: + left_meshes = self._robot_scene_model.get_home_meshes(entry.dual_base_left) + for name, mesh, transform in left_meshes: + h = self.server.scene.add_mesh_trimesh( + self._p(f"/robot_left/{name}"), + mesh=mesh, + ) + h.position = transform[:3, 3] + h.wxyz = self.vtf.SO3.from_matrix(transform[:3, :3]).wxyz + self.robot_left.append(h) + + self._current_robot = robot_key + log.info(f"Loaded {len(right_meshes)} meshes for {entry.robot_name}") + + if self._robot_scene_model is None: + return + + # Right arm IK + if state.right_poses is not None: + try: + right_result = self._robot_scene_model.solve_visual_trajectory( + state.right_poses, + gripper_openings=state.gripper_right, + to_opencv=self._to_opencv, + base_pose=entry.dual_base_right if is_dual else None, + ) + if right_result is not None: + self._ik_right = right_result.mesh_transforms + self._robot_frames_right = right_result.named_frames + self._rebuild_robot_frame_handles("right", self._robot_frames_right) + else: + self._ik_right = None + self._robot_frames_right = None + self._rebuild_robot_frame_handles("right", None) + except Exception as e: + log.warning(f"IK failed (right): {e}") + self._ik_right = None + self._robot_frames_right = None + self._rebuild_robot_frame_handles("right", None) + else: + self._ik_right = None + self._robot_frames_right = None + self._rebuild_robot_frame_handles("right", None) + + # Left arm IK (dual only) + if is_dual and state.left_poses is not None: + try: + left_result = self._robot_scene_model.solve_visual_trajectory( + state.left_poses, + gripper_openings=state.gripper_left, + to_opencv=self._to_opencv, + base_pose=entry.dual_base_left, + ) + if left_result is not None: + self._ik_left = left_result.mesh_transforms + self._robot_frames_left = left_result.named_frames + self._rebuild_robot_frame_handles("left", self._robot_frames_left) + else: + self._ik_left = None + self._robot_frames_left = None + self._rebuild_robot_frame_handles("left", None) + except Exception as e: + log.warning(f"IK failed (left): {e}") + self._ik_left = None + self._robot_frames_left = None + self._rebuild_robot_frame_handles("left", None) + else: + self._ik_left = None + self._robot_frames_left = None + self._rebuild_robot_frame_handles("left", None) + + def _update_robot(self, t: int, show: dict): + vis = show.get("robot", True) + for handles, ik in [(self.robot_right, self._ik_right), (self.robot_left, self._ik_left)]: + for idx, h in enumerate(handles): + if vis and ik is not None and t < len(ik) and idx < len(ik[t]): + p, m = ik[t][idx] + h.position = p + h.wxyz = self.vtf.SO3.from_matrix(m).wxyz + h.visible = True + else: + h.visible = False + self._update_robot_debug_frames(t, show) + + # ─── Visibility ─────────────────────────────────────────────────────────── + + def hide_all(self): + """Hide every scene element.""" + for attr in [ + self.ego_frame, + self.ego_frustum, + self.ego_frustum_up, + self.ego_traj, + self.right_frame, + self.right_ee, + self.right_traj, + self.left_frame, + self.left_ee, + self.left_traj, + ]: + attr.visible = False + for h in self.right_gripper_tips + self.left_gripper_tips: + h.visible = False + for h in self.robot_right + self.robot_left: + h.visible = False + for handle in list(self._robot_frame_handles_right.values()) + list(self._robot_frame_handles_left.values()): + handle.visible = False + + def update_axis_scale(self, scale: float): + """Update coordinate frame axis size and effector point size.""" + self._axis_scale = scale + s = scale + self.ego_frame.axes_length = self._ego_axis_length_base * s + self.ego_frame.axes_radius = self._ego_axis_radius_base * s + self.ego_frustum.scale = self._ego_frustum_scale_base * s + self.ego_frustum_up.scale = self._ego_frustum_scale_base * s + for frame in (self.right_frame, self.left_frame): + frame.axes_length = self.HAND_AXIS_LENGTH * s + frame.axes_radius = self.HAND_AXIS_RADIUS * s + for ee in (self.right_ee, self.left_ee): + ee.point_size = 0.015 * s + for handles in (self._robot_frame_handles_right, self._robot_frame_handles_left): + for frame_key, handle in handles.items(): + axes_length, axes_radius = self._robot_frame_dims(frame_key) + handle.axes_length = axes_length * s + handle.axes_radius = axes_radius * s diff --git a/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/urdf_loader.py b/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/urdf_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..60aa7e222359772d08932b6b20687c128240b016 --- /dev/null +++ b/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/urdf_loader.py @@ -0,0 +1,780 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: OpenMDW-1.1 + +"""Robot mesh loading from mujoco_menagerie. + +Downloads robot MJCF/URDF/mesh assets on first use, caches in ~/.cache/mujoco_menagerie/. +Each loader returns (meshes, ee_home_pose) where: + - meshes: list of (name, trimesh.Trimesh, 4x4_transform) + - ee_home_pose: (4, 4) float32 — EE pose at home configuration +""" + +from __future__ import annotations + +import os +import xml.etree.ElementTree as ET +from dataclasses import dataclass +from functools import lru_cache +from pathlib import Path +from typing import Any + +import numpy as np +from scipy.spatial.transform import Rotation as R + +from cosmos_framework.utils import log + +_MENAGERIE_REPO = "https://github.com/google-deepmind/mujoco_menagerie" +_ROBOT_CACHE_DIR = Path("/tmp") / "mujoco_menagerie" +_FALLBACK_MESH_COLORS = np.asarray( + [ + [52, 152, 219, 255], + [243, 156, 18, 255], + [155, 89, 182, 255], + [46, 204, 113, 255], + [231, 76, 60, 255], + [26, 188, 156, 255], + [241, 196, 15, 255], + [52, 73, 94, 255], + [127, 140, 141, 255], + [211, 84, 0, 255], + [39, 174, 96, 255], + [41, 128, 185, 255], + ], + dtype=np.uint8, +) +_UNSPECIFIED_RGBA_VALUES = ( + np.asarray([0.5, 0.5, 0.5, 1.0], dtype=np.float32), + np.asarray([1.0, 1.0, 1.0, 1.0], dtype=np.float32), + # Some autogenerated URDF/MJCF assets use pink as a placeholder/default + # material. Treat it as unspecified so meshes do not all render pink. + np.asarray([1.0, 0.5, 1.0, 1.0], dtype=np.float32), +) +_UNSPECIFIED_MATERIAL_NAMES = {"", "default", "default_material"} + + +def _fallback_mesh_color(name: str, index: int = 0) -> np.ndarray: + """Return a stable fallback RGBA color for a mesh without material color.""" + + key = name or f"mesh_{index}" + palette_index = sum((char_idx + 1) * ord(char) for char_idx, char in enumerate(key)) + return _FALLBACK_MESH_COLORS[(palette_index + index) % len(_FALLBACK_MESH_COLORS)].copy() + + +def _is_unspecified_rgba(rgba: np.ndarray) -> bool: + """Return whether RGBA is an uninformative default color.""" + + return any(np.allclose(rgba, default_rgba, atol=1e-4) for default_rgba in _UNSPECIFIED_RGBA_VALUES) + + +def _apply_mesh_color(mesh: Any, rgba: np.ndarray) -> None: + """Apply one RGBA color to all mesh faces for viser/trimesh rendering.""" + + face_count = int(len(getattr(mesh, "faces", []))) + if face_count > 0: + mesh.visual.face_colors = np.tile(np.asarray(rgba, dtype=np.uint8), (face_count, 1)) + + +# ── Robot-specific configuration ────────────────────────────────────────────── + +# EE frame name candidates (tried in order by IK solver) +# --------------------------------------------------------------------------- +# End-effector frame references per dataset +# --------------------------------------------------------------------------- +# Each dataset records EE poses at a specific URDF link. The IK solver must +# target the same frame (via ``ee_frame`` or the ``_EE_FRAME_CANDIDATES`` +# fallback list). Below we document, for every robot: +# (a) which link the dataset records at, with upstream source reference, +# (b) what that link physically represents (flange, gripper body, or TCP), +# (c) any orientation transforms applied during recording. +# +# ── Google Robot (fractal / RT-1) ────────────────────────────────────────── +# Recorded link: ``link_gripper_tcp`` +# The TFDS observation field is ``base_pose_tool_reached`` (shape (7,)). +# Source: https://www.tensorflow.org/datasets/catalog/fractal20220817_data +# Meaning: TCP — a calibrated tool-center-point 164 mm past the wrist +# (``link_gripper``), roughly at the fingertip. The name contains "tool" +# and SimplerEnv's real→sim calibration targets the same link: +# ``self.ee_link_name = "link_gripper_tcp"`` +# Source: https://github.com/simpler-env/ManiSkill2_real2sim/blob/ef7a4d4/mani_skill2_real2sim/agents/configs/google_robot/defaults.py#L141 +# Orientation: recorded as-is from the URDF FK (quaternion). No extra +# rotation applied. +# Re-referenced to: ``link_gripper`` (gripper body / last actuated link) +# via ``_TCP_TO_FLANGE`` in the dataset class (−164 mm along local z). +# See ``fractal.py`` for the full transform and rationale. +# Our config: ``"ee_frame": "link_gripper"`` (explicit). +# Important MJCF note: MuJoCo Menagerie places ``base_link`` at +# ``pos="0 0 0.06205"`` under ``worldbody``. Pinocchio's +# ``buildModelFromMJCF()`` omits this global root transform, so IK / dataset +# poses live in a root-free world that is 62.05 mm lower than raw MuJoCo +# body/site poses. We therefore strip the same root transform from MuJoCo +# mesh/body/site outputs before rendering or comparing them. +# +# ── WidowX (bridge) ─────────────────────────────────────────────────────── +# Recorded link: ``ee_gripper_link`` +# The bridge data collection uses the Interbotix SDK's Modern Robotics FK +# (``FKinSpace(M, Slist, q)``). The M matrix for wx250s terminates at +# ``ee_gripper_link`` — confirmed by the Interbotix source comment and +# numerically: ``wx250s.M[0,3] = 0.458325`` matches ``ee_gripper_link`` +# position exactly (vs ``gripper_link`` at 0.3648). +# Source: https://github.com/Interbotix/interbotix_ros_toolboxes/blob/main/interbotix_xs_toolbox/interbotix_xs_modules/src/interbotix_xs_modules/mr_descriptions.py +# Line 1: "Note that the end-effector is positioned at '/ee_gripper_link'" +# SimplerEnv confirms: ``self.ee_link_name = "ee_gripper_link"`` +# Source: https://github.com/simpler-env/ManiSkill2_real2sim/blob/ef7a4d4/mani_skill2_real2sim/agents/configs/widowx/defaults.py#L87 +# Meaning: Interbotix-defined "end-effector" reference point, 93.6 mm past +# the wrist (``gripper_link``), 27.6 mm past the finger pivot +# (``fingers_link``). This is roughly the grasp center between the +# finger pads — *not* the fingertip. +# Orientation: the bridge data collection applies ``DEFAULT_ROTATION`` to +# the FK orientation before recording (in ``transform2state``): +# ``euler = rotationMatrixToEulerAngles(rot.dot(default_rotation.T))`` +# where ``DEFAULT_ROTATION = [[0,0,1],[0,1,0],[-1,0,0]]``. +# Source: https://github.com/rail-berkeley/bridge_data_robot/blob/main/widowx_envs/widowx_controller/src/widowx_controller/widowx_controller.py#L44 +# Re-referenced to: ``gripper_link`` (wrist rotate body / last actuated link) +# via ``_TCP_TO_FLANGE`` in the dataset class (−93.6 mm along local x). +# See ``bridge_orig_lerobot_dataset.py`` for the full transform and rationale. +# Our config: ``"ee_frame": "wx250s/gripper_link"`` (explicit). +# +# ── Franka + Robotiq 2F-85 (DROID) ──────────────────────────────────────── +# Recorded link: ``panda_link8`` (= Franka flange) +# DROID's ``get_robot_state()`` calls Polymetis FK: +# ``pos, quat = self._robot.robot_model.forward_kinematics(joint_positions)`` +# Source: https://github.com/droid-dataset/droid/blob/main/droid/franka/robot.py +# Polymetis is configured with ``ee_link_name: panda_link8``: +# Source: https://github.com/facebookresearch/fairo/blob/main/polymetis/polymetis/conf/robot_model/franka_panda.yaml +# Meaning: flange — the bare mounting plate at the end of the Franka arm, +# *before* the Robotiq gripper. +# MJCF body: ``panda_hand`` in the composite model (pos 0 0 0.107 +# above ``link7``, identity quat). This is at the panda_link8 +# (flange) position with link7 orientation, matching the URDF. +# ``link7`` is panda_link7 (wrist), *not* the flange. +# Orientation: Polymetis reports FK orientation at ``panda_link8`` frame +# as-is. No extra rotation applied. +# Current viewer convention: all Franka-backed datasets reuse this DROID +# composite model, so ``franka_panda`` is the only supported Franka robot +# config in this module. +# Our config: ``"ee_frame": "panda_hand"`` (explicit). +# --------------------------------------------------------------------------- + +_EE_FRAME_CANDIDATES = [ + "link_gripper_tcp", # SimplerEnv Google Robot (calibrated TCP at fingertip) + "link_gripper", # Google Robot (Menagerie / fallback) + "ee_gripper_link", # SimplerEnv WidowX (end of finger chain) + "gripper_link", # WidowX (MuJoCo body name) + "wx250s/gripper_link", # WidowX Menagerie (prefixed body name) + "gripper", # Google Robot (Menagerie site) + "hand", # Franka Panda (standard gripper) + "attachment", # Franka + Robotiq + "wx250s/gripper_link", # WidowX 250S (Menagerie) + "ee_link", # generic + "tool0", # generic industrial +] + +# Robot-specific configs: menagerie name, MJCF filename, joint info, finger range. +ROBOT_CONFIGS = { + "google_robot": { + "menagerie": "google_robot", + "mjcf": "robot.xml", + # EE: link_gripper (gripper body / last actuated link). + # The Menagerie model has link_gripper directly (no TCP frame). + # The dataset applies _TCP_TO_FLANGE to shift from the recorded + # link_gripper_tcp to link_gripper, so poses already target this frame. + # MuJoCo Menagerie also adds a global worldbody -> base_link offset + # (+62.05 mm in z). Pinocchio's MJCF importer omits that root transform, + # so the viewer removes it from MuJoCo outputs to keep meshes / body + # frames aligned with dataset poses and IK outputs. + "ee_frame": "link_gripper", + "pinocchio_removed_root_body": "base_link", + "arm_joints": [ + "joint_torso", + "joint_shoulder", + "joint_bicep", + "joint_elbow", + "joint_forearm", + "joint_wrist", + "joint_gripper", + ], + "n_arm_joints": 7, + "finger_joint_names": ["joint_finger_left", "joint_finger_right"], + "finger_min": 0.01, + "finger_max": 1.30, + "finger_close_is_max": True, + "camera_body": None, + }, + "franka_panda": { + "menagerie": "droid_franka_robotiq", + "mjcf": "panda_updated_robotiq_2f85.xml", + # EE: panda_link8 (flange) — the bare mounting plate, *not* the + # gripper TCP. MJCF body: ``panda_hand`` in the composite model + # (pos 0 0 0.107 above link7, identity quat). + + "ee_frame": "panda_hand", + "arm_joints": [ + "joint1", + "joint2", + "joint3", + "joint4", + "joint5", + "joint6", + "joint7", + ], + "n_arm_joints": 7, + "finger_min": 0.0, + "finger_max": 0.8, + "finger_close_is_max": True, + # All Robotiq 2F-85 chain joints (some share names with bodies in + # pinocchio MJCF parse — must keep all to avoid buildReducedModel error) + "finger_joint_names": [ + "right_driver_joint", + "left_driver_joint", + "left_spring_link_joint", + "left_follower", + "right_spring_link_joint", + "right_follower_joint", + ], + "camera_body": None, + }, + "widowx": { + "menagerie": "trossen_wx250s", + "mjcf": "wx250s.xml", + # EE: gripper_link (wrist rotate body / last actuated link). + # The Menagerie model has gripper_link directly. + # The dataset applies _TCP_TO_FLANGE to shift from the recorded + # ee_gripper_link to gripper_link, so poses already target this frame. + "ee_frame": "wx250s/gripper_link", + "arm_joints": [ + "waist", + "shoulder", + "elbow", + "forearm_roll", + "wrist_angle", + "wrist_rotate", + ], + "n_arm_joints": 6, + "finger_min": 0.015, + "finger_max": 0.037, + "finger_close_is_max": False, + "finger_joint_names": ["left_finger", "right_finger"], + "camera_body": None, + }, + +} + + +def get_urdf_path(robot_name: str) -> str | None: + """Get URDF path for a robot if available, else None (falls back to MJCF in caller).""" + cfg = ROBOT_CONFIGS.get(robot_name) + if cfg is None: + return None + + menagerie_name = cfg.get("menagerie") + if menagerie_name is None: + return None + mjcf_dir = _ensure_robot_assets(menagerie_name) + + urdf_filename = cfg.get("urdf") + if urdf_filename: + urdf_path = mjcf_dir / urdf_filename + if urdf_path.exists(): + return str(urdf_path) + + urdfs = list(mjcf_dir.glob("*.urdf")) + if urdfs: + return str(urdfs[0]) + + return None + + +def get_mjcf_path(robot_name: str) -> str: + """Get MJCF path for a robot, downloading from mujoco_menagerie if needed.""" + cfg = ROBOT_CONFIGS.get(robot_name) + if cfg is None: + raise ValueError(f"Unknown robot: {robot_name}. Available: {list(ROBOT_CONFIGS.keys())}") + + menagerie_name = cfg.get("menagerie") + if menagerie_name is None: + raise FileNotFoundError(f"Robot {robot_name!r} does not have a MuJoCo MJCF asset.") + mjcf_filename = cfg.get("mjcf", "robot.xml") + + mjcf_dir = _ensure_robot_assets(menagerie_name) + mjcf_path = mjcf_dir / mjcf_filename + if mjcf_path.exists(): + return str(mjcf_path) + + fallback = mjcf_dir / "robot.xml" + if fallback.exists(): + return str(fallback) + + raise FileNotFoundError(f"MJCF not found: {mjcf_path} (also tried robot.xml)") + + +# ── Asset download ─────────────────────────────────────────────────────────── + + +def _ensure_robot_assets(robot_name: str) -> Path: + """Ensure robot MJCF and mesh assets are available locally. + + Downloads from mujoco_menagerie GitHub repo if not found. + For composite robots (``droid_franka_robotiq``), downloads from both + MuJoCo Menagerie and MuJoCo Playground and merges assets. + + Assets are cached in ~/.cache/mujoco_menagerie//. + + Returns: + Path to the cached MJCF directory (caller picks the right .xml). + """ + cached_dir = _ROBOT_CACHE_DIR / robot_name + if cached_dir.exists(): + return cached_dir + + # Composite: Franka arm + Robotiq 2F-85 gripper (DROID setup) + if robot_name == "droid_franka_robotiq": + return _build_droid_franka_robotiq() + + log.info(f"Downloading {robot_name} assets from mujoco_menagerie...") + _download_menagerie_model(robot_name) + return cached_dir + + +def _download_menagerie_model(model_name: str) -> Path: + """Download a single model from MuJoCo Menagerie. Returns cached path.""" + cached_dir = _ROBOT_CACHE_DIR / model_name + if cached_dir.exists(): + return cached_dir + + import shutil + import subprocess + import tempfile + + _ROBOT_CACHE_DIR.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory() as tmpdir: + subprocess.run( + ["git", "clone", "--depth=1", "--filter=blob:none", "--sparse", _MENAGERIE_REPO, tmpdir], + check=True, + capture_output=True, + ) + subprocess.run( + ["git", "sparse-checkout", "set", model_name], + cwd=tmpdir, + check=True, + capture_output=True, + ) + src = Path(tmpdir) / model_name + dst = _ROBOT_CACHE_DIR / model_name + if dst.exists(): + shutil.rmtree(dst) + shutil.copytree(src, dst) + + log.info(f"Cached {model_name} assets at {dst}") + return dst + + +def _build_droid_franka_robotiq() -> Path: + """Prepare composite Franka + Robotiq 2F-85 MJCF for DROID visualization. + + The hand-tuned composite XML is committed in the repo alongside this + module (``droid_franka_robotiq_2f85.xml``). This function downloads the + mesh assets from MuJoCo Menagerie (``franka_emika_panda`` + + ``robotiq_2f85_v4``) and copies them together with the XML into a cache + directory that MuJoCo can load from. + """ + import shutil + + log.info("Preparing composite Franka + Robotiq 2F-85 (committed XML + Menagerie assets)...") + + franka_dir = _download_menagerie_model("franka_emika_panda") + robotiq_dir = _download_menagerie_model("robotiq_2f85_v4") + + dst = _ROBOT_CACHE_DIR / "droid_franka_robotiq" + dst.mkdir(parents=True, exist_ok=True) + assets_dir = dst / "assets" + assets_dir.mkdir(exist_ok=True) + + for f in (franka_dir / "assets").iterdir(): + shutil.copy2(f, assets_dir / f.name) + for f in (robotiq_dir / "assets").iterdir(): + shutil.copy2(f, assets_dir / f.name) + + committed_xml = Path(__file__).parent / "droid_franka_robotiq_2f85.xml" + out_path = dst / "panda_updated_robotiq_2f85.xml" + shutil.copy2(committed_xml, out_path) + + log.info(f"Prepared composite Franka + Robotiq 2F-85 at {dst}") + return dst + + + +# ── Robot loaders ──────────────────────────────────────────────────────────── + + +def _load_google_robot() -> tuple[list, np.ndarray]: + """Load Google Robot from MuJoCo Menagerie. + + Uses the official google_robot model from + https://github.com/google-deepmind/mujoco_menagerie/tree/main/google_robot + which has visual OBJ meshes for accurate rendering. + """ + import mujoco + + cfg = ROBOT_CONFIGS["google_robot"] + mjcf_dir = _ensure_robot_assets(cfg["menagerie"]) + mjcf_path = mjcf_dir / cfg["mjcf"] + model = mujoco.MjModel.from_xml_path(str(mjcf_path)) + data = mujoco.MjData(model) + mujoco.mj_forward(model, data) + + meshes = _extract_mujoco_meshes(model, data) + world_correction = get_mujoco_to_pinocchio_world_transform(model, data, "google_robot") + if not np.allclose(world_correction, np.eye(4, dtype=np.float32)): + meshes = _apply_world_transform_to_meshes(meshes, world_correction) + + # Find EE pose at link_gripper + ee_pose = np.eye(4, dtype=np.float32) + for i in range(model.nbody): + name = mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_BODY, i) or "" + if name == "link_gripper": + ee_pose[:3, 3] = data.xpos[i].astype(np.float32) + ee_pose[:3, :3] = data.xmat[i].reshape(3, 3).astype(np.float32) + break + ee_pose = (world_correction @ ee_pose).astype(np.float32) + + log.info(f"Google Robot (Menagerie) loaded: {len(meshes)} meshes, EE pos={ee_pose[:3, 3]}") + return meshes, ee_pose + + +def _load_franka_panda() -> tuple[list, np.ndarray]: + """Load Franka Panda + Robotiq 2F-85 gripper (DROID variant). + + Uses the composite model built from MuJoCo Menagerie + (``franka_emika_panda`` arm + ``robotiq_2f85_v4`` gripper). + """ + import mujoco + + mjcf_dir = _ensure_robot_assets("droid_franka_robotiq") + mjcf_path = mjcf_dir / "panda_updated_robotiq_2f85.xml" + model = mujoco.MjModel.from_xml_path(str(mjcf_path)) + data = mujoco.MjData(model) + + # Franka home configuration + home_qpos = np.array([0.0, -0.78, 0.0, -2.36, 0.0, 1.57, 0.78]) + data.qpos[: len(home_qpos)] = home_qpos + mujoco.mj_forward(model, data) + + meshes = _extract_mujoco_meshes(model, data) + + # EE pose: use the "gripper" site (on the Robotiq base), or fall + # back to "base_mount" / "attachment" body if site isn't found. + ee_pose = np.eye(4, dtype=np.float32) + for si in range(model.nsite): + name = mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_SITE, si) or "" + if name == "gripper": + ee_pose[:3, 3] = data.site_xpos[si].astype(np.float32) + ee_pose[:3, :3] = data.site_xmat[si].reshape(3, 3).astype(np.float32) + break + else: + # Fallback to body search + for i in range(model.nbody): + name = mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_BODY, i) or "" + if name in ("base_mount", "attachment"): + ee_pose[:3, 3] = data.xpos[i].astype(np.float32) + ee_pose[:3, :3] = data.xmat[i].reshape(3, 3).astype(np.float32) + break + + log.info(f"Franka Panda + Robotiq loaded: {len(meshes)} meshes, EE pos={ee_pose[:3, 3]}") + return meshes, ee_pose + + +def _load_widowx() -> tuple[list, np.ndarray]: + """Load WidowX 250S from MuJoCo Menagerie (trossen_wx250s). + + Uses the official Trossen Robotics WX250S model from + https://github.com/google-deepmind/mujoco_menagerie/tree/main/trossen_wx250s + which has visual OBJ meshes for accurate rendering. + """ + import mujoco + + cfg = ROBOT_CONFIGS["widowx"] + mjcf_dir = _ensure_robot_assets(cfg["menagerie"]) + mjcf_path = mjcf_dir / cfg["mjcf"] + model = mujoco.MjModel.from_xml_path(str(mjcf_path)) + data = mujoco.MjData(model) + mujoco.mj_forward(model, data) + + meshes = _extract_mujoco_meshes(model, data) + + ee_pose = np.eye(4, dtype=np.float32) + for i in range(model.nbody): + name = mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_BODY, i) or "" + if name == "gripper_link": + ee_pose[:3, 3] = data.xpos[i].astype(np.float32) + ee_pose[:3, :3] = data.xmat[i].reshape(3, 3).astype(np.float32) + break + + log.info(f"WidowX 250S (Menagerie) loaded: {len(meshes)} meshes, EE pos={ee_pose[:3, 3]}") + return meshes, ee_pose + + +def _parse_urdf_origin(origin_element) -> np.ndarray: + transform = np.eye(4, dtype=np.float32) + if origin_element is None: + return transform + + xyz_text = origin_element.attrib.get("xyz", "0 0 0") + rpy_text = origin_element.attrib.get("rpy", "0 0 0") + xyz = np.asarray([float(value) for value in xyz_text.split()], dtype=np.float32) + rpy = np.asarray([float(value) for value in rpy_text.split()], dtype=np.float32) + transform[:3, :3] = R.from_euler("xyz", rpy).as_matrix().astype(np.float32) + transform[:3, 3] = xyz + return transform + + +def _parse_urdf_color(color_element: ET.Element | None) -> np.ndarray | None: + if color_element is None: + return None + rgba_text = color_element.attrib.get("rgba") + if not rgba_text: + return None + rgba = np.asarray([float(value) for value in rgba_text.split()], dtype=np.float32) + if rgba.shape != (4,): + return None + return (np.clip(rgba, 0.0, 1.0) * 255.0).astype(np.uint8) + + +def _parse_urdf_material_colors(root: ET.Element) -> dict[str, np.ndarray]: + material_colors: dict[str, np.ndarray] = {} + for material_element in root.findall("material"): + material_name = material_element.attrib.get("name", "") + color = _parse_urdf_color(material_element.find("color")) + if material_name and color is not None: + material_colors[material_name] = color + return material_colors + + +def _resolve_urdf_visual_color(parent_element: ET.Element, material_colors: dict[str, np.ndarray]) -> np.ndarray | None: + material_element = parent_element.find("material") + if material_element is None: + return None + + material_name = material_element.attrib.get("name", "") + color = _parse_urdf_color(material_element.find("color")) + if color is None and material_name: + color = material_colors.get(material_name) + if color is None: + return None + + color_unit = color.astype(np.float32) / 255.0 + if material_name.lower() in _UNSPECIFIED_MATERIAL_NAMES or _is_unspecified_rgba(color_unit): + return None + return color + + +# ── Helpers ────────────────────────────────────────────────────────────────── + + +def _get_visual_geom_ids(model) -> list[int]: + """Get visual geom IDs from a MuJoCo model. + + Strategy: + 1. Google Robot uses *_v suffix for visual meshes → use those + 2. Other robots (Franka, WidowX) use geom_group=2 for visual → use those + 3. Fallback: all mesh geoms + + Includes both mesh geoms and primitive geoms (box, cylinder, sphere) in group 2. + """ + import mujoco + + VISUAL_TYPES = { + mujoco.mjtGeom.mjGEOM_MESH, + mujoco.mjtGeom.mjGEOM_BOX, + mujoco.mjtGeom.mjGEOM_CYLINDER, + mujoco.mjtGeom.mjGEOM_SPHERE, + mujoco.mjtGeom.mjGEOM_CAPSULE, + mujoco.mjtGeom.mjGEOM_ELLIPSOID, + } + + v_ids = [] + group2_ids = [] + all_ids = [] + for gi in range(model.ngeom): + gtype = model.geom_type[gi] + if gtype not in VISUAL_TYPES: + continue + all_ids.append(gi) + if gtype == mujoco.mjtGeom.mjGEOM_MESH: + mesh_id = model.geom_dataid[gi] + mesh_name = mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_MESH, mesh_id) or "" + if mesh_name.endswith("_v"): + v_ids.append(gi) + if model.geom_group[gi] == 2: + group2_ids.append(gi) + + # Priority: _v suffix > group 2 > all + if v_ids: + return v_ids + if group2_ids: + return group2_ids + return all_ids + + +def _resolve_geom_color(model, gi: int, geom_name: str) -> np.ndarray: + """Resolve the effective RGBA color for a MuJoCo geom. + + Priority: + 1. If geom has a material with a diffuse texture → sample average texture color + 2. If geom has a material with non-default rgba → use mat_rgba + 3. If geom_rgba is non-default → use geom_rgba + 4. Fallback: deterministic per-geom color + + Returns (4,) uint8 RGBA. + """ + + rgba = model.geom_rgba[gi].copy() # (4,) float [0,1] + mat_id = model.geom_matid[gi] + + if mat_id >= 0: + # Check if material has a diffuse texture + tex_id = model.mat_texid[mat_id][1] # index 1 = diffuse texture + if tex_id >= 0: + # Sample average color from the texture + tex_adr = model.tex_adr[tex_id] + tex_w = model.tex_width[tex_id] + tex_h = model.tex_height[tex_id] + n_pixels = tex_w * tex_h + tex_data = model.tex_data[tex_adr : tex_adr + n_pixels * 3].reshape(n_pixels, 3) + avg_rgb = tex_data.mean(axis=0) / 255.0 + # Multiply by mat_rgba (which acts as a tint) + mat_rgba = model.mat_rgba[mat_id] + final = np.array( + [ + avg_rgb[0] * mat_rgba[0], + avg_rgb[1] * mat_rgba[1], + avg_rgb[2] * mat_rgba[2], + mat_rgba[3], + ] + ) + return (np.clip(final, 0, 1) * 255).astype(np.uint8) + + # No texture — use material rgba if it is informative. + mat_rgba = model.mat_rgba[mat_id].copy() + if not _is_unspecified_rgba(mat_rgba): + return (np.clip(mat_rgba, 0, 1) * 255).astype(np.uint8) + + if not _is_unspecified_rgba(rgba): + return (np.clip(rgba, 0, 1) * 255).astype(np.uint8) + + return _fallback_mesh_color(geom_name, gi) + + +def _extract_mujoco_meshes(model, data) -> list: + """Extract visual geom meshes from a MuJoCo model as trimesh objects. + + Uses the same visual geom filtering as ``ik_solver._get_visual_geom_ids`` + to ensure mesh ordering matches IK transform output. + + For geoms with primitive types (box, cylinder, etc.), generates the + corresponding trimesh primitive. + + Applies per-geom RGBA color from MuJoCo materials when available. + + Returns list of (geom_name, trimesh.Trimesh, 4x4_transform). + """ + import mujoco + import trimesh + + # Use the same visual filter as IK solver + visual_geom_ids = _get_visual_geom_ids(model) + + meshes = [] + for gi in visual_geom_ids: + gtype = model.geom_type[gi] + pos = data.geom_xpos[gi].copy() + rot = data.geom_xmat[gi].reshape(3, 3).copy() + + geom_name = mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_GEOM, gi) or f"geom_{gi}" + face_color = _resolve_geom_color(model, gi, geom_name) + + mesh = None + if gtype == mujoco.mjtGeom.mjGEOM_MESH: + mesh_id = model.geom_dataid[gi] + vert_start = model.mesh_vertadr[mesh_id] + vert_count = model.mesh_vertnum[mesh_id] + face_start = model.mesh_faceadr[mesh_id] + face_count = model.mesh_facenum[mesh_id] + verts = model.mesh_vert[vert_start : vert_start + vert_count].copy() + faces = model.mesh_face[face_start : face_start + face_count].copy() + mesh = trimesh.Trimesh(vertices=verts, faces=faces) + _apply_mesh_color(mesh, face_color) + elif gtype == mujoco.mjtGeom.mjGEOM_BOX: + size = model.geom_size[gi].copy() + mesh = trimesh.creation.box(extents=size * 2) + _apply_mesh_color(mesh, face_color) + elif gtype == mujoco.mjtGeom.mjGEOM_SPHERE: + mesh = trimesh.creation.icosphere(radius=model.geom_size[gi][0]) + _apply_mesh_color(mesh, face_color) + elif gtype == mujoco.mjtGeom.mjGEOM_CYLINDER: + mesh = trimesh.creation.cylinder(radius=model.geom_size[gi][0], height=model.geom_size[gi][1] * 2) + _apply_mesh_color(mesh, face_color) + elif gtype == mujoco.mjtGeom.mjGEOM_CAPSULE: + mesh = trimesh.creation.capsule(radius=model.geom_size[gi][0], height=model.geom_size[gi][1] * 2) + _apply_mesh_color(mesh, face_color) + + if mesh is not None: + transform = np.eye(4) + transform[:3, :3] = rot + transform[:3, 3] = pos + meshes.append((geom_name, mesh, transform)) + return meshes + + +def get_mujoco_to_pinocchio_world_transform(model, data, robot_name: str | None = None) -> np.ndarray: + """Return a correction that maps MuJoCo world poses into Pinocchio world. + + For some MJCFs, MuJoCo includes a fixed worldbody -> root-body transform + that Pinocchio's ``buildModelFromMJCF()`` omits. When that happens, the IK + solver and dataset poses live in a root-free world, while raw MuJoCo + body/site poses are globally shifted. This helper returns the inverse root + transform so callers can strip that offset from MuJoCo-derived meshes, + body frames, and sites before comparing them against Pinocchio / dataset + poses. + """ + import mujoco + + cfg = ROBOT_CONFIGS.get(robot_name, {}) if robot_name else {} + root_body_name = cfg.get("pinocchio_removed_root_body") + if not root_body_name: + return np.eye(4, dtype=np.float32) + + root_body_id = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_BODY, root_body_name) + if root_body_id < 0: + log.warning(f"Configured root body '{root_body_name}' not found in MuJoCo model") + return np.eye(4, dtype=np.float32) + + root_pose = np.eye(4, dtype=np.float32) + root_pose[:3, 3] = data.xpos[root_body_id].astype(np.float32) + root_pose[:3, :3] = data.xmat[root_body_id].reshape(3, 3).astype(np.float32) + return np.linalg.inv(root_pose).astype(np.float32) + + +def _apply_world_transform_to_meshes( + meshes: list[tuple[str, object, np.ndarray]], + world_transform: np.ndarray, +) -> list[tuple[str, object, np.ndarray]]: + """Left-multiply a world-space transform into each mesh pose.""" + transformed_meshes = [] + for name, mesh, transform in meshes: + transformed_meshes.append((name, mesh, (world_transform @ transform).astype(np.float32))) + return transformed_meshes + + +# ── Public API ─────────────────────────────────────────────────────────────── + + +def get_robot_loaders() -> dict[str, callable]: + """Get the robot loader registry. + + Maps robot_name → loader function that returns (meshes, ee_home_pose). + """ + return { + "google_robot": _load_google_robot, + "franka_panda": _load_franka_panda, + "widowx": _load_widowx, + } diff --git a/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/viewer.py b/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/viewer.py new file mode 100644 index 0000000000000000000000000000000000000000..c41ea250fde9e05e120fa68786edcdce75bca5f2 --- /dev/null +++ b/cosmos-framework/cosmos_framework/data/vfm/action/urdf_visualizer/viewer.py @@ -0,0 +1,863 @@ +#!/usr/bin/env python +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: OpenMDW-1.1 + +"""Interactive 3D viewer for robot action datasets. + +Uses raw release action layouts: 9D ego/camera, 10D single-arm, and 20D dual-arm. +Each sample is converted to a small internal render state before drawing. + +Dependencies:: + + pip install viser mujoco pin + +Usage: + # Use each dataset's declared raw action format: + uv run python cosmos_framework/data/vfm/action/urdf_visualizer/viewer.py --share + +""" + +from __future__ import annotations + +import argparse +import importlib +from functools import lru_cache +import os +import random +import sys +import time as _time +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, cast + +import numpy as np +import torch + +from cosmos_framework.utils import log +from cosmos_framework.data.vfm.action.urdf_visualizer.unified_action import ActionFormat + +_REPO_ROOT = str(Path(__file__).resolve().parents[6]) +if _REPO_ROOT not in sys.path: + sys.path.insert(0, _REPO_ROOT) + +# ── Dataset Registry ────────────────────────────────────────────────────────── + + +@dataclass +class DatasetEntry: + """Metadata for a dataset available in the viewer.""" + + name: str + robot_name: str + max_finger_width: float + fps: int + pose_convention: str = "backward_framewise" + camera_fov_deg: float = 60.0 + camera_aspect: float = 4 / 3 + dataset_class: str = "" + dataset_kwargs: dict[str, Any] = field(default_factory=dict) + action_format: ActionFormat = ActionFormat.SINGLE_ARM_10D + initial_index: int = 0 + dual_base_left: np.ndarray | None = None + dual_base_right: np.ndarray | None = None + robot_embodiment_type: str | None = None + to_unified_fn: str | None = None # "module.path:function" for custom action conversion + to_opencv: np.ndarray | dict[str, np.ndarray] | None = None # native EE → OpenCV rotation + + +def _lazycfg_to_entry( + cfg: Any, + *, + robot_name: str = "", + max_finger_width: float = 0.0, + fps: int = 10, + action_format: ActionFormat = ActionFormat.SINGLE_ARM_10D, + initial_index: int = 0, + camera_fov_deg: float = 60.0, + camera_aspect: float = 4 / 3, + dual_base_left: np.ndarray | None = None, + dual_base_right: np.ndarray | None = None, + robot_embodiment_type: str | None = None, + to_unified_fn: str | None = None, + to_opencv: np.ndarray | dict[str, np.ndarray] | None = None, + viewer_overrides: dict[str, Any] | None = None, +) -> DatasetEntry: + """Build a viewer dataset entry from a v1p2 ``LazyCall(dataset_entry)`` config.""" + + ds_cfg = cfg["dataset"] if isinstance(cfg, dict) else cfg.dataset + target = ds_cfg["_target_"] if isinstance(ds_cfg, dict) else ds_cfg._target_ + dataset_class = target if isinstance(target, str) else f"{target.__module__}.{target.__qualname__}" + ds_items = ds_cfg.items() if isinstance(ds_cfg, dict) else ds_cfg.items() + dataset_kwargs = {key: value for key, value in ds_items if key != "_target_"} + if viewer_overrides is not None: + dataset_kwargs.update(viewer_overrides) + + pose_convention = str(dataset_kwargs.get("pose_convention", "backward_framewise")) + cfg_dict = cfg if isinstance(cfg, dict) else dict(cfg) + dataset_name = str(cfg_dict.get("name", "unknown")) + return DatasetEntry( + name=dataset_name, + robot_name=robot_name, + max_finger_width=max_finger_width, + fps=fps, + pose_convention=pose_convention, + camera_fov_deg=camera_fov_deg, + camera_aspect=camera_aspect, + dataset_class=dataset_class, + dataset_kwargs=dataset_kwargs, + action_format=action_format, + initial_index=int(initial_index), + dual_base_left=dual_base_left, + dual_base_right=dual_base_right, + robot_embodiment_type=robot_embodiment_type, + to_unified_fn=to_unified_fn, + to_opencv=to_opencv, + ) + + +def _build_datasets() -> dict[str, DatasetEntry]: + """Build the viewer dataset registry from release-supported action data configs.""" + + from cosmos_framework.data.vfm.action.urdf_visualizer.action_datasets import ( + DATASET_AV_480, + DATASET_BRIDGE_480, + DATASET_DROID_480, + DATASET_FRACTAL_256, + DATASET_ROBOMIND_FRANKA_480, + DATASET_ROBOMIND_FRANKA_DUAL_480, + DATASET_UMI_256, + ) + + from cosmos_framework.data.vfm.action.bridge_orig_lerobot_dataset import _BRIDGE_TO_OPENCV + from cosmos_framework.data.vfm.action.droid_lerobot_dataset import _DROID_TO_OPENCV + from cosmos_framework.data.vfm.action.fractal import _GOOGLE_ROBOT_TO_OPENCV + from cosmos_framework.data.vfm.action.robomind_franka_dataset import _ROBOMIND_FRANKA_TO_OPENCV + + _FRANKA_TO_OPENCV = _ROBOMIND_FRANKA_TO_OPENCV[:3, :3] + + return { + "av": _lazycfg_to_entry( + DATASET_AV_480, + robot_name="", + max_finger_width=0.0, + fps=10, + action_format=ActionFormat.EGO_9D, + ), + "fractal": _lazycfg_to_entry( + DATASET_FRACTAL_256, + robot_name="google_robot", + max_finger_width=0.05, + fps=3, + action_format=ActionFormat.SINGLE_ARM_10D, + camera_fov_deg=69.0, + camera_aspect=320 / 256, + to_opencv=_GOOGLE_ROBOT_TO_OPENCV, + ), + "bridge": _lazycfg_to_entry( + DATASET_BRIDGE_480, + robot_name="widowx", + max_finger_width=0.06, + fps=5, + action_format=ActionFormat.SINGLE_ARM_10D, + to_opencv=_BRIDGE_TO_OPENCV, + ), + "droid": _lazycfg_to_entry( + DATASET_DROID_480, + robot_name="franka_panda", + max_finger_width=0.08, + fps=15, + action_format=ActionFormat.SINGLE_ARM_10D, + initial_index=45, + to_opencv=_DROID_TO_OPENCV, + ), + "umi": _lazycfg_to_entry( + DATASET_UMI_256, + robot_name="", + max_finger_width=0.08, + fps=20, + action_format=ActionFormat.SINGLE_ARM_10D, + ), + "robomind_franka": _lazycfg_to_entry( + DATASET_ROBOMIND_FRANKA_480, + robot_name="franka_panda", + max_finger_width=0.08, + fps=10, + action_format=ActionFormat.SINGLE_ARM_10D, + to_opencv=_FRANKA_TO_OPENCV, + ), + "robomind_franka_dual": _lazycfg_to_entry( + DATASET_ROBOMIND_FRANKA_DUAL_480, + robot_name="franka_panda", + max_finger_width=0.08, + fps=10, + action_format=ActionFormat.DUAL_ARM_20D, + dual_base_left=np.array( + [[1, 0, 0, 0.0], [0, 1, 0, 0.3], [0, 0, 1, 0.0], [0, 0, 0, 1.0]], + dtype=np.float32, + ), + dual_base_right=np.array( + [[1, 0, 0, 0.0], [0, 1, 0, -0.3], [0, 0, 1, 0.0], [0, 0, 0, 1.0]], + dtype=np.float32, + ), + to_opencv=_FRANKA_TO_OPENCV, + ), + } + + +DATASETS: dict[str, DatasetEntry] = {} + + +# ── Dataset Creation ────────────────────────────────────────────────────────── + + +def _create_dataset(entry: DatasetEntry, chunk_length: int): + """Instantiate a dataset class for the given entry.""" + import importlib + import inspect + + module_path, class_name = entry.dataset_class.rsplit(".", 1) + mod = importlib.import_module(module_path) + cls = getattr(mod, class_name) + + kwargs = dict(entry.dataset_kwargs) + kwargs["chunk_length"] = chunk_length + kwargs["split"] = "full" + kwargs["mode"] = "policy" + kwargs["enable_fast_init"] = True + + # UMI: factory function + if callable(cls) and not inspect.isclass(cls): + _OMEGACONF_BLOCKLIST = {"chunk_length", "split", "enable_fast_init"} + kwargs = {k: v for k, v in kwargs.items() if k not in _OMEGACONF_BLOCKLIST} + kwargs["eager_load"] = True + return cls(**kwargs) + + sig = inspect.signature(cls.__init__) + valid_params = set(sig.parameters.keys()) - {"self"} + has_var_keyword = any(p.kind == inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values()) + if not has_var_keyword: + kwargs = {k: v for k, v in kwargs.items() if k in valid_params} + + dataset = cls(**kwargs) + + if hasattr(dataset, "_register_sources"): + dataset._register_sources() + if hasattr(dataset, "__len__") and len(dataset) == 0: + raise RuntimeError(f"{entry.name}: registered sources but found no valid samples") + + from torch.utils.data import IterableDataset as _IterableBase + + if isinstance(dataset, _IterableBase): + dataset = _IterableToMapDataset(dataset) + + return dataset + + +def _resolve_action_format( + entry: DatasetEntry, + action_format_override: ActionFormat | None, +) -> ActionFormat: + """Return the explicit raw action format for one dataset load.""" + return action_format_override if action_format_override is not None else entry.action_format + + +@lru_cache(maxsize=None) +def _load_symbol(target: str): + """Import and cache one ``module:symbol`` reference.""" + + module_name, symbol_name = target.split(":", maxsplit=1) + module = importlib.import_module(module_name) + return getattr(module, symbol_name) + + +def _format_sample_text(value: Any, max_chars: int | None = None) -> str: + """Format optional sample text for the viewer info panel.""" + + if value is None: + return "" + text = value if isinstance(value, str) else str(value) + if not text: + return "" + if max_chars is None: + return text + return text[:max_chars] + + + +class _IterableToMapDataset: + """Wraps an IterableDataset into a random-access dataset with lazy loading.""" + + _MAX_CACHE = 200 + + def __init__(self, iterable_dataset, max_samples: int | None = None): + self._iter = iter(iterable_dataset) + self._samples: list[dict] = [] + self._exhausted = False + self._max = max_samples or self._MAX_CACHE + self._ds_name = iterable_dataset.__class__.__name__ + log.info(f"Lazy wrapper: {self._ds_name} (max {self._max})") + + def _fetch_up_to(self, idx: int) -> bool: + while len(self._samples) <= idx and not self._exhausted and len(self._samples) < self._max: + try: + self._samples.append(next(self._iter)) + log.info(f"{self._ds_name}: fetched sample {len(self._samples) - 1}") + except StopIteration: + self._exhausted = True + log.info(f"{self._ds_name}: exhausted at {len(self._samples)}") + return idx < len(self._samples) + + def __len__(self): + return max(len(self._samples), 1) + + def __getitem__(self, idx): + if self._fetch_up_to(idx): + return self._samples[idx] + if self._samples: + return self._samples[idx % len(self._samples)] + raise IndexError(f"{self._ds_name}: no samples available") + + +# ── Viewer ──────────────────────────────────────────────────────────────────── + + +def _collect_scene_points(state) -> np.ndarray: + """Collect all visible trajectory positions for camera fitting.""" + points: list[np.ndarray] = [] + for poses in (state.ego_poses, state.right_poses, state.left_poses): + if poses is not None and len(poses) > 0: + points.append(poses[:, :3, 3].astype(np.float32)) + if not points: + return np.zeros((1, 3), dtype=np.float32) + return np.concatenate(points, axis=0) + + +def _get_observation_up_direction(state, view_forward: np.ndarray) -> np.ndarray: + """Estimate a stable viewer up-direction from the observation camera poses.""" + if state.ego_poses is None or len(state.ego_poses) == 0: + return np.array([0.0, 0.0, 1.0], dtype=np.float32) + + # Ego poses are camera-to-world transforms in OpenCV camera convention, + # where image up corresponds to the negative camera Y axis. + camera_up = -state.ego_poses[:, :3, 1].astype(np.float32) + reference = camera_up[0] + aligned_up = camera_up.copy() + for idx in range(1, len(aligned_up)): + if float(np.dot(aligned_up[idx], reference)) < 0.0: + aligned_up[idx] *= -1.0 + + up_direction = aligned_up.mean(axis=0) + up_direction -= view_forward * float(np.dot(up_direction, view_forward)) + up_norm = float(np.linalg.norm(up_direction)) + if up_norm < 1e-6: + return np.array([0.0, 0.0, 1.0], dtype=np.float32) + return up_direction / up_norm + + +def _get_observation_forward_direction(state) -> np.ndarray | None: + """Estimate a stable viewer forward direction from the observation camera poses.""" + if state.ego_poses is None or len(state.ego_poses) == 0: + return None + + # Ego poses are camera-to-world transforms in OpenCV camera convention, + # where the optical axis points along the positive camera Z axis. + camera_forward = state.ego_poses[:, :3, 2].astype(np.float32) + reference = camera_forward[0] + aligned_forward = camera_forward.copy() + for idx in range(1, len(aligned_forward)): + if float(np.dot(aligned_forward[idx], reference)) < 0.0: + aligned_forward[idx] *= -1.0 + + forward_direction = aligned_forward.mean(axis=0) + forward_norm = float(np.linalg.norm(forward_direction)) + if forward_norm < 1e-6: + return None + return forward_direction / forward_norm + + +def _reset_camera_to_trajectory(client, state, camera_fov_deg: float) -> None: + """Frame one client's viewport using the current trajectory extent.""" + points = _collect_scene_points(state) + center = points.mean(axis=0) + extent = points - center[None, :] + radius = float(np.linalg.norm(extent, axis=1).max()) if len(points) > 0 else 0.0 + radius = max(radius, 0.15) + + fov_rad = float(np.deg2rad(camera_fov_deg)) + fit_distance = radius / max(np.tan(fov_rad / 2.0), 0.35) + view_forward = _get_observation_forward_direction(state) + if view_forward is None: + view_dir = np.array([1.0, -1.0, 0.7], dtype=np.float32) + view_dir /= np.linalg.norm(view_dir) + camera_position = center + view_dir * max(fit_distance * 1.35, 0.5) + view_forward = center - camera_position + view_forward /= np.linalg.norm(view_forward) + else: + camera_position = center - view_forward * max(fit_distance * 1.35, 0.5) + view_forward = center - camera_position + view_forward /= np.linalg.norm(view_forward) + up_direction = _get_observation_up_direction(state, view_forward) + camera = client.camera + + # Camera state arrives asynchronously from the browser. Wait briefly so we can + # update only this client's viewport instead of broadcasting a global reset target. + deadline = _time.time() + 1.0 + while getattr(camera._state, "update_timestamp", 0.0) == 0.0 and _time.time() < deadline: + _time.sleep(0.01) + if getattr(camera._state, "update_timestamp", 0.0) == 0.0: + return + + camera.fov = fov_rad + camera.up_direction = tuple(up_direction.tolist()) + camera.look_at = tuple(center.tolist()) + # Setting position also translates look_at, so restore the target afterwards. + camera.position = tuple(camera_position.tolist()) + camera.look_at = tuple(center.tolist()) + client.flush() + + +def launch_viewer( + port: int = 8013, + share: bool = False, + chunk_length: int = 16, + action_format_override: ActionFormat | None = None, + default_dataset: str = "robomind_franka_dual", +) -> None: + """Launch the interactive dataset viewer.""" + global DATASETS + import threading as _threading + + import viser + + from cosmos_framework.data.vfm.action.urdf_visualizer.unified_action import ( + build_scene_state, + get_video_from_sample, + to_unified, + ) + from cosmos_framework.data.vfm.action.urdf_visualizer.unified_renderer import UnifiedRenderer + + server = viser.ViserServer(host="0.0.0.0", port=port) + if not DATASETS: + DATASETS = _build_datasets() + datasets = DATASETS + default_dataset_name = os.environ.get("COSMOS_VIEWER_DEFAULT_DATASET", default_dataset) + if default_dataset_name not in datasets: + log.warning( + f"Default dataset {default_dataset_name!r} is not registered; " + f"falling back to {next(iter(datasets))!r}." + ) + default_dataset_name = next(iter(datasets)) + dataset_cache: dict[str, Any] = {} + dataset_locks: dict[str, Any] = {} + dataset_cache_lock = _threading.Lock() + sessions_lock = _threading.Lock() + + def _get_dataset_lock(cache_key: str) -> Any: + """Return the per-dataset lock for a cache key.""" + with dataset_cache_lock: + lock = dataset_locks.get(cache_key) + if lock is None: + lock = _threading.Lock() + dataset_locks[cache_key] = lock + return lock + + @dataclass + class ViewerSession: + client: Any + renderer: Any + time_slider: Any + speed_slider: Any + play_button: Any + action_text: Any + show: dict[str, bool | float] + load_lock: Any = field(default_factory=_threading.Lock) + playing: bool = False + last_frame_time: float = 0.0 + + sessions: dict[int, ViewerSession] = {} + + @server.on_client_connect + def _(client) -> None: + client.scene.reset() + client.scene.set_up_direction("+z") + client.gui.reset() + + renderer = UnifiedRenderer(client) + + with client.gui.add_folder("Dataset"): + ds_dropdown = client.gui.add_dropdown( + "Dataset", options=list(datasets.keys()), initial_value=default_dataset_name + ) + ep_input = client.gui.add_number( + "Episode", initial_value=int(datasets[default_dataset_name].initial_index), min=0, step=1 + ) + random_button = client.gui.add_button("🎲 Random episode") + status_text = client.gui.add_markdown("*Ready*") + info_text = client.gui.add_markdown("") + + with client.gui.add_folder("Display", expand_by_default=False): + show_robot = client.gui.add_checkbox("Show robot mesh", initial_value=True) + show_frames = client.gui.add_checkbox("Show wrist frames", initial_value=True) + show_traj = client.gui.add_checkbox("Show trajectory", initial_value=True) + show_fingertips = client.gui.add_checkbox("Show fingertips", initial_value=True) + show_ego = client.gui.add_checkbox("Show ego camera", initial_value=True) + axis_scale = client.gui.add_slider("Axis scale", min=0.1, max=20.0, step=0.1, initial_value=1.0) + + robot_frame_toggle_handles: dict[str, Any] = {} + robot_frame_toggle_folder = client.gui.add_folder("Robot Frame Toggles", expand_by_default=False) + with robot_frame_toggle_folder: + robot_frame_toggle_status = client.gui.add_markdown("*Load an episode to choose robot frame coordinates.*") + + with client.gui.add_folder("Playback"): + time_slider = client.gui.add_slider("Time", min=0, max=1, step=1, initial_value=0) + play_button = client.gui.add_button("▶ Play") + speed_slider = client.gui.add_slider("Speed (fps)", min=1, max=30, step=1, initial_value=3) + + cam_panel = client.gui.add_image(np.zeros((64, 64, 3), dtype=np.uint8)) + renderer.set_video_panel(cam_panel) + + with client.gui.add_folder("Action"): + action_text = client.gui.add_markdown("*No episode loaded*") + + show = { + "frames": True, + "traj": True, + "fingertips": True, + "ego": True, + "robot": True, + "robot_frame_filters": {}, + "axis_scale": 1.0, + } + session = ViewerSession( + client=client, + renderer=renderer, + time_slider=time_slider, + speed_slider=speed_slider, + play_button=play_button, + action_text=action_text, + show=show, + ) + + def _update_action_text(t: int) -> None: + """Update the action display for one client.""" + txt = renderer.format_action_text(t) + action_text.content = txt if txt else "*No data*" + + def _clear_robot_frame_toggles() -> None: + """Remove the dynamic per-frame toggle controls.""" + for handle in robot_frame_toggle_handles.values(): + handle.remove() + robot_frame_toggle_handles.clear() + + def _rebuild_robot_frame_toggles() -> None: + """Rebuild the GUI toggles for the currently loaded robot frames.""" + _clear_robot_frame_toggles() + selectors = renderer.get_robot_frame_selectors() + if not selectors: + show["robot_frame_filters"] = {} + robot_frame_toggle_status.content = "*No robot frame coordinates available for this episode.*" + return + + prev_filters = cast(dict[str, bool], show.get("robot_frame_filters", {})) + show["robot_frame_filters"] = { + selector_key: prev_filters.get(selector_key, False) for selector_key, _ in selectors + } + robot_frame_toggle_status.content = "*Choose which robot frame coordinates to show.*" + + with robot_frame_toggle_folder: + for selector_key, label in selectors: + checkbox = client.gui.add_checkbox( + label, + initial_value=cast(dict[str, bool], show["robot_frame_filters"])[selector_key], + ) + robot_frame_toggle_handles[selector_key] = checkbox + + @checkbox.on_update + def _(_, selector_key: str = selector_key, checkbox: Any = checkbox) -> None: + cast(dict[str, bool], show["robot_frame_filters"])[selector_key] = bool(checkbox.value) + renderer.update(time_slider.value, show) + + def do_load_episode() -> None: + t_start = _time.time() + ds_name = ds_dropdown.value + entry = datasets[ds_name] + effective_action_format = _resolve_action_format(entry, action_format_override) + ep_idx = max(int(ep_input.value), 0) + cache_key = ds_name + + status_text.content = f"⏳ Loading {ds_name} episode {ep_idx}..." + + try: + with _get_dataset_lock(cache_key): + dataset: Any + with dataset_cache_lock: + dataset = cast(Any, dataset_cache.get(cache_key)) + if dataset is None: + status_text.content = f"⏳ Creating {ds_name} dataset..." + dataset = _create_dataset(entry, chunk_length) + with dataset_cache_lock: + dataset_cache[cache_key] = dataset + to_opencv = entry.to_opencv if entry.to_opencv is not None else np.eye(3, dtype=np.float32) + + n_total = len(dataset) + if ep_idx >= n_total: + if isinstance(dataset, _IterableToMapDataset) and not dataset._exhausted: + pass + else: + ep_idx = n_total - 1 + ep_input.value = ep_idx + + sample: Any = dataset[ep_idx] + + action_tensor = sample["action"] + action_raw = ( + action_tensor.numpy() if isinstance(action_tensor, torch.Tensor) else np.asarray(action_tensor) + ) + + uses_dual_initial_pose = effective_action_format is ActionFormat.DUAL_ARM_20D + + initial_pose_t = sample.get("initial_pose") + if initial_pose_t is None: + initial_pose = np.eye(4, dtype=np.float32) + elif isinstance(initial_pose_t, torch.Tensor): + initial_pose = initial_pose_t.numpy().astype(np.float32) + else: + initial_pose = np.asarray(initial_pose_t, dtype=np.float32) + + initial_pose_right_t = sample.get("initial_pose_right") + initial_pose_left_t = sample.get("initial_pose_left") + initial_pose_right = None + initial_pose_left = None + if initial_pose_right_t is not None: + initial_pose_right = ( + initial_pose_right_t.numpy().astype(np.float32) + if isinstance(initial_pose_right_t, torch.Tensor) + else np.asarray(initial_pose_right_t, dtype=np.float32) + ) + if initial_pose_left_t is not None: + initial_pose_left = ( + initial_pose_left_t.numpy().astype(np.float32) + if isinstance(initial_pose_left_t, torch.Tensor) + else np.asarray(initial_pose_left_t, dtype=np.float32) + ) + if uses_dual_initial_pose: + if initial_pose_left is None: + initial_pose_left = initial_pose + + if entry.to_unified_fn: + converter = _load_symbol(entry.to_unified_fn) + import inspect as _inspect + + params = _inspect.signature(converter).parameters + embodiment_type = entry.robot_embodiment_type or str( + entry.dataset_kwargs.get("embodiment_type", "") + ) + if "embodiment_type" in params: + unified = converter(sample, embodiment_type=embodiment_type) + elif "kind" in params: + unified = converter(action_raw, kind="gripper") + else: + unified = converter(action_raw) + raw_action_label = "custom" + else: + unified = to_unified(action_raw, action_format=effective_action_format) + raw_action_label = effective_action_format.value + state = build_scene_state( + unified, + initial_pose=initial_pose, + initial_pose_right=initial_pose_right, + initial_pose_left=initial_pose_left, + right_base_pose=entry.dual_base_right, + left_base_pose=entry.dual_base_left, + pose_convention=entry.pose_convention, + sample=sample, + ) + state.video = get_video_from_sample(sample) + + status_text.content = "⏳ Loading robot animation..." + renderer.load(state, entry, to_opencv=to_opencv) + _rebuild_robot_frame_toggles() + _reset_camera_to_trajectory(client, state, entry.camera_fov_deg) + + T = state.T + time_slider.max = max(T, 1) + time_slider.value = 0 + + ai_caption_text = _format_sample_text(sample.get("ai_caption", ""), max_chars=160) + debug_caption_text = _format_sample_text(sample.get("debug_caption", "")) + t_total = _time.time() - t_start + info_text.content = ( + f"**{ds_name.upper()}** — Episode {ep_idx}\n\n" + + (f"Task: {ai_caption_text}\n\n" if ai_caption_text else "") + + (f"Debug: {debug_caption_text}\n\n" if debug_caption_text else "") + + ( + f"Steps: {T} | Raw action: {raw_action_label} ({action_raw.shape[-1]}D) | " + f"Robot: {entry.robot_name or '—'} | FPS: {entry.fps}" + ) + ) + status_text.content = f"✅ Loaded in {t_total:.1f}s" + log.info(f"Loaded {ds_name} ep {ep_idx}: {ai_caption_text[:60]}, {T} steps, {t_total:.1f}s") + + renderer.update(0, show) + renderer.update_axis_scale(axis_scale.value) + _update_action_text(0) + session.last_frame_time = _time.time() + + except Exception as e: + status_text.content = f"❌ Load failed: {e}" + log.error(f"Load failed for client {client.client_id}: {e}") + import traceback + + traceback.print_exc() + + def _do_load_threaded() -> None: + if not session.load_lock.acquire(blocking=False): + return + + def _run() -> None: + try: + do_load_episode() + finally: + session.load_lock.release() + + _threading.Thread(target=_run, daemon=True).start() + + @ds_dropdown.on_update + def _(_) -> None: + ep_input.value = int(datasets[ds_dropdown.value].initial_index) + _do_load_threaded() + + @ep_input.on_update + def _(_) -> None: + _do_load_threaded() + + @random_button.on_click + def _(_) -> None: + ds_name = ds_dropdown.value + cache_key = ds_name + with _get_dataset_lock(cache_key): + with dataset_cache_lock: + ds = dataset_cache.get(cache_key) + if ds is None: + ep_input.value = 0 + elif isinstance(ds, _IterableToMapDataset): + ep_input.value = len(ds._samples) + else: + ep_input.value = random.randint(0, max(len(ds) - 1, 0)) + _do_load_threaded() + + @time_slider.on_update + def _(_) -> None: + renderer.update(time_slider.value, show) + _update_action_text(time_slider.value) + + @show_robot.on_update + def _(_) -> None: + show["robot"] = show_robot.value + renderer.update(time_slider.value, show) + + @show_frames.on_update + def _(_) -> None: + show["frames"] = show_frames.value + renderer.update(time_slider.value, show) + + @show_traj.on_update + def _(_) -> None: + show["traj"] = show_traj.value + renderer.update(time_slider.value, show) + + @show_fingertips.on_update + def _(_) -> None: + show["fingertips"] = show_fingertips.value + renderer.update(time_slider.value, show) + + @show_ego.on_update + def _(_) -> None: + show["ego"] = show_ego.value + renderer.update(time_slider.value, show) + + @axis_scale.on_update + def _(_) -> None: + show["axis_scale"] = axis_scale.value + renderer.update_axis_scale(axis_scale.value) + + @play_button.on_click + def _(_) -> None: + session.playing = not session.playing + session.last_frame_time = _time.time() + play_button.label = "⏸ Pause" if session.playing else "▶ Play" + + with sessions_lock: + sessions[client.client_id] = session + _do_load_threaded() + + @server.on_client_disconnect + def _(client) -> None: + with sessions_lock: + sessions.pop(client.client_id, None) + + # ── Share URL ── + log.info(f"✅ Viewer ready at http://0.0.0.0:{port}") + if share: + share_url = server.request_share_url() + if share_url: + log.info(f"🌐 Share URL: {share_url}") + try: + with open(os.path.expanduser("~/share_url.txt"), "w") as f: + f.write(share_url + "\n") + except Exception: + pass + + # ── Main Loop ── + try: + while True: + now = _time.time() + with sessions_lock: + active_sessions = list(sessions.values()) + for session in active_sessions: + renderer = session.renderer + if not session.playing or renderer.state is None: + continue + frame_period = 1.0 / max(float(session.speed_slider.value), 1.0) + if now - session.last_frame_time < frame_period: + continue + t = session.time_slider.value + t = (t + 1) % max(renderer.state.T, 1) + session.time_slider.value = t + renderer.update(t, session.show) + txt = renderer.format_action_text(t) + session.action_text.content = txt if txt else "*No data*" + session.last_frame_time = now + _time.sleep(0.02) + except KeyboardInterrupt: + log.info("Shutting down.") + + +def main(): + parser = argparse.ArgumentParser(description="Action dataset viewer") + parser.add_argument("--port", type=int, default=8013) + parser.add_argument("--share", action="store_true") + parser.add_argument("--chunk-length", type=int, default=16) + parser.add_argument( + "--action-format", + choices=[fmt.value for fmt in ActionFormat], + default=None, + help="Optional override for the dataset-declared raw action format", + ) + parser.add_argument( + "--default-dataset", + default=os.environ.get("COSMOS_VIEWER_DEFAULT_DATASET", "robomind_franka_dual"), + help="Dataset key selected and loaded for new viewer sessions", + ) + args = parser.parse_args() + launch_viewer( + port=args.port, + share=args.share, + chunk_length=args.chunk_length, + action_format_override=ActionFormat(args.action_format) if args.action_format is not None else None, + default_dataset=args.default_dataset, + ) + + +if __name__ == "__main__": + main() diff --git a/cosmos-framework/cosmos_framework/data/vfm/action/viewpoint_utils.py b/cosmos-framework/cosmos_framework/data/vfm/action/viewpoint_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e98c9b65ed8756281b5a1be07daf6f8e2620f0cc --- /dev/null +++ b/cosmos-framework/cosmos_framework/data/vfm/action/viewpoint_utils.py @@ -0,0 +1,10 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: OpenMDW-1.1 + +"""Viewpoint type definitions for release action datasets.""" + +from __future__ import annotations + +from typing import Literal + +Viewpoint = Literal["ego_view", "third_person_view", "wrist_view", "concat_view"] diff --git a/cosmos-framework/cosmos_framework/utils/__init__.py b/cosmos-framework/cosmos_framework/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..503ec1b18d584ba1c349360dedbe6951e3216df6 --- /dev/null +++ b/cosmos-framework/cosmos_framework/utils/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: OpenMDW-1.1 + diff --git a/cosmos-framework/cosmos_framework/utils/easy_io/__init__.py b/cosmos-framework/cosmos_framework/utils/easy_io/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9f47d2e10ce222193f23f79e6cf1c70445dcb233 --- /dev/null +++ b/cosmos-framework/cosmos_framework/utils/easy_io/__init__.py @@ -0,0 +1 @@ +from .easy_io import easy_io diff --git a/cosmos-framework/cosmos_framework/utils/easy_io/easy_io.py b/cosmos-framework/cosmos_framework/utils/easy_io/easy_io.py new file mode 100644 index 0000000000000000000000000000000000000000..a768cb2d2c541856fef8b65a33a19aba2e7ab031 --- /dev/null +++ b/cosmos-framework/cosmos_framework/utils/easy_io/easy_io.py @@ -0,0 +1,40 @@ +# Minimal easy_io shim for the standalone action viewer. +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +class _EasyIO: + def __init__(self) -> None: + self._s3_backend_args: dict[str, Any] = {} + + def set_s3_backend(self, backend_args: dict[str, Any] | None = None) -> None: + self._s3_backend_args = dict(backend_args or {}) + + def _get_s3_client(self): + import boto3, yaml + cred_path = self._s3_backend_args.get("s3_credential_path") + kwargs = {} + if cred_path and Path(cred_path).exists(): + kwargs = yaml.safe_load(Path(cred_path).read_text()) or {} + return boto3.client("s3", **kwargs) + + def get_bytes(self, path: str) -> bytes: + if path.startswith("s3://") or path.startswith("gs://"): + no_scheme = path.split("://", 1)[1] + bucket, key = no_scheme.split("/", 1) + obj = self._get_s3_client().get_object(Bucket=bucket, Key=key) + return obj["Body"].read() + return Path(path).read_bytes() + + def get(self, path: str) -> str: + return self.get_bytes(path).decode() + + def load(self, path: str) -> Any: + text = self.get(path) + if path.endswith(".json"): + return json.loads(text) + return text + +easy_io = _EasyIO() diff --git a/cosmos-framework/cosmos_framework/utils/log.py b/cosmos-framework/cosmos_framework/utils/log.py new file mode 100644 index 0000000000000000000000000000000000000000..7736ef2c34571d12cc611707d98857d26a913720 --- /dev/null +++ b/cosmos-framework/cosmos_framework/utils/log.py @@ -0,0 +1,144 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: OpenMDW-1.1 + +import atexit +import os +import sys +from typing import Any + +import torch.distributed as dist +from loguru._logger import Core, Logger + +RANK0_ONLY = True +LEVEL = os.environ.get("LOGURU_LEVEL", "INFO") +RANK = int(os.environ.get("RANK", "0")) + + +def make_new_logger(depth: int = 1) -> Logger: + return Logger( + core=Core(), + exception=None, + depth=depth, + record=False, + lazy=False, + colors=False, + raw=False, + capture=True, + patchers=[], + extra={}, + ) + + +logger = make_new_logger(depth=1) +atexit.register(logger.remove) + + +def _add_relative_path(record: dict[str, Any]) -> None: + try: + start = os.getcwd() + record["extra"]["relative_path"] = os.path.relpath(record["file"].path, start) + except OSError: + # CWD may have been removed (e.g. on some ranks in distributed jobs). + # Fall back to the absolute path so logging still works. + record["extra"]["relative_path"] = f":{record['file'].path}" + + +*options, _, extra = logger._options # type: ignore +logger._options = tuple([*options, [_add_relative_path], extra]) # type: ignore + + +def init_loguru_stdout() -> None: + logger.remove() + datetime_format = get_datetime_format() + machine_format = get_machine_format() + message_format = get_message_format() + logger.add( + sys.stdout, + level=LEVEL, + format=f"{datetime_format}{machine_format}{message_format}", + filter=_rank0_only_filter, + ) + + +def init_loguru_file(path: str) -> None: + datetime_format = get_datetime_format() + machine_format = get_machine_format() + message_format = get_message_format() + logger.add( + path, + encoding="utf8", + level=LEVEL, + format=f"{datetime_format}{machine_format}{message_format}", + rotation="100 MB", + filter=lambda result: _rank0_only_filter(result) or not RANK0_ONLY, + enqueue=True, + ) + + +def get_datetime_format() -> str: + return "[{time:MM-DD HH:mm:ss}|" + + +def get_machine_format() -> str: + node_id = os.environ.get("NGC_ARRAY_INDEX", "0") + num_nodes = int(os.environ.get("NGC_ARRAY_SIZE", "1")) + machine_format = "" + rank = 0 + if dist.is_available(): + if not RANK0_ONLY and dist.is_initialized(): + rank = dist.get_rank() + world_size = dist.get_world_size() + machine_format = ( + f"[Node{node_id:<3}/{num_nodes:<3}][RANK{rank:<5}/{world_size:<5}]" + "[{process.name:<8}]| " + ) + return machine_format + + +def get_message_format() -> str: + message_format = "{level}|{extra[relative_path]}:{line}:{function}] {message}" + return message_format + + +def _rank0_only_filter(record: Any) -> bool: + is_rank0 = record["extra"].get("rank0_only", True) + if RANK == 0 and is_rank0: + return True + if not is_rank0: + record["message"] = f"[RANK {RANK}] " + record["message"] + return not is_rank0 + + +def trace(message: str, rank0_only: bool = True) -> None: + logger.opt(depth=1).bind(rank0_only=rank0_only).trace(message) + + +def debug(message: str, rank0_only: bool = True) -> None: + logger.opt(depth=1).bind(rank0_only=rank0_only).debug(message) + + +def info(message: str, rank0_only: bool = True) -> None: + logger.opt(depth=1).bind(rank0_only=rank0_only).info(message) + + +def success(message: str, rank0_only: bool = True) -> None: + logger.opt(depth=1).bind(rank0_only=rank0_only).success(message) + + +def warning(message: str, rank0_only: bool = True) -> None: + logger.opt(depth=1).bind(rank0_only=rank0_only).warning(message) + + +def error(message: str, rank0_only: bool = True) -> None: + logger.opt(depth=1).bind(rank0_only=rank0_only).error(message) + + +def critical(message: str, rank0_only: bool = True) -> None: + logger.opt(depth=1).bind(rank0_only=rank0_only).critical(message) + + +def exception(message: str, rank0_only: bool = True) -> None: + logger.opt(depth=1).bind(rank0_only=rank0_only).exception(message) + + +# Execute at import time. +init_loguru_stdout() diff --git a/start.sh b/start.sh new file mode 100755 index 0000000000000000000000000000000000000000..593c58218f6f90073790a8655fbb50515ed09847 --- /dev/null +++ b/start.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +set -euo pipefail + +export PORT="${PORT:-7860}" +export COSMOS_VIEWER_SHARE="${COSMOS_VIEWER_SHARE:-0}" +export PYTHONUNBUFFERED=1 +export PYTHONPATH="${PYTHONPATH:-/app/cosmos-framework}" +export HF_HOME="${HF_HOME:-/tmp/.cache/huggingface}" +export XDG_CACHE_HOME="${XDG_CACHE_HOME:-/tmp/.cache}" +export MPLCONFIGDIR="${MPLCONFIGDIR:-/tmp/matplotlib}" +export MUJOCO_GL="${MUJOCO_GL:-osmesa}" +export HF_HUB_DISABLE_XET="${HF_HUB_DISABLE_XET:-1}" + +# Default to the packaged Bridge demo subset. No HF download/streaming is needed. +export COSMOS_VIEWER_ON_DEMAND_VIDEO="${COSMOS_VIEWER_ON_DEMAND_VIDEO:-0}" +export COSMOS_VIEWER_DOWNLOAD_DATA="${COSMOS_VIEWER_DOWNLOAD_DATA:-0}" +export BRIDGE_LEROBOT_ROOT="${BRIDGE_LEROBOT_ROOT:-/app/assets/examples/bridge_lerobot_v3}" +export AV_ROOT="${AV_ROOT:-/app/assets/examples/av_v2_03292026_wdinfo}" +export UMI_ROOT="${UMI_ROOT:-/app/assets/examples/fastumi/fastumi_single_arm/pour_coke}" +export FRACTAL_ROOT="${FRACTAL_ROOT:-/app/assets/examples/fractal20220817_data}" +export DROID_ROOT="${DROID_ROOT:-/app/assets/examples/droid_plus_lerobot_640x360_20260412}" +export ROBOMIND_FRANKA_ROOT="${ROBOMIND_FRANKA_ROOT:-/app/assets/examples/RoboMIND_20251228/benchmark1_0_release/franka_3rgb/241021_close_trash_bin_1}" +export ROBOMIND_FRANKA_DUAL_ROOT="${ROBOMIND_FRANKA_DUAL_ROOT:-/app/assets/examples/RoboMIND_20251228/benchmark1_1_release/franka_fr3_dual/both_pour_water}" +export ROBOMIND_ROOT="${ROBOMIND_ROOT:-/app/assets/examples/RoboMIND_20251228}" + +mkdir -p "${HF_HOME}" "${XDG_CACHE_HOME}" + +echo "Starting Cosmos3 action viewer on port ${PORT}" +echo "BRIDGE_LEROBOT_ROOT=${BRIDGE_LEROBOT_ROOT}" +echo "COSMOS_VIEWER_ON_DEMAND_VIDEO=${COSMOS_VIEWER_ON_DEMAND_VIDEO}" +echo "COSMOS_VIEWER_SHARE=${COSMOS_VIEWER_SHARE}" +echo "AV_ROOT=${AV_ROOT}" +echo "UMI_ROOT=${UMI_ROOT}" +echo "FRACTAL_ROOT=${FRACTAL_ROOT}" +echo "DROID_ROOT=${DROID_ROOT}" +echo "ROBOMIND_FRANKA_ROOT=${ROBOMIND_FRANKA_ROOT}" +echo "ROBOMIND_FRANKA_DUAL_ROOT=${ROBOMIND_FRANKA_DUAL_ROOT}" + +viewer_args=(--port "${PORT}") +case "${COSMOS_VIEWER_SHARE}" in + 1|true|TRUE|yes|YES|on|ON) + viewer_args+=(--share) + ;; +esac + +cd /app/cosmos-framework +exec python cosmos_framework/data/vfm/action/urdf_visualizer/viewer.py "${viewer_args[@]}"