File size: 10,854 Bytes
3f4bb1d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 | #!/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()
|