File size: 17,686 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 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 | #!/usr/bin/env python3
"""Roll out the released CoordEx WalkGrab policy on the v2d reconstructed object.
This is not SONIC and not ``V2D-G1-SonicManip``. CoordEx's actor consumes
Wuji proprio history, VAE prior means, cube/table poses, and fingertip forces,
and emits 28 residual latents. Those tensors do not exist on the 4-D wrist+grip
task, so the weights cannot be loaded there.
The checkpoint was trained with rsl-rl 2.x, whose ``OnPolicyRunner`` cannot read
this repo's rsl-rl 5.x config schema. The actor is therefore built and loaded
directly, and the env is stepped through its Gym API instead.
cd simulation
./jobs/coordex_v2d_play.sh --headless --video
"""
from __future__ import annotations
import argparse
import os
import pathlib
import sys
from math import prod
_PROJECT = pathlib.Path(__file__).resolve().parents[2]
_COORDEX = _PROJECT / "third-party" / "coordex"
_COORDEX_PKG = _COORDEX / "source" / "coordex"
for p in (_COORDEX_PKG, _PROJECT / "simulation" / "source"):
s = str(p)
if s not in sys.path:
sys.path.insert(0, s)
from isaaclab.app import AppLauncher
parser = argparse.ArgumentParser(
description="CoordEx WalkGrab policy on the v2d coffee-can (or exported URDF)."
)
parser.add_argument("--task", default="V2D-CoorDex-WalkGrab-Play-v0")
parser.add_argument(
"--checkpoint",
default=str(_COORDEX / "ckpts/locomanip/walkgrab_8k.pt"),
)
parser.add_argument(
"--body-prior-checkpoint",
default=str(_COORDEX / "ckpts/body_prior/walkgrab_10k.pt"),
)
parser.add_argument(
"--hand-prior-checkpoint",
default=str(_COORDEX / "ckpts/hand_prior/kinematic_wrist_16k.pt"),
)
parser.add_argument(
"--clip",
default="20200709_141754_836212060125",
help="reconstruction/runs/<clip> whose exported object.urdf goes on the table.",
)
parser.add_argument("--num_envs", type=int, default=1)
parser.add_argument("--max_steps", type=int, default=0, help="0 = one full episode.")
parser.add_argument("--video", action="store_true")
parser.add_argument(
"--video_length",
type=int,
default=0,
help="Recorded steps; 0 = whole run. Used when --video is set.",
)
parser.add_argument(
"--norm-eps",
type=float,
default=1.0e-2,
help="rsl-rl 2.x EmpiricalNormalization eps; the checkpoint was written with the default.",
)
AppLauncher.add_app_launcher_args(parser)
args_cli, hydra_args = parser.parse_known_args()
sys.argv = [sys.argv[0], *hydra_args]
# Read by g1_coordex_v2d_env_cfg.object_urdf() when the cfg is built.
os.environ["V2D_COORDEX_CLIP"] = args_cli.clip
if args_cli.video:
args_cli.enable_cameras = True
app_launcher = AppLauncher(args_cli)
simulation_app = app_launcher.app
import gymnasium as gym # noqa: E402
import torch # noqa: E402
from coordex.policies import ActorCriticCoordResidual # noqa: E402
from coordex.tasks.locomanip.constants import RIGHT_HAND_TIP_NAMES # noqa: E402
from isaaclab.utils.dict import print_dict # noqa: E402
from isaaclab_tasks.utils.hydra import hydra_task_config # noqa: E402
import v2d_sim.tasks.coordex_v2d # noqa: E402, F401
from v2d_sim.tasks.coordex_v2d.proxy_compat import apply_data_tensor_compat # noqa: E402
def _resolve_path(path: str | os.PathLike[str]) -> str:
candidate = pathlib.Path(path).expanduser()
if not candidate.is_absolute():
candidate = _COORDEX / candidate
candidate = candidate.resolve()
if not candidate.is_file():
raise FileNotFoundError(f"Checkpoint not found: {candidate}")
return str(candidate)
def _t(x):
"""Isaac Lab 6 hands back warp ProxyArray from ``.data``; CoordEx wants Tensors."""
return x.torch if hasattr(x, "torch") else x
def _term_dim_to_int(dim) -> int:
if isinstance(dim, int):
return int(dim)
if isinstance(dim, tuple):
return int(prod(dim))
return int(prod(int(value) for value in dim))
def _actor_obs_metadata(env) -> tuple[tuple[str, ...], list[int]]:
obs_mgr = getattr(env.unwrapped, "observation_manager", None)
if obs_mgr is None:
raise RuntimeError("CoordResidual policy requires a ManagerBased observation manager.")
names = tuple(obs_mgr._group_obs_term_names["policy"])
dims = [_term_dim_to_int(dim) for dim in obs_mgr._group_obs_term_dim["policy"]]
return names, dims
def _group_dim(env, group: str) -> int:
return int(prod(env.unwrapped.observation_manager.group_obs_dim[group]))
def _build_actor(env, agent_cfg, checkpoint: str, device: str):
"""Instantiate ActorCriticCoordResidual and load the rsl-rl 2.x checkpoint."""
policy_cfg = agent_cfg.policy
names, dims = _actor_obs_metadata(env)
num_actor_obs = _group_dim(env, "policy")
num_critic_obs = _group_dim(env, "critic")
num_actions = int(env.unwrapped.action_manager.total_action_dim)
model = ActorCriticCoordResidual(
num_actor_obs=num_actor_obs,
num_critic_obs=num_critic_obs,
num_actions=num_actions,
critic_hidden_dims=policy_cfg.critic_hidden_dims,
activation=policy_cfg.activation,
init_noise_std=policy_cfg.init_noise_std,
noise_std_type=policy_cfg.noise_std_type,
coord_trunk_hidden_dims=policy_cfg.coord_trunk_hidden_dims,
body_head_hidden_dims=policy_cfg.body_head_hidden_dims,
hand_head_hidden_dims=policy_cfg.hand_head_hidden_dims,
body_residual_scale=policy_cfg.body_residual_scale,
hand_residual_scale=policy_cfg.hand_residual_scale,
fixed_log_std=policy_cfg.fixed_log_std,
actor_obs_term_names=names,
actor_obs_term_dims=dims,
).to(device)
payload = torch.load(checkpoint, map_location=device, weights_only=False)
ckpt_in = payload["model_state_dict"]["actor.coord_trunk.0.weight"].shape[1]
live_in = model.actor.coord_trunk[0].weight.shape[1]
if ckpt_in != live_in:
raise RuntimeError(
f"coord trunk input mismatch: checkpoint {ckpt_in} vs env {live_in}.\n"
f"policy obs dim={num_actor_obs}, terms={list(zip(names, dims))}\n"
"The env's observation layout drifted from the one WalkGrab was trained on."
)
model.load_state_dict(payload["model_state_dict"], strict=True)
model.eval()
norm = payload.get("obs_norm_state_dict")
if norm is None:
mean = torch.zeros(num_actor_obs, device=device)
std = torch.ones(num_actor_obs, device=device)
else:
mean = norm["_mean"].to(device).reshape(-1)
std = norm["_std"].to(device).reshape(-1)
if mean.numel() != num_actor_obs:
raise RuntimeError(
f"obs normalizer is {mean.numel()}-D but the policy group is {num_actor_obs}-D."
)
eps = float(args_cli.norm_eps)
def policy(obs: torch.Tensor) -> torch.Tensor:
return model.act_inference((_t(obs) - mean) / (std + eps))
print(
f"[coordex-v2d] actor obs={num_actor_obs} critic obs={num_critic_obs} "
f"actions={num_actions} (checkpoint iter={payload.get('iter')})",
flush=True,
)
return policy
def _iter_prims(prim):
from pxr import Usd
yield prim
# Colliders often sit inside instanced references, which GetChildren() skips.
for child in prim.GetFilteredChildren(Usd.TraverseInstanceProxies(Usd.PrimAllPrimsPredicate)):
yield from _iter_prims(child)
def _dump_object_prims(root: str = "/World/envs/env_0/Bottle") -> None:
"""Print the physics schemas under the Bottle prim.
The fingertip sensors filter on exactly this path. If the rigid body and collider
actually live on a child prim (the URDF importer nests link prims), or if the
contact report API never got applied, PhysX cannot build the filter and
``force_matrix_w`` stays zero. Both cases are visible here.
"""
import omni.usd
from pxr import PhysxSchema, UsdPhysics
stage = omni.usd.get_context().get_stage()
prim = stage.GetPrimAtPath(root)
if not prim or not prim.IsValid():
print(f"[coordex-v2d] prim dump: {root} not found", flush=True)
return
print(f"[coordex-v2d] prim tree under {root}:", flush=True)
for p in _iter_prims(prim):
tags = []
if p.HasAPI(UsdPhysics.RigidBodyAPI):
tags.append("RigidBody")
if p.HasAPI(UsdPhysics.CollisionAPI):
tags.append("Collision")
if p.HasAPI(UsdPhysics.MeshCollisionAPI):
approx = UsdPhysics.MeshCollisionAPI(p).GetApproximationAttr().Get()
tags.append(f"MeshCollision({approx})")
if p.HasAPI(PhysxSchema.PhysxContactReportAPI):
tags.append("ContactReport")
print(
f" {p.GetPath()} type={p.GetTypeName() or '-'} {' '.join(tags) or '-'}",
flush=True,
)
_TIP_SENSORS = (
"contact_force_thumb",
"contact_force_index",
"contact_force_middle",
"contact_force_ring",
"contact_force_pinky",
)
class _ContactProbe:
"""Track whether the fingertip->Bottle contact filter actually reports anything.
WalkGrab's ``fingertip_cube_forces`` term reads ``force_matrix_w`` from five
sensors filtered to the Bottle prim. If PhysX cannot build that filter (it warns
``GPU contact filter for collider ... is not supported``) the field stays zero and
the term silently feeds the policy 15 zeros, i.e. "never touching anything".
Without this probe a dead grasp input is indistinguishable from a bad policy.
"""
def __init__(self, env) -> None:
sensors = getattr(env.unwrapped.scene, "sensors", None) or {}
self.sensors = {n: sensors[n] for n in _TIP_SENSORS if n in sensors}
self.missing = [n for n in _TIP_SENSORS if n not in sensors]
self.field: str | None = None
self.peak = 0.0
self.peak_unfiltered = 0.0
for sensor in self.sensors.values():
for candidate in ("force_matrix_w", "force_matrix_w_history", "net_forces_w"):
if getattr(sensor.data, candidate, None) is not None:
self.field = candidate
break
break
def describe(self) -> str:
if not self.sensors:
return "[coordex-v2d] WARNING no fingertip contact sensors on the scene"
msg = f"[coordex-v2d] fingertip sensors={len(self.sensors)} field={self.field}"
if self.missing:
msg += f" missing={self.missing}"
return msg
def update(self) -> float:
step_peak = 0.0
for sensor in self.sensors.values():
value = getattr(sensor.data, self.field, None) if self.field else None
if value is not None:
step_peak = max(step_peak, float(_t(value).abs().max()))
# Unfiltered force distinguishes "the filter is broken" from "the fingers
# genuinely touched nothing": net_forces_w counts contact with anything.
net = getattr(sensor.data, "net_forces_w", None)
if net is not None:
self.peak_unfiltered = max(self.peak_unfiltered, float(_t(net).abs().max()))
self.peak = max(self.peak, step_peak)
return step_peak
@hydra_task_config(args_cli.task, "rsl_rl_cfg_entry_point")
def main(env_cfg, agent_cfg):
checkpoint = _resolve_path(args_cli.checkpoint)
body_prior = _resolve_path(args_cli.body_prior_checkpoint)
hand_prior = _resolve_path(args_cli.hand_prior_checkpoint)
if args_cli.num_envs is not None:
env_cfg.scene.num_envs = args_cli.num_envs
if getattr(args_cli, "device", None) is not None:
env_cfg.sim.device = args_cli.device
agent_cfg.device = args_cli.device
joint_action_cfg = getattr(getattr(env_cfg, "actions", None), "joint_pos", None)
if joint_action_cfg is None:
raise RuntimeError("Locomanip env is missing actions.joint_pos.")
joint_action_cfg.body_prior_checkpoint = body_prior
joint_action_cfg.hand_prior_checkpoint = hand_prior
print(f"[coordex-v2d] task={args_cli.task}", flush=True)
print(f"[coordex-v2d] policy {checkpoint}", flush=True)
print(f"[coordex-v2d] body prior {body_prior}", flush=True)
print(f"[coordex-v2d] hand prior {hand_prior}", flush=True)
print(
"[coordex-v2d] object is the v2d URDF at WalkGrab bottle xy=(1.5,-0.35); "
"robot is G1-Wuji, not Inspire+SONIC",
flush=True,
)
env = gym.make(
args_cli.task,
cfg=env_cfg,
render_mode="rgb_array" if args_cli.video else None,
)
apply_data_tensor_compat(env)
# Default to exactly one episode rather than a round number, so a run is never
# cut off mid-attempt. WalkGrab is 15 s at 60 Hz, i.e. 900 steps, not 500.
episode_steps = int(env.unwrapped.max_episode_length)
n = args_cli.max_steps or episode_steps
video_length = args_cli.video_length or n
print(f"[coordex-v2d] episode={episode_steps} steps, running {n}, recording {video_length}", flush=True)
if args_cli.video:
tag = "stock" if "Stock" in args_cli.task else args_cli.clip
out_dir = _PROJECT / "simulation" / "runs" / "coordex_v2d" / tag
out_dir.mkdir(parents=True, exist_ok=True)
video_kwargs = {
"video_folder": str(out_dir),
"step_trigger": lambda step: step == 0,
"video_length": video_length,
"disable_logger": True,
}
print("[coordex-v2d] recording video", flush=True)
print_dict(video_kwargs, nesting=4)
env = gym.wrappers.RecordVideo(env, **video_kwargs)
device = env.unwrapped.device
policy = _build_actor(env, agent_cfg, checkpoint, device)
obs_dict, _ = env.reset()
min_root_z = float("inf")
robot = env.unwrapped.scene["robot"]
obj = env.unwrapped.scene["bottle"]
palm_id = robot.find_bodies(["right_palm_link"], preserve_order=True)[0][0]
tip_ids = robot.find_bodies(list(RIGHT_HAND_TIP_NAMES), preserve_order=True)[0]
probe = _ContactProbe(env)
print(probe.describe(), flush=True)
_dump_object_prims()
term_mgr = env.unwrapped.termination_manager
resets: dict[str, int] = {}
# Baseline after the object has settled: spawning can leave it slightly
# interpenetrating, and measuring lift from the spawn z inflates it.
settle_step = 10
obj_z0 = float(_t(obj.data.root_pos_w)[0, 2])
max_lift = 0.0
min_palm_dist = float("inf")
min_tip_dist = float("inf")
for step in range(n):
if not simulation_app.is_running():
break
with torch.inference_mode():
actions = policy(obs_dict["policy"])
obs_dict, _, terminated, truncated, _ = env.step(actions)
if bool(terminated[0]) or bool(truncated[0]):
fired = [t for t in term_mgr.active_terms if bool(term_mgr.get_term(t)[0])]
for name in fired or ["<unknown>"]:
resets[name] = resets.get(name, 0) + 1
print(f" step {step}: episode reset by {fired or '<unknown>'}", flush=True)
root_z = float(_t(robot.data.root_pos_w)[0, 2])
min_root_z = min(min_root_z, root_z)
obj_pos = _t(obj.data.root_pos_w)[0]
if step == settle_step:
obj_z0 = float(obj_pos[2])
max_lift = max(max_lift, float(obj_pos[2]) - obj_z0)
bodies = _t(robot.data.body_pos_w)[0]
palm_dist = float(torch.linalg.norm(bodies[palm_id] - obj_pos))
min_palm_dist = min(min_palm_dist, palm_dist)
tip_dist = float(torch.linalg.norm(bodies[tip_ids] - obj_pos, dim=-1).min())
min_tip_dist = min(min_tip_dist, tip_dist)
force = probe.update()
if step % 50 == 0:
print(
f" step {step}/{n} root_z={root_z:.3f} object_z={float(obj_pos[2]):.3f}"
f" palm_dist={palm_dist:.3f} tip_force={force:.3f}",
flush=True,
)
print(f"[coordex-v2d] min root_z={min_root_z:.3f}", flush=True)
print(f"[coordex-v2d] min palm-object distance={min_palm_dist:.3f} m", flush=True)
print(f"[coordex-v2d] min fingertip-object distance={min_tip_dist:.3f} m", flush=True)
print(f"[coordex-v2d] peak object lift above rest={max_lift:+.3f} m", flush=True)
print(
f"[coordex-v2d] peak fingertip force: filtered={probe.peak:.4f} "
f"unfiltered={probe.peak_unfiltered:.4f}",
flush=True,
)
if probe.peak == 0.0 and probe.peak_unfiltered > 0.0:
print(
"[coordex-v2d] WARNING fingertips registered contact with something but the "
"Bottle filter reported nothing: the filter path is still wrong.",
flush=True,
)
print(f"[coordex-v2d] episode resets: {resets or 'none'}", flush=True)
if resets.get("robot_passed_bottle_without_grasp"):
print(
"[coordex-v2d] NOTE robot_passed_bottle_without_grasp fires when the robot "
"walks past the object and is_grasped() is False. is_grasped() requires "
"fingertip contact, so a dead contact filter forces this termination "
"regardless of how well the policy actually reached.",
flush=True,
)
if probe.peak == 0.0 and min_palm_dist < 0.15:
print(
"[coordex-v2d] WARNING hand reached the object but the contact filter never "
"reported force: fingertip_cube_forces fed the policy 15 zeros, so this run "
"does not test CoordEx's grasp input fairly.",
flush=True,
)
env.close()
if __name__ == "__main__":
try:
main()
except Exception:
import traceback
traceback.print_exc()
sys.exit(1)
finally:
simulation_app.close()
|