File size: 8,893 Bytes
d8e9a5e | 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 | """Does the policy aim from what it sees? A visual-feedback probe, no training.
The scripted teacher's clean pick is executed until its pinch point is `--heights` mm above the
grasp point, and the state is frozen there. Two observations are made of it: as it is, and with
the target piece moved `--shift-mm` sideways (four directions: along and across the jaws' closing
axis), with the arm unchanged. For each, the policy's 50-step action chunk is predicted with
identical sampling noise, and the pinch point of every predicted action is found by forward
kinematics. The chunk's aim is its lowest pinch point (where the predicted descent ends).
Follow ratio = the aim's shift along the piece's shift, divided by the piece's shift:
1 = the aim follows the piece fully (the policy aims from the images), 0 = it ignores the change
(it replays a path from the joint state). Noise floor: the aim of the same observation under
different sampling noise.
Run: MUJOCO_GL=egl PHASE2_PROFILE=baseline .venv/bin/python sim/visual_probe.py \
--policy baseline=models/baseline --policy dart300=models/dart300 --out sim/reports/visual_probe
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
DIRECTIONS = ("along+", "along-", "across+", "across-")
def make_probes(args, cfg):
"""Frozen teacher states at each height, as observations: unshifted and per shift direction."""
import mujoco
import numpy as np
from camera_effects import training_look
from episode import EpisodeRunner
from lerobot_export import Recorder, video_settings
from piece_sets import sample_piece_set
crf, pix_fmt = video_settings(cfg)
runner = EpisodeRunner(cfg, sample_piece_set(np.random.default_rng([args.seed, 10**9]), cfg, "probe"), render=True)
m, d, kin, w = runner.m, runner.d, runner.expert.kin, runner.w
heights = sorted((float(h) for h in args.heights.split(",")), reverse=True)
shift = args.shift_mm / 1000
probes = []
for i in range(args.scenes):
ep_seed = int(np.random.default_rng([args.seed, i]).integers(2**62))
task = runner.setup(np.random.default_rng(ep_seed))
pick = runner.expert.plan_pick(d, task.target, np.random.default_rng(ep_seed))
rec = Recorder(cfg, None)
rec.begin(runner, task, np.random.default_rng(ep_seed ^ 0x5EED))
axis = np.array([np.cos(pick.yaw), np.sin(pick.yaw), 0.0]) # jaw closing direction
across = np.array([-axis[1], axis[0], 0.0])
vecs = {"along+": axis, "along-": -axis, "across+": across, "across-": -across}
a = w.qadr[task.target]
def observe():
return {"observation.images.overhead": training_look(rec.observe(runner, "overhead"), crf, pix_fmt),
"observation.images.wrist": training_look(rec.observe(runner, "wrist"), crf, pix_fmt),
"observation.state": runner.to_lerobot(d.qpos[runner.qadr])}
k = 0
for q, g in zip(pick.traj.q, pick.traj.g):
d.ctrl[:5], d.ctrl[5] = q, g
for _ in range(runner.n_sub):
mujoco.mj_step(m, d)
above = (kin.pose(d.qpos[kin.qadr], pick.offset)[0][2] - pick.grasp_point[2]) * 1000
if above > heights[k]:
continue
mujoco.mj_forward(m, d) # render every observation from the same, current kinematics
base = observe()
shifted = {}
saved = d.qpos[a:a + 7].copy()
for name, v in vecs.items():
d.qpos[a:a + 2] = saved[:2] + v[:2] * shift
mujoco.mj_forward(m, d)
shifted[name] = observe()
d.qpos[a:a + 7] = saved
mujoco.mj_forward(m, d)
probes.append(dict(scene=i, height=heights[k], actual_mm=round(float(above), 1), piece=w.kind[task.target],
move=f"{task.source}-{task.dest.square}", offset=pick.offset, vecs=vecs,
base=base, shifted=shifted))
k += 1
if k == len(heights):
break
runner.close()
return probes, cfg["dataset"]["instruction"], m
def run_policy(path, probes, instruction, noise_seeds, kin, shift):
import numpy as np
import torch
from lerobot.utils.control_utils import predict_action
from eval_policy import load_policy
policy, pre, post, device = load_policy(path)
def aim(obs, seed, offset):
policy.reset()
torch.manual_seed(seed)
chunk = np.array([predict_action(dict(obs), policy, device, pre, post, use_amp=False, task=instruction,
robot_type="so101_follower").squeeze().float().cpu().numpy() for _ in range(50)])
pts = np.array([kin.pose(np.radians(c[:5]), offset)[0] for c in chunk])
return pts[int(np.argmin(pts[:, 2]))]
rows = []
for p in probes:
ratios, perps, floors = [], [], []
for s in range(noise_seeds):
seed = 1000 + s
a0 = aim(p["base"], seed, p["offset"])
floors.append(float(np.linalg.norm((aim(p["base"], seed + 500, p["offset"]) - a0)[:2]) * 1000))
for name in DIRECTIONS:
v = p["vecs"][name]
dv = (aim(p["shifted"][name], seed, p["offset"]) - a0)[:2]
ratios.append(float(dv @ v[:2]) / (np.linalg.norm(v[:2]) * shift))
perps.append(float(abs(dv @ np.array([-v[1], v[0]])) * 1000))
rows.append(dict(scene=p["scene"], height=p["height"], piece=p["piece"], move=p["move"],
follow=float(np.mean(ratios)), sideways_mm=float(np.mean(perps)), floor_mm=float(np.mean(floors))))
del policy
torch.cuda.empty_cache()
return rows
def main():
import numpy as np
from episode import load_config
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--policy", action="append", required=True, help="NAME=path, repeatable")
ap.add_argument("--scenes", type=int, default=20)
ap.add_argument("--seed", type=int, default=9_200_003, help="probe scenes; not a test set")
ap.add_argument("--heights", default="40,20", help="mm above the grasp point")
ap.add_argument("--shift-mm", type=float, default=4.0)
ap.add_argument("--noise", type=int, default=3, help="sampling-noise seeds per probe")
ap.add_argument("--out", required=True)
args = ap.parse_args()
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
cfg = load_config()
probes, instruction, model = make_probes(args, cfg)
from kinematics import Kinematics
kin = Kinematics(model)
results = {}
for spec in args.policy:
name, path = spec.split("=", 1)
results[name] = run_policy(path, probes, instruction, args.noise, kin, args.shift_mm / 1000)
print(name, "done", flush=True)
def med(rows, key):
return round(float(np.median([r[key] for r in rows])), 2) if rows else None
heights = sorted({p["height"] for p in probes}, reverse=True)
lines = ["# Visual-feedback probe", "",
f"{args.scenes} scenes (seed {args.seed}); the teacher's hand frozen at {', '.join(f'{h:g}' for h in heights)} mm "
f"above its grasp point; the target moved {args.shift_mm:g} mm along and across the jaw axis (4 directions) "
f"with the arm unchanged; {args.noise} sampling-noise seeds per probe.", "",
"Follow ratio: how far the predicted aim (lowest pinch point of the 50-step chunk) moves along the piece's "
"shift, per mm of shift. 1 = follows the piece fully, 0 = ignores it. Floor: the aim's change from sampling "
"noise alone (mm).", "",
"| model | height | follow ratio, median (all) | pawns | knights | sideways drift mm | noise floor mm |",
"|---|---|---|---|---|---|---|"]
for name, rows in results.items():
for h in heights:
r = [x for x in rows if x["height"] == h]
lines.append(f"| {name} | {h:g} mm | {med(r, 'follow')} | {med([x for x in r if x['piece'] == 'pawn'], 'follow')} | "
f"{med([x for x in r if x['piece'] == 'knight'], 'follow')} | {med(r, 'sideways_mm')} | {med(r, 'floor_mm')} |")
text = "\n".join(lines) + "\n"
(out / "visual_probe.md").write_text(text)
(out / "visual_probe.json").write_text(json.dumps(dict(args=vars(args), results=results,
probes=[dict(scene=p["scene"], height=p["height"], actual_mm=p["actual_mm"],
piece=p["piece"], move=p["move"]) for p in probes]), indent=1))
print(text)
if __name__ == "__main__":
main()
|