T-K-233 commited on
Commit
c42c446
·
verified ·
1 Parent(s): 9732ee2

Add files using upload-large-folder tool

Browse files
scripts/common.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared helpers for the LAFAN1 → Lite retargeting pipeline.
2
+
3
+ Conventions:
4
+ - Quaternions are scalar-first WXYZ, unit-norm, ``w >= 0``. The only non-WXYZ
5
+ appearance is the LAFAN1 CSV row, converted exactly once in
6
+ :func:`load_lafan_csv`.
7
+ - The Lite ``joint_pos`` column order is whatever MuJoCo emits from the MJCF
8
+ (:func:`lite_joint_names`); we never hardcode it.
9
+ """
10
+
11
+ import re
12
+ from pathlib import Path
13
+
14
+ import mujoco
15
+ import numpy as np
16
+
17
+ # ── Constants ─────────────────────────────────────────────────────────────────
18
+
19
+ FPS: int = 30
20
+ LAFAN_REPO_ID: str = "lvhaidong/LAFAN1_Retargeting_Dataset"
21
+ LITE_DATASET_REPO_ID: str = "Berkeley-Humanoids/Lite-Motion-Tracking-Dataset"
22
+ LITE_TASK_NAME: str = "track_lafan1"
23
+
24
+ # End-effector body names — Lite (matches the MJCF) and the G1 URDF after MuJoCo
25
+ # import (the ``*_rubber_hand`` link is fixed-jointed and fuses into
26
+ # ``*_wrist_yaw_link``, which is the last named body in each arm chain).
27
+ LITE_FOOT_BODIES: tuple[str, str] = ("left_foot", "right_foot")
28
+ LITE_HAND_BODIES: tuple[str, str] = ("left_hand", "right_hand")
29
+ G1_FOOT_BODIES: tuple[str, str] = ("left_ankle_roll_link", "right_ankle_roll_link")
30
+ G1_HAND_BODIES: tuple[str, str] = ("left_wrist_yaw_link", "right_wrist_yaw_link")
31
+
32
+ LAFAN_G1_URDF_RELPATH: str = "robot_description/g1/g1_29dof_rev_1_0.urdf"
33
+
34
+ # Authoritative LAFAN1 G1 CSV joint order. Every CSV row is
35
+ # ``[base_x, base_y, base_z, base_qx, base_qy, base_qz, base_qw,
36
+ # *G1_LAFAN_JOINT_NAMES]`` at 30 FPS.
37
+ G1_LAFAN_JOINT_NAMES: tuple[str, ...] = (
38
+ "left_hip_pitch_joint",
39
+ "left_hip_roll_joint",
40
+ "left_hip_yaw_joint",
41
+ "left_knee_joint",
42
+ "left_ankle_pitch_joint",
43
+ "left_ankle_roll_joint",
44
+ "right_hip_pitch_joint",
45
+ "right_hip_roll_joint",
46
+ "right_hip_yaw_joint",
47
+ "right_knee_joint",
48
+ "right_ankle_pitch_joint",
49
+ "right_ankle_roll_joint",
50
+ "waist_yaw_joint",
51
+ "waist_roll_joint",
52
+ "waist_pitch_joint",
53
+ "left_shoulder_pitch_joint",
54
+ "left_shoulder_roll_joint",
55
+ "left_shoulder_yaw_joint",
56
+ "left_elbow_joint",
57
+ "left_wrist_roll_joint",
58
+ "left_wrist_pitch_joint",
59
+ "left_wrist_yaw_joint",
60
+ "right_shoulder_pitch_joint",
61
+ "right_shoulder_roll_joint",
62
+ "right_shoulder_yaw_joint",
63
+ "right_elbow_joint",
64
+ "right_wrist_roll_joint",
65
+ "right_wrist_pitch_joint",
66
+ "right_wrist_yaw_joint",
67
+ )
68
+
69
+ # G1 joint → (Lite joint, sign, offset_rad). Step-1 retargeting applies
70
+ # ``lite_q[t] = sign * g1_q[t] + offset`` per joint.
71
+ #
72
+ # Decisions baked into this table:
73
+ # - Legs: chain order and axes match; sign=+1, offset=0.
74
+ # - Waist: chain order DIFFERS (G1 yaw→roll→pitch vs Lite yaw→pitch→roll),
75
+ # but axes match by *name*, so we map by name and accept the small
76
+ # rotation-order approximation when multiple waist joints are non-zero.
77
+ # - Shoulders + elbows: chain order matches; offsets bring G1's arms-down
78
+ # rest pose to Lite's T-pose rest (±π/2 on shoulder_roll and elbow).
79
+ # - Wrists: chain order DIFFERS (G1 roll→pitch→yaw vs Lite yaw→roll→pitch)
80
+ # but the physical 3-DoF wrist is the same, so we map by *position in
81
+ # the chain* (G1 wrist_roll → Lite wrist_yaw, etc.). Sign of the first
82
+ # wrist DoF is -1 because the URDFs picked opposite positive directions.
83
+ G1_TO_LITE: dict[str, tuple[str, int, float]] = {
84
+ # Legs (12)
85
+ "left_hip_pitch_joint": ("left_hip_pitch", +1, 0.0),
86
+ "left_hip_roll_joint": ("left_hip_roll", +1, 0.0),
87
+ "left_hip_yaw_joint": ("left_hip_yaw", +1, 0.0),
88
+ "left_knee_joint": ("left_knee_pitch", +1, 0.0),
89
+ "left_ankle_pitch_joint": ("left_ankle_pitch", +1, 0.0),
90
+ "left_ankle_roll_joint": ("left_ankle_roll", +1, 0.0),
91
+ "right_hip_pitch_joint": ("right_hip_pitch", +1, 0.0),
92
+ "right_hip_roll_joint": ("right_hip_roll", +1, 0.0),
93
+ "right_hip_yaw_joint": ("right_hip_yaw", +1, 0.0),
94
+ "right_knee_joint": ("right_knee_pitch", +1, 0.0),
95
+ "right_ankle_pitch_joint": ("right_ankle_pitch", +1, 0.0),
96
+ "right_ankle_roll_joint": ("right_ankle_roll", +1, 0.0),
97
+ # Waist (3)
98
+ "waist_yaw_joint": ("waist_yaw", +1, 0.0),
99
+ "waist_roll_joint": ("waist_roll", +1, 0.0),
100
+ "waist_pitch_joint": ("waist_pitch", +1, 0.0),
101
+ # Arms (14) — left
102
+ "left_shoulder_pitch_joint": ("left_shoulder_pitch", +1, 0.0),
103
+ "left_shoulder_roll_joint": ("left_shoulder_roll", +1, -1.5708),
104
+ "left_shoulder_yaw_joint": ("left_shoulder_yaw", +1, 0.0),
105
+ "left_elbow_joint": ("left_elbow_pitch", +1, -1.5708),
106
+ "left_wrist_roll_joint": ("left_wrist_yaw", -1, 0.0),
107
+ "left_wrist_pitch_joint": ("left_wrist_roll", +1, 0.0),
108
+ "left_wrist_yaw_joint": ("left_wrist_pitch", +1, 0.0),
109
+ # Arms (14) — right
110
+ "right_shoulder_pitch_joint":("right_shoulder_pitch",+1, 0.0),
111
+ "right_shoulder_roll_joint": ("right_shoulder_roll", +1, +1.5708),
112
+ "right_shoulder_yaw_joint": ("right_shoulder_yaw", +1, 0.0),
113
+ "right_elbow_joint": ("right_elbow_pitch", +1, -1.5708),
114
+ "right_wrist_roll_joint": ("right_wrist_yaw", -1, 0.0),
115
+ "right_wrist_pitch_joint": ("right_wrist_roll", +1, 0.0),
116
+ "right_wrist_yaw_joint": ("right_wrist_pitch", +1, 0.0),
117
+ }
118
+
119
+
120
+ # ── Model loaders ─────────────────────────────────────────────────────────────
121
+
122
+
123
+ def load_lite_model() -> mujoco.MjModel:
124
+ """Load the Berkeley Lite humanoid MJCF via the Berkeley-Humanoids package."""
125
+ from robot_descriptions import load_asset
126
+
127
+ return mujoco.MjModel.from_xml_path(str(load_asset("robots/lite/mjcf/lite.xml")))
128
+
129
+
130
+ def load_g1_model(lafan_root: Path) -> mujoco.MjModel:
131
+ """Load the Unitree G1 URDF bundled in the downloaded LAFAN1 dataset.
132
+
133
+ The URDF declares ``<compiler meshdir="meshes"/>`` and also references
134
+ meshes as ``meshes/foo.STL`` — MuJoCo would concatenate to
135
+ ``meshes/meshes/foo.STL``. We rewrite meshdir to ``"."`` and supply the
136
+ mesh bytes through the ``assets`` dict so nothing touches the filesystem
137
+ a second time.
138
+ """
139
+ urdf = Path(lafan_root) / LAFAN_G1_URDF_RELPATH
140
+ if not urdf.exists():
141
+ raise FileNotFoundError(
142
+ f"G1 URDF not found at {urdf}. Run scripts/download_lafan.py first."
143
+ )
144
+ text = re.sub(r'meshdir="[^"]*"', 'meshdir="."', urdf.read_text())
145
+ assets = {f"meshes/{p.name}": p.read_bytes() for p in (urdf.parent / "meshes").glob("*.STL")}
146
+ return mujoco.MjModel.from_xml_string(text, assets=assets)
147
+
148
+
149
+ def joint_qpos_addr(model: mujoco.MjModel, joint_name: str) -> int:
150
+ """Index into ``data.qpos`` for a 1-DoF joint by name."""
151
+ jid = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_JOINT, joint_name)
152
+ if jid < 0:
153
+ raise KeyError(f"Joint {joint_name!r} not found in model")
154
+ return int(model.jnt_qposadr[jid])
155
+
156
+
157
+ def body_id(model: mujoco.MjModel, body_name: str) -> int:
158
+ """Body id for ``body_name``, raising if absent."""
159
+ bid = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_BODY, body_name)
160
+ if bid < 0:
161
+ raise KeyError(f"Body {body_name!r} not found in model")
162
+ return int(bid)
163
+
164
+
165
+ def lite_joint_names(model: mujoco.MjModel) -> tuple[str, ...]:
166
+ """All hinge joint names in the Lite model in MuJoCo's depth-first order.
167
+
168
+ Skips the free joint at index 0 if present. The result is the single
169
+ source of truth for the LeRobotDataset ``joint_pos`` column order.
170
+ """
171
+ names: list[str] = []
172
+ for jid in range(model.njnt):
173
+ if model.jnt_type[jid] == mujoco.mjtJoint.mjJNT_FREE:
174
+ continue
175
+ name = mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_JOINT, jid)
176
+ if name is None:
177
+ raise RuntimeError(f"Lite joint id {jid} has no name")
178
+ names.append(name)
179
+ return tuple(names)
180
+
181
+
182
+ # ── LAFAN1 CSV I/O ────────────────────────────────────────────────────────────
183
+
184
+
185
+ def load_lafan_csv(path: Path) -> dict[str, np.ndarray]:
186
+ """Read one LAFAN1 G1 CSV into base pose + joint positions.
187
+
188
+ On-disk format: headerless, 30 FPS, ``[base_xyz(3), base_quat_xyzw(4),
189
+ joint_pos(29)]`` per row. Converts XYZW → WXYZ and flips quaternion sign
190
+ so ``w >= 0``.
191
+
192
+ Returns:
193
+ Dict with ``base_pos`` ``(T, 3)``, ``base_quat_wxyz`` ``(T, 4)``,
194
+ ``g1_joint_pos`` ``(T, 29)`` — all float32. Joint columns follow
195
+ :data:`G1_LAFAN_JOINT_NAMES`.
196
+ """
197
+ raw = np.loadtxt(path, delimiter=",", dtype=np.float32)
198
+ expected_cols = 7 + len(G1_LAFAN_JOINT_NAMES)
199
+ if raw.ndim != 2 or raw.shape[1] != expected_cols:
200
+ raise ValueError(
201
+ f"{path}: expected {expected_cols} columns, got shape {raw.shape}"
202
+ )
203
+ base_quat = np.empty((raw.shape[0], 4), dtype=np.float32)
204
+ base_quat[:, 0] = raw[:, 6]
205
+ base_quat[:, 1:4] = raw[:, 3:6]
206
+ base_quat /= np.linalg.norm(base_quat, axis=1, keepdims=True)
207
+ base_quat[base_quat[:, 0] < 0] *= -1.0
208
+ return {
209
+ "base_pos": raw[:, 0:3],
210
+ "base_quat_wxyz": base_quat,
211
+ "g1_joint_pos": raw[:, 7:],
212
+ }
213
+
214
+
215
+ # ── Derivatives ───────────────────────────────────────────────────────────────
216
+
217
+
218
+ def finite_diff(x: np.ndarray, fps: int) -> np.ndarray:
219
+ """Central finite difference along axis 0."""
220
+ return np.gradient(x, 1.0 / fps, axis=0).astype(x.dtype, copy=False)
221
+
222
+
223
+ def angular_velocity_from_quat(q_wxyz: np.ndarray, fps: int) -> np.ndarray:
224
+ """World-frame angular velocity (rad/s) from a sequence of WXYZ quaternions.
225
+
226
+ Uses the central stencil ``omega = axis_angle(q[t+1] * q[t-1]^-1) / 2dt``;
227
+ endpoints are repeated to keep length T.
228
+ """
229
+ dt = 1.0 / fps
230
+ rel = _quat_mul(q_wxyz[2:], _quat_conj(q_wxyz[:-2]))
231
+ omega_mid = _axis_angle_from_quat(rel) / (2.0 * dt)
232
+ omega = np.empty((q_wxyz.shape[0], 3), dtype=q_wxyz.dtype)
233
+ omega[1:-1] = omega_mid
234
+ omega[0] = omega_mid[0]
235
+ omega[-1] = omega_mid[-1]
236
+ return omega
237
+
238
+
239
+ def _quat_mul(a: np.ndarray, b: np.ndarray) -> np.ndarray:
240
+ aw, ax, ay, az = a[..., 0], a[..., 1], a[..., 2], a[..., 3]
241
+ bw, bx, by, bz = b[..., 0], b[..., 1], b[..., 2], b[..., 3]
242
+ out = np.empty_like(a)
243
+ out[..., 0] = aw * bw - ax * bx - ay * by - az * bz
244
+ out[..., 1] = aw * bx + ax * bw + ay * bz - az * by
245
+ out[..., 2] = aw * by - ax * bz + ay * bw + az * bx
246
+ out[..., 3] = aw * bz + ax * by - ay * bx + az * bw
247
+ return out
248
+
249
+
250
+ def _quat_conj(q: np.ndarray) -> np.ndarray:
251
+ out = q.copy()
252
+ out[..., 1:] *= -1.0
253
+ return out
254
+
255
+
256
+ def _axis_angle_from_quat(q: np.ndarray) -> np.ndarray:
257
+ """WXYZ quaternion → rotation vector ``axis * angle``, shape ``(..., 3)``."""
258
+ w = np.clip(q[..., 0], -1.0, 1.0)
259
+ xyz = q[..., 1:]
260
+ sin_half = np.linalg.norm(xyz, axis=-1)
261
+ angle = 2.0 * np.arctan2(sin_half, w)
262
+ safe = sin_half > 1e-8
263
+ axis = np.zeros_like(xyz)
264
+ axis[safe] = xyz[safe] / sin_half[safe, None]
265
+ return axis * angle[..., None]
266
+
267
+
268
+ # ── LeRobotDataset feature schema ─────────────────────────────────────────────
269
+
270
+
271
+ def dataset_features(joint_count: int) -> dict:
272
+ """LeRobotDataset feature schema for the retargeted Lite motion dataset.
273
+
274
+ Six flat fields, scalar-first WXYZ for the base orientation, no ``action``
275
+ (this is a kinematic reference).
276
+ """
277
+ return {
278
+ "base_pos": {"dtype": "float32", "shape": (3,), "names": ["x", "y", "z"]},
279
+ "base_quat": {"dtype": "float32", "shape": (4,), "names": ["w", "x", "y", "z"]},
280
+ "base_lin_vel": {"dtype": "float32", "shape": (3,), "names": ["vx", "vy", "vz"]},
281
+ "base_ang_vel": {"dtype": "float32", "shape": (3,), "names": ["wx", "wy", "wz"]},
282
+ "joint_pos": {"dtype": "float32", "shape": (joint_count,), "names": None},
283
+ "joint_vel": {"dtype": "float32", "shape": (joint_count,), "names": None},
284
+ }
scripts/download_lafan.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Download the LAFAN1 G1 subset from the Hugging Face Hub.
2
+
3
+ Pulls only the G1 motion CSVs, the G1 URDF + meshes (needed by
4
+ ``visualize.py`` to render the source ghost), and dataset metadata.
5
+
6
+ Usage:
7
+ uv run scripts/download_lafan.py
8
+ uv run scripts/download_lafan.py --clip 'walk.*subject1'
9
+ uv run scripts/download_lafan.py --force
10
+ """
11
+
12
+ import re
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+ import tyro
18
+ from huggingface_hub import snapshot_download
19
+
20
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
21
+ from common import G1_LAFAN_JOINT_NAMES, LAFAN_REPO_ID # noqa: E402
22
+
23
+ CACHE_ROOT: Path = Path(__file__).resolve().parent.parent / ".cache" / "lafan1_g1"
24
+ ALLOW_PATTERNS: list[str] = [
25
+ "g1/*.csv",
26
+ "robot_description/g1/**",
27
+ "meta_data/**",
28
+ "README.md",
29
+ "LICENSE",
30
+ ]
31
+
32
+
33
+ def main(clip: str | None = None, force: bool = False) -> None:
34
+ """Download the LAFAN1 G1 subset into ``.cache/lafan1_g1/``.
35
+
36
+ Args:
37
+ clip: Regex; if given, the smoke check only inspects matching CSVs.
38
+ The download itself always pulls every G1 CSV — restricting at
39
+ ``snapshot_download`` would defeat the cache for later runs.
40
+ force: Re-download even if files already exist.
41
+ """
42
+ CACHE_ROOT.mkdir(parents=True, exist_ok=True)
43
+ local_path = Path(snapshot_download(
44
+ repo_id=LAFAN_REPO_ID,
45
+ repo_type="dataset",
46
+ local_dir=str(CACHE_ROOT),
47
+ allow_patterns=ALLOW_PATTERNS,
48
+ force_download=force,
49
+ ))
50
+
51
+ csvs = sorted((local_path / "g1").glob("*.csv"))
52
+ if clip is not None:
53
+ csvs = [p for p in csvs if re.search(clip, p.stem)]
54
+ if not csvs:
55
+ raise SystemExit(f"No G1 CSVs found under {local_path / 'g1'} (clip={clip!r}).")
56
+
57
+ raw = np.loadtxt(csvs[0], delimiter=",", dtype=np.float32)
58
+ expected = 7 + len(G1_LAFAN_JOINT_NAMES)
59
+ if raw.ndim != 2 or raw.shape[1] != expected:
60
+ raise SystemExit(
61
+ f"Schema check failed on {csvs[0]}: expected {expected} cols, got {raw.shape}"
62
+ )
63
+ print(f"LAFAN1 G1 subset → {local_path}")
64
+ print(f" csvs : {len(csvs)}")
65
+ print(f" sample : {csvs[0].name} ({raw.shape[0]} frames @ 30 FPS, {raw.shape[1]} cols)")
66
+
67
+
68
+ if __name__ == "__main__":
69
+ tyro.cli(main)
scripts/push_to_hub.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Push the local LeRobotDataset to the Hugging Face Hub.
2
+
3
+ Authenticate first (``hf auth login`` or ``export HF_TOKEN=hf_...``).
4
+ Uses :meth:`LeRobotDataset.push_to_hub` so the repo gets a LeRobot
5
+ auto-generated dataset card and a version tag.
6
+
7
+ Usage:
8
+ uv run scripts/push_to_hub.py
9
+ uv run scripts/push_to_hub.py --repo-id your-org/your-dataset --private
10
+ uv run scripts/push_to_hub.py --branch v0.1
11
+ """
12
+
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ import tyro
17
+
18
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
19
+ from common import LITE_DATASET_REPO_ID # noqa: E402
20
+
21
+ REPO_ROOT: Path = Path(__file__).resolve().parent.parent
22
+ TAGS: list[str] = [
23
+ "lerobot",
24
+ "humanoid",
25
+ "motion-capture",
26
+ "motion-tracking",
27
+ "berkeley-humanoids",
28
+ "lite",
29
+ "lafan1",
30
+ ]
31
+
32
+
33
+ def main(
34
+ repo_id: str = LITE_DATASET_REPO_ID,
35
+ private: bool = False,
36
+ branch: str | None = None,
37
+ ) -> None:
38
+ """Upload the local dataset to the HF Hub.
39
+
40
+ Args:
41
+ repo_id: Target dataset repo id ``{user_or_org}/{name}``. Must be a
42
+ location your authenticated account can write to.
43
+ private: If True, create the repo as private.
44
+ branch: Optional branch to push to (created from main if missing).
45
+ """
46
+ from lerobot.datasets import LeRobotDataset
47
+
48
+ if not (REPO_ROOT / "meta").exists() or not (REPO_ROOT / "data").exists():
49
+ raise SystemExit(
50
+ f"Expected meta/ and data/ under {REPO_ROOT}. "
51
+ f"Run scripts/retarget.py first."
52
+ )
53
+
54
+ dataset = LeRobotDataset(repo_id=repo_id, root=REPO_ROOT)
55
+ print(
56
+ f"Uploading {dataset.meta.total_episodes} episodes "
57
+ f"({dataset.meta.total_frames} frames @ {dataset.meta.fps} FPS) "
58
+ f"→ https://huggingface.co/datasets/{repo_id}"
59
+ )
60
+ # The dataset root *is* the repo root, so the folder also contains the
61
+ # LAFAN1 download cache, venv, build artefacts, etc. ``allow_patterns``
62
+ # restricts the upload to dataset content + reproduction sources
63
+ # (scripts, pyproject, instructions). ``scripts/*.py`` is intentionally
64
+ # not ``scripts/**`` so we don't accidentally publish ``__pycache__/``.
65
+ # ``upload_large_folder`` chunks the parquet payload into retryable
66
+ # batches — robust against transient network drops on the ~218 shards.
67
+ dataset.push_to_hub(
68
+ tags=TAGS,
69
+ license="cc-by-nc-4.0",
70
+ private=private,
71
+ branch=branch,
72
+ push_videos=False,
73
+ allow_patterns=[
74
+ "meta/**",
75
+ "data/**",
76
+ "scripts/*.py",
77
+ "pyproject.toml",
78
+ "INSTRUCTIONS.md",
79
+ ],
80
+ upload_large_folder=True,
81
+ )
82
+ print(f"Done. View at https://huggingface.co/datasets/{repo_id}")
83
+
84
+
85
+ if __name__ == "__main__":
86
+ tyro.cli(main)
scripts/retarget.py ADDED
@@ -0,0 +1,523 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Retarget LAFAN1 G1 motions to the Berkeley Lite humanoid.
2
+
3
+ Two-step pipeline per clip:
4
+
5
+ * **Step 1** — direct joint copy ``lite_q = sign * g1_q + offset`` using the
6
+ static :data:`common.G1_TO_LITE` table. Adds a constant pelvis-z shift so
7
+ Lite's feet stand on the ground.
8
+ * **Step 2** — per-frame ``mink`` IK that refines step 1 to match G1's
9
+ pelvis-local EE poses (feet + hands, position + orientation). The
10
+ per-DOF posture cost biases the solution toward step 1 so the refinement
11
+ is a *tweak*, not a rearrangement.
12
+
13
+ Output is a HuggingFace LeRobotDataset written at the repository root.
14
+
15
+ Usage:
16
+ uv run scripts/retarget.py
17
+ uv run scripts/retarget.py --clip 'walk1_subject1'
18
+ uv run scripts/retarget.py --validate-only
19
+ uv run scripts/retarget.py --workers 8 # parallel across clips
20
+ uv run scripts/retarget.py --workers -1 # use all CPU cores
21
+ """
22
+
23
+ import os
24
+ import re
25
+ import shutil
26
+ import sys
27
+ from concurrent.futures import ProcessPoolExecutor
28
+ from pathlib import Path
29
+
30
+ import mujoco
31
+ import numpy as np
32
+ import tyro
33
+ from tqdm import tqdm
34
+
35
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
36
+ from common import ( # noqa: E402
37
+ FPS,
38
+ G1_FOOT_BODIES,
39
+ G1_HAND_BODIES,
40
+ G1_LAFAN_JOINT_NAMES,
41
+ G1_TO_LITE,
42
+ LITE_DATASET_REPO_ID,
43
+ LITE_FOOT_BODIES,
44
+ LITE_HAND_BODIES,
45
+ LITE_TASK_NAME,
46
+ angular_velocity_from_quat,
47
+ body_id,
48
+ dataset_features,
49
+ finite_diff,
50
+ joint_qpos_addr,
51
+ lite_joint_names,
52
+ load_g1_model,
53
+ load_lafan_csv,
54
+ load_lite_model,
55
+ )
56
+
57
+ REPO_ROOT: Path = Path(__file__).resolve().parent.parent
58
+ LAFAN_ROOT: Path = REPO_ROOT / ".cache" / "lafan1_g1"
59
+ BUILD_ROOT: Path = REPO_ROOT / ".lerobot_build"
60
+ # LeRobotDataset.create refuses an existing destination, so the writer drops
61
+ # its meta/ + data/ tree into BUILD_ROOT and we move it up to REPO_ROOT on
62
+ # finalize.
63
+
64
+ # Validation frame stride for the EE-error summary.
65
+ SAMPLE_STRIDE: int = 50
66
+
67
+
68
+ # ── Step 1: direct copy with sign + offset ────────────────────────────────────
69
+
70
+
71
+ def _build_remap_indices(
72
+ lite_model: mujoco.MjModel,
73
+ lite_joint_addrs: np.ndarray,
74
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
75
+ """Parallel arrays ``(lite_col, g1_col, sign, offset)`` over mapped joints."""
76
+ addr_to_col = {int(a): i for i, a in enumerate(lite_joint_addrs.tolist())}
77
+ lite_cols, g1_cols, signs, offsets = [], [], [], []
78
+ for g1_col, g1_name in enumerate(G1_LAFAN_JOINT_NAMES):
79
+ entry = G1_TO_LITE.get(g1_name)
80
+ if entry is None:
81
+ continue
82
+ lite_name, sign, offset = entry
83
+ lite_cols.append(addr_to_col[joint_qpos_addr(lite_model, lite_name)])
84
+ g1_cols.append(g1_col)
85
+ signs.append(float(sign))
86
+ offsets.append(float(offset))
87
+ return (
88
+ np.asarray(lite_cols, dtype=np.int32),
89
+ np.asarray(g1_cols, dtype=np.int32),
90
+ np.asarray(signs, dtype=np.float32),
91
+ np.asarray(offsets, dtype=np.float32),
92
+ )
93
+
94
+
95
+ def _pelvis_z_offset(g1_model: mujoco.MjModel, lite_model: mujoco.MjModel) -> float:
96
+ """Difference in standing leg length between Lite and G1 (welded pelvis).
97
+
98
+ Both robots default with the pelvis at z=0 and feet hanging at negative z,
99
+ so ``-min(foot_z)`` is each robot's standing leg length; the difference
100
+ is the z-shift to apply to LAFAN1's base trajectory so Lite stays grounded.
101
+ """
102
+
103
+ def _leg_length(model: mujoco.MjModel, foot_names: tuple[str, str]) -> float:
104
+ data = mujoco.MjData(model)
105
+ mujoco.mj_kinematics(model, data)
106
+ return -min(float(data.xpos[body_id(model, n), 2]) for n in foot_names)
107
+
108
+ return _leg_length(lite_model, LITE_FOOT_BODIES) - _leg_length(g1_model, G1_FOOT_BODIES)
109
+
110
+
111
+ def step1_direct_remap(
112
+ motion: dict[str, np.ndarray],
113
+ lite_joint_addrs: np.ndarray,
114
+ lite_model: mujoco.MjModel,
115
+ z_offset: float,
116
+ ) -> dict[str, np.ndarray]:
117
+ """Apply ``lite_q = sign * g1_q + offset`` to every mapped joint.
118
+
119
+ Returns ``base_pos`` (with the pelvis-z shift), ``base_quat`` (WXYZ,
120
+ unchanged from the source), and a ``(T, 74)`` ``joint_pos`` in Lite MJCF
121
+ order. Joints with no G1 source (neck, fingers, ankle_yaw) stay at 0.
122
+ """
123
+ lite_cols, g1_cols, signs, offsets = _build_remap_indices(lite_model, lite_joint_addrs)
124
+ frames = motion["base_pos"].shape[0]
125
+ joint_pos = np.zeros((frames, lite_joint_addrs.shape[0]), dtype=np.float32)
126
+ joint_pos[:, lite_cols] = signs * motion["g1_joint_pos"][:, g1_cols] + offsets
127
+
128
+ base_pos = motion["base_pos"].astype(np.float32, copy=True)
129
+ base_pos[:, 2] += z_offset
130
+ return {
131
+ "base_pos": base_pos,
132
+ "base_quat": motion["base_quat_wxyz"].astype(np.float32),
133
+ "joint_pos": joint_pos,
134
+ }
135
+
136
+
137
+ # ── Step 2: per-frame IK refinement ────────────────────────────────────���──────
138
+
139
+ _LIMB_TOKENS: tuple[str, ...] = ("hip", "knee", "ankle", "shoulder", "elbow", "wrist")
140
+ _TRUNK_TOKENS: tuple[str, ...] = ("waist",)
141
+
142
+
143
+ def _posture_cost_vector(lite_model: mujoco.MjModel) -> np.ndarray:
144
+ """Per-DOF posture cost — three tiers so step 2 only *tweaks* step 1.
145
+
146
+ The PostureTask pulls each joint toward step 1 with cost ``c``; the EE
147
+ FrameTasks pull joints away with cost 1.0 + 1.0 (position + orientation).
148
+ Costs:
149
+
150
+ * ``1e3`` — locked. Neck, fingers, and ankle_yaw have no G1 source, so
151
+ we keep them at step 1's zero.
152
+ * ``10.0`` — stiff but adjustable. Waist rotates the torso (and head),
153
+ so a high cost prevents the IK from twisting the whole upper body to
154
+ satisfy hand targets; arm joints are recruited first.
155
+ * ``1.0`` — same magnitude as the EE tasks. Arms + legs get a balanced
156
+ trade-off; per-frame corrections come out small.
157
+ """
158
+ cost = np.full(lite_model.nv, 1e3, dtype=np.float64)
159
+ for jid in range(lite_model.njnt):
160
+ name = mujoco.mj_id2name(lite_model, mujoco.mjtObj.mjOBJ_JOINT, jid)
161
+ if not name:
162
+ continue
163
+ dof = int(lite_model.jnt_dofadr[jid])
164
+ if any(tok in name for tok in _LIMB_TOKENS):
165
+ cost[dof] = 1.0
166
+ elif any(tok in name for tok in _TRUNK_TOKENS):
167
+ cost[dof] = 10.0
168
+ return cost
169
+
170
+
171
+ def _rest_frame_conversions(
172
+ g1_model: mujoco.MjModel,
173
+ lite_model: mujoco.MjModel,
174
+ ) -> dict[str, np.ndarray]:
175
+ """Per-body constant ``R_conv`` such that ``R_target = R_g1_actual @ R_conv``.
176
+
177
+ Derivation: we want Lite's world-frame motion delta (relative to its
178
+ matched rest) to equal G1's world-frame motion delta (relative to G1
179
+ rest). Solving for the target orientation gives
180
+ ``R_target = R_g1_actual @ (R_g1_rest^-1 @ R_lite_matched_rest)``.
181
+ """
182
+ g1_data = mujoco.MjData(g1_model)
183
+ mujoco.mj_kinematics(g1_model, g1_data)
184
+ lite_data = mujoco.MjData(lite_model)
185
+ for _, (lite_name, _, offset) in G1_TO_LITE.items():
186
+ lite_data.qpos[joint_qpos_addr(lite_model, lite_name)] = offset
187
+ mujoco.mj_kinematics(lite_model, lite_data)
188
+
189
+ out: dict[str, np.ndarray] = {}
190
+ for lite_name, g1_name in zip(
191
+ (*LITE_FOOT_BODIES, *LITE_HAND_BODIES),
192
+ (*G1_FOOT_BODIES, *G1_HAND_BODIES),
193
+ strict=True,
194
+ ):
195
+ R_g1 = g1_data.xmat[body_id(g1_model, g1_name)].reshape(3, 3)
196
+ R_lite = lite_data.xmat[body_id(lite_model, lite_name)].reshape(3, 3)
197
+ out[lite_name] = R_g1.T @ R_lite
198
+ return out
199
+
200
+
201
+ def step2_ik_refine(
202
+ motion: dict[str, np.ndarray],
203
+ step1_joint_pos: np.ndarray,
204
+ g1_model: mujoco.MjModel,
205
+ lite_model: mujoco.MjModel,
206
+ lite_joint_addrs: np.ndarray,
207
+ iters: int = 15,
208
+ show_progress: bool = True,
209
+ ) -> np.ndarray:
210
+ """Refine step-1 joint positions to match G1's pelvis-local EE poses.
211
+
212
+ Per-frame IK is independent — each frame seeds from step 1 and converges
213
+ on its own. ``show_progress`` controls the inner tqdm bar; worker
214
+ processes set it to False so their bars don't interleave in the terminal.
215
+ """
216
+ import mink
217
+
218
+ g1_data = mujoco.MjData(g1_model)
219
+ g1_addrs = np.asarray(
220
+ [joint_qpos_addr(g1_model, n) for n in G1_LAFAN_JOINT_NAMES], dtype=np.int32
221
+ )
222
+ R_conv = _rest_frame_conversions(g1_model, lite_model)
223
+
224
+ configuration = mink.Configuration(lite_model)
225
+ foot_tasks = [
226
+ mink.FrameTask(name, "body", position_cost=1.0, orientation_cost=1.0, lm_damping=1.0)
227
+ for name in LITE_FOOT_BODIES
228
+ ]
229
+ hand_tasks = [
230
+ mink.FrameTask(name, "body", position_cost=1.0, orientation_cost=1.0, lm_damping=1.0)
231
+ for name in LITE_HAND_BODIES
232
+ ]
233
+ posture_task = mink.PostureTask(lite_model, cost=_posture_cost_vector(lite_model))
234
+ all_tasks = [*foot_tasks, *hand_tasks, posture_task]
235
+ limits = [mink.ConfigurationLimit(lite_model)]
236
+
237
+ ee_pairs = tuple(zip(
238
+ (*LITE_FOOT_BODIES, *LITE_HAND_BODIES),
239
+ (*G1_FOOT_BODIES, *G1_HAND_BODIES),
240
+ strict=True,
241
+ ))
242
+ out = step1_joint_pos.copy()
243
+ seed_qpos = np.zeros(lite_model.nq, dtype=np.float64)
244
+ frames = step1_joint_pos.shape[0]
245
+ frame_iter = tqdm(range(frames), desc=" IK", leave=False, unit="frame") if show_progress else range(frames)
246
+
247
+ for t in frame_iter:
248
+ g1_data.qpos[g1_addrs] = motion["g1_joint_pos"][t]
249
+ mujoco.mj_kinematics(g1_model, g1_data)
250
+ for task, (lite_name, g1_name) in zip([*foot_tasks, *hand_tasks], ee_pairs, strict=True):
251
+ bid = body_id(g1_model, g1_name)
252
+ mat = np.eye(4)
253
+ mat[:3, :3] = g1_data.xmat[bid].reshape(3, 3) @ R_conv[lite_name]
254
+ mat[:3, 3] = g1_data.xpos[bid]
255
+ task.set_target(mink.SE3.from_matrix(mat))
256
+
257
+ seed_qpos[lite_joint_addrs] = step1_joint_pos[t]
258
+ configuration.q[:] = seed_qpos
259
+ posture_task.set_target(seed_qpos.copy())
260
+ for _ in range(iters):
261
+ vel = mink.solve_ik(
262
+ configuration, all_tasks, 1.0, solver="daqp", damping=1e-1, limits=limits,
263
+ )
264
+ configuration.integrate_inplace(vel, 1.0)
265
+ out[t] = configuration.q[lite_joint_addrs]
266
+
267
+ return out
268
+
269
+
270
+ # ── Validation ────────────────────────────────────────────────────────────────
271
+
272
+
273
+ def _rotation_angle_error(R_a: np.ndarray, R_b: np.ndarray) -> float:
274
+ cos_theta = np.clip((np.trace(R_a @ R_b.T) - 1.0) * 0.5, -1.0, 1.0)
275
+ return float(np.arccos(cos_theta))
276
+
277
+
278
+ def validate_ee_tracking(
279
+ motion: dict[str, np.ndarray],
280
+ lite_joint_pos: np.ndarray,
281
+ g1_model: mujoco.MjModel,
282
+ lite_model: mujoco.MjModel,
283
+ lite_joint_addrs: np.ndarray,
284
+ ) -> None:
285
+ """Print per-EE position + rotation error vs. G1 at every SAMPLE_STRIDE frames.
286
+
287
+ Rotation error is measured as the angle of "motion delta from matched
288
+ rest" — each robot's EE rotation relative to its own matched rest.
289
+ Lite's matched rest is step 1 applied at G1 ``q = 0`` (arms at offsets).
290
+ """
291
+ g1_data = mujoco.MjData(g1_model)
292
+ lite_data = mujoco.MjData(lite_model)
293
+ g1_addrs = np.asarray(
294
+ [joint_qpos_addr(g1_model, n) for n in G1_LAFAN_JOINT_NAMES], dtype=np.int32
295
+ )
296
+
297
+ mujoco.mj_kinematics(g1_model, g1_data)
298
+ pairs = tuple(zip(
299
+ (*LITE_FOOT_BODIES, *LITE_HAND_BODIES),
300
+ (*G1_FOOT_BODIES, *G1_HAND_BODIES),
301
+ strict=True,
302
+ ))
303
+ rest_g1 = {g: g1_data.xmat[body_id(g1_model, g)].reshape(3, 3).copy() for _, g in pairs}
304
+
305
+ matched_rest = np.zeros(lite_model.nq, dtype=np.float64)
306
+ for _, (lite_name, _, offset) in G1_TO_LITE.items():
307
+ matched_rest[joint_qpos_addr(lite_model, lite_name)] = offset
308
+ lite_data.qpos[:] = matched_rest
309
+ mujoco.mj_kinematics(lite_model, lite_data)
310
+ rest_lite = {l: lite_data.xmat[body_id(lite_model, l)].reshape(3, 3).copy() for l, _ in pairs}
311
+
312
+ frames = lite_joint_pos.shape[0]
313
+ indices = list(range(0, frames, SAMPLE_STRIDE))
314
+ stats: dict[str, dict[str, list[float]]] = {l: {"pos": [], "rot": []} for l, _ in pairs}
315
+
316
+ for t in indices:
317
+ lite_data.qpos[lite_joint_addrs] = lite_joint_pos[t]
318
+ mujoco.mj_kinematics(lite_model, lite_data)
319
+ g1_data.qpos[g1_addrs] = motion["g1_joint_pos"][t]
320
+ mujoco.mj_kinematics(g1_model, g1_data)
321
+ for lname, gname in pairs:
322
+ lbid, gbid = body_id(lite_model, lname), body_id(g1_model, gname)
323
+ stats[lname]["pos"].append(float(np.linalg.norm(lite_data.xpos[lbid] - g1_data.xpos[gbid])))
324
+ R_l = lite_data.xmat[lbid].reshape(3, 3) @ rest_lite[lname].T
325
+ R_g = g1_data.xmat[gbid].reshape(3, 3) @ rest_g1[gname].T
326
+ stats[lname]["rot"].append(_rotation_angle_error(R_l, R_g))
327
+
328
+ print(f"\nEE tracking error across {len(indices)} frames (stride={SAMPLE_STRIDE}, total={frames}):")
329
+ print(f" {'body':<14s} {'pos mean':>9s} {'pos max':>9s} {'rot mean':>9s} {'rot max':>9s}")
330
+ for lname, _ in pairs:
331
+ pos = np.asarray(stats[lname]["pos"])
332
+ rot = np.asarray(stats[lname]["rot"])
333
+ print(
334
+ f" {lname:<14s} {pos.mean():>8.3f}m {pos.max():>8.3f}m "
335
+ f"{np.degrees(rot.mean()):>7.2f}° {np.degrees(rot.max()):>7.2f}°"
336
+ )
337
+
338
+
339
+ # ── Per-clip pipeline + LeRobotDataset writer ─────────────────────────────────
340
+
341
+
342
+ def _frame_records(
343
+ base_pos: np.ndarray,
344
+ base_quat: np.ndarray,
345
+ joint_pos: np.ndarray,
346
+ ) -> dict[str, np.ndarray]:
347
+ """Compose the six dataset-feature arrays from a per-clip trajectory."""
348
+ base_pos = base_pos.astype(np.float32, copy=False)
349
+ base_quat = base_quat.astype(np.float32, copy=False)
350
+ joint_pos = joint_pos.astype(np.float32, copy=False)
351
+ return {
352
+ "base_pos": base_pos,
353
+ "base_quat": base_quat,
354
+ "base_lin_vel": finite_diff(base_pos, FPS),
355
+ "base_ang_vel": angular_velocity_from_quat(base_quat, FPS).astype(np.float32),
356
+ "joint_pos": joint_pos,
357
+ "joint_vel": finite_diff(joint_pos, FPS),
358
+ }
359
+
360
+
361
+ # ── Multiprocess worker (across-clip parallelism) ─────────────────────────────
362
+
363
+ _WORKER_STATE: dict[str, object] = {}
364
+
365
+
366
+ def _worker_init() -> None:
367
+ """ProcessPoolExecutor initializer: compile MuJoCo models once per worker."""
368
+ g1_model = load_g1_model(LAFAN_ROOT)
369
+ lite_model = load_lite_model()
370
+ addrs = np.asarray(
371
+ [joint_qpos_addr(lite_model, n) for n in lite_joint_names(lite_model)], dtype=np.int32
372
+ )
373
+ _WORKER_STATE.update(
374
+ g1_model=g1_model,
375
+ lite_model=lite_model,
376
+ lite_joint_addrs=addrs,
377
+ z_offset=_pelvis_z_offset(g1_model, lite_model),
378
+ )
379
+
380
+
381
+ def _worker_retarget(args: tuple[str, bool, int]) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
382
+ """Retarget a single clip; returns ``(base_pos, base_quat, joint_pos)``."""
383
+ csv_path_str, do_ik, ik_iters = args
384
+ g1_model: mujoco.MjModel = _WORKER_STATE["g1_model"] # type: ignore[assignment]
385
+ lite_model: mujoco.MjModel = _WORKER_STATE["lite_model"] # type: ignore[assignment]
386
+ lite_joint_addrs: np.ndarray = _WORKER_STATE["lite_joint_addrs"] # type: ignore[assignment]
387
+ z_offset: float = _WORKER_STATE["z_offset"] # type: ignore[assignment]
388
+
389
+ motion = load_lafan_csv(Path(csv_path_str))
390
+ step1 = step1_direct_remap(motion, lite_joint_addrs, lite_model, z_offset)
391
+ joint_pos = step1["joint_pos"]
392
+ if do_ik:
393
+ joint_pos = step2_ik_refine(
394
+ motion, joint_pos, g1_model, lite_model, lite_joint_addrs,
395
+ iters=ik_iters, show_progress=False,
396
+ )
397
+ return step1["base_pos"], step1["base_quat"], joint_pos
398
+
399
+
400
+ # ── CLI ───────────────────────────────────────────────────────────────────────
401
+
402
+
403
+ def main(
404
+ repo_id: str = LITE_DATASET_REPO_ID,
405
+ clip: str | None = None,
406
+ ik: bool = True,
407
+ ik_iters: int = 15,
408
+ workers: int = 1,
409
+ validate_only: bool = False,
410
+ ) -> None:
411
+ """Retarget LAFAN1 G1 clips to Lite and write a LeRobotDataset.
412
+
413
+ Args:
414
+ repo_id: HF dataset repo id, recorded in dataset metadata.
415
+ clip: Optional regex to retarget only matching CSVs.
416
+ ik: If True, run step 2 IK to refine step 1. If False, output step 1 only.
417
+ ik_iters: Newton-step iterations per frame in step 2.
418
+ workers: Worker processes for across-clip parallelism. ``1`` (default)
419
+ keeps the sequential path with per-frame tqdm. ``-1`` uses every
420
+ CPU core. ``>1`` spawns a ``ProcessPoolExecutor`` and suppresses
421
+ inner tqdm bars to keep the terminal readable.
422
+ validate_only: Run on the first matching clip and stop without writing
423
+ the dataset. Prints the step-1 (and step-2 if ``ik=True``) EE error
424
+ table.
425
+ """
426
+ if workers == -1:
427
+ workers = os.cpu_count() or 1
428
+ # Each save_episode runs an HFDataset.map pass that prints its own bar
429
+ # — 218 of those interleave badly with our outer clip bar.
430
+ os.environ.setdefault("HF_DATASETS_DISABLE_PROGRESS_BARS", "1")
431
+
432
+ csvs = sorted((LAFAN_ROOT / "g1").glob("*.csv"))
433
+ if clip is not None:
434
+ csvs = [p for p in csvs if re.search(clip, p.stem)]
435
+ if not csvs:
436
+ raise SystemExit(
437
+ f"No CSVs to retarget under {LAFAN_ROOT / 'g1'} (clip={clip!r}). "
438
+ f"Run scripts/download_lafan.py first."
439
+ )
440
+
441
+ print("Loading models …")
442
+ g1_model = load_g1_model(LAFAN_ROOT)
443
+ lite_model = load_lite_model()
444
+ lite_jnames = lite_joint_names(lite_model)
445
+ lite_joint_addrs = np.asarray(
446
+ [joint_qpos_addr(lite_model, n) for n in lite_jnames], dtype=np.int32
447
+ )
448
+ z_offset = _pelvis_z_offset(g1_model, lite_model)
449
+ flipped = sum(1 for _, s, _ in G1_TO_LITE.values() if s < 0)
450
+ nonzero = sum(1 for _, _, off in G1_TO_LITE.values() if abs(off) > 1e-6)
451
+ print(f" G1 nq={g1_model.nq}, Lite nq={lite_model.nq}, joints={len(lite_jnames)}")
452
+ print(
453
+ f" {len(G1_TO_LITE)} joint pairs, {flipped} sign flips, "
454
+ f"{nonzero} nonzero offsets, pelvis z-offset={z_offset * 1000:.2f} mm"
455
+ )
456
+
457
+ if validate_only:
458
+ motion = load_lafan_csv(csvs[0])
459
+ step1 = step1_direct_remap(motion, lite_joint_addrs, lite_model, z_offset)
460
+ print(f"\nClip: {csvs[0].name} ({step1['joint_pos'].shape[0]} frames)")
461
+ print("\n=== Step 1 (direct copy with sign + offset) ===")
462
+ validate_ee_tracking(motion, step1["joint_pos"], g1_model, lite_model, lite_joint_addrs)
463
+ if ik:
464
+ step2 = step2_ik_refine(
465
+ motion, step1["joint_pos"], g1_model, lite_model, lite_joint_addrs,
466
+ iters=ik_iters,
467
+ )
468
+ print("\n=== Step 1 + Step 2 (per-frame IK refinement) ===")
469
+ validate_ee_tracking(motion, step2, g1_model, lite_model, lite_joint_addrs)
470
+ return
471
+
472
+ from lerobot.datasets import LeRobotDataset # deferred: heavy import
473
+
474
+ if BUILD_ROOT.exists():
475
+ shutil.rmtree(BUILD_ROOT)
476
+ dataset = LeRobotDataset.create(
477
+ repo_id=repo_id,
478
+ fps=FPS,
479
+ features=dataset_features(joint_count=len(lite_jnames)),
480
+ root=BUILD_ROOT,
481
+ robot_type="lite",
482
+ use_videos=False,
483
+ )
484
+
485
+ def _write_clip(base_pos: np.ndarray, base_quat: np.ndarray, joint_pos: np.ndarray) -> None:
486
+ records = _frame_records(base_pos, base_quat, joint_pos)
487
+ for t in range(records["base_pos"].shape[0]):
488
+ dataset.add_frame({"task": LITE_TASK_NAME, **{k: v[t] for k, v in records.items()}})
489
+ dataset.save_episode()
490
+
491
+ if workers > 1:
492
+ args_list = [(str(p), bool(ik), int(ik_iters)) for p in csvs]
493
+ with ProcessPoolExecutor(max_workers=workers, initializer=_worker_init) as executor:
494
+ for base_pos, base_quat, joint_pos in tqdm(
495
+ executor.map(_worker_retarget, args_list, chunksize=1),
496
+ total=len(csvs), desc=f"Clips (workers={workers})", unit="clip",
497
+ ):
498
+ _write_clip(base_pos, base_quat, joint_pos)
499
+ else:
500
+ for csv_path in tqdm(csvs, desc="Clips", unit="clip"):
501
+ motion = load_lafan_csv(csv_path)
502
+ step1 = step1_direct_remap(motion, lite_joint_addrs, lite_model, z_offset)
503
+ joint_pos = step1["joint_pos"]
504
+ if ik:
505
+ joint_pos = step2_ik_refine(
506
+ motion, joint_pos, g1_model, lite_model, lite_joint_addrs, iters=ik_iters,
507
+ )
508
+ _write_clip(step1["base_pos"], step1["base_quat"], joint_pos)
509
+
510
+ dataset.finalize()
511
+ for sub in ("meta", "data"):
512
+ src = BUILD_ROOT / sub
513
+ if src.exists():
514
+ dst = REPO_ROOT / sub
515
+ if dst.exists():
516
+ shutil.rmtree(dst)
517
+ shutil.move(str(src), str(dst))
518
+ shutil.rmtree(BUILD_ROOT, ignore_errors=True)
519
+ print(f"\nWrote dataset to {REPO_ROOT} ({len(csvs)} episodes)")
520
+
521
+
522
+ if __name__ == "__main__":
523
+ tyro.cli(main)
scripts/visualize.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Viser-based viewer for the retargeted Lite motion dataset.
2
+
3
+ Renders Lite (solid) alongside the source LAFAN1 G1 (alpha-blended ghost).
4
+ Mesh data comes straight from MuJoCo — no yourdfpy / trimesh dependency.
5
+ The GUI exposes an episode dropdown; switching episodes loads the new clip's
6
+ motion arrays on demand.
7
+
8
+ Usage:
9
+ uv run scripts/visualize.py
10
+ uv run scripts/visualize.py --episode-index 3 --port 8080
11
+ uv run scripts/visualize.py --no-ghost
12
+ """
13
+
14
+ import sys
15
+ import threading
16
+ import time
17
+ from pathlib import Path
18
+
19
+ import mujoco
20
+ import numpy as np
21
+ import tyro
22
+ import viser
23
+
24
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
25
+ from common import ( # noqa: E402
26
+ FPS,
27
+ G1_LAFAN_JOINT_NAMES,
28
+ LITE_DATASET_REPO_ID,
29
+ joint_qpos_addr,
30
+ lite_joint_names,
31
+ load_g1_model,
32
+ load_lafan_csv,
33
+ load_lite_model,
34
+ )
35
+
36
+ REPO_ROOT: Path = Path(__file__).resolve().parent.parent
37
+ LAFAN_ROOT: Path = REPO_ROOT / ".cache" / "lafan1_g1"
38
+
39
+
40
+ # ── Rotation helpers ──────────────────────────────────────────────────────────
41
+
42
+
43
+ def _rot_to_quat_wxyz(R: np.ndarray) -> np.ndarray:
44
+ """3x3 rotation matrix → WXYZ quaternion with ``w >= 0``."""
45
+ trace = R[0, 0] + R[1, 1] + R[2, 2]
46
+ if trace > 0.0:
47
+ s = np.sqrt(trace + 1.0) * 2.0
48
+ w = 0.25 * s
49
+ x = (R[2, 1] - R[1, 2]) / s
50
+ y = (R[0, 2] - R[2, 0]) / s
51
+ z = (R[1, 0] - R[0, 1]) / s
52
+ elif R[0, 0] > R[1, 1] and R[0, 0] > R[2, 2]:
53
+ s = np.sqrt(1.0 + R[0, 0] - R[1, 1] - R[2, 2]) * 2.0
54
+ w = (R[2, 1] - R[1, 2]) / s
55
+ x = 0.25 * s
56
+ y = (R[0, 1] + R[1, 0]) / s
57
+ z = (R[0, 2] + R[2, 0]) / s
58
+ elif R[1, 1] > R[2, 2]:
59
+ s = np.sqrt(1.0 + R[1, 1] - R[0, 0] - R[2, 2]) * 2.0
60
+ w = (R[0, 2] - R[2, 0]) / s
61
+ x = (R[0, 1] + R[1, 0]) / s
62
+ y = 0.25 * s
63
+ z = (R[1, 2] + R[2, 1]) / s
64
+ else:
65
+ s = np.sqrt(1.0 + R[2, 2] - R[0, 0] - R[1, 1]) * 2.0
66
+ w = (R[1, 0] - R[0, 1]) / s
67
+ x = (R[0, 2] + R[2, 0]) / s
68
+ y = (R[1, 2] + R[2, 1]) / s
69
+ z = 0.25 * s
70
+ q = np.array([w, x, y, z], dtype=np.float64)
71
+ if q[0] < 0:
72
+ q = -q
73
+ return q / np.linalg.norm(q)
74
+
75
+
76
+ def _quat_wxyz_to_rot(q: np.ndarray) -> np.ndarray:
77
+ w, x, y, z = float(q[0]), float(q[1]), float(q[2]), float(q[3])
78
+ return np.array(
79
+ [
80
+ [1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
81
+ [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
82
+ [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)],
83
+ ],
84
+ dtype=np.float64,
85
+ )
86
+
87
+
88
+ # ── Robot rendering ───────────────────────────────────────────────────────────
89
+
90
+
91
+ def _mesh_handles(
92
+ server: viser.ViserServer,
93
+ model: mujoco.MjModel,
94
+ prefix: str,
95
+ color: tuple[int, int, int],
96
+ opacity: float,
97
+ ) -> list[tuple[viser.MeshHandle, int]]:
98
+ """One viser mesh handle per ``mjGEOM_MESH`` geom in the model."""
99
+ handles: list[tuple[viser.MeshHandle, int]] = []
100
+ for gid in range(model.ngeom):
101
+ if model.geom_type[gid] != mujoco.mjtGeom.mjGEOM_MESH:
102
+ continue
103
+ mesh_id = int(model.geom_dataid[gid])
104
+ if mesh_id < 0:
105
+ continue
106
+ v0, vn = int(model.mesh_vertadr[mesh_id]), int(model.mesh_vertnum[mesh_id])
107
+ f0, fn = int(model.mesh_faceadr[mesh_id]), int(model.mesh_facenum[mesh_id])
108
+ handle = server.scene.add_mesh_simple(
109
+ name=f"{prefix}/g{gid}",
110
+ vertices=np.asarray(model.mesh_vert[v0 : v0 + vn], dtype=np.float32),
111
+ faces=np.asarray(model.mesh_face[f0 : f0 + fn], dtype=np.int32),
112
+ color=color,
113
+ opacity=opacity,
114
+ )
115
+ handles.append((handle, gid))
116
+ return handles
117
+
118
+
119
+ def _update_pose(
120
+ handles: list[tuple[viser.MeshHandle, int]],
121
+ data: mujoco.MjData,
122
+ base_pos: np.ndarray,
123
+ base_R: np.ndarray,
124
+ ) -> None:
125
+ """Push current MuJoCo geom poses to viser.
126
+
127
+ Both Lite and G1 are welded to world in their shipped descriptions, so
128
+ ``data.geom_xpos`` / ``geom_xmat`` are pelvis-local; we compose with the
129
+ LAFAN1 base transform to recover world coordinates.
130
+ """
131
+ for handle, gid in handles:
132
+ handle.position = base_pos + base_R @ data.geom_xpos[gid]
133
+ handle.wxyz = _rot_to_quat_wxyz(base_R @ data.geom_xmat[gid].reshape(3, 3))
134
+
135
+
136
+ # ── Dataset / CSV loading ─────────────────────────────────────────────────────
137
+
138
+
139
+ def _load_episode_lite(repo_id: str, root: Path, episode_index: int) -> dict[str, np.ndarray]:
140
+ """Load one Lite LeRobotDataset episode as plain arrays."""
141
+ from lerobot.datasets import LeRobotDataset
142
+
143
+ dataset = LeRobotDataset(repo_id=repo_id, root=root, episodes=[episode_index])
144
+ rows = dataset.hf_dataset.with_format("numpy")[:]
145
+ return {
146
+ "base_pos": np.asarray(rows["base_pos"], dtype=np.float64),
147
+ "base_quat": np.asarray(rows["base_quat"], dtype=np.float64),
148
+ "joint_pos": np.asarray(rows["joint_pos"], dtype=np.float64),
149
+ }
150
+
151
+
152
+ def _load_episode_g1(lafan_root: Path, episode_index: int) -> dict[str, np.ndarray]:
153
+ """Load the LAFAN1 G1 CSV paired with ``episode_index`` (sorted file order)."""
154
+ csvs = sorted((lafan_root / "g1").glob("*.csv"))
155
+ if not csvs:
156
+ raise SystemExit(f"No G1 CSVs under {lafan_root / 'g1'}. Run download_lafan.py.")
157
+ if episode_index >= len(csvs):
158
+ raise SystemExit(f"--episode-index {episode_index} out of range ({len(csvs)} clips).")
159
+ return load_lafan_csv(csvs[episode_index])
160
+
161
+
162
+ # ── Main ──────────────────────────────────────────────────────────────────────
163
+
164
+
165
+ def main(
166
+ episode_index: int = 0,
167
+ repo_id: str = LITE_DATASET_REPO_ID,
168
+ port: int = 8080,
169
+ ghost: bool = True,
170
+ ) -> None:
171
+ """Play one retargeted clip alongside its LAFAN1 source.
172
+
173
+ Args:
174
+ episode_index: Initial episode to load (switch later from the GUI).
175
+ repo_id: Repo identifier of the local LeRobotDataset.
176
+ port: viser HTTP port.
177
+ ghost: Render the source G1 alpha-blended on top of the Lite robot.
178
+ """
179
+ print("Loading models …")
180
+ lite_model = load_lite_model()
181
+ lite_data = mujoco.MjData(lite_model)
182
+ lite_addrs = np.asarray(
183
+ [joint_qpos_addr(lite_model, n) for n in lite_joint_names(lite_model)], dtype=np.int32
184
+ )
185
+
186
+ g1_model: mujoco.MjModel | None = None
187
+ g1_data: mujoco.MjData | None = None
188
+ g1_addrs: np.ndarray | None = None
189
+ if ghost:
190
+ g1_model = load_g1_model(LAFAN_ROOT)
191
+ g1_data = mujoco.MjData(g1_model)
192
+ g1_addrs = np.asarray(
193
+ [joint_qpos_addr(g1_model, n) for n in G1_LAFAN_JOINT_NAMES], dtype=np.int32
194
+ )
195
+
196
+ csvs = sorted((LAFAN_ROOT / "g1").glob("*.csv"))
197
+ if not csvs:
198
+ raise SystemExit(f"No G1 CSVs under {LAFAN_ROOT / 'g1'}. Run download_lafan.py.")
199
+ if not (0 <= episode_index < len(csvs)):
200
+ raise SystemExit(f"--episode-index {episode_index} out of range ({len(csvs)} clips).")
201
+ idx_width = len(str(len(csvs) - 1))
202
+ episode_labels: list[str] = [f"{i:0{idx_width}d}: {p.stem}" for i, p in enumerate(csvs)]
203
+
204
+ # Mutable state shared between GUI callbacks and the playback thread; the
205
+ # lock guards the swap during episode reload.
206
+ state: dict[str, object] = {"lite": None, "g1": None, "frames": 0}
207
+ state_lock = threading.Lock()
208
+
209
+ def load_episode(idx: int) -> None:
210
+ print(f"Loading episode {episode_labels[idx]} …")
211
+ lite_motion = _load_episode_lite(repo_id, REPO_ROOT, idx)
212
+ g1_motion = _load_episode_g1(LAFAN_ROOT, idx) if ghost else None
213
+ frames = lite_motion["base_pos"].shape[0]
214
+ if g1_motion is not None:
215
+ frames = min(frames, g1_motion["base_pos"].shape[0])
216
+ with state_lock:
217
+ state["lite"] = lite_motion
218
+ state["g1"] = g1_motion
219
+ state["frames"] = frames
220
+
221
+ load_episode(episode_index)
222
+
223
+ server = viser.ViserServer(port=port)
224
+ server.scene.add_grid("/grid", width=4.0, height=4.0)
225
+ lite_handles = _mesh_handles(server, lite_model, "/lite", (200, 200, 210), opacity=1.0)
226
+ g1_handles: list[tuple[viser.MeshHandle, int]] = []
227
+ if ghost:
228
+ assert g1_model is not None
229
+ g1_handles = _mesh_handles(server, g1_model, "/g1", (100, 180, 255), opacity=0.35)
230
+
231
+ episode_dropdown = server.gui.add_dropdown(
232
+ "episode", options=tuple(episode_labels), initial_value=episode_labels[episode_index]
233
+ )
234
+ slider = server.gui.add_slider(
235
+ "frame", min=0, max=int(state["frames"]) - 1, step=1, initial_value=0
236
+ )
237
+ play_btn = server.gui.add_button("play / pause")
238
+ speed = server.gui.add_slider("speed", min=0.1, max=2.0, step=0.1, initial_value=1.0)
239
+ playing = threading.Event()
240
+
241
+ @play_btn.on_click
242
+ def _(_event):
243
+ playing.clear() if playing.is_set() else playing.set()
244
+
245
+ def render_frame(t: int) -> None:
246
+ with state_lock:
247
+ lite_motion = state["lite"]
248
+ g1_motion = state["g1"]
249
+ lite_data.qpos[lite_addrs] = lite_motion["joint_pos"][t] # type: ignore[index]
250
+ mujoco.mj_kinematics(lite_model, lite_data)
251
+ _update_pose(
252
+ lite_handles, lite_data,
253
+ base_pos=lite_motion["base_pos"][t], # type: ignore[index]
254
+ base_R=_quat_wxyz_to_rot(lite_motion["base_quat"][t]), # type: ignore[index]
255
+ )
256
+ if g1_motion is None:
257
+ return
258
+ g1_data.qpos[g1_addrs] = g1_motion["g1_joint_pos"][t] # type: ignore[index]
259
+ mujoco.mj_kinematics(g1_model, g1_data)
260
+ _update_pose(
261
+ g1_handles, g1_data,
262
+ base_pos=g1_motion["base_pos"][t],
263
+ base_R=_quat_wxyz_to_rot(g1_motion["base_quat_wxyz"][t]),
264
+ )
265
+
266
+ render_frame(0)
267
+
268
+ def play_loop() -> None:
269
+ while True:
270
+ if playing.is_set():
271
+ frames = int(state["frames"])
272
+ next_frame = (int(slider.value) + 1) % frames
273
+ slider.value = next_frame
274
+ render_frame(next_frame)
275
+ time.sleep(1.0 / (FPS * float(speed.value)))
276
+ else:
277
+ time.sleep(0.05)
278
+
279
+ threading.Thread(target=play_loop, daemon=True).start()
280
+
281
+ @slider.on_update
282
+ def _(_event):
283
+ t = int(slider.value)
284
+ if t < int(state["frames"]):
285
+ render_frame(t)
286
+
287
+ @episode_dropdown.on_update
288
+ def _(_event):
289
+ was_playing = playing.is_set()
290
+ playing.clear()
291
+ load_episode(int(episode_dropdown.value.split(":", 1)[0]))
292
+ slider.max = int(state["frames"]) - 1
293
+ slider.value = 0
294
+ render_frame(0)
295
+ if was_playing:
296
+ playing.set()
297
+
298
+ print(f"\nviser listening on http://localhost:{port}")
299
+ print(" ctrl-c to exit")
300
+ try:
301
+ while True:
302
+ time.sleep(1.0)
303
+ except KeyboardInterrupt:
304
+ pass
305
+
306
+
307
+ if __name__ == "__main__":
308
+ tyro.cli(main)