Instructions to use khanhnd61/pop-so101 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- LeRobot
How to use khanhnd61/pop-so101 with LeRobot:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- Notebooks
- Google Colab
- Kaggle
File size: 12,494 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 | """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()
|