cagataydev commited on
Commit
b724994
·
verified ·
1 Parent(s): b7431a9

Polished card: strands-robots usage, playback gif/mp4, LICENSE, examples

Browse files
LICENSE.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # License
2
+
3
+ **Generated content in this repository** (recorded trajectories, rendered camera video, playback clips, trained policy weights and
4
+ training logs) was produced with NVIDIA Isaac Sim 6.1.0.0 / Isaac Lab 3.0.0rc1 via strands-robots and is released under the
5
+ **Creative Commons Attribution 4.0 International (CC-BY-4.0)** license — https://creativecommons.org/licenses/by/4.0/.
6
+ Attribution: "cagataydev / strands-robots Isaac Lab showcase (strands-labs/robots#4227)".
7
+
8
+ This relies on the NVIDIA Omniverse License Agreement §2.1, which permits distributing user-generated content made with
9
+ Omniverse "such as video, audio, stills, models, 3D assets and screen captures".
10
+
11
+ **Not included / not licensed here:** NVIDIA Content (robot and scene USD assets from the Isaac Lab / Isaac Sim asset packs,
12
+ e.g. the Shadow Hand USDs) are not redistributed; `params/env.yaml` only references asset paths. Using those assets
13
+ or running Isaac Sim requires your own acceptance of the NVIDIA Isaac Sim / Omniverse License Agreement
14
+ (https://docs.omniverse.nvidia.com/dev-guide/latest/common/NVIDIA_Omniverse_License_Agreement.html).
15
+
16
+ **Configuration and code:** `params/*.yaml` are Isaac Lab task/agent configurations (Isaac Lab: BSD-3-Clause).
17
+ `examples/*.py` are provided under Apache-2.0 (as strands-robots).
18
+
19
+ "Shadow Hand" is a product of The Shadow Robot Company; NVIDIA, Isaac Sim and Isaac Lab are NVIDIA trademarks. No endorsement
20
+ by either is implied. Simulation-only research artifact, provided AS IS without warranty.
README.md CHANGED
@@ -1,36 +1,166 @@
1
  ---
2
  license: other
3
- license_name: nvidia-isaac-sim-generated
4
- tags: [lerobot, isaaclab, isaac-sim, strands-robots, robotics, simulation, reinforcement-learning]
5
- task_categories: [robotics]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  configs:
7
  - config_name: default
8
  data_files: data/*/*.parquet
9
  ---
10
- # strands-isaaclab-shadow-handover — Two Shadow Hands hand over an object
11
 
12
- LeRobot v3 dataset of a **trained rsl_rl PPO policy** rolling out in Isaac Lab (`Isaac-Shadow-Handover`), recorded
13
- end-to-end through **strands-robots**: trained with strands' `isaaclab` train_policy provider, deployed as a
14
- strands `Policy` (`RslRlJitPolicy`, wrapping Isaac Lab's exported TorchScript actor) and recorded with strands'
15
- `DatasetRecorder` including RTX camera video. Policy: [cagataydev/strands-isaaclab-shadow-handover-policy](https://huggingface.co/cagataydev/strands-isaaclab-shadow-handover-policy).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  ## Provenance
18
- - **strands-robots**: `feat/isaaclab-trainer` @ `fa66fc68` ([strands-labs/robots#4227](https://github.com/strands-labs/robots/pull/4227)) — `isaaclab` train_policy provider (`IsaacLabTrainer`) + `DatasetRecorder` (LeRobot v3)
19
- - **Isaac Lab** 3.0.0rc1 · **Isaac Sim** 6.1.0.0 · rsl-rl-lib 5.4.1 · lerobot 0.6.1 · NVIDIA L40S
20
- - **Task**: `Isaac-Shadow-Handover` · physics: `task default (PhysX)` · train envs: 2048 · iterations: 1500 · seed 1
21
- - **Training job**: `isaaclab-20260929-081406-931b9b40e4ff` → `isaaclab train --rl_library rsl_rl --task Isaac-Shadow-Handover --max_iterations 1500 --visualizer none --run_name isaaclab-20260929-081406-931b9b40e4ff --seed 1`
22
- - Training call (strands): `train_policy(action="train", provider="isaaclab", output_dir=..., steps=1500, extra={"task": "Isaac-Shadow-Handover", "timeout_s": 10800})`
23
-
24
- ## Recording
25
- - episodes: **12** · frames: **2857** · fps: 60 · camera `observation.images.front` 320x240 (fixed cam, RTX)
26
- - one episode = one parallel env (envs 0..11) from a common reset until its first done or 300 frames; play-mode env cfg: True
27
- - episode lengths: [300, 65, 300, 300, 43, 300, 49, 300, 300, 300, 300, 300] · ends: ['frames', 'terminated', 'frames', 'frames', 'terminated', 'frames', 'terminated', 'frames', 'frames', 'frames', 'frames', 'frames']
28
- - episode returns: [17.451, 0.023, 17.312, 17.327, 0.022, 17.41, 0.231, 17.273, 17.297, 17.057, 17.463, 17.523] (mean 13.032)
29
- - `observation.state` = 24 joint positions + `policy_obs.*` (290-D actor observation, exactly what the policy saw) + `root_pos.*` (env frame) + `root_quat.*` (xyzw)
30
- - `action` = 40-D raw policy action (right_hand.rh_WRJ2, right_hand.rh_WRJ1, right_hand.rh_FFJ4, right_hand.rh_FFJ3, …) as applied to the env
31
- - strands-wrapped JIT vs rsl_rl inference policy max |Δa| = 1.55e-06
32
- - verification: strands `verify_dataset` ok=True, LeRobotDataset load ok, video decode ok, NaN/inf = 0, round-trip from the Hub checked (see policy repo)
33
- - command: `/home/ubuntu/strands-robots-isaac-test/isaaclab-research/.venv/bin/python examples/record_trained_policy.py --task Isaac-Shadow-Handover --checkpoint /home/ubuntu/strands-robots-isaac-test/isaaclab-extreme/runs/c6_shadow_handover/logs/rsl_rl/handover/2026-09-29_08-14-10_isaaclab-20260929-081406-931b9b40e4ff/model_1499.pt --episodes 12 --frames 300 --cam fixed --task_str pass the object from one hand to the other and bring it to the goal --robot_type shadow_hand_x2 --root rec/shadow-handover/ds --repo_id cagataydev/strands-isaaclab-shadow-handover --cam_name front --eye 1.0,-1.5,1.05 --target 0,-0.5,0.55`
 
 
34
 
35
  ## License
36
- Generated in NVIDIA Isaac Sim / Isaac Lab; use is subject to the [NVIDIA Isaac Sim EULA](https://docs.isaacsim.omniverse.nvidia.com/latest/common/NVIDIA_Omniverse_License_Agreement.html) (robot assets © their owners). Isaac Lab code BSD-3. Private research artifact.
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: other
3
+ license_name: cc-by-4.0-generated-with-nvidia-isaac
4
+ license_link: LICENSE.md
5
+ tags:
6
+ - lerobot
7
+ - isaaclab
8
+ - isaac-sim
9
+ - strands-robots
10
+ - robotics
11
+ - reinforcement-learning
12
+ - shadow-hand
13
+ - dexterous-manipulation
14
+ - bimanual
15
+ - simulation
16
+ task_categories:
17
+ - robotics
18
+ pretty_name: Two Shadow hands hand an object over (Isaac Lab, recorded with strands-robots)
19
+ size_categories:
20
+ - 1K<n<10K
21
  configs:
22
  - config_name: default
23
  data_files: data/*/*.parquet
24
  ---
 
25
 
26
+ # strands-isaaclab-shadow-handover
27
+
28
+ **Two Shadow Dexterous Hands pass an object from one hand to the other and bring it to a goal, in NVIDIA Isaac Lab, recorded through
29
+ [strands-robots](https://github.com/strands-labs/robots).** The PPO policy was trained with strands' `isaaclab` train_policy provider
30
+ ([PR #4227](https://github.com/strands-labs/robots/pull/4227)); its rollouts, written with strands' `DatasetRecorder`, are this LeRobot v3 dataset.
31
+
32
+ ![playback: 4 recorded envs](playback.gif)
33
+
34
+ *4 recorded envs (2×2) from the strands camera — [mp4](playback.mp4). Policy: [cagataydev/strands-isaaclab-shadow-handover-policy](https://huggingface.co/cagataydev/strands-isaaclab-shadow-handover-policy).*
35
+
36
+ | | |
37
+ |---|---|
38
+ | episodes / frames | **12 / 2857** at 60 fps (up to 300 frames = 5 s each; 9 full, 3 ended on a drop) |
39
+ | camera | `observation.images.front` 320×240 RTX, fixed (eye 1.0,-1.5,1.05 → target 0,-0.5,0.55) |
40
+ | `observation.state` | 321-D = 24 right-hand joint pos + 290-D two-hand policy observation (`policy_obs.*`) + root pos (3) + root quat xyzw (4) |
41
+ | `action` | 40-D raw policy action: 20 actuated joints per hand × 2 (right then left), 60 Hz |
42
+ | task string | "pass the object from one hand to the other and bring it to the goal" |
43
+ | episode return (mean) | 13.0 (range 0.0 – 17.5) |
44
+ | checks | strands `verify_dataset` ok · `LeRobotDataset` load ok · video decode ok · NaN/inf = 0 · Hub round-trip ok |
45
+
46
+ ## Results (the policy that generated this data)
47
+
48
+ Trained with **2048 parallel envs × 1500 PPO iterations** (49 M env steps) in **45 min 35 s** on one NVIDIA L40S
49
+ (Newton/MJWarp). Mean reward **0.00 → 25.2 (best) → 23.3 (last)**; handover success
50
+ **0.89** at the last iteration (peak 0.96); final object-to-goal distance ≈ 4 cm; throughput median **16 k**
51
+ env-steps/s (max 47 k, GPU shared with the cable-lift run).
52
+
53
+ | PPO iteration | mean reward | handover success | env-steps/s |
54
+ |---|---|---|---|
55
+ | 0 | 0.00 | 0.000 | 27,700 |
56
+ | 100 | 0.32 | 0.002 | 19,498 |
57
+ | 300 | 15.47 | 0.638 | 40,439 |
58
+ | 600 | 19.51 | 0.767 | 16,978 |
59
+ | 900 | 20.58 | 0.791 | 15,199 |
60
+ | 1200 | 24.09 | 0.939 | 14,530 |
61
+ | 1499 | 23.26 | 0.892 | 14,438 |
62
+
63
+ ## How it was made with strands-robots
64
+
65
+ ```bash
66
+ # Isaac Lab in its OWN venv (its pins clash with strands; strands never imports it)
67
+ uv venv --python 3.12 ~/il && uv pip install --python ~/il/bin/python --prerelease=allow \
68
+ --index https://pypi.nvidia.com --index-strategy unsafe-best-match "isaaclab[rsl-rl,isaacsim]==3.0.0rc1"
69
+ export ISAACLAB_PYTHON=~/il/bin/python
70
+ export OMNI_KIT_ACCEPT_EULA=YES # you accept the NVIDIA Omniverse / Isaac Sim EULA yourself
71
+ pip install "git+https://github.com/cagataycali/robots@feat/isaaclab-trainer" # strands-robots with PR #4227
72
+ ```
73
+
74
+ ### 1. Train (strands `train_policy`, `isaaclab` provider)
75
+
76
+ **As an agent tool call** (the `train_policy` tool is a Strands `@tool`):
77
+
78
+ ```python
79
+ from strands import Agent
80
+ from strands_robots.tools.train_policy import train_policy
81
+
82
+ agent = Agent(tools=[train_policy])
83
+ agent("Train two Shadow hands to hand an object over with the isaaclab provider: task Isaac-Shadow-Handover, 1500 iterations, seed 1.")
84
+ # -> train_policy(action="train", provider="isaaclab", steps=1500, seed=1, output_dir="runs/c6_shadow_handover",
85
+ # extra={"task": "Isaac-Shadow-Handover", "timeout_s": 10800})
86
+ ```
87
+
88
+ **As plain Python** (exactly what produced this run):
89
+
90
+ ```python
91
+ from strands_robots.tools.train_policy import train_policy
92
+
93
+ job = train_policy(action="train", provider="isaaclab", steps=1500, seed=1, output_dir="runs/c6_shadow_handover",
94
+ extra={"task": "Isaac-Shadow-Handover", "timeout_s": 10800}) # task default: 2048 envs, Newton/MJWarp physics
95
+ train_policy(action="status", provider="isaaclab", job_id="<job_id from the result>")
96
+ ```
97
+
98
+ Under the hood: `python -m isaaclab train --rl_library rsl_rl --task Isaac-Shadow-Handover --max_iterations 1500 --seed 1` in `$ISAACLAB_PYTHON`.
99
+ Job id of this run: `isaaclab-20260929-081406-931b9b40e4ff`. Docs: [`docs/learn/training/isaaclab.md`](https://github.com/cagataycali/robots/blob/feat/isaaclab-trainer/docs/learn/training/isaaclab.md) · PR: [strands-labs/robots#4227](https://github.com/strands-labs/robots/pull/4227).
100
+
101
+ ### 2. Record (strands `Policy` + `DatasetRecorder`)
102
+
103
+ The final checkpoint was rolled out and recorded with [`examples/record_trained_policy.py`](examples/record_trained_policy.py)
104
+ (included): rebuild the task env in play mode with an RTX camera → load `model_1499.pt` with rsl_rl and export TorchScript/ONNX →
105
+ wrap the actor as a **strands `Policy`** (`RslRlJitPolicy`, max |Δa| vs rsl_rl = 1.5e-06) → step with
106
+ `policy.get_actions_sync(...)` → write every frame through **strands `DatasetRecorder`** (LeRobot v3) → verify with strands `verify_dataset`.
107
+
108
+ ```bash
109
+ OMNI_KIT_ACCEPT_EULA=YES PYTHONPATH=/path/to/strands-robots $ISAACLAB_PYTHON examples/record_trained_policy.py \
110
+ --task Isaac-Shadow-Handover --checkpoint model_1499.pt --episodes 12 --frames 300 \
111
+ --cam fixed --cam_name front --eye 1.0,-1.5,1.05 --target 0,-0.5,0.55 \
112
+ --task_str "pass the object from one hand to the other and bring it to the goal" --robot_type shadow_hand_x2 --root out/ds --repo_id cagataydev/strands-isaaclab-shadow-handover
113
+ $ISAACLAB_PYTHON examples/record_trained_policy.py --verify out/ds --repo_id cagataydev/strands-isaaclab-shadow-handover
114
+ ```
115
+
116
+ ## Use it
117
+
118
+ ```python
119
+ from lerobot.datasets.lerobot_dataset import LeRobotDataset
120
+ ds = LeRobotDataset("cagataydev/strands-isaaclab-shadow-handover")
121
+ print(ds.num_episodes, ds.num_frames) # 12 2857
122
+ x = ds[0]; print(x["observation.state"].shape, x["action"].shape, x["observation.images.front"].shape)
123
+ # (321,) (40,) (3, 240, 320)
124
+ ```
125
+
126
+ Train an imitation policy on it with strands:
127
+
128
+ ```python
129
+ from strands_robots.tools.train_policy import train_policy
130
+ train_policy(action="train", provider="lerobot", dataset_repo_id="cagataydev/strands-isaaclab-shadow-handover",
131
+ output_dir="runs/act_handover", steps=20000, batch_size=32, extra={"policy_type": "act"})
132
+ ```
133
 
134
  ## Provenance
135
+
136
+ - **strands-robots**: `feat/isaaclab-trainer` @ [`fa66fc68`](https://github.com/cagataycali/robots/commit/fa66fc682047f3cb70e2e2bc60f0b2dde2fbebae) — [strands-labs/robots#4227](https://github.com/strands-labs/robots/pull/4227) (`isaaclab` train_policy provider; `DatasetRecorder`; `verify_dataset`)
137
+ - **Isaac Lab** 3.0.0rc1 · **Isaac Sim** 6.1.0.0 · Newton / MJWarp (task default physics) · rsl-rl-lib 5.4.1 (PPO) · lerobot 0.6.1
138
+ - **GPU**: 1× NVIDIA L40S (46 GB), shared with the Franka cable-lift training
139
+ - **Seeds**: training seed 1 (`params/agent.yaml`, `params/env.yaml`); recording seed 7
140
+ - **Training job**: `isaaclab-20260929-081406-931b9b40e4ff`, 2026-09-29
141
+
142
+ ## Limitations
143
+
144
+ - **Simulation only**; no real Shadow Hands were used; no sim-to-real claims.
145
+ - **Release candidates**: Isaac Lab 3.0.0rc1 / Isaac Sim 6.1.0.0. Trained on the task's default Newton/MJWarp physics; the checkpoint does
146
+ not remember the preset (IL-X-011) — replay on the same physics.
147
+ - **Not every rollout succeeds:** training success is 0.89 (peak 0.96), and in the recording 3 of 12 episodes
148
+ ended early when the object was dropped (lengths 43, 49 and 65 frames); the other 9 ran the full 5 s.
149
+ - Recording: 12 parallel envs, 300 frames (5 s @ 60 fps) each from one fixed camera; an episode ends at 300 frames or when the
150
+ object is dropped. `observation.state` = 24 joint pos of the **right** hand only + 290-D two-hand policy observation + root pos/quat (321-D);
151
+ the left hand's state is inside `policy_obs.*`. Not a standard LeRobot robot state.
152
+ - `create_policy("rl")` in strands cannot load rsl_rl checkpoints yet (IL-X-006); use the exported TorchScript + the wrapper above.
153
 
154
  ## License
155
+
156
+ **Card choice: `license: other` — our generated data / weights under CC-BY-4.0, plus NVIDIA notices.** Why:
157
+
158
+ - Trajectories, rendered camera video, playback clips and trained weights are *user-generated content* made with NVIDIA Isaac Sim /
159
+ Isaac Lab; the NVIDIA Omniverse License Agreement (governs Isaac Sim 6.1, `isaacsim/LICENSE.txt`) §2.1 allows distributing
160
+ *"user generated content that you develop using Omniverse, such as video, audio, stills, models, 3D assets and screen captures"*.
161
+ We release it under **CC-BY-4.0**.
162
+ - **No NVIDIA Content is redistributed**: the Shadow Hand USDs (`Robots_Multiphysics/ShadowRobot/ShadowHandMultiPhysics_v0/…`) and the ground-plane asset come from the Isaac Lab / Isaac Sim asset packs and are
163
+ not in this repo (`params/env.yaml` only references their paths). "Shadow Hand" is a product of The Shadow Robot Company; no endorsement
164
+ by Shadow Robot or NVIDIA is implied.
165
+ - `params/*.yaml` are Isaac Lab configurations (**BSD-3-Clause**); `examples/*` are Apache-2.0 like strands-robots. Running Isaac
166
+ Sim requires your own acceptance of the NVIDIA Isaac Sim / Omniverse EULA. Full text: [`LICENSE.md`](LICENSE.md).
examples/play_video.sh ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Play a trained rsl_rl checkpoint headless-with-RTX and record an mp4 (detached).
3
+ # usage: play_video.sh TASK CHECKPOINT_PT OUT_LOG [num_envs=16] [video_length=400] [extra hydra overrides...]
4
+ set -euo pipefail
5
+ TASK=$1; CKPT=$2; LOG=$3; N=${4:-16}; L=${5:-400}; shift 5 || shift $#
6
+ cd "$(dirname "$(dirname "$(dirname "$(dirname "$CKPT")")")")/.." # the run's output_dir, so videos land in the run dir
7
+ env -u PYTHONPATH -u VIRTUAL_ENV OMNI_KIT_ACCEPT_EULA=YES setsid nohup "$ISAACLAB_PYTHON" -m isaaclab play --rl_library rsl_rl \
8
+ --task "$TASK" --num_envs "$N" --checkpoint "$CKPT" --video --video_length "$L" --visualizer kit "$@" > "$LOG" 2>&1 < /dev/null &
9
+ echo "play pid $!"
examples/record_trained_policy.py ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Record a TRAINED Isaac Lab rsl_rl policy to a LeRobot v3 dataset through strands-robots.
2
+
3
+ Chain proven here (strands-robots feat/isaaclab-trainer @fa66fc68, PR #4227):
4
+ train_policy(provider="isaaclab") -> rsl_rl run dir with model_<N>.pt + params/{env,agent}.yaml
5
+ THIS SCRIPT (runs in the Isaac Lab venv, strands on PYTHONPATH):
6
+ 1. rebuild the task env (play-mode cfg, same physics preset) + a strands camera per env
7
+ 2. load the rsl_rl checkpoint with OnPolicyRunner, export JIT + ONNX (Isaac Lab's own exporter)
8
+ 3. wrap the exported JIT actor as a strands `Policy` (RslRlJitPolicy) -- IL-X-006: strands'
9
+ create_policy("rl") cannot load the rsl_rl ELU actor, so the example carries the adapter
10
+ 4. roll it out: every env i in 0..N-1 is one episode (from a common reset to its first done or
11
+ --frames), actions come from policy.get_actions_sync() per env (strands single-robot API)
12
+ 5. record with strands `DatasetRecorder` (observation.state = joint pos + policy obs + root pose,
13
+ action = policy action, observation.images.<cam> = RTX camera video, task string, fps)
14
+ --verify ROOT (fresh process, no Kit): strands verify_dataset + LeRobotDataset load + video decode
15
+ + frame counts + NaN scan.
16
+
17
+ Run (Isaac Lab venv):
18
+ OMNI_KIT_ACCEPT_EULA=YES PYTHONPATH=$T/isaaclab-wt $ISAACLAB_PYTHON record_trained_policy.py \
19
+ --task Isaac-Velocity-Rough-G1 --checkpoint RUN/model_1499.pt --episodes 12 --frames 500 \
20
+ --override physics=newton_mjwarp --cam chase --root out/ds --repo_id cagataydev/x
21
+ $ISAACLAB_PYTHON record_trained_policy.py --verify out/ds --repo_id cagataydev/x
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import argparse
27
+ import json
28
+ import os
29
+ import shutil
30
+ import sys
31
+ import time
32
+
33
+ ap = argparse.ArgumentParser()
34
+ ap.add_argument("--task")
35
+ ap.add_argument("--checkpoint")
36
+ ap.add_argument("--episodes", type=int, default=12, help="= num_envs; env i is episode i")
37
+ ap.add_argument("--frames", type=int, default=500)
38
+ ap.add_argument("--override", action="append", default=[], help="hydra override, e.g. physics=newton_mjwarp")
39
+ ap.add_argument("--cam", default="chase", choices=["chase", "fixed", "none"])
40
+ ap.add_argument("--cam_name", default=None)
41
+ ap.add_argument("--eye", default=None, help="eye offset x,y,z (chase: from root; fixed: from env origin)")
42
+ ap.add_argument("--target", default="0,0,0", help="fixed cam: look-at offset from env origin (or root with chase)")
43
+ ap.add_argument("--attach", default="Robot/pelvis", help="chase cam parent prim under the env ns (a robot link)")
44
+ ap.add_argument("--width", type=int, default=320)
45
+ ap.add_argument("--height", type=int, default=240)
46
+ ap.add_argument("--no_play_mode", action="store_true")
47
+ ap.add_argument("--task_str", default=None, help="language task string stored per frame")
48
+ ap.add_argument("--robot_type", default=None)
49
+ ap.add_argument("--root")
50
+ ap.add_argument("--repo_id", default="local/isaaclab_policy")
51
+ ap.add_argument("--min_len", type=int, default=1)
52
+ ap.add_argument("--verify", default=None, help="verify an existing dataset root and exit (no Kit)")
53
+ ap.add_argument("--seed", type=int, default=7)
54
+ a = ap.parse_args()
55
+ sys.argv = sys.argv[:1]
56
+
57
+
58
+ # ----------------------------------------------------------------------------- verify (no Kit)
59
+ def verify(root: str, repo_id: str, expected: int | None = None) -> dict:
60
+ import numpy as np
61
+ import pandas as pd
62
+
63
+ out: dict = {"root": root}
64
+ from strands_robots.verify_dataset import verify_dataset
65
+
66
+ rep = verify_dataset(root, expected=expected, min_frames=1)
67
+ out["strands_verify"] = rep
68
+ from lerobot.datasets.lerobot_dataset import LeRobotDataset
69
+
70
+ ds = LeRobotDataset(repo_id, root=root)
71
+ out["num_episodes"], out["num_frames"], out["fps"] = ds.num_episodes, ds.num_frames, ds.fps
72
+ info = json.load(open(os.path.join(root, "meta", "info.json")))
73
+ out["features"] = {k: v.get("shape") for k, v in info["features"].items()}
74
+ vid_keys = [k for k, v in info["features"].items() if v.get("dtype") == "video"]
75
+ # decode first / middle / last frame through LeRobot (torchcodec/pyav)
76
+ dec = {}
77
+ for idx in (0, ds.num_frames // 2, ds.num_frames - 1):
78
+ it = ds[idx]
79
+ for k in vid_keys:
80
+ t = it[k]
81
+ dec[f"{k}@{idx}"] = {"shape": list(t.shape), "mean": round(float(t.float().mean()), 4)}
82
+ out["video_decode"] = dec
83
+ # NaN scan + per-episode frame counts straight from parquet
84
+ files = sorted(
85
+ os.path.join(dp, f) for dp, _, fs in os.walk(os.path.join(root, "data")) for f in fs if f.endswith(".parquet")
86
+ )
87
+ df = pd.concat([pd.read_parquet(f) for f in files])
88
+ nan = 0
89
+ for c in ("observation.state", "action"):
90
+ arr = np.stack(df[c].to_numpy())
91
+ nan += int((~np.isfinite(arr)).sum())
92
+ out[f"{c}.dim"] = arr.shape[1]
93
+ out["nan_or_inf"] = nan
94
+ out["frames_per_episode"] = df.groupby("episode_index").size().tolist()
95
+ out["tasks"] = sorted(set(ds.meta.tasks.index)) if hasattr(ds.meta.tasks, "index") else str(ds.meta.tasks)[:200]
96
+ ok_verify = bool(rep.get("ok", rep.get("valid", True))) if isinstance(rep, dict) else True
97
+ out["OK"] = bool(
98
+ nan == 0
99
+ and ds.num_frames == sum(out["frames_per_episode"])
100
+ and (expected is None or ds.num_episodes == expected)
101
+ and all(v["shape"][0] == 3 for v in dec.values())
102
+ and ok_verify
103
+ )
104
+ return out
105
+
106
+
107
+ if a.verify:
108
+ res = verify(a.verify, a.repo_id)
109
+ print("[record] VERIFY " + json.dumps(res, default=str))
110
+ json.dump(res, open(a.verify.rstrip("/") + "_verify.json", "w"), indent=1, default=str)
111
+ sys.exit(0 if res["OK"] else 3)
112
+
113
+ # ----------------------------------------------------------------------------- record (Kit)
114
+ import gymnasium as gym # noqa: E402
115
+ import numpy as np # noqa: E402
116
+ import torch # noqa: E402
117
+ from isaaclab.app import launch_simulation # noqa: E402
118
+
119
+ import isaaclab_tasks # noqa: E402,F401
120
+ from isaaclab_tasks.utils import resolve_task_config # noqa: E402
121
+
122
+ N = a.episodes
123
+ env_cfg, agent_cfg = resolve_task_config(
124
+ a.task, "rsl_rl_cfg_entry_point", play_mode=not a.no_play_mode, overrides=list(a.override)
125
+ )
126
+ env_cfg.scene.num_envs = N
127
+ env_cfg.sim.device = "cuda:0"
128
+ env_cfg.seed = a.seed
129
+ CAM = a.cam_name or ("chase" if a.cam == "chase" else "front")
130
+ use_cam = a.cam != "none"
131
+ if use_cam:
132
+ import isaaclab.sim as sim_utils
133
+ from isaaclab.sensors import CameraCfg
134
+
135
+ import math
136
+
137
+ def look_quat_world(eye, tgt):
138
+ """xyzw quat, 'world' camera convention (+X forward, +Z up), looking from eye to tgt (no roll)."""
139
+ dx, dy, dz = (t - e for t, e in zip(tgt, eye))
140
+ yaw, pitch = math.atan2(dy, dx), math.atan2(-dz, math.hypot(dx, dy))
141
+ sz, cz, sy, cy = math.sin(yaw / 2), math.cos(yaw / 2), math.sin(pitch / 2), math.cos(pitch / 2)
142
+ return (-sz * sy, cz * sy, sz * cy, cz * cy)
143
+
144
+ EYE = [float(v) for v in (a.eye or ("1.8,-2.6,0.6" if a.cam == "chase" else "1.2,0,0.8")).split(",")]
145
+ TGT = [float(v) for v in a.target.split(",")]
146
+ parent = "{ENV_REGEX_NS}/" + (a.attach if a.cam == "chase" else "")
147
+ # NB: Camera.set_world_poses[_from_view] writes Fabric poses the RTX render does not pick up in
148
+ # Isaac Lab 3.0.0rc1 (camera stays at its spawn pose) -> static offsets on a parent prim instead.
149
+ setattr(
150
+ env_cfg.scene,
151
+ "strands_cam",
152
+ CameraCfg(
153
+ prim_path=parent.rstrip("/") + "/StrandsCam",
154
+ update_period=0.0,
155
+ height=a.height,
156
+ width=a.width,
157
+ data_types=["rgb"],
158
+ spawn=sim_utils.PinholeCameraCfg(focal_length=18.0, clipping_range=(0.02, 50.0)),
159
+ offset=CameraCfg.OffsetCfg(pos=tuple(EYE), rot=look_quat_world(EYE, TGT), convention="world"),
160
+ ),
161
+ )
162
+ largs = {"device": "cuda:0", "headless": True, "enable_cameras": use_cam}
163
+ meta: dict = {
164
+ "task": a.task, "checkpoint": a.checkpoint, "episodes_requested": N, "frames": a.frames,
165
+ "overrides": a.override, "cam": a.cam, "cam_name": CAM, "res": [a.width, a.height],
166
+ "play_mode": not a.no_play_mode, "seed": a.seed, "cmd": " ".join(map(str, sys.orig_argv)),
167
+ }
168
+ t0 = time.time()
169
+
170
+ from strands_robots.policies.base import Policy # noqa: E402
171
+
172
+
173
+ class RslRlJitPolicy(Policy):
174
+ """strands Policy over an Isaac Lab-exported rsl_rl TorchScript actor (obs normalizer + ELU MLP).
175
+
176
+ observation_dict must carry "policy_obs": the concatenated actor observation groups (1-D).
177
+ Returns a 1-step chunk [{action_name: value}]. Adapter exists because create_policy("rl")
178
+ rebuilds strands' Tanh actor and cannot load rsl_rl weights (IL-X-006).
179
+ """
180
+
181
+ def __init__(self, jit_path: str, action_names: list[str], device: str = "cpu"):
182
+ self.net = torch.jit.load(jit_path, map_location=device).eval()
183
+ self.device = device
184
+ self.action_names = list(action_names)
185
+ self.robot_state_keys: list[str] = []
186
+
187
+ def set_robot_state_keys(self, robot_state_keys: list[str]) -> None:
188
+ self.robot_state_keys = list(robot_state_keys)
189
+
190
+ @property
191
+ def provider_name(self) -> str: # type: ignore[override]
192
+ return "isaaclab_rsl_rl_jit"
193
+
194
+ def reset(self) -> None:
195
+ self.net.reset()
196
+
197
+ async def get_actions(self, observation_dict, instruction, **kwargs):
198
+ x = torch.as_tensor(np.asarray(observation_dict["policy_obs"], dtype=np.float32), device=self.device)
199
+ with torch.inference_mode():
200
+ y = self.net(x.unsqueeze(0))[0].cpu().numpy()
201
+ return [{n: float(v) for n, v in zip(self.action_names, y)}]
202
+
203
+
204
+ with launch_simulation(env_cfg, largs):
205
+ from rsl_rl.runners import OnPolicyRunner
206
+
207
+ from isaaclab_rl.rsl_rl import RslRlVecEnvWrapper, handle_deprecated_rsl_rl_cfg
208
+ import importlib.metadata as md
209
+
210
+ agent_cfg = handle_deprecated_rsl_rl_cfg(agent_cfg, md.version("rsl-rl-lib"))
211
+ genv = gym.make(a.task, cfg=env_cfg)
212
+ env = RslRlVecEnvWrapper(genv, clip_actions=agent_cfg.clip_actions)
213
+ u = env.unwrapped
214
+ runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=None, device="cuda:0")
215
+ runner.load(a.checkpoint)
216
+ exp_dir = os.path.join(os.path.dirname(a.checkpoint), "exported")
217
+ runner.export_policy_to_jit(path=exp_dir, filename="policy.pt")
218
+ try:
219
+ runner.export_policy_to_onnx(path=exp_dir, filename="policy.onnx")
220
+ except Exception as e: # noqa: BLE001
221
+ meta["onnx_error"] = f"{type(e).__name__}: {e}"[:300]
222
+ gpol = runner.alg.get_policy()
223
+ obs_groups = list(getattr(gpol, "obs_groups", ["policy"]))
224
+ meta["actor_obs_groups"] = obs_groups
225
+ robot = next(iter(u.scene.articulations.values()))
226
+ jn = list(robot.joint_names)
227
+ adim = int(env.num_actions)
228
+ names: list[str] = []
229
+ am = getattr(u, "action_manager", None)
230
+ if am is not None:
231
+ for tname, term in am._terms.items():
232
+ jj = list(getattr(term, "_joint_names", []) or [])
233
+ names += [f"{tname}.{j}" for j in jj] if len(jj) == term.action_dim else [f"{tname}.{k}" for k in range(term.action_dim)]
234
+ if len(names) != adim:
235
+ idx = getattr(u, "actuated_dof_indices", None)
236
+ names = [f"act.{jn[i]}" for i in idx] if idx is not None and len(idx) == adim else [f"a{k:02d}" for k in range(adim)]
237
+ pol = RslRlJitPolicy(os.path.join(exp_dir, "policy.pt"), names)
238
+ pol.set_robot_state_keys(jn)
239
+ fps = int(round(1.0 / u.step_dt))
240
+ meta.update(joint_names=jn, action_names=names, action_dim=adim, fps=fps, step_dt=u.step_dt,
241
+ env_build_s=round(time.time() - t0, 1))
242
+
243
+ obs = env.get_observations()
244
+ pobs = torch.cat([obs[g] for g in obs_groups], dim=-1)
245
+ D = int(pobs.shape[-1])
246
+ meta["policy_obs_dim"] = D
247
+ print(f"[record] env ready {meta['env_build_s']}s joints={len(jn)} act={adim} obs={D} fps={fps}")
248
+ # consistency: strands-wrapped JIT vs rsl_rl inference policy on the same obs
249
+ with torch.inference_mode():
250
+ ref = runner.get_inference_policy(device="cuda:0")(obs)[0].cpu().numpy()
251
+ got = np.array(list(pol.get_actions_sync({"policy_obs": pobs[0].cpu().numpy()}, "")[0].values()))
252
+ meta["jit_vs_rslrl_max_abs"] = float(np.abs(ref - got).max())
253
+
254
+ from strands_robots.dataset_recorder import DatasetRecorder
255
+
256
+ task_str = a.task_str or f"{a.task}: trained rsl_rl PPO policy rollout"
257
+ shutil.rmtree(a.root, ignore_errors=True)
258
+ os.makedirs(os.path.dirname(os.path.abspath(a.root)), exist_ok=True)
259
+ rec = DatasetRecorder.create(
260
+ repo_id=a.repo_id, fps=fps, robot_type=a.robot_type or a.task, joint_names=jn, action_names=names,
261
+ camera_keys=[CAM] if use_cam else None, camera_dims={CAM: (a.height, a.width)} if use_cam else None,
262
+ extra_state_specs=[("policy_obs", [str(k) for k in range(D)]), ("root_pos", ["x", "y", "z"]),
263
+ ("root_quat", ["x", "y", "z", "w"])],
264
+ task=task_str, root=a.root, use_videos=use_cam, overwrite=True,
265
+ )
266
+ def aim():
267
+ pass
268
+
269
+ buf: list[list] = [[] for _ in range(N)] # per env: (obs_dict, act_dict)
270
+ alive = np.ones(N, bool)
271
+ ret = np.zeros(N)
272
+ lens = np.zeros(N, int)
273
+ term_reason = ["frames"] * N
274
+ pol_s = step_s = 0.0
275
+ pol.reset()
276
+ aim()
277
+ with torch.inference_mode(): # LSTM actuator nets (AnymalD) keep inference tensors -> reset inside the same mode
278
+ env.step(torch.zeros(N, adim, device=u.device)) # warm the renderer
279
+ obs, _ = env.reset() if hasattr(env, "reset") else (env.get_observations(), None)
280
+ obs = env.get_observations()
281
+ for f in range(a.frames):
282
+ aim()
283
+ if f in (0, 1, 10) and use_cam:
284
+ cd = u.scene["strands_cam"].data
285
+ pw = cd.pos_w.torch if hasattr(cd.pos_w, "torch") else cd.pos_w
286
+ rpw = robot.data.root_pos_w.torch if hasattr(robot.data.root_pos_w, "torch") else robot.data.root_pos_w
287
+ meta.setdefault("debug", []).append({"f": f, "cam_pos_w0": pw[0].tolist(), "root_pos_w0": rpw[0].tolist()})
288
+ pobs = torch.cat([obs[g] for g in obs_groups], dim=-1)
289
+ pc = pobs.cpu().numpy()
290
+ q = (robot.data.joint_pos.torch if hasattr(robot.data.joint_pos, "torch") else robot.data.joint_pos).cpu().numpy()
291
+ rp = robot.data.root_pos_w
292
+ rp = (rp.torch if hasattr(rp, "torch") else rp).cpu().numpy() - u.scene.env_origins.cpu().numpy()
293
+ rq = robot.data.root_quat_w
294
+ rq = (rq.torch if hasattr(rq, "torch") else rq).cpu().numpy()
295
+ img = None
296
+ if use_cam:
297
+ im = u.scene["strands_cam"].data.output["rgb"]
298
+ im = im.torch if hasattr(im, "torch") else im
299
+ img = im[..., :3].to(torch.uint8).cpu().numpy()
300
+ ts = time.time()
301
+ acts = np.zeros((N, adim), np.float32)
302
+ for i in range(N):
303
+ ad = pol.get_actions_sync({"policy_obs": pc[i]}, task_str)[0]
304
+ acts[i] = [ad[n] for n in names]
305
+ pol_s += time.time() - ts
306
+ for i in range(N):
307
+ if not alive[i]:
308
+ continue
309
+ ob = {n: float(q[i, k]) for k, n in enumerate(jn)}
310
+ ob.update(policy_obs=pc[i].astype(np.float32), root_pos=rp[i].astype(np.float32), root_quat=rq[i].astype(np.float32))
311
+ if img is not None:
312
+ ob[CAM] = img[i]
313
+ buf[i].append((ob, {n: float(acts[i, k]) for k, n in enumerate(names)}))
314
+ lens[i] += 1
315
+ ts = time.time()
316
+ with torch.inference_mode():
317
+ obs, rew, dones, extras = env.step(torch.as_tensor(acts, device=u.device))
318
+ step_s += time.time() - ts
319
+ r = rew.cpu().numpy()
320
+ d = dones.cpu().numpy().astype(bool)
321
+ ret[alive] += r[alive]
322
+ for i in np.where(d & alive)[0]:
323
+ alive[i] = False
324
+ to = extras.get("time_outs")
325
+ term_reason[i] = "time_out" if (to is not None and bool(to[i])) else "terminated"
326
+ if not alive.any():
327
+ break
328
+ print("[record] lens", lens.tolist(), term_reason, flush=True)
329
+ meta.update(policy_ms_per_step_all_envs=round(1000 * pol_s / max(1, f + 1), 2),
330
+ env_ms_per_step=round(1000 * step_s / max(1, f + 1), 2))
331
+ # dump a 2x2 playback grid video (envs 0..3) + episode 0 video for model cards
332
+ if use_cam:
333
+ import imageio.v2 as iio
334
+
335
+ base = a.root.rstrip("/")
336
+ k = min(4, N)
337
+ show = [int(i) for i in np.argsort(-lens, kind="stable")[:k]] # the 4 longest episodes
338
+ meta["playback_envs"] = show
339
+ T = int(min(lens[show]))
340
+ w = iio.get_writer(base + "_playback.mp4", fps=fps, codec="libx264", quality=7, macro_block_size=8)
341
+ for t in range(T):
342
+ ims = [buf[i][t][0][CAM] for i in show] + [np.zeros_like(buf[0][0][0][CAM])] * (4 - k)
343
+ w.append_data(np.concatenate([np.concatenate(ims[:2], 1), np.concatenate(ims[2:4], 1)], 0))
344
+ w.close()
345
+ iio.imwrite(base + "_frame.png", buf[show[0]][min(T - 1, 60)][0][CAM])
346
+ meta["cam_mean"] = float(np.mean([buf[i][-1][0][CAM].mean() for i in range(N) if buf[i]]))
347
+ ts = time.time()
348
+ kept = []
349
+ for i in range(N):
350
+ if lens[i] < a.min_len:
351
+ continue
352
+ for ob, ac in buf[i]:
353
+ rec.add_frame(ob, ac, task=task_str, camera_keys=[CAM] if use_cam else None)
354
+ rec.save_episode()
355
+ kept.append(i)
356
+ buf[i] = []
357
+ rec.finalize()
358
+ meta.update(record_s=round(time.time() - ts, 1), episodes_saved=len(kept), kept_envs=kept,
359
+ episode_len=lens.tolist(), episode_return=[round(float(x), 3) for x in ret],
360
+ episode_end=term_reason, mean_return=round(float(ret.mean()), 3),
361
+ total_frames=int(lens[kept].sum()), total_wall_s=round(time.time() - t0, 1))
362
+ print("[record] RESULT " + json.dumps(meta, default=str))
363
+ json.dump(meta, open(a.root.rstrip("/") + "_record.json", "w"), indent=1, default=str)
364
+ sys.stdout.flush()
365
+ genv.close() # Kit exits the process here; verify runs in a fresh process
playback.gif ADDED

Git LFS Details

  • SHA256: 347d93a114a3116ce19cc7ee8f3908d09c13f841832d48cfce87dd8f176837aa
  • Pointer size: 131 Bytes
  • Size of remote file: 523 kB
playback.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8155f50c74b5d18530e85fa65cf4201a68c2f5531d9febca30dde3708870839f
3
+ size 449349