File size: 12,768 Bytes
3aa087b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2026 Tenstorrent USA, Inc.
# SPDX-License-Identifier: Apache-2.0
"""Agreement of the served tt-nn X-VLA with the upstream LeRobot X-VLA on CPU.

Three steps, on a sample set written by ``scripts/extract_samples.py``:

1. ``served``: send every sample to a running server (``POST /predict``) for each
   ``--steps`` setting, with seed ``--seed-base + sample id``; save the action chunks.
2. ``reference``: run the upstream ``lerobot`` ``XVLAPolicy`` in float32 on the CPU (same
   weights) on exactly the batch the server builds (its own ``_build_batch``: decode,
   /255, ImageNet normalisation, ``resize_with_pad`` to 224x224, BART tokens), with the same
   seed and the same flow-matching noise (``--noise bf16``: the noise tensor is drawn exactly
   as the served bfloat16 policy draws it, then cast to float32; ``--noise fp32``: the
   reference's own float32 draw). Needs no device.
3. ``compare``: per steps setting, PCC / MSE / max abs difference of the action chunks
   (the 10 meaningful ee6d channels -- xyz, 6-D rotation, gripper -- and all 20); the same
   PCC on the input-dependent part only (``centered``: both chunks minus the reference's mean
   chunk over the sample set, which removes the pattern common to every input); and the mean
   absolute error against the dataset's ground-truth actions when ``--gt-dims`` > 0.

    python scripts/eval_agreement.py served --url http://127.0.0.1:20000 --samples S --steps 1,10 --out tt.npz
    python scripts/eval_agreement.py reference --samples S --steps 1,10 --out ref.npz
    python scripts/eval_agreement.py compare --test tt.npz --ref ref.npz --samples S --out metrics.json [--gt-dims 2]
"""
from __future__ import annotations

import argparse
import base64
import http.client
import importlib.util
import json
import os
import socket
import sys
import time
import urllib.parse
from pathlib import Path

import numpy as np

CODE = Path(__file__).resolve().parents[1]
MEANINGFUL = 10  # ee6d: xyz(3) + rotation6d(6) + gripper(1); channels 10..19 are the second-arm slots


def _load_samples(d: Path) -> dict:
    doc = json.loads((d / "samples.json").read_text())
    for s in doc["samples"]:
        s["b64"] = [base64.b64encode((d / f).read_bytes()).decode("ascii") for f in s["images"]]
    return doc


def _steps(v: str) -> list[int]:
    return [int(x) for x in v.split(",") if x.strip()]


# ----------------------------------------------------------------------------------- served
def cmd_served(a) -> int:
    doc = _load_samples(a.samples)
    steps = _steps(a.steps)
    u = urllib.parse.urlparse(a.url)
    conn = http.client.HTTPConnection(u.hostname, u.port or 80, timeout=a.timeout)
    conn.connect()
    conn.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)  # no Nagle delay on small writes
    n = len(doc["samples"])
    acts = np.zeros((n, len(steps), 30, 20), np.float32)
    timing = np.zeros((n, len(steps), 4), np.float64)  # client, preprocess, inference, total (ms)
    for i, s in enumerate(doc["samples"]):
        for j, st in enumerate(steps):
            body = json.dumps(dict(images=s["b64"], instruction=s["task"], state=s["state"],
                                   num_denoising_steps=st, seed=a.seed_base + s["id"], domain_id=a.domain_id))
            t0 = time.perf_counter()
            conn.request("POST", "/predict", body=body, headers={"Content-Type": "application/json"})
            r = conn.getresponse()
            raw = r.read()
            dt = (time.perf_counter() - t0) * 1e3
            if r.status != 200:
                raise SystemExit(f"sample {s['id']} steps {st}: HTTP {r.status} {raw[:300]!r}")
            out = json.loads(raw)
            acts[i, j] = np.asarray(out["actions"], np.float32)
            tm = out["timing_ms"]
            timing[i, j] = (dt, tm["preprocess"], tm["inference"], tm["total"])
        if (i + 1) % 10 == 0:
            print(f"served {i + 1}/{n}", flush=True)
    np.savez(a.out, actions=acts, steps=np.asarray(steps), ids=np.asarray([s["id"] for s in doc["samples"]]),
             seeds=np.asarray([a.seed_base + s["id"] for s in doc["samples"]]), timing_ms=timing)
    info = json.loads(_get(conn, "/info"))
    Path(str(a.out) + ".info.json").write_text(json.dumps(info, indent=1))
    print(f"wrote {a.out}: {n} samples x steps {steps}")
    return 0


def _get(conn, path: str) -> bytes:
    conn.request("GET", path)
    r = conn.getresponse()
    return r.read()


# -------------------------------------------------------------------------------- reference
def _load_file_module(name: str, path: Path):
    spec = importlib.util.spec_from_file_location(name, str(path))
    m = importlib.util.module_from_spec(spec)
    sys.modules[name] = m
    spec.loader.exec_module(m)
    return m


def _resolve_weights(path):
    path = path or os.environ.get("XVLA_WEIGHTS_DIR")
    if path:
        return Path(path)
    from huggingface_hub import hf_hub_download

    repo = os.environ.get("HF_MODEL") or "lerobot/xvla-base"
    rev = os.environ.get("TT_WEIGHTS_REVISION") or None
    cfg = hf_hub_download(repo_id=repo, filename="config.json", revision=rev)
    hf_hub_download(repo_id=repo, filename="model.safetensors", revision=rev)
    return Path(cfg).parent


def cmd_reference(a) -> int:
    import torch

    if a.threads:
        torch.set_num_threads(a.threads)
    torch.set_grad_enabled(False)
    _load_file_module("xvla_lerobot_bootstrap", CODE / "benchmark" / "lerobot_bootstrap.py").install()
    if str(CODE) not in sys.path:
        sys.path.insert(0, str(CODE))
    import tt.server.app as app  # import is side-effect free (no device, no weights)
    from lerobot.configs.policies import PreTrainedConfig
    from lerobot.policies.xvla.modeling_xvla import XVLAPolicy, resize_with_pad

    weights = _resolve_weights(a.weights)
    config = PreTrainedConfig.from_pretrained(str(weights))
    config.device = "cpu"
    config.dtype = "float32"
    policy = XVLAPolicy.from_pretrained(str(weights), config=config)
    policy.eval()
    app.STATE.update(resize_with_pad=resize_with_pad, tokenizer=app._load_tokenizer(str(app.VENDORED_TOKENIZER_DIR)),
                     lang_tokens=a.lang_tokens)

    orig_randn = torch.randn
    calls = []

    def randn_like_served(*size, dtype=None, **kw):
        # generate_actions draws x1 = torch.randn(B, chunk, dim, dtype=target_dtype) once per chunk.
        calls.append(tuple(size))
        if a.noise == "bf16":
            return orig_randn(*size, dtype=torch.bfloat16, **kw).to(dtype or torch.float32)
        return orig_randn(*size, dtype=dtype, **kw)

    doc = _load_samples(a.samples)
    steps = _steps(a.steps)
    n = len(doc["samples"])
    acts = np.zeros((n, len(steps), 30, 20), np.float32)
    secs = np.zeros((n, len(steps)), np.float64)
    t_all = time.perf_counter()
    for i, s in enumerate(doc["samples"]):
        batch, _ = app._build_batch(s["b64"], s["task"], [float(x) for x in s["state"]], a.domain_id)
        for j, st in enumerate(steps):
            policy.config.num_denoising_steps = st
            policy.reset()
            torch.manual_seed(a.seed_base + s["id"])
            calls.clear()
            torch.randn = randn_like_served
            try:
                t0 = time.perf_counter()
                out = policy.predict_action_chunk(batch)
                secs[i, j] = time.perf_counter() - t0
            finally:
                torch.randn = orig_randn
            if len(calls) != 1:
                raise SystemExit(f"expected one noise draw per chunk, saw {calls}")
            acts[i, j] = out.detach().to(torch.float32).cpu().numpy()[0]
        if (i + 1) % 5 == 0:
            print(f"reference {i + 1}/{n} ({time.perf_counter() - t_all:.0f} s)", flush=True)
    np.savez(a.out, actions=acts, steps=np.asarray(steps), ids=np.asarray([s["id"] for s in doc["samples"]]),
             seeds=np.asarray([a.seed_base + s["id"] for s in doc["samples"]]), seconds=secs)
    meta = dict(torch=torch.__version__, threads=torch.get_num_threads(), noise=a.noise, weights=str(weights),
                dtype="float32", lang_tokens=a.lang_tokens, mean_seconds_per_chunk=secs.mean(axis=0).tolist())
    Path(str(a.out) + ".meta.json").write_text(json.dumps(meta, indent=1))
    print(f"wrote {a.out}: {n} samples x steps {steps}; {meta}")
    return 0


# ---------------------------------------------------------------------------------- compare
def _pcc(x: np.ndarray, y: np.ndarray) -> float:
    x = x.astype(np.float64).ravel() - x.mean()
    y = y.astype(np.float64).ravel() - y.mean()
    d = np.linalg.norm(x) * np.linalg.norm(y)
    return float(np.dot(x, y) / d) if d else float("nan")


def _block(t: np.ndarray, r: np.ndarray) -> dict:
    pcc = np.array([_pcc(t[i], r[i]) for i in range(len(t))])
    mse = ((t.astype(np.float64) - r) ** 2).mean(axis=(1, 2))
    mx = np.abs(t.astype(np.float64) - r).max(axis=(1, 2))
    return dict(pcc_mean=float(pcc.mean()), pcc_min=float(pcc.min()), pcc_median=float(np.median(pcc)),
                pcc_pooled=_pcc(t, r), mse_mean=float(mse.mean()), mse_max=float(mse.max()),
                max_abs=float(mx.max()), max_abs_median=float(np.median(mx)),
                ref_std=float(r.std()), n=int(len(t)))


def cmd_compare(a) -> int:
    T, R = np.load(a.test), np.load(a.ref)
    if not (np.array_equal(T["ids"], R["ids"]) and np.array_equal(T["seeds"], R["seeds"])):
        raise SystemExit("test and reference cover different samples or seeds")
    doc = json.loads((a.samples / "samples.json").read_text())
    gt = np.asarray([s["gt_actions"] for s in doc["samples"]], np.float64) if a.gt_dims else None
    res = dict(test=str(a.test), ref=str(a.ref), samples=doc.get("source", ""), samples_sha256=doc.get("sha256"),
               n=int(len(T["ids"])), per_steps={})
    for j, st in enumerate(T["steps"].tolist()):
        jr = R["steps"].tolist().index(st)
        t, r = T["actions"][:, j], R["actions"][:, jr]
        tm, rm = t[..., :MEANINGFUL].astype(np.float64), r[..., :MEANINGFUL].astype(np.float64)
        mean_chunk = rm.mean(axis=0, keepdims=True)
        row = dict(meaningful_10=_block(tm, rm), all_20=_block(t, r),
                   centered_10=_block(tm - mean_chunk, rm - mean_chunk))
        if gt is not None:
            g = gt[..., : a.gt_dims]
            row["gt_mae"] = dict(test=float(np.abs(t[..., : a.gt_dims] - g).mean()),
                                 ref=float(np.abs(r[..., : a.gt_dims] - g).mean()), dims=a.gt_dims)
        res["per_steps"][str(st)] = row
    Path(a.out).write_text(json.dumps(res, indent=1))
    for st, row in res["per_steps"].items():
        m = row["meaningful_10"]
        c = row["centered_10"]
        line = (f"steps {st:>2}: PCC mean {m['pcc_mean']:.6f} min {m['pcc_min']:.6f} pooled {m['pcc_pooled']:.6f} | "
                f"centered PCC pooled {c['pcc_pooled']:.4f} min {c['pcc_min']:.4f} (std {c['ref_std']:.4f}) | "
                f"MSE {m['mse_mean']:.3e} | max|d| {m['max_abs']:.3e} (ref std {m['ref_std']:.3f})")
        if "gt_mae" in row:
            line += f" | GT MAE test {row['gt_mae']['test']:.4f} ref {row['gt_mae']['ref']:.4f}"
        print(line)
    return 0


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = ap.add_subparsers(dest="cmd", required=True)
    p = sub.add_parser("served")
    p.add_argument("--url", required=True)
    p.add_argument("--timeout", type=float, default=300.0)
    p = sub.add_parser("reference")
    p.add_argument("--weights", default=None, help="checkpoint dir (default $XVLA_WEIGHTS_DIR or the HF snapshot)")
    p.add_argument("--noise", choices=("bf16", "fp32"), default="bf16")
    p.add_argument("--lang-tokens", type=int, default=int(os.environ.get("XVLA_LANG_TOKENS", "32")))
    p.add_argument("--threads", type=int, default=0)
    for p in sub.choices.values():
        p.add_argument("--samples", required=True, type=Path)
        p.add_argument("--steps", default="1,10")
        p.add_argument("--seed-base", type=int, default=1000)
        p.add_argument("--domain-id", type=int, default=0)
        p.add_argument("--out", required=True)
    p = sub.add_parser("compare")
    p.add_argument("--test", required=True)
    p.add_argument("--ref", required=True)
    p.add_argument("--samples", required=True, type=Path)
    p.add_argument("--gt-dims", type=int, default=0, help="compare the first N action channels with the dataset's")
    p.add_argument("--out", required=True)
    a = ap.parse_args()
    return {"served": cmd_served, "reference": cmd_reference, "compare": cmd_compare}[a.cmd](a)


if __name__ == "__main__":
    raise SystemExit(main())