v2 eval code snapshot
Browse files- code_v2/agree_v2.py +21 -0
- code_v2/annotate_or.py +86 -0
- code_v2/annotate_par.py +78 -0
- code_v2/annotate_v2.py +71 -0
- code_v2/ckpt_delta.py +32 -0
- code_v2/correlate_v2.py +187 -0
- code_v2/dump_predictions_v2.py +85 -0
- code_v2/eval_sim_v2.py +97 -0
- code_v2/eval_sim_v3.py +116 -0
- code_v2/gt_intervals_v2.py +38 -0
- code_v2/make_subsets.py +16 -0
- code_v2/merge_mix_intervals.py +10 -0
- code_v2/profile_te.py +23 -0
- code_v2/prompt_bowl.json +17 -0
- code_v2/queue_v2.sh +28 -0
- code_v2/queue_v3.sh +37 -0
- code_v2/setup_train_box.sh +29 -0
- code_v2/so100_bowl_env.py +240 -0
- code_v2/subsets.json +1 -0
- code_v2/train_v2.sh +25 -0
code_v2/agree_v2.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json, numpy as np, os
|
| 2 |
+
def iou(a, b):
|
| 3 |
+
i = max(0, min(a[1], b[1]) - max(a[0], b[0])); u = max(a[1], b[1]) - min(a[0], b[0]); return i / u if u > 0 else 0.0
|
| 4 |
+
rows = []
|
| 5 |
+
for s in ["s0", "s1", "s2"]:
|
| 6 |
+
gt = {r["episode"]: r for r in json.load(open(f"cimse/intervals_val_{s}_gt.json"))}
|
| 7 |
+
vl = {r["episode"]: r for r in json.load(open(f"cimse/intervals_val_{s}_vlm.json"))}
|
| 8 |
+
ok = [e for e in vl if e in gt and len(vl[e]["intervals"]) == 3]
|
| 9 |
+
I = np.array([[iou((gt[e]["intervals"][j]["start"], gt[e]["intervals"][j]["end"]), (vl[e]["intervals"][j]["start"], vl[e]["intervals"][j]["end"])) for j in range(3)] for e in ok])
|
| 10 |
+
E = np.array([[abs(vl[e]["intervals"][j][k] - gt[e]["intervals"][j][k]) for j in range(3) for k in ("start", "end")] for e in ok])
|
| 11 |
+
L = np.array([[vl[e]["intervals"][j]["end"] - vl[e]["intervals"][j]["start"] for j in range(3)] for e in ok])
|
| 12 |
+
print(f"{s}: n={len(ok)}/{len(vl)} IoU commit {I[:,0].mean():.2f} grasp {I[:,1].mean():.2f} release {I[:,2].mean():.2f} | VLM window len {L.mean(0).round(0).tolist()} | |boundary err| frames grasp s/e {E[:,2].mean():.0f}/{E[:,3].mean():.0f} release s/e {E[:,4].mean():.0f}/{E[:,5].mean():.0f}")
|
| 13 |
+
# val-mix VLM = prefix of each split's VLM list, sizes from the GT mix parts
|
| 14 |
+
sizes = [len(json.load(open(f"cimse/intervals_mix_part_{s}.json"))) for s in ["s0", "s1", "s2"]]
|
| 15 |
+
out = []; n = 0
|
| 16 |
+
for s, k in zip(["s0", "s1", "s2"], sizes):
|
| 17 |
+
vl = {r["episode"]: r for r in json.load(open(f"cimse/intervals_val_{s}_vlm.json"))}
|
| 18 |
+
for e in range(k):
|
| 19 |
+
r = dict(vl[e]) if e in vl else {"episode": e, "intervals": []}; r["episode"] = n; out.append(r); n += 1
|
| 20 |
+
json.dump(out, open("cimse/intervals_val_mix_vlm.json", "w"), indent=1)
|
| 21 |
+
print("val_mix VLM built:", n, "episodes; parts", sizes, "missing", sum(1 for r in out if len(r["intervals"]) != 3))
|
code_v2/annotate_or.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Critical-interval annotation of val episodes with Gemini (replicates ci_mse vlm_annotator prompt/parse,
|
| 2 |
+
but reads our LeRobot v3.0 dataset videos directly). Output JSON in ci_mse format with 30 Hz frame indices.
|
| 3 |
+
Usage: GEMINI_API_KEY=... python annotate_val.py --root datasets/so100_pickcube_val --out cimse/intervals_val.json [--model gemini-2.5-pro] [--episodes 0-39]
|
| 4 |
+
"""
|
| 5 |
+
import argparse, json, os, re, subprocess, sys, time, copy
|
| 6 |
+
import pandas as pd
|
| 7 |
+
ap = argparse.ArgumentParser()
|
| 8 |
+
ap.add_argument("--root", default="/workspace/cimse/datasets/so100_pickcube_val"); ap.add_argument("--out", required=True)
|
| 9 |
+
ap.add_argument("--prompt", default="/workspace/cimse/sim/prompt_bowl.json"); ap.add_argument("--model", default="gemini-2.5-pro"); ap.add_argument("--max-episodes", type=int, default=0)
|
| 10 |
+
ap.add_argument("--cam", default="observation.images.cam0"); ap.add_argument("--downsample", type=int, default=3)
|
| 11 |
+
ap.add_argument("--episodes", default=None); ap.add_argument("--samples", type=int, default=1); ap.add_argument("--workers", type=int, default=24); ap.add_argument("--workdir", default="/workspace/cimse/cimse/anno_tmp")
|
| 12 |
+
a = ap.parse_args(); os.makedirs(a.workdir, exist_ok=True); os.makedirs(os.path.dirname(a.out), exist_ok=True)
|
| 13 |
+
|
| 14 |
+
# ---- prompt (verbatim logic from ci_mse/vlm_annotator/gemini_annotator.py) ----
|
| 15 |
+
def get_default_template(N):
|
| 16 |
+
b = ["You are given a short robot manipulation video.", f"Your task is to annotate {N} specific time intervals in the video with timestamps in seconds, accurate to one decimal place.", "", f"The {N} intervals are defined semantically as:", ""]
|
| 17 |
+
for i in range(N):
|
| 18 |
+
b += [f"{i+1}. Interval {i+1}:", " - Start: \"{interval_" + str(i) + "_start}\"", " - End: \"{interval_" + str(i) + "_end}\"", ""]
|
| 19 |
+
b += ["Requirements:", f"- Return exactly {N} intervals in a JSON object.", "- Each interval must have:", " - \"label\": a short description.",
|
| 20 |
+
" - \"start\": start time in seconds, with exactly one decimal place (e.g., 2.3).", " - \"end\": end time in seconds, with exactly one decimal place.",
|
| 21 |
+
"- Timestamps must be within the video duration.", "- If you are uncertain, make your best estimate based on the visual evidence, but still output valid timestamps.",
|
| 22 |
+
"- If there are retries, only return the last attempt's timestamps." "", "Output format:",
|
| 23 |
+
"Return ONLY a valid JSON object, with no extra text, no explanations, and no Markdown code fences.", "", "The JSON format must be exactly:", "",
|
| 24 |
+
"{\n \"intervals\": [\n {\n \"label\": \"<description text>\",\n \"start\": <time in seconds, 1 decimal place>,\n \"end\": <time in seconds, 1 decimal place>\n },\n ... one object per interval above ...\n ]\n}", ""]
|
| 25 |
+
return "\n".join(b)
|
| 26 |
+
pd_ = json.load(open(a.prompt)); N = len(pd_["intervals"])
|
| 27 |
+
mapping = {"task": pd_["task"], "num_intervals": str(N)}
|
| 28 |
+
for i, iv in enumerate(pd_["intervals"]): mapping[f"interval_{i}_start"] = iv["start"]; mapping[f"interval_{i}_end"] = iv["end"]
|
| 29 |
+
instruction = pd_.get("template", get_default_template(N))
|
| 30 |
+
for k, v in mapping.items(): instruction = instruction.replace("{" + k + "}", v)
|
| 31 |
+
|
| 32 |
+
# ---- dataset episodes -> per-episode mp4 (cam0), downsampled ----
|
| 33 |
+
info = json.load(open(f"{a.root}/meta/info.json")); fps = int(info["fps"])
|
| 34 |
+
import glob
|
| 35 |
+
ep_meta = pd.concat([pd.read_parquet(p) for p in sorted(glob.glob(f"{a.root}/meta/episodes/**/*.parquet", recursive=True))])
|
| 36 |
+
vid_col = [c for c in ep_meta.columns if c.startswith(f"videos/{a.cam}/from_timestamp")][0]
|
| 37 |
+
vid_end = vid_col.replace("from_timestamp", "to_timestamp"); chunk_c = f"videos/{a.cam}/chunk_index"; file_c = f"videos/{a.cam}/file_index"
|
| 38 |
+
eps = list(range(int(ep_meta["episode_index"].max()) + 1))
|
| 39 |
+
if a.episodes: s, e = a.episodes.split("-"); eps = list(range(int(s), int(e) + 1))
|
| 40 |
+
if a.max_episodes: eps = [e for e in eps if e < a.max_episodes]
|
| 41 |
+
|
| 42 |
+
import base64, httpx
|
| 43 |
+
API_KEY = os.environ["OPENROUTER_API_KEY"]
|
| 44 |
+
def annotate_intervals_express(clip, instruction, model, key, N):
|
| 45 |
+
"""OpenRouter (OpenAI-compatible) backend: inline mp4 as data URL + same instruction text; returns model text."""
|
| 46 |
+
b64 = base64.b64encode(open(clip, "rb").read()).decode()
|
| 47 |
+
body = {"model": "google/" + model, "temperature": 1.0,
|
| 48 |
+
"messages": [{"role": "user", "content": [{"type": "text", "text": instruction}, {"type": "video_url", "video_url": {"url": "data:video/mp4;base64," + b64}}]}]}
|
| 49 |
+
r = httpx.post("https://openrouter.ai/api/v1/chat/completions", headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"}, json=body, timeout=180)
|
| 50 |
+
if r.status_code != 200: raise RuntimeError(f"{r.status_code}: {r.text[:300]}")
|
| 51 |
+
return r.json()["choices"][0]["message"]["content"]
|
| 52 |
+
import concurrent.futures as cf, threading
|
| 53 |
+
lock = threading.Lock()
|
| 54 |
+
ap2 = None
|
| 55 |
+
results = json.load(open(a.out)) if os.path.exists(a.out) else []
|
| 56 |
+
done = {(r["episode"], r.get("sample", 0)) for r in results}
|
| 57 |
+
raw_log = open(a.out.replace(".json", "_raw.txt"), "a")
|
| 58 |
+
def clip_for(ep):
|
| 59 |
+
row = ep_meta[ep_meta["episode_index"] == ep].iloc[0]
|
| 60 |
+
src = f"{a.root}/videos/{a.cam}/chunk-{int(row[chunk_c]):03d}/file-{int(row[file_c]):03d}.mp4"
|
| 61 |
+
t0, t1 = float(row[vid_col]), float(row[vid_end]); clip = f"{a.workdir}/ep{ep:03d}.mp4"
|
| 62 |
+
if not os.path.exists(clip): subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-ss", f"{t0:.3f}", "-to", f"{t1:.3f}", "-i", src, "-vf", f"fps={fps/a.downsample}", "-c:v", "libx264", "-pix_fmt", "yuv420p", clip], check=True)
|
| 63 |
+
return clip, t0, t1
|
| 64 |
+
def job(ep, k):
|
| 65 |
+
clip, t0, t1 = clip_for(ep); text = None
|
| 66 |
+
for attempt in range(4):
|
| 67 |
+
try: text = annotate_intervals_express(clip, instruction, a.model, API_KEY, N); break
|
| 68 |
+
except Exception as ex: print(f"[retry {attempt}] ep{ep}/{k}: {str(ex)[:160]}", flush=True); time.sleep(5 * (attempt + 1))
|
| 69 |
+
with lock: raw_log.write(f"--- Episode {ep} sample {k} ---\n{text}\n\n"); raw_log.flush()
|
| 70 |
+
if text is None: print("FAILED", ep, k, flush=True); return None
|
| 71 |
+
rc = text.strip(); m = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", rc, re.DOTALL)
|
| 72 |
+
if m: rc = m.group(1)
|
| 73 |
+
try: res = json.loads(rc)
|
| 74 |
+
except json.JSONDecodeError as ex: print("JSON fail", ep, k, str(ex)[:80], flush=True); return None
|
| 75 |
+
ivs = copy.deepcopy(res.get("intervals", []))
|
| 76 |
+
for iv in ivs: iv["start"] = int(round(float(iv["start"]) * fps)); iv["end"] = int(round(float(iv["end"]) * fps))
|
| 77 |
+
return {"episode": ep, "sample": k, "intervals": ivs, "duration_s": round(t1 - t0, 2)}
|
| 78 |
+
todo = [(ep, k) for ep in eps for k in range(a.samples) if (ep, k) not in done]
|
| 79 |
+
print(f"{len(todo)} calls, {a.workers} workers", flush=True)
|
| 80 |
+
with cf.ThreadPoolExecutor(a.workers) as ex:
|
| 81 |
+
for r in ex.map(lambda t: job(*t), todo):
|
| 82 |
+
if r is None: continue
|
| 83 |
+
with lock:
|
| 84 |
+
results.append(r); results.sort(key=lambda r: (r["episode"], r.get("sample", 0))); json.dump(results, open(a.out, "w"), indent=1)
|
| 85 |
+
print(f"ep{r['episode']}/{r['sample']} dur {r['duration_s']}s -> {[(iv['label'][:16], iv['start'], iv['end']) for iv in r['intervals']]}", flush=True)
|
| 86 |
+
print("ANNOTATE_DONE", len(results))
|
code_v2/annotate_par.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Critical-interval annotation of val episodes with Gemini (replicates ci_mse vlm_annotator prompt/parse,
|
| 2 |
+
but reads our LeRobot v3.0 dataset videos directly). Output JSON in ci_mse format with 30 Hz frame indices.
|
| 3 |
+
Usage: GEMINI_API_KEY=... python annotate_val.py --root datasets/so100_pickcube_val --out cimse/intervals_val.json [--model gemini-2.5-pro] [--episodes 0-39]
|
| 4 |
+
"""
|
| 5 |
+
import argparse, json, os, re, subprocess, sys, time, copy
|
| 6 |
+
import pandas as pd
|
| 7 |
+
ap = argparse.ArgumentParser()
|
| 8 |
+
ap.add_argument("--root", default="/workspace/cimse/datasets/so100_pickcube_val"); ap.add_argument("--out", required=True)
|
| 9 |
+
ap.add_argument("--prompt", default="/workspace/cimse/sim/prompt_bowl.json"); ap.add_argument("--model", default="gemini-2.5-pro"); ap.add_argument("--max-episodes", type=int, default=0)
|
| 10 |
+
ap.add_argument("--cam", default="observation.images.cam0"); ap.add_argument("--downsample", type=int, default=3)
|
| 11 |
+
ap.add_argument("--episodes", default=None); ap.add_argument("--samples", type=int, default=1); ap.add_argument("--workers", type=int, default=24); ap.add_argument("--workdir", default="/workspace/cimse/cimse/anno_tmp")
|
| 12 |
+
a = ap.parse_args(); os.makedirs(a.workdir, exist_ok=True); os.makedirs(os.path.dirname(a.out), exist_ok=True)
|
| 13 |
+
|
| 14 |
+
# ---- prompt (verbatim logic from ci_mse/vlm_annotator/gemini_annotator.py) ----
|
| 15 |
+
def get_default_template(N):
|
| 16 |
+
b = ["You are given a short robot manipulation video.", f"Your task is to annotate {N} specific time intervals in the video with timestamps in seconds, accurate to one decimal place.", "", f"The {N} intervals are defined semantically as:", ""]
|
| 17 |
+
for i in range(N):
|
| 18 |
+
b += [f"{i+1}. Interval {i+1}:", " - Start: \"{interval_" + str(i) + "_start}\"", " - End: \"{interval_" + str(i) + "_end}\"", ""]
|
| 19 |
+
b += ["Requirements:", f"- Return exactly {N} intervals in a JSON object.", "- Each interval must have:", " - \"label\": a short description.",
|
| 20 |
+
" - \"start\": start time in seconds, with exactly one decimal place (e.g., 2.3).", " - \"end\": end time in seconds, with exactly one decimal place.",
|
| 21 |
+
"- Timestamps must be within the video duration.", "- If you are uncertain, make your best estimate based on the visual evidence, but still output valid timestamps.",
|
| 22 |
+
"- If there are retries, only return the last attempt's timestamps." "", "Output format:",
|
| 23 |
+
"Return ONLY a valid JSON object, with no extra text, no explanations, and no Markdown code fences.", "", "The JSON format must be exactly:", "",
|
| 24 |
+
"{\n \"intervals\": [\n {\n \"label\": \"<description text>\",\n \"start\": <time in seconds, 1 decimal place>,\n \"end\": <time in seconds, 1 decimal place>\n },\n ... one object per interval above ...\n ]\n}", ""]
|
| 25 |
+
return "\n".join(b)
|
| 26 |
+
pd_ = json.load(open(a.prompt)); N = len(pd_["intervals"])
|
| 27 |
+
mapping = {"task": pd_["task"], "num_intervals": str(N)}
|
| 28 |
+
for i, iv in enumerate(pd_["intervals"]): mapping[f"interval_{i}_start"] = iv["start"]; mapping[f"interval_{i}_end"] = iv["end"]
|
| 29 |
+
instruction = pd_.get("template", get_default_template(N))
|
| 30 |
+
for k, v in mapping.items(): instruction = instruction.replace("{" + k + "}", v)
|
| 31 |
+
|
| 32 |
+
# ---- dataset episodes -> per-episode mp4 (cam0), downsampled ----
|
| 33 |
+
info = json.load(open(f"{a.root}/meta/info.json")); fps = int(info["fps"])
|
| 34 |
+
import glob
|
| 35 |
+
ep_meta = pd.concat([pd.read_parquet(p) for p in sorted(glob.glob(f"{a.root}/meta/episodes/**/*.parquet", recursive=True))])
|
| 36 |
+
vid_col = [c for c in ep_meta.columns if c.startswith(f"videos/{a.cam}/from_timestamp")][0]
|
| 37 |
+
vid_end = vid_col.replace("from_timestamp", "to_timestamp"); chunk_c = f"videos/{a.cam}/chunk_index"; file_c = f"videos/{a.cam}/file_index"
|
| 38 |
+
eps = list(range(int(ep_meta["episode_index"].max()) + 1))
|
| 39 |
+
if a.episodes: s, e = a.episodes.split("-"); eps = list(range(int(s), int(e) + 1))
|
| 40 |
+
if a.max_episodes: eps = [e for e in eps if e < a.max_episodes]
|
| 41 |
+
|
| 42 |
+
sys.path.insert(0, "/workspace/cimse/ci_mse"); from vlm_annotator.express_backend import annotate_intervals_express
|
| 43 |
+
API_KEY = os.environ["GEMINI_API_KEY"]
|
| 44 |
+
import concurrent.futures as cf, threading
|
| 45 |
+
lock = threading.Lock()
|
| 46 |
+
ap2 = None
|
| 47 |
+
results = json.load(open(a.out)) if os.path.exists(a.out) else []
|
| 48 |
+
done = {(r["episode"], r.get("sample", 0)) for r in results}
|
| 49 |
+
raw_log = open(a.out.replace(".json", "_raw.txt"), "a")
|
| 50 |
+
def clip_for(ep):
|
| 51 |
+
row = ep_meta[ep_meta["episode_index"] == ep].iloc[0]
|
| 52 |
+
src = f"{a.root}/videos/{a.cam}/chunk-{int(row[chunk_c]):03d}/file-{int(row[file_c]):03d}.mp4"
|
| 53 |
+
t0, t1 = float(row[vid_col]), float(row[vid_end]); clip = f"{a.workdir}/ep{ep:03d}.mp4"
|
| 54 |
+
if not os.path.exists(clip): subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-ss", f"{t0:.3f}", "-to", f"{t1:.3f}", "-i", src, "-vf", f"fps={fps/a.downsample}", "-c:v", "libx264", "-pix_fmt", "yuv420p", clip], check=True)
|
| 55 |
+
return clip, t0, t1
|
| 56 |
+
def job(ep, k):
|
| 57 |
+
clip, t0, t1 = clip_for(ep); text = None
|
| 58 |
+
for attempt in range(10):
|
| 59 |
+
try: text = annotate_intervals_express(clip, instruction, a.model, API_KEY, N); break
|
| 60 |
+
except Exception as ex: print(f"[retry {attempt}] ep{ep}/{k}: {str(ex)[:160]}", flush=True); time.sleep(min(60, 3 * 2 ** attempt))
|
| 61 |
+
with lock: raw_log.write(f"--- Episode {ep} sample {k} ---\n{text}\n\n"); raw_log.flush()
|
| 62 |
+
if text is None: print("FAILED", ep, k, flush=True); return None
|
| 63 |
+
rc = text.strip(); m = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", rc, re.DOTALL)
|
| 64 |
+
if m: rc = m.group(1)
|
| 65 |
+
try: res = json.loads(rc)
|
| 66 |
+
except json.JSONDecodeError as ex: print("JSON fail", ep, k, str(ex)[:80], flush=True); return None
|
| 67 |
+
ivs = copy.deepcopy(res.get("intervals", []))
|
| 68 |
+
for iv in ivs: iv["start"] = int(round(float(iv["start"]) * fps)); iv["end"] = int(round(float(iv["end"]) * fps))
|
| 69 |
+
return {"episode": ep, "sample": k, "intervals": ivs, "duration_s": round(t1 - t0, 2)}
|
| 70 |
+
todo = [(ep, k) for ep in eps for k in range(a.samples) if (ep, k) not in done]
|
| 71 |
+
print(f"{len(todo)} calls, {a.workers} workers", flush=True)
|
| 72 |
+
with cf.ThreadPoolExecutor(a.workers) as ex:
|
| 73 |
+
for r in ex.map(lambda t: job(*t), todo):
|
| 74 |
+
if r is None: continue
|
| 75 |
+
with lock:
|
| 76 |
+
results.append(r); results.sort(key=lambda r: (r["episode"], r.get("sample", 0))); json.dump(results, open(a.out, "w"), indent=1)
|
| 77 |
+
print(f"ep{r['episode']}/{r['sample']} dur {r['duration_s']}s -> {[(iv['label'][:16], iv['start'], iv['end']) for iv in r['intervals']]}", flush=True)
|
| 78 |
+
print("ANNOTATE_DONE", len(results))
|
code_v2/annotate_v2.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Critical-interval annotation of val episodes with Gemini (replicates ci_mse vlm_annotator prompt/parse,
|
| 2 |
+
but reads our LeRobot v3.0 dataset videos directly). Output JSON in ci_mse format with 30 Hz frame indices.
|
| 3 |
+
Usage: GEMINI_API_KEY=... python annotate_val.py --root datasets/so100_pickcube_val --out cimse/intervals_val.json [--model gemini-2.5-pro] [--episodes 0-39]
|
| 4 |
+
"""
|
| 5 |
+
import argparse, json, os, re, subprocess, sys, time, copy
|
| 6 |
+
import pandas as pd
|
| 7 |
+
ap = argparse.ArgumentParser()
|
| 8 |
+
ap.add_argument("--root", default="/workspace/cimse/datasets/so100_pickcube_val"); ap.add_argument("--out", required=True)
|
| 9 |
+
ap.add_argument("--prompt", default="/workspace/cimse/sim/prompt_bowl.json"); ap.add_argument("--model", default="gemini-2.5-pro"); ap.add_argument("--max-episodes", type=int, default=0)
|
| 10 |
+
ap.add_argument("--cam", default="observation.images.cam0"); ap.add_argument("--downsample", type=int, default=3)
|
| 11 |
+
ap.add_argument("--episodes", default=None); ap.add_argument("--workdir", default="/workspace/cimse/cimse/anno_tmp")
|
| 12 |
+
a = ap.parse_args(); os.makedirs(a.workdir, exist_ok=True); os.makedirs(os.path.dirname(a.out), exist_ok=True)
|
| 13 |
+
|
| 14 |
+
# ---- prompt (verbatim logic from ci_mse/vlm_annotator/gemini_annotator.py) ----
|
| 15 |
+
def get_default_template(N):
|
| 16 |
+
b = ["You are given a short robot manipulation video.", f"Your task is to annotate {N} specific time intervals in the video with timestamps in seconds, accurate to one decimal place.", "", f"The {N} intervals are defined semantically as:", ""]
|
| 17 |
+
for i in range(N):
|
| 18 |
+
b += [f"{i+1}. Interval {i+1}:", " - Start: \"{interval_" + str(i) + "_start}\"", " - End: \"{interval_" + str(i) + "_end}\"", ""]
|
| 19 |
+
b += ["Requirements:", f"- Return exactly {N} intervals in a JSON object.", "- Each interval must have:", " - \"label\": a short description.",
|
| 20 |
+
" - \"start\": start time in seconds, with exactly one decimal place (e.g., 2.3).", " - \"end\": end time in seconds, with exactly one decimal place.",
|
| 21 |
+
"- Timestamps must be within the video duration.", "- If you are uncertain, make your best estimate based on the visual evidence, but still output valid timestamps.",
|
| 22 |
+
"- If there are retries, only return the last attempt's timestamps." "", "Output format:",
|
| 23 |
+
"Return ONLY a valid JSON object, with no extra text, no explanations, and no Markdown code fences.", "", "The JSON format must be exactly:", "",
|
| 24 |
+
"{\n \"intervals\": [\n {\n \"label\": \"<description text>\",\n \"start\": <time in seconds, 1 decimal place>,\n \"end\": <time in seconds, 1 decimal place>\n },\n ... one object per interval above ...\n ]\n}", ""]
|
| 25 |
+
return "\n".join(b)
|
| 26 |
+
pd_ = json.load(open(a.prompt)); N = len(pd_["intervals"])
|
| 27 |
+
mapping = {"task": pd_["task"], "num_intervals": str(N)}
|
| 28 |
+
for i, iv in enumerate(pd_["intervals"]): mapping[f"interval_{i}_start"] = iv["start"]; mapping[f"interval_{i}_end"] = iv["end"]
|
| 29 |
+
instruction = pd_.get("template", get_default_template(N))
|
| 30 |
+
for k, v in mapping.items(): instruction = instruction.replace("{" + k + "}", v)
|
| 31 |
+
|
| 32 |
+
# ---- dataset episodes -> per-episode mp4 (cam0), downsampled ----
|
| 33 |
+
info = json.load(open(f"{a.root}/meta/info.json")); fps = int(info["fps"])
|
| 34 |
+
import glob
|
| 35 |
+
ep_meta = pd.concat([pd.read_parquet(p) for p in sorted(glob.glob(f"{a.root}/meta/episodes/**/*.parquet", recursive=True))])
|
| 36 |
+
vid_col = [c for c in ep_meta.columns if c.startswith(f"videos/{a.cam}/from_timestamp")][0]
|
| 37 |
+
vid_end = vid_col.replace("from_timestamp", "to_timestamp"); chunk_c = f"videos/{a.cam}/chunk_index"; file_c = f"videos/{a.cam}/file_index"
|
| 38 |
+
eps = list(range(int(ep_meta["episode_index"].max()) + 1))
|
| 39 |
+
if a.episodes: s, e = a.episodes.split("-"); eps = list(range(int(s), int(e) + 1))
|
| 40 |
+
if a.max_episodes: eps = [e for e in eps if e < a.max_episodes]
|
| 41 |
+
|
| 42 |
+
sys.path.insert(0, "/workspace/cimse/ci_mse"); from vlm_annotator.express_backend import annotate_intervals_express
|
| 43 |
+
API_KEY = os.environ["GEMINI_API_KEY"]
|
| 44 |
+
results = json.load(open(a.out)) if os.path.exists(a.out) else []
|
| 45 |
+
done = {r["episode"] for r in results}
|
| 46 |
+
raw_log = open(a.out.replace(".json", "_raw.txt"), "a")
|
| 47 |
+
for ep in eps:
|
| 48 |
+
if ep in done: continue
|
| 49 |
+
row = ep_meta[ep_meta["episode_index"] == ep].iloc[0]
|
| 50 |
+
src = f"{a.root}/videos/{a.cam}/chunk-{int(row[chunk_c]):03d}/file-{int(row[file_c]):03d}.mp4"
|
| 51 |
+
t0, t1 = float(row[vid_col]), float(row[vid_end])
|
| 52 |
+
clip = f"{a.workdir}/ep{ep:03d}.mp4"
|
| 53 |
+
subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-ss", f"{t0:.3f}", "-to", f"{t1:.3f}", "-i", src, "-vf", f"fps={fps/a.downsample}", "-c:v", "libx264", "-pix_fmt", "yuv420p", clip], check=True)
|
| 54 |
+
for attempt in range(3):
|
| 55 |
+
try:
|
| 56 |
+
text = annotate_intervals_express(clip, instruction, a.model, API_KEY, N); break
|
| 57 |
+
except Exception as ex:
|
| 58 |
+
print(f"[retry {attempt}] ep{ep}: {str(ex)[:200]}"); time.sleep(5 * (attempt + 1)); text = None
|
| 59 |
+
raw_log.write(f"--- Episode {ep} ---\n{text}\n\n"); raw_log.flush()
|
| 60 |
+
if text is None: print("FAILED", ep); continue
|
| 61 |
+
rc = text.strip()
|
| 62 |
+
m = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", rc, re.DOTALL)
|
| 63 |
+
if m: rc = m.group(1)
|
| 64 |
+
try: res = json.loads(rc)
|
| 65 |
+
except json.JSONDecodeError as ex: print("JSON fail", ep, ex, text[:200]); continue
|
| 66 |
+
ivs = copy.deepcopy(res.get("intervals", []))
|
| 67 |
+
for iv in ivs: iv["start"] = int(round(float(iv["start"]) * fps)); iv["end"] = int(round(float(iv["end"]) * fps))
|
| 68 |
+
results.append({"episode": ep, "intervals": ivs, "duration_s": round(t1 - t0, 2)})
|
| 69 |
+
results.sort(key=lambda r: r["episode"]); json.dump(results, open(a.out, "w"), indent=1)
|
| 70 |
+
print(f"ep{ep} dur {t1-t0:.1f}s -> {[(iv['label'][:20], iv['start'], iv['end']) for iv in ivs]}", flush=True)
|
| 71 |
+
print("ANNOTATE_DONE", len(results))
|
code_v2/ckpt_delta.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Checkpoint delta packing: all our MolmoAct2 ckpts share frozen tensors bit-identical to a reference ckpt (LoRA unmerged).
|
| 2 |
+
pack: python ckpt_delta.py pack <ref_pretrained_model> <ckpt_pretrained_model> <out.safetensors> # only tensors differing from ref
|
| 3 |
+
unpack: python ckpt_delta.py unpack <ref_pretrained_model> <delta.safetensors> <out_pretrained_model> # ref + delta -> full dir (copies config/json files from delta dir's sidecar)
|
| 4 |
+
"""
|
| 5 |
+
import sys, os, shutil, glob, json, torch
|
| 6 |
+
from safetensors import safe_open
|
| 7 |
+
from safetensors.torch import save_file
|
| 8 |
+
mode, ref, src, out = sys.argv[1:5]
|
| 9 |
+
if mode == "pack":
|
| 10 |
+
fr = safe_open(f"{ref}/model.safetensors", "pt"); fs = safe_open(f"{src}/model.safetensors", "pt")
|
| 11 |
+
delta = {}; same = 0
|
| 12 |
+
for k in fs.keys():
|
| 13 |
+
t = fs.get_tensor(k)
|
| 14 |
+
if k in fr.keys():
|
| 15 |
+
r = fr.get_tensor(k)
|
| 16 |
+
if r.shape == t.shape and r.dtype == t.dtype and torch.equal(r, t): same += 1; continue
|
| 17 |
+
delta[k] = t.contiguous()
|
| 18 |
+
meta = {"ref_keys_missing": json.dumps([k for k in fr.keys() if k not in fs.keys()])}
|
| 19 |
+
os.makedirs(os.path.dirname(out), exist_ok=True); save_file(delta, out, metadata=meta)
|
| 20 |
+
side = out + ".sidecar"; os.makedirs(side, exist_ok=True)
|
| 21 |
+
for f in glob.glob(f"{src}/*"):
|
| 22 |
+
if not f.endswith("model.safetensors"): (shutil.copytree if os.path.isdir(f) else shutil.copy2)(f, os.path.join(side, os.path.basename(f)), **({"dirs_exist_ok": True} if os.path.isdir(f) else {}))
|
| 23 |
+
print(f"PACK {src}: {len(delta)} tensors differ, {same} identical, delta {os.path.getsize(out)/1e9:.2f} GB")
|
| 24 |
+
else:
|
| 25 |
+
fr = safe_open(f"{ref}/model.safetensors", "pt"); fd = safe_open(src, "pt")
|
| 26 |
+
missing = set(json.loads(fd.metadata().get("ref_keys_missing", "[]")))
|
| 27 |
+
full = {k: fr.get_tensor(k) for k in fr.keys() if k not in missing}
|
| 28 |
+
for k in fd.keys(): full[k] = fd.get_tensor(k)
|
| 29 |
+
os.makedirs(out, exist_ok=True); save_file({k: v.contiguous() for k, v in full.items()}, f"{out}/model.safetensors", metadata=fr.metadata())
|
| 30 |
+
side = src + ".sidecar"
|
| 31 |
+
for f in glob.glob(f"{side}/*"): (shutil.copytree if os.path.isdir(f) else shutil.copy2)(f, os.path.join(out, os.path.basename(f)), **({"dirs_exist_ok": True} if os.path.isdir(f) else {}))
|
| 32 |
+
print(f"UNPACK -> {out}: {len(full)} tensors, {os.path.getsize(out + '/model.safetensors')/1e9:.2f} GB")
|
code_v2/correlate_v2.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""v2 offline-metric vs closed-loop correlation.
|
| 2 |
+
Inputs: results/<ckpt>/te/eval.json (TE success + phase outcomes), cimse/preds/<ckpt>/val_<split>/predictions.h5,
|
| 3 |
+
cimse/intervals_val_<split>_{gt,vlm}.json (3 windows: commit, grasp, release).
|
| 4 |
+
Outputs (cimse/report_v2/): table.csv, correlation.json, segments.json, scatter_<split>.png, summary.md
|
| 5 |
+
Metrics per (ckpt, split, source): raw_all, raw_win, ci, ci_ens8, ci_ens8_dtw1, ci_dtw1; plus per-window ci_ens8_dtw1 (commit/grasp/release).
|
| 6 |
+
Stats vs TE SR: Spearman rho, Kendall tau, Pearson (fine-tuned only), selection regret, top-3 precision, bootstrap CI on rho.
|
| 7 |
+
"""
|
| 8 |
+
import argparse, glob, json, os, sys, collections
|
| 9 |
+
import numpy as np, h5py
|
| 10 |
+
sys.path.insert(0, "/workspace/cimse/ci_mse")
|
| 11 |
+
from val_metrics.critical_interval_mse import CriticalIntervalMSE, CriticalIntervalMSEConfig
|
| 12 |
+
from scipy.stats import spearmanr, pearsonr, kendalltau
|
| 13 |
+
ap = argparse.ArgumentParser()
|
| 14 |
+
ap.add_argument("--root", default="/workspace/cimse"); ap.add_argument("--out", default="/workspace/cimse/cimse/report_v2")
|
| 15 |
+
ap.add_argument("--splits", nargs="+", default=["s0", "s1", "s2", "mix"]); ap.add_argument("--sources", nargs="+", default=["gt", "vlm", "vlm3"])
|
| 16 |
+
ap.add_argument("--boot", type=int, default=300)
|
| 17 |
+
a = ap.parse_args(); os.makedirs(a.out, exist_ok=True); R = a.root
|
| 18 |
+
CFG = {
|
| 19 |
+
"raw_win": CriticalIntervalMSEConfig(use_critical_intervals=True, use_horizon_truncation=False, use_temporal_ensemble=False, use_dtw=False),
|
| 20 |
+
"ci_ens8": CriticalIntervalMSEConfig(use_critical_intervals=True, use_horizon_truncation=False, use_temporal_ensemble=True, ensemble_horizon=8, use_dtw=False),
|
| 21 |
+
"ci_ens8_dtw1": CriticalIntervalMSEConfig(use_critical_intervals=True, use_horizon_truncation=False, use_temporal_ensemble=True, ensemble_horizon=8, use_dtw=True, dtw_window_size=1, interpolation_factor=1),
|
| 22 |
+
"ci_dtw1": CriticalIntervalMSEConfig(use_critical_intervals=True, use_horizon_truncation=False, use_temporal_ensemble=False, use_dtw=True, dtw_window_size=1, interpolation_factor=1),
|
| 23 |
+
}
|
| 24 |
+
WINDOWS = ["commit", "grasp", "release"]
|
| 25 |
+
|
| 26 |
+
def load_iv(path):
|
| 27 |
+
d = json.load(open(path)); by_ep = collections.defaultdict(list)
|
| 28 |
+
for r in d:
|
| 29 |
+
if len(r["intervals"]) >= 3: by_ep[r["episode"]].append(r["intervals"])
|
| 30 |
+
out = {}
|
| 31 |
+
for ep, samples in by_ep.items(): # multi-sample files (vlm3): per-window median of start/end across samples
|
| 32 |
+
out[ep] = {w: (int(np.median([s[i]["start"] for s in samples])), int(np.median([s[i]["end"] for s in samples]))) for i, w in enumerate(WINDOWS)}
|
| 33 |
+
return out
|
| 34 |
+
|
| 35 |
+
def load_h5(h5):
|
| 36 |
+
with h5py.File(h5) as f:
|
| 37 |
+
return f["predictions"][:], f["targets"][:], f["episode_index"][:], f["frame_local"][:]
|
| 38 |
+
|
| 39 |
+
def per_ep_windows(ep_idx, loc, ivmap, which):
|
| 40 |
+
changes = np.where(np.diff(ep_idx) != 0)[0] + 1; starts = np.concatenate([[0], changes]); ends = np.append(changes, len(ep_idx))
|
| 41 |
+
per_ep = []
|
| 42 |
+
for s, e in zip(starts, ends):
|
| 43 |
+
ep = int(ep_idx[s]); ivs = []
|
| 44 |
+
if ep in ivmap:
|
| 45 |
+
for w in which:
|
| 46 |
+
a0, a1 = ivmap[ep][w]; pos = np.where((loc[s:e] >= a0) & (loc[s:e] < a1))[0]
|
| 47 |
+
if len(pos): ivs.append((int(pos[0]), int(pos[-1]) + 1))
|
| 48 |
+
ivs.sort()
|
| 49 |
+
per_ep.append(ivs)
|
| 50 |
+
return ends.astype(np.int64), per_ep
|
| 51 |
+
|
| 52 |
+
# ---- collect checkpoints with TE eval ----
|
| 53 |
+
def load_eps(name, kinds):
|
| 54 |
+
eps = []
|
| 55 |
+
for k in kinds:
|
| 56 |
+
f = f"{R}/results/{name}/{k}/eval.json"
|
| 57 |
+
if os.path.exists(f): eps += json.load(open(f))["episodes"]
|
| 58 |
+
return eps
|
| 59 |
+
ckpts = sorted([os.path.basename(p) for p in glob.glob(f"{R}/results/*") if os.path.exists(f"{p}/ol1/eval.json")])
|
| 60 |
+
rows = []
|
| 61 |
+
for name in ckpts:
|
| 62 |
+
eps = load_eps(name, ["ol1", "ol2"]); n = len(eps) # headline: open-loop chunk execution, up to 200 eps
|
| 63 |
+
row = {"ckpt": name, "sr": float(np.mean([e["success"] for e in eps])), "n_eps": n, "grasp_rate": float(np.mean([e["ever_grasped"] for e in eps])), "wrong_cube_rate": float(np.mean([e["wrong_cube"] for e in eps]))}
|
| 64 |
+
ff = collections.Counter(e["first_failure"] for e in eps)
|
| 65 |
+
for k in ["wrong_cube", "commit_or_grasp", "grasp_lift", "carry", "release", "release_settle"]: row[f"fail_{k}"] = ff.get(k, 0) / n
|
| 66 |
+
te = load_eps(name, ["te"])
|
| 67 |
+
if te: row["sr_te"] = float(np.mean([e["success"] for e in te])); row["n_te"] = len(te)
|
| 68 |
+
def load_split(sp):
|
| 69 |
+
if sp != "mix":
|
| 70 |
+
h5 = f"{R}/cimse/preds/{name}/val_{sp}/predictions.h5"
|
| 71 |
+
return load_h5(h5) if os.path.exists(h5) else None
|
| 72 |
+
parts = [load_h5(f"{R}/cimse/preds/{name}/val_{q}/predictions.h5") for q in ["s0", "s1", "s2"] if os.path.exists(f"{R}/cimse/preds/{name}/val_{q}/predictions.h5")]
|
| 73 |
+
if len(parts) < 3: return None
|
| 74 |
+
off = 0; E = []
|
| 75 |
+
for P_, T_, e_, l_ in parts: E.append(e_ + off); off += int(e_.max()) + 1
|
| 76 |
+
return np.concatenate([p[0] for p in parts]), np.concatenate([p[1] for p in parts]), np.concatenate(E), np.concatenate([p[3] for p in parts])
|
| 77 |
+
def load_iv_split(sp, src):
|
| 78 |
+
if sp != "mix":
|
| 79 |
+
f = f"{R}/cimse/intervals_val_{sp}_{src}.json"; return load_iv(f) if os.path.exists(f) else None
|
| 80 |
+
out = {}; off = 0
|
| 81 |
+
for q in ["s0", "s1", "s2"]:
|
| 82 |
+
f = f"{R}/cimse/intervals_val_{q}_{src}.json"
|
| 83 |
+
if not os.path.exists(f): return None
|
| 84 |
+
m = load_iv(f); n_q = len(json.load(open(f"{R}/datasets/so100_bowl_val_{q}/meta/episode_targets.json"))["targets"])
|
| 85 |
+
out.update({ep + off: v for ep, v in m.items()}); off += n_q
|
| 86 |
+
return out
|
| 87 |
+
for sp in a.splits:
|
| 88 |
+
got = load_split(sp)
|
| 89 |
+
if got is None: continue
|
| 90 |
+
P, T, ep_idx, loc = got
|
| 91 |
+
row[f"raw_all[{sp}]"] = float(np.mean((P - T) ** 2))
|
| 92 |
+
for src in a.sources:
|
| 93 |
+
ivmap = load_iv_split(sp, src)
|
| 94 |
+
if ivmap is None: continue
|
| 95 |
+
ep_ends, per_ep = per_ep_windows(ep_idx, loc, ivmap, ["grasp", "release"]) # CI = contact windows (paper semantics)
|
| 96 |
+
for cname, cfg in CFG.items():
|
| 97 |
+
err, _, _ = CriticalIntervalMSE(cfg).compute(P, T, ep_ends, per_ep); row[f"{cname}[{sp},{src}]"] = float(np.mean(err)) if len(err) else np.nan
|
| 98 |
+
for w in WINDOWS: # per-window CI-MSE (ens8+dtw1) and plain
|
| 99 |
+
ep_ends_w, per_ep_w = per_ep_windows(ep_idx, loc, ivmap, [w])
|
| 100 |
+
for cname in ["raw_win", "ci_ens8_dtw1"]:
|
| 101 |
+
err, _, _ = CriticalIntervalMSE(CFG[cname]).compute(P, T, ep_ends_w, per_ep_w); row[f"{cname}@{w}[{sp},{src}]"] = float(np.mean(err)) if len(err) else np.nan
|
| 102 |
+
rows.append(row); print(name, "sr", row["sr"], "raw_all", {sp: round(row.get(f"raw_all[{sp}]", np.nan), 1) for sp in a.splits}, flush=True)
|
| 103 |
+
if not rows: sys.exit("no evaluated checkpoints")
|
| 104 |
+
|
| 105 |
+
# ---- statistics ----
|
| 106 |
+
def stats(x, y, ft_mask):
|
| 107 |
+
x, y = np.array(x, float), np.array(y, float); ok = ~np.isnan(x)
|
| 108 |
+
if ok.sum() < 4: return None
|
| 109 |
+
rho = spearmanr(x[ok], y[ok])[0]; tau = kendalltau(x[ok], y[ok])[0]
|
| 110 |
+
okf = ok & ft_mask; r_ft = pearsonr(x[okf], y[okf])[0] if okf.sum() >= 4 else np.nan
|
| 111 |
+
best_by = int(np.nanargmin(np.where(ok, x, np.inf))); regret = float(np.nanmax(y[ok]) - y[best_by])
|
| 112 |
+
top3_true = set(np.argsort(-np.where(ok, y, -np.inf))[:3]); top3_metric = set(np.argsort(np.where(ok, x, np.inf))[:3]); top3 = len(top3_true & top3_metric) / 3
|
| 113 |
+
return dict(spearman=float(rho), kendall=float(tau), pearson_ft=float(r_ft), regret=regret, top3=top3, n=int(ok.sum()))
|
| 114 |
+
sr = [r["sr"] for r in rows]; ft = np.array([not r["ckpt"].startswith("zeroshot") for r in rows])
|
| 115 |
+
metrics = sorted({k for r in rows for k in r if "[" in k and "@" not in k})
|
| 116 |
+
summary = {m: stats([r.get(m, np.nan) for r in rows], sr, ft) for m in metrics}
|
| 117 |
+
# bootstrap CI on rho (resample episodes -> SR noise) for headline metrics
|
| 118 |
+
rng = np.random.default_rng(0); boot = {}
|
| 119 |
+
ep_succ = {r["ckpt"]: np.array([e["success"] for e in load_eps(r["ckpt"], ["ol1", "ol2"])]) for r in rows}
|
| 120 |
+
for m in [k for k in metrics if k.startswith(("raw_all", "ci_ens8_dtw1"))]:
|
| 121 |
+
x = np.array([r.get(m, np.nan) for r in rows]); ok = ~np.isnan(x)
|
| 122 |
+
if ok.sum() < 4: continue
|
| 123 |
+
rs = []
|
| 124 |
+
for _ in range(a.boot):
|
| 125 |
+
y = np.array([ep_succ[r["ckpt"]][rng.integers(0, len(ep_succ[r["ckpt"]]), len(ep_succ[r["ckpt"]]))].mean() for r in rows]); rs.append(spearmanr(x[ok], y[ok])[0])
|
| 126 |
+
boot[m] = [float(np.percentile(rs, 2.5)), float(np.percentile(rs, 97.5))]
|
| 127 |
+
# per-window (phase) stats vs phase outcomes
|
| 128 |
+
seg = {}
|
| 129 |
+
for sp in a.splits:
|
| 130 |
+
for src in a.sources:
|
| 131 |
+
for w in WINDOWS:
|
| 132 |
+
for cname in ["raw_win", "ci_ens8_dtw1"]:
|
| 133 |
+
m = f"{cname}@{w}[{sp},{src}]"; x = [r.get(m, np.nan) for r in rows]
|
| 134 |
+
seg[m] = {"vs_sr": stats(x, sr, ft), "vs_grasp_rate": stats(x, [r["grasp_rate"] for r in rows], ft),
|
| 135 |
+
"vs_wrong_cube": stats(x, [1 - r["wrong_cube_rate"] for r in rows], ft),
|
| 136 |
+
"vs_release_fail": stats(x, [1 - r["fail_release"] - r["fail_release_settle"] for r in rows], ft)}
|
| 137 |
+
# data-scale family sign test: R2/R3/R4/R1 @3000
|
| 138 |
+
fam = [r for r in rows if r["ckpt"] in ("R2_p05_003000", "R3_p15_003000", "R4_p40_003000", "R1_p100_003000")]
|
| 139 |
+
family = {}
|
| 140 |
+
if len(fam) >= 3:
|
| 141 |
+
for m in [k for k in metrics if k.startswith(("raw_all", "ci_ens8_dtw1"))]:
|
| 142 |
+
x = [r.get(m, np.nan) for r in fam]; y = [r["sr"] for r in fam]
|
| 143 |
+
if not any(np.isnan(x)): family[m] = float(spearmanr(x, y)[0])
|
| 144 |
+
json.dump({"rows": rows, "correlations": summary, "bootstrap95": boot, "segments": seg, "data_scale_family": family,
|
| 145 |
+
"best_true": max(rows, key=lambda r: r["sr"])["ckpt"]}, open(f"{a.out}/correlation.json", "w"), indent=1)
|
| 146 |
+
import csv
|
| 147 |
+
with open(f"{a.out}/table.csv", "w") as f:
|
| 148 |
+
keys = ["ckpt", "sr", "n_eps", "grasp_rate", "wrong_cube_rate", "sr_te"] + metrics
|
| 149 |
+
w = csv.DictWriter(f, fieldnames=keys, extrasaction="ignore"); w.writeheader(); w.writerows(rows)
|
| 150 |
+
# ---- summary.md ----
|
| 151 |
+
L = [f"# v2 correlation — {len(rows)} checkpoints", "", "## Closed-loop success per checkpoint (headline = open-loop chunk execution)", "| ckpt | SR (open-loop) | n | grasp | wrong-cube | TE SR (control) |", "|---|---|---|---|---|---|"]
|
| 152 |
+
for r in sorted(rows, key=lambda r: r["ckpt"]): L.append(f"| {r['ckpt']} | {r['sr']:.2f} | {r['n_eps']} | {r['grasp_rate']:.2f} | {r['wrong_cube_rate']:.2f} | {r.get('sr_te', float('nan')):.2f} |")
|
| 153 |
+
L += ["", "## Spearman rho vs open-loop SR (Kendall tau) — rows: metric, cols: val split", "| metric | " + " | ".join(a.splits) + " |", "|---|" + "---|" * len(a.splits)]
|
| 154 |
+
for base in ["raw_all", "raw_win", "ci_ens8", "ci_ens8_dtw1", "ci_dtw1"]:
|
| 155 |
+
for src in (["-"] if base == "raw_all" else a.sources):
|
| 156 |
+
cells = []
|
| 157 |
+
for sp in a.splits:
|
| 158 |
+
m = f"raw_all[{sp}]" if base == "raw_all" else f"{base}[{sp},{src}]"; s = summary.get(m)
|
| 159 |
+
cells.append(f"{s['spearman']:+.2f} ({s['kendall']:+.2f})" if s else "—")
|
| 160 |
+
L.append(f"| {base}{'' if src=='-' else ' ['+src+']'} | " + " | ".join(cells) + " |")
|
| 161 |
+
L += ["", "## Selection regret (SR_best − SR_by_metric) / top-3 precision", "| metric | " + " | ".join(a.splits) + " |", "|---|" + "---|" * len(a.splits)]
|
| 162 |
+
for base in ["raw_all", "ci_ens8_dtw1"]:
|
| 163 |
+
for src in (["-"] if base == "raw_all" else a.sources):
|
| 164 |
+
cells = []
|
| 165 |
+
for sp in a.splits:
|
| 166 |
+
m = f"raw_all[{sp}]" if base == "raw_all" else f"{base}[{sp},{src}]"; s = summary.get(m)
|
| 167 |
+
cells.append(f"{s['regret']:.2f} / {s['top3']:.2f}" if s else "—")
|
| 168 |
+
L.append(f"| {base}{'' if src=='-' else ' ['+src+']'} | " + " | ".join(cells) + " |")
|
| 169 |
+
L += ["", "## Bootstrap 95% CI on rho (episode resampling)"] + [f"- {m}: [{v[0]:+.2f}, {v[1]:+.2f}]" for m, v in boot.items()]
|
| 170 |
+
L += ["", "## Data-scale family (R2/R3/R4/R1 @3000) Spearman"] + [f"- {m}: {v:+.2f}" for m, v in family.items()]
|
| 171 |
+
L += ["", "## Phase windows vs phase outcomes (Spearman; rows = window error, cols = outcome)", "| window metric | vs SR | vs grasp rate | vs (1−wrong-cube) | vs (1−release-fail) |", "|---|---|---|---|---|"]
|
| 172 |
+
for m, v in seg.items():
|
| 173 |
+
if "ci_ens8_dtw1" in m and ",gt]" in m and "[mix" in m: L.append(f"| {m} | " + " | ".join(f"{v[k]['spearman']:+.2f}" if v[k] else "—" for k in ["vs_sr", "vs_grasp_rate", "vs_wrong_cube", "vs_release_fail"]) + " |")
|
| 174 |
+
L += ["", f"best true checkpoint: {max(rows, key=lambda r: r['sr'])['ckpt']}"]
|
| 175 |
+
open(f"{a.out}/summary.md", "w").write("\n".join(L)); print("\n".join(L))
|
| 176 |
+
# scatter per split (ci_ens8_dtw1[gt] and raw_all), fine-tuned only
|
| 177 |
+
import matplotlib; matplotlib.use("Agg"); import matplotlib.pyplot as plt
|
| 178 |
+
fig, axs = plt.subplots(2, len(a.splits), figsize=(4.2 * len(a.splits), 7))
|
| 179 |
+
for j, sp in enumerate(a.splits):
|
| 180 |
+
for i, m in enumerate([f"raw_all[{sp}]", f"ci_ens8_dtw1[{sp},gt]"]):
|
| 181 |
+
ax = axs[i, j]; xs = [r.get(m, np.nan) for r in rows]
|
| 182 |
+
for r, x in zip(rows, xs):
|
| 183 |
+
if np.isnan(x) or r["ckpt"].startswith("zeroshot"): continue
|
| 184 |
+
c = {"R1": "tab:blue", "R2": "tab:red", "R3": "tab:orange", "R4": "tab:green", "R5": "tab:purple"}.get(r["ckpt"][:2], "gray")
|
| 185 |
+
ax.scatter(x, r["sr"], c=c, s=30); ax.annotate(r["ckpt"].replace("_p100", "").replace("_00", "@"), (x, r["sr"]), fontsize=6)
|
| 186 |
+
s = summary.get(m); ax.set_title(f"{m} ρ={s['spearman']:+.2f}" if s else m, fontsize=9); ax.set_xlabel("offline error (deg²)"); ax.set_ylabel("open-loop success"); ax.grid(alpha=.3)
|
| 187 |
+
fig.tight_layout(); fig.savefig(f"{a.out}/scatter.png", dpi=120); print("saved", a.out)
|
code_v2/dump_predictions_v2.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Offline prediction dump for CI-MSE: for every val frame t, predict action chunk [H, D] and pair with
|
| 2 |
+
ground-truth next-H actions. Writes HDF5 with predictions/targets/episode_ends/proprio (ci_mse val_metrics format).
|
| 3 |
+
Runs in .venv. Usage:
|
| 4 |
+
python dump_predictions.py --ckpt <pretrained_model_dir> --val-root /workspace/cimse/datasets/so100_pickcube_val \
|
| 5 |
+
--out /workspace/cimse/results/runA_1500/predictions.h5 --bs 16
|
| 6 |
+
"""
|
| 7 |
+
import argparse, os, sys, json, time
|
| 8 |
+
import numpy as np, torch, h5py
|
| 9 |
+
from lerobot.configs.policies import PreTrainedConfig
|
| 10 |
+
from lerobot.datasets.lerobot_dataset import LeRobotDataset, LeRobotDatasetMetadata
|
| 11 |
+
from lerobot.policies import make_policy, make_pre_post_processors
|
| 12 |
+
|
| 13 |
+
ap = argparse.ArgumentParser()
|
| 14 |
+
ap.add_argument("--ckpt", required=True); ap.add_argument("--val-root", default="/workspace/cimse/datasets/so100_pickcube_val")
|
| 15 |
+
ap.add_argument("--out", required=True); ap.add_argument("--bs", type=int, default=16)
|
| 16 |
+
ap.add_argument("--inference-steps", type=int, default=10); ap.add_argument("--seed", type=int, default=0)
|
| 17 |
+
ap.add_argument("--stride", type=int, default=1, help="evaluate every k-th frame (1 = all)")
|
| 18 |
+
ap.add_argument("--frames-json", default=None, help="JSON list of global frame indices to evaluate (overrides stride)")
|
| 19 |
+
ap.add_argument("--workers", type=int, default=16); ap.add_argument("--max-episodes", type=int, default=0, help="use only the first N episodes of the dataset (0 = all)")
|
| 20 |
+
a = ap.parse_args()
|
| 21 |
+
os.makedirs(os.path.dirname(a.out), exist_ok=True)
|
| 22 |
+
torch.manual_seed(a.seed)
|
| 23 |
+
|
| 24 |
+
pcfg = PreTrainedConfig.from_pretrained(a.ckpt); pcfg.pretrained_path = a.ckpt; pcfg.device = "cuda"
|
| 25 |
+
if hasattr(pcfg, "inference_action_mode"): pcfg.inference_action_mode = "continuous"
|
| 26 |
+
if hasattr(pcfg, "num_inference_steps"): pcfg.num_inference_steps = a.inference_steps
|
| 27 |
+
if hasattr(pcfg, "enable_inference_cuda_graph"): pcfg.enable_inference_cuda_graph = False
|
| 28 |
+
if hasattr(pcfg, "eval_seed"): pcfg.eval_seed = a.seed
|
| 29 |
+
H = pcfg.chunk_size
|
| 30 |
+
repo = "local/" + os.path.basename(a.val_root)
|
| 31 |
+
meta = LeRobotDatasetMetadata(repo_id=repo, root=a.val_root)
|
| 32 |
+
policy = make_policy(cfg=pcfg, ds_meta=meta); policy.eval()
|
| 33 |
+
pre, post = make_pre_post_processors(policy_cfg=pcfg, pretrained_path=a.ckpt, preprocessor_overrides={"device_processor": {"device": "cuda"}})
|
| 34 |
+
|
| 35 |
+
# dataset with action chunk targets: delta_timestamps gives action[t..t+H-1]
|
| 36 |
+
fps = meta.fps
|
| 37 |
+
ds = LeRobotDataset(repo_id=repo, root=a.val_root, delta_timestamps={"action": [i / fps for i in range(H)]}, video_backend="pyav")
|
| 38 |
+
D = meta.features["action"]["shape"][0]
|
| 39 |
+
N = len(ds)
|
| 40 |
+
idx = sorted(json.load(open(a.frames_json))) if a.frames_json else list(range(0, N, a.stride))
|
| 41 |
+
if a.max_episodes:
|
| 42 |
+
ep_of = ds.hf_dataset["episode_index"] if hasattr(ds, "hf_dataset") else None
|
| 43 |
+
import pandas as _pd, glob as _glob
|
| 44 |
+
_df = _pd.concat([_pd.read_parquet(p, columns=["episode_index"]) for p in sorted(_glob.glob(f"{a.val_root}/data/**/*.parquet", recursive=True))])
|
| 45 |
+
keep = set(np.where(_df["episode_index"].values < a.max_episodes)[0].tolist()); idx = [i for i in idx if i in keep]
|
| 46 |
+
preds = np.zeros((len(idx), H, D), np.float32); tgts = np.zeros((len(idx), H, D), np.float32)
|
| 47 |
+
proprio = np.zeros((len(idx), D), np.float32); ep_idx = np.zeros(len(idx), np.int64); pad = np.zeros((len(idx), H), bool); fr_loc = np.zeros(len(idx), np.int64)
|
| 48 |
+
t0 = time.time()
|
| 49 |
+
from torch.utils.data import DataLoader, Subset
|
| 50 |
+
def collate(rows):
|
| 51 |
+
batch = {}
|
| 52 |
+
for k in rows[0]:
|
| 53 |
+
v = rows[0][k]
|
| 54 |
+
if torch.is_tensor(v): batch[k] = torch.stack([r[k] for r in rows])
|
| 55 |
+
elif isinstance(v, str): batch[k] = [r[k] for r in rows]
|
| 56 |
+
batch["task"] = [r["task"] for r in rows]; return batch
|
| 57 |
+
loader = DataLoader(Subset(ds, idx), batch_size=a.bs, shuffle=False, num_workers=a.workers, collate_fn=collate, prefetch_factor=4 if a.workers else None)
|
| 58 |
+
with torch.inference_mode():
|
| 59 |
+
for bi, batch in enumerate(loader):
|
| 60 |
+
s = bi * a.bs; rows = range(len(batch["task"]))
|
| 61 |
+
gt = batch["action"].clone() # [B,H,D] degrees (dataset units)
|
| 62 |
+
padm = batch.get("action_is_pad")
|
| 63 |
+
inp = {k: v for k, v in batch.items() if not k.startswith("action")}
|
| 64 |
+
inp = pre(inp)
|
| 65 |
+
chunk = policy.predict_action_chunk(inp) # [B,H',D'] normalized
|
| 66 |
+
chunk = post(chunk[:, :H]) # unnormalize -> degrees, [B,H,D]
|
| 67 |
+
preds[s:s + len(rows)] = chunk[:, :, :D].float().cpu().numpy()
|
| 68 |
+
tgts[s:s + len(rows)] = gt[:, :, :D].numpy()
|
| 69 |
+
proprio[s:s + len(rows)] = batch["observation.state"][:, :D].numpy()
|
| 70 |
+
ep_idx[s:s + len(rows)] = batch["episode_index"].numpy()
|
| 71 |
+
fr_loc[s:s + len(rows)] = batch["frame_index"].numpy()
|
| 72 |
+
if padm is not None: pad[s:s + len(rows)] = padm.numpy()
|
| 73 |
+
if (s // a.bs) % 20 == 0: print(f"{s}/{len(idx)} {time.time()-t0:.0f}s", flush=True)
|
| 74 |
+
# episode_ends (cumulative) in the order frames were visited
|
| 75 |
+
changes = np.where(np.diff(ep_idx) != 0)[0] + 1
|
| 76 |
+
episode_ends = np.append(changes, len(idx)).astype(np.int64)
|
| 77 |
+
mse_all = float(np.mean((preds - tgts) ** 2)); mse_valid = float(np.mean(((preds - tgts) ** 2)[~pad])) if pad.any() else mse_all
|
| 78 |
+
with h5py.File(a.out, "w") as f:
|
| 79 |
+
f.create_dataset("predictions", data=preds); f.create_dataset("targets", data=tgts)
|
| 80 |
+
f.create_dataset("episode_ends", data=episode_ends); f.create_dataset("proprio", data=proprio)
|
| 81 |
+
f.create_dataset("episode_index", data=ep_idx); f.create_dataset("action_is_pad", data=pad); f.create_dataset("frame_local", data=fr_loc)
|
| 82 |
+
f.attrs.update(dict(ckpt=a.ckpt, H=H, D=D, fps=fps, stride=a.stride, inference_steps=a.inference_steps, seed=a.seed))
|
| 83 |
+
summary = dict(ckpt=a.ckpt, frames=len(idx), episodes=len(episode_ends), H=H, D=D, raw_mse_deg2=mse_all, raw_mse_unpadded=mse_valid, wall_s=time.time() - t0)
|
| 84 |
+
json.dump(summary, open(a.out.replace(".h5", "_summary.json"), "w"), indent=1)
|
| 85 |
+
print("SUMMARY", json.dumps(summary))
|
code_v2/eval_sim_v2.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Closed-loop eval of a MolmoAct2 checkpoint on PickCubeBowlSO100-v1 with temporal ensembling (TE) or open-loop chunks.
|
| 2 |
+
TE: policy queried every step; executed action = mean over the last H chunks' prediction for the current step (paper Eq. 3).
|
| 3 |
+
Logs per episode: success, first-failure phase, phase flags/steps, wrong-cube, steps.
|
| 4 |
+
Usage: python eval_sim_v2.py --ckpt <pretrained_model> --mode te --H 8 --episodes 100 --num-envs 25 --seed 200000000 --out results/<ckpt>_te
|
| 5 |
+
"""
|
| 6 |
+
import argparse, json, os, sys, time, collections
|
| 7 |
+
import numpy as np, torch, gymnasium as gym
|
| 8 |
+
sys.path.insert(0, "/workspace/cimse/sim"); import so100_bowl_env # noqa
|
| 9 |
+
from lerobot.configs.policies import PreTrainedConfig
|
| 10 |
+
from lerobot.datasets.lerobot_dataset import LeRobotDatasetMetadata
|
| 11 |
+
from lerobot.policies import make_policy, make_pre_post_processors
|
| 12 |
+
RAD2DEG = 180.0 / np.pi
|
| 13 |
+
ap = argparse.ArgumentParser()
|
| 14 |
+
ap.add_argument("--ckpt", required=True); ap.add_argument("--val-root", default="/workspace/cimse/datasets/so100_bowl_val_mix")
|
| 15 |
+
ap.add_argument("--mode", choices=["te", "openloop"], default="te"); ap.add_argument("--H", type=int, default=8)
|
| 16 |
+
ap.add_argument("--episodes", type=int, default=100); ap.add_argument("--num-envs", type=int, default=25)
|
| 17 |
+
ap.add_argument("--seed", type=int, default=200000000); ap.add_argument("--max-steps", type=int, default=450)
|
| 18 |
+
ap.add_argument("--out", required=True); ap.add_argument("--video", type=int, default=4); ap.add_argument("--inference-steps", type=int, default=10); ap.add_argument("--cuda-graph", type=int, default=0)
|
| 19 |
+
a = ap.parse_args(); os.makedirs(a.out, exist_ok=True)
|
| 20 |
+
|
| 21 |
+
pcfg = PreTrainedConfig.from_pretrained(a.ckpt); pcfg.pretrained_path = a.ckpt; pcfg.device = "cuda"
|
| 22 |
+
for k, v in [("inference_action_mode", "continuous"), ("num_inference_steps", a.inference_steps), ("enable_inference_cuda_graph", bool(a.cuda_graph)), ("eval_seed", 0)]:
|
| 23 |
+
if hasattr(pcfg, k): setattr(pcfg, k, v)
|
| 24 |
+
if a.mode == "openloop": pcfg.n_action_steps = 30
|
| 25 |
+
ds_meta = LeRobotDatasetMetadata(repo_id="local/" + os.path.basename(a.val_root), root=a.val_root)
|
| 26 |
+
policy = make_policy(cfg=pcfg, ds_meta=ds_meta); policy.eval()
|
| 27 |
+
pre, post = make_pre_post_processors(policy_cfg=pcfg, pretrained_path=a.ckpt, preprocessor_overrides={"device_processor": {"device": "cuda"}})
|
| 28 |
+
H_CHUNK = pcfg.chunk_size
|
| 29 |
+
|
| 30 |
+
env = gym.make("PickCubeBowlSO100-v1", obs_mode="rgb", control_mode="pd_joint_pos", render_mode="rgb_array", num_envs=a.num_envs, sim_backend="gpu")
|
| 31 |
+
u = env.unwrapped; dev = u.device
|
| 32 |
+
|
| 33 |
+
def batch_from(obs):
|
| 34 |
+
return {"observation.images.cam0": obs["sensor_data"]["cam0"]["rgb"].permute(0, 3, 1, 2).float() / 255.0,
|
| 35 |
+
"observation.images.cam1": obs["sensor_data"]["cam1"]["rgb"].permute(0, 3, 1, 2).float() / 255.0,
|
| 36 |
+
"observation.state": obs["agent"]["qpos"].float() * RAD2DEG, "task": list(u.task_description)}
|
| 37 |
+
|
| 38 |
+
PHASES = ["grasped", "lifted", "over_bowl", "released"]
|
| 39 |
+
def first_failure(info, i, succ):
|
| 40 |
+
if succ: return "none"
|
| 41 |
+
if bool(info["ever_wrong_cube"][i]): return "wrong_cube"
|
| 42 |
+
if not bool(info["ever_grasped"][i]): return "commit_or_grasp"
|
| 43 |
+
if not bool(info["ever_lifted"][i]): return "grasp_lift"
|
| 44 |
+
if not bool(info["ever_over_bowl"][i]): return "carry"
|
| 45 |
+
if not bool(info["ever_released"][i]): return "release"
|
| 46 |
+
return "release_settle"
|
| 47 |
+
|
| 48 |
+
results, frames = [], {}; t0 = time.time()
|
| 49 |
+
n_batches = int(np.ceil(a.episodes / a.num_envs))
|
| 50 |
+
for bi in range(n_batches):
|
| 51 |
+
seeds = [a.seed + bi * a.num_envs + i for i in range(a.num_envs)]
|
| 52 |
+
obs, info = env.reset(seed=seeds); policy.reset()
|
| 53 |
+
hist = collections.deque(maxlen=a.H) # each: (t0, chunk[B,H_CHUNK,D] in degrees)
|
| 54 |
+
succ = torch.zeros(a.num_envs, dtype=torch.bool, device=dev); done = torch.zeros_like(succ)
|
| 55 |
+
first_succ = torch.full((a.num_envs,), -1, dtype=torch.long, device=dev)
|
| 56 |
+
rec = bi == 0 and a.video > 0
|
| 57 |
+
if rec: frames = {i: [] for i in range(min(a.video, a.num_envs))}
|
| 58 |
+
queue = None
|
| 59 |
+
for t in range(a.max_steps):
|
| 60 |
+
if a.mode == "te":
|
| 61 |
+
b = pre(batch_from(obs))
|
| 62 |
+
with torch.inference_mode(): chunk = post(policy.predict_action_chunk(b)[:, :H_CHUNK])
|
| 63 |
+
hist.append((t, chunk.float()))
|
| 64 |
+
acts = [c[:, t - t0_] for (t0_, c) in hist if t - t0_ < H_CHUNK]
|
| 65 |
+
act = torch.stack(acts, 0).mean(0)
|
| 66 |
+
else:
|
| 67 |
+
if queue is None or len(queue) == 0:
|
| 68 |
+
b = pre(batch_from(obs))
|
| 69 |
+
with torch.inference_mode(): chunk = post(policy.predict_action_chunk(b)[:, :H_CHUNK]).float()
|
| 70 |
+
queue = collections.deque([chunk[:, k] for k in range(30)])
|
| 71 |
+
act = queue.popleft()
|
| 72 |
+
act_rad = (act[:, :6] / RAD2DEG).to(dev)
|
| 73 |
+
obs, rew, term, trunc, info = env.step(act_rad)
|
| 74 |
+
s = info["success"].bool(); newly = s & ~succ; first_succ[newly] = t; succ |= s
|
| 75 |
+
if rec:
|
| 76 |
+
for i in frames: frames[i].append(np.concatenate([obs["sensor_data"]["cam0"]["rgb"][i].cpu().numpy(), obs["sensor_data"]["cam1"]["rgb"][i].cpu().numpy()], 1))
|
| 77 |
+
done |= s
|
| 78 |
+
if bool(done.all()): break
|
| 79 |
+
for i, sd in enumerate(seeds):
|
| 80 |
+
if len(results) >= a.episodes: break
|
| 81 |
+
ok = bool(succ[i])
|
| 82 |
+
results.append(dict(seed=sd, success=ok, success_step=int(first_succ[i]), first_failure=first_failure(info, i, ok),
|
| 83 |
+
target=str(u.task_description[i].split()[2]), wrong_cube=bool(info["ever_wrong_cube"][i]),
|
| 84 |
+
**{f"ever_{p}": bool(info[f"ever_{p}"][i]) for p in PHASES}, **{f"step_{p}": int(info[f"step_{p}"][i]) for p in PHASES}))
|
| 85 |
+
print(f"batch {bi+1}/{n_batches} sr {np.mean([r['success'] for r in results]):.2f} {time.time()-t0:.0f}s", flush=True)
|
| 86 |
+
env.close()
|
| 87 |
+
sr = float(np.mean([r["success"] for r in results])); ff = collections.Counter(r["first_failure"] for r in results)
|
| 88 |
+
summary = dict(ckpt=a.ckpt, mode=a.mode, H=a.H if a.mode == "te" else None, episodes=len(results), success_rate=sr,
|
| 89 |
+
grasp_rate=float(np.mean([r["ever_grasped"] for r in results])), wrong_cube_rate=float(np.mean([r["wrong_cube"] for r in results])),
|
| 90 |
+
first_failure=dict(ff), mean_success_step=float(np.mean([r["success_step"] for r in results if r["success_step"] >= 0])) if sr > 0 else -1,
|
| 91 |
+
seed0=a.seed, num_envs=a.num_envs, wall_s=time.time() - t0)
|
| 92 |
+
json.dump(dict(summary=summary, episodes=results), open(os.path.join(a.out, "eval.json"), "w"), indent=1)
|
| 93 |
+
print("SUMMARY", json.dumps(summary))
|
| 94 |
+
if frames:
|
| 95 |
+
import imageio
|
| 96 |
+
for i, fr in frames.items():
|
| 97 |
+
imageio.mimwrite(os.path.join(a.out, f"ep{i}_{'ok' if results[i]['success'] else results[i]['first_failure']}.mp4"), fr, fps=30, codec="libx264", quality=7)
|
code_v2/eval_sim_v3.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Closed-loop eval of a MolmoAct2 checkpoint on PickCubeBowlSO100-v1, continuous batching version of eval_sim_v2.
|
| 2 |
+
Same protocol (TE H=8 query-every-step per paper Eq. 3, or open-loop 30-step chunks), same seeds (seed0 + i), same
|
| 3 |
+
success/phase logging. Difference: env slots are re-seeded individually as soon as their episode ends (success or
|
| 4 |
+
max_steps), so the model batch is always full -> no wasted forward passes on finished envs and CUDA-graph shape stays fixed.
|
| 5 |
+
Usage: python eval_sim_v3.py --ckpt <pretrained_model> --mode te --H 8 --episodes 100 --num-envs 25 --seed 200000000 --out results/<ckpt>/te
|
| 6 |
+
"""
|
| 7 |
+
import argparse, json, os, sys, time, collections
|
| 8 |
+
import numpy as np, torch, gymnasium as gym
|
| 9 |
+
sys.path.insert(0, "/workspace/cimse/sim"); import so100_bowl_env # noqa
|
| 10 |
+
from lerobot.configs.policies import PreTrainedConfig
|
| 11 |
+
from lerobot.datasets.lerobot_dataset import LeRobotDatasetMetadata
|
| 12 |
+
from lerobot.policies import make_policy, make_pre_post_processors
|
| 13 |
+
RAD2DEG = 180.0 / np.pi
|
| 14 |
+
ap = argparse.ArgumentParser()
|
| 15 |
+
ap.add_argument("--ckpt", required=True); ap.add_argument("--val-root", default="/workspace/cimse/datasets/so100_bowl_val_mix")
|
| 16 |
+
ap.add_argument("--mode", choices=["te", "openloop"], default="te"); ap.add_argument("--H", type=int, default=8)
|
| 17 |
+
ap.add_argument("--episodes", type=int, default=100); ap.add_argument("--num-envs", type=int, default=25)
|
| 18 |
+
ap.add_argument("--seed", type=int, default=200000000); ap.add_argument("--max-steps", type=int, default=450)
|
| 19 |
+
ap.add_argument("--out", required=True); ap.add_argument("--video", type=int, default=4); ap.add_argument("--inference-steps", type=int, default=10)
|
| 20 |
+
ap.add_argument("--cuda-graph", type=int, default=1)
|
| 21 |
+
a = ap.parse_args(); os.makedirs(a.out, exist_ok=True)
|
| 22 |
+
|
| 23 |
+
pcfg = PreTrainedConfig.from_pretrained(a.ckpt); pcfg.pretrained_path = a.ckpt; pcfg.device = "cuda"
|
| 24 |
+
for k, v in [("inference_action_mode", "continuous"), ("num_inference_steps", a.inference_steps), ("enable_inference_cuda_graph", bool(a.cuda_graph)), ("eval_seed", 0)]:
|
| 25 |
+
if hasattr(pcfg, k): setattr(pcfg, k, v)
|
| 26 |
+
if a.mode == "openloop": pcfg.n_action_steps = 30
|
| 27 |
+
ds_meta = LeRobotDatasetMetadata(repo_id="local/" + os.path.basename(a.val_root), root=a.val_root)
|
| 28 |
+
policy = make_policy(cfg=pcfg, ds_meta=ds_meta); policy.eval()
|
| 29 |
+
pre, post = make_pre_post_processors(policy_cfg=pcfg, pretrained_path=a.ckpt, preprocessor_overrides={"device_processor": {"device": "cuda"}})
|
| 30 |
+
H_CHUNK = pcfg.chunk_size; B = a.num_envs
|
| 31 |
+
|
| 32 |
+
env = gym.make("PickCubeBowlSO100-v1", obs_mode="rgb", control_mode="pd_joint_pos", render_mode="rgb_array", num_envs=B, sim_backend="gpu")
|
| 33 |
+
u = env.unwrapped; dev = u.device
|
| 34 |
+
|
| 35 |
+
def batch_from(obs):
|
| 36 |
+
return {"observation.images.cam0": obs["sensor_data"]["cam0"]["rgb"].permute(0, 3, 1, 2).float() / 255.0,
|
| 37 |
+
"observation.images.cam1": obs["sensor_data"]["cam1"]["rgb"].permute(0, 3, 1, 2).float() / 255.0,
|
| 38 |
+
"observation.state": obs["agent"]["qpos"].float() * RAD2DEG, "task": list(u.task_description)}
|
| 39 |
+
|
| 40 |
+
PHASES = ["grasped", "lifted", "over_bowl", "released"]
|
| 41 |
+
def first_failure(info, i, succ):
|
| 42 |
+
if succ: return "none"
|
| 43 |
+
if bool(info["ever_wrong_cube"][i]): return "wrong_cube"
|
| 44 |
+
if not bool(info["ever_grasped"][i]): return "commit_or_grasp"
|
| 45 |
+
if not bool(info["ever_lifted"][i]): return "grasp_lift"
|
| 46 |
+
if not bool(info["ever_over_bowl"][i]): return "carry"
|
| 47 |
+
if not bool(info["ever_released"][i]): return "release"
|
| 48 |
+
return "release_settle"
|
| 49 |
+
|
| 50 |
+
# ---- slot state ----
|
| 51 |
+
seeds_all = [a.seed + i for i in range(a.episodes)]; next_seed = 0
|
| 52 |
+
slot_seed = [None] * B; slot_t = torch.zeros(B, dtype=torch.long, device=dev); slot_succ = torch.zeros(B, dtype=torch.bool, device=dev)
|
| 53 |
+
slot_first_succ = torch.full((B,), -1, dtype=torch.long, device=dev)
|
| 54 |
+
hist = [collections.deque(maxlen=a.H) for _ in range(B)] # per slot: (t0, chunk[H_CHUNK, D])
|
| 55 |
+
queue = [None] * B # open-loop: per slot deque of remaining actions
|
| 56 |
+
frames = {}; rec_slots = set(range(min(a.video, B))) if a.video > 0 else set(); rec_done = set()
|
| 57 |
+
results = []; t_wall = time.time(); n_model_calls = 0
|
| 58 |
+
obs, info = env.reset(seed=seeds_all[:B]); policy.reset()
|
| 59 |
+
for i in range(B): slot_seed[i] = seeds_all[i]
|
| 60 |
+
next_seed = B
|
| 61 |
+
if rec_slots: frames = {i: [] for i in rec_slots}
|
| 62 |
+
while len(results) < a.episodes:
|
| 63 |
+
if a.mode == "te":
|
| 64 |
+
b = pre(batch_from(obs))
|
| 65 |
+
with torch.inference_mode(): chunk = post(policy.predict_action_chunk(b)[:, :H_CHUNK]).float()
|
| 66 |
+
n_model_calls += 1
|
| 67 |
+
act = torch.zeros(B, chunk.shape[-1], device=chunk.device)
|
| 68 |
+
for i in range(B):
|
| 69 |
+
t = int(slot_t[i]); hist[i].append((t, chunk[i]))
|
| 70 |
+
acts = [c[t - t0_] for (t0_, c) in hist[i] if t - t0_ < H_CHUNK]
|
| 71 |
+
act[i] = torch.stack(acts, 0).mean(0)
|
| 72 |
+
else:
|
| 73 |
+
need = [i for i in range(B) if queue[i] is None or len(queue[i]) == 0]
|
| 74 |
+
if need: # replan for all slots at once (slots that still have queued actions keep theirs)
|
| 75 |
+
b = pre(batch_from(obs))
|
| 76 |
+
with torch.inference_mode(): chunk = post(policy.predict_action_chunk(b)[:, :H_CHUNK]).float()
|
| 77 |
+
n_model_calls += 1
|
| 78 |
+
for i in need: queue[i] = collections.deque([chunk[i, k] for k in range(30)])
|
| 79 |
+
act = torch.stack([queue[i].popleft() for i in range(B)], 0)
|
| 80 |
+
act_rad = (act[:, :6] / RAD2DEG).to(dev)
|
| 81 |
+
obs, rew, term, trunc, info = env.step(act_rad)
|
| 82 |
+
slot_t += 1
|
| 83 |
+
s = info["success"].bool(); newly = s & ~slot_succ; slot_first_succ[newly] = slot_t[newly] - 1; slot_succ |= s
|
| 84 |
+
for i in rec_slots:
|
| 85 |
+
if i not in rec_done: frames[i].append(np.concatenate([obs["sensor_data"]["cam0"]["rgb"][i].cpu().numpy(), obs["sensor_data"]["cam1"]["rgb"][i].cpu().numpy()], 1))
|
| 86 |
+
finished = [i for i in range(B) if slot_seed[i] is not None and (bool(slot_succ[i]) or int(slot_t[i]) >= a.max_steps)]
|
| 87 |
+
if finished:
|
| 88 |
+
for i in finished:
|
| 89 |
+
ok = bool(slot_succ[i])
|
| 90 |
+
results.append(dict(seed=slot_seed[i], success=ok, success_step=int(slot_first_succ[i]), first_failure=first_failure(info, i, ok),
|
| 91 |
+
target=str(u.task_description[i].split()[2]), wrong_cube=bool(info["ever_wrong_cube"][i]), steps=int(slot_t[i]),
|
| 92 |
+
**{f"ever_{p}": bool(info[f"ever_{p}"][i]) for p in PHASES}, **{f"step_{p}": int(info[f"step_{p}"][i]) for p in PHASES}))
|
| 93 |
+
if i in rec_slots: rec_done.add(i)
|
| 94 |
+
# re-seed finished slots (partial reset) with the next seeds; slots with no seed left are parked (still stepped, ignored)
|
| 95 |
+
idx = [i for i in finished if next_seed < a.episodes]
|
| 96 |
+
for i in finished:
|
| 97 |
+
if i in idx: slot_seed[i] = seeds_all[next_seed]; next_seed += 1
|
| 98 |
+
else: slot_seed[i] = None
|
| 99 |
+
slot_t[i] = 0; slot_succ[i] = False; slot_first_succ[i] = -1; hist[i].clear(); queue[i] = None
|
| 100 |
+
if idx:
|
| 101 |
+
obs, info = env.reset(seed=[slot_seed[i] for i in idx], options={"env_idx": torch.tensor(idx, device=dev)})
|
| 102 |
+
if len(results) % 10 < len(finished): print(f"episodes {len(results)}/{a.episodes} sr {np.mean([r['success'] for r in results]):.2f} calls {n_model_calls} {time.time()-t_wall:.0f}s", flush=True)
|
| 103 |
+
env.close()
|
| 104 |
+
results.sort(key=lambda r: r["seed"]); results = results[:a.episodes]
|
| 105 |
+
sr = float(np.mean([r["success"] for r in results])); ff = collections.Counter(r["first_failure"] for r in results)
|
| 106 |
+
summary = dict(ckpt=a.ckpt, mode=a.mode, H=a.H if a.mode == "te" else None, episodes=len(results), success_rate=sr,
|
| 107 |
+
grasp_rate=float(np.mean([r["ever_grasped"] for r in results])), wrong_cube_rate=float(np.mean([r["wrong_cube"] for r in results])),
|
| 108 |
+
first_failure=dict(ff), mean_success_step=float(np.mean([r["success_step"] for r in results if r["success_step"] >= 0])) if sr > 0 else -1,
|
| 109 |
+
seed0=a.seed, num_envs=B, model_calls=n_model_calls, wall_s=time.time() - t_wall, batching="continuous")
|
| 110 |
+
json.dump(dict(summary=summary, episodes=results), open(os.path.join(a.out, "eval.json"), "w"), indent=1)
|
| 111 |
+
print("SUMMARY", json.dumps(summary))
|
| 112 |
+
if frames:
|
| 113 |
+
import imageio
|
| 114 |
+
for i, fr in frames.items():
|
| 115 |
+
r = [x for x in results if x["seed"] == seeds_all[i]][0]
|
| 116 |
+
imageio.mimwrite(os.path.join(a.out, f"ep{i}_{'ok' if r['success'] else r['first_failure']}.mp4"), fr, fps=30, codec="libx264", quality=7)
|
code_v2/gt_intervals_v2.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""GT critical intervals (3 windows) for a v2 val split from the raw merged h5, aligned to the built LeRobot dataset order
|
| 2 |
+
(assembly kept trajectories with T<=450 and success, in order). Windows (30 Hz frame indices):
|
| 3 |
+
commit : 0 -> first frame TCP within 5 cm of the TARGET cube (approach + target choice / language grounding)
|
| 4 |
+
grasp : first frame TCP < 5 cm from target -> first frame target lifted > 2 cm after gripper-close cmd
|
| 5 |
+
release: first frame target over bowl (xy < R) while lifted -> first success frame + 15 (0.5 s settle), capped at T
|
| 6 |
+
Usage: python gt_intervals_v2.py --h5 raw/raw/val_s1/traj.h5 --dataset datasets/so100_bowl_val_s1 --out cimse/intervals_val_s1_gt.json"""
|
| 7 |
+
import argparse, json, h5py, numpy as np
|
| 8 |
+
BOWL_R = 0.05
|
| 9 |
+
ap = argparse.ArgumentParser(); ap.add_argument("--h5", required=True); ap.add_argument("--dataset", required=True); ap.add_argument("--out", required=True); ap.add_argument("--cap", type=int, default=450); ap.add_argument("--take-first", type=int, default=0, help="only the first K merged trajectories (val-mix assembly)"); ap.add_argument("--no-assert", action="store_true")
|
| 10 |
+
a = ap.parse_args()
|
| 11 |
+
f = h5py.File(a.h5, "r"); keys = sorted([k for k in f if k.startswith("traj_")], key=lambda k: int(k.split("_")[1]))
|
| 12 |
+
if a.take_first: keys = keys[:a.take_first]
|
| 13 |
+
tg = json.load(open(f"{a.dataset}/meta/episode_targets.json")); COLORS = ["red", "green", "blue"]
|
| 14 |
+
out = []; ep = 0; stats = []
|
| 15 |
+
for k in keys:
|
| 16 |
+
g = f[k]; T = g["actions"].shape[0]
|
| 17 |
+
if T > a.cap or ("success" in g and not bool(g["success"][-1])): continue
|
| 18 |
+
oh = g["obs/extra/target_onehot"][0]; tc = COLORS[int(np.argmax(oh))]
|
| 19 |
+
if not a.no_assert: assert tg["targets"][ep] == tc, f"colour mismatch at dataset episode {ep}: {tg['targets'][ep]} vs h5 {tc}"
|
| 20 |
+
tcp = g["obs/extra/tcp_pose"][:T, :3]
|
| 21 |
+
cubes = {c: g[f"env_states/actors/cube_{c}"][:T, :3] for c in COLORS}
|
| 22 |
+
bowl = g["env_states/actors/bowl"][:T, :3]; target = cubes[tc]; grip = g["actions"][:, 5]; succ = g["success"][:T]
|
| 23 |
+
d_any = np.min([np.linalg.norm(tcp - cubes[c], axis=1) for c in COLORS], axis=0); d_t = np.linalg.norm(tcp - target, axis=1)
|
| 24 |
+
commit_end = int(np.argmax(d_any < 0.08)) if (d_any < 0.08).any() else T // 4
|
| 25 |
+
g_start = int(np.argmax(d_t < 0.05)) if (d_t < 0.05).any() else commit_end
|
| 26 |
+
close = int(np.argmax(grip < -0.4)) if (grip < -0.4).any() else g_start + 20
|
| 27 |
+
z0 = target[0, 2]; lifted = np.where((np.arange(T) > close) & (target[:, 2] > z0 + 0.02))[0]
|
| 28 |
+
g_end = int(lifted[0]) if len(lifted) else min(T - 1, close + 20)
|
| 29 |
+
over = np.where((np.arange(T) > g_end) & (np.linalg.norm(target[:, :2] - bowl[:, :2], axis=1) < BOWL_R) & (target[:, 2] > z0 + 0.02))[0]
|
| 30 |
+
r_start = int(over[0]) if len(over) else max(g_end, T - 60)
|
| 31 |
+
sidx = np.where(succ)[0]; r_end = min(T, (int(sidx[0]) + 15) if len(sidx) else T)
|
| 32 |
+
if r_end <= r_start: r_end = T
|
| 33 |
+
ivs = [{"label": "commit", "start": 0, "end": max(g_start, 5)}, {"label": "grasp", "start": g_start, "end": g_end}, {"label": "release", "start": r_start, "end": r_end}]
|
| 34 |
+
out.append({"episode": ep, "intervals": ivs, "T": T, "target": tc, "close_step": close}); stats.append([iv["end"] - iv["start"] for iv in ivs]); ep += 1
|
| 35 |
+
json.dump(out, open(a.out, "w"), indent=1)
|
| 36 |
+
S = np.array(stats); tot = sum(r["T"] for r in out)
|
| 37 |
+
print(f"{a.out}: {len(out)} eps (dataset has {len(tg['targets'])}); window len mean commit {S[:,0].mean():.0f} grasp {S[:,1].mean():.0f} release {S[:,2].mean():.0f}; frames in windows {S.sum()}/{tot} ({S.sum()/tot*100:.0f}%)")
|
| 38 |
+
if not a.no_assert: assert len(out) == len(tg["targets"]), "episode count mismatch vs dataset"
|
code_v2/make_subsets.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stratified episode subsets of so100_bowl_train for the data-scale runs.
|
| 2 |
+
Train set episode order: S0 [0,1146) , S1 [1146,2005), S2 [2005,2812). Each subset keeps the same source ratio.
|
| 3 |
+
Writes train/subsets.json {"p05": [...], "p15": [...], "p40": [...], "p100": null} and prints counts."""
|
| 4 |
+
import json, sys, os
|
| 5 |
+
root = sys.argv[1] if len(sys.argv) > 1 else "/workspace/cimse/datasets/so100_bowl_train"
|
| 6 |
+
n_total = json.load(open(f"{root}/meta/info.json"))["total_episodes"]
|
| 7 |
+
blocks = [(0, 1146), (1146, 2005), (2005, n_total)]
|
| 8 |
+
out = {}
|
| 9 |
+
for tag, frac in [("p05", 0.05), ("p15", 0.15), ("p40", 0.40)]:
|
| 10 |
+
idx = []
|
| 11 |
+
for a, b in blocks:
|
| 12 |
+
k = max(1, round((b - a) * frac)); idx += list(range(a, a + k)) # first k of each block (blocks are seed-ordered, i.e. random scenes)
|
| 13 |
+
out[tag] = idx; print(tag, len(idx), "episodes; per source", [round((b - a) * frac) for a, b in blocks])
|
| 14 |
+
out["p100"] = None
|
| 15 |
+
json.dump(out, open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "subsets.json"), "w"))
|
| 16 |
+
print("total", n_total)
|
code_v2/merge_mix_intervals.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""val-mix GT = concat of per-source GT computed on the first 34/33/33 merged trajectories (same as subset_h5 assembly), renumbered."""
|
| 2 |
+
import json, sys
|
| 3 |
+
parts = [("cimse/intervals_mix_part_s0.json"), ("cimse/intervals_mix_part_s1.json"), ("cimse/intervals_mix_part_s2.json")]
|
| 4 |
+
out = []; n = 0
|
| 5 |
+
for p in parts:
|
| 6 |
+
for r in json.load(open(p)): r = dict(r); r["episode"] = n; out.append(r); n += 1
|
| 7 |
+
tg = json.load(open("datasets/so100_bowl_val_mix/meta/episode_targets.json"))
|
| 8 |
+
assert len(out) == len(tg["targets"]), (len(out), len(tg["targets"]))
|
| 9 |
+
for r in out: assert r["target"] == tg["targets"][r["episode"]], r["episode"]
|
| 10 |
+
json.dump(out, open("cimse/intervals_val_mix_gt.json", "w"), indent=1); print("val_mix GT", len(out), "episodes, colours verified")
|
code_v2/profile_te.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys, time, torch, numpy as np, gymnasium as gym, collections
|
| 2 |
+
sys.path.insert(0, "/workspace/cimse/sim"); import so100_bowl_env
|
| 3 |
+
from lerobot.configs.policies import PreTrainedConfig
|
| 4 |
+
from lerobot.datasets.lerobot_dataset import LeRobotDatasetMetadata
|
| 5 |
+
from lerobot.policies import make_policy, make_pre_post_processors
|
| 6 |
+
ck = sys.argv[1]; NE = int(sys.argv[2]); CG = int(sys.argv[3]) if len(sys.argv) > 3 else 0; R2D = 180/np.pi
|
| 7 |
+
t = time.time(); pcfg = PreTrainedConfig.from_pretrained(ck); pcfg.pretrained_path = ck; pcfg.device = "cuda"
|
| 8 |
+
for k, v in [("inference_action_mode", "continuous"), ("num_inference_steps", 10), ("enable_inference_cuda_graph", bool(CG)), ("eval_seed", 0)]:
|
| 9 |
+
if hasattr(pcfg, k): setattr(pcfg, k, v)
|
| 10 |
+
meta = LeRobotDatasetMetadata(repo_id="local/so100_bowl_val_mix", root="/workspace/cimse/datasets/so100_bowl_val_mix")
|
| 11 |
+
policy = make_policy(cfg=pcfg, ds_meta=meta); policy.eval(); pre, post = make_pre_post_processors(policy_cfg=pcfg, pretrained_path=ck, preprocessor_overrides={"device_processor": {"device": "cuda"}})
|
| 12 |
+
print(f"load {time.time()-t:.1f}s dtype {next(policy.parameters()).dtype} torch_threads {torch.get_num_threads()}", flush=True)
|
| 13 |
+
t = time.time(); env = gym.make("PickCubeBowlSO100-v1", obs_mode="rgb", control_mode="pd_joint_pos", render_mode="rgb_array", num_envs=NE, sim_backend="gpu"); u = env.unwrapped
|
| 14 |
+
obs, info = env.reset(seed=list(range(NE))); print(f"env make+reset {time.time()-t:.1f}s", flush=True)
|
| 15 |
+
def bf(obs): return {"observation.images.cam0": obs["sensor_data"]["cam0"]["rgb"].permute(0,3,1,2).float()/255, "observation.images.cam1": obs["sensor_data"]["cam1"]["rgb"].permute(0,3,1,2).float()/255, "observation.state": obs["agent"]["qpos"].float()*R2D, "task": list(u.task_description)}
|
| 16 |
+
T = collections.defaultdict(float); N = 12
|
| 17 |
+
for i in range(N + 2):
|
| 18 |
+
if i == 2: T.clear()
|
| 19 |
+
torch.cuda.synchronize(); a = time.time(); b = pre(bf(obs)); torch.cuda.synchronize(); T["pre"] += time.time()-a; a = time.time()
|
| 20 |
+
with torch.inference_mode(): ch = post(policy.predict_action_chunk(b)[:, :30])
|
| 21 |
+
torch.cuda.synchronize(); T["predict"] += time.time()-a; a = time.time()
|
| 22 |
+
obs, *_ = env.step((ch[:, 0, :6].float()/R2D).to(u.device)); torch.cuda.synchronize(); T["envstep"] += time.time()-a
|
| 23 |
+
print("PROFILE", NE, "envs cg", CG, {k: round(v/N, 3) for k, v in T.items()}, "s/step", flush=True)
|
code_v2/prompt_bowl.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"task": "Pick up the cube of the requested color (red, green or blue) and put it into the white bowl. There are three cubes; only one is the target.",
|
| 3 |
+
"intervals": [
|
| 4 |
+
{
|
| 5 |
+
"start": "The very beginning of the video, before the arm has moved toward any cube.",
|
| 6 |
+
"end": "The gripper has clearly committed to one cube: its tip is within about 8 cm of a cube and is no longer moving toward the others."
|
| 7 |
+
},
|
| 8 |
+
{
|
| 9 |
+
"start": "The gripper has not yet grabbed the target cube, and its tip is about 5 cm away from it.",
|
| 10 |
+
"end": "The gripper closes and has just fully gripped the target cube, lifting it slightly off the table."
|
| 11 |
+
},
|
| 12 |
+
{
|
| 13 |
+
"start": "The gripper is holding the cube directly above the bowl opening, about to lower or release it.",
|
| 14 |
+
"end": "The cube has been released, has landed inside the bowl and come to rest, and the gripper has stopped moving."
|
| 15 |
+
}
|
| 16 |
+
]
|
| 17 |
+
}
|
code_v2/queue_v2.sh
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Eval/dump/push/delete queue for one GPU. Usage: queue_v2.sh <gpu> ; scans ckpts/*/checkpoints/*/pretrained_model, claims via lock dir.
|
| 3 |
+
# Per checkpoint: TE eval (100 eps) -> [openloop eval if in OPENLOOP list] -> dumps (4 val splits, first 50 eps, all frames) -> push -> delete local ckpt.
|
| 4 |
+
set -uo pipefail
|
| 5 |
+
GPU=$1; export CUDA_VISIBLE_DEVICES=$GPU HF_HOME=/workspace/.hf_home HF_TOKEN=$(grep HF_TOKEN /workspace/.env | cut -d= -f2) HF_HUB_ENABLE_HF_TRANSFER=1
|
| 6 |
+
cd /workspace/cimse && source .venv/bin/activate; mkdir -p results cimse/preds locks
|
| 7 |
+
log(){ echo "[$(date -u +%T) gpu$GPU] $*"; }
|
| 8 |
+
OPENLOOP="R1_p100/003000 R1_p100/001000 R2_p05/003000 R5_freeze/003000 zeroshot/000000"
|
| 9 |
+
CK=Kavin60606/cimse-so100-bowl-molmoact2-ckpts
|
| 10 |
+
while true; do
|
| 11 |
+
found=0
|
| 12 |
+
for d in $(ls -d ckpts/*/checkpoints/0*/pretrained_model 2>/dev/null); do
|
| 13 |
+
run=$(echo $d | cut -d/ -f2); step=$(echo $d | cut -d/ -f4); name=${run}_${step}
|
| 14 |
+
[ -f $d/model.safetensors ] || continue; [ -f results/$name/done ] && continue
|
| 15 |
+
mkdir locks/$name 2>/dev/null || continue # claim
|
| 16 |
+
found=1; log "START $name"
|
| 17 |
+
rm -rf $d/../training_state
|
| 18 |
+
python sim/eval_sim_v2.py --ckpt $d --mode te --H 8 --episodes 100 --num-envs 25 --out results/$name/te --video 4 2>&1 | grep -E "SUMMARY|Traceback|Error" | cut -c1-300
|
| 19 |
+
if echo " $OPENLOOP " | grep -q " $run/$step "; then python sim/eval_sim_v2.py --ckpt $d --mode openloop --episodes 100 --num-envs 25 --out results/$name/openloop --video 2 2>&1 | grep -E "SUMMARY|Traceback|Error" | cut -c1-300; fi
|
| 20 |
+
for s in s0 s1 s2 mix; do python sim/dump_predictions_v2.py --ckpt $d --val-root datasets/so100_bowl_val_$s --max-episodes 50 --stride 1 --bs 16 --workers 12 --out cimse/preds/$name/val_$s/predictions.h5 2>&1 | grep -E "SUMMARY|Traceback|Error" | cut -c1-200; done
|
| 21 |
+
hf upload $CK $d $run/$step --repo-type model --commit-message "$name" >/dev/null 2>&1 && log "pushed ckpt $name" || log "PUSH FAILED $name (kept local)"
|
| 22 |
+
hf upload Kavin60606/cimse-so100-experiment-v2 results/$name results/$name --repo-type dataset >/dev/null 2>&1; hf upload Kavin60606/cimse-so100-experiment-v2 cimse/preds/$name preds/$name --repo-type dataset >/dev/null 2>&1
|
| 23 |
+
[ -f results/$name/te/eval.json ] && ls cimse/preds/$name/val_s0/predictions.h5 >/dev/null 2>&1 && { touch results/$name/done; [ -d ckpts/$run/checkpoints/$step ] && [ "$step" != "003000" ] && rm -rf ckpts/$run/checkpoints/$step; log "DONE $name sr=$(python3 -c "import json;print(json.load(open('results/$name/te/eval.json'))['summary']['success_rate'])")"; } || log "INCOMPLETE $name"
|
| 24 |
+
done
|
| 25 |
+
[ -f /workspace/cimse/QUEUE_STOP ] && [ $found = 0 ] && break
|
| 26 |
+
[ $found = 0 ] && sleep 60
|
| 27 |
+
done
|
| 28 |
+
log QUEUE_EXIT
|
code_v2/queue_v3.sh
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Pooled job queue. Usage: queue_v3.sh <gpu>. Jobs from /workspace/cimse/jobs.txt (line = "<kind> <run/step> [split]"), claimed via mkdir locks/<jobid>.
|
| 3 |
+
# kinds: te1 (TE 100 eps seeds 2e8), te2 (TE 100 eps seeds 2e8+1e6), ol (open-loop 100 eps), dump <split> (all eps, all frames).
|
| 4 |
+
set -uo pipefail
|
| 5 |
+
GPU=$1; export CUDA_VISIBLE_DEVICES=$GPU HF_HOME=/workspace/.hf_home HF_TOKEN=$(grep HF_TOKEN /workspace/.env | cut -d= -f2) HF_HUB_ENABLE_HF_TRANSFER=1 OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=4 HF_HUB_OFFLINE=1 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
|
| 6 |
+
cd /workspace/cimse && source .venv/bin/activate; mkdir -p results cimse/preds locks
|
| 7 |
+
log(){ echo "[$(date -u +%T) gpu$GPU] $*"; }
|
| 8 |
+
CK=Kavin60606/cimse-so100-bowl-molmoact2-ckpts
|
| 9 |
+
while true; do
|
| 10 |
+
found=0
|
| 11 |
+
while read -r kind ref split; do
|
| 12 |
+
[ -z "$kind" ] && continue
|
| 13 |
+
run=${ref%/*}; step=${ref#*/}; name=${run}_${step}; jid=${kind}_${name}${split:+_$split}
|
| 14 |
+
d=ckpts/$run/checkpoints/$step/pretrained_model
|
| 15 |
+
case $kind in ol1) out=results/$name/ol1/eval.json;; ol2) out=results/$name/ol2/eval.json;; te1) out=results/$name/te/eval.json;; te2) out=results/$name/te2/eval.json;; ol) out=results/$name/openloop/eval.json;; dump) out=cimse/preds/$name/val_$split/predictions.h5;; esac
|
| 16 |
+
[ -f $out ] && continue
|
| 17 |
+
mkdir locks/$jid 2>/dev/null || continue
|
| 18 |
+
found=1; log "START $jid"
|
| 19 |
+
if [ ! -f $d/model.safetensors ]; then hf download $CK --include "$run/$step/*" --local-dir ckpts_hf >/dev/null 2>&1; d=ckpts_hf/$run/$step; fi
|
| 20 |
+
rm -rf ckpts/$run/checkpoints/$step/training_state 2>/dev/null
|
| 21 |
+
t0=$(date +%s)
|
| 22 |
+
case $kind in
|
| 23 |
+
te1) python sim/eval_sim_v2.py --ckpt $d --mode te --H 8 --episodes 100 --num-envs 25 --seed 200000000 --cuda-graph 1 --out results/$name/te --video 4 2>&1 | grep -E "SUMMARY|Traceback|Error" | cut -c1-300;;
|
| 24 |
+
te2) python sim/eval_sim_v2.py --ckpt $d --mode te --H 8 --episodes 100 --num-envs 25 --seed 201000000 --cuda-graph 1 --out results/$name/te2 --video 0 2>&1 | grep -E "SUMMARY|Traceback|Error" | cut -c1-300;;
|
| 25 |
+
ol1) python sim/eval_sim_v2.py --ckpt $d --mode openloop --episodes 100 --num-envs 10 --seed 200000000 --cuda-graph 0 --out results/$name/ol1 --video 4 2>&1 | grep -E "SUMMARY|Traceback|Error" | cut -c1-300;;
|
| 26 |
+
ol2) python sim/eval_sim_v2.py --ckpt $d --mode openloop --episodes 100 --num-envs 10 --seed 201000000 --cuda-graph 0 --out results/$name/ol2 --video 0 2>&1 | grep -E "SUMMARY|Traceback|Error" | cut -c1-300;;
|
| 27 |
+
ol) python sim/eval_sim_v2.py --ckpt $d --mode openloop --episodes 100 --num-envs 25 --seed 200000000 --cuda-graph 1 --out results/$name/openloop --video 2 2>&1 | grep -E "SUMMARY|Traceback|Error" | cut -c1-300;;
|
| 28 |
+
dump) python sim/dump_predictions_v2.py --ckpt $d --val-root datasets/so100_bowl_val_$split --stride 1 --bs 32 --workers 8 --out $out 2>&1 | grep -E "SUMMARY|Traceback|Error" | cut -c1-200;;
|
| 29 |
+
esac
|
| 30 |
+
if [ -f $out ]; then log "DONE $jid $(( $(date +%s) - t0 ))s"; case $kind in te1|te2|ol|ol1|ol2) log "SR $jid $(python3 -c "import json;s=json.load(open(\"$out\"))[\"summary\"];print(s[\"success_rate\"], \"grasp\", s[\"grasp_rate\"], \"wrong\", s[\"wrong_cube_rate\"])")";; esac
|
| 31 |
+
hf upload Kavin60606/cimse-so100-experiment-v2 $(dirname $out) $(dirname $out | sed "s#^cimse/##") --repo-type dataset >/dev/null 2>&1 || log "upload failed $jid"
|
| 32 |
+
else log "FAILED $jid"; fi
|
| 33 |
+
done < jobs.txt
|
| 34 |
+
[ -f /workspace/cimse/QUEUE_STOP ] && [ $found = 0 ] && break
|
| 35 |
+
[ $found = 0 ] && sleep 60
|
| 36 |
+
done
|
| 37 |
+
log QUEUE_EXIT
|
code_v2/setup_train_box.sh
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# 8xA100 training/eval box setup. Two venvs: .venv (torch+lerobot+mani-skill, numpy2) for train/eval/dump; .venv-sim not needed (no planner).
|
| 3 |
+
set -uxo pipefail
|
| 4 |
+
ROOT=/workspace/cimse; mkdir -p $ROOT/{sim,datasets,ckpts,results,cimse,media,raw} && cd $ROOT
|
| 5 |
+
echo "HF_TOKEN=$HF_TOKEN" > /workspace/.env; echo "GEMINI_API_KEY=$GEMINI_API_KEY" >> /workspace/.env; chmod 600 /workspace/.env
|
| 6 |
+
export HF_HOME=/workspace/.hf_home HF_HUB_ENABLE_HF_TRANSFER=1
|
| 7 |
+
mkdir -p /usr/share/vulkan/icd.d && ln -sf /etc/vulkan/icd.d/nvidia_icd.json /usr/share/vulkan/icd.d/nvidia_icd.json || true
|
| 8 |
+
[ -d .venv ] || uv venv .venv --python 3.12
|
| 9 |
+
source .venv/bin/activate
|
| 10 |
+
uv pip install torch torchvision --index-url https://download.pytorch.org/whl/cu128 2>&1 | tail -1
|
| 11 |
+
[ -d lerobot ] || (git clone -q https://github.com/huggingface/lerobot && cd lerobot && git checkout -q 3f2c29ef7e44b1ddccbcda3b6a63939e53639e9e)
|
| 12 |
+
uv pip install -e "lerobot[molmoact2,dataset]" 2>&1 | tail -1
|
| 13 |
+
uv pip install mani-skill h5py dtw-python scipy matplotlib pandas imageio imageio-ffmpeg "huggingface_hub[cli,hf_transfer]" httpx google-genai 2>&1 | tail -1
|
| 14 |
+
hf auth login --token $HF_TOKEN >/dev/null 2>&1
|
| 15 |
+
python -c "import torch,lerobot,mani_skill;print('torch',torch.__version__,torch.cuda.device_count(),'gpus; lerobot',lerobot.__version__,'ms',mani_skill.__version__)"
|
| 16 |
+
# weights + data (parallel)
|
| 17 |
+
( hf download allenai/MolmoAct2 >/dev/null 2>&1 && echo BASE_OK ) &
|
| 18 |
+
( hf download lerobot/MolmoAct2-SO100_101-LeRobot >/dev/null 2>&1 && echo ZS_OK ) &
|
| 19 |
+
for n in so100_bowl_train so100_bowl_val_s0 so100_bowl_val_s1 so100_bowl_val_s2 so100_bowl_val_mix; do ( hf download Kavin60606/$n --repo-type dataset --local-dir datasets/$n >/dev/null 2>&1 && echo "DS_OK $n" ) & done
|
| 20 |
+
( hf download Kavin60606/cimse-so100-experiment-v2 --repo-type dataset --include "raw/val_s0/*" "raw/val_s1/*" "raw/val_s2/*" "eval_seeds.json" --local-dir raw >/dev/null 2>&1 && echo RAW_OK ) &
|
| 21 |
+
wait
|
| 22 |
+
du -sh /workspace/.hf_home datasets raw | cut -f1 | tr "\n" " "; echo; df -h / | tail -1
|
| 23 |
+
# gallery
|
| 24 |
+
cp $ROOT/sim/gallery/serve.py $ROOT/gallery/serve.py 2>/dev/null || (mkdir -p $ROOT/gallery && cp $ROOT/sim/gallery/serve.py $ROOT/gallery/serve.py); cp $ROOT/sim/gallery/gallery.sh /opt/supervisor-scripts/gallery.sh; chmod +x /opt/supervisor-scripts/gallery.sh
|
| 25 |
+
cp $ROOT/sim/gallery/supervisor.conf /etc/supervisor/conf.d/gallery.conf
|
| 26 |
+
python3 -c "import yaml; d=yaml.safe_load(open('/etc/portal.yaml')); d['applications']['Gallery']={'hostname':'localhost','external_port':10100,'internal_port':17100,'open_path':'/','name':'Gallery'}; yaml.safe_dump(d, open('/etc/portal.yaml','w'), sort_keys=False)"
|
| 27 |
+
supervisorctl reread >/dev/null; supervisorctl update >/dev/null; supervisorctl restart caddy >/dev/null; sleep 3; supervisorctl status gallery | cut -c1-40
|
| 28 |
+
echo "GALLERY http://$PUBLIC_IPADDR:$VAST_TCP_PORT_10100/?token=$OPEN_BUTTON_TOKEN"
|
| 29 |
+
echo SETUP_TRAIN_OK
|
code_v2/so100_bowl_env.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PickCubeBowlSO100-v1 — v2 task: "put the {color} cube in the bowl".
|
| 2 |
+
SO-100, 3 colored cubes (red/green/blue), primitive bowl, domain randomization (lighting, camera pose/fov, cube size,
|
| 3 |
+
color jitter), per-episode language target, phase flags for failure attribution, staged dense reward for RL.
|
| 4 |
+
Works on CPU (num_envs=1, demo gen) and GPU-batched (eval / PPO)."""
|
| 5 |
+
from typing import Any, Dict, Union
|
| 6 |
+
import numpy as np, sapien, torch
|
| 7 |
+
from transforms3d.euler import euler2quat
|
| 8 |
+
from mani_skill.agents.robots import SO100
|
| 9 |
+
from mani_skill.envs.sapien_env import BaseEnv
|
| 10 |
+
from mani_skill.envs.utils import randomization
|
| 11 |
+
from mani_skill.sensors.camera import CameraConfig
|
| 12 |
+
from mani_skill.utils import common, sapien_utils
|
| 13 |
+
from mani_skill.utils.registration import register_env
|
| 14 |
+
from mani_skill.utils.scene_builder.table import TableSceneBuilder
|
| 15 |
+
from mani_skill.utils.structs import Actor, Pose
|
| 16 |
+
from mani_skill.utils.structs.types import SimConfig
|
| 17 |
+
|
| 18 |
+
COLORS = ["red", "green", "blue"]
|
| 19 |
+
BASE_RGB = {"red": (0.9, 0.1, 0.1), "green": (0.1, 0.75, 0.15), "blue": (0.1, 0.2, 0.9)}
|
| 20 |
+
CAM_RES = 224
|
| 21 |
+
BOWL_R, BOWL_WALL_H, BOWL_FLOOR_H, N_WALL = 0.05, 0.028, 0.004, 14
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@register_env("PickCubeBowlSO100-v1", max_episode_steps=450)
|
| 25 |
+
class PickCubeBowlSO100Env(BaseEnv):
|
| 26 |
+
SUPPORTED_ROBOTS = ["so100"]
|
| 27 |
+
agent: SO100
|
| 28 |
+
# workspace (robot base at origin, arm reaches toward -x like the ManiSkill SO-100 pick-cube config)
|
| 29 |
+
cube_box = dict(x=(-0.50, -0.40), y=(-0.09, 0.09))
|
| 30 |
+
bowl_box = dict(x=(-0.50, -0.42), y_abs=(0.11, 0.16))
|
| 31 |
+
min_sep = 0.055
|
| 32 |
+
bowl_release_height = BOWL_WALL_H + 0.03 # above bowl floor for oracle release
|
| 33 |
+
|
| 34 |
+
def __init__(self, *args, robot_uids="so100", robot_init_qpos_noise=0.02, domain_randomization=True, **kwargs):
|
| 35 |
+
self.robot_init_qpos_noise = robot_init_qpos_noise
|
| 36 |
+
self.dr = domain_randomization
|
| 37 |
+
self.phase_log = [] # (event, step) for single-env cpu use
|
| 38 |
+
super().__init__(*args, robot_uids=robot_uids, **kwargs)
|
| 39 |
+
|
| 40 |
+
@property
|
| 41 |
+
def _default_sim_config(self):
|
| 42 |
+
return SimConfig(sim_freq=120, control_freq=30)
|
| 43 |
+
|
| 44 |
+
# ---------------- cameras (mounted so pose can be randomized per episode) ----------------
|
| 45 |
+
@property
|
| 46 |
+
def _default_sensor_configs(self):
|
| 47 |
+
fov_noise = (np.deg2rad(2.5) * (2 * self._batched_episode_rng.rand() - 1)) if self.dr else np.zeros(self.num_envs)
|
| 48 |
+
fov0 = np.pi / 2.6
|
| 49 |
+
front = sapien_utils.look_at(eye=[-0.22, 0.0, 0.34], target=[-0.47, 0.0, 0.02])
|
| 50 |
+
side = sapien_utils.look_at(eye=[-0.46, -0.36, 0.26], target=[-0.46, 0.0, 0.04])
|
| 51 |
+
return [
|
| 52 |
+
CameraConfig("cam0", front, CAM_RES, CAM_RES, fov0 + float(np.mean(fov_noise)), 0.01, 100, mount=self.cam_mount0),
|
| 53 |
+
CameraConfig("cam1", side, CAM_RES, CAM_RES, fov0 + float(np.mean(fov_noise)), 0.01, 100, mount=self.cam_mount1),
|
| 54 |
+
]
|
| 55 |
+
|
| 56 |
+
@property
|
| 57 |
+
def _default_human_render_camera_configs(self):
|
| 58 |
+
pose = sapien_utils.look_at(eye=[-0.15, 0.45, 0.45], target=[-0.47, 0.0, 0.05])
|
| 59 |
+
return CameraConfig("render_camera", pose, 512, 512, np.pi / 3, 0.01, 100)
|
| 60 |
+
|
| 61 |
+
def _sample_mount_pose(self, n):
|
| 62 |
+
if not self.dr:
|
| 63 |
+
return Pose.create_from_pq(p=torch.zeros((n, 3)), q=torch.tensor([[1.0, 0, 0, 0]] * n))
|
| 64 |
+
p = (torch.rand((n, 3)) * 2 - 1) * torch.tensor([0.02, 0.02, 0.02])
|
| 65 |
+
ang = (torch.rand((n, 3)) * 2 - 1) * np.deg2rad(3.0)
|
| 66 |
+
qs = torch.tensor(np.array([euler2quat(*a) for a in ang.cpu().numpy()]), dtype=torch.float32)
|
| 67 |
+
return Pose.create_from_pq(p=p, q=qs)
|
| 68 |
+
|
| 69 |
+
# ---------------- lighting DR ----------------
|
| 70 |
+
def _load_lighting(self, options: dict):
|
| 71 |
+
if self.dr:
|
| 72 |
+
amb = self._batched_episode_rng.uniform(0.15, 0.55, size=(3,))
|
| 73 |
+
for i, scene in enumerate(self.scene.sub_scenes):
|
| 74 |
+
scene.render_system.ambient_light = amb[i]
|
| 75 |
+
d = self._batched_episode_rng.uniform(-1, 1, size=(3,))
|
| 76 |
+
strength = self._batched_episode_rng.uniform(0.6, 1.4)
|
| 77 |
+
for i, scene in enumerate(self.scene.sub_scenes):
|
| 78 |
+
dd = np.array([d[i][0], d[i][1], -abs(d[i][2]) - 0.5]); dd /= np.linalg.norm(dd)
|
| 79 |
+
scene.add_directional_light(dd.tolist(), [float(strength[i])] * 3, shadow=self.enable_shadow, shadow_scale=5, shadow_map_size=2048)
|
| 80 |
+
scene.add_directional_light([0, 0, -1], [0.5, 0.5, 0.5])
|
| 81 |
+
else:
|
| 82 |
+
self.scene.set_ambient_light([0.3, 0.3, 0.3])
|
| 83 |
+
self.scene.add_directional_light([1, 1, -1], [1, 1, 1], shadow=self.enable_shadow, shadow_scale=5, shadow_map_size=2048)
|
| 84 |
+
self.scene.add_directional_light([0, 0, -1], [1, 1, 1])
|
| 85 |
+
|
| 86 |
+
# ---------------- scene ----------------
|
| 87 |
+
def _load_scene(self, options: dict):
|
| 88 |
+
self.table_scene = TableSceneBuilder(self, robot_init_qpos_noise=self.robot_init_qpos_noise)
|
| 89 |
+
self.table_scene.build()
|
| 90 |
+
n = self.num_envs
|
| 91 |
+
# camera mounts
|
| 92 |
+
b = self.scene.create_actor_builder(); b.initial_pose = sapien.Pose(); self.cam_mount0 = b.build_kinematic("cam_mount0")
|
| 93 |
+
b = self.scene.create_actor_builder(); b.initial_pose = sapien.Pose(); self.cam_mount1 = b.build_kinematic("cam_mount1")
|
| 94 |
+
# cube sizes / colors
|
| 95 |
+
if self.dr:
|
| 96 |
+
half = self._batched_episode_rng.uniform(0.0125, 0.0145)
|
| 97 |
+
else:
|
| 98 |
+
half = np.ones(n) * 0.0125
|
| 99 |
+
self.cube_half = common.to_tensor(half, device=self.device)
|
| 100 |
+
self.cubes: Dict[str, Actor] = {}
|
| 101 |
+
for c in COLORS:
|
| 102 |
+
actors = []
|
| 103 |
+
for i in range(n):
|
| 104 |
+
rgb = np.array(BASE_RGB[c])
|
| 105 |
+
if self.dr:
|
| 106 |
+
rgb = np.clip(rgb + self._batched_episode_rng[i].uniform(-0.08, 0.08, size=3), 0, 1)
|
| 107 |
+
bld = self.scene.create_actor_builder()
|
| 108 |
+
bld.add_box_collision(half_size=[half[i]] * 3) # default material/density (as v1 cube)
|
| 109 |
+
bld.add_box_visual(half_size=[half[i]] * 3, material=sapien.render.RenderMaterial(base_color=list(rgb) + [1]))
|
| 110 |
+
bld.initial_pose = sapien.Pose(p=[0, 0, half[i]]); bld.set_scene_idxs([i])
|
| 111 |
+
a = bld.build(name=f"cube_{c}-{i}"); actors.append(a); self.remove_from_state_dict_registry(a)
|
| 112 |
+
self.cubes[c] = Actor.merge(actors, name=f"cube_{c}"); self.add_to_state_dict_registry(self.cubes[c])
|
| 113 |
+
# bowl: primitive (floor disk + wall segments), kinematic
|
| 114 |
+
bowls = []
|
| 115 |
+
for i in range(n):
|
| 116 |
+
gray = float(self._batched_episode_rng[i].uniform(0.75, 0.95)) if self.dr else 0.85
|
| 117 |
+
mat = sapien.render.RenderMaterial(base_color=[gray, gray, gray * 0.97, 1])
|
| 118 |
+
bld = self.scene.create_actor_builder()
|
| 119 |
+
bld.add_cylinder_collision(radius=BOWL_R, half_length=BOWL_FLOOR_H / 2, pose=sapien.Pose(p=[0, 0, BOWL_FLOOR_H / 2], q=euler2quat(0, np.pi / 2, 0)))
|
| 120 |
+
bld.add_cylinder_visual(radius=BOWL_R, half_length=BOWL_FLOOR_H / 2, pose=sapien.Pose(p=[0, 0, BOWL_FLOOR_H / 2], q=euler2quat(0, np.pi / 2, 0)), material=mat)
|
| 121 |
+
seg = np.pi * BOWL_R / N_WALL
|
| 122 |
+
for k in range(N_WALL):
|
| 123 |
+
th = 2 * np.pi * k / N_WALL
|
| 124 |
+
p = [BOWL_R * np.cos(th), BOWL_R * np.sin(th), BOWL_WALL_H / 2 + BOWL_FLOOR_H]
|
| 125 |
+
pose = sapien.Pose(p=p, q=euler2quat(0, 0, th))
|
| 126 |
+
bld.add_box_collision(half_size=[0.004, seg * 1.05, BOWL_WALL_H / 2], pose=pose)
|
| 127 |
+
bld.add_box_visual(half_size=[0.004, seg * 1.05, BOWL_WALL_H / 2], pose=pose, material=mat)
|
| 128 |
+
bld.initial_pose = sapien.Pose(p=[-0.45, 0.18, 0]); bld.set_scene_idxs([i])
|
| 129 |
+
a = bld.build_kinematic(name=f"bowl-{i}"); bowls.append(a); self.remove_from_state_dict_registry(a)
|
| 130 |
+
self.bowl = Actor.merge(bowls, name="bowl"); self.add_to_state_dict_registry(self.bowl)
|
| 131 |
+
# per-env target index + phase flags
|
| 132 |
+
self.target_idx = torch.zeros(n, dtype=torch.long, device=self.device)
|
| 133 |
+
self._flags = {k: torch.zeros(n, dtype=torch.bool, device=self.device) for k in ["grasped", "lifted", "over_bowl", "released", "wrong_cube"]}
|
| 134 |
+
self._flag_step = {k: torch.full((n,), -1, dtype=torch.long, device=self.device) for k in self._flags}
|
| 135 |
+
|
| 136 |
+
# ---------------- episode init ----------------
|
| 137 |
+
def _initialize_episode(self, env_idx: torch.Tensor, options: dict):
|
| 138 |
+
with torch.device(self.device):
|
| 139 |
+
b = len(env_idx)
|
| 140 |
+
self.table_scene.initialize(env_idx)
|
| 141 |
+
# bowl side and position
|
| 142 |
+
side = torch.where(torch.rand(b) < 0.5, -1.0, 1.0)
|
| 143 |
+
bx = torch.rand(b) * (self.bowl_box["x"][1] - self.bowl_box["x"][0]) + self.bowl_box["x"][0]
|
| 144 |
+
by = side * (torch.rand(b) * (self.bowl_box["y_abs"][1] - self.bowl_box["y_abs"][0]) + self.bowl_box["y_abs"][0])
|
| 145 |
+
bowl_p = torch.stack([bx, by, torch.zeros(b)], 1)
|
| 146 |
+
self.bowl.set_pose(Pose.create_from_pq(bowl_p, torch.tensor([[1.0, 0, 0, 0]] * b)))
|
| 147 |
+
# cubes: rejection-sample non-overlapping positions away from bowl
|
| 148 |
+
pos = torch.zeros((b, 3, 3))
|
| 149 |
+
for i in range(b):
|
| 150 |
+
pts = []
|
| 151 |
+
for _ in range(300):
|
| 152 |
+
x = float(torch.rand(1)) * (self.cube_box["x"][1] - self.cube_box["x"][0]) + self.cube_box["x"][0]
|
| 153 |
+
y = float(torch.rand(1)) * (self.cube_box["y"][1] - self.cube_box["y"][0]) + self.cube_box["y"][0]
|
| 154 |
+
if all(np.hypot(x - px, y - py) >= self.min_sep for px, py in pts) and np.hypot(x - float(bx[i]), y - float(by[i])) >= BOWL_R + 0.05:
|
| 155 |
+
pts.append((x, y))
|
| 156 |
+
if len(pts) == 3: break
|
| 157 |
+
while len(pts) < 3: pts.append((pts[-1][0] + 0.06, pts[-1][1]))
|
| 158 |
+
for k in range(3): pos[i, k, 0], pos[i, k, 1] = pts[k]
|
| 159 |
+
half = self.cube_half[env_idx]
|
| 160 |
+
for k, c in enumerate(COLORS):
|
| 161 |
+
xyz = pos[:, k].clone(); xyz[:, 2] = half
|
| 162 |
+
qs = randomization.random_quaternions(b, lock_x=True, lock_y=True)
|
| 163 |
+
self.cubes[c].set_pose(Pose.create_from_pq(xyz, qs))
|
| 164 |
+
self.target_idx[env_idx] = torch.randint(0, 3, (b,))
|
| 165 |
+
for k in self._flags: self._flags[k][env_idx] = False; self._flag_step[k][env_idx] = -1
|
| 166 |
+
self.cam_mount0.set_pose(self._sample_mount_pose(b)); self.cam_mount1.set_pose(self._sample_mount_pose(b))
|
| 167 |
+
self.phase_log = []
|
| 168 |
+
|
| 169 |
+
# ---------------- helpers ----------------
|
| 170 |
+
@property
|
| 171 |
+
def target_color(self) -> str:
|
| 172 |
+
return COLORS[int(self.target_idx[0])]
|
| 173 |
+
|
| 174 |
+
@property
|
| 175 |
+
def target_cube(self) -> Actor:
|
| 176 |
+
return self.cubes[self.target_color]
|
| 177 |
+
|
| 178 |
+
@property
|
| 179 |
+
def task_description(self):
|
| 180 |
+
return [f"put the {COLORS[int(i)]} cube in the bowl" for i in self.target_idx]
|
| 181 |
+
|
| 182 |
+
def _stack_cube_pos(self):
|
| 183 |
+
return torch.stack([self.cubes[c].pose.p for c in COLORS], 1) # (n,3,3)
|
| 184 |
+
|
| 185 |
+
def _target_pos(self):
|
| 186 |
+
return self._stack_cube_pos()[torch.arange(self.num_envs, device=self.device), self.target_idx]
|
| 187 |
+
|
| 188 |
+
def _grasping_each(self):
|
| 189 |
+
return torch.stack([self.agent.is_grasping(self.cubes[c]) for c in COLORS], 1) # (n,3) bool
|
| 190 |
+
|
| 191 |
+
def _inside_bowl(self, p):
|
| 192 |
+
bp = self.bowl.pose.p
|
| 193 |
+
d = torch.linalg.norm(p[:, :2] - bp[:, :2], axis=1)
|
| 194 |
+
return (d < BOWL_R - 0.012) & (p[:, 2] < bp[:, 2] + BOWL_FLOOR_H + BOWL_WALL_H) & (p[:, 2] > bp[:, 2] - 0.005)
|
| 195 |
+
|
| 196 |
+
def evaluate(self):
|
| 197 |
+
n = self.num_envs; ar = torch.arange(n, device=self.device)
|
| 198 |
+
g = self._grasping_each(); g_t = g[ar, self.target_idx]
|
| 199 |
+
others = g.clone(); others[ar, self.target_idx] = False; wrong = others.any(1)
|
| 200 |
+
tp = self._target_pos(); inside = self._inside_bowl(tp)
|
| 201 |
+
lifted = tp[:, 2] > self.cube_half + 0.02
|
| 202 |
+
over = torch.linalg.norm(tp[:, :2] - self.bowl.pose.p[:, :2], axis=1) < BOWL_R
|
| 203 |
+
step = self.elapsed_steps if torch.is_tensor(self.elapsed_steps) else torch.full((n,), int(self.elapsed_steps), device=self.device)
|
| 204 |
+
for k, v in [("grasped", g_t), ("lifted", g_t & lifted), ("over_bowl", g_t & over & lifted), ("released", self._flags["over_bowl"] & ~g_t), ("wrong_cube", wrong)]:
|
| 205 |
+
new = v & ~self._flags[k]
|
| 206 |
+
self._flag_step[k] = torch.where(new, step, self._flag_step[k]); self._flags[k] |= v
|
| 207 |
+
if n == 1 and bool(new[0]): self.phase_log.append((k, int(step[0])))
|
| 208 |
+
static = self.agent.is_static(0.6)
|
| 209 |
+
success = inside & ~g_t & static
|
| 210 |
+
return {"success": success, "is_grasped": g_t, "inside_bowl": inside, "wrong_cube": wrong, "lifted": lifted, "over_bowl": over,
|
| 211 |
+
**{f"ever_{k}": self._flags[k].clone() for k in self._flags}, **{f"step_{k}": self._flag_step[k].clone() for k in self._flags}}
|
| 212 |
+
|
| 213 |
+
def _get_obs_extra(self, info: dict):
|
| 214 |
+
obs = dict(is_grasped=info["is_grasped"], tcp_pose=self.agent.tcp_pose.raw_pose, target_onehot=torch.nn.functional.one_hot(self.target_idx, 3).float())
|
| 215 |
+
if "state" in self.obs_mode:
|
| 216 |
+
obs.update(target_pos=self._target_pos(), bowl_pos=self.bowl.pose.p, cubes_pos=self._stack_cube_pos().reshape(self.num_envs, -1),
|
| 217 |
+
tcp_to_target=self._target_pos() - self.agent.tcp_pos, target_to_bowl=self.bowl.pose.p - self._target_pos())
|
| 218 |
+
return obs
|
| 219 |
+
|
| 220 |
+
# ---------------- reward for RL demonstrator ----------------
|
| 221 |
+
def compute_dense_reward(self, obs: Any, action: torch.Tensor, info: Dict):
|
| 222 |
+
"""Staged potential reward (no per-step holding bonus once over the bowl; big terminal bonus)."""
|
| 223 |
+
tp = self._target_pos(); bp = self.bowl.pose.p; g = info["is_grasped"].float()
|
| 224 |
+
d_reach = torch.linalg.norm(tp - self.agent.tcp_pos, axis=1)
|
| 225 |
+
d_bowl = torch.linalg.norm(tp[:, :2] - bp[:, :2], axis=1)
|
| 226 |
+
lift = torch.clamp((tp[:, 2] - self.cube_half) / 0.05, 0, 1)
|
| 227 |
+
over = self._flags["over_bowl"].float() # sticky once reached while grasped+lifted
|
| 228 |
+
r = (1 - torch.tanh(5 * d_reach)) * (1 - g) # stage 0: reach (only until grasped)
|
| 229 |
+
r += g * (1 + lift) * (1 - over) # stage 1: grasp + lift (until over bowl)
|
| 230 |
+
r += g * (lift > 0.5).float() * (1 - torch.tanh(4 * d_bowl)) * 2 * (1 - over) # stage 2: carry toward bowl
|
| 231 |
+
grip_open = torch.clamp(-self.agent.robot.get_qpos()[:, -1] / 0.8, 0, 1) # 0 open ... 1 closed (gripper joint ~ -0.8 closed)
|
| 232 |
+
r += over * (3.0 + 2.0 * (1 - grip_open)) # stage 3: over bowl -> reward opening
|
| 233 |
+
r += info["inside_bowl"].float() * 4
|
| 234 |
+
r -= info["wrong_cube"].float() * 1.0
|
| 235 |
+
r -= 0.02 * torch.linalg.norm(action[:, :5], axis=1)
|
| 236 |
+
r = torch.where(info["success"], torch.full_like(r, 50.0), r)
|
| 237 |
+
return r
|
| 238 |
+
|
| 239 |
+
def compute_normalized_dense_reward(self, obs, action, info):
|
| 240 |
+
return self.compute_dense_reward(obs, action, info) / 50.0
|
code_v2/subsets.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"p05": [0, 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, 1146, 1147, 1148, 1149, 1150, 1151, 1152, 1153, 1154, 1155, 1156, 1157, 1158, 1159, 1160, 1161, 1162, 1163, 1164, 1165, 1166, 1167, 1168, 1169, 1170, 1171, 1172, 1173, 1174, 1175, 1176, 1177, 1178, 1179, 1180, 1181, 1182, 1183, 1184, 1185, 1186, 1187, 1188, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2032, 2033, 2034, 2035, 2036, 2037, 2038, 2039, 2040, 2041, 2042, 2043, 2044], "p15": [0, 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, 1146, 1147, 1148, 1149, 1150, 1151, 1152, 1153, 1154, 1155, 1156, 1157, 1158, 1159, 1160, 1161, 1162, 1163, 1164, 1165, 1166, 1167, 1168, 1169, 1170, 1171, 1172, 1173, 1174, 1175, 1176, 1177, 1178, 1179, 1180, 1181, 1182, 1183, 1184, 1185, 1186, 1187, 1188, 1189, 1190, 1191, 1192, 1193, 1194, 1195, 1196, 1197, 1198, 1199, 1200, 1201, 1202, 1203, 1204, 1205, 1206, 1207, 1208, 1209, 1210, 1211, 1212, 1213, 1214, 1215, 1216, 1217, 1218, 1219, 1220, 1221, 1222, 1223, 1224, 1225, 1226, 1227, 1228, 1229, 1230, 1231, 1232, 1233, 1234, 1235, 1236, 1237, 1238, 1239, 1240, 1241, 1242, 1243, 1244, 1245, 1246, 1247, 1248, 1249, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258, 1259, 1260, 1261, 1262, 1263, 1264, 1265, 1266, 1267, 1268, 1269, 1270, 1271, 1272, 1273, 1274, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2032, 2033, 2034, 2035, 2036, 2037, 2038, 2039, 2040, 2041, 2042, 2043, 2044, 2045, 2046, 2047, 2048, 2049, 2050, 2051, 2052, 2053, 2054, 2055, 2056, 2057, 2058, 2059, 2060, 2061, 2062, 2063, 2064, 2065, 2066, 2067, 2068, 2069, 2070, 2071, 2072, 2073, 2074, 2075, 2076, 2077, 2078, 2079, 2080, 2081, 2082, 2083, 2084, 2085, 2086, 2087, 2088, 2089, 2090, 2091, 2092, 2093, 2094, 2095, 2096, 2097, 2098, 2099, 2100, 2101, 2102, 2103, 2104, 2105, 2106, 2107, 2108, 2109, 2110, 2111, 2112, 2113, 2114, 2115, 2116, 2117, 2118, 2119, 2120, 2121, 2122, 2123, 2124, 2125], "p40": [0, 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, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 1146, 1147, 1148, 1149, 1150, 1151, 1152, 1153, 1154, 1155, 1156, 1157, 1158, 1159, 1160, 1161, 1162, 1163, 1164, 1165, 1166, 1167, 1168, 1169, 1170, 1171, 1172, 1173, 1174, 1175, 1176, 1177, 1178, 1179, 1180, 1181, 1182, 1183, 1184, 1185, 1186, 1187, 1188, 1189, 1190, 1191, 1192, 1193, 1194, 1195, 1196, 1197, 1198, 1199, 1200, 1201, 1202, 1203, 1204, 1205, 1206, 1207, 1208, 1209, 1210, 1211, 1212, 1213, 1214, 1215, 1216, 1217, 1218, 1219, 1220, 1221, 1222, 1223, 1224, 1225, 1226, 1227, 1228, 1229, 1230, 1231, 1232, 1233, 1234, 1235, 1236, 1237, 1238, 1239, 1240, 1241, 1242, 1243, 1244, 1245, 1246, 1247, 1248, 1249, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258, 1259, 1260, 1261, 1262, 1263, 1264, 1265, 1266, 1267, 1268, 1269, 1270, 1271, 1272, 1273, 1274, 1275, 1276, 1277, 1278, 1279, 1280, 1281, 1282, 1283, 1284, 1285, 1286, 1287, 1288, 1289, 1290, 1291, 1292, 1293, 1294, 1295, 1296, 1297, 1298, 1299, 1300, 1301, 1302, 1303, 1304, 1305, 1306, 1307, 1308, 1309, 1310, 1311, 1312, 1313, 1314, 1315, 1316, 1317, 1318, 1319, 1320, 1321, 1322, 1323, 1324, 1325, 1326, 1327, 1328, 1329, 1330, 1331, 1332, 1333, 1334, 1335, 1336, 1337, 1338, 1339, 1340, 1341, 1342, 1343, 1344, 1345, 1346, 1347, 1348, 1349, 1350, 1351, 1352, 1353, 1354, 1355, 1356, 1357, 1358, 1359, 1360, 1361, 1362, 1363, 1364, 1365, 1366, 1367, 1368, 1369, 1370, 1371, 1372, 1373, 1374, 1375, 1376, 1377, 1378, 1379, 1380, 1381, 1382, 1383, 1384, 1385, 1386, 1387, 1388, 1389, 1390, 1391, 1392, 1393, 1394, 1395, 1396, 1397, 1398, 1399, 1400, 1401, 1402, 1403, 1404, 1405, 1406, 1407, 1408, 1409, 1410, 1411, 1412, 1413, 1414, 1415, 1416, 1417, 1418, 1419, 1420, 1421, 1422, 1423, 1424, 1425, 1426, 1427, 1428, 1429, 1430, 1431, 1432, 1433, 1434, 1435, 1436, 1437, 1438, 1439, 1440, 1441, 1442, 1443, 1444, 1445, 1446, 1447, 1448, 1449, 1450, 1451, 1452, 1453, 1454, 1455, 1456, 1457, 1458, 1459, 1460, 1461, 1462, 1463, 1464, 1465, 1466, 1467, 1468, 1469, 1470, 1471, 1472, 1473, 1474, 1475, 1476, 1477, 1478, 1479, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1488, 1489, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2032, 2033, 2034, 2035, 2036, 2037, 2038, 2039, 2040, 2041, 2042, 2043, 2044, 2045, 2046, 2047, 2048, 2049, 2050, 2051, 2052, 2053, 2054, 2055, 2056, 2057, 2058, 2059, 2060, 2061, 2062, 2063, 2064, 2065, 2066, 2067, 2068, 2069, 2070, 2071, 2072, 2073, 2074, 2075, 2076, 2077, 2078, 2079, 2080, 2081, 2082, 2083, 2084, 2085, 2086, 2087, 2088, 2089, 2090, 2091, 2092, 2093, 2094, 2095, 2096, 2097, 2098, 2099, 2100, 2101, 2102, 2103, 2104, 2105, 2106, 2107, 2108, 2109, 2110, 2111, 2112, 2113, 2114, 2115, 2116, 2117, 2118, 2119, 2120, 2121, 2122, 2123, 2124, 2125, 2126, 2127, 2128, 2129, 2130, 2131, 2132, 2133, 2134, 2135, 2136, 2137, 2138, 2139, 2140, 2141, 2142, 2143, 2144, 2145, 2146, 2147, 2148, 2149, 2150, 2151, 2152, 2153, 2154, 2155, 2156, 2157, 2158, 2159, 2160, 2161, 2162, 2163, 2164, 2165, 2166, 2167, 2168, 2169, 2170, 2171, 2172, 2173, 2174, 2175, 2176, 2177, 2178, 2179, 2180, 2181, 2182, 2183, 2184, 2185, 2186, 2187, 2188, 2189, 2190, 2191, 2192, 2193, 2194, 2195, 2196, 2197, 2198, 2199, 2200, 2201, 2202, 2203, 2204, 2205, 2206, 2207, 2208, 2209, 2210, 2211, 2212, 2213, 2214, 2215, 2216, 2217, 2218, 2219, 2220, 2221, 2222, 2223, 2224, 2225, 2226, 2227, 2228, 2229, 2230, 2231, 2232, 2233, 2234, 2235, 2236, 2237, 2238, 2239, 2240, 2241, 2242, 2243, 2244, 2245, 2246, 2247, 2248, 2249, 2250, 2251, 2252, 2253, 2254, 2255, 2256, 2257, 2258, 2259, 2260, 2261, 2262, 2263, 2264, 2265, 2266, 2267, 2268, 2269, 2270, 2271, 2272, 2273, 2274, 2275, 2276, 2277, 2278, 2279, 2280, 2281, 2282, 2283, 2284, 2285, 2286, 2287, 2288, 2289, 2290, 2291, 2292, 2293, 2294, 2295, 2296, 2297, 2298, 2299, 2300, 2301, 2302, 2303, 2304, 2305, 2306, 2307, 2308, 2309, 2310, 2311, 2312, 2313, 2314, 2315, 2316, 2317, 2318, 2319, 2320, 2321, 2322, 2323, 2324, 2325, 2326, 2327], "p100": null}
|
code_v2/train_v2.sh
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# MolmoAct2 LoRA fine-tune on so100_bowl_train. Usage: train_v2.sh <gpu> <job> <subset:p05|p15|p40|p100> <save_freq> [extra args]
|
| 3 |
+
# R1: train_v2.sh 0 R1_p100 p100 250 ; R2: 1 R2_p05 p05 1500 ; R3: 2 R3_p15 p15 1500 ; R4: 3 R4_p40 p40 1500 ; R5: 4 R5_freeze p100 1500 --policy.train_mode_vlm=freeze
|
| 4 |
+
set -euo pipefail
|
| 5 |
+
GPU=$1; JOB=$2; SUB=$3; SAVE=$4; shift 4
|
| 6 |
+
export HF_HOME=/workspace/.hf_home CUDA_VISIBLE_DEVICES=$GPU
|
| 7 |
+
cd /workspace/cimse && source .venv/bin/activate
|
| 8 |
+
DS=/workspace/cimse/datasets/so100_bowl_train
|
| 9 |
+
EPS=$(python3 -c "import json;s=json.load(open('/workspace/cimse/sim/subsets.json'))['$SUB'];print('' if s is None else '--dataset.episodes='+json.dumps(s,separators=(',',':')))")
|
| 10 |
+
python -m lerobot.scripts.lerobot_train \
|
| 11 |
+
--dataset.repo_id=local/so100_bowl_train --dataset.root=$DS --dataset.video_backend=pyav $EPS \
|
| 12 |
+
--dataset.image_transforms.enable=true --dataset.image_transforms.max_num_transforms=3 --dataset.image_transforms.random_order=false \
|
| 13 |
+
--dataset.image_transforms.tfs='{"crop":{"weight":1.0,"type":"RandomResizedCrop","kwargs":{"size":[224,224],"scale":[0.9025,0.9025],"ratio":[1.0,1.0]}},"rotation":{"weight":1.0,"type":"RandomRotation","kwargs":{"degrees":[-5.0,5.0],"interpolation":2}},"color":{"weight":1.0,"type":"ColorJitter","kwargs":{"brightness":0.2,"contrast":[0.8,1.2],"saturation":[0.8,1.2],"hue":0.05}}}' \
|
| 14 |
+
--policy.type=molmoact2 --policy.checkpoint_path=allenai/MolmoAct2 --policy.device=cuda \
|
| 15 |
+
--policy.action_mode=continuous --policy.train_mode_vlm=lora \
|
| 16 |
+
--policy.chunk_size=30 --policy.n_action_steps=30 \
|
| 17 |
+
--policy.setup_type="single so100/so101 robotic arm in molmoact2" --policy.control_mode="absolute joint pose" \
|
| 18 |
+
--policy.image_keys='["observation.images.cam0","observation.images.cam1"]' \
|
| 19 |
+
--policy.dtype=bfloat16 --policy.num_flow_timesteps=8 --policy.gradient_checkpointing=true \
|
| 20 |
+
--policy.freeze_embedding=true --policy.normalize_gripper=true --policy.enable_knowledge_insulation=false \
|
| 21 |
+
--policy.push_to_hub=false --wandb.enable=false --seed=1000 \
|
| 22 |
+
--job_name=$JOB --output_dir=/workspace/cimse/ckpts/$JOB \
|
| 23 |
+
--steps=3000 --save_freq=$SAVE --save_checkpoint=true --log_freq=25 --env_eval_freq=-1 --num_workers=8 --batch_size=16 \
|
| 24 |
+
"$@"
|
| 25 |
+
echo "TRAIN_DONE $JOB"
|