#!/usr/bin/env python3 """Generate a point-to-point walking reference with the GEAR kinematic planner. SONIC is a tracker, not a planner: it follows a reference motion and cannot invent a gait. GEAR splits those roles, and the planner half lives in ``motionbricks`` (root + pose + VQ-VAE backbones plus the idle/walk clip library). This drives that planner toward a world xy target and writes the resulting MuJoCo ``qpos`` trajectory, which SONIC then tracks in ``g1`` mode. The planner is a self-contained kinematic rollout -- it conditions on the frames it generated itself, never on a physics robot -- so generating offline is equivalent to running it in the loop, and it keeps the heavy motionbricks dependency stack out of the Isaac Lab process. Runs in ``simulation/.venv-planner``, not the Isaac Lab venv: ./jobs/gen_walk_reference.sh --target 1.5 -0.35 """ from __future__ import annotations import argparse import os import sys from pathlib import Path from types import SimpleNamespace _PROJECT = Path(__file__).resolve().parents[2] _MB = _PROJECT / "third-party" / "GR00T-WholeBodyControl" / "motionbricks" if str(_MB) not in sys.path: sys.path.insert(0, str(_MB)) import numpy as np import torch as t def _parse_args() -> argparse.Namespace: p = argparse.ArgumentParser(description="GEAR planner walk reference for SONIC.") p.add_argument( "--target", type=float, nargs=2, default=(1.5, -0.35), metavar=("X", "Y"), help="world xy the pelvis should walk to; default is the WalkGrab object.", ) p.add_argument( "--standoff", type=float, default=0.85, help="stop this far short of --target along the approach ray, metres. The " "robot has to end up beside the object, not on top of it, and the planner " "coasts a variable 0.3-0.8 m past whatever goal it is given because it " "regenerates in multi-frame blocks. Check the reported final distance.", ) p.add_argument( "--stop-radius", type=float, default=0.35, help="switch the planner to idle once the root is this close to the " "stand-off point, metres.", ) p.add_argument("--max-seconds", type=float, default=12.0) p.add_argument( "--settle-seconds", type=float, default=1.0, help="extra idle time recorded after arrival so the reference ends standing.", ) p.add_argument("--mode", default="walk", choices=("walk", "slow_walk")) p.add_argument( "--device", default=None, help="default: cuda when a GPU is visible, else cpu (slow but works on a login node).", ) p.add_argument("--generate-dt", type=float, default=2.0) p.add_argument("--out", type=Path, default=None) return p.parse_args() def _build_agent(args: argparse.Namespace): """Instantiate the planner directly. ``motionbricks``' own ``navigation_demo`` is not reusable here: it builds a WASD controller that imports ``pynput``, which needs an X server and dies on a headless node. Everything below the controller is what we actually want. The checkpoints' ``hparams.yaml`` store skeleton and VQ-VAE paths relative to the motionbricks root, so the process has to sit there while they load. """ os.chdir(_MB) from motionbricks.exp_setup.experiment import test from motionbricks.motion_backbone.demo.full_agent import full_navigation_agent from motionbricks.motion_backbone.inference.motion_inference import motion_inference out_dir = _MB / "out" clips_ckpt = out_dir / "G1-clip.ckpt" if clips_ckpt.stat().st_size < 10_000: raise SystemExit( f"{clips_ckpt} is still a Git LFS pointer.\n" "run simulation/scripts/fetch_gear_lfs.sh first" ) conf_args = SimpleNamespace( result_dir=str(out_dir), data_root=str(_MB / "datasets"), explicit_dataset_folder=None, EXP="default", return_model_configs=True, # The clip library is cached in G1-clip.ckpt, so no motion dataset is # needed; asking for a dataloader here would require the training data. return_dataloader=False, ) if args.device == "cpu": # Two CUDA assumptions are baked into the training-time code path: # test() calls torch.cuda.set_device because the config said "gpu", and # the pose model torch.load()s its VQ-VAE checkpoint without a # map_location, so the CUDA-tagged storages fail to deserialize. # Neither matters for inference; both are neutralised just for the call. real_set_device, real_load = t.cuda.set_device, t.load def _cpu_load(*a, **kw): kw.setdefault("map_location", "cpu") return real_load(*a, **kw) t.cuda.set_device = lambda *a, **k: None t.load = _cpu_load try: models, confs = test(conf_args) finally: t.cuda.set_device, t.load = real_set_device, real_load else: models, confs = test(conf_args) for name in ("pose", "root"): state = t.load(confs[name].ckpt_path, map_location=args.device)["state_dict"] models[name].load_state_dict(state) inferencer = motion_inference(models, models["pose"].args, device=args.device) agent = full_navigation_agent( inferencer, None, device=args.device, speed_scale=[1.0, 1.0], skeleton_xml=str(_MB / "assets" / "skeletons" / "g1" / "g1.xml"), clips="G1", ckpt_path=str(clips_ckpt), reprocess_clips=False, val_dataloader=None, ).to(args.device) return agent, inferencer def main() -> None: args = _parse_args() if args.device is None: args.device = "cuda" if t.cuda.is_available() else "cpu" # Resolved before _build_agent chdirs into the motionbricks root. args.out = (args.out or (_PROJECT / "simulation" / "assets" / "walk_reference.npz")).resolve() from motionbricks.motion_backbone.demo.clips import clip_holder_G1 agent, inferencer = _build_agent(args) fps = int(inferencer.motion_rep.fps) min_tok = inferencer._args["min_tokens"] max_tok = inferencer._args["max_tokens"] clip_names = list(clip_holder_G1.CLIPS.keys()) walk_id = clip_names.index(args.mode) idle_id = clip_names.index("idle") def allowed_tokens(mode_name: str) -> t.Tensor: spec = clip_holder_G1.CLIPS[mode_name].get("allowed_pred_num_tokens") if spec is not None: return t.tensor(spec).view([1, -1]) return t.ones(max_tok - min_tok + 1, dtype=t.int).view([1, -1]) target = np.asarray(args.target, dtype=np.float64) # The planner is steered at the stand-off point; everything is still # reported against the object so the numbers mean what they say. approach = target / (np.linalg.norm(target) + 1e-9) goal = target - args.standoff * approach # Matches motionbricks' own demo: replan every 8 frames, times generate_dt. controller_dt = (8.0 / fps) * float(args.generate_dt) max_steps = int(args.max_seconds * fps) settle_steps = int(args.settle_seconds * fps) print(f"[planner] device={args.device} fps={fps} tokens=[{min_tok},{max_tok}]", flush=True) print(f"[planner] modes={clip_names}", flush=True) print( f"[planner] object={tuple(np.round(target, 3))} standoff={args.standoff} " f"goal={tuple(np.round(goal, 3))} stop_radius={args.stop_radius}", flush=True, ) agent.reset() frames: list[np.ndarray] = [] arrived_at: int | None = None last_movement = np.array([approach[0], approach[1], 0.0]) for step in range(max_steps): qpos = np.asarray(agent.get_next_frame(), dtype=np.float64) frames.append(qpos.copy()) delta = goal - qpos[:2] dist = float(np.linalg.norm(delta)) obj_dist = float(np.linalg.norm(target - qpos[:2])) if dist < args.stop_radius and arrived_at is None: arrived_at = step print( f"[planner] idling at step {step} ({step / fps:.2f}s), " f"{obj_dist:.3f} m from the object", flush=True, ) if arrived_at is not None and step - arrived_at >= settle_steps: break walking = arrived_at is None if walking: movement = np.array([delta[0], delta[1], 0.0]) / (dist + 1e-8) last_movement = movement else: # The planner coasts past the stand-off point, which flips the sign # of `delta`. Steering by it here would spin the robot 180 degrees # on the spot, so the approach heading is held instead. movement = last_movement # Always look at the object, never at the stand-off point, so the robot # finishes square to what it is about to reach for. to_object = target - qpos[:2] facing = np.array([to_object[0], to_object[1], 0.0]) facing /= np.linalg.norm(facing) + 1e-8 mode_id = walk_id if walking else idle_id mode_name = args.mode if walking else "idle" control = { "movement_direction": t.from_numpy(movement).float().view([1, -1]), "facing_direction": t.from_numpy(facing).float().view([1, -1]), "mode": t.tensor([mode_id]).view([1, -1]), "allowed_pred_num_tokens": allowed_tokens(mode_name), "context_mujoco_qpos": agent.get_context_mujoco_qpos(), } with t.no_grad(): agent.generate_new_frames(control, controller_dt) if step % (fps // 2) == 0: print( f" t={step / fps:5.2f}s root=({qpos[0]:+.3f},{qpos[1]:+.3f}) " f"to_object={obj_dist:.3f} mode={mode_name}", flush=True, ) qpos = np.stack(frames, axis=0) travelled = float(np.linalg.norm(qpos[-1, :2] - qpos[0, :2])) final_dist = float(np.linalg.norm(target - qpos[-1, :2])) print( f"[planner] {len(qpos)} frames ({len(qpos) / fps:.2f}s), travelled {travelled:.3f} m, " f"ends {final_dist:.3f} m from the object", flush=True, ) if arrived_at is None: print("[planner] WARNING never reached the stop radius", flush=True) out = args.out out.parent.mkdir(parents=True, exist_ok=True) np.savez( out, # (T, 36): root xyz, root quat wxyz, then 29 joints in MuJoCo order. qpos=qpos.astype(np.float32), fps=np.int32(fps), target=target.astype(np.float32), stop_radius=np.float32(args.stop_radius), arrived_frame=np.int32(-1 if arrived_at is None else arrived_at), ) print(f"[planner] wrote {out}", flush=True) if __name__ == "__main__": main()