File size: 13,343 Bytes
5a3fcf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Roll out a fine-tuned checkpoint (PoP or the sentence baseline) on an SO-101 follower arm through LeRobot
(lerobot 0.7.0: SO101Follower, OpenCV cameras).

    python scripts/rollout.py --run 261121-so101-pop-s0 --task cups \
        --port /dev/ttyACM0 --robot-id my_follower --front 0 --wrist 2

Control loop, at the training rate of 10 Hz: every tick read the joints and both cameras; every --replan ticks (0.8 s)
run the policy and get 16 joint targets for the next 1.6 s; send the first 8, one per tick, interpolated to
--servo-hz. LeRobot clamps each command to --max-relative-target degrees from the current position.

PoP needs the task's points in the fixed camera ("front") image: click them in the window at the start, or pass
--points. The active step and "object in hand" are tracked from the gripper and the forward kinematics
(popt/runtime.py StepTracker). Window keys: n = next step, g = toggle object in hand, q or Esc = stop. The sentence
baseline gets the task's training instruction and needs no points.

Defaults download the checkpoint and the task's fitted camera from the Hub repo (--repo). The fitted cameras belong
to the rig that recorded the training data; another rig needs its own fit (scripts/fit_camera.py).
"""
import argparse
import json
import os
import sys
import time

import numpy as np
import torch

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)
from popt.runtime import HZ, JOINTS, TASKS, Camera, Policy, StepTracker, pixel_to_xy, resize_256, xy_to_pixel  # noqa: E402

def make_robot(a):
    from pathlib import Path

    from lerobot.cameras.opencv import OpenCVCameraConfig
    from lerobot.robots.so_follower import SO101Follower, SO101FollowerConfig

    def cam(src):
        return OpenCVCameraConfig(index_or_path=int(src) if str(src).isdigit() else Path(src), fps=a.cam_fps,
                                  width=a.cam_width, height=a.cam_height)
    cfg = SO101FollowerConfig(port=a.port, id=a.robot_id,
                              calibration_dir=Path(a.calibration_dir) if a.calibration_dir else None,
                              cameras={"front": cam(a.front), "wrist": cam(a.wrist)},
                              max_relative_target=a.max_relative_target, use_degrees=True)
    return SO101Follower(cfg)


def obs_state(obs) -> np.ndarray:
    return np.array([obs[f"{j}.pos"] for j in JOINTS], np.float32)


def parse_points(s: str) -> dict:
    """'grasp1=320,200 release1=330,150' -> {name: (u, v)} in pixels of the front image."""
    out = {}
    for item in s.replace(";", " ").split():
        k, v = item.split("=")
        u, w = v.split(",")
        out[k] = (float(u), float(w))
    return out


class Window:
    """OpenCV window: point clicks, live view with the points, keys. Needs an OpenCV build with GUI support."""

    def __init__(self):
        import cv2
        self.cv2 = cv2
        cv2.namedWindow("pop", cv2.WINDOW_AUTOSIZE)
        self.click = None
        cv2.setMouseCallback("pop", self._on_mouse)

    def _on_mouse(self, ev, x, y, *_):
        if ev == self.cv2.EVENT_LBUTTONDOWN:
            self.click = (x, y)

    def show(self, rgb, marks=(), lines=()) -> int:
        cv2 = self.cv2
        img = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)
        for (u, v), color, label in marks:
            cv2.circle(img, (int(round(u)), int(round(v))), 6, color, 2)
            cv2.putText(img, label, (int(u) + 8, int(v) - 8), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1, cv2.LINE_AA)
        for k, t in enumerate(lines):
            cv2.putText(img, t, (10, 22 + 22 * k), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2, cv2.LINE_AA)
            cv2.putText(img, t, (10, 22 + 22 * k), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 0), 1, cv2.LINE_AA)
        cv2.imshow("pop", img)
        return cv2.waitKey(1) & 0xFF

    def click_points(self, robot, prompts) -> dict:
        """Click each point on the live fixed view; u = undo, Enter or space = done."""
        pts, self.click = {}, None
        while True:
            frame = robot.get_observation()["front"]
            if self.click is not None and len(pts) < len(prompts):
                pts[prompts[len(pts)][0]] = self.click
            self.click = None
            marks = [(p, (0, 200, 0), n) for n, p in pts.items()]
            todo = prompts[len(pts)][1] if len(pts) < len(prompts) else "all points set: Enter = start setup, u = undo"
            key = self.show(frame, marks, [f"click: {todo}"])
            if key == ord("u") and pts:
                pts.pop(list(pts)[-1])
            elif key in (13, 10, 32) and len(pts) == len(prompts):
                return pts
            elif key in (ord("q"), 27):
                raise KeyboardInterrupt


def wait_start(robot, window):
    if window is None:
        input("Place the objects, then press Enter to start (Ctrl-C stops). ")
        return
    while True:
        key = window.show(robot.get_observation()["front"], (), ["space = start, q = quit"])
        if key == 32:
            return
        if key in (ord("q"), 27):
            raise KeyboardInterrupt


def main():
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--task", required=True, choices=sorted(TASKS))
    p.add_argument("--run", default="261121-so101-pop-s0", help="fine-tuning run in --repo (finetune/<run>/)")
    p.add_argument("--step", default="step_040000.pt", help="checkpoint file of the run (the final one by default)")
    p.add_argument("--ckpt", default="", help="local checkpoint instead of --run")
    p.add_argument("--repo", default="khanhnd61/pop-so101")
    p.add_argument("--revision", default=None, help="Hub revision of --repo (default: main)")
    p.add_argument("--camera", default="", help="fitted camera JSON (default: the task's camera from --repo)")
    p.add_argument("--urdf", default=os.path.join(ROOT, "assets", "so101_new_calib.urdf"))
    p.add_argument("--t5", default=os.path.join(ROOT, "assets", "t5_efficient_tiny"), help="folder with T5 config.json")
    p.add_argument("--points", default="", help="PoP points as name=u,v in front-image pixels, e.g. 'grasp=300,220 release=420,180'")
    p.add_argument("--port", required=True, help="serial port of the follower arm, e.g. /dev/ttyACM0")
    p.add_argument("--robot-id", required=True, help="the id used for lerobot-calibrate")
    p.add_argument("--calibration-dir", default="")
    p.add_argument("--front", required=True, help="fixed camera: OpenCV index or device path")
    p.add_argument("--wrist", required=True, help="wrist camera: OpenCV index or device path")
    p.add_argument("--cam-width", type=int, default=640)
    p.add_argument("--cam-height", type=int, default=480)
    p.add_argument("--cam-fps", type=int, default=30)
    p.add_argument("--replan", type=int, default=8, help="targets sent per policy call (of 16)")
    p.add_argument("--servo-hz", type=int, default=30)
    p.add_argument("--max-relative-target", type=float, default=10.0, help="largest step per command, degrees")
    p.add_argument("--max-seconds", type=float, default=60.0)
    p.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
    p.add_argument("--no-window", action="store_true", help="no OpenCV window: points from --points, Ctrl-C stops")
    p.add_argument("--save", default="", help="write a per-trial log (.npz) here")
    a = p.parse_args()
    assert 1 <= a.replan <= 15 and a.servo_hz % HZ == 0

    spec = TASKS[a.task]
    if a.ckpt:
        ckpt = a.ckpt
    else:
        from huggingface_hub import hf_hub_download
        ckpt = hf_hub_download(a.repo, f"finetune/{a.run}/{a.step}", revision=a.revision)
    policy = Policy(ckpt, a.device, t5_dir=a.t5)
    ref = policy.iface == "ref"
    print(f"checkpoint {ckpt}: {'PoP (points + skill)' if ref else 'sentence baseline'}, step {policy.step}, device {a.device}")
    if ref:
        cam_json = a.camera
        if not cam_json:
            from huggingface_hub import hf_hub_download
            cam_json = hf_hub_download(a.repo, f"finetune/data/cameras/{spec['dataset']}.json", revision=a.revision)
        cam = Camera(cam_json, a.urdf)
    else:
        text = policy.instruction_of(spec["dataset"])
        cond_sent = policy.instruction_cond(text)
        print(f"instruction: {text!r}")

    window = None
    if not a.no_window:
        try:
            window = Window()
        except Exception as e:  # noqa: BLE001  (headless OpenCV build)
            sys.exit(f"no OpenCV window ({e}); install opencv-python (GUI build) or run with --no-window --points ...")

    robot = make_robot(a)
    robot.connect()
    log, info = [], {}
    try:
        obs = robot.get_observation()
        H, W = obs["front"].shape[:2]
        if (W, H) != (a.cam_width, a.cam_height):
            print(f"warning: front camera gives {W}x{H}, training frames were 640x480")
        if ref:
            if a.points:
                px = parse_points(a.points)
            elif window is not None:
                px = window.click_points(robot, spec["points"])
            else:
                sys.exit(f"--points needed for task {a.task}: " + ", ".join(n for n, _ in spec["points"]))
            print("points (reuse with --points): '" + " ".join(f"{k}={u:.0f},{v:.0f}" for k, (u, v) in px.items()) + "'")
            tracker = StepTracker(a.task, {k: pixel_to_xy(u, v, W, H) for k, (u, v) in px.items()}, cam)
            info["points_px"] = {k: list(v) for k, v in px.items()}
        t = time.perf_counter()  # warm-up call (the first one is slow), timed
        policy.act(obs["front"], obs["wrist"], obs_state(obs),
                   policy.referent_cond(**tracker.update(obs_state(obs), resize_256(obs["front"]) if a.task == "push" else None))
                   if ref else cond_sent)
        print(f"policy call: {time.perf_counter() - t:.2f} s (warm-up)")
        if ref:  # the warm-up fed the tracker one tick: start it again
            tracker = StepTracker(a.task, tracker.points, cam)
        wait_start(robot, window)

        period, sub = 1.0 / HZ, a.servo_hz // HZ
        t0, tick, targets, k0, stop = time.perf_counter(), 0, None, 0, False
        while not stop and time.perf_counter() - t0 < a.max_seconds:
            t_tick = time.perf_counter()
            obs = robot.get_observation()
            state = obs_state(obs)
            if ref:
                kw = tracker.update(state, resize_256(obs["front"]) if a.task == "push" else None)
            replan = targets is None or tick - k0 >= a.replan
            if replan:
                cond = policy.referent_cond(**kw) if ref else cond_sent
                targets, k0 = policy.act(obs["front"], obs["wrist"], state, cond), tick
            k = tick - k0
            for s in range(sub):
                q = targets[k] + (s / sub) * (targets[k + 1] - targets[k])
                sent = robot.send_action({f"{j}.pos": float(v) for j, v in zip(JOINTS, q)})
                if s == 0:
                    first_sent = np.array([sent[f"{j}.pos"] for j in JOINTS], np.float32)
                while time.perf_counter() < t_tick + (s + 1) * period / sub:
                    time.sleep(0.001)
            row = {"t": t_tick - t0, "state": state, "target": targets[k], "sent": first_sent, "replan": replan}
            if ref:
                row |= {"step": tracker.k, "in_hand": tracker.in_hand, "what_xy": kw["what_xy"], "tip_xy": kw["tip_xy"],
                        "where_xy": kw["where_xy"] if kw["where_xy"] is not None else np.full(2, np.nan, np.float32)}
            log.append(row)
            if window is not None:
                marks, lines = [], [f"t {t_tick - t0:4.1f} s"]
                if ref:
                    for key, color, label in (("what_xy", (0, 200, 0), "object"), ("where_xy", (0, 0, 255), "destination"),
                                              ("tip_xy", (255, 128, 0), "tip")):
                        if kw[key] is not None:
                            marks.append((xy_to_pixel(kw[key], W, H), color, label))
                    lines.append(f"step {tracker.k + 1}/{len(spec['steps'])} {tracker.skill}"
                                 f"{', object in hand' if tracker.in_hand else ''}  (n, g, q)")
                key = window.show(obs["front"], marks, lines)
                if key in (ord("q"), 27):
                    stop = True
                elif ref and key == ord("n"):
                    tracker.next_step()
                elif ref and key == ord("g"):
                    tracker.toggle_in_hand()
            tick += 1
        print(f"stopped after {time.perf_counter() - t0:.1f} s")
    except KeyboardInterrupt:
        print("stopped")
    finally:
        try:
            input("Support the arm, then press Enter to switch its torque off and disconnect. ")
        except (KeyboardInterrupt, EOFError):
            pass
        robot.disconnect()
        if a.save and log:
            os.makedirs(os.path.dirname(os.path.abspath(a.save)), exist_ok=True)
            arrays = {k: np.stack([np.asarray(r[k]) for r in log]) for k in log[0]}
            np.savez(a.save, **arrays, info=json.dumps(info | {"args": vars(a), "checkpoint": ckpt}))
            print("log written to", a.save)


if __name__ == "__main__":
    main()