deploy_package_basket_v2: add debug section to README, debug_step0.py and record_run.py
Browse filesFiles changed (4)
123version https://git-lfs.github.com/spec/v1oid sha256:f2a6cb44e3344f1f4d1ab3cf76361d2aec9166eee28401e81ba04b75a7138194size 63685360123version https://git-lfs.github.com/spec/v1oid sha256:75b78badf3072c30a162a14bcde841ea66a1fb2df23ad38e81e5111217fecc65size 63692921
57 unmodified lines58596061626381 unmodified lines14514614757 unmodified lines- **复位要准**:每个关节和 `START_Q` 的差最好在 0.01 弧度(约 0.6 度)以内,夹爪读数要是 0.070 m(不是 0.08)。训练数据里所有回合的起点几乎完全一样,bottle、basket 对起点特别敏感,偏 0.02–0.05 弧度就可能一开始就走偏。- **夹爪读数必须正常**:复位后 `state` 的最后一个数(夹爪宽度)应该在 0.06–0.08 之间。如果是 -1,说明控制服务器没连上夹爪(服务器启动时会打印 `Gripper unavailable`),这时开合指令会被静默跳过,策略还会以为自己已经抓着东西,一开始就往别处走。必须先修好夹爪(Franka Desk 里启用夹爪、重启服务器,确认开合真的能动),再跑策略。## 布置场景(照 `scene_reference/` 里的图摆)图都取自录数据时的侧面相机(base_rgb),原图 256x256,图里放大了,手机上能直接看。部署前先照着把场景摆好。81 unmodified lines- Success: at the end of the episode all three objects are in the basket and the gripper has let go. Also note how many objects ended up in the basket (0-3).- Record success or failure (with a short reason) for every episode, ideally with video.- Press the emergency stop if the arm moves dangerously, and count that episode as a failure.57 unmodified lines58596061626364656667686970717273747576777879808182838485868788899081 unmodified lines17217317417517617717817918018118218318418518618718857 unmodified lines- **复位要准**:每个关节和 `START_Q` 的差最好在 0.01 弧度(约 0.6 度)以内,夹爪读数要是 0.070 m(不是 0.08)。训练数据里所有回合的起点几乎完全一样,bottle、basket 对起点特别敏感,偏 0.02–0.05 弧度就可能一开始就走偏。- **夹爪读数必须正常**:复位后 `state` 的最后一个数(夹爪宽度)应该在 0.06–0.08 之间。如果是 -1,说明控制服务器没连上夹爪(服务器启动时会打印 `Gripper unavailable`),这时开合指令会被静默跳过,策略还会以为自己已经抓着东西,一开始就往别处走。必须先修好夹爪(Franka Desk 里启用夹爪、重启服务器,确认开合真的能动),再跑策略。## 调试:每次测试都要存的东西这个包里带了两个调试脚本:`debug_step0.py` 和 `record_run.py`。用的时候把它们和你们的 `run_robot.py` 放在同一层,也就是这个包的目录。**开测前**:每次重启机器人或控制服务器后做一遍,把输出存成文字或截图。1. 控制服务器启动时终端打印的内容。重点看有没有 `Gripper unavailable`:有的话说明夹爪没连上,策略一定会一开始就走偏,先修好再测。2. 运行 `python debug_step0.py --ckpt checkpoints/ours.pt`,存下它的输出和它生成的 `debug_step0.png`。它只算第一步,不让策略动机器人。正常情况下,夹爪读数在 0.06–0.08 之间,第一个 action 和 state 每个关节相差不超过 0.05 rad。3. 运行 `python align_camera.py --home` 把相机调好,存下最后打印的那一行。**每个回合**:用 `record_run.py` 代替 `run_robot.py` 跑。参数和原来完全一样,不改变机器人的任何动作:```bashpython record_run.py --ckpt checkpoints/ours.pt --max-steps 450```原来的 mp4 照常存。另外每个回合会在 `rollouts/` 里多存 `..._log.npz` 和 `..._log.json` 两个文件,记下这些内容:- 每一步喂给策略的画面(256×256)、state(7 个关节角加夹爪读数)、策略输出的 action、实际发给机器人的关节目标、夹爪开合指令,以及每一步的耗时。- 复位后的 state:离起始姿态差多少,夹爪读数是多少。读数不对时会当场打印警告。- 这次用的是哪个权重(文件名和校验和),以及代码版本。- 成功与否和一句备注。回答完 `success?` 后会再问一句备注,失败的话写一句原因,比如「一开始就往左偏」「抓空了」「放偏了」。不要加 `--no-video`,因为记录和视频存在同一个文件夹里。能用手机从侧面再录一段最好,失败的回合尤其要录。**测完**:把 `rollouts/` 文件夹、开测前那三项的输出、手机视频一起打包发给我们。拿到这些,我们能把每一步原样重放,查出是哪一步、哪个输入出了问题。## 布置场景(照 `scene_reference/` 里的图摆)图都取自录数据时的侧面相机(base_rgb),原图 256x256,图里放大了,手机上能直接看。部署前先照着把场景摆好。81 unmodified lines- Success: at the end of the episode all three objects are in the basket and the gripper has let go. Also note how many objects ended up in the basket (0-3).- Record success or failure (with a short reason) for every episode, ideally with video.- Press the emergency stop if the arm moves dangerously, and count that episode as a failure.**Debugging: what to record every time.** This package includes two debug scripts, `debug_step0.py` and `record_run.py`. Put them next to your `run_robot.py`, i.e. in this package directory.- Before testing (each time the robot or the control server is restarted), save the following as text or a screenshot:1. The control server's startup output. Look for `Gripper unavailable`: it means the gripper is not connected, and the policy will veer off from the start. Fix it first.2. The output of `python debug_step0.py --ckpt checkpoints/ours.pt` and the `debug_step0.png` it writes. It computes only the first step and does not let the policy move the robot. The gripper reading should be 0.06-0.08, and the first action should be within 0.05 rad of the state for every joint.3. The last line printed by `python align_camera.py --home` after the camera is aligned.- Every episode: run `record_run.py` instead of `run_robot.py` with exactly the same arguments: `python record_run.py --ckpt checkpoints/ours.pt --max-steps 450`. It does not change any robot motion. Besides the usual mp4 it writes `..._log.npz` and `..._log.json` per episode into `rollouts/`. They contain:- for every step: the image fed to the policy, the state, the action, the joint target sent, the gripper command, and timing;- the state after the reset, with a warning printed on the spot if it is wrong;- the checkpoint and code checksums;- success or failure and a one-line note. It asks for the note after `success?`; for failures, write the reason.Do not pass `--no-video`. A phone video from the side helps, especially for failures.- After testing, send us the `rollouts/` folder, the three pre-test outputs and any phone videos. With these we can replay every step exactly and find what went wrong.
123456789101112131415161718192021222324252627282930313233343536373839404142434445"""debug_step0.py — 只看策略第一步,不让策略动机器人(机械臂只会回起始姿态)。
放在部署包目录里、和 run_robot.py 同一层运行(每个部署包里都带了一份): python debug_step0.py --ckpt checkpoints/ours.pt
会打印:读到的 state、第一步的 action、两者的差;并把这一帧相机画面存成 debug_step0.png。正常情况: - state 最后一个数(夹爪宽度)约 0.06–0.07;如果是 -1,说明控制服务器没连上夹爪 - state 前 7 个数接近 START_Q(每个差 < 0.01) - action 前 7 个数和 state 前 7 个数每个差 < 0.05;action 最后一个数约 0.07(不想合夹爪)"""import argparse
import cv2import numpy as np
from deploy import DeployAgentfrom run_robot import START_Q, FrankaRobot
ap = argparse.ArgumentParser()ap.add_argument("--ckpt", default="checkpoints/ours.pt")ap.add_argument("--zmq-host", default="localhost")ap.add_argument("--zmq-port", type=int, default=5555)args = ap.parse_args()
np.set_printoptions(precision=4, suppress=True)robot = FrankaRobot(args.zmq_host, args.zmq_port, speed_factor=0.2)try: robot.go_home() # 回 START_Q,并张开夹爪 agent = DeployAgent(args.ckpt) agent.reset() img_full, img_policy = robot.get_image() state = robot.get_state() action = agent.step(img_policy, state) # 只算,不发给机器人 print("夹爪读数 :", round(float(state[7]), 4), "(正常约 0.06-0.07;-1 = 服务器没连上夹爪)") print("state 前 7 个 :", state[:7]) print("START_Q :", START_Q) print("state - START_Q :", state[:7] - START_Q, "(每个应 < 0.01)") print("action :", action) print("action - state :", action[:7] - state[:7], "(每个应 < 0.05)") print("action 夹爪 :", round(float(action[7]), 4), "(正常约 0.07;约 0.02-0.03 表示策略以为已经抓着东西)") cv2.imwrite("debug_step0.png", cv2.cvtColor(img_policy, cv2.COLOR_RGB2BGR)) print("已存 debug_step0.png(策略看到的 256x256 画面)")finally: robot.close()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275"""record_run.py — 跑法和你们的 run_robot.py 完全一样,另外把调试要用的东西全存下来。不改变机器人的任何动作。
用法:把它放进部署包目录,和 run_robot.py、deploy.py 同一层。命令里的 run_robot.py 换成 record_run.py,其余参数照旧: python record_run.py --ckpt checkpoints/ours.pt # knife、bottle python record_run.py --ckpt checkpoints/ours.pt --max-steps 450 # basket不要加 --no-video:调试记录和视频存在同一个文件夹里(默认 rollouts/)。
每个回合结束、回答完 success? 之后,会多问一句备注:失败的话写一句原因,比如「一开始就往左偏」「抓空了」「放偏了」;直接回车可以跳过。
每个回合除了 run_robot.py 原来存的 rollout_NNN_<时间>_<结果>.mp4,还会多存两个文件,编号相同: rollout_NNN_<时间>_<结果>_log.npz 逐步的记录: img_policy [T,256,256,3] uint8 喂给策略的画面(RGB,和 agent.step 收到的一模一样) state [T,8] 喂给策略的 state:7 个关节角(rad)+ 夹爪读数(m) action [T,8] 策略输出:7 个关节的绝对目标(rad)+ 夹爪目标宽度(m) q_sent [T,7] 实际发给机器人的关节目标(经过 run_robot.py 的安全裁剪) gripper_open_after [T] 这一步之后夹爪的开合指令状态:1 = 张开,0 = 合上,-1 = 不知道 t_img0 / t_img1 / t_pol0 / t_pol1 / t_send0 / t_send1 [T] 取图、策略、发指令各段的起止时间(秒) move_to_joints 是阻塞调用,从这些时间能看出每步实际用了多久 rollout_NNN_<时间>_<结果>_log.json 这个回合的信息: 权重文件和 md5、代码文件的 md5、命令行参数;复位后的 state、各关节离 START_Q 多远、夹爪读数; 步数、实际控制周期、成功与否、备注如果用 Ctrl-C 中途退出,没存的回合也会存成 ..._interrupted_log.npz / .json。"""import atexitimport hashlibimport jsonimport platformimport socketimport sysimport timefrom datetime import datetimefrom pathlib import Path
import numpy as np
THIS_DIR = Path(__file__).resolve().parentif str(THIS_DIR) not in sys.path: sys.path.insert(0, str(THIS_DIR))
if "--no-video" in sys.argv: sys.exit("[record] 别加 --no-video:调试记录要和视频存在同一个文件夹里")
try: import run_robot as RR # 你们自己的 run_robot.py(同一层)except Exception as exc: # noqa: BLE001 sys.exit(f"[record] 导入同一层的 run_robot.py 失败:{exc!r}。record_run.py 要放在 run_robot.py 同一层")
_NEED = {"DeployAgent": ("__init__", "reset", "step"), "FrankaRobot": ("reset_episode", "get_image", "get_state", "send_joint_target")}_missing = [f"{c}.{m}" for c, ms in _NEED.items() for m in ms if not hasattr(getattr(RR, c, None), m)]_missing += [n for n in ("save_rollout_video", "main", "START_Q") if not hasattr(RR, n)]if _missing: sys.exit(f"[record] run_robot.py 里找不到 {_missing},和我们拿到的版本不一样了。请把现在的 run_robot.py 发给我们")
def _md5(p): try: return hashlib.md5(Path(p).read_bytes()).hexdigest() except Exception as exc: # noqa: BLE001 return f"读不了:{exc!r}"
def _jsonable(x): if isinstance(x, dict): return {str(k): _jsonable(v) for k, v in x.items()} if isinstance(x, (list, tuple)): return [_jsonable(v) for v in x] if isinstance(x, np.ndarray): return _jsonable(x.tolist()) if isinstance(x, (np.floating, float)): return None if not np.isfinite(x) else float(x) if isinstance(x, (np.integer,)): return int(x) return x
SESSION = { "argv": sys.argv, "cwd": str(Path.cwd()), "host": socket.gethostname(), "python": platform.python_version(), "started": datetime.now().isoformat(timespec="seconds"), "code_md5": {f: _md5(THIS_DIR / f) for f in ("run_robot.py", "deploy.py", "record_run.py", "agent/agent.py", "agent/nets.py", "agent/utils.py")},}EP = {"steps": [], "pending": {}, "reset": None, "saved": True, "t_start": None, "save_dir": None}
# ---------------- DeployAgent:记下喂给策略的输入和策略的输出 ----------------_agent_init = RR.DeployAgent.__init___agent_reset = RR.DeployAgent.reset_agent_step = RR.DeployAgent.step
def _agent_init_w(self, *a, **k): _agent_init(self, *a, **k) ck = a[0] if a else k.get("ckpt_path", k.get("ckpt")) SESSION["ckpt"] = str(Path(ck).resolve()) if ck else None SESSION["ckpt_md5"] = _md5(ck) if ck else None SESSION["versions"] = {m: getattr(sys.modules.get(m), "__version__", None) for m in ("torch", "numpy", "cv2")} print(f"[record] 权重 {SESSION['ckpt']}(md5 {SESSION['ckpt_md5']})", flush=True)
def _agent_reset_w(self, *a, **k): if EP["steps"] and not EP["saved"]: _dump_unsaved("unsaved") EP.update(steps=[], pending={}, reset=None, saved=False, t_start=time.time()) return _agent_reset(self, *a, **k)
def _agent_step_w(self, image, state, *a, **k): t0 = time.time() act = _agent_step(self, image, state, *a, **k) t1 = time.time() rec = dict(EP["pending"]) EP["pending"] = {} rec.update(img=np.array(image, dtype=np.uint8, copy=True), state=np.array(state, dtype=np.float64).reshape(-1), action=np.array(act, dtype=np.float64).reshape(-1), t_pol0=t0, t_pol1=t1) EP["steps"].append(rec) return act
RR.DeployAgent.__init__ = _agent_init_wRR.DeployAgent.reset = _agent_reset_wRR.DeployAgent.step = _agent_step_w
# ---------------- FrankaRobot:记下复位结果、发出去的指令和各段耗时 ----------------_rb_reset_episode = RR.FrankaRobot.reset_episode_rb_get_image = RR.FrankaRobot.get_image_rb_get_state = RR.FrankaRobot.get_state_rb_send = RR.FrankaRobot.send_joint_target
def _rb_reset_episode_w(self, *a, **k): out = _rb_reset_episode(self, *a, **k) try: st = np.asarray(_rb_get_state(self), dtype=np.float64).reshape(-1) dq = st[:7] - np.asarray(RR.START_Q, dtype=np.float64) warn = [] if not (0.05 <= st[7] <= 0.085): warn.append(f"夹爪读数 {st[7]:.4f} 不对(正常约 0.07;-1 = 控制服务器没连上夹爪)") if np.abs(dq).max() > 0.01: warn.append(f"复位不准:关节离 START_Q 最多差 {np.abs(dq).max():.3f} rad(要 < 0.01)") EP["reset"] = {"state": st, "dq_from_START_Q": dq, "max_abs_dq": float(np.abs(dq).max()), "gripper_reading": float(st[7]), "warnings": warn, "t": time.time()} print(f"[record] 复位后 state = {np.round(st, 4).tolist()}", flush=True) for w in warn: print(f"[record] !!! 注意:{w}", flush=True) except Exception as exc: # noqa: BLE001 EP["reset"] = {"error": repr(exc)} print(f"[record] 复位后读 state 失败:{exc!r}", flush=True) return out
def _rb_get_image_w(self, *a, **k): t0 = time.time() out = _rb_get_image(self, *a, **k) EP["pending"].update(t_img0=t0, t_img1=time.time()) return out
def _rb_send_w(self, q7, *a, **k): t0 = time.time() out = _rb_send(self, q7, *a, **k) t1 = time.time() if EP["steps"]: q = np.asarray(q7, dtype=np.float64).reshape(-1)[:7] if hasattr(RR, "SAFE_Q_MIN") and hasattr(RR, "SAFE_Q_MAX"): q = np.clip(q, RR.SAFE_Q_MIN, RR.SAFE_Q_MAX) g = k.get("gripper", a[0] if a else None) EP["steps"][-1].update(q_sent=q, gripper_arg=float(g) if g is not None else np.nan, gripper_open_after=int(self._gripper_open) if hasattr(self, "_gripper_open") else -1, t_send0=t0, t_send1=t1) return out
RR.FrankaRobot.reset_episode = _rb_reset_episode_wRR.FrankaRobot.get_image = _rb_get_image_wRR.FrankaRobot.send_joint_target = _rb_send_w
# ---------------- 存盘:跟着 run_robot.py 存视频的时机一起存 ----------------def _stats(x): x = np.asarray(x, dtype=np.float64) x = x[np.isfinite(x)] if not len(x): return None return {"median": float(np.median(x)), "max": float(x.max()), "min": float(x.min())}
def _dump(save_dir, idx, label, note): save_dir = Path(save_dir) save_dir.mkdir(parents=True, exist_ok=True) S = EP["steps"] T = len(S) ts = datetime.now().strftime("%Y%m%d_%H%M%S") base = save_dir / f"rollout_{idx:03d}_{ts}_{label}_log" arr = {} if T: arr["img_policy"] = np.stack([r["img"] for r in S]).astype(np.uint8) arr["state"] = np.stack([r["state"] for r in S]) arr["action"] = np.stack([r["action"] for r in S]) arr["q_sent"] = np.stack([r.get("q_sent", np.full(7, np.nan)) for r in S]) arr["gripper_arg"] = np.array([r.get("gripper_arg", np.nan) for r in S], dtype=np.float64) arr["gripper_open_after"] = np.array([r.get("gripper_open_after", -1) for r in S], dtype=np.int8) for key in ("t_img0", "t_img1", "t_pol0", "t_pol1", "t_send0", "t_send1"): arr[key] = np.array([r.get(key, np.nan) for r in S], dtype=np.float64) np.savez_compressed(str(base) + ".npz", **arr) meta = {"session": SESSION, "episode_index": idx, "label": label, "note": note, "n_steps": T, "saved": datetime.now().isoformat(timespec="seconds"), "reset": EP["reset"]} if T: st0, a0 = arr["state"][0], arr["action"][0] meta["first_step"] = {"gripper_reading": float(st0[7]), "state": st0, "action": a0, "max_abs_action_minus_state_joints": float(np.abs(a0[:7] - st0[:7]).max())} meta["gripper_reading"] = _stats(arr["state"][:, 7]) meta["control_period_s"] = _stats(np.diff(arr["t_img0"])) if T > 1 else None meta["move_to_joints_s"] = _stats(arr["t_send1"] - arr["t_send0"]) meta["policy_s"] = _stats(arr["t_pol1"] - arr["t_pol0"]) meta["first_close_step"] = int(np.argmax(arr["gripper_open_after"] == 0)) if (arr["gripper_open_after"] == 0).any() else None Path(str(base) + ".json").write_text(json.dumps(_jsonable(meta), indent=1, ensure_ascii=False)) EP["saved"] = True print(f"[record] 调试记录已存:{base}.npz 和 .json({T} 步)", flush=True)
def _default_save_dir(): try: args, _ = RR.build_parser().parse_known_args() return Path(args.save_dir) except Exception: # noqa: BLE001 return THIS_DIR / "rollouts"
def _dump_unsaved(label): try: sd = EP["save_dir"] or _default_save_dir() idx = RR.next_rollout_idx(sd) if hasattr(RR, "next_rollout_idx") else 999 _dump(sd, idx, label, "") except Exception as exc: # noqa: BLE001 print(f"[record] 存没存完的回合失败:{exc!r}", flush=True)
_save_video = RR.save_rollout_video
def _save_video_w(frames, save_dir, idx, fps, label, *a, **k): EP["save_dir"] = Path(save_dir) try: return _save_video(frames, save_dir, idx, fps, label, *a, **k) finally: note = "" if label != "error": try: note = input(" [record] 备注(失败的话写一句原因,比如「一开始就往左偏」「抓空了」「放偏了」;直接回车跳过): ").strip() except Exception: # noqa: BLE001 note = "" try: _dump(save_dir, idx, label, note) except Exception as exc: # noqa: BLE001 print(f"[record] 存调试记录失败:{exc!r}", flush=True)
RR.save_rollout_video = _save_video_w
@atexit.registerdef _at_exit(): if EP["steps"] and not EP["saved"]: print("[record] 有一个回合还没存(Ctrl-C 退出?),现在存成 interrupted", flush=True) _dump_unsaved("interrupted")
if __name__ == "__main__": print("[record] record_run.py:照常运行 run_robot.py,同时存调试记录(见文件开头的说明)", flush=True) RR.main()deploy_package_basket_v2.zip+2-2
deploy_package_basket_v2/README.md+41
deploy_package_basket_v2/debug_step0.pyAdded+45
deploy_package_basket_v2/record_run.pyAdded+275