File size: 16,808 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
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
"""Roll-out runtime for the fine-tuned SO-101 checkpoints (scripts/finetune.py). It loads a checkpoint, turns camera
frames, joint readings and the operator's points into model inputs exactly as in training, and tracks the active step
of the task with causal versions of the rules that made the training labels (scripts/label_events.py).

Units: joints as LeRobot's SO-101 follower reports them with use_degrees=True (arm joints in degrees, zero at the
middle of the calibrated range; gripper 0 = closed to 100 = open). Points: pixels of the fixed camera ("front") image.
Used by scripts/rollout.py (robot) and scripts/check_runtime.py (recorded episodes, no robot).
"""
from __future__ import annotations

import json
import math

import numpy as np
import torch
import torch.nn.functional as F

from popt.model import PopFinetune, warp
from popt.so101 import SO101

JOINTS = ("shoulder_pan", "shoulder_lift", "elbow_flex", "wrist_flex", "wrist_roll", "gripper")
RES = 256  # training images: the 640 x 480 frames squashed to 256 x 256 (scripts/convert_v3.py)
HZ = 10    # training rate: one observation and one action target every 0.1 s
SKILLS = {"open": 0, "pick_place": 1, "close": 2, "push": 3, "fold": 4}  # = scripts/label_events.py

# Per task: the training dataset (its instruction and fitted camera); the steps as (skill, object point, destination
# point), where a point is the name of an operator point, "@mug" (found by colour), "@close" (kept from the drawer's
# open step) or None; and the operator points with their prompts. As in the labels, an object point is where the
# fingertips' midpoint is when the gripper closes on the object, a destination where it is when the gripper opens.
TASKS = {
    "towel": {"dataset": "so101-fold-towel", "steps": [("fold", "grasp", "release")],
              "points": [("grasp", "towel: where the fingertips close (near corner or edge)"),
                         ("release", "where the fingertips open (far corner)")]},
    "cups": {"dataset": "so101-stack-cup-v4", "steps": [("pick_place", "grasp1", "release1"),
                                                        ("pick_place", "grasp2", "release2")],
             "points": [("grasp1", "pink cup: where the fingertips close"),
                        ("release1", "just above the beige cup: where the gripper opens"),
                        ("grasp2", "beige cup: where the fingertips close"),
                        ("release2", "just above the white cup: where the gripper opens")]},
    "drawer": {"dataset": "so101-drawer-v3", "steps": [("open", "handle", None), ("pick_place", "grasp", "release"),
                                                       ("close", "@close", None)],
               "points": [("handle", "drawer handle, drawer closed"),
                          ("grasp", "red block: where the fingertips close"),
                          ("release", "inside the open drawer: where the gripper opens")]},
    "push": {"dataset": "so101-push", "steps": [("push", "@mug", "goal")],
             "points": [("goal", "goal: where the centre of the mug should end up")]},
}


def pixel_to_xy(u: float, v: float, width: int, height: int) -> np.ndarray:
    """Pixel (u, v) of a width x height image -> the model's coordinates: [-1, 1] across the image, pixel centres at
    integers. The training images were resized without keeping the aspect ratio, so x and y scale separately."""
    return np.array([(u + 0.5) / width * 2 - 1, (v + 0.5) / height * 2 - 1], np.float32)


def xy_to_pixel(xy, width: int, height: int) -> tuple[float, float]:
    return (float(xy[0]) + 1) / 2 * width - 0.5, (float(xy[1]) + 1) / 2 * height - 0.5


def resize_256(rgb: np.ndarray) -> np.ndarray:
    """H x W x 3 uint8 RGB -> 256 x 256 by area averaging, as the converter's resize (aspect ratio not kept)."""
    if rgb.shape[:2] == (RES, RES):
        return np.ascontiguousarray(rgb)
    x = torch.from_numpy(np.ascontiguousarray(rgb)).permute(2, 0, 1)[None].float()
    y = F.adaptive_avg_pool2d(x, (RES, RES))
    return y[0].permute(1, 2, 0).round().clamp(0, 255).to(torch.uint8).numpy()


class Policy:
    """A fine-tuning checkpoint ready to act: act() returns the next 16 joint targets (absolute, LeRobot units), one
    per 0.1 s, the first one for the moment of the observation."""

    def __init__(self, ckpt_path: str, device: str = "cuda", t5_dir: str | None = None):
        ck = torch.load(ckpt_path, map_location="cpu", weights_only=False)
        cfg = ck.get("config", {})
        if "norm" not in ck or "iface" not in cfg:
            raise ValueError(f"{ckpt_path} is not a fine-tuning checkpoint; the pretraining checkpoint has no "
                             "conditioning and is not meant to be rolled out")
        assert ck.get("action_mode", "delta") == "delta", ck.get("action_mode")
        arch = cfg["arch"]
        self.iface, self.run_id, self.step, self.chunk = cfg["iface"], cfg.get("run_id"), ck.get("step"), arch["chunk"]
        if self.iface == "sent" and not t5_dir:
            raise ValueError("sentence checkpoints need t5_dir: a folder with T5-Efficient-Tiny's config.json")
        self.device = torch.device(device)
        self.model = PopFinetune(iface=self.iface, t5_dir=t5_dir, t5_pretrained=False, d=arch["d"],
                                 layers=arch["layers"], heads=arch["heads"], chunk=arch["chunk"])
        self.model.load_state_dict(ck["ema"], strict=True)
        self.model.to(self.device).eval()
        n = ck["norm"]
        self.mu_s, self.sd_s = np.array(n["state_mean"], np.float32), np.array(n["state_std"], np.float32)
        self.mu_d, self.sd_d = np.array(n["delta_mean"], np.float32), np.array(n["delta_std"], np.float32)
        self.instructions = [r["text"] for r in ck["instructions"]]
        self._ids = {r["text"]: r["ids"] for r in ck["instructions"]}
        self._by_dataset = {r.get("dataset", "").split("/")[-1]: r["text"] for r in ck["instructions"]}
        self.amp = self.device.type == "cuda"
        self._aff = torch.tensor([[1.0, 0.0, 0.0]], device=self.device)

    def instruction_of(self, dataset: str) -> str:
        """The training instruction of a dataset (TASKS[task]["dataset"])."""
        return self._by_dataset[dataset]

    def instruction_cond(self, text: str) -> dict:
        """Sentence checkpoints: one of the training instructions (tokenized in the checkpoint)."""
        if text not in self._ids:
            raise KeyError(f"not a training instruction: {text!r}; the checkpoint knows {self.instructions}")
        ids = torch.tensor([self._ids[text]], device=self.device)
        return {"ids": ids, "mask": ids != 0}

    def referent_cond(self, skill: str, what_xy, where_xy, tip_xy) -> dict:
        """PoP checkpoints: skill name, object point, destination point (None = no destination) and the projected
        gripper tip, all in the model's coordinates (pixel_to_xy)."""
        t = lambda x: torch.as_tensor(np.asarray(x, np.float32), device=self.device)[None].clamp(-2.0, 2.0)  # noqa: E731
        return {"what": t(what_xy), "where": t(where_xy if where_xy is not None else (0.0, 0.0)), "tip": t(tip_xy),
                "where_valid": torch.tensor([where_xy is not None], device=self.device),
                "skill": torch.tensor([SKILLS[skill]], device=self.device)}

    @torch.no_grad()
    def act(self, front_rgb: np.ndarray, wrist_rgb: np.ndarray, state, cond: dict) -> np.ndarray:
        """front_rgb, wrist_rgb: H x W x 3 uint8 RGB (resized to 256 x 256 here, as in training); state: the 6 joint
        values; cond: instruction_cond() or referent_cond(). -> (16, 6) absolute joint targets."""
        imgs = torch.from_numpy(np.stack([resize_256(front_rgb), resize_256(wrist_rgb)])).to(self.device)
        x = warp(imgs, self._aff.expand(2, 3))
        s = np.asarray(state, np.float32)
        st = torch.from_numpy((s - self.mu_s) / self.sd_s)[None].to(self.device)
        wv = torch.ones(1, dtype=torch.bool, device=self.device)
        with torch.autocast(self.device.type, dtype=torch.bfloat16, enabled=self.amp):
            pred = self.model(x[:1], x[1:], st, wv, cond)
        return s[None] + pred.float()[0].cpu().numpy() * self.sd_d + self.mu_d


def project_np(X: np.ndarray, cam: dict) -> np.ndarray:
    """Base-frame points (..., 3) -> pixels (..., 2) in the 256 x 256 image (= scripts/finetune.py project_np)."""
    w = np.asarray(cam["rotvec"], np.float64)
    th = np.linalg.norm(w)
    k = w / max(th, 1e-12)
    K = np.array([[0, -k[2], k[1]], [k[2], 0, -k[0]], [-k[1], k[0], 0]])
    R = np.eye(3) + math.sin(th) * K + (1 - math.cos(th)) * K @ K
    Y = X @ R.T + np.asarray(cam["t"])
    xy = Y[..., :2] / np.maximum(Y[..., 2:3], 1e-3)
    if "k1" in cam:
        r2 = (xy ** 2).sum(-1, keepdims=True)
        xy = xy * (1 + cam["k1"] * r2 + cam["k2"] * r2 ** 2)
    return xy * np.asarray(cam["f"]) + np.asarray(cam["c"])


class Camera:
    """A fitted fixed camera (scripts/fit_camera.py; finetune/data/cameras/*.json on the Hub) with SO-101 forward
    kinematics: the gripper tip in metres (robot base frame) and in the model's coordinates."""

    def __init__(self, camera_json: str, urdf: str):
        cj = json.load(open(camera_json))
        self.cam = dict(cj["camera"])
        if "distortion_k1_k2" in cj:
            self.cam["k1"], self.cam["k2"] = cj["distortion_k1_k2"]
        self.size = cj.get("image_size", RES)
        self.off = np.array(list(cj.get("joint_offsets_deg", [0.0] * 5)) + [0.0])
        self.arm = SO101(urdf, points_per_link=1, exclude=(".stl",))  # joints only: no meshes needed

    def tip(self, state) -> np.ndarray:
        return self.arm.tip((np.asarray(state, np.float64) + self.off)[None])[0]

    def to_xy(self, X) -> np.ndarray:
        uv = project_np(np.asarray(X, np.float64), self.cam)
        return ((uv + 0.5) / self.size * 2 - 1).astype(np.float32)


def yellow_mask(img: np.ndarray) -> np.ndarray:
    """= scripts/label_events.py yellow_mask (the push task's mug)."""
    x = img.astype(np.float32) / 255
    mx, mn = x.max(-1), x.min(-1)
    dd = mx - mn + 1e-6
    r, g, b = x[..., 0], x[..., 1], x[..., 2]
    h = np.where(mx == r, ((g - b) / dd) % 6, np.where(mx == g, (b - r) / dd + 2, (r - g) / dd + 4)) * 60
    s = dd / (mx + 1e-6)
    return (h >= 42) & (h <= 66) & (s >= 0.45) & (mx >= 0.35)


class StepTracker:
    """Active step, object point and destination point of a PoP roll-out, from the robot's own signals. Causal
    versions of the labelling rules (scripts/label_events.py), called once per 0.1 s:
      - Gripper events: close = the end of a fall of more than `delta` units within `win` ticks; open = a rise of more
        than `delta` within `win` ticks (seen 0.3 s after it starts; the labels place it at its start).
      - Towel, cups: the object point is the operator's point until the gripper closes (after it has opened once),
        then the gripper tip (the object is in the hand). The next open ends the step; on the last step the tip stays.
      - Drawer, open step: the handle point until the tip has come `pull_m` back toward the base from its farthest
        reach after the first open, then the tip. The step ends when the tip has risen `lift_m` above its lowest point
        since then; the tip position closest to the base in between (the handle of the open drawer) is the close
        step's object point. Pick-and-place: a close at `hold_min` units or more (a close below holds nothing) puts
        the block in the hand; the step ends when the gripper, once settled, leaves that value by more than
        `release_units` (opening or closing, as in the labels). Close step: to the end.
      - Push: the object point is the mug, found by colour (yellow) in the fixed view on every tick.
    next_step() and toggle_in_hand() let the operator override (scripts/rollout.py keys n and g)."""

    def __init__(self, task: str, points: dict, cam: Camera, delta: float = 6.0, win: int = 3, hold_min: float = 8.0,
                 release_units: float = 1.0, pull_m: float = 0.02, lift_m: float = 0.03, min_px: int = 30):
        self.task, self.spec, self.points, self.cam = task, TASKS[task], points, cam
        missing = [n for n, _ in self.spec["points"] if n not in points]
        assert not missing, f"missing points for {task}: {missing}"
        self.delta, self.win, self.hold_min, self.release_units = delta, win, hold_min, release_units
        self.pull_m, self.lift_m, self.min_px = pull_m, lift_m, min_px
        self.g_hold = None
        self.k, self.in_hand, self.g, self.falling, self.rising, self.last_event = 0, False, [], False, False, None
        self.seen_open = False
        self.r_max, self.z_min, self.r_best, self.close_X = -math.inf, math.inf, math.inf, None
        self.mug_px, self.tip3d, self.tip_xy, self.log = None, None, None, []

    @property
    def skill(self) -> str:
        return self.spec["steps"][self.k][0]

    def _next(self):
        if self.k < len(self.spec["steps"]) - 1:
            self.k += 1
            self.in_hand = False
            if self.spec["steps"][self.k][1] == "@close" and self.close_X is None:
                self.close_X = self.tip3d.copy()

    def next_step(self):
        self._next()

    def toggle_in_hand(self):
        self.in_hand = not self.in_hand
        if self.in_hand and self.task == "drawer" and self.k == 0:
            self.z_min, self.r_best, self.close_X = self.tip3d[2], math.hypot(*self.tip3d[:2]), self.tip3d.copy()

    def _events(self, g: float) -> str | None:
        self.g.append(g)
        if len(self.g) <= self.win:
            return None
        d = self.g[-1] - self.g[-1 - self.win]
        fall, rise = d < -self.delta, d > self.delta
        ev = None
        if self.falling and not fall:
            ev = "close"
        if rise and not self.rising and self.last_event != "open":
            ev = "open"
        self.falling, self.rising = fall, rise
        if ev:
            self.last_event = ev
        return ev

    def update(self, state, front_256: np.ndarray | None = None) -> dict:
        """state: the 6 joint values now; front_256: the fixed view at 256 x 256 (push only). -> keyword arguments of
        Policy.referent_cond."""
        self.tip3d = self.cam.tip(state)
        self.tip_xy = self.cam.to_xy(self.tip3d)
        g = float(state[5])
        ev = self._events(g)
        if self.task in ("towel", "cups"):
            if ev == "close" and not self.in_hand and self.seen_open:
                self.in_hand = True
            elif ev == "open" and self.in_hand and self.k < len(self.spec["steps"]) - 1:
                self._next()
        elif self.task == "drawer":
            r, z = math.hypot(*self.tip3d[:2]), self.tip3d[2]
            if self.k == 0:
                if not self.in_hand:
                    if self.seen_open or ev == "open":
                        self.r_max = max(self.r_max, r)
                        if self.r_max - r >= self.pull_m:
                            self.toggle_in_hand()
                else:
                    self.z_min = min(self.z_min, z)
                    if r < self.r_best:
                        self.r_best, self.close_X = r, self.tip3d.copy()
                    if z - self.z_min >= self.lift_m:
                        self._next()
            elif self.k == 1:
                if not self.in_hand:
                    if ev == "close" and g >= self.hold_min:
                        self.in_hand, self.g_hold = True, None
                elif self.g_hold is None:
                    if self.g[-1] >= self.g[-1 - self.win] - 0.5:  # settled: no longer closing
                        self.g_hold = g
                elif abs(g - self.g_hold) > self.release_units or ev == "open":
                    self._next()
        elif self.task == "push" and front_256 is not None:
            ys, xs = np.nonzero(yellow_mask(front_256))
            if len(xs) >= self.min_px:
                self.mug_px = (xs.mean(), ys.mean())
        if ev == "open":
            self.seen_open = True
        skill, what, where = self.spec["steps"][self.k]
        if self.in_hand:
            what_xy = self.tip_xy
        elif what == "@mug":
            if self.mug_px is None:
                raise RuntimeError("push: the mug (yellow) is not visible in the fixed view")
            what_xy = ((np.array(self.mug_px) + 0.5) / RES * 2 - 1).astype(np.float32)
        elif what == "@close":
            what_xy = self.cam.to_xy(self.close_X)
        else:
            what_xy = self.points[what]
        out = {"skill": skill, "what_xy": what_xy, "where_xy": self.points[where] if where else None,
               "tip_xy": self.tip_xy}
        self.log.append({"step": self.k, "in_hand": self.in_hand, "event": ev})
        return out