pop-so101 / code /scripts /check_runtime.py
khanhnd61's picture
Claude Opus 5.5
Roll-out on an SO-101 with LeRobot: code/ and model card section
5a3fcf5 verified
Raw History Blame Contribute Delete
12.5 kB
"""Check the roll-out runtime (popt/runtime.py) against training on recorded episodes, without a robot:
1. Policy.act on the stored 256 x 256 validation frames with the label points reproduces the training log's
validation L1 (same frames, same normalized error).
2. Frames decoded at full size and resized by resize_256, as on the robot, against the stored frames: pixel
difference and the change in predicted targets.
3. StepTracker against the labels on every labelled episode (train and val), fed only what the robot gives (joints;
the fixed view for push) and the label points as the operator's points: step agreement, object point error.
python scripts/check_runtime.py --shards ~/pop/realworld/shards --raw ~/pop/realworld/raw \
--runs ~/pop/realworld/runs --urdf ~/pop/realworld/so101_urdf/so101_new_calib.urdf \
--t5 ~/pop/realworld/weights/t5_efficient_tiny --out ~/pop/realworld/check_runtime.json
"""
import argparse
import json
import os
import sys
import av
import numpy as np
import torch
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from popt.runtime import SKILLS, TASKS, Camera, Policy, StepTracker, project_np, resize_256, yellow_mask # noqa: E402
from scripts.finetune import FTData, project_np as project_ft # noqa: E402
from scripts.label_events import yellow_mask as yellow_ft # noqa: E402
NAME = {v: k for k, v in SKILLS.items()}
TASK_OF = {spec["dataset"]: t for t, spec in TASKS.items()}
def val_l1(policy: Policy, shards: str, n_max: int | None = None):
task_ids = {t: k for k, t in enumerate(policy.instructions)}
vs = FTData(os.path.join(shards, "val"), policy.chunk, {"state_mean": policy.mu_s, "state_std": policy.sd_s,
"delta_mean": policy.mu_d, "delta_std": policy.sd_d}, task_ids, with_shard=True, ref=True,
need_labels=True)
idx = np.nonzero(vs.ok)[0][:n_max]
tot = np.zeros((len(vs.shards), 2))
for i in idx:
b = vs[int(i)]
s = vs.state[i]
if policy.iface == "ref":
cond = policy.referent_cond(NAME[int(b["skill"])], b["what_xy"].numpy(),
b["where_xy"].numpy() if bool(b["where_valid"]) else None, b["tip_xy"].numpy())
else:
cond = policy.instruction_cond(policy.instructions[int(b["task"])])
tg = policy.act(b["agent"].numpy(), b["wrist"].numpy(), s, cond)
pred = (tg - s - policy.mu_d) / policy.sd_d
err = np.abs(pred - b["actions"].numpy()).mean(-1)
m = b["act_mask"].numpy()
tot[int(b["shard"])] += [(err * m).sum(), m.sum()]
per = {s["dataset"].split("/")[-1]: round(float(x[0] / x[1]), 4) for s, x in zip(vs.shards, tot)}
return float(tot[:, 0].sum() / tot[:, 1].sum()), per, len(idx)
def decode_full(path: str, t0: float, idx: np.ndarray, fps: float) -> np.ndarray:
"""Frames idx (episode-relative) of the episode starting at t0 s, at full size (scripts/convert_v3.py timing)."""
want, out = set(int(j) for j in idx), {}
with av.open(path) as c:
s = c.streams.video[0]
c.seek(int(max(t0 - 1.0, 0.0) / s.time_base), stream=s, backward=True, any_frame=False)
for fr in c.decode(s):
if fr.time is None:
continue
j = int(round((fr.time - t0) * fps))
if j > idx[-1]:
break
if j in want and j not in out:
out[j] = fr.to_ndarray(format="rgb24")
return np.stack([out[int(j)] for j in idx])
def resize_check(policy: Policy, shards: str, raw: str, n_frames: int = 8):
from scripts.convert_v3 import episodes_meta
out = {}
idx_all = json.load(open(os.path.join(shards, "val", "index.json")))
for sh in idx_all["shards"]:
d = os.path.join(shards, "val", sh["dir"])
meta = json.load(open(os.path.join(d, "meta.json")))
name = sh["dataset"].split("/")[-1]
rd = os.path.join(raw, name)
info = json.load(open(os.path.join(rd, "meta", "info.json")))
fps, tf = float(info["fps"]), meta["target_fps"]
ep = json.load(open(os.path.join(d, "episodes.json")))[0]
em = {e["episode_index"]: e for e in episodes_meta(rd)}[ep["source_episode"]]
js = np.linspace(0, ep["length"] - 1, n_frames).round().astype(int)
native = np.minimum(np.round(js * fps / tf).astype(int), em["length"] - 1)
stored = np.memmap(os.path.join(d, "agent.u8"), np.uint8, "r", shape=(sh["frames"], 256, 256, 3))
stored_w = np.memmap(os.path.join(d, "wrist.u8"), np.uint8, "r", shape=(sh["frames"], 256, 256, 3))
r = {}
for key, st in (("front", stored), ("wrist", stored_w)):
vk = f"observation.images.{key}"
p = os.path.join(rd, info["video_path"].format(video_key=vk, chunk_index=em[f"videos/{vk}/chunk_index"],
file_index=em[f"videos/{vk}/file_index"]))
full = decode_full(p, em[f"videos/{vk}/from_timestamp"], native, fps)
mine = np.stack([resize_256(f) for f in full])
ref = np.asarray(st[ep["start"] + js])
diff = np.abs(mine.astype(np.int16) - ref.astype(np.int16))
r[key] = {"full_size": list(full.shape[1:3]), "mean_abs_px": round(float(diff.mean()), 3),
"p99_abs_px": float(np.percentile(diff, 99)), "max_abs_px": int(diff.max())}
r[f"_{key}"] = (full, ref)
z = np.load(os.path.join(d, "arrays.npz"))
lab = np.load(os.path.join(d, "ref.npz"))
cam = Camera(os.path.join(d, "camera.json"), ARGS.urdf)
dl = []
for k, j in enumerate(js):
i = ep["start"] + j
s = z["state"][i]
if policy.iface == "ref":
X = np.stack([lab["what"][i], lab["where"][i]])
xy = cam.to_xy(X)
cond = policy.referent_cond(NAME[int(lab["skill"][i])], xy[0], xy[1] if lab["where_valid"][i] else None,
cam.to_xy(lab["tip"][i]))
else:
cond = policy.instruction_cond(policy.instructions[0])
a = policy.act(r["_front"][0][k], r["_wrist"][0][k], s, cond)
b = policy.act(r["_front"][1][k], r["_wrist"][1][k], s, cond)
dl.append(np.abs((a - b) / policy.sd_d).mean())
del r["_front"], r["_wrist"]
r["pred_change_norm_l1_mean"] = round(float(np.mean(dl)), 4)
out[name] = r
return out
def first(mask):
return int(np.argmax(mask))
def tracker_check(shards: str, urdf: str):
res = {}
for split in ("train", "val"):
idx = json.load(open(os.path.join(shards, split, "index.json")))
for sh in idx["shards"]:
d = os.path.join(shards, split, sh["dir"])
name = sh["dataset"].split("/")[-1]
task = TASK_OF[name]
cam = Camera(os.path.join(d, "camera.json"), urdf)
z = np.load(os.path.join(d, "arrays.npz"))
lab = dict(np.load(os.path.join(d, "ref.npz")))
eps = json.load(open(os.path.join(d, "episodes.json")))
img = np.memmap(os.path.join(d, "agent.u8"), np.uint8, "r", shape=(sh["frames"], 256, 256, 3)) if task == "push" else None
tip_mine = np.stack([cam.tip(s) for s in z["state"][::25]])
r = res.setdefault(task, {"episodes": 0, "frames": 0, "step_agree": 0, "what_err_px": [], "where_agree": 0,
"tip_vs_label_m_max": 0.0, "lag_ticks": []})
r["tip_vs_label_m_max"] = max(r["tip_vs_label_m_max"], float(np.abs(tip_mine - lab["tip"][::25]).max()))
for e in eps:
sl = slice(e["start"], e["start"] + e["length"])
if not lab["ok"][sl].all():
continue
st, wl, dl, vl = lab["step"][sl], lab["what"][sl], lab["where"][sl], lab["where_valid"][sl]
wxy = cam.to_xy(wl)
p = {}
if task == "towel":
p = {"grasp": wxy[0], "release": cam.to_xy(dl[0])}
elif task == "cups":
a, b = first(st == 0), first(st == 1)
p = {"grasp1": wxy[a], "release1": cam.to_xy(dl[a]), "grasp2": wxy[b], "release2": cam.to_xy(dl[b])}
elif task == "drawer":
b = first(st == 1)
p = {"handle": wxy[0], "grasp": wxy[b], "release": cam.to_xy(dl[b])}
elif task == "push":
p = {"goal": cam.to_xy(dl[0])}
tr = StepTracker(task, p, cam)
ks, err, wv = [], [], []
for t in range(e["length"]):
i = e["start"] + t
out = tr.update(z["state"][i], np.asarray(img[i]) if img is not None else None)
ks.append(tr.k)
err.append(float(np.abs(out["what_xy"] - wxy[t]).max() * 128))
wv.append(out["where_xy"] is not None)
ks = np.array(ks)
r["episodes"] += 1
r["frames"] += e["length"]
r["step_agree"] += int((ks == st).sum())
r["where_agree"] += int((np.array(wv) == vl).sum())
r["what_err_px"] += err
for k in range(1, int(st.max()) + 1): # switch time: tracker minus labels, in ticks
if (ks == k).any():
r["lag_ticks"].append(first(ks == k) - first(st == k))
else:
r["lag_ticks"].append(None)
out = {}
for task, r in res.items():
e = np.array(r["what_err_px"])
lags = [x for x in r["lag_ticks"] if x is not None]
out[task] = {"episodes": r["episodes"], "frames": r["frames"],
"step_agree": round(r["step_agree"] / r["frames"], 4),
"where_valid_agree": round(r["where_agree"] / r["frames"], 4),
"what_err_px256_median": round(float(np.median(e)), 2),
"what_err_px256_p95": round(float(np.percentile(e, 95)), 2),
"what_err_over_6px": round(float((e > 6).mean()), 4),
"switches": len(r["lag_ticks"]), "switch_missed": sum(x is None for x in r["lag_ticks"]),
"switch_lag_ticks_median": float(np.median(lags)) if lags else None,
"switch_lag_ticks_range": [int(min(lags)), int(max(lags))] if lags else None,
"tip_vs_label_m_max": round(r["tip_vs_label_m_max"], 6)}
return out
def same_helpers():
rng = np.random.default_rng(0)
img = rng.integers(0, 256, (64, 64, 3), dtype=np.uint8)
cam = {"rotvec": [1.8, -1.5, 0.7], "t": [0.0, 0.2, 0.7], "f": [420.0, 560.0], "c": [128.0, 128.0], "k1": -0.7, "k2": 1.8}
X = rng.normal(0, 0.2, (100, 3))
return {"yellow_mask_equal": bool((yellow_mask(img) == yellow_ft(img)).all()),
"project_np_max_diff": float(np.abs(project_np(X, cam) - project_ft(X, cam)).max())}
def main():
global ARGS
p = argparse.ArgumentParser()
p.add_argument("--shards", required=True)
p.add_argument("--raw", required=True)
p.add_argument("--runs", required=True)
p.add_argument("--urdf", required=True)
p.add_argument("--t5", required=True)
p.add_argument("--check-runs", default="261121-so101-pop-s0,261121-so101-sent-lab-s0")
p.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
p.add_argument("--out", required=True)
ARGS = p.parse_args()
report = {"helpers": same_helpers()}
print(report["helpers"], flush=True)
report["tracker"] = tracker_check(ARGS.shards, ARGS.urdf)
print(json.dumps(report["tracker"], indent=1), flush=True)
for rid in ARGS.check_runs.split(","):
pol = Policy(os.path.join(ARGS.runs, rid, "ckpt", "step_040000.pt"), ARGS.device, ARGS.t5)
v, per, n = val_l1(pol, ARGS.shards)
logged = [ln for ln in open(os.path.join(ARGS.runs, rid, "train.log")) if ln.startswith("val step 40000 ")]
report[rid] = {"val_l1_runtime": round(v, 4), "per_dataset": per, "frames": n,
"logged": logged[0].strip() if logged else None, "resize": resize_check(pol, ARGS.shards, ARGS.raw)}
print(rid, json.dumps(report[rid], indent=1), flush=True)
json.dump(report, open(ARGS.out, "w"), indent=1)
if __name__ == "__main__":
main()