File size: 20,259 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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
#!/usr/bin/env python3
"""Open-loop action ablation on V2D-G1-SonicManip, before any PPO.

Inject a named action stream (zeros, scripted pick, right-to-left hover sweep,
relocated clip). Rank streams on physics: did the robot stay up, did SONIC track
the wrist command, did the object move, how jerky was the command. Do not rank
on resemblance to HaWoR.

  cd simulation
  ./run_isaaclab.sh --python scripts/ablate_actions.py --headless \\
      --policies zero,scripted_4d,rel_hover,raw_clip --video-dir runs/action_ablate

``vae0`` / ``vae_grasp`` are reserved; the env is still 4-D and those names
error out until the hand prior is wired.
"""

from __future__ import annotations

import argparse
import os
import sys
import traceback
from pathlib import Path

from isaaclab.app import AppLauncher

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(line_buffering=True)

parser = argparse.ArgumentParser(description="Open-loop action ablation for SonicManip.")
parser.add_argument("--task", type=str, default="V2D-G1-SonicManip-Play-v0")
parser.add_argument("--num_envs", type=int, default=4)
parser.add_argument("--steps", type=int, default=150)
parser.add_argument(
    "--policies",
    type=str,
    default="zero,scripted_4d,rel_hover,raw_clip",
    help="comma-separated names, or 'all' (excludes VAE stubs)",
)
parser.add_argument(
    "--ema",
    type=float,
    default=1.0,
    help="causal EMA on the 4-D command; 1 = off. *_smooth policies default to 0.3",
)
parser.add_argument(
    "--hover",
    type=float,
    nargs=3,
    default=(0.0, 0.0, 0.02),
    metavar=("X", "Y", "Z"),
    help="pelvis-frame offset on the frozen object pose (rel_hover sweep endpoint)",
)
parser.add_argument(
    "--contact-dist",
    type=float,
    default=0.05,
    help="rel_hover stops the y-sweep when wrist-object is closer than this (m)",
)
parser.add_argument(
    "--sweep-frac",
    type=float,
    default=0.75,
    help="unused for rel_hover (kept for CLI compat); speed is --sweep-speed",
)
parser.add_argument(
    "--sweep-speed",
    type=float,
    default=0.08,
    help="rel_hover max wrist-target speed in m/s (pelvis). 0.08 ≈ 8 cm/s",
)
parser.add_argument(
    "--sweep-margin",
    type=float,
    default=0.06,
    help="start the lateral sweep this many metres to the robot's right of the object",
)
parser.add_argument("--clip", type=Path, default=None, help="isaaclab_replay.npz")
parser.add_argument("--wuji", type=Path, default=None, help="g1_wuji_retarget.npz for clip grip")
parser.add_argument("--video-dir", type=Path, default=None)
parser.add_argument("--log-dir", type=Path, default=None)
parser.add_argument("--fps", type=float, default=25.0)
parser.add_argument("--jitter", action="store_true", help="keep object xy/yaw reset jitter")
parser.add_argument("--keep-term", action="store_true", help="keep fall / object-off-table resets")
parser.add_argument("--list-policies", action="store_true")
AppLauncher.add_app_launcher_args(parser)
args_cli = parser.parse_args()

# Names mirrored from openloop.POLICY_NAMES so --list works before Isaac boots.
_POLICY_NAMES = (
    "zero",
    "park",
    "scripted_4d",
    "raw_clip",
    "smooth_clip",
    "rel_hover",
    "rel_hover_smooth",
    "vae0",
    "vae_grasp",
)

if args_cli.list_policies:
    print("\n".join(_POLICY_NAMES))
    sys.exit(0)

if args_cli.video_dir:
    args_cli.enable_cameras = True

app_launcher = AppLauncher(args_cli)
simulation_app = app_launcher.app

import gymnasium as gym  # noqa: E402
import numpy as np  # noqa: E402
import torch  # noqa: E402
from isaaclab_tasks.utils import parse_env_cfg  # noqa: E402

import v2d_sim  # noqa: E402, F401
from v2d_sim.tasks.g1_sonic_manip.mdp.observations import t as _t  # noqa: E402
from v2d_sim.tasks.g1_sonic_manip.openloop import (  # noqa: E402
    DEFAULT_REPLAY_NPZ,
    DEFAULT_WUJI_NPZ,
    default_ema,
    expand_policies,
    is_vae_policy,
    load_clip_wrist_stream,
    scripted_grip,
    scripted_lift_z,
)

_GRAV, _WRIST, _OBJ, _DELTA, _OBJV, _GRIP = (
    slice(0, 3),
    slice(3, 6),
    slice(6, 9),
    slice(9, 12),
    slice(12, 15),
    slice(15, 16),
)
_SETTLE_STEPS = 20


def _rgb(img) -> np.ndarray | None:
    if img is None:
        return None
    if hasattr(img, "detach"):
        img = img.detach().cpu().numpy()
    img = np.asarray(img)
    if img.ndim == 4:
        img = img[0]
    img = img[..., :3]
    if img.dtype != np.uint8:
        scale = 255.0 if float(np.nanmax(img)) <= 1.5 else 1.0
        img = np.clip(img * scale, 0, 255).astype(np.uint8)
    h, w = img.shape[:2]
    return img[: h - (h % 2), : w - (w % 2)]


class Ema4:
    def __init__(self, alpha: float) -> None:
        self.alpha = float(alpha)
        self.state: torch.Tensor | None = None

    def reset(self) -> None:
        self.state = None

    def __call__(self, a: torch.Tensor) -> torch.Tensor:
        if self.alpha >= 1.0 - 1e-6:
            return a
        if self.state is None:
            self.state = a.clone()
        else:
            self.state = self.alpha * a + (1.0 - self.alpha) * self.state
        return self.state


def _box(env_cfg, device) -> tuple[torch.Tensor, torch.Tensor, np.ndarray, np.ndarray]:
    acfg = env_cfg.actions.wrist
    lo = torch.tensor([acfg.wrist_x[0], acfg.wrist_y[0], acfg.wrist_z[0]], device=device)
    hi = torch.tensor([acfg.wrist_x[1], acfg.wrist_y[1], acfg.wrist_z[1]], device=device)
    center, half = (lo + hi) / 2.0, (hi - lo) / 2.0
    return center, half, center.detach().cpu().numpy(), half.detach().cpu().numpy()


def _pack_action(xyz_b: torch.Tensor, grip: torch.Tensor | float, center, half) -> torch.Tensor:
    a = torch.clamp((xyz_b - center) / half, -1.0, 1.0)
    if not torch.is_tensor(grip):
        g = torch.full((a.shape[0], 1), float(grip), device=a.device, dtype=a.dtype)
    else:
        g = grip.reshape(a.shape[0], 1).to(device=a.device, dtype=a.dtype)
    return torch.cat([a, g], dim=1)


class ActionStream:
    def __init__(
        self,
        name: str,
        *,
        center,
        half,
        center_np,
        half_np,
        hover_obj: torch.Tensor,
        clip,
        n_steps: int,
        dt: float = 0.04,
    ) -> None:
        self.name = name
        self.center, self.half = center, half
        self.center_np, self.half_np = center_np, half_np
        self.hover_obj = hover_obj
        self.clip = clip
        self.n_steps = n_steps
        self.dt = float(dt)
        self._goal: torch.Tensor | None = None
        self._start: torch.Tensor | None = None
        self._cmd: torch.Tensor | None = None
        self._obj_xy0: torch.Tensor | None = None
        self._hit: torch.Tensor | None = None
        self._at_start: torch.Tensor | None = None

    def _rel_hover_sweep(self, i: int, obs: torch.Tensor) -> torch.Tensor:
        """Rate-limited approach from slightly right of the can; no lift.

        Parking at the wrist-box y-min first is ~12 cm off the object; at a
        few cm/s that leg eats the episode and the hand never arrives. Crawl
        from the achieved wrist to a point ``--sweep-margin`` to the right of
        the frozen object (clamped to the SONIC box), then slide +y onto the
        can. Contact is ignored until that approach point.
        """
        n_env, device = obs.shape[0], obs.device
        obj = obs[:, _OBJ]
        vmax = float(args_cli.sweep_speed)
        max_step = vmax * self.dt
        lo = self.center - self.half
        hi = self.center + self.half
        if self._goal is None:
            offset = self.hover_obj.to(device=device, dtype=obj.dtype).view(1, 3)
            self._goal = torch.minimum(hi, torch.maximum(lo, obj + offset))
            y_right = torch.clamp(
                self._goal[:, 1] - float(args_cli.sweep_margin), min=float(lo[1])
            )
            self._start = self._goal.clone()
            self._start[:, 1] = y_right
            self._cmd = torch.minimum(hi, torch.maximum(lo, obs[:, _WRIST].clone()))
            self._obj_xy0 = obj[:, :2].clone()
            self._hit = torch.zeros(n_env, dtype=torch.bool, device=device)
            already = obs[:, _WRIST][:, 1] <= self._start[:, 1] + 0.01
            self._at_start = already
            path = torch.norm(self._start - self._cmd, dim=1) + torch.norm(
                self._goal - self._start, dim=1
            )
            eta = float(path.mean() / max(vmax, 1e-6))
            print(
                f"  sweep {vmax:.3f} m/s  margin={args_cli.sweep_margin:.3f} m  "
                f"path≈{float(path.mean()):.3f} m  eta≈{eta:.1f}s  "
                f"goal_b={self._goal[0].detach().cpu().tolist()}  "
                f"(need ~{int(eta / self.dt) + 1} steps; this run has {self.n_steps})"
            )

        target = torch.where(self._at_start.unsqueeze(-1), self._goal, self._start)
        delta = target - self._cmd
        dist = torch.linalg.norm(delta, dim=1, keepdim=True).clamp_min(1e-8)
        step = torch.clamp(dist, max=max_step)
        moved = self._cmd + step * delta / dist
        live = (~self._hit).unsqueeze(-1)
        self._cmd = torch.where(live, moved, self._cmd)
        self._at_start |= (~self._hit) & (dist.squeeze(-1) <= max_step + 1e-4)

        dist_obj = torch.norm(obs[:, _DELTA], dim=1)
        shoved = torch.norm(obj[:, :2] - self._obj_xy0, dim=1) > 0.02
        self._hit |= self._at_start & ((dist_obj < args_cli.contact_dist) | shoved)
        grip = torch.where(
            self._hit,
            torch.ones(n_env, device=device, dtype=obj.dtype),
            -torch.ones(n_env, device=device, dtype=obj.dtype),
        )
        return _pack_action(self._cmd, grip, self.center, self.half)

    def raw(self, i: int, obs: torch.Tensor, robot, obj) -> torch.Tensor:
        n_env = obs.shape[0]
        device = obs.device
        name = self.name
        if name == "zero":
            return torch.zeros(n_env, 4, device=device)
        if name == "park":
            a = torch.zeros(n_env, 4, device=device)
            a[:, 2] = 1.0
            a[:, 3] = -1.0
            return a
        if name == "scripted_4d":
            want = obs[:, _OBJ].clone()
            reach_end = int(0.40 * self.n_steps)
            if i < reach_end:
                want[:, 2] += 0.06 * (1.0 - i / max(1, reach_end))
            else:
                want[:, 2] += scripted_lift_z(i, self.n_steps)
            return _pack_action(want, scripted_grip(i, self.n_steps), self.center, self.half)
        if name in ("rel_hover", "rel_hover_smooth"):
            return self._rel_hover_sweep(i, obs)
        if name in ("raw_clip", "smooth_clip"):
            if self.clip is None:
                raise RuntimeError("clip stream requested but isaaclab_replay.npz was not loaded")
            k = min(i, self.clip.wrist_b.shape[0] - 1)
            xyz = torch.tensor(self.clip.wrist_b[k], device=device, dtype=obs.dtype).expand(n_env, 3)
            g = float(self.clip.grip[k])
            return _pack_action(xyz, g, self.center, self.half)
        raise RuntimeError(f"unhandled policy {name}")


def _prepare_cfg(env_cfg):
    if not args_cli.jitter:
        env_cfg.events.reset_object.params["x_range"] = (0.0, 0.0)
        env_cfg.events.reset_object.params["y_range"] = (0.0, 0.0)
        env_cfg.events.reset_object.params["yaw_range"] = (0.0, 0.0)
    if not args_cli.keep_term:
        env_cfg.terminations.fallen = None
        env_cfg.terminations.object_fell = None
        env_cfg.episode_length_s = max(env_cfg.episode_length_s, args_cli.steps * 0.04 + 2.0)
    return env_cfg


def _rollout(env, inner, env_cfg, name: str, clip, log_dir: Path | None, video_dir: Path | None):
    if is_vae_policy(name):
        raise RuntimeError(
            f"{name}: SonicManip is still 4-D (wrist xyz + 1-D grip). "
            "Wire CoordEx kinematic_wrist_16k.pt before rolling out Δz=0 / grasp latent."
        )
    robot = inner.scene["robot"]
    obj = inner.scene["object"]
    rest_z = env_cfg.scene.object.init_state.pos[2]
    center, half, center_np, half_np = _box(env_cfg, inner.device)
    hover = torch.tensor(list(args_cli.hover), device=inner.device, dtype=torch.float32)
    alpha = default_ema(name, args_cli.ema)
    stream = ActionStream(
        name,
        center=center,
        half=half,
        center_np=center_np,
        half_np=half_np,
        hover_obj=hover,
        clip=clip,
        n_steps=args_cli.steps,
        dt=float(env_cfg.sim.dt * env_cfg.decimation),
    )
    ema = Ema4(alpha)

    obs_dict, _ = env.reset()
    hold = torch.zeros(inner.num_envs, 4, device=inner.device)
    hold[:, 2] = 1.0
    hold[:, 3] = -1.0
    for _ in range(_SETTLE_STEPS):
        env.step(hold)
    obs_dict, _ = env.reset()
    obs = obs_dict["policy"]
    ema.reset()

    n = args_cli.steps
    rec = {
        "action_raw": [],
        "action_ema": [],
        "wrist_cmd": [],
        "wrist_ach": [],
        "object_b": [],
        "delta": [],
        "root_z": [],
        "object_z": [],
        "reward": [],
        "done": [],
    }
    frames: list[np.ndarray] = []
    term = inner.action_manager.get_term("wrist")

    print(f"\n=== {name}  ema={alpha:.2f}  steps={n} ===")
    for i in range(n):
        if not simulation_app.is_running():
            break
        raw = stream.raw(i, obs, robot, obj)
        applied = ema(raw)
        obs_dict, rew, terminated, truncated, _ = env.step(applied)
        obs = obs_dict["policy"]
        rec["action_raw"].append(raw.detach().cpu().numpy())
        rec["action_ema"].append(applied.detach().cpu().numpy())
        rec["wrist_cmd"].append(term.wrist_target.detach().cpu().numpy())
        rec["wrist_ach"].append(obs[:, _WRIST].detach().cpu().numpy())
        rec["object_b"].append(obs[:, _OBJ].detach().cpu().numpy())
        rec["delta"].append(obs[:, _DELTA].detach().cpu().numpy())
        rec["root_z"].append(_t(robot.data.root_pos_w)[:, 2].detach().cpu().numpy())
        rec["object_z"].append(_t(obj.data.root_pos_w)[:, 2].detach().cpu().numpy())
        rec["reward"].append(rew.detach().cpu().numpy())
        rec["done"].append((terminated | truncated).float().detach().cpu().numpy())
        if video_dir is not None:
            fr = _rgb(inner.render())
            if fr is not None:
                frames.append(fr)

    stacked = {k: np.stack(v, axis=0) for k, v in rec.items()}
    d_act = np.linalg.norm(np.diff(stacked["action_ema"], axis=0), axis=-1)
    track = np.linalg.norm(stacked["wrist_ach"] - stacked["wrist_cmd"], axis=-1)
    hand_obj = np.linalg.norm(stacked["delta"], axis=-1)
    lift = stacked["object_z"] - rest_z
    summary = {
        "policy": name,
        "ema": alpha,
        "min_root_z": float(stacked["root_z"].min()),
        "mean_hand_obj": float(hand_obj.mean()),
        "final_hand_obj": float(hand_obj[-1].mean()),
        "max_lift": float(lift.max()),
        "final_lift": float(lift[-1].mean()),
        "picked": int((lift[-1] > 0.03).sum()),
        "n_env": int(lift.shape[1]),
        "mean_action_rate": float(d_act.mean()) if d_act.size else 0.0,
        "mean_track_err": float(track.mean()),
        "return": float(stacked["reward"].sum(axis=0).mean()),
        "n_done": float(stacked["done"].sum()),
    }
    print(
        f"  min_root_z={summary['min_root_z']:.3f}  "
        f"hand-obj mean/final={summary['mean_hand_obj']:.3f}/{summary['final_hand_obj']:.3f}  "
        f"lift max/final={summary['max_lift']:.3f}/{summary['final_lift']:.3f}  "
        f"picked={summary['picked']}/{summary['n_env']}  "
        f"|Δa|={summary['mean_action_rate']:.3f}  "
        f"track={summary['mean_track_err']:.3f}  "
        f"R={summary['return']:.2f}"
    )
    if stream._hit is not None:
        print(f"  contact {int(stream._hit.sum())}/{int(stream._hit.numel())} envs (sweep freeze)")

    tag = f"{name}_ema{alpha:.2f}".replace(".", "p")
    if log_dir is not None:
        log_dir.mkdir(parents=True, exist_ok=True)
        out = log_dir / f"{tag}.npz"
        scalars = {
            k: np.asarray(v) for k, v in summary.items() if k != "policy"
        }
        np.savez_compressed(out, **stacked, **{f"s_{k}": v for k, v in scalars.items()}, policy=np.array(name))
        print(f"  wrote {out}")
    if video_dir is not None and frames:
        video_dir.mkdir(parents=True, exist_ok=True)
        mp4 = video_dir / f"{tag}.mp4"
        import imageio.v2 as imageio

        imageio.mimsave(str(mp4), frames, fps=float(args_cli.fps), codec="libx264", pixelformat="yuv420p")
        print(f"  wrote {mp4} ({len(frames)} frames)")
    return summary


def main() -> None:
    names = expand_policies(args_cli.policies)
    env_cfg = parse_env_cfg(args_cli.task, device=args_cli.device, num_envs=args_cli.num_envs)
    env_cfg = _prepare_cfg(env_cfg)
    render = "rgb_array" if args_cli.video_dir else None
    env = gym.make(args_cli.task, cfg=env_cfg, render_mode=render)
    inner = env.unwrapped

    clip_path = args_cli.clip or DEFAULT_REPLAY_NPZ
    wuji_path = args_cli.wuji or DEFAULT_WUJI_NPZ
    need_clip = any(n in ("raw_clip", "smooth_clip") for n in names)
    clip_raw = clip_smooth = None
    if need_clip:
        if not Path(clip_path).is_file():
            raise FileNotFoundError(f"replay clip missing: {clip_path}")
        kwargs = dict(
            replay_npz=clip_path,
            wuji_npz=wuji_path if Path(wuji_path).is_file() else None,
            policy_fps=1.0 / (env_cfg.sim.dt * env_cfg.decimation),
            object_xy=(env_cfg.scene.object.init_state.pos[0], env_cfg.scene.object.init_state.pos[1]),
            table_z=env_cfg.scene.table.init_state.pos[2] + 0.5 * env_cfg.scene.table.spawn.size[2],
            pelvis_z=env_cfg.scene.robot.init_state.pos[2],
        )
        if any(n == "raw_clip" for n in names):
            clip_raw = load_clip_wrist_stream(**kwargs, smooth=False)
        if any(n == "smooth_clip" for n in names):
            clip_smooth = load_clip_wrist_stream(**kwargs, smooth=True)
        shown = clip_raw or clip_smooth
        acfg = env_cfg.actions.wrist
        lo = np.array([acfg.wrist_x[0], acfg.wrist_y[0], acfg.wrist_z[0]])
        hi = np.array([acfg.wrist_x[1], acfg.wrist_y[1], acfg.wrist_z[1]])
        inside = ((shown.wrist_b >= lo) & (shown.wrist_b <= hi)).all(axis=1).mean()
        print(
            f"[ablate] clip {clip_path}  T={shown.wrist_b.shape[0]}  "
            f"inside wrist box {100.0 * inside:.0f}%  "
            f"(frames outside are clamped — that is the result, not a loader bug)"
        )

    log_dir = args_cli.log_dir
    if log_dir is None and args_cli.video_dir is not None:
        log_dir = args_cli.video_dir
    if log_dir is None:
        log_dir = Path("runs/action_ablate")

    print(f"[ablate] task={args_cli.task}  envs={inner.num_envs}  device={inner.device}")
    print(f"[ablate] policies={names}  jitter={args_cli.jitter}  keep_term={args_cli.keep_term}")
    print(
        f"[ablate] hover_b={tuple(args_cli.hover)}  sweep_frac={args_cli.sweep_frac}  "
        f"contact={args_cli.contact_dist}  sweep_speed={args_cli.sweep_speed} m/s  log={log_dir}"
    )

    summaries = []
    for name in names:
        clip = clip_smooth if name == "smooth_clip" else clip_raw
        summaries.append(
            _rollout(env, inner, env_cfg, name, clip, log_dir, args_cli.video_dir)
        )

    print(f"\n{'policy':<20} {'ema':>5} {'root_z':>7} {'hand-obj':>8} {'lift':>7} {'|Δa|':>6} {'track':>6} {'R':>8}")
    for s in summaries:
        print(
            f"{s['policy']:<20} {s['ema']:5.2f} {s['min_root_z']:7.3f} "
            f"{s['final_hand_obj']:8.3f} {s['final_lift']:7.3f} "
            f"{s['mean_action_rate']:6.3f} {s['mean_track_err']:6.3f} {s['return']:8.2f}"
        )
    ranked = sorted(summaries, key=lambda s: (s["final_lift"], -s["final_hand_obj"]), reverse=True)
    print(f"\n[ablate] rank by final lift, then closer hand: {[s['policy'] for s in ranked]}")
    env.close()


if __name__ == "__main__":
    code = 0
    try:
        main()
    except Exception:
        traceback.print_exc()
        sys.stdout.flush()
        sys.stderr.flush()
        code = 1
    finally:
        simulation_app.close()
    os._exit(code)