File size: 5,680 Bytes
cfb943d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Client-side test of the pi0.5 MMB policy server (shared interface): sends real dataset frames (raw 480x640 RGB head /
wrist images, the stored canonical state, robot_id, task string) and checks the response format; compares the
predicted chunk with the training target (expert targets + recorded commands) and decodes it with the real base pose.
Usage: OPENPI_VIDEO_BACKEND=pyav HF_LEROBOT_HOME=/data/changyi/mmb/lerobot python test_server_client.py [--port 8000] [--n 20]"""
import argparse
import json
import random
import time
from pathlib import Path

import numpy as np
import pyarrow.parquet as pq
from lerobot.common.datasets.lerobot_dataset import LeRobotDataset
from openpi_client import websocket_client_policy

from openpi.policies import mmb_canonical_action as ca

ROOT = Path("/data/changyi/mmb/merged_v2t")
NAMES = {0: "go2_arm", 1: "sawyer_umi", 2: "stretch3"}


def to_uint8_hwc(img):
    x = np.asarray(img)
    if x.shape[0] == 3:
        x = np.transpose(x, (1, 2, 0))
    if x.dtype != np.uint8:
        x = np.clip(np.round(x * 255), 0, 255).astype(np.uint8)
    return x


def main():
    ap = argparse.ArgumentParser(); ap.add_argument("--port", type=int, default=8000); ap.add_argument("--n", type=int, default=20)
    a = ap.parse_args()
    client = websocket_client_policy.WebsocketClientPolicy("localhost", a.port)
    meta = client.get_server_metadata()
    print("server metadata:", json.dumps(meta, default=str), flush=True)
    H = int(meta["action_horizon"])
    ds = LeRobotDataset("mmb/v2t", video_backend="pyav")
    eps = [json.loads(l) for l in open(ROOT / "meta/episodes.jsonl")]
    src = [json.loads(l) for l in open(ROOT / "meta/source_map.jsonl")]
    offsets = np.concatenate([[0], np.cumsum([e["length"] for e in eps])])
    random.seed(7)
    by = {}
    for i, s in enumerate(src):
        by.setdefault(s["robot"], []).append(i)
    res = {r: {"pos_cm": [], "rot_deg": [], "grip_ok": [], "base_err": [], "ms": [], "dec_pos_cm": []} for r in ca.ROBOTS}
    fmt_ok = True
    for robot in ca.ROBOTS:
        for ep in random.sample(by[robot], a.n):
            L = eps[ep]["length"]; t = random.randrange(L)
            item = ds[int(offsets[ep] + t)]
            tab = pq.read_table(ROOT / f"data/chunk-{ep // 1000:03d}/episode_{ep:06d}.parquet",
                                columns=["observation.state_canonical", "action.command", "action.eef_target", "observation.base_pose", "actions"])
            S, Cm, G, B, A = (np.asarray(tab.column(c).to_pylist(), np.float64) for c in tab.column_names)
            rid = {"go2_arm": 0, "sawyer_umi": 1, "stretch3": 2}[robot]
            obs = {"observation/image": to_uint8_hwc(item["observation.images.head"]),
                   "observation/wrist_image": to_uint8_hwc(item["observation.images.wrist"]),
                   "observation/state": S[t].astype(np.float32), "robot_id": rid, "prompt": item["task"]}
            assert obs["observation/image"].shape == (480, 640, 3), obs["observation/image"].shape
            t0 = time.time(); out = client.infer(obs); ms = (time.time() - t0) * 1000
            act = np.asarray(out["actions"])
            fmt_ok &= act.shape == (H, 14) and act.dtype == np.float32 and bool(np.all(act[:, ~ca.ACTION_MASK[robot]] == 0))
            idx = np.minimum(t + np.arange(H), L - 1)
            gt = ca.action_chunk_from_targets(robot, S[t], G[idx], Cm[idx])
            r = res[robot]
            r["ms"].append(ms)
            r["pos_cm"].append(np.linalg.norm(act[:, ca.A_POS] - gt[:, ca.A_POS], axis=-1) * 100)
            Rp, Rg = ca.rot6d_to_rotmat(act[:, ca.A_ROT]), ca.rot6d_to_rotmat(gt[:, ca.A_ROT])
            r["rot_deg"].append(ca.rot_angle_deg(np.einsum("hji,hjk->hik", Rg, Rp)))
            r["grip_ok"].append(((act[:, ca.A_GRIP] > 0.5) == (gt[:, ca.A_GRIP] > 0.5)).astype(float))
            m = ca.ACTION_MASK[robot][:4]
            r["base_err"].append(np.abs(act[:, :4][:, m] - gt[:, :4][:, m]).max(1))
            dec = ca.decode_action_chunk(robot, act, S[t], B[idx])                    # world EEF target vs recorded expert target
            o = 4 if robot == "go2_arm" else 3
            r["dec_pos_cm"].append(np.linalg.norm(dec[:, o:o + 3] - A[idx][:, o:o + 3], axis=-1) * 100)
    summary = {"format_ok": bool(fmt_ok), "horizon": H}
    for robot, r in res.items():
        c = {k: np.concatenate([np.ravel(x) for x in v]) for k, v in r.items()}
        summary[robot] = {"requests": len(r["ms"]), "latency_ms_p50_max": [round(float(np.median(c["ms"])), 1), round(float(c["ms"].max()), 1)],
                          "eef_pos_err_cm_p50_p90": [round(float(np.percentile(c["pos_cm"], q)), 2) for q in (50, 90)],
                          "eef_rot_err_deg_p50_p90": [round(float(np.percentile(c["rot_deg"], q)), 2) for q in (50, 90)],
                          "gripper_agreement": round(float(c["grip_ok"].mean()), 3),
                          "base_cmd_abs_err_p50_p90": [round(float(np.percentile(c["base_err"], q)), 3) for q in (50, 90)],
                          "decoded_world_target_vs_recorded_cm_p50": round(float(np.median(c["dec_pos_cm"])), 2),
                          # same summary as the GR00T test: worst step of each chunk, median over requests
                          "chunk_max_median_pos_cm_rot_deg_base": [round(float(np.median([x.max() for x in r[k]])), 3)
                                                                   for k in ("pos_cm", "rot_deg", "base_err")],
                          "chunks_with_all_gripper_steps_correct": round(float(np.mean([x.min() for x in r["grip_ok"]])), 3)}
    print(json.dumps(summary, indent=1), flush=True)


if __name__ == "__main__":
    main()