diff --git a/leaf/code/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lerobot_export.py b/leaf/code/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lerobot_export.py new file mode 100644 index 0000000000000000000000000000000000000000..fa4fa0a1be92844c9cf410663f77de5e200bda18 --- /dev/null +++ b/leaf/code/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lerobot_export.py @@ -0,0 +1,431 @@ +"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars. + +Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding +can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan): + + python scripts/lerobot_export.py plan --raw [,] --runs-root /runs/api \ + --paper --task-set /sets/main_v2_1inst.txt --work [--batches ...] [--limit N] + python scripts/lerobot_export.py shard --work --shard i --nshards N + python scripts/lerobot_export.py merge --work --nshards N --out + +Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0 +mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped. + +LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t): + observation.images.image agentview RGB 256x256 (upright; LIBERO naming) + observation.images.wrist_image wrist (eye-in-hand) RGB 256x256 + observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout) + observation.joint_pos / joint_vel 7 arm joints (rad, rad/s) + observation.eef_quat 4: xyzw; observation.gripper_width 1 (m) + action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad), + gripper (-1 open, +1 close) + annotation.attempt_index attempt (1-based) the frame belongs to + annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`) + annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action) + annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt + annotation.task_event number of task-monitor events (error / progress events) registered at this step +Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table), +runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state +per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/. +""" +import argparse +import glob +import json +import os +import re +import shutil +import time + +import numpy as np + +FPS = 20 +RES = 256 +BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke", + "cc_smoke", "cc_opus_smoke"] +BATCH_NOTES = { + "cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog", + "cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267", + "cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299", + "cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances", + "cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)", + "cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the " + "with-history continuation of failed runs is incomplete", + "cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early", + "cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt", + "cc_opus_smoke": "smoke test: single attempt", +} +PHASES = {"move": 0, "gripper": 1, "judge": 2} +CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)", + "L2": "disturbed state to restore (incl. damage the agent causes)", + "L3": "infeasible manipulation strategy (grasp / contact / tool must change)", + "L4": "misjudged geometry (size, shape, fit, hidden structure)", + "L5": "misjudged physics (mass distribution, friction, dynamics)"} + + +def features(): + vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]} + f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names} + i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None} + return { + "observation.images.image": vid(), + "observation.images.wrist_image": vid(), + "observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z", + "finger_qpos_left", "finger_qpos_right"]), + "observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]), + "observation.gripper_width": f32(1, ["width_m"]), + "action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y", + "eef_delta_rot_aa_z", "gripper_close"]), + "annotation.attempt_index": i64(), + "annotation.command_index": i64(), + "annotation.phase": i64(), + "annotation.attempt_success": i64(), + "annotation.task_event": i64(), + } + + +# ------------------------------------------------------------------------------------------------ paper metadata + +def _clean_tex(s): + s = re.sub(r"%.*", "", s) + for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"), + (r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"), + (r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"), + (r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"), + (r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]: + s = re.sub(a, b, s) + s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s) + s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s) + for _ in range(3): + s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\$([^$]*)\$", r"\1", s) + s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ") + s = re.sub(r"\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\\[a-zA-Z]+\*?", "", s) + return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip() + + +def paper_tasks(paper_dir): + """{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the + paper's task table and task appendix (empty if the paper sources are not there).""" + out = {} + if not paper_dir: + return out + app = os.path.join(paper_dir, "sections", "appendix_tasks.tex") + tab = os.path.join(paper_dir, "sections", "tab_tasks.tex") + if os.path.exists(app): + txt = open(app).read() + parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt) + for i in range(1, len(parts) - 1, 2): + if parts[i] != "\\paragraph{": + continue + body = parts[i + 1] + m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S) + if not m: + continue + name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip() + desc = _clean_tex(body[m.end():]) + out[code] = dict(name=name, cause=_clean_tex(cause), description=desc) + if os.path.exists(tab): + names = {v["name"].lower(): k for k, v in out.items()} + for line in open(tab): + cells = [c.strip() for c in line.split("&")] + if len(cells) != 6 or not cells[-1].endswith("\\\\"): + continue + nm = re.sub(r"\\contscene", "", cells[0]).strip().lower() + code = names.get(nm) + if not code: + continue + out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]), + repair_within_attempt=_clean_tex(cells[3]) == "yes", + oracle_first_attempt_pct=_clean_tex(cells[4]), + naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip())) + return out + + +# ------------------------------------------------------------------------------------------------ collection + +def manifest_status(runs_root, batch, run, cache={}): + if batch not in cache: + p = os.path.join(runs_root, batch, "manifest.json") + cache[batch] = json.load(open(p)) if os.path.exists(p) else {} + m = cache[batch] + for r in m.get("runs", []): + if r.get("run") == run: + return r.get("status", "?"), r + for r in m.get("superseded", []): + if r.get("run") == run: + return "superseded_" + str(r.get("status", "?")), r + return "not_in_manifest", {} + + +def collect(raw_roots, runs_root, batches, task_order): + """Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root.""" + eps, rejected, seen = [], [], set() + for root in raw_roots: + for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))): + rep = json.load(open(rj)) + batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"] + if (batches and batch not in batches) or (batch, run) in seen: + continue + seen.add((batch, run)) + ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff") + status, entry = manifest_status(runs_root, batch, run) + if not ok: + never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked") + rejected.append(dict(run=run, batch=batch, run_status=status, + reason="run never started (no contract, no robot command)" if never else + "replay does not reproduce the log (the log has gaps or the replay diverged)", + detail=rep.get("first_mismatches"))) + continue + for ep in rep.get("episodes", []): + d = os.path.join(root, ep["dir"]) + ann = json.load(open(os.path.join(d, "annotation.json"))) + judged = [a for a in ann["attempts"] if a.get("success") is not None] + if not judged or ep["n_frames"] == 0: + rejected.append(dict(run=run, batch=batch, episode=ep["dir"], + reason="no judged attempt" if not judged else "no frames")) + continue + ann["source"]["run_status"] = status + ann["source"]["manifest_id"] = entry.get("id") + ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"], + max_eef_dev_m=rep["max_eef_dev_m"]) + key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99), + {"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2), + ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"]) + eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann)) + eps.sort(key=lambda x: x["key"]) + return eps, rejected + + +# ------------------------------------------------------------------------------------------------ writing + +def frames_of(path): + import av + with av.open(path) as c: + for fr in c.decode(video=0): + yield fr.to_ndarray(format="rgb24") + + +def flat_row(i, ann, n, idx0): + s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"] + att = ann["attempts"] + a0 = att[0] + return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n, + batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"], + memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"), + episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att], + harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"), + effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"), + task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"), + category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"], + success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att], + feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att], + auto_ended=[a.get("auto_ended") for a in att], + corrected_later_in_run=[a.get("corrected_later_in_run") for a in att], + error_event_in_attempt=[a.get("error_event_in_attempt") for a in att], + run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"), + n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]), + first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None) + + +def cmd_plan(a): + task_order = {} + if a.task_set and os.path.exists(a.task_set): + for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")): + task_order[line.split(":")[0].strip()] = i + batches = [b for b in a.batches.split(",") if b] if a.batches else None + eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order) + if a.limit: + eps = eps[:a.limit] + paper = paper_tasks(a.paper) + idx0 = 0 + for i, e in enumerate(eps): + ann = e["ann"] + tname = ann["task"]["name"] + if tname in paper: + ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"} + ann["episode_index"] = i + ann["dataset_index_range"] = [idx0, idx0 + e["n"]] + e["index"], e["from"] = i, idx0 + idx0 += e["n"] + del e["key"] + os.makedirs(a.work, exist_ok=True) + with open(os.path.join(a.work, "plan.json"), "w") as f: + json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f, + ensure_ascii=False) + print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True) + + +def shard_range(n_eps, i, k): + return (n_eps * i) // k, (n_eps * (i + 1)) // k + + +def cmd_shard(a): + from lerobot.datasets.lerobot_dataset import LeRobotDataset + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + lo, hi = shard_range(len(eps), a.shard, a.nshards) + out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}") + if os.path.exists(os.path.join(out, "DONE")): + print(f"shard {a.shard}: done already", flush=True) + return + shutil.rmtree(out, ignore_errors=True) + ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out, + robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads, + vcodec=a.vcodec) + nfr = 0 + for e in eps[lo:hi]: + d, ann, n = e["dir"], e["ann"], e["n"] + fr = np.load(os.path.join(d, "frames.npz")) + assert len(fr["action"]) == n, d + succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]} + evc = np.zeros(n, np.int64) + for ev in ann["task_events"]: + if 0 <= ev["frame"] < n: + evc[ev["frame"]] += 1 + state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32) + instr = ann["task"]["instruction"] + k = 0 + for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))): + if k >= n: + break + ds.add_frame({ + "observation.images.image": img, "observation.images.wrist_image": wr, + "observation.state": state[k], + "observation.joint_pos": fr["joint_pos"][k].astype(np.float32), + "observation.joint_vel": fr["joint_vel"][k].astype(np.float32), + "observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32), + "observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32), + "action": fr["action"][k].astype(np.float32), + "annotation.attempt_index": np.array([fr["attempt"][k]], np.int64), + "annotation.command_index": np.array([fr["command"][k]], np.int64), + "annotation.phase": np.array([fr["phase"][k]], np.int64), + "annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64), + "annotation.task_event": np.array([evc[k]], np.int64), + "task": instr, + }) + k += 1 + if k != n: + raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames") + ds.save_episode() + nfr += n + ds.finalize() + shutil.rmtree(os.path.join(out, "images"), ignore_errors=True) + open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n") + print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True) + + +def cmd_merge(a): + from pathlib import Path + from lerobot.datasets.aggregate import aggregate_datasets + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + roots, ids = [], [] + for i in range(a.nshards): + lo, hi = shard_range(len(eps), i, a.nshards) + if hi <= lo: + continue + r = os.path.join(a.work, "shards", f"shard_{i:03d}") + if not os.path.exists(os.path.join(r, "DONE")): + raise SystemExit(f"shard {i} is not done") + roots.append(Path(r)) + ids.append(f"{plan['repo_id']}-shard{i:03d}") + if os.path.exists(a.out): + raise SystemExit(f"{a.out} exists; refusing to overwrite") + aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out)) + print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True) + write_sidecars(a, plan) + print(f"merge done in {time.time() - t0:.0f}s", flush=True) + + +def write_sidecars(a, plan): + eps, paper = plan["episodes"], plan["paper"] + lff = os.path.join(a.out, "lff") + for sub in ("annotations", "sim_state", "final", "code"): + os.makedirs(os.path.join(lff, sub), exist_ok=True) + rows, runs, tasks = [], {}, {} + for e in eps: + i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"] + name = f"episode_{i:06d}" + if os.path.exists(os.path.join(d, "sim_state.npy")): + shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy")) + shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz")) + for cam, key in (("agentview", "image"), ("wrist", "wrist_image")): + shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png")) + with open(os.path.join(lff, "annotations", name + ".json"), "w") as f: + json.dump(ann, f, indent=1, ensure_ascii=False) + rows.append(flat_row(i, ann, n, e["from"])) + tname = ann["task"]["name"] + rk = (ann["source"]["batch"], ann["source"]["run"]) + r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"), + run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"], + memory_free_chain_of=ann["source"].get("memory_free_chain_of"), + memory_free_rep=ann["source"].get("memory_free_rep"), task=tname, + seed=ann["task"]["seed"], model=ann["agent"].get("model"), + harness=ann["agent"].get("harness"), + harness_version=ann["agent"].get("harness_version"), + codex_catalog=ann["agent"].get("codex_catalog"), + outcome_class=ann["run_outcome"].get("outcome_class"), + attempt_history=ann["run_outcome"].get("attempt_history"), + agent_final_report=ann["run_outcome"].get("agent_final_report"), + episodes=[])) + for x in ann["attempts"]: + r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success"))) + if tname not in tasks: + tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")} + if tname in paper: + tasks[tname]["paper"] = paper[tname] + tasks[tname]["instances"] = {} + tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"] + # memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id) + by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")} + for r in runs.values(): + if r.get("memory_free_chain_of"): + r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"])) + for (b, rn), r in runs.items(): + r["memory_free_retries"] = sorted((x["run"] for x in runs.values() + if x["batch"] == b and x.get("memory_free_chain_of_run") == rn), + key=lambda q: runs[(b, q)].get("memory_free_rep") or 0) + with open(os.path.join(lff, "episodes.jsonl"), "w") as f: + for row in rows: + f.write(json.dumps(row, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "runs.jsonl"), "w") as f: + for r in runs.values(): + f.write(json.dumps(r, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "tasks.json"), "w") as f: + json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False) + with open(os.path.join(lff, "batches.json"), "w") as f: + json.dump(BATCH_NOTES, f, indent=1) + with open(os.path.join(lff, "rejected.json"), "w") as f: + json.dump(plan["rejected"], f, indent=1) + here = os.path.dirname(os.path.abspath(__file__)) + for s in ("lerobot_replay.py", "lerobot_export.py"): + shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("step", choices=["plan", "shard", "merge"]) + ap.add_argument("--work", required=True) + ap.add_argument("--raw", default="") + ap.add_argument("--runs-root", default="") + ap.add_argument("--out", default="") + ap.add_argument("--paper", default="") + ap.add_argument("--task-set", default="") + ap.add_argument("--repo-id", default="lffbench/agent-replays") + ap.add_argument("--batches", default="") + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--shard", type=int, default=0) + ap.add_argument("--nshards", type=int, default=1) + ap.add_argument("--threads", type=int, default=2) + ap.add_argument("--vcodec", default="libsvtav1") + a = ap.parse_args() + {"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a) + + +if __name__ == "__main__": + main() diff --git a/leaf/code/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lerobot_replay.py b/leaf/code/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lerobot_replay.py new file mode 100644 index 0000000000000000000000000000000000000000..4c43a69bdb066327b27614bc9efda53d4a74e931 --- /dev/null +++ b/leaf/code/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lerobot_replay.py @@ -0,0 +1,744 @@ +"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay +against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the +LeRobot export (scripts/lerobot_export.py). + + python scripts/lerobot_replay.py check [ ...] [--json out.json] # replay only, print fidelity + python scripts/lerobot_replay.py record --out [--res 256] + +Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot +commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite +is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly +like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same +outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width, +ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code +hashes equal the current files are expected to match (check_code()). + +Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB, +proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes: +protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode +per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the +fidelity check runs in record mode too. Per episode the recorder writes ///epNN/: + agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes) + frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase + sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel) + final_*.png, final.npz observation after the last control step (the state the outcome was judged in) + annotation.json episode annotation (build_annotation) +and ///replay.json (fidelity) when the whole run is done. +""" +import argparse +import ast +import hashlib +import importlib +import json +import math +import os +import pkgutil +import re +import shutil +import sys +import time +from collections import defaultdict + +import numpy as np + +LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, LFF_ROOT) + +from lffbench import envs # noqa: E402 +from lffbench import tasks as task_pkg # noqa: E402 +from lffbench.agent import camera as C # noqa: E402 +from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402 +from lffbench.task_base import TASKS # noqa: E402 + +for _m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{_m.name}") + +# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the +# task's outcome() check after `finish` (the arm holds still; not an agent action) +PHASES = {"move": 0, "gripper": 1, "judge": 2} +FPS = 20 +SCHEMA = "lff-replay-1" + +# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR" +ERROR_FLAGS = ("trap_fired", "recovered_in_attempt") +ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events", + "n_missed_strikes", "n_open_gripper_pushes") + + +def load_jsonl(p): + out = [] + if not os.path.exists(p): + return out + with open(p) as f: + for line in f: + line = line.strip() + if line: + try: + out.append(json.loads(line)) + except ValueError: + pass + return out + + +def norm_json(o): + return json.loads(json.dumps(o, default=_json_default)) + + +def sha256(p): + with open(p, "rb") as f: + return hashlib.sha256(f.read()).hexdigest() + + +def check_code(run_dir): + """[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract.""" + p = os.path.join(run_dir, "contract.json") + if not os.path.exists(p): + return [("contract.json", None, None)] + files = json.load(open(p))["contract"].get("server_code_files", {}) + bad = [] + for f, h in files.items(): + q = os.path.join(LFF_ROOT, f) + cur = sha256(q) if os.path.exists(q) else None + if cur != h: + bad.append((f, h, cur)) + return bad + + +def diff_json(a, b, path="", tol=0.0, out=None, limit=20): + """Differences between two JSON values (numbers compared with an absolute tolerance).""" + out = [] if out is None else out + if len(out) >= limit: + return out + if isinstance(a, dict) and isinstance(b, dict): + for k in sorted(set(a) | set(b)): + if k not in a or k not in b: + out.append((f"{path}.{k}", a.get(k, ""), b.get(k, ""))) + else: + diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit) + elif isinstance(a, list) and isinstance(b, list): + if len(a) != len(b): + out.append((path, f"len {len(a)}", f"len {len(b)}")) + else: + for i, (x, y) in enumerate(zip(a, b)): + diff_json(x, y, f"{path}[{i}]", tol, out, limit) + elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))): + if a != b: + out.append((path, a, b)) + elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))): + out.append((path, a, b)) + return out + + +def error_event(o): + """True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none.""" + if not isinstance(o, dict): + return None + keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o] + if not keys: + return None + return any(bool(o[k]) for k in ERROR_FLAGS if k in o) or any((o.get(k) or 0) > 0 for k in ERROR_COUNTS if k in o) + + +# ====================================================================================================== logs -> notes + +class RunLog: + """Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's + narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition.""" + + def __init__(self, run_dir, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run = os.path.basename(self.run_dir) + self.batch = os.path.basename(os.path.dirname(self.run_dir)) + self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl")) + self.start = next(e for e in self.ev if e["ev"] == "session_start") + self.calls, self.dones, self.harness_status = {}, [], [] + last = None + for e in self.ev: + if e["ev"] == "call": + self.calls[(int(e["attempt"]), int(e["step"]))] = e + last = e + elif e["ev"] == "done": + self.dones.append(e) + last = e + elif e["ev"] == "http" and last is not None and "think_s" not in last: + ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \ + (last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe")) + if ok: + last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s") + self.manifest = manifest or {} + self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {} + p = os.path.join(self.run_dir, "harness.json") + self.harness = json.load(open(p)) if os.path.exists(p) else {} + self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl")) + self._narration() + + # ---------------------------------------------------------------- agent narration + def _narration(self): + """notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one; + finish_notes[attempt] likewise for the agent's finish call; final_report = its last message.""" + self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", [] + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + attempt = 1 + + def take(): + nonlocal buf + out = {k: v for k, v in buf.items() if v} + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + return out + + last_msg = "" + for t in self.traj: + if t.get("kind") == "header": + self.headers.append(t.get("agent") or {}) + continue + if t.get("kind") != "step": + continue + if (t.get("message") or "").strip(): + buf["messages"].append(t["message"].strip()) + last_msg = t["message"].strip() + if (t.get("reasoning_content") or "").strip(): + buf["reasoning"].append(t["reasoning_content"].strip()) + res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])} + for c in t.get("tool_calls") or []: + fn, args = c.get("function_name"), c.get("arguments") or {} + if fn == "shell": + buf["shell"].append(str(args.get("command", ""))[:2000]) + elif fn == "view_images": + buf["viewed"].extend(args.get("paths") or []) + elif fn == "robot": + cmd = str(args.get("command", "")).strip() + r = res.get(c.get("tool_call_id")) or {} + try: + rep = json.loads(r.get("content") or "{}") + except ValueError: + rep = {} + word = cmd.split()[0] if cmd else "" + m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", ""))) + if word in ("move_eef", "observe") and m: + a, s = int(m.group(1)), int(m.group(2)) + n = take() + n["command"] = cmd + self.notes[(a, s)] = n + attempt = a + elif word in ("finish", "done"): + n = take() + n["command"] = cmd + n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)} + self.finish_notes.setdefault(attempt, n) + if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"): + attempt += 1 + # status / help / errors: their narration stays in the buffer for the next command + self.final_report = last_msg + + # ---------------------------------------------------------------- run-level labels + def attempts(self): + out = [] + for e in self.dones: + o = e.get("outcome") or {} + if isinstance(o, str): + try: + o = ast.literal_eval(o) + except (ValueError, SyntaxError): + o = {} + out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o, + reason=e.get("reason") or "")) + return sorted(out, key=lambda x: x["attempt"]) + + def condition(self): + s, en = self.start, self.entry + mem = s.get("memory", en.get("mem")) + chain = en.get("chain") + if mem == "full": + cond = "with_history" + elif chain: + cond = "memory_free_retry" + else: + cond = "independent_single_attempt" + return cond, chain + + def outcome_class(self): + """CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None.""" + att = self.attempts() + if not att or self.start.get("memory") != "full": + return None, "".join("S" if a["success"] else "F" for a in att) + hist = "".join("S" if a["success"] else "F" for a in att) + if att[0]["success"]: + ev = error_event(att[0]["outcome"]) + cls = "S?" if ev is None else ("IR" if ev else "CS") + else: + cls = "XR" if any(a["success"] for a in att) else "F" + return cls, hist + + def agent_info(self): + h, en = self.harness, self.entry + hdr = self.headers[0] if self.headers else {} + return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"), + harness_version=h.get("version") or hdr.get("version"), + harness_binary_sha256=(h.get("binary") or {}).get("sha256"), + model=h.get("model") or en.get("model") or hdr.get("model_name"), + effort=h.get("effort") or en.get("effort") or hdr.get("effort"), + provider=h.get("provider") or en.get("provider"), + codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"), + jail=en.get("jail")) + + +# ====================================================================================================== recording + +class EpisodeSink: + """Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed.""" + + def __init__(self, path): + self.path = path + os.makedirs(path, exist_ok=True) + self.w = None + self.num = defaultdict(list) + self.n = 0 + + def add(self, st, imgs): + import imageio + if self.w is None: + self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb", + pixelformat="rgb24", macro_block_size=1, + ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error") + for k in ("agentview", "wrist")] + for w, im in zip(self.w, imgs): + w.append_data(im) + for k, v in st.items(): + self.num[k].append(v) + self.n += 1 + + def close(self, final_state, final_imgs): + from PIL import Image + if self.w is not None: + for w in self.w: + w.close() + arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"} + np.savez(os.path.join(self.path, "frames.npz"), **arr) + if self.num.get("sim_state"): + np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64)) + np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()}) + for k, im in zip(("agentview", "wrist"), final_imgs): + Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png")) + + +class Recorder: + """Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink.""" + + def __init__(self, rp, res): + self.rp, self.res = rp, int(res) + self.active = False + self.sink = None + self.cur = dict(attempt=1, command=-1, phase=PHASES["move"]) + env = rp.task.env + self.env, self.rob = env, env.robots[0] + self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist")) + orig = env.step + + def step(a): + if self.active and self.sink is not None: + self.capture(np.asarray(a, np.float64)) + out = orig(a) + if self.active and self.sink is not None: + self.rp.poll_events(self.sink.n - 1) + return out + + env.step = step + + @property + def n(self): + return self.sink.n if self.sink is not None else 0 + + def state(self): + import robosuite.utils.transform_utils as T + env, rob = self.env, self.rob + d = env.sim.data + eef = np.array(d.site_xpos[rob.eef_site_id], np.float64) + q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw") + gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64) + try: + flat = np.asarray(env.sim.get_state().flatten(), np.float64) + except Exception: + flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64) + sk = self.rp.task.sk + return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64), + gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64), + joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64), + gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64), + eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)), + sim_time=np.float64(d.time), sim_state=flat) + + def images(self): + return [envs.render(self.env, c, self.res) for c in self.cams] + + def capture(self, a): + st = self.state() + st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]), + phase=np.int64(self.cur["phase"])) + self.sink.add(st, self.images()) + + +class RunReplay: + def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run_name = os.path.basename(self.run_dir) + self.log = RunLog(self.run_dir, manifest) + self.ev = self.log.ev + self.start = self.log.start + cp = os.path.join(self.run_dir, "contract.json") + self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {} + spec = self.contract.get("image_spec") or {} + self.image_res = int(spec.get("width", 512)) + self.code_diff = check_code(self.run_dir) + s = self.start + self.task = TASKS[s["task"]](cam_res=self.image_res) + inst = self.task.sample_instance(s["seed"]) + logged = s.get("inst") or {} + sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")}) + self.inst_diff = diff_json(sampled, logged, "inst") + if s.get("arm", "none") not in (None, "none") or logged.get("nominal"): + inst.update(logged) # controlled arms / nominal: the server overrode these instance fields + self.inst_diff = [] + self.inst = inst + self.protocol = getattr(self.task, "protocol", "cross") + self.k = int(s.get("k") or self.task.max_attempts) + self.attempt = 1 + self.mismatch = [] # (where, what, logged, replayed) + self.n_checked = 0 + self.max_dev_m = 0.0 + self.unfinished = None + self.rec = Recorder(self, res) if record else None + self.res = int(res) + self.out_root = out_root + self.n_mon = 0 + self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0 + self.episodes = [] # summaries of the written episodes + self.task.reset_instance(self.inst) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + sim = self.task.env.sim + bid = sim.model.body_name2id("robot0_base") + self.base_off = np.array(sim.data.body_xpos[bid], float).copy() + if self.rec: + self._open_episode() + + # ------------------------------------------------------------------ episodes + def _ep_dir(self): + return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}") + + def _open_episode(self): + self.rec.sink = EpisodeSink(self._ep_dir()) + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.rec.active = True + self.events, self.spans, self.ep_attempts = [], [], [] + self.ep_initial = self.rec.state() # state right after the reset (before frame 0) + + def close_episode(self): + if not self.rec: + self.ep_attempts = [] + return + sink = self.rec.sink + st = self.rec.state() + imgs = self.rec.images() + st.pop("sim_state", None) + sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs) + ann = build_annotation(self, sink) + with open(os.path.join(sink.path, "annotation.json"), "w") as f: + json.dump(ann, f, indent=1, default=_json_default) + self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n, + attempts=[a["attempt"] for a in self.ep_attempts])) + self.rec.active = False + self.rec.sink = None + self.ep_index += 1 + + # ------------------------------------------------------------------ monitor events (task-side error events) + def poll_events(self, frame): + mon = getattr(self.task, "mon", None) + evs = mon.get("events") if isinstance(mon, dict) else None + if not isinstance(evs, list): + return + if len(evs) < self.n_mon: # monitor was rebuilt + self.n_mon = 0 + for e in evs[self.n_mon:]: + self.events.append(dict(frame=int(frame), attempt=self.attempt, + event=norm_json(e) if isinstance(e, dict) else str(e))) + self.n_mon = len(evs) + + # ------------------------------------------------------------------ state as the server reports it + def proprio_la(self): + p = self.ex.proprio() + pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off] + return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"]) + + def compare(self, where, rep_logged, rep): + self.n_checked += 1 + for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"): + if k not in rep_logged or k not in rep: + continue + a, b = rep_logged[k], rep[k] + if k == "eef_pos": + dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float)))) + self.max_dev_m = max(self.max_dev_m, dev) + if dev > 1.5e-4: + self.mismatch.append((where, k, a, b)) + elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4): + self.mismatch.append((where, k, a, b)) + if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)): + self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok"))) + + def _span(self, e, f0, kind): + if self.rec: + self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0, + frame_end=self.rec.n)) + + # ------------------------------------------------------------------ commands (robot_server._handle_v2) + def move_eef(self, e): + args = e.get("args") or {} + where = f"a{e['attempt']}s{e['step']}" + logged = e.get("report") or {} + f0 = self.rec.n if self.rec else 0 + p = self.ex.proprio() + if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}: + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + off = self.base_off + try: + cur = np.asarray(p["eef_pos"], float) - off + tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")] + yaw = float(args.get("yaw", p["eef_yaw_deg"])) + speed = None if args.get("speed") in (None, "") else float(args["speed"]) + except (TypeError, ValueError): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + grip = args.get("gripper") + if grip not in (None, "open", "close"): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + moving = any(k in args for k in ("x", "y", "z", "yaw")) + tgt_w = np.asarray(tgt) + off + if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)): + self._span(e, f0, "rejected") + return self.compare(where, logged, dict(ok=False, **self.proprio_la())) + raw = {} + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"]) + if moving: + mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw) + if speed is not None: + mv["speed"] = speed + raw.update(self.ex.call("move_to", mv).report) + if grip is not None: + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"]) + raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report) + rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la()) + self.compare(where, logged, rep) + lr = e.get("raw") or {} + for k in ("holding_object", "touched_object"): + if k in lr and k in raw and bool(lr[k]) != bool(raw[k]): + self.mismatch.append((where, "raw." + k, lr[k], raw[k])) + self._span(e, f0, "move_eef") + + def observe(self, e): + f0 = self.rec.n if self.rec else 0 + self._span(e, f0, "observe") + + def done(self, e): + f0 = self.rec.n if self.rec else 0 + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"]) + out = self.task.outcome(self.inst) + succ = bool(out["success"]) + where = f"a{e['attempt']}done" + if succ != bool(e.get("success") in (True, "True")): + self.mismatch.append((where, "success", e.get("success"), succ)) + lo = e.get("outcome") or {} + ro = norm_json({k: v for k, v in out.items() if k != "feedback"}) + if isinstance(lo, dict): + for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8): + self.mismatch.append((where,) + d) + info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""), + feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")), + think_s=e.get("think_s")) + try: + info["feedback_f2"] = self.task.feedback(self.inst, out, "F2") + except Exception as ex_: + info["feedback_f2"] = f"" + if self.rec: + info["judge_frames"] = [f0, self.rec.n] + self.ep_attempts.append(info) + last = self.attempt >= self.k or succ or bool(out.get("terminal")) + if self.protocol == "cross" or last: + self.close_episode() + if last: + return True + self.attempt += 1 + if self.protocol == "cross": + self.task.reset_instance(self.inst) + self.n_mon = 0 + if self.rec: + self._open_episode() + elif self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + return False + + def run(self): + t0 = time.time() + finished = False + for e in self.ev: + if e["ev"] == "call": + if e.get("cmd") == "move_eef": + self.move_eef(e) + elif e.get("cmd") == "observe": + self.observe(e) + else: + self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None)) + elif e["ev"] == "done": + finished = self.done(e) + if finished: + break + self.unfinished = not finished + if not finished and self.rec and self.rec.sink is not None: + # the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged + if self.rec.n or self.ep_attempts: + self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True, + finish_reason="", feedback_shown="", auto_ended=False)) + self.close_episode() + else: + shutil.rmtree(self.rec.sink.path, ignore_errors=True) + self.rec.sink = None + self.wall_s = time.time() - t0 + return self + + def summary(self): + return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"], + protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff), + n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6), + unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1), + first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]]) + + +# ====================================================================================================== annotation + +def task_info(task, inst): + cls = type(task) + return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable", + category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"), + max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)), + instruction=cls.instruction) + + +def build_annotation(rp, sink): + """Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2 + failure description), run-level outcome class, every robot command with its frame span and the agent's narration, + task-side error events with frame indices.""" + log = rp.log + s = rp.start + cond, chain = log.condition() + cls, hist = log.outcome_class() + att_all = log.attempts() + attempts = [] + for a in rp.ep_attempts: + a = dict(a) + n = a["attempt"] + later = [x for x in att_all if x["attempt"] > n] + a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later)) + a["is_last_attempt_of_run"] = not later + fn = log.finish_notes.get(n) + if fn: + a["agent_finish"] = fn + a["error_event_in_attempt"] = error_event(a.get("outcome")) + attempts.append(a) + # post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command) + for a in attempts: + nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1]) + if a.get("success") is False and nxt: + note = log.notes[nxt[0]] + a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note} + commands = [] + for sp in rp.spans: + e = log.calls.get((sp["attempt"], sp["step"])) or {} + rep = e.get("report") or {} + c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"], + frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]), + args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"), + stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"), + gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"), + touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"), + agent_obs_images=rep.get("images")) + note = log.notes.get((sp["attempt"], sp["step"])) + if note: + c["agent_note"] = {k: v for k, v in note.items() if k != "command"} + commands.append(c) + t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x] + return dict( + schema=SCHEMA, + source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts], + episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain, + memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None), + feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"), + k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"), + contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256") + if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)), + agent=log.agent_info(), + task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"), + instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}), + run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all), + run_success=any(x["success"] for x in att_all) if att_all else None, + agent_final_report=log.final_report[:6000] or None, + mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)), + attempts=attempts, + commands=commands, + task_events=rp.events, + frames=dict(n=sink.n, fps=FPS, image_res=rp.res, + phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"], + joint_pos=rp.ep_initial["joint_pos"], + gripper_qpos=rp.ep_initial["gripper_qpos"])), + ) + + +# ====================================================================================================== CLI + +def load_manifest(run_dir): + p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json") + return json.load(open(p)) if os.path.exists(p) else {} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("mode", choices=["check", "record"]) + ap.add_argument("runs", nargs="+") + ap.add_argument("--json", default="") + ap.add_argument("--out", default="") + ap.add_argument("--res", type=int, default=256) + ap.add_argument("--force", action="store_true", help="record again even if replay.json exists") + a = ap.parse_args() + rows = [] + for r in a.runs: + r = r.rstrip("/") + try: + if a.mode == "check": + s = RunReplay(r, manifest=load_manifest(r)).run().summary() + else: + batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r) + rd = os.path.join(a.out, batch, name) + if os.path.exists(os.path.join(rd, "replay.json")) and not a.force: + print(json.dumps(dict(run=name, skipped="exists")), flush=True) + continue + shutil.rmtree(rd, ignore_errors=True) + rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run() + s = rp.summary() + s["episodes"] = rp.episodes + with open(os.path.join(rd, "replay.json"), "w") as f: + json.dump(s, f, indent=1) + except Exception: + import traceback + s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:]) + rows.append(s) + print(json.dumps(s), flush=True) + if a.json: + with open(a.json, "w") as f: + json.dump(rows, f, indent=1) + + +if __name__ == "__main__": + main() diff --git a/leaf/code/compound-lh-20261102-clh_20261102_deepseek/lerobot_export.py b/leaf/code/compound-lh-20261102-clh_20261102_deepseek/lerobot_export.py new file mode 100644 index 0000000000000000000000000000000000000000..fa4fa0a1be92844c9cf410663f77de5e200bda18 --- /dev/null +++ b/leaf/code/compound-lh-20261102-clh_20261102_deepseek/lerobot_export.py @@ -0,0 +1,431 @@ +"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars. + +Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding +can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan): + + python scripts/lerobot_export.py plan --raw [,] --runs-root /runs/api \ + --paper --task-set /sets/main_v2_1inst.txt --work [--batches ...] [--limit N] + python scripts/lerobot_export.py shard --work --shard i --nshards N + python scripts/lerobot_export.py merge --work --nshards N --out + +Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0 +mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped. + +LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t): + observation.images.image agentview RGB 256x256 (upright; LIBERO naming) + observation.images.wrist_image wrist (eye-in-hand) RGB 256x256 + observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout) + observation.joint_pos / joint_vel 7 arm joints (rad, rad/s) + observation.eef_quat 4: xyzw; observation.gripper_width 1 (m) + action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad), + gripper (-1 open, +1 close) + annotation.attempt_index attempt (1-based) the frame belongs to + annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`) + annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action) + annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt + annotation.task_event number of task-monitor events (error / progress events) registered at this step +Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table), +runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state +per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/. +""" +import argparse +import glob +import json +import os +import re +import shutil +import time + +import numpy as np + +FPS = 20 +RES = 256 +BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke", + "cc_smoke", "cc_opus_smoke"] +BATCH_NOTES = { + "cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog", + "cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267", + "cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299", + "cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances", + "cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)", + "cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the " + "with-history continuation of failed runs is incomplete", + "cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early", + "cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt", + "cc_opus_smoke": "smoke test: single attempt", +} +PHASES = {"move": 0, "gripper": 1, "judge": 2} +CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)", + "L2": "disturbed state to restore (incl. damage the agent causes)", + "L3": "infeasible manipulation strategy (grasp / contact / tool must change)", + "L4": "misjudged geometry (size, shape, fit, hidden structure)", + "L5": "misjudged physics (mass distribution, friction, dynamics)"} + + +def features(): + vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]} + f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names} + i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None} + return { + "observation.images.image": vid(), + "observation.images.wrist_image": vid(), + "observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z", + "finger_qpos_left", "finger_qpos_right"]), + "observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]), + "observation.gripper_width": f32(1, ["width_m"]), + "action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y", + "eef_delta_rot_aa_z", "gripper_close"]), + "annotation.attempt_index": i64(), + "annotation.command_index": i64(), + "annotation.phase": i64(), + "annotation.attempt_success": i64(), + "annotation.task_event": i64(), + } + + +# ------------------------------------------------------------------------------------------------ paper metadata + +def _clean_tex(s): + s = re.sub(r"%.*", "", s) + for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"), + (r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"), + (r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"), + (r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"), + (r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]: + s = re.sub(a, b, s) + s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s) + s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s) + for _ in range(3): + s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\$([^$]*)\$", r"\1", s) + s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ") + s = re.sub(r"\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\\[a-zA-Z]+\*?", "", s) + return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip() + + +def paper_tasks(paper_dir): + """{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the + paper's task table and task appendix (empty if the paper sources are not there).""" + out = {} + if not paper_dir: + return out + app = os.path.join(paper_dir, "sections", "appendix_tasks.tex") + tab = os.path.join(paper_dir, "sections", "tab_tasks.tex") + if os.path.exists(app): + txt = open(app).read() + parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt) + for i in range(1, len(parts) - 1, 2): + if parts[i] != "\\paragraph{": + continue + body = parts[i + 1] + m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S) + if not m: + continue + name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip() + desc = _clean_tex(body[m.end():]) + out[code] = dict(name=name, cause=_clean_tex(cause), description=desc) + if os.path.exists(tab): + names = {v["name"].lower(): k for k, v in out.items()} + for line in open(tab): + cells = [c.strip() for c in line.split("&")] + if len(cells) != 6 or not cells[-1].endswith("\\\\"): + continue + nm = re.sub(r"\\contscene", "", cells[0]).strip().lower() + code = names.get(nm) + if not code: + continue + out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]), + repair_within_attempt=_clean_tex(cells[3]) == "yes", + oracle_first_attempt_pct=_clean_tex(cells[4]), + naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip())) + return out + + +# ------------------------------------------------------------------------------------------------ collection + +def manifest_status(runs_root, batch, run, cache={}): + if batch not in cache: + p = os.path.join(runs_root, batch, "manifest.json") + cache[batch] = json.load(open(p)) if os.path.exists(p) else {} + m = cache[batch] + for r in m.get("runs", []): + if r.get("run") == run: + return r.get("status", "?"), r + for r in m.get("superseded", []): + if r.get("run") == run: + return "superseded_" + str(r.get("status", "?")), r + return "not_in_manifest", {} + + +def collect(raw_roots, runs_root, batches, task_order): + """Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root.""" + eps, rejected, seen = [], [], set() + for root in raw_roots: + for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))): + rep = json.load(open(rj)) + batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"] + if (batches and batch not in batches) or (batch, run) in seen: + continue + seen.add((batch, run)) + ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff") + status, entry = manifest_status(runs_root, batch, run) + if not ok: + never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked") + rejected.append(dict(run=run, batch=batch, run_status=status, + reason="run never started (no contract, no robot command)" if never else + "replay does not reproduce the log (the log has gaps or the replay diverged)", + detail=rep.get("first_mismatches"))) + continue + for ep in rep.get("episodes", []): + d = os.path.join(root, ep["dir"]) + ann = json.load(open(os.path.join(d, "annotation.json"))) + judged = [a for a in ann["attempts"] if a.get("success") is not None] + if not judged or ep["n_frames"] == 0: + rejected.append(dict(run=run, batch=batch, episode=ep["dir"], + reason="no judged attempt" if not judged else "no frames")) + continue + ann["source"]["run_status"] = status + ann["source"]["manifest_id"] = entry.get("id") + ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"], + max_eef_dev_m=rep["max_eef_dev_m"]) + key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99), + {"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2), + ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"]) + eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann)) + eps.sort(key=lambda x: x["key"]) + return eps, rejected + + +# ------------------------------------------------------------------------------------------------ writing + +def frames_of(path): + import av + with av.open(path) as c: + for fr in c.decode(video=0): + yield fr.to_ndarray(format="rgb24") + + +def flat_row(i, ann, n, idx0): + s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"] + att = ann["attempts"] + a0 = att[0] + return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n, + batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"], + memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"), + episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att], + harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"), + effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"), + task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"), + category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"], + success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att], + feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att], + auto_ended=[a.get("auto_ended") for a in att], + corrected_later_in_run=[a.get("corrected_later_in_run") for a in att], + error_event_in_attempt=[a.get("error_event_in_attempt") for a in att], + run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"), + n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]), + first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None) + + +def cmd_plan(a): + task_order = {} + if a.task_set and os.path.exists(a.task_set): + for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")): + task_order[line.split(":")[0].strip()] = i + batches = [b for b in a.batches.split(",") if b] if a.batches else None + eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order) + if a.limit: + eps = eps[:a.limit] + paper = paper_tasks(a.paper) + idx0 = 0 + for i, e in enumerate(eps): + ann = e["ann"] + tname = ann["task"]["name"] + if tname in paper: + ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"} + ann["episode_index"] = i + ann["dataset_index_range"] = [idx0, idx0 + e["n"]] + e["index"], e["from"] = i, idx0 + idx0 += e["n"] + del e["key"] + os.makedirs(a.work, exist_ok=True) + with open(os.path.join(a.work, "plan.json"), "w") as f: + json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f, + ensure_ascii=False) + print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True) + + +def shard_range(n_eps, i, k): + return (n_eps * i) // k, (n_eps * (i + 1)) // k + + +def cmd_shard(a): + from lerobot.datasets.lerobot_dataset import LeRobotDataset + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + lo, hi = shard_range(len(eps), a.shard, a.nshards) + out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}") + if os.path.exists(os.path.join(out, "DONE")): + print(f"shard {a.shard}: done already", flush=True) + return + shutil.rmtree(out, ignore_errors=True) + ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out, + robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads, + vcodec=a.vcodec) + nfr = 0 + for e in eps[lo:hi]: + d, ann, n = e["dir"], e["ann"], e["n"] + fr = np.load(os.path.join(d, "frames.npz")) + assert len(fr["action"]) == n, d + succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]} + evc = np.zeros(n, np.int64) + for ev in ann["task_events"]: + if 0 <= ev["frame"] < n: + evc[ev["frame"]] += 1 + state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32) + instr = ann["task"]["instruction"] + k = 0 + for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))): + if k >= n: + break + ds.add_frame({ + "observation.images.image": img, "observation.images.wrist_image": wr, + "observation.state": state[k], + "observation.joint_pos": fr["joint_pos"][k].astype(np.float32), + "observation.joint_vel": fr["joint_vel"][k].astype(np.float32), + "observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32), + "observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32), + "action": fr["action"][k].astype(np.float32), + "annotation.attempt_index": np.array([fr["attempt"][k]], np.int64), + "annotation.command_index": np.array([fr["command"][k]], np.int64), + "annotation.phase": np.array([fr["phase"][k]], np.int64), + "annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64), + "annotation.task_event": np.array([evc[k]], np.int64), + "task": instr, + }) + k += 1 + if k != n: + raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames") + ds.save_episode() + nfr += n + ds.finalize() + shutil.rmtree(os.path.join(out, "images"), ignore_errors=True) + open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n") + print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True) + + +def cmd_merge(a): + from pathlib import Path + from lerobot.datasets.aggregate import aggregate_datasets + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + roots, ids = [], [] + for i in range(a.nshards): + lo, hi = shard_range(len(eps), i, a.nshards) + if hi <= lo: + continue + r = os.path.join(a.work, "shards", f"shard_{i:03d}") + if not os.path.exists(os.path.join(r, "DONE")): + raise SystemExit(f"shard {i} is not done") + roots.append(Path(r)) + ids.append(f"{plan['repo_id']}-shard{i:03d}") + if os.path.exists(a.out): + raise SystemExit(f"{a.out} exists; refusing to overwrite") + aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out)) + print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True) + write_sidecars(a, plan) + print(f"merge done in {time.time() - t0:.0f}s", flush=True) + + +def write_sidecars(a, plan): + eps, paper = plan["episodes"], plan["paper"] + lff = os.path.join(a.out, "lff") + for sub in ("annotations", "sim_state", "final", "code"): + os.makedirs(os.path.join(lff, sub), exist_ok=True) + rows, runs, tasks = [], {}, {} + for e in eps: + i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"] + name = f"episode_{i:06d}" + if os.path.exists(os.path.join(d, "sim_state.npy")): + shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy")) + shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz")) + for cam, key in (("agentview", "image"), ("wrist", "wrist_image")): + shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png")) + with open(os.path.join(lff, "annotations", name + ".json"), "w") as f: + json.dump(ann, f, indent=1, ensure_ascii=False) + rows.append(flat_row(i, ann, n, e["from"])) + tname = ann["task"]["name"] + rk = (ann["source"]["batch"], ann["source"]["run"]) + r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"), + run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"], + memory_free_chain_of=ann["source"].get("memory_free_chain_of"), + memory_free_rep=ann["source"].get("memory_free_rep"), task=tname, + seed=ann["task"]["seed"], model=ann["agent"].get("model"), + harness=ann["agent"].get("harness"), + harness_version=ann["agent"].get("harness_version"), + codex_catalog=ann["agent"].get("codex_catalog"), + outcome_class=ann["run_outcome"].get("outcome_class"), + attempt_history=ann["run_outcome"].get("attempt_history"), + agent_final_report=ann["run_outcome"].get("agent_final_report"), + episodes=[])) + for x in ann["attempts"]: + r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success"))) + if tname not in tasks: + tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")} + if tname in paper: + tasks[tname]["paper"] = paper[tname] + tasks[tname]["instances"] = {} + tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"] + # memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id) + by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")} + for r in runs.values(): + if r.get("memory_free_chain_of"): + r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"])) + for (b, rn), r in runs.items(): + r["memory_free_retries"] = sorted((x["run"] for x in runs.values() + if x["batch"] == b and x.get("memory_free_chain_of_run") == rn), + key=lambda q: runs[(b, q)].get("memory_free_rep") or 0) + with open(os.path.join(lff, "episodes.jsonl"), "w") as f: + for row in rows: + f.write(json.dumps(row, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "runs.jsonl"), "w") as f: + for r in runs.values(): + f.write(json.dumps(r, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "tasks.json"), "w") as f: + json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False) + with open(os.path.join(lff, "batches.json"), "w") as f: + json.dump(BATCH_NOTES, f, indent=1) + with open(os.path.join(lff, "rejected.json"), "w") as f: + json.dump(plan["rejected"], f, indent=1) + here = os.path.dirname(os.path.abspath(__file__)) + for s in ("lerobot_replay.py", "lerobot_export.py"): + shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("step", choices=["plan", "shard", "merge"]) + ap.add_argument("--work", required=True) + ap.add_argument("--raw", default="") + ap.add_argument("--runs-root", default="") + ap.add_argument("--out", default="") + ap.add_argument("--paper", default="") + ap.add_argument("--task-set", default="") + ap.add_argument("--repo-id", default="lffbench/agent-replays") + ap.add_argument("--batches", default="") + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--shard", type=int, default=0) + ap.add_argument("--nshards", type=int, default=1) + ap.add_argument("--threads", type=int, default=2) + ap.add_argument("--vcodec", default="libsvtav1") + a = ap.parse_args() + {"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a) + + +if __name__ == "__main__": + main() diff --git a/leaf/code/compound-lh-20261102-clh_20261102_deepseek/lerobot_replay.py b/leaf/code/compound-lh-20261102-clh_20261102_deepseek/lerobot_replay.py new file mode 100644 index 0000000000000000000000000000000000000000..4c43a69bdb066327b27614bc9efda53d4a74e931 --- /dev/null +++ b/leaf/code/compound-lh-20261102-clh_20261102_deepseek/lerobot_replay.py @@ -0,0 +1,744 @@ +"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay +against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the +LeRobot export (scripts/lerobot_export.py). + + python scripts/lerobot_replay.py check [ ...] [--json out.json] # replay only, print fidelity + python scripts/lerobot_replay.py record --out [--res 256] + +Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot +commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite +is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly +like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same +outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width, +ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code +hashes equal the current files are expected to match (check_code()). + +Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB, +proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes: +protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode +per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the +fidelity check runs in record mode too. Per episode the recorder writes ///epNN/: + agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes) + frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase + sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel) + final_*.png, final.npz observation after the last control step (the state the outcome was judged in) + annotation.json episode annotation (build_annotation) +and ///replay.json (fidelity) when the whole run is done. +""" +import argparse +import ast +import hashlib +import importlib +import json +import math +import os +import pkgutil +import re +import shutil +import sys +import time +from collections import defaultdict + +import numpy as np + +LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, LFF_ROOT) + +from lffbench import envs # noqa: E402 +from lffbench import tasks as task_pkg # noqa: E402 +from lffbench.agent import camera as C # noqa: E402 +from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402 +from lffbench.task_base import TASKS # noqa: E402 + +for _m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{_m.name}") + +# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the +# task's outcome() check after `finish` (the arm holds still; not an agent action) +PHASES = {"move": 0, "gripper": 1, "judge": 2} +FPS = 20 +SCHEMA = "lff-replay-1" + +# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR" +ERROR_FLAGS = ("trap_fired", "recovered_in_attempt") +ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events", + "n_missed_strikes", "n_open_gripper_pushes") + + +def load_jsonl(p): + out = [] + if not os.path.exists(p): + return out + with open(p) as f: + for line in f: + line = line.strip() + if line: + try: + out.append(json.loads(line)) + except ValueError: + pass + return out + + +def norm_json(o): + return json.loads(json.dumps(o, default=_json_default)) + + +def sha256(p): + with open(p, "rb") as f: + return hashlib.sha256(f.read()).hexdigest() + + +def check_code(run_dir): + """[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract.""" + p = os.path.join(run_dir, "contract.json") + if not os.path.exists(p): + return [("contract.json", None, None)] + files = json.load(open(p))["contract"].get("server_code_files", {}) + bad = [] + for f, h in files.items(): + q = os.path.join(LFF_ROOT, f) + cur = sha256(q) if os.path.exists(q) else None + if cur != h: + bad.append((f, h, cur)) + return bad + + +def diff_json(a, b, path="", tol=0.0, out=None, limit=20): + """Differences between two JSON values (numbers compared with an absolute tolerance).""" + out = [] if out is None else out + if len(out) >= limit: + return out + if isinstance(a, dict) and isinstance(b, dict): + for k in sorted(set(a) | set(b)): + if k not in a or k not in b: + out.append((f"{path}.{k}", a.get(k, ""), b.get(k, ""))) + else: + diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit) + elif isinstance(a, list) and isinstance(b, list): + if len(a) != len(b): + out.append((path, f"len {len(a)}", f"len {len(b)}")) + else: + for i, (x, y) in enumerate(zip(a, b)): + diff_json(x, y, f"{path}[{i}]", tol, out, limit) + elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))): + if a != b: + out.append((path, a, b)) + elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))): + out.append((path, a, b)) + return out + + +def error_event(o): + """True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none.""" + if not isinstance(o, dict): + return None + keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o] + if not keys: + return None + return any(bool(o[k]) for k in ERROR_FLAGS if k in o) or any((o.get(k) or 0) > 0 for k in ERROR_COUNTS if k in o) + + +# ====================================================================================================== logs -> notes + +class RunLog: + """Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's + narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition.""" + + def __init__(self, run_dir, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run = os.path.basename(self.run_dir) + self.batch = os.path.basename(os.path.dirname(self.run_dir)) + self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl")) + self.start = next(e for e in self.ev if e["ev"] == "session_start") + self.calls, self.dones, self.harness_status = {}, [], [] + last = None + for e in self.ev: + if e["ev"] == "call": + self.calls[(int(e["attempt"]), int(e["step"]))] = e + last = e + elif e["ev"] == "done": + self.dones.append(e) + last = e + elif e["ev"] == "http" and last is not None and "think_s" not in last: + ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \ + (last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe")) + if ok: + last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s") + self.manifest = manifest or {} + self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {} + p = os.path.join(self.run_dir, "harness.json") + self.harness = json.load(open(p)) if os.path.exists(p) else {} + self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl")) + self._narration() + + # ---------------------------------------------------------------- agent narration + def _narration(self): + """notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one; + finish_notes[attempt] likewise for the agent's finish call; final_report = its last message.""" + self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", [] + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + attempt = 1 + + def take(): + nonlocal buf + out = {k: v for k, v in buf.items() if v} + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + return out + + last_msg = "" + for t in self.traj: + if t.get("kind") == "header": + self.headers.append(t.get("agent") or {}) + continue + if t.get("kind") != "step": + continue + if (t.get("message") or "").strip(): + buf["messages"].append(t["message"].strip()) + last_msg = t["message"].strip() + if (t.get("reasoning_content") or "").strip(): + buf["reasoning"].append(t["reasoning_content"].strip()) + res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])} + for c in t.get("tool_calls") or []: + fn, args = c.get("function_name"), c.get("arguments") or {} + if fn == "shell": + buf["shell"].append(str(args.get("command", ""))[:2000]) + elif fn == "view_images": + buf["viewed"].extend(args.get("paths") or []) + elif fn == "robot": + cmd = str(args.get("command", "")).strip() + r = res.get(c.get("tool_call_id")) or {} + try: + rep = json.loads(r.get("content") or "{}") + except ValueError: + rep = {} + word = cmd.split()[0] if cmd else "" + m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", ""))) + if word in ("move_eef", "observe") and m: + a, s = int(m.group(1)), int(m.group(2)) + n = take() + n["command"] = cmd + self.notes[(a, s)] = n + attempt = a + elif word in ("finish", "done"): + n = take() + n["command"] = cmd + n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)} + self.finish_notes.setdefault(attempt, n) + if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"): + attempt += 1 + # status / help / errors: their narration stays in the buffer for the next command + self.final_report = last_msg + + # ---------------------------------------------------------------- run-level labels + def attempts(self): + out = [] + for e in self.dones: + o = e.get("outcome") or {} + if isinstance(o, str): + try: + o = ast.literal_eval(o) + except (ValueError, SyntaxError): + o = {} + out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o, + reason=e.get("reason") or "")) + return sorted(out, key=lambda x: x["attempt"]) + + def condition(self): + s, en = self.start, self.entry + mem = s.get("memory", en.get("mem")) + chain = en.get("chain") + if mem == "full": + cond = "with_history" + elif chain: + cond = "memory_free_retry" + else: + cond = "independent_single_attempt" + return cond, chain + + def outcome_class(self): + """CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None.""" + att = self.attempts() + if not att or self.start.get("memory") != "full": + return None, "".join("S" if a["success"] else "F" for a in att) + hist = "".join("S" if a["success"] else "F" for a in att) + if att[0]["success"]: + ev = error_event(att[0]["outcome"]) + cls = "S?" if ev is None else ("IR" if ev else "CS") + else: + cls = "XR" if any(a["success"] for a in att) else "F" + return cls, hist + + def agent_info(self): + h, en = self.harness, self.entry + hdr = self.headers[0] if self.headers else {} + return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"), + harness_version=h.get("version") or hdr.get("version"), + harness_binary_sha256=(h.get("binary") or {}).get("sha256"), + model=h.get("model") or en.get("model") or hdr.get("model_name"), + effort=h.get("effort") or en.get("effort") or hdr.get("effort"), + provider=h.get("provider") or en.get("provider"), + codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"), + jail=en.get("jail")) + + +# ====================================================================================================== recording + +class EpisodeSink: + """Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed.""" + + def __init__(self, path): + self.path = path + os.makedirs(path, exist_ok=True) + self.w = None + self.num = defaultdict(list) + self.n = 0 + + def add(self, st, imgs): + import imageio + if self.w is None: + self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb", + pixelformat="rgb24", macro_block_size=1, + ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error") + for k in ("agentview", "wrist")] + for w, im in zip(self.w, imgs): + w.append_data(im) + for k, v in st.items(): + self.num[k].append(v) + self.n += 1 + + def close(self, final_state, final_imgs): + from PIL import Image + if self.w is not None: + for w in self.w: + w.close() + arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"} + np.savez(os.path.join(self.path, "frames.npz"), **arr) + if self.num.get("sim_state"): + np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64)) + np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()}) + for k, im in zip(("agentview", "wrist"), final_imgs): + Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png")) + + +class Recorder: + """Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink.""" + + def __init__(self, rp, res): + self.rp, self.res = rp, int(res) + self.active = False + self.sink = None + self.cur = dict(attempt=1, command=-1, phase=PHASES["move"]) + env = rp.task.env + self.env, self.rob = env, env.robots[0] + self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist")) + orig = env.step + + def step(a): + if self.active and self.sink is not None: + self.capture(np.asarray(a, np.float64)) + out = orig(a) + if self.active and self.sink is not None: + self.rp.poll_events(self.sink.n - 1) + return out + + env.step = step + + @property + def n(self): + return self.sink.n if self.sink is not None else 0 + + def state(self): + import robosuite.utils.transform_utils as T + env, rob = self.env, self.rob + d = env.sim.data + eef = np.array(d.site_xpos[rob.eef_site_id], np.float64) + q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw") + gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64) + try: + flat = np.asarray(env.sim.get_state().flatten(), np.float64) + except Exception: + flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64) + sk = self.rp.task.sk + return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64), + gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64), + joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64), + gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64), + eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)), + sim_time=np.float64(d.time), sim_state=flat) + + def images(self): + return [envs.render(self.env, c, self.res) for c in self.cams] + + def capture(self, a): + st = self.state() + st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]), + phase=np.int64(self.cur["phase"])) + self.sink.add(st, self.images()) + + +class RunReplay: + def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run_name = os.path.basename(self.run_dir) + self.log = RunLog(self.run_dir, manifest) + self.ev = self.log.ev + self.start = self.log.start + cp = os.path.join(self.run_dir, "contract.json") + self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {} + spec = self.contract.get("image_spec") or {} + self.image_res = int(spec.get("width", 512)) + self.code_diff = check_code(self.run_dir) + s = self.start + self.task = TASKS[s["task"]](cam_res=self.image_res) + inst = self.task.sample_instance(s["seed"]) + logged = s.get("inst") or {} + sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")}) + self.inst_diff = diff_json(sampled, logged, "inst") + if s.get("arm", "none") not in (None, "none") or logged.get("nominal"): + inst.update(logged) # controlled arms / nominal: the server overrode these instance fields + self.inst_diff = [] + self.inst = inst + self.protocol = getattr(self.task, "protocol", "cross") + self.k = int(s.get("k") or self.task.max_attempts) + self.attempt = 1 + self.mismatch = [] # (where, what, logged, replayed) + self.n_checked = 0 + self.max_dev_m = 0.0 + self.unfinished = None + self.rec = Recorder(self, res) if record else None + self.res = int(res) + self.out_root = out_root + self.n_mon = 0 + self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0 + self.episodes = [] # summaries of the written episodes + self.task.reset_instance(self.inst) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + sim = self.task.env.sim + bid = sim.model.body_name2id("robot0_base") + self.base_off = np.array(sim.data.body_xpos[bid], float).copy() + if self.rec: + self._open_episode() + + # ------------------------------------------------------------------ episodes + def _ep_dir(self): + return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}") + + def _open_episode(self): + self.rec.sink = EpisodeSink(self._ep_dir()) + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.rec.active = True + self.events, self.spans, self.ep_attempts = [], [], [] + self.ep_initial = self.rec.state() # state right after the reset (before frame 0) + + def close_episode(self): + if not self.rec: + self.ep_attempts = [] + return + sink = self.rec.sink + st = self.rec.state() + imgs = self.rec.images() + st.pop("sim_state", None) + sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs) + ann = build_annotation(self, sink) + with open(os.path.join(sink.path, "annotation.json"), "w") as f: + json.dump(ann, f, indent=1, default=_json_default) + self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n, + attempts=[a["attempt"] for a in self.ep_attempts])) + self.rec.active = False + self.rec.sink = None + self.ep_index += 1 + + # ------------------------------------------------------------------ monitor events (task-side error events) + def poll_events(self, frame): + mon = getattr(self.task, "mon", None) + evs = mon.get("events") if isinstance(mon, dict) else None + if not isinstance(evs, list): + return + if len(evs) < self.n_mon: # monitor was rebuilt + self.n_mon = 0 + for e in evs[self.n_mon:]: + self.events.append(dict(frame=int(frame), attempt=self.attempt, + event=norm_json(e) if isinstance(e, dict) else str(e))) + self.n_mon = len(evs) + + # ------------------------------------------------------------------ state as the server reports it + def proprio_la(self): + p = self.ex.proprio() + pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off] + return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"]) + + def compare(self, where, rep_logged, rep): + self.n_checked += 1 + for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"): + if k not in rep_logged or k not in rep: + continue + a, b = rep_logged[k], rep[k] + if k == "eef_pos": + dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float)))) + self.max_dev_m = max(self.max_dev_m, dev) + if dev > 1.5e-4: + self.mismatch.append((where, k, a, b)) + elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4): + self.mismatch.append((where, k, a, b)) + if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)): + self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok"))) + + def _span(self, e, f0, kind): + if self.rec: + self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0, + frame_end=self.rec.n)) + + # ------------------------------------------------------------------ commands (robot_server._handle_v2) + def move_eef(self, e): + args = e.get("args") or {} + where = f"a{e['attempt']}s{e['step']}" + logged = e.get("report") or {} + f0 = self.rec.n if self.rec else 0 + p = self.ex.proprio() + if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}: + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + off = self.base_off + try: + cur = np.asarray(p["eef_pos"], float) - off + tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")] + yaw = float(args.get("yaw", p["eef_yaw_deg"])) + speed = None if args.get("speed") in (None, "") else float(args["speed"]) + except (TypeError, ValueError): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + grip = args.get("gripper") + if grip not in (None, "open", "close"): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + moving = any(k in args for k in ("x", "y", "z", "yaw")) + tgt_w = np.asarray(tgt) + off + if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)): + self._span(e, f0, "rejected") + return self.compare(where, logged, dict(ok=False, **self.proprio_la())) + raw = {} + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"]) + if moving: + mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw) + if speed is not None: + mv["speed"] = speed + raw.update(self.ex.call("move_to", mv).report) + if grip is not None: + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"]) + raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report) + rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la()) + self.compare(where, logged, rep) + lr = e.get("raw") or {} + for k in ("holding_object", "touched_object"): + if k in lr and k in raw and bool(lr[k]) != bool(raw[k]): + self.mismatch.append((where, "raw." + k, lr[k], raw[k])) + self._span(e, f0, "move_eef") + + def observe(self, e): + f0 = self.rec.n if self.rec else 0 + self._span(e, f0, "observe") + + def done(self, e): + f0 = self.rec.n if self.rec else 0 + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"]) + out = self.task.outcome(self.inst) + succ = bool(out["success"]) + where = f"a{e['attempt']}done" + if succ != bool(e.get("success") in (True, "True")): + self.mismatch.append((where, "success", e.get("success"), succ)) + lo = e.get("outcome") or {} + ro = norm_json({k: v for k, v in out.items() if k != "feedback"}) + if isinstance(lo, dict): + for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8): + self.mismatch.append((where,) + d) + info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""), + feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")), + think_s=e.get("think_s")) + try: + info["feedback_f2"] = self.task.feedback(self.inst, out, "F2") + except Exception as ex_: + info["feedback_f2"] = f"" + if self.rec: + info["judge_frames"] = [f0, self.rec.n] + self.ep_attempts.append(info) + last = self.attempt >= self.k or succ or bool(out.get("terminal")) + if self.protocol == "cross" or last: + self.close_episode() + if last: + return True + self.attempt += 1 + if self.protocol == "cross": + self.task.reset_instance(self.inst) + self.n_mon = 0 + if self.rec: + self._open_episode() + elif self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + return False + + def run(self): + t0 = time.time() + finished = False + for e in self.ev: + if e["ev"] == "call": + if e.get("cmd") == "move_eef": + self.move_eef(e) + elif e.get("cmd") == "observe": + self.observe(e) + else: + self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None)) + elif e["ev"] == "done": + finished = self.done(e) + if finished: + break + self.unfinished = not finished + if not finished and self.rec and self.rec.sink is not None: + # the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged + if self.rec.n or self.ep_attempts: + self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True, + finish_reason="", feedback_shown="", auto_ended=False)) + self.close_episode() + else: + shutil.rmtree(self.rec.sink.path, ignore_errors=True) + self.rec.sink = None + self.wall_s = time.time() - t0 + return self + + def summary(self): + return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"], + protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff), + n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6), + unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1), + first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]]) + + +# ====================================================================================================== annotation + +def task_info(task, inst): + cls = type(task) + return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable", + category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"), + max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)), + instruction=cls.instruction) + + +def build_annotation(rp, sink): + """Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2 + failure description), run-level outcome class, every robot command with its frame span and the agent's narration, + task-side error events with frame indices.""" + log = rp.log + s = rp.start + cond, chain = log.condition() + cls, hist = log.outcome_class() + att_all = log.attempts() + attempts = [] + for a in rp.ep_attempts: + a = dict(a) + n = a["attempt"] + later = [x for x in att_all if x["attempt"] > n] + a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later)) + a["is_last_attempt_of_run"] = not later + fn = log.finish_notes.get(n) + if fn: + a["agent_finish"] = fn + a["error_event_in_attempt"] = error_event(a.get("outcome")) + attempts.append(a) + # post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command) + for a in attempts: + nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1]) + if a.get("success") is False and nxt: + note = log.notes[nxt[0]] + a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note} + commands = [] + for sp in rp.spans: + e = log.calls.get((sp["attempt"], sp["step"])) or {} + rep = e.get("report") or {} + c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"], + frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]), + args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"), + stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"), + gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"), + touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"), + agent_obs_images=rep.get("images")) + note = log.notes.get((sp["attempt"], sp["step"])) + if note: + c["agent_note"] = {k: v for k, v in note.items() if k != "command"} + commands.append(c) + t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x] + return dict( + schema=SCHEMA, + source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts], + episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain, + memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None), + feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"), + k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"), + contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256") + if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)), + agent=log.agent_info(), + task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"), + instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}), + run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all), + run_success=any(x["success"] for x in att_all) if att_all else None, + agent_final_report=log.final_report[:6000] or None, + mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)), + attempts=attempts, + commands=commands, + task_events=rp.events, + frames=dict(n=sink.n, fps=FPS, image_res=rp.res, + phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"], + joint_pos=rp.ep_initial["joint_pos"], + gripper_qpos=rp.ep_initial["gripper_qpos"])), + ) + + +# ====================================================================================================== CLI + +def load_manifest(run_dir): + p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json") + return json.load(open(p)) if os.path.exists(p) else {} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("mode", choices=["check", "record"]) + ap.add_argument("runs", nargs="+") + ap.add_argument("--json", default="") + ap.add_argument("--out", default="") + ap.add_argument("--res", type=int, default=256) + ap.add_argument("--force", action="store_true", help="record again even if replay.json exists") + a = ap.parse_args() + rows = [] + for r in a.runs: + r = r.rstrip("/") + try: + if a.mode == "check": + s = RunReplay(r, manifest=load_manifest(r)).run().summary() + else: + batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r) + rd = os.path.join(a.out, batch, name) + if os.path.exists(os.path.join(rd, "replay.json")) and not a.force: + print(json.dumps(dict(run=name, skipped="exists")), flush=True) + continue + shutil.rmtree(rd, ignore_errors=True) + rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run() + s = rp.summary() + s["episodes"] = rp.episodes + with open(os.path.join(rd, "replay.json"), "w") as f: + json.dump(s, f, indent=1) + except Exception: + import traceback + s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:]) + rows.append(s) + print(json.dumps(s), flush=True) + if a.json: + with open(a.json, "w") as f: + json.dump(rows, f, indent=1) + + +if __name__ == "__main__": + main() diff --git a/leaf/code/compound-lh-20261102-clh_20261102_gpt/lerobot_export.py b/leaf/code/compound-lh-20261102-clh_20261102_gpt/lerobot_export.py new file mode 100644 index 0000000000000000000000000000000000000000..fa4fa0a1be92844c9cf410663f77de5e200bda18 --- /dev/null +++ b/leaf/code/compound-lh-20261102-clh_20261102_gpt/lerobot_export.py @@ -0,0 +1,431 @@ +"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars. + +Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding +can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan): + + python scripts/lerobot_export.py plan --raw [,] --runs-root /runs/api \ + --paper --task-set /sets/main_v2_1inst.txt --work [--batches ...] [--limit N] + python scripts/lerobot_export.py shard --work --shard i --nshards N + python scripts/lerobot_export.py merge --work --nshards N --out + +Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0 +mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped. + +LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t): + observation.images.image agentview RGB 256x256 (upright; LIBERO naming) + observation.images.wrist_image wrist (eye-in-hand) RGB 256x256 + observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout) + observation.joint_pos / joint_vel 7 arm joints (rad, rad/s) + observation.eef_quat 4: xyzw; observation.gripper_width 1 (m) + action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad), + gripper (-1 open, +1 close) + annotation.attempt_index attempt (1-based) the frame belongs to + annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`) + annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action) + annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt + annotation.task_event number of task-monitor events (error / progress events) registered at this step +Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table), +runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state +per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/. +""" +import argparse +import glob +import json +import os +import re +import shutil +import time + +import numpy as np + +FPS = 20 +RES = 256 +BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke", + "cc_smoke", "cc_opus_smoke"] +BATCH_NOTES = { + "cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog", + "cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267", + "cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299", + "cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances", + "cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)", + "cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the " + "with-history continuation of failed runs is incomplete", + "cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early", + "cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt", + "cc_opus_smoke": "smoke test: single attempt", +} +PHASES = {"move": 0, "gripper": 1, "judge": 2} +CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)", + "L2": "disturbed state to restore (incl. damage the agent causes)", + "L3": "infeasible manipulation strategy (grasp / contact / tool must change)", + "L4": "misjudged geometry (size, shape, fit, hidden structure)", + "L5": "misjudged physics (mass distribution, friction, dynamics)"} + + +def features(): + vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]} + f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names} + i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None} + return { + "observation.images.image": vid(), + "observation.images.wrist_image": vid(), + "observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z", + "finger_qpos_left", "finger_qpos_right"]), + "observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]), + "observation.gripper_width": f32(1, ["width_m"]), + "action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y", + "eef_delta_rot_aa_z", "gripper_close"]), + "annotation.attempt_index": i64(), + "annotation.command_index": i64(), + "annotation.phase": i64(), + "annotation.attempt_success": i64(), + "annotation.task_event": i64(), + } + + +# ------------------------------------------------------------------------------------------------ paper metadata + +def _clean_tex(s): + s = re.sub(r"%.*", "", s) + for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"), + (r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"), + (r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"), + (r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"), + (r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]: + s = re.sub(a, b, s) + s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s) + s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s) + for _ in range(3): + s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\$([^$]*)\$", r"\1", s) + s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ") + s = re.sub(r"\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\\[a-zA-Z]+\*?", "", s) + return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip() + + +def paper_tasks(paper_dir): + """{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the + paper's task table and task appendix (empty if the paper sources are not there).""" + out = {} + if not paper_dir: + return out + app = os.path.join(paper_dir, "sections", "appendix_tasks.tex") + tab = os.path.join(paper_dir, "sections", "tab_tasks.tex") + if os.path.exists(app): + txt = open(app).read() + parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt) + for i in range(1, len(parts) - 1, 2): + if parts[i] != "\\paragraph{": + continue + body = parts[i + 1] + m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S) + if not m: + continue + name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip() + desc = _clean_tex(body[m.end():]) + out[code] = dict(name=name, cause=_clean_tex(cause), description=desc) + if os.path.exists(tab): + names = {v["name"].lower(): k for k, v in out.items()} + for line in open(tab): + cells = [c.strip() for c in line.split("&")] + if len(cells) != 6 or not cells[-1].endswith("\\\\"): + continue + nm = re.sub(r"\\contscene", "", cells[0]).strip().lower() + code = names.get(nm) + if not code: + continue + out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]), + repair_within_attempt=_clean_tex(cells[3]) == "yes", + oracle_first_attempt_pct=_clean_tex(cells[4]), + naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip())) + return out + + +# ------------------------------------------------------------------------------------------------ collection + +def manifest_status(runs_root, batch, run, cache={}): + if batch not in cache: + p = os.path.join(runs_root, batch, "manifest.json") + cache[batch] = json.load(open(p)) if os.path.exists(p) else {} + m = cache[batch] + for r in m.get("runs", []): + if r.get("run") == run: + return r.get("status", "?"), r + for r in m.get("superseded", []): + if r.get("run") == run: + return "superseded_" + str(r.get("status", "?")), r + return "not_in_manifest", {} + + +def collect(raw_roots, runs_root, batches, task_order): + """Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root.""" + eps, rejected, seen = [], [], set() + for root in raw_roots: + for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))): + rep = json.load(open(rj)) + batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"] + if (batches and batch not in batches) or (batch, run) in seen: + continue + seen.add((batch, run)) + ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff") + status, entry = manifest_status(runs_root, batch, run) + if not ok: + never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked") + rejected.append(dict(run=run, batch=batch, run_status=status, + reason="run never started (no contract, no robot command)" if never else + "replay does not reproduce the log (the log has gaps or the replay diverged)", + detail=rep.get("first_mismatches"))) + continue + for ep in rep.get("episodes", []): + d = os.path.join(root, ep["dir"]) + ann = json.load(open(os.path.join(d, "annotation.json"))) + judged = [a for a in ann["attempts"] if a.get("success") is not None] + if not judged or ep["n_frames"] == 0: + rejected.append(dict(run=run, batch=batch, episode=ep["dir"], + reason="no judged attempt" if not judged else "no frames")) + continue + ann["source"]["run_status"] = status + ann["source"]["manifest_id"] = entry.get("id") + ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"], + max_eef_dev_m=rep["max_eef_dev_m"]) + key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99), + {"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2), + ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"]) + eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann)) + eps.sort(key=lambda x: x["key"]) + return eps, rejected + + +# ------------------------------------------------------------------------------------------------ writing + +def frames_of(path): + import av + with av.open(path) as c: + for fr in c.decode(video=0): + yield fr.to_ndarray(format="rgb24") + + +def flat_row(i, ann, n, idx0): + s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"] + att = ann["attempts"] + a0 = att[0] + return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n, + batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"], + memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"), + episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att], + harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"), + effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"), + task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"), + category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"], + success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att], + feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att], + auto_ended=[a.get("auto_ended") for a in att], + corrected_later_in_run=[a.get("corrected_later_in_run") for a in att], + error_event_in_attempt=[a.get("error_event_in_attempt") for a in att], + run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"), + n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]), + first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None) + + +def cmd_plan(a): + task_order = {} + if a.task_set and os.path.exists(a.task_set): + for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")): + task_order[line.split(":")[0].strip()] = i + batches = [b for b in a.batches.split(",") if b] if a.batches else None + eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order) + if a.limit: + eps = eps[:a.limit] + paper = paper_tasks(a.paper) + idx0 = 0 + for i, e in enumerate(eps): + ann = e["ann"] + tname = ann["task"]["name"] + if tname in paper: + ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"} + ann["episode_index"] = i + ann["dataset_index_range"] = [idx0, idx0 + e["n"]] + e["index"], e["from"] = i, idx0 + idx0 += e["n"] + del e["key"] + os.makedirs(a.work, exist_ok=True) + with open(os.path.join(a.work, "plan.json"), "w") as f: + json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f, + ensure_ascii=False) + print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True) + + +def shard_range(n_eps, i, k): + return (n_eps * i) // k, (n_eps * (i + 1)) // k + + +def cmd_shard(a): + from lerobot.datasets.lerobot_dataset import LeRobotDataset + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + lo, hi = shard_range(len(eps), a.shard, a.nshards) + out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}") + if os.path.exists(os.path.join(out, "DONE")): + print(f"shard {a.shard}: done already", flush=True) + return + shutil.rmtree(out, ignore_errors=True) + ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out, + robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads, + vcodec=a.vcodec) + nfr = 0 + for e in eps[lo:hi]: + d, ann, n = e["dir"], e["ann"], e["n"] + fr = np.load(os.path.join(d, "frames.npz")) + assert len(fr["action"]) == n, d + succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]} + evc = np.zeros(n, np.int64) + for ev in ann["task_events"]: + if 0 <= ev["frame"] < n: + evc[ev["frame"]] += 1 + state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32) + instr = ann["task"]["instruction"] + k = 0 + for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))): + if k >= n: + break + ds.add_frame({ + "observation.images.image": img, "observation.images.wrist_image": wr, + "observation.state": state[k], + "observation.joint_pos": fr["joint_pos"][k].astype(np.float32), + "observation.joint_vel": fr["joint_vel"][k].astype(np.float32), + "observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32), + "observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32), + "action": fr["action"][k].astype(np.float32), + "annotation.attempt_index": np.array([fr["attempt"][k]], np.int64), + "annotation.command_index": np.array([fr["command"][k]], np.int64), + "annotation.phase": np.array([fr["phase"][k]], np.int64), + "annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64), + "annotation.task_event": np.array([evc[k]], np.int64), + "task": instr, + }) + k += 1 + if k != n: + raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames") + ds.save_episode() + nfr += n + ds.finalize() + shutil.rmtree(os.path.join(out, "images"), ignore_errors=True) + open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n") + print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True) + + +def cmd_merge(a): + from pathlib import Path + from lerobot.datasets.aggregate import aggregate_datasets + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + roots, ids = [], [] + for i in range(a.nshards): + lo, hi = shard_range(len(eps), i, a.nshards) + if hi <= lo: + continue + r = os.path.join(a.work, "shards", f"shard_{i:03d}") + if not os.path.exists(os.path.join(r, "DONE")): + raise SystemExit(f"shard {i} is not done") + roots.append(Path(r)) + ids.append(f"{plan['repo_id']}-shard{i:03d}") + if os.path.exists(a.out): + raise SystemExit(f"{a.out} exists; refusing to overwrite") + aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out)) + print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True) + write_sidecars(a, plan) + print(f"merge done in {time.time() - t0:.0f}s", flush=True) + + +def write_sidecars(a, plan): + eps, paper = plan["episodes"], plan["paper"] + lff = os.path.join(a.out, "lff") + for sub in ("annotations", "sim_state", "final", "code"): + os.makedirs(os.path.join(lff, sub), exist_ok=True) + rows, runs, tasks = [], {}, {} + for e in eps: + i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"] + name = f"episode_{i:06d}" + if os.path.exists(os.path.join(d, "sim_state.npy")): + shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy")) + shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz")) + for cam, key in (("agentview", "image"), ("wrist", "wrist_image")): + shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png")) + with open(os.path.join(lff, "annotations", name + ".json"), "w") as f: + json.dump(ann, f, indent=1, ensure_ascii=False) + rows.append(flat_row(i, ann, n, e["from"])) + tname = ann["task"]["name"] + rk = (ann["source"]["batch"], ann["source"]["run"]) + r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"), + run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"], + memory_free_chain_of=ann["source"].get("memory_free_chain_of"), + memory_free_rep=ann["source"].get("memory_free_rep"), task=tname, + seed=ann["task"]["seed"], model=ann["agent"].get("model"), + harness=ann["agent"].get("harness"), + harness_version=ann["agent"].get("harness_version"), + codex_catalog=ann["agent"].get("codex_catalog"), + outcome_class=ann["run_outcome"].get("outcome_class"), + attempt_history=ann["run_outcome"].get("attempt_history"), + agent_final_report=ann["run_outcome"].get("agent_final_report"), + episodes=[])) + for x in ann["attempts"]: + r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success"))) + if tname not in tasks: + tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")} + if tname in paper: + tasks[tname]["paper"] = paper[tname] + tasks[tname]["instances"] = {} + tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"] + # memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id) + by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")} + for r in runs.values(): + if r.get("memory_free_chain_of"): + r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"])) + for (b, rn), r in runs.items(): + r["memory_free_retries"] = sorted((x["run"] for x in runs.values() + if x["batch"] == b and x.get("memory_free_chain_of_run") == rn), + key=lambda q: runs[(b, q)].get("memory_free_rep") or 0) + with open(os.path.join(lff, "episodes.jsonl"), "w") as f: + for row in rows: + f.write(json.dumps(row, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "runs.jsonl"), "w") as f: + for r in runs.values(): + f.write(json.dumps(r, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "tasks.json"), "w") as f: + json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False) + with open(os.path.join(lff, "batches.json"), "w") as f: + json.dump(BATCH_NOTES, f, indent=1) + with open(os.path.join(lff, "rejected.json"), "w") as f: + json.dump(plan["rejected"], f, indent=1) + here = os.path.dirname(os.path.abspath(__file__)) + for s in ("lerobot_replay.py", "lerobot_export.py"): + shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("step", choices=["plan", "shard", "merge"]) + ap.add_argument("--work", required=True) + ap.add_argument("--raw", default="") + ap.add_argument("--runs-root", default="") + ap.add_argument("--out", default="") + ap.add_argument("--paper", default="") + ap.add_argument("--task-set", default="") + ap.add_argument("--repo-id", default="lffbench/agent-replays") + ap.add_argument("--batches", default="") + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--shard", type=int, default=0) + ap.add_argument("--nshards", type=int, default=1) + ap.add_argument("--threads", type=int, default=2) + ap.add_argument("--vcodec", default="libsvtav1") + a = ap.parse_args() + {"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a) + + +if __name__ == "__main__": + main() diff --git a/leaf/code/compound-lh-20261102-clh_20261102_gpt/lerobot_replay.py b/leaf/code/compound-lh-20261102-clh_20261102_gpt/lerobot_replay.py new file mode 100644 index 0000000000000000000000000000000000000000..4c43a69bdb066327b27614bc9efda53d4a74e931 --- /dev/null +++ b/leaf/code/compound-lh-20261102-clh_20261102_gpt/lerobot_replay.py @@ -0,0 +1,744 @@ +"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay +against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the +LeRobot export (scripts/lerobot_export.py). + + python scripts/lerobot_replay.py check [ ...] [--json out.json] # replay only, print fidelity + python scripts/lerobot_replay.py record --out [--res 256] + +Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot +commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite +is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly +like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same +outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width, +ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code +hashes equal the current files are expected to match (check_code()). + +Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB, +proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes: +protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode +per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the +fidelity check runs in record mode too. Per episode the recorder writes ///epNN/: + agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes) + frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase + sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel) + final_*.png, final.npz observation after the last control step (the state the outcome was judged in) + annotation.json episode annotation (build_annotation) +and ///replay.json (fidelity) when the whole run is done. +""" +import argparse +import ast +import hashlib +import importlib +import json +import math +import os +import pkgutil +import re +import shutil +import sys +import time +from collections import defaultdict + +import numpy as np + +LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, LFF_ROOT) + +from lffbench import envs # noqa: E402 +from lffbench import tasks as task_pkg # noqa: E402 +from lffbench.agent import camera as C # noqa: E402 +from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402 +from lffbench.task_base import TASKS # noqa: E402 + +for _m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{_m.name}") + +# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the +# task's outcome() check after `finish` (the arm holds still; not an agent action) +PHASES = {"move": 0, "gripper": 1, "judge": 2} +FPS = 20 +SCHEMA = "lff-replay-1" + +# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR" +ERROR_FLAGS = ("trap_fired", "recovered_in_attempt") +ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events", + "n_missed_strikes", "n_open_gripper_pushes") + + +def load_jsonl(p): + out = [] + if not os.path.exists(p): + return out + with open(p) as f: + for line in f: + line = line.strip() + if line: + try: + out.append(json.loads(line)) + except ValueError: + pass + return out + + +def norm_json(o): + return json.loads(json.dumps(o, default=_json_default)) + + +def sha256(p): + with open(p, "rb") as f: + return hashlib.sha256(f.read()).hexdigest() + + +def check_code(run_dir): + """[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract.""" + p = os.path.join(run_dir, "contract.json") + if not os.path.exists(p): + return [("contract.json", None, None)] + files = json.load(open(p))["contract"].get("server_code_files", {}) + bad = [] + for f, h in files.items(): + q = os.path.join(LFF_ROOT, f) + cur = sha256(q) if os.path.exists(q) else None + if cur != h: + bad.append((f, h, cur)) + return bad + + +def diff_json(a, b, path="", tol=0.0, out=None, limit=20): + """Differences between two JSON values (numbers compared with an absolute tolerance).""" + out = [] if out is None else out + if len(out) >= limit: + return out + if isinstance(a, dict) and isinstance(b, dict): + for k in sorted(set(a) | set(b)): + if k not in a or k not in b: + out.append((f"{path}.{k}", a.get(k, ""), b.get(k, ""))) + else: + diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit) + elif isinstance(a, list) and isinstance(b, list): + if len(a) != len(b): + out.append((path, f"len {len(a)}", f"len {len(b)}")) + else: + for i, (x, y) in enumerate(zip(a, b)): + diff_json(x, y, f"{path}[{i}]", tol, out, limit) + elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))): + if a != b: + out.append((path, a, b)) + elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))): + out.append((path, a, b)) + return out + + +def error_event(o): + """True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none.""" + if not isinstance(o, dict): + return None + keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o] + if not keys: + return None + return any(bool(o[k]) for k in ERROR_FLAGS if k in o) or any((o.get(k) or 0) > 0 for k in ERROR_COUNTS if k in o) + + +# ====================================================================================================== logs -> notes + +class RunLog: + """Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's + narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition.""" + + def __init__(self, run_dir, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run = os.path.basename(self.run_dir) + self.batch = os.path.basename(os.path.dirname(self.run_dir)) + self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl")) + self.start = next(e for e in self.ev if e["ev"] == "session_start") + self.calls, self.dones, self.harness_status = {}, [], [] + last = None + for e in self.ev: + if e["ev"] == "call": + self.calls[(int(e["attempt"]), int(e["step"]))] = e + last = e + elif e["ev"] == "done": + self.dones.append(e) + last = e + elif e["ev"] == "http" and last is not None and "think_s" not in last: + ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \ + (last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe")) + if ok: + last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s") + self.manifest = manifest or {} + self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {} + p = os.path.join(self.run_dir, "harness.json") + self.harness = json.load(open(p)) if os.path.exists(p) else {} + self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl")) + self._narration() + + # ---------------------------------------------------------------- agent narration + def _narration(self): + """notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one; + finish_notes[attempt] likewise for the agent's finish call; final_report = its last message.""" + self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", [] + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + attempt = 1 + + def take(): + nonlocal buf + out = {k: v for k, v in buf.items() if v} + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + return out + + last_msg = "" + for t in self.traj: + if t.get("kind") == "header": + self.headers.append(t.get("agent") or {}) + continue + if t.get("kind") != "step": + continue + if (t.get("message") or "").strip(): + buf["messages"].append(t["message"].strip()) + last_msg = t["message"].strip() + if (t.get("reasoning_content") or "").strip(): + buf["reasoning"].append(t["reasoning_content"].strip()) + res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])} + for c in t.get("tool_calls") or []: + fn, args = c.get("function_name"), c.get("arguments") or {} + if fn == "shell": + buf["shell"].append(str(args.get("command", ""))[:2000]) + elif fn == "view_images": + buf["viewed"].extend(args.get("paths") or []) + elif fn == "robot": + cmd = str(args.get("command", "")).strip() + r = res.get(c.get("tool_call_id")) or {} + try: + rep = json.loads(r.get("content") or "{}") + except ValueError: + rep = {} + word = cmd.split()[0] if cmd else "" + m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", ""))) + if word in ("move_eef", "observe") and m: + a, s = int(m.group(1)), int(m.group(2)) + n = take() + n["command"] = cmd + self.notes[(a, s)] = n + attempt = a + elif word in ("finish", "done"): + n = take() + n["command"] = cmd + n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)} + self.finish_notes.setdefault(attempt, n) + if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"): + attempt += 1 + # status / help / errors: their narration stays in the buffer for the next command + self.final_report = last_msg + + # ---------------------------------------------------------------- run-level labels + def attempts(self): + out = [] + for e in self.dones: + o = e.get("outcome") or {} + if isinstance(o, str): + try: + o = ast.literal_eval(o) + except (ValueError, SyntaxError): + o = {} + out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o, + reason=e.get("reason") or "")) + return sorted(out, key=lambda x: x["attempt"]) + + def condition(self): + s, en = self.start, self.entry + mem = s.get("memory", en.get("mem")) + chain = en.get("chain") + if mem == "full": + cond = "with_history" + elif chain: + cond = "memory_free_retry" + else: + cond = "independent_single_attempt" + return cond, chain + + def outcome_class(self): + """CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None.""" + att = self.attempts() + if not att or self.start.get("memory") != "full": + return None, "".join("S" if a["success"] else "F" for a in att) + hist = "".join("S" if a["success"] else "F" for a in att) + if att[0]["success"]: + ev = error_event(att[0]["outcome"]) + cls = "S?" if ev is None else ("IR" if ev else "CS") + else: + cls = "XR" if any(a["success"] for a in att) else "F" + return cls, hist + + def agent_info(self): + h, en = self.harness, self.entry + hdr = self.headers[0] if self.headers else {} + return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"), + harness_version=h.get("version") or hdr.get("version"), + harness_binary_sha256=(h.get("binary") or {}).get("sha256"), + model=h.get("model") or en.get("model") or hdr.get("model_name"), + effort=h.get("effort") or en.get("effort") or hdr.get("effort"), + provider=h.get("provider") or en.get("provider"), + codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"), + jail=en.get("jail")) + + +# ====================================================================================================== recording + +class EpisodeSink: + """Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed.""" + + def __init__(self, path): + self.path = path + os.makedirs(path, exist_ok=True) + self.w = None + self.num = defaultdict(list) + self.n = 0 + + def add(self, st, imgs): + import imageio + if self.w is None: + self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb", + pixelformat="rgb24", macro_block_size=1, + ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error") + for k in ("agentview", "wrist")] + for w, im in zip(self.w, imgs): + w.append_data(im) + for k, v in st.items(): + self.num[k].append(v) + self.n += 1 + + def close(self, final_state, final_imgs): + from PIL import Image + if self.w is not None: + for w in self.w: + w.close() + arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"} + np.savez(os.path.join(self.path, "frames.npz"), **arr) + if self.num.get("sim_state"): + np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64)) + np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()}) + for k, im in zip(("agentview", "wrist"), final_imgs): + Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png")) + + +class Recorder: + """Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink.""" + + def __init__(self, rp, res): + self.rp, self.res = rp, int(res) + self.active = False + self.sink = None + self.cur = dict(attempt=1, command=-1, phase=PHASES["move"]) + env = rp.task.env + self.env, self.rob = env, env.robots[0] + self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist")) + orig = env.step + + def step(a): + if self.active and self.sink is not None: + self.capture(np.asarray(a, np.float64)) + out = orig(a) + if self.active and self.sink is not None: + self.rp.poll_events(self.sink.n - 1) + return out + + env.step = step + + @property + def n(self): + return self.sink.n if self.sink is not None else 0 + + def state(self): + import robosuite.utils.transform_utils as T + env, rob = self.env, self.rob + d = env.sim.data + eef = np.array(d.site_xpos[rob.eef_site_id], np.float64) + q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw") + gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64) + try: + flat = np.asarray(env.sim.get_state().flatten(), np.float64) + except Exception: + flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64) + sk = self.rp.task.sk + return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64), + gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64), + joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64), + gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64), + eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)), + sim_time=np.float64(d.time), sim_state=flat) + + def images(self): + return [envs.render(self.env, c, self.res) for c in self.cams] + + def capture(self, a): + st = self.state() + st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]), + phase=np.int64(self.cur["phase"])) + self.sink.add(st, self.images()) + + +class RunReplay: + def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run_name = os.path.basename(self.run_dir) + self.log = RunLog(self.run_dir, manifest) + self.ev = self.log.ev + self.start = self.log.start + cp = os.path.join(self.run_dir, "contract.json") + self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {} + spec = self.contract.get("image_spec") or {} + self.image_res = int(spec.get("width", 512)) + self.code_diff = check_code(self.run_dir) + s = self.start + self.task = TASKS[s["task"]](cam_res=self.image_res) + inst = self.task.sample_instance(s["seed"]) + logged = s.get("inst") or {} + sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")}) + self.inst_diff = diff_json(sampled, logged, "inst") + if s.get("arm", "none") not in (None, "none") or logged.get("nominal"): + inst.update(logged) # controlled arms / nominal: the server overrode these instance fields + self.inst_diff = [] + self.inst = inst + self.protocol = getattr(self.task, "protocol", "cross") + self.k = int(s.get("k") or self.task.max_attempts) + self.attempt = 1 + self.mismatch = [] # (where, what, logged, replayed) + self.n_checked = 0 + self.max_dev_m = 0.0 + self.unfinished = None + self.rec = Recorder(self, res) if record else None + self.res = int(res) + self.out_root = out_root + self.n_mon = 0 + self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0 + self.episodes = [] # summaries of the written episodes + self.task.reset_instance(self.inst) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + sim = self.task.env.sim + bid = sim.model.body_name2id("robot0_base") + self.base_off = np.array(sim.data.body_xpos[bid], float).copy() + if self.rec: + self._open_episode() + + # ------------------------------------------------------------------ episodes + def _ep_dir(self): + return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}") + + def _open_episode(self): + self.rec.sink = EpisodeSink(self._ep_dir()) + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.rec.active = True + self.events, self.spans, self.ep_attempts = [], [], [] + self.ep_initial = self.rec.state() # state right after the reset (before frame 0) + + def close_episode(self): + if not self.rec: + self.ep_attempts = [] + return + sink = self.rec.sink + st = self.rec.state() + imgs = self.rec.images() + st.pop("sim_state", None) + sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs) + ann = build_annotation(self, sink) + with open(os.path.join(sink.path, "annotation.json"), "w") as f: + json.dump(ann, f, indent=1, default=_json_default) + self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n, + attempts=[a["attempt"] for a in self.ep_attempts])) + self.rec.active = False + self.rec.sink = None + self.ep_index += 1 + + # ------------------------------------------------------------------ monitor events (task-side error events) + def poll_events(self, frame): + mon = getattr(self.task, "mon", None) + evs = mon.get("events") if isinstance(mon, dict) else None + if not isinstance(evs, list): + return + if len(evs) < self.n_mon: # monitor was rebuilt + self.n_mon = 0 + for e in evs[self.n_mon:]: + self.events.append(dict(frame=int(frame), attempt=self.attempt, + event=norm_json(e) if isinstance(e, dict) else str(e))) + self.n_mon = len(evs) + + # ------------------------------------------------------------------ state as the server reports it + def proprio_la(self): + p = self.ex.proprio() + pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off] + return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"]) + + def compare(self, where, rep_logged, rep): + self.n_checked += 1 + for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"): + if k not in rep_logged or k not in rep: + continue + a, b = rep_logged[k], rep[k] + if k == "eef_pos": + dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float)))) + self.max_dev_m = max(self.max_dev_m, dev) + if dev > 1.5e-4: + self.mismatch.append((where, k, a, b)) + elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4): + self.mismatch.append((where, k, a, b)) + if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)): + self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok"))) + + def _span(self, e, f0, kind): + if self.rec: + self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0, + frame_end=self.rec.n)) + + # ------------------------------------------------------------------ commands (robot_server._handle_v2) + def move_eef(self, e): + args = e.get("args") or {} + where = f"a{e['attempt']}s{e['step']}" + logged = e.get("report") or {} + f0 = self.rec.n if self.rec else 0 + p = self.ex.proprio() + if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}: + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + off = self.base_off + try: + cur = np.asarray(p["eef_pos"], float) - off + tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")] + yaw = float(args.get("yaw", p["eef_yaw_deg"])) + speed = None if args.get("speed") in (None, "") else float(args["speed"]) + except (TypeError, ValueError): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + grip = args.get("gripper") + if grip not in (None, "open", "close"): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + moving = any(k in args for k in ("x", "y", "z", "yaw")) + tgt_w = np.asarray(tgt) + off + if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)): + self._span(e, f0, "rejected") + return self.compare(where, logged, dict(ok=False, **self.proprio_la())) + raw = {} + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"]) + if moving: + mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw) + if speed is not None: + mv["speed"] = speed + raw.update(self.ex.call("move_to", mv).report) + if grip is not None: + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"]) + raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report) + rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la()) + self.compare(where, logged, rep) + lr = e.get("raw") or {} + for k in ("holding_object", "touched_object"): + if k in lr and k in raw and bool(lr[k]) != bool(raw[k]): + self.mismatch.append((where, "raw." + k, lr[k], raw[k])) + self._span(e, f0, "move_eef") + + def observe(self, e): + f0 = self.rec.n if self.rec else 0 + self._span(e, f0, "observe") + + def done(self, e): + f0 = self.rec.n if self.rec else 0 + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"]) + out = self.task.outcome(self.inst) + succ = bool(out["success"]) + where = f"a{e['attempt']}done" + if succ != bool(e.get("success") in (True, "True")): + self.mismatch.append((where, "success", e.get("success"), succ)) + lo = e.get("outcome") or {} + ro = norm_json({k: v for k, v in out.items() if k != "feedback"}) + if isinstance(lo, dict): + for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8): + self.mismatch.append((where,) + d) + info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""), + feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")), + think_s=e.get("think_s")) + try: + info["feedback_f2"] = self.task.feedback(self.inst, out, "F2") + except Exception as ex_: + info["feedback_f2"] = f"" + if self.rec: + info["judge_frames"] = [f0, self.rec.n] + self.ep_attempts.append(info) + last = self.attempt >= self.k or succ or bool(out.get("terminal")) + if self.protocol == "cross" or last: + self.close_episode() + if last: + return True + self.attempt += 1 + if self.protocol == "cross": + self.task.reset_instance(self.inst) + self.n_mon = 0 + if self.rec: + self._open_episode() + elif self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + return False + + def run(self): + t0 = time.time() + finished = False + for e in self.ev: + if e["ev"] == "call": + if e.get("cmd") == "move_eef": + self.move_eef(e) + elif e.get("cmd") == "observe": + self.observe(e) + else: + self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None)) + elif e["ev"] == "done": + finished = self.done(e) + if finished: + break + self.unfinished = not finished + if not finished and self.rec and self.rec.sink is not None: + # the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged + if self.rec.n or self.ep_attempts: + self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True, + finish_reason="", feedback_shown="", auto_ended=False)) + self.close_episode() + else: + shutil.rmtree(self.rec.sink.path, ignore_errors=True) + self.rec.sink = None + self.wall_s = time.time() - t0 + return self + + def summary(self): + return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"], + protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff), + n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6), + unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1), + first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]]) + + +# ====================================================================================================== annotation + +def task_info(task, inst): + cls = type(task) + return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable", + category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"), + max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)), + instruction=cls.instruction) + + +def build_annotation(rp, sink): + """Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2 + failure description), run-level outcome class, every robot command with its frame span and the agent's narration, + task-side error events with frame indices.""" + log = rp.log + s = rp.start + cond, chain = log.condition() + cls, hist = log.outcome_class() + att_all = log.attempts() + attempts = [] + for a in rp.ep_attempts: + a = dict(a) + n = a["attempt"] + later = [x for x in att_all if x["attempt"] > n] + a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later)) + a["is_last_attempt_of_run"] = not later + fn = log.finish_notes.get(n) + if fn: + a["agent_finish"] = fn + a["error_event_in_attempt"] = error_event(a.get("outcome")) + attempts.append(a) + # post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command) + for a in attempts: + nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1]) + if a.get("success") is False and nxt: + note = log.notes[nxt[0]] + a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note} + commands = [] + for sp in rp.spans: + e = log.calls.get((sp["attempt"], sp["step"])) or {} + rep = e.get("report") or {} + c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"], + frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]), + args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"), + stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"), + gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"), + touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"), + agent_obs_images=rep.get("images")) + note = log.notes.get((sp["attempt"], sp["step"])) + if note: + c["agent_note"] = {k: v for k, v in note.items() if k != "command"} + commands.append(c) + t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x] + return dict( + schema=SCHEMA, + source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts], + episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain, + memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None), + feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"), + k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"), + contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256") + if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)), + agent=log.agent_info(), + task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"), + instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}), + run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all), + run_success=any(x["success"] for x in att_all) if att_all else None, + agent_final_report=log.final_report[:6000] or None, + mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)), + attempts=attempts, + commands=commands, + task_events=rp.events, + frames=dict(n=sink.n, fps=FPS, image_res=rp.res, + phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"], + joint_pos=rp.ep_initial["joint_pos"], + gripper_qpos=rp.ep_initial["gripper_qpos"])), + ) + + +# ====================================================================================================== CLI + +def load_manifest(run_dir): + p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json") + return json.load(open(p)) if os.path.exists(p) else {} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("mode", choices=["check", "record"]) + ap.add_argument("runs", nargs="+") + ap.add_argument("--json", default="") + ap.add_argument("--out", default="") + ap.add_argument("--res", type=int, default=256) + ap.add_argument("--force", action="store_true", help="record again even if replay.json exists") + a = ap.parse_args() + rows = [] + for r in a.runs: + r = r.rstrip("/") + try: + if a.mode == "check": + s = RunReplay(r, manifest=load_manifest(r)).run().summary() + else: + batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r) + rd = os.path.join(a.out, batch, name) + if os.path.exists(os.path.join(rd, "replay.json")) and not a.force: + print(json.dumps(dict(run=name, skipped="exists")), flush=True) + continue + shutil.rmtree(rd, ignore_errors=True) + rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run() + s = rp.summary() + s["episodes"] = rp.episodes + with open(os.path.join(rd, "replay.json"), "w") as f: + json.dump(s, f, indent=1) + except Exception: + import traceback + s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:]) + rows.append(s) + print(json.dumps(s), flush=True) + if a.json: + with open(a.json, "w") as f: + json.dump(rows, f, indent=1) + + +if __name__ == "__main__": + main() diff --git a/leaf/code/compound-lh-20261102-clh_20261102_sonnet/lerobot_export.py b/leaf/code/compound-lh-20261102-clh_20261102_sonnet/lerobot_export.py new file mode 100644 index 0000000000000000000000000000000000000000..fa4fa0a1be92844c9cf410663f77de5e200bda18 --- /dev/null +++ b/leaf/code/compound-lh-20261102-clh_20261102_sonnet/lerobot_export.py @@ -0,0 +1,431 @@ +"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars. + +Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding +can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan): + + python scripts/lerobot_export.py plan --raw [,] --runs-root /runs/api \ + --paper --task-set /sets/main_v2_1inst.txt --work [--batches ...] [--limit N] + python scripts/lerobot_export.py shard --work --shard i --nshards N + python scripts/lerobot_export.py merge --work --nshards N --out + +Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0 +mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped. + +LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t): + observation.images.image agentview RGB 256x256 (upright; LIBERO naming) + observation.images.wrist_image wrist (eye-in-hand) RGB 256x256 + observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout) + observation.joint_pos / joint_vel 7 arm joints (rad, rad/s) + observation.eef_quat 4: xyzw; observation.gripper_width 1 (m) + action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad), + gripper (-1 open, +1 close) + annotation.attempt_index attempt (1-based) the frame belongs to + annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`) + annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action) + annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt + annotation.task_event number of task-monitor events (error / progress events) registered at this step +Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table), +runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state +per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/. +""" +import argparse +import glob +import json +import os +import re +import shutil +import time + +import numpy as np + +FPS = 20 +RES = 256 +BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke", + "cc_smoke", "cc_opus_smoke"] +BATCH_NOTES = { + "cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog", + "cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267", + "cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299", + "cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances", + "cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)", + "cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the " + "with-history continuation of failed runs is incomplete", + "cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early", + "cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt", + "cc_opus_smoke": "smoke test: single attempt", +} +PHASES = {"move": 0, "gripper": 1, "judge": 2} +CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)", + "L2": "disturbed state to restore (incl. damage the agent causes)", + "L3": "infeasible manipulation strategy (grasp / contact / tool must change)", + "L4": "misjudged geometry (size, shape, fit, hidden structure)", + "L5": "misjudged physics (mass distribution, friction, dynamics)"} + + +def features(): + vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]} + f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names} + i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None} + return { + "observation.images.image": vid(), + "observation.images.wrist_image": vid(), + "observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z", + "finger_qpos_left", "finger_qpos_right"]), + "observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]), + "observation.gripper_width": f32(1, ["width_m"]), + "action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y", + "eef_delta_rot_aa_z", "gripper_close"]), + "annotation.attempt_index": i64(), + "annotation.command_index": i64(), + "annotation.phase": i64(), + "annotation.attempt_success": i64(), + "annotation.task_event": i64(), + } + + +# ------------------------------------------------------------------------------------------------ paper metadata + +def _clean_tex(s): + s = re.sub(r"%.*", "", s) + for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"), + (r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"), + (r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"), + (r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"), + (r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]: + s = re.sub(a, b, s) + s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s) + s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s) + for _ in range(3): + s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\$([^$]*)\$", r"\1", s) + s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ") + s = re.sub(r"\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\\[a-zA-Z]+\*?", "", s) + return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip() + + +def paper_tasks(paper_dir): + """{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the + paper's task table and task appendix (empty if the paper sources are not there).""" + out = {} + if not paper_dir: + return out + app = os.path.join(paper_dir, "sections", "appendix_tasks.tex") + tab = os.path.join(paper_dir, "sections", "tab_tasks.tex") + if os.path.exists(app): + txt = open(app).read() + parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt) + for i in range(1, len(parts) - 1, 2): + if parts[i] != "\\paragraph{": + continue + body = parts[i + 1] + m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S) + if not m: + continue + name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip() + desc = _clean_tex(body[m.end():]) + out[code] = dict(name=name, cause=_clean_tex(cause), description=desc) + if os.path.exists(tab): + names = {v["name"].lower(): k for k, v in out.items()} + for line in open(tab): + cells = [c.strip() for c in line.split("&")] + if len(cells) != 6 or not cells[-1].endswith("\\\\"): + continue + nm = re.sub(r"\\contscene", "", cells[0]).strip().lower() + code = names.get(nm) + if not code: + continue + out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]), + repair_within_attempt=_clean_tex(cells[3]) == "yes", + oracle_first_attempt_pct=_clean_tex(cells[4]), + naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip())) + return out + + +# ------------------------------------------------------------------------------------------------ collection + +def manifest_status(runs_root, batch, run, cache={}): + if batch not in cache: + p = os.path.join(runs_root, batch, "manifest.json") + cache[batch] = json.load(open(p)) if os.path.exists(p) else {} + m = cache[batch] + for r in m.get("runs", []): + if r.get("run") == run: + return r.get("status", "?"), r + for r in m.get("superseded", []): + if r.get("run") == run: + return "superseded_" + str(r.get("status", "?")), r + return "not_in_manifest", {} + + +def collect(raw_roots, runs_root, batches, task_order): + """Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root.""" + eps, rejected, seen = [], [], set() + for root in raw_roots: + for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))): + rep = json.load(open(rj)) + batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"] + if (batches and batch not in batches) or (batch, run) in seen: + continue + seen.add((batch, run)) + ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff") + status, entry = manifest_status(runs_root, batch, run) + if not ok: + never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked") + rejected.append(dict(run=run, batch=batch, run_status=status, + reason="run never started (no contract, no robot command)" if never else + "replay does not reproduce the log (the log has gaps or the replay diverged)", + detail=rep.get("first_mismatches"))) + continue + for ep in rep.get("episodes", []): + d = os.path.join(root, ep["dir"]) + ann = json.load(open(os.path.join(d, "annotation.json"))) + judged = [a for a in ann["attempts"] if a.get("success") is not None] + if not judged or ep["n_frames"] == 0: + rejected.append(dict(run=run, batch=batch, episode=ep["dir"], + reason="no judged attempt" if not judged else "no frames")) + continue + ann["source"]["run_status"] = status + ann["source"]["manifest_id"] = entry.get("id") + ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"], + max_eef_dev_m=rep["max_eef_dev_m"]) + key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99), + {"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2), + ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"]) + eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann)) + eps.sort(key=lambda x: x["key"]) + return eps, rejected + + +# ------------------------------------------------------------------------------------------------ writing + +def frames_of(path): + import av + with av.open(path) as c: + for fr in c.decode(video=0): + yield fr.to_ndarray(format="rgb24") + + +def flat_row(i, ann, n, idx0): + s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"] + att = ann["attempts"] + a0 = att[0] + return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n, + batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"], + memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"), + episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att], + harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"), + effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"), + task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"), + category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"], + success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att], + feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att], + auto_ended=[a.get("auto_ended") for a in att], + corrected_later_in_run=[a.get("corrected_later_in_run") for a in att], + error_event_in_attempt=[a.get("error_event_in_attempt") for a in att], + run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"), + n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]), + first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None) + + +def cmd_plan(a): + task_order = {} + if a.task_set and os.path.exists(a.task_set): + for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")): + task_order[line.split(":")[0].strip()] = i + batches = [b for b in a.batches.split(",") if b] if a.batches else None + eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order) + if a.limit: + eps = eps[:a.limit] + paper = paper_tasks(a.paper) + idx0 = 0 + for i, e in enumerate(eps): + ann = e["ann"] + tname = ann["task"]["name"] + if tname in paper: + ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"} + ann["episode_index"] = i + ann["dataset_index_range"] = [idx0, idx0 + e["n"]] + e["index"], e["from"] = i, idx0 + idx0 += e["n"] + del e["key"] + os.makedirs(a.work, exist_ok=True) + with open(os.path.join(a.work, "plan.json"), "w") as f: + json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f, + ensure_ascii=False) + print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True) + + +def shard_range(n_eps, i, k): + return (n_eps * i) // k, (n_eps * (i + 1)) // k + + +def cmd_shard(a): + from lerobot.datasets.lerobot_dataset import LeRobotDataset + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + lo, hi = shard_range(len(eps), a.shard, a.nshards) + out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}") + if os.path.exists(os.path.join(out, "DONE")): + print(f"shard {a.shard}: done already", flush=True) + return + shutil.rmtree(out, ignore_errors=True) + ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out, + robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads, + vcodec=a.vcodec) + nfr = 0 + for e in eps[lo:hi]: + d, ann, n = e["dir"], e["ann"], e["n"] + fr = np.load(os.path.join(d, "frames.npz")) + assert len(fr["action"]) == n, d + succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]} + evc = np.zeros(n, np.int64) + for ev in ann["task_events"]: + if 0 <= ev["frame"] < n: + evc[ev["frame"]] += 1 + state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32) + instr = ann["task"]["instruction"] + k = 0 + for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))): + if k >= n: + break + ds.add_frame({ + "observation.images.image": img, "observation.images.wrist_image": wr, + "observation.state": state[k], + "observation.joint_pos": fr["joint_pos"][k].astype(np.float32), + "observation.joint_vel": fr["joint_vel"][k].astype(np.float32), + "observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32), + "observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32), + "action": fr["action"][k].astype(np.float32), + "annotation.attempt_index": np.array([fr["attempt"][k]], np.int64), + "annotation.command_index": np.array([fr["command"][k]], np.int64), + "annotation.phase": np.array([fr["phase"][k]], np.int64), + "annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64), + "annotation.task_event": np.array([evc[k]], np.int64), + "task": instr, + }) + k += 1 + if k != n: + raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames") + ds.save_episode() + nfr += n + ds.finalize() + shutil.rmtree(os.path.join(out, "images"), ignore_errors=True) + open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n") + print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True) + + +def cmd_merge(a): + from pathlib import Path + from lerobot.datasets.aggregate import aggregate_datasets + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + roots, ids = [], [] + for i in range(a.nshards): + lo, hi = shard_range(len(eps), i, a.nshards) + if hi <= lo: + continue + r = os.path.join(a.work, "shards", f"shard_{i:03d}") + if not os.path.exists(os.path.join(r, "DONE")): + raise SystemExit(f"shard {i} is not done") + roots.append(Path(r)) + ids.append(f"{plan['repo_id']}-shard{i:03d}") + if os.path.exists(a.out): + raise SystemExit(f"{a.out} exists; refusing to overwrite") + aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out)) + print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True) + write_sidecars(a, plan) + print(f"merge done in {time.time() - t0:.0f}s", flush=True) + + +def write_sidecars(a, plan): + eps, paper = plan["episodes"], plan["paper"] + lff = os.path.join(a.out, "lff") + for sub in ("annotations", "sim_state", "final", "code"): + os.makedirs(os.path.join(lff, sub), exist_ok=True) + rows, runs, tasks = [], {}, {} + for e in eps: + i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"] + name = f"episode_{i:06d}" + if os.path.exists(os.path.join(d, "sim_state.npy")): + shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy")) + shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz")) + for cam, key in (("agentview", "image"), ("wrist", "wrist_image")): + shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png")) + with open(os.path.join(lff, "annotations", name + ".json"), "w") as f: + json.dump(ann, f, indent=1, ensure_ascii=False) + rows.append(flat_row(i, ann, n, e["from"])) + tname = ann["task"]["name"] + rk = (ann["source"]["batch"], ann["source"]["run"]) + r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"), + run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"], + memory_free_chain_of=ann["source"].get("memory_free_chain_of"), + memory_free_rep=ann["source"].get("memory_free_rep"), task=tname, + seed=ann["task"]["seed"], model=ann["agent"].get("model"), + harness=ann["agent"].get("harness"), + harness_version=ann["agent"].get("harness_version"), + codex_catalog=ann["agent"].get("codex_catalog"), + outcome_class=ann["run_outcome"].get("outcome_class"), + attempt_history=ann["run_outcome"].get("attempt_history"), + agent_final_report=ann["run_outcome"].get("agent_final_report"), + episodes=[])) + for x in ann["attempts"]: + r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success"))) + if tname not in tasks: + tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")} + if tname in paper: + tasks[tname]["paper"] = paper[tname] + tasks[tname]["instances"] = {} + tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"] + # memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id) + by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")} + for r in runs.values(): + if r.get("memory_free_chain_of"): + r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"])) + for (b, rn), r in runs.items(): + r["memory_free_retries"] = sorted((x["run"] for x in runs.values() + if x["batch"] == b and x.get("memory_free_chain_of_run") == rn), + key=lambda q: runs[(b, q)].get("memory_free_rep") or 0) + with open(os.path.join(lff, "episodes.jsonl"), "w") as f: + for row in rows: + f.write(json.dumps(row, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "runs.jsonl"), "w") as f: + for r in runs.values(): + f.write(json.dumps(r, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "tasks.json"), "w") as f: + json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False) + with open(os.path.join(lff, "batches.json"), "w") as f: + json.dump(BATCH_NOTES, f, indent=1) + with open(os.path.join(lff, "rejected.json"), "w") as f: + json.dump(plan["rejected"], f, indent=1) + here = os.path.dirname(os.path.abspath(__file__)) + for s in ("lerobot_replay.py", "lerobot_export.py"): + shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("step", choices=["plan", "shard", "merge"]) + ap.add_argument("--work", required=True) + ap.add_argument("--raw", default="") + ap.add_argument("--runs-root", default="") + ap.add_argument("--out", default="") + ap.add_argument("--paper", default="") + ap.add_argument("--task-set", default="") + ap.add_argument("--repo-id", default="lffbench/agent-replays") + ap.add_argument("--batches", default="") + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--shard", type=int, default=0) + ap.add_argument("--nshards", type=int, default=1) + ap.add_argument("--threads", type=int, default=2) + ap.add_argument("--vcodec", default="libsvtav1") + a = ap.parse_args() + {"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a) + + +if __name__ == "__main__": + main() diff --git a/leaf/code/compound-lh-20261102-clh_20261102_sonnet/lerobot_replay.py b/leaf/code/compound-lh-20261102-clh_20261102_sonnet/lerobot_replay.py new file mode 100644 index 0000000000000000000000000000000000000000..4c43a69bdb066327b27614bc9efda53d4a74e931 --- /dev/null +++ b/leaf/code/compound-lh-20261102-clh_20261102_sonnet/lerobot_replay.py @@ -0,0 +1,744 @@ +"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay +against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the +LeRobot export (scripts/lerobot_export.py). + + python scripts/lerobot_replay.py check [ ...] [--json out.json] # replay only, print fidelity + python scripts/lerobot_replay.py record --out [--res 256] + +Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot +commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite +is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly +like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same +outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width, +ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code +hashes equal the current files are expected to match (check_code()). + +Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB, +proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes: +protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode +per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the +fidelity check runs in record mode too. Per episode the recorder writes ///epNN/: + agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes) + frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase + sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel) + final_*.png, final.npz observation after the last control step (the state the outcome was judged in) + annotation.json episode annotation (build_annotation) +and ///replay.json (fidelity) when the whole run is done. +""" +import argparse +import ast +import hashlib +import importlib +import json +import math +import os +import pkgutil +import re +import shutil +import sys +import time +from collections import defaultdict + +import numpy as np + +LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, LFF_ROOT) + +from lffbench import envs # noqa: E402 +from lffbench import tasks as task_pkg # noqa: E402 +from lffbench.agent import camera as C # noqa: E402 +from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402 +from lffbench.task_base import TASKS # noqa: E402 + +for _m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{_m.name}") + +# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the +# task's outcome() check after `finish` (the arm holds still; not an agent action) +PHASES = {"move": 0, "gripper": 1, "judge": 2} +FPS = 20 +SCHEMA = "lff-replay-1" + +# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR" +ERROR_FLAGS = ("trap_fired", "recovered_in_attempt") +ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events", + "n_missed_strikes", "n_open_gripper_pushes") + + +def load_jsonl(p): + out = [] + if not os.path.exists(p): + return out + with open(p) as f: + for line in f: + line = line.strip() + if line: + try: + out.append(json.loads(line)) + except ValueError: + pass + return out + + +def norm_json(o): + return json.loads(json.dumps(o, default=_json_default)) + + +def sha256(p): + with open(p, "rb") as f: + return hashlib.sha256(f.read()).hexdigest() + + +def check_code(run_dir): + """[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract.""" + p = os.path.join(run_dir, "contract.json") + if not os.path.exists(p): + return [("contract.json", None, None)] + files = json.load(open(p))["contract"].get("server_code_files", {}) + bad = [] + for f, h in files.items(): + q = os.path.join(LFF_ROOT, f) + cur = sha256(q) if os.path.exists(q) else None + if cur != h: + bad.append((f, h, cur)) + return bad + + +def diff_json(a, b, path="", tol=0.0, out=None, limit=20): + """Differences between two JSON values (numbers compared with an absolute tolerance).""" + out = [] if out is None else out + if len(out) >= limit: + return out + if isinstance(a, dict) and isinstance(b, dict): + for k in sorted(set(a) | set(b)): + if k not in a or k not in b: + out.append((f"{path}.{k}", a.get(k, ""), b.get(k, ""))) + else: + diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit) + elif isinstance(a, list) and isinstance(b, list): + if len(a) != len(b): + out.append((path, f"len {len(a)}", f"len {len(b)}")) + else: + for i, (x, y) in enumerate(zip(a, b)): + diff_json(x, y, f"{path}[{i}]", tol, out, limit) + elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))): + if a != b: + out.append((path, a, b)) + elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))): + out.append((path, a, b)) + return out + + +def error_event(o): + """True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none.""" + if not isinstance(o, dict): + return None + keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o] + if not keys: + return None + return any(bool(o[k]) for k in ERROR_FLAGS if k in o) or any((o.get(k) or 0) > 0 for k in ERROR_COUNTS if k in o) + + +# ====================================================================================================== logs -> notes + +class RunLog: + """Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's + narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition.""" + + def __init__(self, run_dir, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run = os.path.basename(self.run_dir) + self.batch = os.path.basename(os.path.dirname(self.run_dir)) + self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl")) + self.start = next(e for e in self.ev if e["ev"] == "session_start") + self.calls, self.dones, self.harness_status = {}, [], [] + last = None + for e in self.ev: + if e["ev"] == "call": + self.calls[(int(e["attempt"]), int(e["step"]))] = e + last = e + elif e["ev"] == "done": + self.dones.append(e) + last = e + elif e["ev"] == "http" and last is not None and "think_s" not in last: + ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \ + (last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe")) + if ok: + last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s") + self.manifest = manifest or {} + self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {} + p = os.path.join(self.run_dir, "harness.json") + self.harness = json.load(open(p)) if os.path.exists(p) else {} + self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl")) + self._narration() + + # ---------------------------------------------------------------- agent narration + def _narration(self): + """notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one; + finish_notes[attempt] likewise for the agent's finish call; final_report = its last message.""" + self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", [] + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + attempt = 1 + + def take(): + nonlocal buf + out = {k: v for k, v in buf.items() if v} + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + return out + + last_msg = "" + for t in self.traj: + if t.get("kind") == "header": + self.headers.append(t.get("agent") or {}) + continue + if t.get("kind") != "step": + continue + if (t.get("message") or "").strip(): + buf["messages"].append(t["message"].strip()) + last_msg = t["message"].strip() + if (t.get("reasoning_content") or "").strip(): + buf["reasoning"].append(t["reasoning_content"].strip()) + res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])} + for c in t.get("tool_calls") or []: + fn, args = c.get("function_name"), c.get("arguments") or {} + if fn == "shell": + buf["shell"].append(str(args.get("command", ""))[:2000]) + elif fn == "view_images": + buf["viewed"].extend(args.get("paths") or []) + elif fn == "robot": + cmd = str(args.get("command", "")).strip() + r = res.get(c.get("tool_call_id")) or {} + try: + rep = json.loads(r.get("content") or "{}") + except ValueError: + rep = {} + word = cmd.split()[0] if cmd else "" + m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", ""))) + if word in ("move_eef", "observe") and m: + a, s = int(m.group(1)), int(m.group(2)) + n = take() + n["command"] = cmd + self.notes[(a, s)] = n + attempt = a + elif word in ("finish", "done"): + n = take() + n["command"] = cmd + n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)} + self.finish_notes.setdefault(attempt, n) + if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"): + attempt += 1 + # status / help / errors: their narration stays in the buffer for the next command + self.final_report = last_msg + + # ---------------------------------------------------------------- run-level labels + def attempts(self): + out = [] + for e in self.dones: + o = e.get("outcome") or {} + if isinstance(o, str): + try: + o = ast.literal_eval(o) + except (ValueError, SyntaxError): + o = {} + out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o, + reason=e.get("reason") or "")) + return sorted(out, key=lambda x: x["attempt"]) + + def condition(self): + s, en = self.start, self.entry + mem = s.get("memory", en.get("mem")) + chain = en.get("chain") + if mem == "full": + cond = "with_history" + elif chain: + cond = "memory_free_retry" + else: + cond = "independent_single_attempt" + return cond, chain + + def outcome_class(self): + """CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None.""" + att = self.attempts() + if not att or self.start.get("memory") != "full": + return None, "".join("S" if a["success"] else "F" for a in att) + hist = "".join("S" if a["success"] else "F" for a in att) + if att[0]["success"]: + ev = error_event(att[0]["outcome"]) + cls = "S?" if ev is None else ("IR" if ev else "CS") + else: + cls = "XR" if any(a["success"] for a in att) else "F" + return cls, hist + + def agent_info(self): + h, en = self.harness, self.entry + hdr = self.headers[0] if self.headers else {} + return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"), + harness_version=h.get("version") or hdr.get("version"), + harness_binary_sha256=(h.get("binary") or {}).get("sha256"), + model=h.get("model") or en.get("model") or hdr.get("model_name"), + effort=h.get("effort") or en.get("effort") or hdr.get("effort"), + provider=h.get("provider") or en.get("provider"), + codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"), + jail=en.get("jail")) + + +# ====================================================================================================== recording + +class EpisodeSink: + """Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed.""" + + def __init__(self, path): + self.path = path + os.makedirs(path, exist_ok=True) + self.w = None + self.num = defaultdict(list) + self.n = 0 + + def add(self, st, imgs): + import imageio + if self.w is None: + self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb", + pixelformat="rgb24", macro_block_size=1, + ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error") + for k in ("agentview", "wrist")] + for w, im in zip(self.w, imgs): + w.append_data(im) + for k, v in st.items(): + self.num[k].append(v) + self.n += 1 + + def close(self, final_state, final_imgs): + from PIL import Image + if self.w is not None: + for w in self.w: + w.close() + arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"} + np.savez(os.path.join(self.path, "frames.npz"), **arr) + if self.num.get("sim_state"): + np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64)) + np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()}) + for k, im in zip(("agentview", "wrist"), final_imgs): + Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png")) + + +class Recorder: + """Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink.""" + + def __init__(self, rp, res): + self.rp, self.res = rp, int(res) + self.active = False + self.sink = None + self.cur = dict(attempt=1, command=-1, phase=PHASES["move"]) + env = rp.task.env + self.env, self.rob = env, env.robots[0] + self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist")) + orig = env.step + + def step(a): + if self.active and self.sink is not None: + self.capture(np.asarray(a, np.float64)) + out = orig(a) + if self.active and self.sink is not None: + self.rp.poll_events(self.sink.n - 1) + return out + + env.step = step + + @property + def n(self): + return self.sink.n if self.sink is not None else 0 + + def state(self): + import robosuite.utils.transform_utils as T + env, rob = self.env, self.rob + d = env.sim.data + eef = np.array(d.site_xpos[rob.eef_site_id], np.float64) + q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw") + gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64) + try: + flat = np.asarray(env.sim.get_state().flatten(), np.float64) + except Exception: + flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64) + sk = self.rp.task.sk + return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64), + gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64), + joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64), + gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64), + eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)), + sim_time=np.float64(d.time), sim_state=flat) + + def images(self): + return [envs.render(self.env, c, self.res) for c in self.cams] + + def capture(self, a): + st = self.state() + st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]), + phase=np.int64(self.cur["phase"])) + self.sink.add(st, self.images()) + + +class RunReplay: + def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run_name = os.path.basename(self.run_dir) + self.log = RunLog(self.run_dir, manifest) + self.ev = self.log.ev + self.start = self.log.start + cp = os.path.join(self.run_dir, "contract.json") + self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {} + spec = self.contract.get("image_spec") or {} + self.image_res = int(spec.get("width", 512)) + self.code_diff = check_code(self.run_dir) + s = self.start + self.task = TASKS[s["task"]](cam_res=self.image_res) + inst = self.task.sample_instance(s["seed"]) + logged = s.get("inst") or {} + sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")}) + self.inst_diff = diff_json(sampled, logged, "inst") + if s.get("arm", "none") not in (None, "none") or logged.get("nominal"): + inst.update(logged) # controlled arms / nominal: the server overrode these instance fields + self.inst_diff = [] + self.inst = inst + self.protocol = getattr(self.task, "protocol", "cross") + self.k = int(s.get("k") or self.task.max_attempts) + self.attempt = 1 + self.mismatch = [] # (where, what, logged, replayed) + self.n_checked = 0 + self.max_dev_m = 0.0 + self.unfinished = None + self.rec = Recorder(self, res) if record else None + self.res = int(res) + self.out_root = out_root + self.n_mon = 0 + self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0 + self.episodes = [] # summaries of the written episodes + self.task.reset_instance(self.inst) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + sim = self.task.env.sim + bid = sim.model.body_name2id("robot0_base") + self.base_off = np.array(sim.data.body_xpos[bid], float).copy() + if self.rec: + self._open_episode() + + # ------------------------------------------------------------------ episodes + def _ep_dir(self): + return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}") + + def _open_episode(self): + self.rec.sink = EpisodeSink(self._ep_dir()) + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.rec.active = True + self.events, self.spans, self.ep_attempts = [], [], [] + self.ep_initial = self.rec.state() # state right after the reset (before frame 0) + + def close_episode(self): + if not self.rec: + self.ep_attempts = [] + return + sink = self.rec.sink + st = self.rec.state() + imgs = self.rec.images() + st.pop("sim_state", None) + sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs) + ann = build_annotation(self, sink) + with open(os.path.join(sink.path, "annotation.json"), "w") as f: + json.dump(ann, f, indent=1, default=_json_default) + self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n, + attempts=[a["attempt"] for a in self.ep_attempts])) + self.rec.active = False + self.rec.sink = None + self.ep_index += 1 + + # ------------------------------------------------------------------ monitor events (task-side error events) + def poll_events(self, frame): + mon = getattr(self.task, "mon", None) + evs = mon.get("events") if isinstance(mon, dict) else None + if not isinstance(evs, list): + return + if len(evs) < self.n_mon: # monitor was rebuilt + self.n_mon = 0 + for e in evs[self.n_mon:]: + self.events.append(dict(frame=int(frame), attempt=self.attempt, + event=norm_json(e) if isinstance(e, dict) else str(e))) + self.n_mon = len(evs) + + # ------------------------------------------------------------------ state as the server reports it + def proprio_la(self): + p = self.ex.proprio() + pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off] + return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"]) + + def compare(self, where, rep_logged, rep): + self.n_checked += 1 + for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"): + if k not in rep_logged or k not in rep: + continue + a, b = rep_logged[k], rep[k] + if k == "eef_pos": + dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float)))) + self.max_dev_m = max(self.max_dev_m, dev) + if dev > 1.5e-4: + self.mismatch.append((where, k, a, b)) + elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4): + self.mismatch.append((where, k, a, b)) + if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)): + self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok"))) + + def _span(self, e, f0, kind): + if self.rec: + self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0, + frame_end=self.rec.n)) + + # ------------------------------------------------------------------ commands (robot_server._handle_v2) + def move_eef(self, e): + args = e.get("args") or {} + where = f"a{e['attempt']}s{e['step']}" + logged = e.get("report") or {} + f0 = self.rec.n if self.rec else 0 + p = self.ex.proprio() + if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}: + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + off = self.base_off + try: + cur = np.asarray(p["eef_pos"], float) - off + tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")] + yaw = float(args.get("yaw", p["eef_yaw_deg"])) + speed = None if args.get("speed") in (None, "") else float(args["speed"]) + except (TypeError, ValueError): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + grip = args.get("gripper") + if grip not in (None, "open", "close"): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + moving = any(k in args for k in ("x", "y", "z", "yaw")) + tgt_w = np.asarray(tgt) + off + if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)): + self._span(e, f0, "rejected") + return self.compare(where, logged, dict(ok=False, **self.proprio_la())) + raw = {} + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"]) + if moving: + mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw) + if speed is not None: + mv["speed"] = speed + raw.update(self.ex.call("move_to", mv).report) + if grip is not None: + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"]) + raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report) + rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la()) + self.compare(where, logged, rep) + lr = e.get("raw") or {} + for k in ("holding_object", "touched_object"): + if k in lr and k in raw and bool(lr[k]) != bool(raw[k]): + self.mismatch.append((where, "raw." + k, lr[k], raw[k])) + self._span(e, f0, "move_eef") + + def observe(self, e): + f0 = self.rec.n if self.rec else 0 + self._span(e, f0, "observe") + + def done(self, e): + f0 = self.rec.n if self.rec else 0 + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"]) + out = self.task.outcome(self.inst) + succ = bool(out["success"]) + where = f"a{e['attempt']}done" + if succ != bool(e.get("success") in (True, "True")): + self.mismatch.append((where, "success", e.get("success"), succ)) + lo = e.get("outcome") or {} + ro = norm_json({k: v for k, v in out.items() if k != "feedback"}) + if isinstance(lo, dict): + for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8): + self.mismatch.append((where,) + d) + info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""), + feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")), + think_s=e.get("think_s")) + try: + info["feedback_f2"] = self.task.feedback(self.inst, out, "F2") + except Exception as ex_: + info["feedback_f2"] = f"" + if self.rec: + info["judge_frames"] = [f0, self.rec.n] + self.ep_attempts.append(info) + last = self.attempt >= self.k or succ or bool(out.get("terminal")) + if self.protocol == "cross" or last: + self.close_episode() + if last: + return True + self.attempt += 1 + if self.protocol == "cross": + self.task.reset_instance(self.inst) + self.n_mon = 0 + if self.rec: + self._open_episode() + elif self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + return False + + def run(self): + t0 = time.time() + finished = False + for e in self.ev: + if e["ev"] == "call": + if e.get("cmd") == "move_eef": + self.move_eef(e) + elif e.get("cmd") == "observe": + self.observe(e) + else: + self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None)) + elif e["ev"] == "done": + finished = self.done(e) + if finished: + break + self.unfinished = not finished + if not finished and self.rec and self.rec.sink is not None: + # the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged + if self.rec.n or self.ep_attempts: + self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True, + finish_reason="", feedback_shown="", auto_ended=False)) + self.close_episode() + else: + shutil.rmtree(self.rec.sink.path, ignore_errors=True) + self.rec.sink = None + self.wall_s = time.time() - t0 + return self + + def summary(self): + return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"], + protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff), + n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6), + unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1), + first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]]) + + +# ====================================================================================================== annotation + +def task_info(task, inst): + cls = type(task) + return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable", + category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"), + max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)), + instruction=cls.instruction) + + +def build_annotation(rp, sink): + """Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2 + failure description), run-level outcome class, every robot command with its frame span and the agent's narration, + task-side error events with frame indices.""" + log = rp.log + s = rp.start + cond, chain = log.condition() + cls, hist = log.outcome_class() + att_all = log.attempts() + attempts = [] + for a in rp.ep_attempts: + a = dict(a) + n = a["attempt"] + later = [x for x in att_all if x["attempt"] > n] + a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later)) + a["is_last_attempt_of_run"] = not later + fn = log.finish_notes.get(n) + if fn: + a["agent_finish"] = fn + a["error_event_in_attempt"] = error_event(a.get("outcome")) + attempts.append(a) + # post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command) + for a in attempts: + nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1]) + if a.get("success") is False and nxt: + note = log.notes[nxt[0]] + a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note} + commands = [] + for sp in rp.spans: + e = log.calls.get((sp["attempt"], sp["step"])) or {} + rep = e.get("report") or {} + c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"], + frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]), + args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"), + stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"), + gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"), + touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"), + agent_obs_images=rep.get("images")) + note = log.notes.get((sp["attempt"], sp["step"])) + if note: + c["agent_note"] = {k: v for k, v in note.items() if k != "command"} + commands.append(c) + t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x] + return dict( + schema=SCHEMA, + source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts], + episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain, + memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None), + feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"), + k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"), + contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256") + if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)), + agent=log.agent_info(), + task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"), + instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}), + run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all), + run_success=any(x["success"] for x in att_all) if att_all else None, + agent_final_report=log.final_report[:6000] or None, + mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)), + attempts=attempts, + commands=commands, + task_events=rp.events, + frames=dict(n=sink.n, fps=FPS, image_res=rp.res, + phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"], + joint_pos=rp.ep_initial["joint_pos"], + gripper_qpos=rp.ep_initial["gripper_qpos"])), + ) + + +# ====================================================================================================== CLI + +def load_manifest(run_dir): + p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json") + return json.load(open(p)) if os.path.exists(p) else {} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("mode", choices=["check", "record"]) + ap.add_argument("runs", nargs="+") + ap.add_argument("--json", default="") + ap.add_argument("--out", default="") + ap.add_argument("--res", type=int, default=256) + ap.add_argument("--force", action="store_true", help="record again even if replay.json exists") + a = ap.parse_args() + rows = [] + for r in a.runs: + r = r.rstrip("/") + try: + if a.mode == "check": + s = RunReplay(r, manifest=load_manifest(r)).run().summary() + else: + batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r) + rd = os.path.join(a.out, batch, name) + if os.path.exists(os.path.join(rd, "replay.json")) and not a.force: + print(json.dumps(dict(run=name, skipped="exists")), flush=True) + continue + shutil.rmtree(rd, ignore_errors=True) + rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run() + s = rp.summary() + s["episodes"] = rp.episodes + with open(os.path.join(rd, "replay.json"), "w") as f: + json.dump(s, f, indent=1) + except Exception: + import traceback + s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:]) + rows.append(s) + print(json.dumps(s), flush=True) + if a.json: + with open(a.json, "w") as f: + json.dump(rows, f, indent=1) + + +if __name__ == "__main__": + main() diff --git a/leaf/code/remaining-lh-20261103-remaining_lh_20261103_deepseek/lerobot_export.py b/leaf/code/remaining-lh-20261103-remaining_lh_20261103_deepseek/lerobot_export.py new file mode 100644 index 0000000000000000000000000000000000000000..fa4fa0a1be92844c9cf410663f77de5e200bda18 --- /dev/null +++ b/leaf/code/remaining-lh-20261103-remaining_lh_20261103_deepseek/lerobot_export.py @@ -0,0 +1,431 @@ +"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars. + +Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding +can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan): + + python scripts/lerobot_export.py plan --raw [,] --runs-root /runs/api \ + --paper --task-set /sets/main_v2_1inst.txt --work [--batches ...] [--limit N] + python scripts/lerobot_export.py shard --work --shard i --nshards N + python scripts/lerobot_export.py merge --work --nshards N --out + +Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0 +mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped. + +LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t): + observation.images.image agentview RGB 256x256 (upright; LIBERO naming) + observation.images.wrist_image wrist (eye-in-hand) RGB 256x256 + observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout) + observation.joint_pos / joint_vel 7 arm joints (rad, rad/s) + observation.eef_quat 4: xyzw; observation.gripper_width 1 (m) + action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad), + gripper (-1 open, +1 close) + annotation.attempt_index attempt (1-based) the frame belongs to + annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`) + annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action) + annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt + annotation.task_event number of task-monitor events (error / progress events) registered at this step +Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table), +runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state +per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/. +""" +import argparse +import glob +import json +import os +import re +import shutil +import time + +import numpy as np + +FPS = 20 +RES = 256 +BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke", + "cc_smoke", "cc_opus_smoke"] +BATCH_NOTES = { + "cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog", + "cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267", + "cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299", + "cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances", + "cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)", + "cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the " + "with-history continuation of failed runs is incomplete", + "cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early", + "cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt", + "cc_opus_smoke": "smoke test: single attempt", +} +PHASES = {"move": 0, "gripper": 1, "judge": 2} +CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)", + "L2": "disturbed state to restore (incl. damage the agent causes)", + "L3": "infeasible manipulation strategy (grasp / contact / tool must change)", + "L4": "misjudged geometry (size, shape, fit, hidden structure)", + "L5": "misjudged physics (mass distribution, friction, dynamics)"} + + +def features(): + vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]} + f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names} + i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None} + return { + "observation.images.image": vid(), + "observation.images.wrist_image": vid(), + "observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z", + "finger_qpos_left", "finger_qpos_right"]), + "observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]), + "observation.gripper_width": f32(1, ["width_m"]), + "action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y", + "eef_delta_rot_aa_z", "gripper_close"]), + "annotation.attempt_index": i64(), + "annotation.command_index": i64(), + "annotation.phase": i64(), + "annotation.attempt_success": i64(), + "annotation.task_event": i64(), + } + + +# ------------------------------------------------------------------------------------------------ paper metadata + +def _clean_tex(s): + s = re.sub(r"%.*", "", s) + for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"), + (r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"), + (r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"), + (r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"), + (r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]: + s = re.sub(a, b, s) + s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s) + s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s) + for _ in range(3): + s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\$([^$]*)\$", r"\1", s) + s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ") + s = re.sub(r"\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\\[a-zA-Z]+\*?", "", s) + return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip() + + +def paper_tasks(paper_dir): + """{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the + paper's task table and task appendix (empty if the paper sources are not there).""" + out = {} + if not paper_dir: + return out + app = os.path.join(paper_dir, "sections", "appendix_tasks.tex") + tab = os.path.join(paper_dir, "sections", "tab_tasks.tex") + if os.path.exists(app): + txt = open(app).read() + parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt) + for i in range(1, len(parts) - 1, 2): + if parts[i] != "\\paragraph{": + continue + body = parts[i + 1] + m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S) + if not m: + continue + name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip() + desc = _clean_tex(body[m.end():]) + out[code] = dict(name=name, cause=_clean_tex(cause), description=desc) + if os.path.exists(tab): + names = {v["name"].lower(): k for k, v in out.items()} + for line in open(tab): + cells = [c.strip() for c in line.split("&")] + if len(cells) != 6 or not cells[-1].endswith("\\\\"): + continue + nm = re.sub(r"\\contscene", "", cells[0]).strip().lower() + code = names.get(nm) + if not code: + continue + out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]), + repair_within_attempt=_clean_tex(cells[3]) == "yes", + oracle_first_attempt_pct=_clean_tex(cells[4]), + naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip())) + return out + + +# ------------------------------------------------------------------------------------------------ collection + +def manifest_status(runs_root, batch, run, cache={}): + if batch not in cache: + p = os.path.join(runs_root, batch, "manifest.json") + cache[batch] = json.load(open(p)) if os.path.exists(p) else {} + m = cache[batch] + for r in m.get("runs", []): + if r.get("run") == run: + return r.get("status", "?"), r + for r in m.get("superseded", []): + if r.get("run") == run: + return "superseded_" + str(r.get("status", "?")), r + return "not_in_manifest", {} + + +def collect(raw_roots, runs_root, batches, task_order): + """Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root.""" + eps, rejected, seen = [], [], set() + for root in raw_roots: + for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))): + rep = json.load(open(rj)) + batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"] + if (batches and batch not in batches) or (batch, run) in seen: + continue + seen.add((batch, run)) + ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff") + status, entry = manifest_status(runs_root, batch, run) + if not ok: + never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked") + rejected.append(dict(run=run, batch=batch, run_status=status, + reason="run never started (no contract, no robot command)" if never else + "replay does not reproduce the log (the log has gaps or the replay diverged)", + detail=rep.get("first_mismatches"))) + continue + for ep in rep.get("episodes", []): + d = os.path.join(root, ep["dir"]) + ann = json.load(open(os.path.join(d, "annotation.json"))) + judged = [a for a in ann["attempts"] if a.get("success") is not None] + if not judged or ep["n_frames"] == 0: + rejected.append(dict(run=run, batch=batch, episode=ep["dir"], + reason="no judged attempt" if not judged else "no frames")) + continue + ann["source"]["run_status"] = status + ann["source"]["manifest_id"] = entry.get("id") + ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"], + max_eef_dev_m=rep["max_eef_dev_m"]) + key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99), + {"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2), + ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"]) + eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann)) + eps.sort(key=lambda x: x["key"]) + return eps, rejected + + +# ------------------------------------------------------------------------------------------------ writing + +def frames_of(path): + import av + with av.open(path) as c: + for fr in c.decode(video=0): + yield fr.to_ndarray(format="rgb24") + + +def flat_row(i, ann, n, idx0): + s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"] + att = ann["attempts"] + a0 = att[0] + return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n, + batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"], + memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"), + episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att], + harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"), + effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"), + task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"), + category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"], + success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att], + feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att], + auto_ended=[a.get("auto_ended") for a in att], + corrected_later_in_run=[a.get("corrected_later_in_run") for a in att], + error_event_in_attempt=[a.get("error_event_in_attempt") for a in att], + run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"), + n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]), + first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None) + + +def cmd_plan(a): + task_order = {} + if a.task_set and os.path.exists(a.task_set): + for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")): + task_order[line.split(":")[0].strip()] = i + batches = [b for b in a.batches.split(",") if b] if a.batches else None + eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order) + if a.limit: + eps = eps[:a.limit] + paper = paper_tasks(a.paper) + idx0 = 0 + for i, e in enumerate(eps): + ann = e["ann"] + tname = ann["task"]["name"] + if tname in paper: + ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"} + ann["episode_index"] = i + ann["dataset_index_range"] = [idx0, idx0 + e["n"]] + e["index"], e["from"] = i, idx0 + idx0 += e["n"] + del e["key"] + os.makedirs(a.work, exist_ok=True) + with open(os.path.join(a.work, "plan.json"), "w") as f: + json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f, + ensure_ascii=False) + print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True) + + +def shard_range(n_eps, i, k): + return (n_eps * i) // k, (n_eps * (i + 1)) // k + + +def cmd_shard(a): + from lerobot.datasets.lerobot_dataset import LeRobotDataset + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + lo, hi = shard_range(len(eps), a.shard, a.nshards) + out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}") + if os.path.exists(os.path.join(out, "DONE")): + print(f"shard {a.shard}: done already", flush=True) + return + shutil.rmtree(out, ignore_errors=True) + ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out, + robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads, + vcodec=a.vcodec) + nfr = 0 + for e in eps[lo:hi]: + d, ann, n = e["dir"], e["ann"], e["n"] + fr = np.load(os.path.join(d, "frames.npz")) + assert len(fr["action"]) == n, d + succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]} + evc = np.zeros(n, np.int64) + for ev in ann["task_events"]: + if 0 <= ev["frame"] < n: + evc[ev["frame"]] += 1 + state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32) + instr = ann["task"]["instruction"] + k = 0 + for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))): + if k >= n: + break + ds.add_frame({ + "observation.images.image": img, "observation.images.wrist_image": wr, + "observation.state": state[k], + "observation.joint_pos": fr["joint_pos"][k].astype(np.float32), + "observation.joint_vel": fr["joint_vel"][k].astype(np.float32), + "observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32), + "observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32), + "action": fr["action"][k].astype(np.float32), + "annotation.attempt_index": np.array([fr["attempt"][k]], np.int64), + "annotation.command_index": np.array([fr["command"][k]], np.int64), + "annotation.phase": np.array([fr["phase"][k]], np.int64), + "annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64), + "annotation.task_event": np.array([evc[k]], np.int64), + "task": instr, + }) + k += 1 + if k != n: + raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames") + ds.save_episode() + nfr += n + ds.finalize() + shutil.rmtree(os.path.join(out, "images"), ignore_errors=True) + open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n") + print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True) + + +def cmd_merge(a): + from pathlib import Path + from lerobot.datasets.aggregate import aggregate_datasets + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + roots, ids = [], [] + for i in range(a.nshards): + lo, hi = shard_range(len(eps), i, a.nshards) + if hi <= lo: + continue + r = os.path.join(a.work, "shards", f"shard_{i:03d}") + if not os.path.exists(os.path.join(r, "DONE")): + raise SystemExit(f"shard {i} is not done") + roots.append(Path(r)) + ids.append(f"{plan['repo_id']}-shard{i:03d}") + if os.path.exists(a.out): + raise SystemExit(f"{a.out} exists; refusing to overwrite") + aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out)) + print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True) + write_sidecars(a, plan) + print(f"merge done in {time.time() - t0:.0f}s", flush=True) + + +def write_sidecars(a, plan): + eps, paper = plan["episodes"], plan["paper"] + lff = os.path.join(a.out, "lff") + for sub in ("annotations", "sim_state", "final", "code"): + os.makedirs(os.path.join(lff, sub), exist_ok=True) + rows, runs, tasks = [], {}, {} + for e in eps: + i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"] + name = f"episode_{i:06d}" + if os.path.exists(os.path.join(d, "sim_state.npy")): + shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy")) + shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz")) + for cam, key in (("agentview", "image"), ("wrist", "wrist_image")): + shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png")) + with open(os.path.join(lff, "annotations", name + ".json"), "w") as f: + json.dump(ann, f, indent=1, ensure_ascii=False) + rows.append(flat_row(i, ann, n, e["from"])) + tname = ann["task"]["name"] + rk = (ann["source"]["batch"], ann["source"]["run"]) + r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"), + run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"], + memory_free_chain_of=ann["source"].get("memory_free_chain_of"), + memory_free_rep=ann["source"].get("memory_free_rep"), task=tname, + seed=ann["task"]["seed"], model=ann["agent"].get("model"), + harness=ann["agent"].get("harness"), + harness_version=ann["agent"].get("harness_version"), + codex_catalog=ann["agent"].get("codex_catalog"), + outcome_class=ann["run_outcome"].get("outcome_class"), + attempt_history=ann["run_outcome"].get("attempt_history"), + agent_final_report=ann["run_outcome"].get("agent_final_report"), + episodes=[])) + for x in ann["attempts"]: + r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success"))) + if tname not in tasks: + tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")} + if tname in paper: + tasks[tname]["paper"] = paper[tname] + tasks[tname]["instances"] = {} + tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"] + # memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id) + by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")} + for r in runs.values(): + if r.get("memory_free_chain_of"): + r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"])) + for (b, rn), r in runs.items(): + r["memory_free_retries"] = sorted((x["run"] for x in runs.values() + if x["batch"] == b and x.get("memory_free_chain_of_run") == rn), + key=lambda q: runs[(b, q)].get("memory_free_rep") or 0) + with open(os.path.join(lff, "episodes.jsonl"), "w") as f: + for row in rows: + f.write(json.dumps(row, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "runs.jsonl"), "w") as f: + for r in runs.values(): + f.write(json.dumps(r, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "tasks.json"), "w") as f: + json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False) + with open(os.path.join(lff, "batches.json"), "w") as f: + json.dump(BATCH_NOTES, f, indent=1) + with open(os.path.join(lff, "rejected.json"), "w") as f: + json.dump(plan["rejected"], f, indent=1) + here = os.path.dirname(os.path.abspath(__file__)) + for s in ("lerobot_replay.py", "lerobot_export.py"): + shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("step", choices=["plan", "shard", "merge"]) + ap.add_argument("--work", required=True) + ap.add_argument("--raw", default="") + ap.add_argument("--runs-root", default="") + ap.add_argument("--out", default="") + ap.add_argument("--paper", default="") + ap.add_argument("--task-set", default="") + ap.add_argument("--repo-id", default="lffbench/agent-replays") + ap.add_argument("--batches", default="") + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--shard", type=int, default=0) + ap.add_argument("--nshards", type=int, default=1) + ap.add_argument("--threads", type=int, default=2) + ap.add_argument("--vcodec", default="libsvtav1") + a = ap.parse_args() + {"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a) + + +if __name__ == "__main__": + main() diff --git a/leaf/code/remaining-lh-20261103-remaining_lh_auto_001_opus/lerobot_export.py b/leaf/code/remaining-lh-20261103-remaining_lh_auto_001_opus/lerobot_export.py new file mode 100644 index 0000000000000000000000000000000000000000..fa4fa0a1be92844c9cf410663f77de5e200bda18 --- /dev/null +++ b/leaf/code/remaining-lh-20261103-remaining_lh_auto_001_opus/lerobot_export.py @@ -0,0 +1,431 @@ +"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars. + +Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding +can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan): + + python scripts/lerobot_export.py plan --raw [,] --runs-root /runs/api \ + --paper --task-set /sets/main_v2_1inst.txt --work [--batches ...] [--limit N] + python scripts/lerobot_export.py shard --work --shard i --nshards N + python scripts/lerobot_export.py merge --work --nshards N --out + +Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0 +mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped. + +LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t): + observation.images.image agentview RGB 256x256 (upright; LIBERO naming) + observation.images.wrist_image wrist (eye-in-hand) RGB 256x256 + observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout) + observation.joint_pos / joint_vel 7 arm joints (rad, rad/s) + observation.eef_quat 4: xyzw; observation.gripper_width 1 (m) + action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad), + gripper (-1 open, +1 close) + annotation.attempt_index attempt (1-based) the frame belongs to + annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`) + annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action) + annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt + annotation.task_event number of task-monitor events (error / progress events) registered at this step +Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table), +runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state +per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/. +""" +import argparse +import glob +import json +import os +import re +import shutil +import time + +import numpy as np + +FPS = 20 +RES = 256 +BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke", + "cc_smoke", "cc_opus_smoke"] +BATCH_NOTES = { + "cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog", + "cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267", + "cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299", + "cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances", + "cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)", + "cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the " + "with-history continuation of failed runs is incomplete", + "cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early", + "cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt", + "cc_opus_smoke": "smoke test: single attempt", +} +PHASES = {"move": 0, "gripper": 1, "judge": 2} +CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)", + "L2": "disturbed state to restore (incl. damage the agent causes)", + "L3": "infeasible manipulation strategy (grasp / contact / tool must change)", + "L4": "misjudged geometry (size, shape, fit, hidden structure)", + "L5": "misjudged physics (mass distribution, friction, dynamics)"} + + +def features(): + vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]} + f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names} + i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None} + return { + "observation.images.image": vid(), + "observation.images.wrist_image": vid(), + "observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z", + "finger_qpos_left", "finger_qpos_right"]), + "observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]), + "observation.gripper_width": f32(1, ["width_m"]), + "action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y", + "eef_delta_rot_aa_z", "gripper_close"]), + "annotation.attempt_index": i64(), + "annotation.command_index": i64(), + "annotation.phase": i64(), + "annotation.attempt_success": i64(), + "annotation.task_event": i64(), + } + + +# ------------------------------------------------------------------------------------------------ paper metadata + +def _clean_tex(s): + s = re.sub(r"%.*", "", s) + for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"), + (r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"), + (r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"), + (r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"), + (r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]: + s = re.sub(a, b, s) + s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s) + s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s) + for _ in range(3): + s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\$([^$]*)\$", r"\1", s) + s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ") + s = re.sub(r"\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\\[a-zA-Z]+\*?", "", s) + return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip() + + +def paper_tasks(paper_dir): + """{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the + paper's task table and task appendix (empty if the paper sources are not there).""" + out = {} + if not paper_dir: + return out + app = os.path.join(paper_dir, "sections", "appendix_tasks.tex") + tab = os.path.join(paper_dir, "sections", "tab_tasks.tex") + if os.path.exists(app): + txt = open(app).read() + parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt) + for i in range(1, len(parts) - 1, 2): + if parts[i] != "\\paragraph{": + continue + body = parts[i + 1] + m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S) + if not m: + continue + name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip() + desc = _clean_tex(body[m.end():]) + out[code] = dict(name=name, cause=_clean_tex(cause), description=desc) + if os.path.exists(tab): + names = {v["name"].lower(): k for k, v in out.items()} + for line in open(tab): + cells = [c.strip() for c in line.split("&")] + if len(cells) != 6 or not cells[-1].endswith("\\\\"): + continue + nm = re.sub(r"\\contscene", "", cells[0]).strip().lower() + code = names.get(nm) + if not code: + continue + out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]), + repair_within_attempt=_clean_tex(cells[3]) == "yes", + oracle_first_attempt_pct=_clean_tex(cells[4]), + naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip())) + return out + + +# ------------------------------------------------------------------------------------------------ collection + +def manifest_status(runs_root, batch, run, cache={}): + if batch not in cache: + p = os.path.join(runs_root, batch, "manifest.json") + cache[batch] = json.load(open(p)) if os.path.exists(p) else {} + m = cache[batch] + for r in m.get("runs", []): + if r.get("run") == run: + return r.get("status", "?"), r + for r in m.get("superseded", []): + if r.get("run") == run: + return "superseded_" + str(r.get("status", "?")), r + return "not_in_manifest", {} + + +def collect(raw_roots, runs_root, batches, task_order): + """Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root.""" + eps, rejected, seen = [], [], set() + for root in raw_roots: + for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))): + rep = json.load(open(rj)) + batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"] + if (batches and batch not in batches) or (batch, run) in seen: + continue + seen.add((batch, run)) + ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff") + status, entry = manifest_status(runs_root, batch, run) + if not ok: + never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked") + rejected.append(dict(run=run, batch=batch, run_status=status, + reason="run never started (no contract, no robot command)" if never else + "replay does not reproduce the log (the log has gaps or the replay diverged)", + detail=rep.get("first_mismatches"))) + continue + for ep in rep.get("episodes", []): + d = os.path.join(root, ep["dir"]) + ann = json.load(open(os.path.join(d, "annotation.json"))) + judged = [a for a in ann["attempts"] if a.get("success") is not None] + if not judged or ep["n_frames"] == 0: + rejected.append(dict(run=run, batch=batch, episode=ep["dir"], + reason="no judged attempt" if not judged else "no frames")) + continue + ann["source"]["run_status"] = status + ann["source"]["manifest_id"] = entry.get("id") + ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"], + max_eef_dev_m=rep["max_eef_dev_m"]) + key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99), + {"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2), + ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"]) + eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann)) + eps.sort(key=lambda x: x["key"]) + return eps, rejected + + +# ------------------------------------------------------------------------------------------------ writing + +def frames_of(path): + import av + with av.open(path) as c: + for fr in c.decode(video=0): + yield fr.to_ndarray(format="rgb24") + + +def flat_row(i, ann, n, idx0): + s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"] + att = ann["attempts"] + a0 = att[0] + return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n, + batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"], + memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"), + episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att], + harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"), + effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"), + task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"), + category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"], + success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att], + feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att], + auto_ended=[a.get("auto_ended") for a in att], + corrected_later_in_run=[a.get("corrected_later_in_run") for a in att], + error_event_in_attempt=[a.get("error_event_in_attempt") for a in att], + run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"), + n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]), + first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None) + + +def cmd_plan(a): + task_order = {} + if a.task_set and os.path.exists(a.task_set): + for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")): + task_order[line.split(":")[0].strip()] = i + batches = [b for b in a.batches.split(",") if b] if a.batches else None + eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order) + if a.limit: + eps = eps[:a.limit] + paper = paper_tasks(a.paper) + idx0 = 0 + for i, e in enumerate(eps): + ann = e["ann"] + tname = ann["task"]["name"] + if tname in paper: + ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"} + ann["episode_index"] = i + ann["dataset_index_range"] = [idx0, idx0 + e["n"]] + e["index"], e["from"] = i, idx0 + idx0 += e["n"] + del e["key"] + os.makedirs(a.work, exist_ok=True) + with open(os.path.join(a.work, "plan.json"), "w") as f: + json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f, + ensure_ascii=False) + print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True) + + +def shard_range(n_eps, i, k): + return (n_eps * i) // k, (n_eps * (i + 1)) // k + + +def cmd_shard(a): + from lerobot.datasets.lerobot_dataset import LeRobotDataset + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + lo, hi = shard_range(len(eps), a.shard, a.nshards) + out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}") + if os.path.exists(os.path.join(out, "DONE")): + print(f"shard {a.shard}: done already", flush=True) + return + shutil.rmtree(out, ignore_errors=True) + ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out, + robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads, + vcodec=a.vcodec) + nfr = 0 + for e in eps[lo:hi]: + d, ann, n = e["dir"], e["ann"], e["n"] + fr = np.load(os.path.join(d, "frames.npz")) + assert len(fr["action"]) == n, d + succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]} + evc = np.zeros(n, np.int64) + for ev in ann["task_events"]: + if 0 <= ev["frame"] < n: + evc[ev["frame"]] += 1 + state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32) + instr = ann["task"]["instruction"] + k = 0 + for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))): + if k >= n: + break + ds.add_frame({ + "observation.images.image": img, "observation.images.wrist_image": wr, + "observation.state": state[k], + "observation.joint_pos": fr["joint_pos"][k].astype(np.float32), + "observation.joint_vel": fr["joint_vel"][k].astype(np.float32), + "observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32), + "observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32), + "action": fr["action"][k].astype(np.float32), + "annotation.attempt_index": np.array([fr["attempt"][k]], np.int64), + "annotation.command_index": np.array([fr["command"][k]], np.int64), + "annotation.phase": np.array([fr["phase"][k]], np.int64), + "annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64), + "annotation.task_event": np.array([evc[k]], np.int64), + "task": instr, + }) + k += 1 + if k != n: + raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames") + ds.save_episode() + nfr += n + ds.finalize() + shutil.rmtree(os.path.join(out, "images"), ignore_errors=True) + open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n") + print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True) + + +def cmd_merge(a): + from pathlib import Path + from lerobot.datasets.aggregate import aggregate_datasets + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + roots, ids = [], [] + for i in range(a.nshards): + lo, hi = shard_range(len(eps), i, a.nshards) + if hi <= lo: + continue + r = os.path.join(a.work, "shards", f"shard_{i:03d}") + if not os.path.exists(os.path.join(r, "DONE")): + raise SystemExit(f"shard {i} is not done") + roots.append(Path(r)) + ids.append(f"{plan['repo_id']}-shard{i:03d}") + if os.path.exists(a.out): + raise SystemExit(f"{a.out} exists; refusing to overwrite") + aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out)) + print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True) + write_sidecars(a, plan) + print(f"merge done in {time.time() - t0:.0f}s", flush=True) + + +def write_sidecars(a, plan): + eps, paper = plan["episodes"], plan["paper"] + lff = os.path.join(a.out, "lff") + for sub in ("annotations", "sim_state", "final", "code"): + os.makedirs(os.path.join(lff, sub), exist_ok=True) + rows, runs, tasks = [], {}, {} + for e in eps: + i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"] + name = f"episode_{i:06d}" + if os.path.exists(os.path.join(d, "sim_state.npy")): + shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy")) + shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz")) + for cam, key in (("agentview", "image"), ("wrist", "wrist_image")): + shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png")) + with open(os.path.join(lff, "annotations", name + ".json"), "w") as f: + json.dump(ann, f, indent=1, ensure_ascii=False) + rows.append(flat_row(i, ann, n, e["from"])) + tname = ann["task"]["name"] + rk = (ann["source"]["batch"], ann["source"]["run"]) + r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"), + run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"], + memory_free_chain_of=ann["source"].get("memory_free_chain_of"), + memory_free_rep=ann["source"].get("memory_free_rep"), task=tname, + seed=ann["task"]["seed"], model=ann["agent"].get("model"), + harness=ann["agent"].get("harness"), + harness_version=ann["agent"].get("harness_version"), + codex_catalog=ann["agent"].get("codex_catalog"), + outcome_class=ann["run_outcome"].get("outcome_class"), + attempt_history=ann["run_outcome"].get("attempt_history"), + agent_final_report=ann["run_outcome"].get("agent_final_report"), + episodes=[])) + for x in ann["attempts"]: + r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success"))) + if tname not in tasks: + tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")} + if tname in paper: + tasks[tname]["paper"] = paper[tname] + tasks[tname]["instances"] = {} + tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"] + # memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id) + by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")} + for r in runs.values(): + if r.get("memory_free_chain_of"): + r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"])) + for (b, rn), r in runs.items(): + r["memory_free_retries"] = sorted((x["run"] for x in runs.values() + if x["batch"] == b and x.get("memory_free_chain_of_run") == rn), + key=lambda q: runs[(b, q)].get("memory_free_rep") or 0) + with open(os.path.join(lff, "episodes.jsonl"), "w") as f: + for row in rows: + f.write(json.dumps(row, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "runs.jsonl"), "w") as f: + for r in runs.values(): + f.write(json.dumps(r, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "tasks.json"), "w") as f: + json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False) + with open(os.path.join(lff, "batches.json"), "w") as f: + json.dump(BATCH_NOTES, f, indent=1) + with open(os.path.join(lff, "rejected.json"), "w") as f: + json.dump(plan["rejected"], f, indent=1) + here = os.path.dirname(os.path.abspath(__file__)) + for s in ("lerobot_replay.py", "lerobot_export.py"): + shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("step", choices=["plan", "shard", "merge"]) + ap.add_argument("--work", required=True) + ap.add_argument("--raw", default="") + ap.add_argument("--runs-root", default="") + ap.add_argument("--out", default="") + ap.add_argument("--paper", default="") + ap.add_argument("--task-set", default="") + ap.add_argument("--repo-id", default="lffbench/agent-replays") + ap.add_argument("--batches", default="") + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--shard", type=int, default=0) + ap.add_argument("--nshards", type=int, default=1) + ap.add_argument("--threads", type=int, default=2) + ap.add_argument("--vcodec", default="libsvtav1") + a = ap.parse_args() + {"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a) + + +if __name__ == "__main__": + main() diff --git a/leaf/code/remaining-lh-20261103-remaining_lh_auto_001_opus/lerobot_replay.py b/leaf/code/remaining-lh-20261103-remaining_lh_auto_001_opus/lerobot_replay.py new file mode 100644 index 0000000000000000000000000000000000000000..4c43a69bdb066327b27614bc9efda53d4a74e931 --- /dev/null +++ b/leaf/code/remaining-lh-20261103-remaining_lh_auto_001_opus/lerobot_replay.py @@ -0,0 +1,744 @@ +"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay +against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the +LeRobot export (scripts/lerobot_export.py). + + python scripts/lerobot_replay.py check [ ...] [--json out.json] # replay only, print fidelity + python scripts/lerobot_replay.py record --out [--res 256] + +Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot +commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite +is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly +like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same +outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width, +ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code +hashes equal the current files are expected to match (check_code()). + +Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB, +proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes: +protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode +per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the +fidelity check runs in record mode too. Per episode the recorder writes ///epNN/: + agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes) + frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase + sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel) + final_*.png, final.npz observation after the last control step (the state the outcome was judged in) + annotation.json episode annotation (build_annotation) +and ///replay.json (fidelity) when the whole run is done. +""" +import argparse +import ast +import hashlib +import importlib +import json +import math +import os +import pkgutil +import re +import shutil +import sys +import time +from collections import defaultdict + +import numpy as np + +LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, LFF_ROOT) + +from lffbench import envs # noqa: E402 +from lffbench import tasks as task_pkg # noqa: E402 +from lffbench.agent import camera as C # noqa: E402 +from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402 +from lffbench.task_base import TASKS # noqa: E402 + +for _m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{_m.name}") + +# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the +# task's outcome() check after `finish` (the arm holds still; not an agent action) +PHASES = {"move": 0, "gripper": 1, "judge": 2} +FPS = 20 +SCHEMA = "lff-replay-1" + +# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR" +ERROR_FLAGS = ("trap_fired", "recovered_in_attempt") +ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events", + "n_missed_strikes", "n_open_gripper_pushes") + + +def load_jsonl(p): + out = [] + if not os.path.exists(p): + return out + with open(p) as f: + for line in f: + line = line.strip() + if line: + try: + out.append(json.loads(line)) + except ValueError: + pass + return out + + +def norm_json(o): + return json.loads(json.dumps(o, default=_json_default)) + + +def sha256(p): + with open(p, "rb") as f: + return hashlib.sha256(f.read()).hexdigest() + + +def check_code(run_dir): + """[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract.""" + p = os.path.join(run_dir, "contract.json") + if not os.path.exists(p): + return [("contract.json", None, None)] + files = json.load(open(p))["contract"].get("server_code_files", {}) + bad = [] + for f, h in files.items(): + q = os.path.join(LFF_ROOT, f) + cur = sha256(q) if os.path.exists(q) else None + if cur != h: + bad.append((f, h, cur)) + return bad + + +def diff_json(a, b, path="", tol=0.0, out=None, limit=20): + """Differences between two JSON values (numbers compared with an absolute tolerance).""" + out = [] if out is None else out + if len(out) >= limit: + return out + if isinstance(a, dict) and isinstance(b, dict): + for k in sorted(set(a) | set(b)): + if k not in a or k not in b: + out.append((f"{path}.{k}", a.get(k, ""), b.get(k, ""))) + else: + diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit) + elif isinstance(a, list) and isinstance(b, list): + if len(a) != len(b): + out.append((path, f"len {len(a)}", f"len {len(b)}")) + else: + for i, (x, y) in enumerate(zip(a, b)): + diff_json(x, y, f"{path}[{i}]", tol, out, limit) + elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))): + if a != b: + out.append((path, a, b)) + elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))): + out.append((path, a, b)) + return out + + +def error_event(o): + """True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none.""" + if not isinstance(o, dict): + return None + keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o] + if not keys: + return None + return any(bool(o[k]) for k in ERROR_FLAGS if k in o) or any((o.get(k) or 0) > 0 for k in ERROR_COUNTS if k in o) + + +# ====================================================================================================== logs -> notes + +class RunLog: + """Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's + narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition.""" + + def __init__(self, run_dir, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run = os.path.basename(self.run_dir) + self.batch = os.path.basename(os.path.dirname(self.run_dir)) + self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl")) + self.start = next(e for e in self.ev if e["ev"] == "session_start") + self.calls, self.dones, self.harness_status = {}, [], [] + last = None + for e in self.ev: + if e["ev"] == "call": + self.calls[(int(e["attempt"]), int(e["step"]))] = e + last = e + elif e["ev"] == "done": + self.dones.append(e) + last = e + elif e["ev"] == "http" and last is not None and "think_s" not in last: + ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \ + (last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe")) + if ok: + last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s") + self.manifest = manifest or {} + self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {} + p = os.path.join(self.run_dir, "harness.json") + self.harness = json.load(open(p)) if os.path.exists(p) else {} + self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl")) + self._narration() + + # ---------------------------------------------------------------- agent narration + def _narration(self): + """notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one; + finish_notes[attempt] likewise for the agent's finish call; final_report = its last message.""" + self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", [] + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + attempt = 1 + + def take(): + nonlocal buf + out = {k: v for k, v in buf.items() if v} + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + return out + + last_msg = "" + for t in self.traj: + if t.get("kind") == "header": + self.headers.append(t.get("agent") or {}) + continue + if t.get("kind") != "step": + continue + if (t.get("message") or "").strip(): + buf["messages"].append(t["message"].strip()) + last_msg = t["message"].strip() + if (t.get("reasoning_content") or "").strip(): + buf["reasoning"].append(t["reasoning_content"].strip()) + res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])} + for c in t.get("tool_calls") or []: + fn, args = c.get("function_name"), c.get("arguments") or {} + if fn == "shell": + buf["shell"].append(str(args.get("command", ""))[:2000]) + elif fn == "view_images": + buf["viewed"].extend(args.get("paths") or []) + elif fn == "robot": + cmd = str(args.get("command", "")).strip() + r = res.get(c.get("tool_call_id")) or {} + try: + rep = json.loads(r.get("content") or "{}") + except ValueError: + rep = {} + word = cmd.split()[0] if cmd else "" + m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", ""))) + if word in ("move_eef", "observe") and m: + a, s = int(m.group(1)), int(m.group(2)) + n = take() + n["command"] = cmd + self.notes[(a, s)] = n + attempt = a + elif word in ("finish", "done"): + n = take() + n["command"] = cmd + n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)} + self.finish_notes.setdefault(attempt, n) + if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"): + attempt += 1 + # status / help / errors: their narration stays in the buffer for the next command + self.final_report = last_msg + + # ---------------------------------------------------------------- run-level labels + def attempts(self): + out = [] + for e in self.dones: + o = e.get("outcome") or {} + if isinstance(o, str): + try: + o = ast.literal_eval(o) + except (ValueError, SyntaxError): + o = {} + out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o, + reason=e.get("reason") or "")) + return sorted(out, key=lambda x: x["attempt"]) + + def condition(self): + s, en = self.start, self.entry + mem = s.get("memory", en.get("mem")) + chain = en.get("chain") + if mem == "full": + cond = "with_history" + elif chain: + cond = "memory_free_retry" + else: + cond = "independent_single_attempt" + return cond, chain + + def outcome_class(self): + """CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None.""" + att = self.attempts() + if not att or self.start.get("memory") != "full": + return None, "".join("S" if a["success"] else "F" for a in att) + hist = "".join("S" if a["success"] else "F" for a in att) + if att[0]["success"]: + ev = error_event(att[0]["outcome"]) + cls = "S?" if ev is None else ("IR" if ev else "CS") + else: + cls = "XR" if any(a["success"] for a in att) else "F" + return cls, hist + + def agent_info(self): + h, en = self.harness, self.entry + hdr = self.headers[0] if self.headers else {} + return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"), + harness_version=h.get("version") or hdr.get("version"), + harness_binary_sha256=(h.get("binary") or {}).get("sha256"), + model=h.get("model") or en.get("model") or hdr.get("model_name"), + effort=h.get("effort") or en.get("effort") or hdr.get("effort"), + provider=h.get("provider") or en.get("provider"), + codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"), + jail=en.get("jail")) + + +# ====================================================================================================== recording + +class EpisodeSink: + """Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed.""" + + def __init__(self, path): + self.path = path + os.makedirs(path, exist_ok=True) + self.w = None + self.num = defaultdict(list) + self.n = 0 + + def add(self, st, imgs): + import imageio + if self.w is None: + self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb", + pixelformat="rgb24", macro_block_size=1, + ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error") + for k in ("agentview", "wrist")] + for w, im in zip(self.w, imgs): + w.append_data(im) + for k, v in st.items(): + self.num[k].append(v) + self.n += 1 + + def close(self, final_state, final_imgs): + from PIL import Image + if self.w is not None: + for w in self.w: + w.close() + arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"} + np.savez(os.path.join(self.path, "frames.npz"), **arr) + if self.num.get("sim_state"): + np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64)) + np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()}) + for k, im in zip(("agentview", "wrist"), final_imgs): + Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png")) + + +class Recorder: + """Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink.""" + + def __init__(self, rp, res): + self.rp, self.res = rp, int(res) + self.active = False + self.sink = None + self.cur = dict(attempt=1, command=-1, phase=PHASES["move"]) + env = rp.task.env + self.env, self.rob = env, env.robots[0] + self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist")) + orig = env.step + + def step(a): + if self.active and self.sink is not None: + self.capture(np.asarray(a, np.float64)) + out = orig(a) + if self.active and self.sink is not None: + self.rp.poll_events(self.sink.n - 1) + return out + + env.step = step + + @property + def n(self): + return self.sink.n if self.sink is not None else 0 + + def state(self): + import robosuite.utils.transform_utils as T + env, rob = self.env, self.rob + d = env.sim.data + eef = np.array(d.site_xpos[rob.eef_site_id], np.float64) + q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw") + gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64) + try: + flat = np.asarray(env.sim.get_state().flatten(), np.float64) + except Exception: + flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64) + sk = self.rp.task.sk + return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64), + gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64), + joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64), + gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64), + eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)), + sim_time=np.float64(d.time), sim_state=flat) + + def images(self): + return [envs.render(self.env, c, self.res) for c in self.cams] + + def capture(self, a): + st = self.state() + st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]), + phase=np.int64(self.cur["phase"])) + self.sink.add(st, self.images()) + + +class RunReplay: + def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run_name = os.path.basename(self.run_dir) + self.log = RunLog(self.run_dir, manifest) + self.ev = self.log.ev + self.start = self.log.start + cp = os.path.join(self.run_dir, "contract.json") + self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {} + spec = self.contract.get("image_spec") or {} + self.image_res = int(spec.get("width", 512)) + self.code_diff = check_code(self.run_dir) + s = self.start + self.task = TASKS[s["task"]](cam_res=self.image_res) + inst = self.task.sample_instance(s["seed"]) + logged = s.get("inst") or {} + sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")}) + self.inst_diff = diff_json(sampled, logged, "inst") + if s.get("arm", "none") not in (None, "none") or logged.get("nominal"): + inst.update(logged) # controlled arms / nominal: the server overrode these instance fields + self.inst_diff = [] + self.inst = inst + self.protocol = getattr(self.task, "protocol", "cross") + self.k = int(s.get("k") or self.task.max_attempts) + self.attempt = 1 + self.mismatch = [] # (where, what, logged, replayed) + self.n_checked = 0 + self.max_dev_m = 0.0 + self.unfinished = None + self.rec = Recorder(self, res) if record else None + self.res = int(res) + self.out_root = out_root + self.n_mon = 0 + self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0 + self.episodes = [] # summaries of the written episodes + self.task.reset_instance(self.inst) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + sim = self.task.env.sim + bid = sim.model.body_name2id("robot0_base") + self.base_off = np.array(sim.data.body_xpos[bid], float).copy() + if self.rec: + self._open_episode() + + # ------------------------------------------------------------------ episodes + def _ep_dir(self): + return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}") + + def _open_episode(self): + self.rec.sink = EpisodeSink(self._ep_dir()) + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.rec.active = True + self.events, self.spans, self.ep_attempts = [], [], [] + self.ep_initial = self.rec.state() # state right after the reset (before frame 0) + + def close_episode(self): + if not self.rec: + self.ep_attempts = [] + return + sink = self.rec.sink + st = self.rec.state() + imgs = self.rec.images() + st.pop("sim_state", None) + sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs) + ann = build_annotation(self, sink) + with open(os.path.join(sink.path, "annotation.json"), "w") as f: + json.dump(ann, f, indent=1, default=_json_default) + self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n, + attempts=[a["attempt"] for a in self.ep_attempts])) + self.rec.active = False + self.rec.sink = None + self.ep_index += 1 + + # ------------------------------------------------------------------ monitor events (task-side error events) + def poll_events(self, frame): + mon = getattr(self.task, "mon", None) + evs = mon.get("events") if isinstance(mon, dict) else None + if not isinstance(evs, list): + return + if len(evs) < self.n_mon: # monitor was rebuilt + self.n_mon = 0 + for e in evs[self.n_mon:]: + self.events.append(dict(frame=int(frame), attempt=self.attempt, + event=norm_json(e) if isinstance(e, dict) else str(e))) + self.n_mon = len(evs) + + # ------------------------------------------------------------------ state as the server reports it + def proprio_la(self): + p = self.ex.proprio() + pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off] + return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"]) + + def compare(self, where, rep_logged, rep): + self.n_checked += 1 + for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"): + if k not in rep_logged or k not in rep: + continue + a, b = rep_logged[k], rep[k] + if k == "eef_pos": + dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float)))) + self.max_dev_m = max(self.max_dev_m, dev) + if dev > 1.5e-4: + self.mismatch.append((where, k, a, b)) + elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4): + self.mismatch.append((where, k, a, b)) + if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)): + self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok"))) + + def _span(self, e, f0, kind): + if self.rec: + self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0, + frame_end=self.rec.n)) + + # ------------------------------------------------------------------ commands (robot_server._handle_v2) + def move_eef(self, e): + args = e.get("args") or {} + where = f"a{e['attempt']}s{e['step']}" + logged = e.get("report") or {} + f0 = self.rec.n if self.rec else 0 + p = self.ex.proprio() + if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}: + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + off = self.base_off + try: + cur = np.asarray(p["eef_pos"], float) - off + tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")] + yaw = float(args.get("yaw", p["eef_yaw_deg"])) + speed = None if args.get("speed") in (None, "") else float(args["speed"]) + except (TypeError, ValueError): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + grip = args.get("gripper") + if grip not in (None, "open", "close"): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + moving = any(k in args for k in ("x", "y", "z", "yaw")) + tgt_w = np.asarray(tgt) + off + if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)): + self._span(e, f0, "rejected") + return self.compare(where, logged, dict(ok=False, **self.proprio_la())) + raw = {} + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"]) + if moving: + mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw) + if speed is not None: + mv["speed"] = speed + raw.update(self.ex.call("move_to", mv).report) + if grip is not None: + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"]) + raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report) + rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la()) + self.compare(where, logged, rep) + lr = e.get("raw") or {} + for k in ("holding_object", "touched_object"): + if k in lr and k in raw and bool(lr[k]) != bool(raw[k]): + self.mismatch.append((where, "raw." + k, lr[k], raw[k])) + self._span(e, f0, "move_eef") + + def observe(self, e): + f0 = self.rec.n if self.rec else 0 + self._span(e, f0, "observe") + + def done(self, e): + f0 = self.rec.n if self.rec else 0 + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"]) + out = self.task.outcome(self.inst) + succ = bool(out["success"]) + where = f"a{e['attempt']}done" + if succ != bool(e.get("success") in (True, "True")): + self.mismatch.append((where, "success", e.get("success"), succ)) + lo = e.get("outcome") or {} + ro = norm_json({k: v for k, v in out.items() if k != "feedback"}) + if isinstance(lo, dict): + for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8): + self.mismatch.append((where,) + d) + info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""), + feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")), + think_s=e.get("think_s")) + try: + info["feedback_f2"] = self.task.feedback(self.inst, out, "F2") + except Exception as ex_: + info["feedback_f2"] = f"" + if self.rec: + info["judge_frames"] = [f0, self.rec.n] + self.ep_attempts.append(info) + last = self.attempt >= self.k or succ or bool(out.get("terminal")) + if self.protocol == "cross" or last: + self.close_episode() + if last: + return True + self.attempt += 1 + if self.protocol == "cross": + self.task.reset_instance(self.inst) + self.n_mon = 0 + if self.rec: + self._open_episode() + elif self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + return False + + def run(self): + t0 = time.time() + finished = False + for e in self.ev: + if e["ev"] == "call": + if e.get("cmd") == "move_eef": + self.move_eef(e) + elif e.get("cmd") == "observe": + self.observe(e) + else: + self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None)) + elif e["ev"] == "done": + finished = self.done(e) + if finished: + break + self.unfinished = not finished + if not finished and self.rec and self.rec.sink is not None: + # the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged + if self.rec.n or self.ep_attempts: + self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True, + finish_reason="", feedback_shown="", auto_ended=False)) + self.close_episode() + else: + shutil.rmtree(self.rec.sink.path, ignore_errors=True) + self.rec.sink = None + self.wall_s = time.time() - t0 + return self + + def summary(self): + return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"], + protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff), + n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6), + unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1), + first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]]) + + +# ====================================================================================================== annotation + +def task_info(task, inst): + cls = type(task) + return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable", + category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"), + max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)), + instruction=cls.instruction) + + +def build_annotation(rp, sink): + """Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2 + failure description), run-level outcome class, every robot command with its frame span and the agent's narration, + task-side error events with frame indices.""" + log = rp.log + s = rp.start + cond, chain = log.condition() + cls, hist = log.outcome_class() + att_all = log.attempts() + attempts = [] + for a in rp.ep_attempts: + a = dict(a) + n = a["attempt"] + later = [x for x in att_all if x["attempt"] > n] + a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later)) + a["is_last_attempt_of_run"] = not later + fn = log.finish_notes.get(n) + if fn: + a["agent_finish"] = fn + a["error_event_in_attempt"] = error_event(a.get("outcome")) + attempts.append(a) + # post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command) + for a in attempts: + nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1]) + if a.get("success") is False and nxt: + note = log.notes[nxt[0]] + a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note} + commands = [] + for sp in rp.spans: + e = log.calls.get((sp["attempt"], sp["step"])) or {} + rep = e.get("report") or {} + c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"], + frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]), + args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"), + stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"), + gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"), + touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"), + agent_obs_images=rep.get("images")) + note = log.notes.get((sp["attempt"], sp["step"])) + if note: + c["agent_note"] = {k: v for k, v in note.items() if k != "command"} + commands.append(c) + t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x] + return dict( + schema=SCHEMA, + source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts], + episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain, + memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None), + feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"), + k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"), + contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256") + if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)), + agent=log.agent_info(), + task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"), + instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}), + run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all), + run_success=any(x["success"] for x in att_all) if att_all else None, + agent_final_report=log.final_report[:6000] or None, + mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)), + attempts=attempts, + commands=commands, + task_events=rp.events, + frames=dict(n=sink.n, fps=FPS, image_res=rp.res, + phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"], + joint_pos=rp.ep_initial["joint_pos"], + gripper_qpos=rp.ep_initial["gripper_qpos"])), + ) + + +# ====================================================================================================== CLI + +def load_manifest(run_dir): + p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json") + return json.load(open(p)) if os.path.exists(p) else {} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("mode", choices=["check", "record"]) + ap.add_argument("runs", nargs="+") + ap.add_argument("--json", default="") + ap.add_argument("--out", default="") + ap.add_argument("--res", type=int, default=256) + ap.add_argument("--force", action="store_true", help="record again even if replay.json exists") + a = ap.parse_args() + rows = [] + for r in a.runs: + r = r.rstrip("/") + try: + if a.mode == "check": + s = RunReplay(r, manifest=load_manifest(r)).run().summary() + else: + batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r) + rd = os.path.join(a.out, batch, name) + if os.path.exists(os.path.join(rd, "replay.json")) and not a.force: + print(json.dumps(dict(run=name, skipped="exists")), flush=True) + continue + shutil.rmtree(rd, ignore_errors=True) + rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run() + s = rp.summary() + s["episodes"] = rp.episodes + with open(os.path.join(rd, "replay.json"), "w") as f: + json.dump(s, f, indent=1) + except Exception: + import traceback + s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:]) + rows.append(s) + print(json.dumps(s), flush=True) + if a.json: + with open(a.json, "w") as f: + json.dump(rows, f, indent=1) + + +if __name__ == "__main__": + main() diff --git a/leaf/code/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lerobot_export.py b/leaf/code/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lerobot_export.py new file mode 100644 index 0000000000000000000000000000000000000000..fa4fa0a1be92844c9cf410663f77de5e200bda18 --- /dev/null +++ b/leaf/code/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lerobot_export.py @@ -0,0 +1,431 @@ +"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars. + +Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding +can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan): + + python scripts/lerobot_export.py plan --raw [,] --runs-root /runs/api \ + --paper --task-set /sets/main_v2_1inst.txt --work [--batches ...] [--limit N] + python scripts/lerobot_export.py shard --work --shard i --nshards N + python scripts/lerobot_export.py merge --work --nshards N --out + +Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0 +mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped. + +LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t): + observation.images.image agentview RGB 256x256 (upright; LIBERO naming) + observation.images.wrist_image wrist (eye-in-hand) RGB 256x256 + observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout) + observation.joint_pos / joint_vel 7 arm joints (rad, rad/s) + observation.eef_quat 4: xyzw; observation.gripper_width 1 (m) + action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad), + gripper (-1 open, +1 close) + annotation.attempt_index attempt (1-based) the frame belongs to + annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`) + annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action) + annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt + annotation.task_event number of task-monitor events (error / progress events) registered at this step +Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table), +runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state +per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/. +""" +import argparse +import glob +import json +import os +import re +import shutil +import time + +import numpy as np + +FPS = 20 +RES = 256 +BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke", + "cc_smoke", "cc_opus_smoke"] +BATCH_NOTES = { + "cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog", + "cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267", + "cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299", + "cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances", + "cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)", + "cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the " + "with-history continuation of failed runs is incomplete", + "cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early", + "cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt", + "cc_opus_smoke": "smoke test: single attempt", +} +PHASES = {"move": 0, "gripper": 1, "judge": 2} +CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)", + "L2": "disturbed state to restore (incl. damage the agent causes)", + "L3": "infeasible manipulation strategy (grasp / contact / tool must change)", + "L4": "misjudged geometry (size, shape, fit, hidden structure)", + "L5": "misjudged physics (mass distribution, friction, dynamics)"} + + +def features(): + vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]} + f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names} + i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None} + return { + "observation.images.image": vid(), + "observation.images.wrist_image": vid(), + "observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z", + "finger_qpos_left", "finger_qpos_right"]), + "observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]), + "observation.gripper_width": f32(1, ["width_m"]), + "action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y", + "eef_delta_rot_aa_z", "gripper_close"]), + "annotation.attempt_index": i64(), + "annotation.command_index": i64(), + "annotation.phase": i64(), + "annotation.attempt_success": i64(), + "annotation.task_event": i64(), + } + + +# ------------------------------------------------------------------------------------------------ paper metadata + +def _clean_tex(s): + s = re.sub(r"%.*", "", s) + for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"), + (r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"), + (r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"), + (r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"), + (r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]: + s = re.sub(a, b, s) + s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s) + s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s) + for _ in range(3): + s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\$([^$]*)\$", r"\1", s) + s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ") + s = re.sub(r"\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\\[a-zA-Z]+\*?", "", s) + return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip() + + +def paper_tasks(paper_dir): + """{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the + paper's task table and task appendix (empty if the paper sources are not there).""" + out = {} + if not paper_dir: + return out + app = os.path.join(paper_dir, "sections", "appendix_tasks.tex") + tab = os.path.join(paper_dir, "sections", "tab_tasks.tex") + if os.path.exists(app): + txt = open(app).read() + parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt) + for i in range(1, len(parts) - 1, 2): + if parts[i] != "\\paragraph{": + continue + body = parts[i + 1] + m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S) + if not m: + continue + name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip() + desc = _clean_tex(body[m.end():]) + out[code] = dict(name=name, cause=_clean_tex(cause), description=desc) + if os.path.exists(tab): + names = {v["name"].lower(): k for k, v in out.items()} + for line in open(tab): + cells = [c.strip() for c in line.split("&")] + if len(cells) != 6 or not cells[-1].endswith("\\\\"): + continue + nm = re.sub(r"\\contscene", "", cells[0]).strip().lower() + code = names.get(nm) + if not code: + continue + out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]), + repair_within_attempt=_clean_tex(cells[3]) == "yes", + oracle_first_attempt_pct=_clean_tex(cells[4]), + naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip())) + return out + + +# ------------------------------------------------------------------------------------------------ collection + +def manifest_status(runs_root, batch, run, cache={}): + if batch not in cache: + p = os.path.join(runs_root, batch, "manifest.json") + cache[batch] = json.load(open(p)) if os.path.exists(p) else {} + m = cache[batch] + for r in m.get("runs", []): + if r.get("run") == run: + return r.get("status", "?"), r + for r in m.get("superseded", []): + if r.get("run") == run: + return "superseded_" + str(r.get("status", "?")), r + return "not_in_manifest", {} + + +def collect(raw_roots, runs_root, batches, task_order): + """Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root.""" + eps, rejected, seen = [], [], set() + for root in raw_roots: + for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))): + rep = json.load(open(rj)) + batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"] + if (batches and batch not in batches) or (batch, run) in seen: + continue + seen.add((batch, run)) + ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff") + status, entry = manifest_status(runs_root, batch, run) + if not ok: + never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked") + rejected.append(dict(run=run, batch=batch, run_status=status, + reason="run never started (no contract, no robot command)" if never else + "replay does not reproduce the log (the log has gaps or the replay diverged)", + detail=rep.get("first_mismatches"))) + continue + for ep in rep.get("episodes", []): + d = os.path.join(root, ep["dir"]) + ann = json.load(open(os.path.join(d, "annotation.json"))) + judged = [a for a in ann["attempts"] if a.get("success") is not None] + if not judged or ep["n_frames"] == 0: + rejected.append(dict(run=run, batch=batch, episode=ep["dir"], + reason="no judged attempt" if not judged else "no frames")) + continue + ann["source"]["run_status"] = status + ann["source"]["manifest_id"] = entry.get("id") + ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"], + max_eef_dev_m=rep["max_eef_dev_m"]) + key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99), + {"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2), + ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"]) + eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann)) + eps.sort(key=lambda x: x["key"]) + return eps, rejected + + +# ------------------------------------------------------------------------------------------------ writing + +def frames_of(path): + import av + with av.open(path) as c: + for fr in c.decode(video=0): + yield fr.to_ndarray(format="rgb24") + + +def flat_row(i, ann, n, idx0): + s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"] + att = ann["attempts"] + a0 = att[0] + return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n, + batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"], + memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"), + episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att], + harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"), + effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"), + task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"), + category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"], + success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att], + feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att], + auto_ended=[a.get("auto_ended") for a in att], + corrected_later_in_run=[a.get("corrected_later_in_run") for a in att], + error_event_in_attempt=[a.get("error_event_in_attempt") for a in att], + run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"), + n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]), + first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None) + + +def cmd_plan(a): + task_order = {} + if a.task_set and os.path.exists(a.task_set): + for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")): + task_order[line.split(":")[0].strip()] = i + batches = [b for b in a.batches.split(",") if b] if a.batches else None + eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order) + if a.limit: + eps = eps[:a.limit] + paper = paper_tasks(a.paper) + idx0 = 0 + for i, e in enumerate(eps): + ann = e["ann"] + tname = ann["task"]["name"] + if tname in paper: + ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"} + ann["episode_index"] = i + ann["dataset_index_range"] = [idx0, idx0 + e["n"]] + e["index"], e["from"] = i, idx0 + idx0 += e["n"] + del e["key"] + os.makedirs(a.work, exist_ok=True) + with open(os.path.join(a.work, "plan.json"), "w") as f: + json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f, + ensure_ascii=False) + print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True) + + +def shard_range(n_eps, i, k): + return (n_eps * i) // k, (n_eps * (i + 1)) // k + + +def cmd_shard(a): + from lerobot.datasets.lerobot_dataset import LeRobotDataset + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + lo, hi = shard_range(len(eps), a.shard, a.nshards) + out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}") + if os.path.exists(os.path.join(out, "DONE")): + print(f"shard {a.shard}: done already", flush=True) + return + shutil.rmtree(out, ignore_errors=True) + ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out, + robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads, + vcodec=a.vcodec) + nfr = 0 + for e in eps[lo:hi]: + d, ann, n = e["dir"], e["ann"], e["n"] + fr = np.load(os.path.join(d, "frames.npz")) + assert len(fr["action"]) == n, d + succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]} + evc = np.zeros(n, np.int64) + for ev in ann["task_events"]: + if 0 <= ev["frame"] < n: + evc[ev["frame"]] += 1 + state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32) + instr = ann["task"]["instruction"] + k = 0 + for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))): + if k >= n: + break + ds.add_frame({ + "observation.images.image": img, "observation.images.wrist_image": wr, + "observation.state": state[k], + "observation.joint_pos": fr["joint_pos"][k].astype(np.float32), + "observation.joint_vel": fr["joint_vel"][k].astype(np.float32), + "observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32), + "observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32), + "action": fr["action"][k].astype(np.float32), + "annotation.attempt_index": np.array([fr["attempt"][k]], np.int64), + "annotation.command_index": np.array([fr["command"][k]], np.int64), + "annotation.phase": np.array([fr["phase"][k]], np.int64), + "annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64), + "annotation.task_event": np.array([evc[k]], np.int64), + "task": instr, + }) + k += 1 + if k != n: + raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames") + ds.save_episode() + nfr += n + ds.finalize() + shutil.rmtree(os.path.join(out, "images"), ignore_errors=True) + open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n") + print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True) + + +def cmd_merge(a): + from pathlib import Path + from lerobot.datasets.aggregate import aggregate_datasets + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + roots, ids = [], [] + for i in range(a.nshards): + lo, hi = shard_range(len(eps), i, a.nshards) + if hi <= lo: + continue + r = os.path.join(a.work, "shards", f"shard_{i:03d}") + if not os.path.exists(os.path.join(r, "DONE")): + raise SystemExit(f"shard {i} is not done") + roots.append(Path(r)) + ids.append(f"{plan['repo_id']}-shard{i:03d}") + if os.path.exists(a.out): + raise SystemExit(f"{a.out} exists; refusing to overwrite") + aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out)) + print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True) + write_sidecars(a, plan) + print(f"merge done in {time.time() - t0:.0f}s", flush=True) + + +def write_sidecars(a, plan): + eps, paper = plan["episodes"], plan["paper"] + lff = os.path.join(a.out, "lff") + for sub in ("annotations", "sim_state", "final", "code"): + os.makedirs(os.path.join(lff, sub), exist_ok=True) + rows, runs, tasks = [], {}, {} + for e in eps: + i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"] + name = f"episode_{i:06d}" + if os.path.exists(os.path.join(d, "sim_state.npy")): + shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy")) + shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz")) + for cam, key in (("agentview", "image"), ("wrist", "wrist_image")): + shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png")) + with open(os.path.join(lff, "annotations", name + ".json"), "w") as f: + json.dump(ann, f, indent=1, ensure_ascii=False) + rows.append(flat_row(i, ann, n, e["from"])) + tname = ann["task"]["name"] + rk = (ann["source"]["batch"], ann["source"]["run"]) + r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"), + run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"], + memory_free_chain_of=ann["source"].get("memory_free_chain_of"), + memory_free_rep=ann["source"].get("memory_free_rep"), task=tname, + seed=ann["task"]["seed"], model=ann["agent"].get("model"), + harness=ann["agent"].get("harness"), + harness_version=ann["agent"].get("harness_version"), + codex_catalog=ann["agent"].get("codex_catalog"), + outcome_class=ann["run_outcome"].get("outcome_class"), + attempt_history=ann["run_outcome"].get("attempt_history"), + agent_final_report=ann["run_outcome"].get("agent_final_report"), + episodes=[])) + for x in ann["attempts"]: + r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success"))) + if tname not in tasks: + tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")} + if tname in paper: + tasks[tname]["paper"] = paper[tname] + tasks[tname]["instances"] = {} + tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"] + # memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id) + by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")} + for r in runs.values(): + if r.get("memory_free_chain_of"): + r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"])) + for (b, rn), r in runs.items(): + r["memory_free_retries"] = sorted((x["run"] for x in runs.values() + if x["batch"] == b and x.get("memory_free_chain_of_run") == rn), + key=lambda q: runs[(b, q)].get("memory_free_rep") or 0) + with open(os.path.join(lff, "episodes.jsonl"), "w") as f: + for row in rows: + f.write(json.dumps(row, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "runs.jsonl"), "w") as f: + for r in runs.values(): + f.write(json.dumps(r, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "tasks.json"), "w") as f: + json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False) + with open(os.path.join(lff, "batches.json"), "w") as f: + json.dump(BATCH_NOTES, f, indent=1) + with open(os.path.join(lff, "rejected.json"), "w") as f: + json.dump(plan["rejected"], f, indent=1) + here = os.path.dirname(os.path.abspath(__file__)) + for s in ("lerobot_replay.py", "lerobot_export.py"): + shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("step", choices=["plan", "shard", "merge"]) + ap.add_argument("--work", required=True) + ap.add_argument("--raw", default="") + ap.add_argument("--runs-root", default="") + ap.add_argument("--out", default="") + ap.add_argument("--paper", default="") + ap.add_argument("--task-set", default="") + ap.add_argument("--repo-id", default="lffbench/agent-replays") + ap.add_argument("--batches", default="") + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--shard", type=int, default=0) + ap.add_argument("--nshards", type=int, default=1) + ap.add_argument("--threads", type=int, default=2) + ap.add_argument("--vcodec", default="libsvtav1") + a = ap.parse_args() + {"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a) + + +if __name__ == "__main__": + main() diff --git a/leaf/code/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lerobot_replay.py b/leaf/code/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lerobot_replay.py new file mode 100644 index 0000000000000000000000000000000000000000..4c43a69bdb066327b27614bc9efda53d4a74e931 --- /dev/null +++ b/leaf/code/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lerobot_replay.py @@ -0,0 +1,744 @@ +"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay +against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the +LeRobot export (scripts/lerobot_export.py). + + python scripts/lerobot_replay.py check [ ...] [--json out.json] # replay only, print fidelity + python scripts/lerobot_replay.py record --out [--res 256] + +Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot +commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite +is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly +like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same +outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width, +ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code +hashes equal the current files are expected to match (check_code()). + +Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB, +proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes: +protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode +per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the +fidelity check runs in record mode too. Per episode the recorder writes ///epNN/: + agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes) + frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase + sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel) + final_*.png, final.npz observation after the last control step (the state the outcome was judged in) + annotation.json episode annotation (build_annotation) +and ///replay.json (fidelity) when the whole run is done. +""" +import argparse +import ast +import hashlib +import importlib +import json +import math +import os +import pkgutil +import re +import shutil +import sys +import time +from collections import defaultdict + +import numpy as np + +LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, LFF_ROOT) + +from lffbench import envs # noqa: E402 +from lffbench import tasks as task_pkg # noqa: E402 +from lffbench.agent import camera as C # noqa: E402 +from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402 +from lffbench.task_base import TASKS # noqa: E402 + +for _m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{_m.name}") + +# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the +# task's outcome() check after `finish` (the arm holds still; not an agent action) +PHASES = {"move": 0, "gripper": 1, "judge": 2} +FPS = 20 +SCHEMA = "lff-replay-1" + +# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR" +ERROR_FLAGS = ("trap_fired", "recovered_in_attempt") +ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events", + "n_missed_strikes", "n_open_gripper_pushes") + + +def load_jsonl(p): + out = [] + if not os.path.exists(p): + return out + with open(p) as f: + for line in f: + line = line.strip() + if line: + try: + out.append(json.loads(line)) + except ValueError: + pass + return out + + +def norm_json(o): + return json.loads(json.dumps(o, default=_json_default)) + + +def sha256(p): + with open(p, "rb") as f: + return hashlib.sha256(f.read()).hexdigest() + + +def check_code(run_dir): + """[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract.""" + p = os.path.join(run_dir, "contract.json") + if not os.path.exists(p): + return [("contract.json", None, None)] + files = json.load(open(p))["contract"].get("server_code_files", {}) + bad = [] + for f, h in files.items(): + q = os.path.join(LFF_ROOT, f) + cur = sha256(q) if os.path.exists(q) else None + if cur != h: + bad.append((f, h, cur)) + return bad + + +def diff_json(a, b, path="", tol=0.0, out=None, limit=20): + """Differences between two JSON values (numbers compared with an absolute tolerance).""" + out = [] if out is None else out + if len(out) >= limit: + return out + if isinstance(a, dict) and isinstance(b, dict): + for k in sorted(set(a) | set(b)): + if k not in a or k not in b: + out.append((f"{path}.{k}", a.get(k, ""), b.get(k, ""))) + else: + diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit) + elif isinstance(a, list) and isinstance(b, list): + if len(a) != len(b): + out.append((path, f"len {len(a)}", f"len {len(b)}")) + else: + for i, (x, y) in enumerate(zip(a, b)): + diff_json(x, y, f"{path}[{i}]", tol, out, limit) + elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))): + if a != b: + out.append((path, a, b)) + elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))): + out.append((path, a, b)) + return out + + +def error_event(o): + """True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none.""" + if not isinstance(o, dict): + return None + keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o] + if not keys: + return None + return any(bool(o[k]) for k in ERROR_FLAGS if k in o) or any((o.get(k) or 0) > 0 for k in ERROR_COUNTS if k in o) + + +# ====================================================================================================== logs -> notes + +class RunLog: + """Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's + narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition.""" + + def __init__(self, run_dir, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run = os.path.basename(self.run_dir) + self.batch = os.path.basename(os.path.dirname(self.run_dir)) + self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl")) + self.start = next(e for e in self.ev if e["ev"] == "session_start") + self.calls, self.dones, self.harness_status = {}, [], [] + last = None + for e in self.ev: + if e["ev"] == "call": + self.calls[(int(e["attempt"]), int(e["step"]))] = e + last = e + elif e["ev"] == "done": + self.dones.append(e) + last = e + elif e["ev"] == "http" and last is not None and "think_s" not in last: + ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \ + (last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe")) + if ok: + last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s") + self.manifest = manifest or {} + self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {} + p = os.path.join(self.run_dir, "harness.json") + self.harness = json.load(open(p)) if os.path.exists(p) else {} + self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl")) + self._narration() + + # ---------------------------------------------------------------- agent narration + def _narration(self): + """notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one; + finish_notes[attempt] likewise for the agent's finish call; final_report = its last message.""" + self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", [] + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + attempt = 1 + + def take(): + nonlocal buf + out = {k: v for k, v in buf.items() if v} + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + return out + + last_msg = "" + for t in self.traj: + if t.get("kind") == "header": + self.headers.append(t.get("agent") or {}) + continue + if t.get("kind") != "step": + continue + if (t.get("message") or "").strip(): + buf["messages"].append(t["message"].strip()) + last_msg = t["message"].strip() + if (t.get("reasoning_content") or "").strip(): + buf["reasoning"].append(t["reasoning_content"].strip()) + res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])} + for c in t.get("tool_calls") or []: + fn, args = c.get("function_name"), c.get("arguments") or {} + if fn == "shell": + buf["shell"].append(str(args.get("command", ""))[:2000]) + elif fn == "view_images": + buf["viewed"].extend(args.get("paths") or []) + elif fn == "robot": + cmd = str(args.get("command", "")).strip() + r = res.get(c.get("tool_call_id")) or {} + try: + rep = json.loads(r.get("content") or "{}") + except ValueError: + rep = {} + word = cmd.split()[0] if cmd else "" + m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", ""))) + if word in ("move_eef", "observe") and m: + a, s = int(m.group(1)), int(m.group(2)) + n = take() + n["command"] = cmd + self.notes[(a, s)] = n + attempt = a + elif word in ("finish", "done"): + n = take() + n["command"] = cmd + n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)} + self.finish_notes.setdefault(attempt, n) + if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"): + attempt += 1 + # status / help / errors: their narration stays in the buffer for the next command + self.final_report = last_msg + + # ---------------------------------------------------------------- run-level labels + def attempts(self): + out = [] + for e in self.dones: + o = e.get("outcome") or {} + if isinstance(o, str): + try: + o = ast.literal_eval(o) + except (ValueError, SyntaxError): + o = {} + out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o, + reason=e.get("reason") or "")) + return sorted(out, key=lambda x: x["attempt"]) + + def condition(self): + s, en = self.start, self.entry + mem = s.get("memory", en.get("mem")) + chain = en.get("chain") + if mem == "full": + cond = "with_history" + elif chain: + cond = "memory_free_retry" + else: + cond = "independent_single_attempt" + return cond, chain + + def outcome_class(self): + """CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None.""" + att = self.attempts() + if not att or self.start.get("memory") != "full": + return None, "".join("S" if a["success"] else "F" for a in att) + hist = "".join("S" if a["success"] else "F" for a in att) + if att[0]["success"]: + ev = error_event(att[0]["outcome"]) + cls = "S?" if ev is None else ("IR" if ev else "CS") + else: + cls = "XR" if any(a["success"] for a in att) else "F" + return cls, hist + + def agent_info(self): + h, en = self.harness, self.entry + hdr = self.headers[0] if self.headers else {} + return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"), + harness_version=h.get("version") or hdr.get("version"), + harness_binary_sha256=(h.get("binary") or {}).get("sha256"), + model=h.get("model") or en.get("model") or hdr.get("model_name"), + effort=h.get("effort") or en.get("effort") or hdr.get("effort"), + provider=h.get("provider") or en.get("provider"), + codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"), + jail=en.get("jail")) + + +# ====================================================================================================== recording + +class EpisodeSink: + """Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed.""" + + def __init__(self, path): + self.path = path + os.makedirs(path, exist_ok=True) + self.w = None + self.num = defaultdict(list) + self.n = 0 + + def add(self, st, imgs): + import imageio + if self.w is None: + self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb", + pixelformat="rgb24", macro_block_size=1, + ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error") + for k in ("agentview", "wrist")] + for w, im in zip(self.w, imgs): + w.append_data(im) + for k, v in st.items(): + self.num[k].append(v) + self.n += 1 + + def close(self, final_state, final_imgs): + from PIL import Image + if self.w is not None: + for w in self.w: + w.close() + arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"} + np.savez(os.path.join(self.path, "frames.npz"), **arr) + if self.num.get("sim_state"): + np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64)) + np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()}) + for k, im in zip(("agentview", "wrist"), final_imgs): + Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png")) + + +class Recorder: + """Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink.""" + + def __init__(self, rp, res): + self.rp, self.res = rp, int(res) + self.active = False + self.sink = None + self.cur = dict(attempt=1, command=-1, phase=PHASES["move"]) + env = rp.task.env + self.env, self.rob = env, env.robots[0] + self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist")) + orig = env.step + + def step(a): + if self.active and self.sink is not None: + self.capture(np.asarray(a, np.float64)) + out = orig(a) + if self.active and self.sink is not None: + self.rp.poll_events(self.sink.n - 1) + return out + + env.step = step + + @property + def n(self): + return self.sink.n if self.sink is not None else 0 + + def state(self): + import robosuite.utils.transform_utils as T + env, rob = self.env, self.rob + d = env.sim.data + eef = np.array(d.site_xpos[rob.eef_site_id], np.float64) + q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw") + gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64) + try: + flat = np.asarray(env.sim.get_state().flatten(), np.float64) + except Exception: + flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64) + sk = self.rp.task.sk + return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64), + gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64), + joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64), + gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64), + eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)), + sim_time=np.float64(d.time), sim_state=flat) + + def images(self): + return [envs.render(self.env, c, self.res) for c in self.cams] + + def capture(self, a): + st = self.state() + st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]), + phase=np.int64(self.cur["phase"])) + self.sink.add(st, self.images()) + + +class RunReplay: + def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run_name = os.path.basename(self.run_dir) + self.log = RunLog(self.run_dir, manifest) + self.ev = self.log.ev + self.start = self.log.start + cp = os.path.join(self.run_dir, "contract.json") + self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {} + spec = self.contract.get("image_spec") or {} + self.image_res = int(spec.get("width", 512)) + self.code_diff = check_code(self.run_dir) + s = self.start + self.task = TASKS[s["task"]](cam_res=self.image_res) + inst = self.task.sample_instance(s["seed"]) + logged = s.get("inst") or {} + sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")}) + self.inst_diff = diff_json(sampled, logged, "inst") + if s.get("arm", "none") not in (None, "none") or logged.get("nominal"): + inst.update(logged) # controlled arms / nominal: the server overrode these instance fields + self.inst_diff = [] + self.inst = inst + self.protocol = getattr(self.task, "protocol", "cross") + self.k = int(s.get("k") or self.task.max_attempts) + self.attempt = 1 + self.mismatch = [] # (where, what, logged, replayed) + self.n_checked = 0 + self.max_dev_m = 0.0 + self.unfinished = None + self.rec = Recorder(self, res) if record else None + self.res = int(res) + self.out_root = out_root + self.n_mon = 0 + self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0 + self.episodes = [] # summaries of the written episodes + self.task.reset_instance(self.inst) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + sim = self.task.env.sim + bid = sim.model.body_name2id("robot0_base") + self.base_off = np.array(sim.data.body_xpos[bid], float).copy() + if self.rec: + self._open_episode() + + # ------------------------------------------------------------------ episodes + def _ep_dir(self): + return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}") + + def _open_episode(self): + self.rec.sink = EpisodeSink(self._ep_dir()) + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.rec.active = True + self.events, self.spans, self.ep_attempts = [], [], [] + self.ep_initial = self.rec.state() # state right after the reset (before frame 0) + + def close_episode(self): + if not self.rec: + self.ep_attempts = [] + return + sink = self.rec.sink + st = self.rec.state() + imgs = self.rec.images() + st.pop("sim_state", None) + sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs) + ann = build_annotation(self, sink) + with open(os.path.join(sink.path, "annotation.json"), "w") as f: + json.dump(ann, f, indent=1, default=_json_default) + self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n, + attempts=[a["attempt"] for a in self.ep_attempts])) + self.rec.active = False + self.rec.sink = None + self.ep_index += 1 + + # ------------------------------------------------------------------ monitor events (task-side error events) + def poll_events(self, frame): + mon = getattr(self.task, "mon", None) + evs = mon.get("events") if isinstance(mon, dict) else None + if not isinstance(evs, list): + return + if len(evs) < self.n_mon: # monitor was rebuilt + self.n_mon = 0 + for e in evs[self.n_mon:]: + self.events.append(dict(frame=int(frame), attempt=self.attempt, + event=norm_json(e) if isinstance(e, dict) else str(e))) + self.n_mon = len(evs) + + # ------------------------------------------------------------------ state as the server reports it + def proprio_la(self): + p = self.ex.proprio() + pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off] + return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"]) + + def compare(self, where, rep_logged, rep): + self.n_checked += 1 + for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"): + if k not in rep_logged or k not in rep: + continue + a, b = rep_logged[k], rep[k] + if k == "eef_pos": + dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float)))) + self.max_dev_m = max(self.max_dev_m, dev) + if dev > 1.5e-4: + self.mismatch.append((where, k, a, b)) + elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4): + self.mismatch.append((where, k, a, b)) + if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)): + self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok"))) + + def _span(self, e, f0, kind): + if self.rec: + self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0, + frame_end=self.rec.n)) + + # ------------------------------------------------------------------ commands (robot_server._handle_v2) + def move_eef(self, e): + args = e.get("args") or {} + where = f"a{e['attempt']}s{e['step']}" + logged = e.get("report") or {} + f0 = self.rec.n if self.rec else 0 + p = self.ex.proprio() + if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}: + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + off = self.base_off + try: + cur = np.asarray(p["eef_pos"], float) - off + tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")] + yaw = float(args.get("yaw", p["eef_yaw_deg"])) + speed = None if args.get("speed") in (None, "") else float(args["speed"]) + except (TypeError, ValueError): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + grip = args.get("gripper") + if grip not in (None, "open", "close"): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + moving = any(k in args for k in ("x", "y", "z", "yaw")) + tgt_w = np.asarray(tgt) + off + if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)): + self._span(e, f0, "rejected") + return self.compare(where, logged, dict(ok=False, **self.proprio_la())) + raw = {} + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"]) + if moving: + mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw) + if speed is not None: + mv["speed"] = speed + raw.update(self.ex.call("move_to", mv).report) + if grip is not None: + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"]) + raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report) + rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la()) + self.compare(where, logged, rep) + lr = e.get("raw") or {} + for k in ("holding_object", "touched_object"): + if k in lr and k in raw and bool(lr[k]) != bool(raw[k]): + self.mismatch.append((where, "raw." + k, lr[k], raw[k])) + self._span(e, f0, "move_eef") + + def observe(self, e): + f0 = self.rec.n if self.rec else 0 + self._span(e, f0, "observe") + + def done(self, e): + f0 = self.rec.n if self.rec else 0 + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"]) + out = self.task.outcome(self.inst) + succ = bool(out["success"]) + where = f"a{e['attempt']}done" + if succ != bool(e.get("success") in (True, "True")): + self.mismatch.append((where, "success", e.get("success"), succ)) + lo = e.get("outcome") or {} + ro = norm_json({k: v for k, v in out.items() if k != "feedback"}) + if isinstance(lo, dict): + for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8): + self.mismatch.append((where,) + d) + info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""), + feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")), + think_s=e.get("think_s")) + try: + info["feedback_f2"] = self.task.feedback(self.inst, out, "F2") + except Exception as ex_: + info["feedback_f2"] = f"" + if self.rec: + info["judge_frames"] = [f0, self.rec.n] + self.ep_attempts.append(info) + last = self.attempt >= self.k or succ or bool(out.get("terminal")) + if self.protocol == "cross" or last: + self.close_episode() + if last: + return True + self.attempt += 1 + if self.protocol == "cross": + self.task.reset_instance(self.inst) + self.n_mon = 0 + if self.rec: + self._open_episode() + elif self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + return False + + def run(self): + t0 = time.time() + finished = False + for e in self.ev: + if e["ev"] == "call": + if e.get("cmd") == "move_eef": + self.move_eef(e) + elif e.get("cmd") == "observe": + self.observe(e) + else: + self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None)) + elif e["ev"] == "done": + finished = self.done(e) + if finished: + break + self.unfinished = not finished + if not finished and self.rec and self.rec.sink is not None: + # the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged + if self.rec.n or self.ep_attempts: + self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True, + finish_reason="", feedback_shown="", auto_ended=False)) + self.close_episode() + else: + shutil.rmtree(self.rec.sink.path, ignore_errors=True) + self.rec.sink = None + self.wall_s = time.time() - t0 + return self + + def summary(self): + return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"], + protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff), + n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6), + unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1), + first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]]) + + +# ====================================================================================================== annotation + +def task_info(task, inst): + cls = type(task) + return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable", + category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"), + max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)), + instruction=cls.instruction) + + +def build_annotation(rp, sink): + """Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2 + failure description), run-level outcome class, every robot command with its frame span and the agent's narration, + task-side error events with frame indices.""" + log = rp.log + s = rp.start + cond, chain = log.condition() + cls, hist = log.outcome_class() + att_all = log.attempts() + attempts = [] + for a in rp.ep_attempts: + a = dict(a) + n = a["attempt"] + later = [x for x in att_all if x["attempt"] > n] + a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later)) + a["is_last_attempt_of_run"] = not later + fn = log.finish_notes.get(n) + if fn: + a["agent_finish"] = fn + a["error_event_in_attempt"] = error_event(a.get("outcome")) + attempts.append(a) + # post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command) + for a in attempts: + nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1]) + if a.get("success") is False and nxt: + note = log.notes[nxt[0]] + a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note} + commands = [] + for sp in rp.spans: + e = log.calls.get((sp["attempt"], sp["step"])) or {} + rep = e.get("report") or {} + c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"], + frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]), + args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"), + stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"), + gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"), + touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"), + agent_obs_images=rep.get("images")) + note = log.notes.get((sp["attempt"], sp["step"])) + if note: + c["agent_note"] = {k: v for k, v in note.items() if k != "command"} + commands.append(c) + t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x] + return dict( + schema=SCHEMA, + source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts], + episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain, + memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None), + feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"), + k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"), + contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256") + if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)), + agent=log.agent_info(), + task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"), + instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}), + run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all), + run_success=any(x["success"] for x in att_all) if att_all else None, + agent_final_report=log.final_report[:6000] or None, + mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)), + attempts=attempts, + commands=commands, + task_events=rp.events, + frames=dict(n=sink.n, fps=FPS, image_res=rp.res, + phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"], + joint_pos=rp.ep_initial["joint_pos"], + gripper_qpos=rp.ep_initial["gripper_qpos"])), + ) + + +# ====================================================================================================== CLI + +def load_manifest(run_dir): + p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json") + return json.load(open(p)) if os.path.exists(p) else {} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("mode", choices=["check", "record"]) + ap.add_argument("runs", nargs="+") + ap.add_argument("--json", default="") + ap.add_argument("--out", default="") + ap.add_argument("--res", type=int, default=256) + ap.add_argument("--force", action="store_true", help="record again even if replay.json exists") + a = ap.parse_args() + rows = [] + for r in a.runs: + r = r.rstrip("/") + try: + if a.mode == "check": + s = RunReplay(r, manifest=load_manifest(r)).run().summary() + else: + batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r) + rd = os.path.join(a.out, batch, name) + if os.path.exists(os.path.join(rd, "replay.json")) and not a.force: + print(json.dumps(dict(run=name, skipped="exists")), flush=True) + continue + shutil.rmtree(rd, ignore_errors=True) + rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run() + s = rp.summary() + s["episodes"] = rp.episodes + with open(os.path.join(rd, "replay.json"), "w") as f: + json.dump(s, f, indent=1) + except Exception: + import traceback + s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:]) + rows.append(s) + print(json.dumps(s), flush=True) + if a.json: + with open(a.json, "w") as f: + json.dump(rows, f, indent=1) + + +if __name__ == "__main__": + main() diff --git a/leaf/code/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lerobot_export.py b/leaf/code/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lerobot_export.py new file mode 100644 index 0000000000000000000000000000000000000000..fa4fa0a1be92844c9cf410663f77de5e200bda18 --- /dev/null +++ b/leaf/code/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lerobot_export.py @@ -0,0 +1,431 @@ +"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars. + +Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding +can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan): + + python scripts/lerobot_export.py plan --raw [,] --runs-root /runs/api \ + --paper --task-set /sets/main_v2_1inst.txt --work [--batches ...] [--limit N] + python scripts/lerobot_export.py shard --work --shard i --nshards N + python scripts/lerobot_export.py merge --work --nshards N --out + +Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0 +mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped. + +LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t): + observation.images.image agentview RGB 256x256 (upright; LIBERO naming) + observation.images.wrist_image wrist (eye-in-hand) RGB 256x256 + observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout) + observation.joint_pos / joint_vel 7 arm joints (rad, rad/s) + observation.eef_quat 4: xyzw; observation.gripper_width 1 (m) + action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad), + gripper (-1 open, +1 close) + annotation.attempt_index attempt (1-based) the frame belongs to + annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`) + annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action) + annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt + annotation.task_event number of task-monitor events (error / progress events) registered at this step +Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table), +runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state +per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/. +""" +import argparse +import glob +import json +import os +import re +import shutil +import time + +import numpy as np + +FPS = 20 +RES = 256 +BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke", + "cc_smoke", "cc_opus_smoke"] +BATCH_NOTES = { + "cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog", + "cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267", + "cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299", + "cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances", + "cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)", + "cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the " + "with-history continuation of failed runs is incomplete", + "cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early", + "cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt", + "cc_opus_smoke": "smoke test: single attempt", +} +PHASES = {"move": 0, "gripper": 1, "judge": 2} +CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)", + "L2": "disturbed state to restore (incl. damage the agent causes)", + "L3": "infeasible manipulation strategy (grasp / contact / tool must change)", + "L4": "misjudged geometry (size, shape, fit, hidden structure)", + "L5": "misjudged physics (mass distribution, friction, dynamics)"} + + +def features(): + vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]} + f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names} + i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None} + return { + "observation.images.image": vid(), + "observation.images.wrist_image": vid(), + "observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z", + "finger_qpos_left", "finger_qpos_right"]), + "observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]), + "observation.gripper_width": f32(1, ["width_m"]), + "action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y", + "eef_delta_rot_aa_z", "gripper_close"]), + "annotation.attempt_index": i64(), + "annotation.command_index": i64(), + "annotation.phase": i64(), + "annotation.attempt_success": i64(), + "annotation.task_event": i64(), + } + + +# ------------------------------------------------------------------------------------------------ paper metadata + +def _clean_tex(s): + s = re.sub(r"%.*", "", s) + for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"), + (r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"), + (r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"), + (r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"), + (r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]: + s = re.sub(a, b, s) + s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s) + s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s) + for _ in range(3): + s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\$([^$]*)\$", r"\1", s) + s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ") + s = re.sub(r"\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\\[a-zA-Z]+\*?", "", s) + return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip() + + +def paper_tasks(paper_dir): + """{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the + paper's task table and task appendix (empty if the paper sources are not there).""" + out = {} + if not paper_dir: + return out + app = os.path.join(paper_dir, "sections", "appendix_tasks.tex") + tab = os.path.join(paper_dir, "sections", "tab_tasks.tex") + if os.path.exists(app): + txt = open(app).read() + parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt) + for i in range(1, len(parts) - 1, 2): + if parts[i] != "\\paragraph{": + continue + body = parts[i + 1] + m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S) + if not m: + continue + name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip() + desc = _clean_tex(body[m.end():]) + out[code] = dict(name=name, cause=_clean_tex(cause), description=desc) + if os.path.exists(tab): + names = {v["name"].lower(): k for k, v in out.items()} + for line in open(tab): + cells = [c.strip() for c in line.split("&")] + if len(cells) != 6 or not cells[-1].endswith("\\\\"): + continue + nm = re.sub(r"\\contscene", "", cells[0]).strip().lower() + code = names.get(nm) + if not code: + continue + out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]), + repair_within_attempt=_clean_tex(cells[3]) == "yes", + oracle_first_attempt_pct=_clean_tex(cells[4]), + naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip())) + return out + + +# ------------------------------------------------------------------------------------------------ collection + +def manifest_status(runs_root, batch, run, cache={}): + if batch not in cache: + p = os.path.join(runs_root, batch, "manifest.json") + cache[batch] = json.load(open(p)) if os.path.exists(p) else {} + m = cache[batch] + for r in m.get("runs", []): + if r.get("run") == run: + return r.get("status", "?"), r + for r in m.get("superseded", []): + if r.get("run") == run: + return "superseded_" + str(r.get("status", "?")), r + return "not_in_manifest", {} + + +def collect(raw_roots, runs_root, batches, task_order): + """Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root.""" + eps, rejected, seen = [], [], set() + for root in raw_roots: + for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))): + rep = json.load(open(rj)) + batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"] + if (batches and batch not in batches) or (batch, run) in seen: + continue + seen.add((batch, run)) + ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff") + status, entry = manifest_status(runs_root, batch, run) + if not ok: + never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked") + rejected.append(dict(run=run, batch=batch, run_status=status, + reason="run never started (no contract, no robot command)" if never else + "replay does not reproduce the log (the log has gaps or the replay diverged)", + detail=rep.get("first_mismatches"))) + continue + for ep in rep.get("episodes", []): + d = os.path.join(root, ep["dir"]) + ann = json.load(open(os.path.join(d, "annotation.json"))) + judged = [a for a in ann["attempts"] if a.get("success") is not None] + if not judged or ep["n_frames"] == 0: + rejected.append(dict(run=run, batch=batch, episode=ep["dir"], + reason="no judged attempt" if not judged else "no frames")) + continue + ann["source"]["run_status"] = status + ann["source"]["manifest_id"] = entry.get("id") + ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"], + max_eef_dev_m=rep["max_eef_dev_m"]) + key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99), + {"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2), + ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"]) + eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann)) + eps.sort(key=lambda x: x["key"]) + return eps, rejected + + +# ------------------------------------------------------------------------------------------------ writing + +def frames_of(path): + import av + with av.open(path) as c: + for fr in c.decode(video=0): + yield fr.to_ndarray(format="rgb24") + + +def flat_row(i, ann, n, idx0): + s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"] + att = ann["attempts"] + a0 = att[0] + return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n, + batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"], + memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"), + episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att], + harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"), + effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"), + task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"), + category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"], + success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att], + feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att], + auto_ended=[a.get("auto_ended") for a in att], + corrected_later_in_run=[a.get("corrected_later_in_run") for a in att], + error_event_in_attempt=[a.get("error_event_in_attempt") for a in att], + run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"), + n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]), + first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None) + + +def cmd_plan(a): + task_order = {} + if a.task_set and os.path.exists(a.task_set): + for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")): + task_order[line.split(":")[0].strip()] = i + batches = [b for b in a.batches.split(",") if b] if a.batches else None + eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order) + if a.limit: + eps = eps[:a.limit] + paper = paper_tasks(a.paper) + idx0 = 0 + for i, e in enumerate(eps): + ann = e["ann"] + tname = ann["task"]["name"] + if tname in paper: + ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"} + ann["episode_index"] = i + ann["dataset_index_range"] = [idx0, idx0 + e["n"]] + e["index"], e["from"] = i, idx0 + idx0 += e["n"] + del e["key"] + os.makedirs(a.work, exist_ok=True) + with open(os.path.join(a.work, "plan.json"), "w") as f: + json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f, + ensure_ascii=False) + print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True) + + +def shard_range(n_eps, i, k): + return (n_eps * i) // k, (n_eps * (i + 1)) // k + + +def cmd_shard(a): + from lerobot.datasets.lerobot_dataset import LeRobotDataset + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + lo, hi = shard_range(len(eps), a.shard, a.nshards) + out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}") + if os.path.exists(os.path.join(out, "DONE")): + print(f"shard {a.shard}: done already", flush=True) + return + shutil.rmtree(out, ignore_errors=True) + ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out, + robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads, + vcodec=a.vcodec) + nfr = 0 + for e in eps[lo:hi]: + d, ann, n = e["dir"], e["ann"], e["n"] + fr = np.load(os.path.join(d, "frames.npz")) + assert len(fr["action"]) == n, d + succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]} + evc = np.zeros(n, np.int64) + for ev in ann["task_events"]: + if 0 <= ev["frame"] < n: + evc[ev["frame"]] += 1 + state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32) + instr = ann["task"]["instruction"] + k = 0 + for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))): + if k >= n: + break + ds.add_frame({ + "observation.images.image": img, "observation.images.wrist_image": wr, + "observation.state": state[k], + "observation.joint_pos": fr["joint_pos"][k].astype(np.float32), + "observation.joint_vel": fr["joint_vel"][k].astype(np.float32), + "observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32), + "observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32), + "action": fr["action"][k].astype(np.float32), + "annotation.attempt_index": np.array([fr["attempt"][k]], np.int64), + "annotation.command_index": np.array([fr["command"][k]], np.int64), + "annotation.phase": np.array([fr["phase"][k]], np.int64), + "annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64), + "annotation.task_event": np.array([evc[k]], np.int64), + "task": instr, + }) + k += 1 + if k != n: + raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames") + ds.save_episode() + nfr += n + ds.finalize() + shutil.rmtree(os.path.join(out, "images"), ignore_errors=True) + open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n") + print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True) + + +def cmd_merge(a): + from pathlib import Path + from lerobot.datasets.aggregate import aggregate_datasets + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + roots, ids = [], [] + for i in range(a.nshards): + lo, hi = shard_range(len(eps), i, a.nshards) + if hi <= lo: + continue + r = os.path.join(a.work, "shards", f"shard_{i:03d}") + if not os.path.exists(os.path.join(r, "DONE")): + raise SystemExit(f"shard {i} is not done") + roots.append(Path(r)) + ids.append(f"{plan['repo_id']}-shard{i:03d}") + if os.path.exists(a.out): + raise SystemExit(f"{a.out} exists; refusing to overwrite") + aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out)) + print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True) + write_sidecars(a, plan) + print(f"merge done in {time.time() - t0:.0f}s", flush=True) + + +def write_sidecars(a, plan): + eps, paper = plan["episodes"], plan["paper"] + lff = os.path.join(a.out, "lff") + for sub in ("annotations", "sim_state", "final", "code"): + os.makedirs(os.path.join(lff, sub), exist_ok=True) + rows, runs, tasks = [], {}, {} + for e in eps: + i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"] + name = f"episode_{i:06d}" + if os.path.exists(os.path.join(d, "sim_state.npy")): + shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy")) + shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz")) + for cam, key in (("agentview", "image"), ("wrist", "wrist_image")): + shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png")) + with open(os.path.join(lff, "annotations", name + ".json"), "w") as f: + json.dump(ann, f, indent=1, ensure_ascii=False) + rows.append(flat_row(i, ann, n, e["from"])) + tname = ann["task"]["name"] + rk = (ann["source"]["batch"], ann["source"]["run"]) + r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"), + run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"], + memory_free_chain_of=ann["source"].get("memory_free_chain_of"), + memory_free_rep=ann["source"].get("memory_free_rep"), task=tname, + seed=ann["task"]["seed"], model=ann["agent"].get("model"), + harness=ann["agent"].get("harness"), + harness_version=ann["agent"].get("harness_version"), + codex_catalog=ann["agent"].get("codex_catalog"), + outcome_class=ann["run_outcome"].get("outcome_class"), + attempt_history=ann["run_outcome"].get("attempt_history"), + agent_final_report=ann["run_outcome"].get("agent_final_report"), + episodes=[])) + for x in ann["attempts"]: + r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success"))) + if tname not in tasks: + tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")} + if tname in paper: + tasks[tname]["paper"] = paper[tname] + tasks[tname]["instances"] = {} + tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"] + # memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id) + by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")} + for r in runs.values(): + if r.get("memory_free_chain_of"): + r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"])) + for (b, rn), r in runs.items(): + r["memory_free_retries"] = sorted((x["run"] for x in runs.values() + if x["batch"] == b and x.get("memory_free_chain_of_run") == rn), + key=lambda q: runs[(b, q)].get("memory_free_rep") or 0) + with open(os.path.join(lff, "episodes.jsonl"), "w") as f: + for row in rows: + f.write(json.dumps(row, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "runs.jsonl"), "w") as f: + for r in runs.values(): + f.write(json.dumps(r, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "tasks.json"), "w") as f: + json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False) + with open(os.path.join(lff, "batches.json"), "w") as f: + json.dump(BATCH_NOTES, f, indent=1) + with open(os.path.join(lff, "rejected.json"), "w") as f: + json.dump(plan["rejected"], f, indent=1) + here = os.path.dirname(os.path.abspath(__file__)) + for s in ("lerobot_replay.py", "lerobot_export.py"): + shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("step", choices=["plan", "shard", "merge"]) + ap.add_argument("--work", required=True) + ap.add_argument("--raw", default="") + ap.add_argument("--runs-root", default="") + ap.add_argument("--out", default="") + ap.add_argument("--paper", default="") + ap.add_argument("--task-set", default="") + ap.add_argument("--repo-id", default="lffbench/agent-replays") + ap.add_argument("--batches", default="") + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--shard", type=int, default=0) + ap.add_argument("--nshards", type=int, default=1) + ap.add_argument("--threads", type=int, default=2) + ap.add_argument("--vcodec", default="libsvtav1") + a = ap.parse_args() + {"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a) + + +if __name__ == "__main__": + main() diff --git a/leaf/code/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lerobot_replay.py b/leaf/code/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lerobot_replay.py new file mode 100644 index 0000000000000000000000000000000000000000..4c43a69bdb066327b27614bc9efda53d4a74e931 --- /dev/null +++ b/leaf/code/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lerobot_replay.py @@ -0,0 +1,744 @@ +"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay +against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the +LeRobot export (scripts/lerobot_export.py). + + python scripts/lerobot_replay.py check [ ...] [--json out.json] # replay only, print fidelity + python scripts/lerobot_replay.py record --out [--res 256] + +Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot +commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite +is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly +like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same +outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width, +ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code +hashes equal the current files are expected to match (check_code()). + +Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB, +proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes: +protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode +per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the +fidelity check runs in record mode too. Per episode the recorder writes ///epNN/: + agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes) + frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase + sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel) + final_*.png, final.npz observation after the last control step (the state the outcome was judged in) + annotation.json episode annotation (build_annotation) +and ///replay.json (fidelity) when the whole run is done. +""" +import argparse +import ast +import hashlib +import importlib +import json +import math +import os +import pkgutil +import re +import shutil +import sys +import time +from collections import defaultdict + +import numpy as np + +LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, LFF_ROOT) + +from lffbench import envs # noqa: E402 +from lffbench import tasks as task_pkg # noqa: E402 +from lffbench.agent import camera as C # noqa: E402 +from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402 +from lffbench.task_base import TASKS # noqa: E402 + +for _m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{_m.name}") + +# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the +# task's outcome() check after `finish` (the arm holds still; not an agent action) +PHASES = {"move": 0, "gripper": 1, "judge": 2} +FPS = 20 +SCHEMA = "lff-replay-1" + +# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR" +ERROR_FLAGS = ("trap_fired", "recovered_in_attempt") +ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events", + "n_missed_strikes", "n_open_gripper_pushes") + + +def load_jsonl(p): + out = [] + if not os.path.exists(p): + return out + with open(p) as f: + for line in f: + line = line.strip() + if line: + try: + out.append(json.loads(line)) + except ValueError: + pass + return out + + +def norm_json(o): + return json.loads(json.dumps(o, default=_json_default)) + + +def sha256(p): + with open(p, "rb") as f: + return hashlib.sha256(f.read()).hexdigest() + + +def check_code(run_dir): + """[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract.""" + p = os.path.join(run_dir, "contract.json") + if not os.path.exists(p): + return [("contract.json", None, None)] + files = json.load(open(p))["contract"].get("server_code_files", {}) + bad = [] + for f, h in files.items(): + q = os.path.join(LFF_ROOT, f) + cur = sha256(q) if os.path.exists(q) else None + if cur != h: + bad.append((f, h, cur)) + return bad + + +def diff_json(a, b, path="", tol=0.0, out=None, limit=20): + """Differences between two JSON values (numbers compared with an absolute tolerance).""" + out = [] if out is None else out + if len(out) >= limit: + return out + if isinstance(a, dict) and isinstance(b, dict): + for k in sorted(set(a) | set(b)): + if k not in a or k not in b: + out.append((f"{path}.{k}", a.get(k, ""), b.get(k, ""))) + else: + diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit) + elif isinstance(a, list) and isinstance(b, list): + if len(a) != len(b): + out.append((path, f"len {len(a)}", f"len {len(b)}")) + else: + for i, (x, y) in enumerate(zip(a, b)): + diff_json(x, y, f"{path}[{i}]", tol, out, limit) + elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))): + if a != b: + out.append((path, a, b)) + elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))): + out.append((path, a, b)) + return out + + +def error_event(o): + """True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none.""" + if not isinstance(o, dict): + return None + keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o] + if not keys: + return None + return any(bool(o[k]) for k in ERROR_FLAGS if k in o) or any((o.get(k) or 0) > 0 for k in ERROR_COUNTS if k in o) + + +# ====================================================================================================== logs -> notes + +class RunLog: + """Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's + narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition.""" + + def __init__(self, run_dir, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run = os.path.basename(self.run_dir) + self.batch = os.path.basename(os.path.dirname(self.run_dir)) + self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl")) + self.start = next(e for e in self.ev if e["ev"] == "session_start") + self.calls, self.dones, self.harness_status = {}, [], [] + last = None + for e in self.ev: + if e["ev"] == "call": + self.calls[(int(e["attempt"]), int(e["step"]))] = e + last = e + elif e["ev"] == "done": + self.dones.append(e) + last = e + elif e["ev"] == "http" and last is not None and "think_s" not in last: + ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \ + (last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe")) + if ok: + last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s") + self.manifest = manifest or {} + self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {} + p = os.path.join(self.run_dir, "harness.json") + self.harness = json.load(open(p)) if os.path.exists(p) else {} + self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl")) + self._narration() + + # ---------------------------------------------------------------- agent narration + def _narration(self): + """notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one; + finish_notes[attempt] likewise for the agent's finish call; final_report = its last message.""" + self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", [] + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + attempt = 1 + + def take(): + nonlocal buf + out = {k: v for k, v in buf.items() if v} + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + return out + + last_msg = "" + for t in self.traj: + if t.get("kind") == "header": + self.headers.append(t.get("agent") or {}) + continue + if t.get("kind") != "step": + continue + if (t.get("message") or "").strip(): + buf["messages"].append(t["message"].strip()) + last_msg = t["message"].strip() + if (t.get("reasoning_content") or "").strip(): + buf["reasoning"].append(t["reasoning_content"].strip()) + res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])} + for c in t.get("tool_calls") or []: + fn, args = c.get("function_name"), c.get("arguments") or {} + if fn == "shell": + buf["shell"].append(str(args.get("command", ""))[:2000]) + elif fn == "view_images": + buf["viewed"].extend(args.get("paths") or []) + elif fn == "robot": + cmd = str(args.get("command", "")).strip() + r = res.get(c.get("tool_call_id")) or {} + try: + rep = json.loads(r.get("content") or "{}") + except ValueError: + rep = {} + word = cmd.split()[0] if cmd else "" + m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", ""))) + if word in ("move_eef", "observe") and m: + a, s = int(m.group(1)), int(m.group(2)) + n = take() + n["command"] = cmd + self.notes[(a, s)] = n + attempt = a + elif word in ("finish", "done"): + n = take() + n["command"] = cmd + n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)} + self.finish_notes.setdefault(attempt, n) + if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"): + attempt += 1 + # status / help / errors: their narration stays in the buffer for the next command + self.final_report = last_msg + + # ---------------------------------------------------------------- run-level labels + def attempts(self): + out = [] + for e in self.dones: + o = e.get("outcome") or {} + if isinstance(o, str): + try: + o = ast.literal_eval(o) + except (ValueError, SyntaxError): + o = {} + out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o, + reason=e.get("reason") or "")) + return sorted(out, key=lambda x: x["attempt"]) + + def condition(self): + s, en = self.start, self.entry + mem = s.get("memory", en.get("mem")) + chain = en.get("chain") + if mem == "full": + cond = "with_history" + elif chain: + cond = "memory_free_retry" + else: + cond = "independent_single_attempt" + return cond, chain + + def outcome_class(self): + """CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None.""" + att = self.attempts() + if not att or self.start.get("memory") != "full": + return None, "".join("S" if a["success"] else "F" for a in att) + hist = "".join("S" if a["success"] else "F" for a in att) + if att[0]["success"]: + ev = error_event(att[0]["outcome"]) + cls = "S?" if ev is None else ("IR" if ev else "CS") + else: + cls = "XR" if any(a["success"] for a in att) else "F" + return cls, hist + + def agent_info(self): + h, en = self.harness, self.entry + hdr = self.headers[0] if self.headers else {} + return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"), + harness_version=h.get("version") or hdr.get("version"), + harness_binary_sha256=(h.get("binary") or {}).get("sha256"), + model=h.get("model") or en.get("model") or hdr.get("model_name"), + effort=h.get("effort") or en.get("effort") or hdr.get("effort"), + provider=h.get("provider") or en.get("provider"), + codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"), + jail=en.get("jail")) + + +# ====================================================================================================== recording + +class EpisodeSink: + """Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed.""" + + def __init__(self, path): + self.path = path + os.makedirs(path, exist_ok=True) + self.w = None + self.num = defaultdict(list) + self.n = 0 + + def add(self, st, imgs): + import imageio + if self.w is None: + self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb", + pixelformat="rgb24", macro_block_size=1, + ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error") + for k in ("agentview", "wrist")] + for w, im in zip(self.w, imgs): + w.append_data(im) + for k, v in st.items(): + self.num[k].append(v) + self.n += 1 + + def close(self, final_state, final_imgs): + from PIL import Image + if self.w is not None: + for w in self.w: + w.close() + arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"} + np.savez(os.path.join(self.path, "frames.npz"), **arr) + if self.num.get("sim_state"): + np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64)) + np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()}) + for k, im in zip(("agentview", "wrist"), final_imgs): + Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png")) + + +class Recorder: + """Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink.""" + + def __init__(self, rp, res): + self.rp, self.res = rp, int(res) + self.active = False + self.sink = None + self.cur = dict(attempt=1, command=-1, phase=PHASES["move"]) + env = rp.task.env + self.env, self.rob = env, env.robots[0] + self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist")) + orig = env.step + + def step(a): + if self.active and self.sink is not None: + self.capture(np.asarray(a, np.float64)) + out = orig(a) + if self.active and self.sink is not None: + self.rp.poll_events(self.sink.n - 1) + return out + + env.step = step + + @property + def n(self): + return self.sink.n if self.sink is not None else 0 + + def state(self): + import robosuite.utils.transform_utils as T + env, rob = self.env, self.rob + d = env.sim.data + eef = np.array(d.site_xpos[rob.eef_site_id], np.float64) + q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw") + gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64) + try: + flat = np.asarray(env.sim.get_state().flatten(), np.float64) + except Exception: + flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64) + sk = self.rp.task.sk + return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64), + gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64), + joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64), + gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64), + eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)), + sim_time=np.float64(d.time), sim_state=flat) + + def images(self): + return [envs.render(self.env, c, self.res) for c in self.cams] + + def capture(self, a): + st = self.state() + st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]), + phase=np.int64(self.cur["phase"])) + self.sink.add(st, self.images()) + + +class RunReplay: + def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run_name = os.path.basename(self.run_dir) + self.log = RunLog(self.run_dir, manifest) + self.ev = self.log.ev + self.start = self.log.start + cp = os.path.join(self.run_dir, "contract.json") + self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {} + spec = self.contract.get("image_spec") or {} + self.image_res = int(spec.get("width", 512)) + self.code_diff = check_code(self.run_dir) + s = self.start + self.task = TASKS[s["task"]](cam_res=self.image_res) + inst = self.task.sample_instance(s["seed"]) + logged = s.get("inst") or {} + sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")}) + self.inst_diff = diff_json(sampled, logged, "inst") + if s.get("arm", "none") not in (None, "none") or logged.get("nominal"): + inst.update(logged) # controlled arms / nominal: the server overrode these instance fields + self.inst_diff = [] + self.inst = inst + self.protocol = getattr(self.task, "protocol", "cross") + self.k = int(s.get("k") or self.task.max_attempts) + self.attempt = 1 + self.mismatch = [] # (where, what, logged, replayed) + self.n_checked = 0 + self.max_dev_m = 0.0 + self.unfinished = None + self.rec = Recorder(self, res) if record else None + self.res = int(res) + self.out_root = out_root + self.n_mon = 0 + self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0 + self.episodes = [] # summaries of the written episodes + self.task.reset_instance(self.inst) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + sim = self.task.env.sim + bid = sim.model.body_name2id("robot0_base") + self.base_off = np.array(sim.data.body_xpos[bid], float).copy() + if self.rec: + self._open_episode() + + # ------------------------------------------------------------------ episodes + def _ep_dir(self): + return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}") + + def _open_episode(self): + self.rec.sink = EpisodeSink(self._ep_dir()) + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.rec.active = True + self.events, self.spans, self.ep_attempts = [], [], [] + self.ep_initial = self.rec.state() # state right after the reset (before frame 0) + + def close_episode(self): + if not self.rec: + self.ep_attempts = [] + return + sink = self.rec.sink + st = self.rec.state() + imgs = self.rec.images() + st.pop("sim_state", None) + sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs) + ann = build_annotation(self, sink) + with open(os.path.join(sink.path, "annotation.json"), "w") as f: + json.dump(ann, f, indent=1, default=_json_default) + self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n, + attempts=[a["attempt"] for a in self.ep_attempts])) + self.rec.active = False + self.rec.sink = None + self.ep_index += 1 + + # ------------------------------------------------------------------ monitor events (task-side error events) + def poll_events(self, frame): + mon = getattr(self.task, "mon", None) + evs = mon.get("events") if isinstance(mon, dict) else None + if not isinstance(evs, list): + return + if len(evs) < self.n_mon: # monitor was rebuilt + self.n_mon = 0 + for e in evs[self.n_mon:]: + self.events.append(dict(frame=int(frame), attempt=self.attempt, + event=norm_json(e) if isinstance(e, dict) else str(e))) + self.n_mon = len(evs) + + # ------------------------------------------------------------------ state as the server reports it + def proprio_la(self): + p = self.ex.proprio() + pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off] + return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"]) + + def compare(self, where, rep_logged, rep): + self.n_checked += 1 + for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"): + if k not in rep_logged or k not in rep: + continue + a, b = rep_logged[k], rep[k] + if k == "eef_pos": + dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float)))) + self.max_dev_m = max(self.max_dev_m, dev) + if dev > 1.5e-4: + self.mismatch.append((where, k, a, b)) + elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4): + self.mismatch.append((where, k, a, b)) + if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)): + self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok"))) + + def _span(self, e, f0, kind): + if self.rec: + self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0, + frame_end=self.rec.n)) + + # ------------------------------------------------------------------ commands (robot_server._handle_v2) + def move_eef(self, e): + args = e.get("args") or {} + where = f"a{e['attempt']}s{e['step']}" + logged = e.get("report") or {} + f0 = self.rec.n if self.rec else 0 + p = self.ex.proprio() + if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}: + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + off = self.base_off + try: + cur = np.asarray(p["eef_pos"], float) - off + tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")] + yaw = float(args.get("yaw", p["eef_yaw_deg"])) + speed = None if args.get("speed") in (None, "") else float(args["speed"]) + except (TypeError, ValueError): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + grip = args.get("gripper") + if grip not in (None, "open", "close"): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + moving = any(k in args for k in ("x", "y", "z", "yaw")) + tgt_w = np.asarray(tgt) + off + if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)): + self._span(e, f0, "rejected") + return self.compare(where, logged, dict(ok=False, **self.proprio_la())) + raw = {} + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"]) + if moving: + mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw) + if speed is not None: + mv["speed"] = speed + raw.update(self.ex.call("move_to", mv).report) + if grip is not None: + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"]) + raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report) + rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la()) + self.compare(where, logged, rep) + lr = e.get("raw") or {} + for k in ("holding_object", "touched_object"): + if k in lr and k in raw and bool(lr[k]) != bool(raw[k]): + self.mismatch.append((where, "raw." + k, lr[k], raw[k])) + self._span(e, f0, "move_eef") + + def observe(self, e): + f0 = self.rec.n if self.rec else 0 + self._span(e, f0, "observe") + + def done(self, e): + f0 = self.rec.n if self.rec else 0 + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"]) + out = self.task.outcome(self.inst) + succ = bool(out["success"]) + where = f"a{e['attempt']}done" + if succ != bool(e.get("success") in (True, "True")): + self.mismatch.append((where, "success", e.get("success"), succ)) + lo = e.get("outcome") or {} + ro = norm_json({k: v for k, v in out.items() if k != "feedback"}) + if isinstance(lo, dict): + for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8): + self.mismatch.append((where,) + d) + info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""), + feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")), + think_s=e.get("think_s")) + try: + info["feedback_f2"] = self.task.feedback(self.inst, out, "F2") + except Exception as ex_: + info["feedback_f2"] = f"" + if self.rec: + info["judge_frames"] = [f0, self.rec.n] + self.ep_attempts.append(info) + last = self.attempt >= self.k or succ or bool(out.get("terminal")) + if self.protocol == "cross" or last: + self.close_episode() + if last: + return True + self.attempt += 1 + if self.protocol == "cross": + self.task.reset_instance(self.inst) + self.n_mon = 0 + if self.rec: + self._open_episode() + elif self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + return False + + def run(self): + t0 = time.time() + finished = False + for e in self.ev: + if e["ev"] == "call": + if e.get("cmd") == "move_eef": + self.move_eef(e) + elif e.get("cmd") == "observe": + self.observe(e) + else: + self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None)) + elif e["ev"] == "done": + finished = self.done(e) + if finished: + break + self.unfinished = not finished + if not finished and self.rec and self.rec.sink is not None: + # the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged + if self.rec.n or self.ep_attempts: + self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True, + finish_reason="", feedback_shown="", auto_ended=False)) + self.close_episode() + else: + shutil.rmtree(self.rec.sink.path, ignore_errors=True) + self.rec.sink = None + self.wall_s = time.time() - t0 + return self + + def summary(self): + return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"], + protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff), + n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6), + unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1), + first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]]) + + +# ====================================================================================================== annotation + +def task_info(task, inst): + cls = type(task) + return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable", + category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"), + max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)), + instruction=cls.instruction) + + +def build_annotation(rp, sink): + """Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2 + failure description), run-level outcome class, every robot command with its frame span and the agent's narration, + task-side error events with frame indices.""" + log = rp.log + s = rp.start + cond, chain = log.condition() + cls, hist = log.outcome_class() + att_all = log.attempts() + attempts = [] + for a in rp.ep_attempts: + a = dict(a) + n = a["attempt"] + later = [x for x in att_all if x["attempt"] > n] + a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later)) + a["is_last_attempt_of_run"] = not later + fn = log.finish_notes.get(n) + if fn: + a["agent_finish"] = fn + a["error_event_in_attempt"] = error_event(a.get("outcome")) + attempts.append(a) + # post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command) + for a in attempts: + nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1]) + if a.get("success") is False and nxt: + note = log.notes[nxt[0]] + a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note} + commands = [] + for sp in rp.spans: + e = log.calls.get((sp["attempt"], sp["step"])) or {} + rep = e.get("report") or {} + c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"], + frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]), + args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"), + stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"), + gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"), + touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"), + agent_obs_images=rep.get("images")) + note = log.notes.get((sp["attempt"], sp["step"])) + if note: + c["agent_note"] = {k: v for k, v in note.items() if k != "command"} + commands.append(c) + t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x] + return dict( + schema=SCHEMA, + source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts], + episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain, + memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None), + feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"), + k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"), + contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256") + if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)), + agent=log.agent_info(), + task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"), + instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}), + run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all), + run_success=any(x["success"] for x in att_all) if att_all else None, + agent_final_report=log.final_report[:6000] or None, + mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)), + attempts=attempts, + commands=commands, + task_events=rp.events, + frames=dict(n=sink.n, fps=FPS, image_res=rp.res, + phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"], + joint_pos=rp.ep_initial["joint_pos"], + gripper_qpos=rp.ep_initial["gripper_qpos"])), + ) + + +# ====================================================================================================== CLI + +def load_manifest(run_dir): + p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json") + return json.load(open(p)) if os.path.exists(p) else {} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("mode", choices=["check", "record"]) + ap.add_argument("runs", nargs="+") + ap.add_argument("--json", default="") + ap.add_argument("--out", default="") + ap.add_argument("--res", type=int, default=256) + ap.add_argument("--force", action="store_true", help="record again even if replay.json exists") + a = ap.parse_args() + rows = [] + for r in a.runs: + r = r.rstrip("/") + try: + if a.mode == "check": + s = RunReplay(r, manifest=load_manifest(r)).run().summary() + else: + batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r) + rd = os.path.join(a.out, batch, name) + if os.path.exists(os.path.join(rd, "replay.json")) and not a.force: + print(json.dumps(dict(run=name, skipped="exists")), flush=True) + continue + shutil.rmtree(rd, ignore_errors=True) + rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run() + s = rp.summary() + s["episodes"] = rp.episodes + with open(os.path.join(rd, "replay.json"), "w") as f: + json.dump(s, f, indent=1) + except Exception: + import traceback + s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:]) + rows.append(s) + print(json.dumps(s), flush=True) + if a.json: + with open(a.json, "w") as f: + json.dump(rows, f, indent=1) + + +if __name__ == "__main__": + main() diff --git a/leaf/code/supp-20261113-g61_evofull_20261025/lerobot_export.py b/leaf/code/supp-20261113-g61_evofull_20261025/lerobot_export.py new file mode 100644 index 0000000000000000000000000000000000000000..fa4fa0a1be92844c9cf410663f77de5e200bda18 --- /dev/null +++ b/leaf/code/supp-20261113-g61_evofull_20261025/lerobot_export.py @@ -0,0 +1,431 @@ +"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars. + +Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding +can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan): + + python scripts/lerobot_export.py plan --raw [,] --runs-root /runs/api \ + --paper --task-set /sets/main_v2_1inst.txt --work [--batches ...] [--limit N] + python scripts/lerobot_export.py shard --work --shard i --nshards N + python scripts/lerobot_export.py merge --work --nshards N --out + +Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0 +mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped. + +LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t): + observation.images.image agentview RGB 256x256 (upright; LIBERO naming) + observation.images.wrist_image wrist (eye-in-hand) RGB 256x256 + observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout) + observation.joint_pos / joint_vel 7 arm joints (rad, rad/s) + observation.eef_quat 4: xyzw; observation.gripper_width 1 (m) + action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad), + gripper (-1 open, +1 close) + annotation.attempt_index attempt (1-based) the frame belongs to + annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`) + annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action) + annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt + annotation.task_event number of task-monitor events (error / progress events) registered at this step +Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table), +runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state +per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/. +""" +import argparse +import glob +import json +import os +import re +import shutil +import time + +import numpy as np + +FPS = 20 +RES = 256 +BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke", + "cc_smoke", "cc_opus_smoke"] +BATCH_NOTES = { + "cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog", + "cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267", + "cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299", + "cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances", + "cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)", + "cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the " + "with-history continuation of failed runs is incomplete", + "cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early", + "cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt", + "cc_opus_smoke": "smoke test: single attempt", +} +PHASES = {"move": 0, "gripper": 1, "judge": 2} +CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)", + "L2": "disturbed state to restore (incl. damage the agent causes)", + "L3": "infeasible manipulation strategy (grasp / contact / tool must change)", + "L4": "misjudged geometry (size, shape, fit, hidden structure)", + "L5": "misjudged physics (mass distribution, friction, dynamics)"} + + +def features(): + vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]} + f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names} + i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None} + return { + "observation.images.image": vid(), + "observation.images.wrist_image": vid(), + "observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z", + "finger_qpos_left", "finger_qpos_right"]), + "observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]), + "observation.gripper_width": f32(1, ["width_m"]), + "action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y", + "eef_delta_rot_aa_z", "gripper_close"]), + "annotation.attempt_index": i64(), + "annotation.command_index": i64(), + "annotation.phase": i64(), + "annotation.attempt_success": i64(), + "annotation.task_event": i64(), + } + + +# ------------------------------------------------------------------------------------------------ paper metadata + +def _clean_tex(s): + s = re.sub(r"%.*", "", s) + for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"), + (r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"), + (r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"), + (r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"), + (r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]: + s = re.sub(a, b, s) + s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s) + s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s) + for _ in range(3): + s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\$([^$]*)\$", r"\1", s) + s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ") + s = re.sub(r"\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\\[a-zA-Z]+\*?", "", s) + return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip() + + +def paper_tasks(paper_dir): + """{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the + paper's task table and task appendix (empty if the paper sources are not there).""" + out = {} + if not paper_dir: + return out + app = os.path.join(paper_dir, "sections", "appendix_tasks.tex") + tab = os.path.join(paper_dir, "sections", "tab_tasks.tex") + if os.path.exists(app): + txt = open(app).read() + parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt) + for i in range(1, len(parts) - 1, 2): + if parts[i] != "\\paragraph{": + continue + body = parts[i + 1] + m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S) + if not m: + continue + name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip() + desc = _clean_tex(body[m.end():]) + out[code] = dict(name=name, cause=_clean_tex(cause), description=desc) + if os.path.exists(tab): + names = {v["name"].lower(): k for k, v in out.items()} + for line in open(tab): + cells = [c.strip() for c in line.split("&")] + if len(cells) != 6 or not cells[-1].endswith("\\\\"): + continue + nm = re.sub(r"\\contscene", "", cells[0]).strip().lower() + code = names.get(nm) + if not code: + continue + out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]), + repair_within_attempt=_clean_tex(cells[3]) == "yes", + oracle_first_attempt_pct=_clean_tex(cells[4]), + naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip())) + return out + + +# ------------------------------------------------------------------------------------------------ collection + +def manifest_status(runs_root, batch, run, cache={}): + if batch not in cache: + p = os.path.join(runs_root, batch, "manifest.json") + cache[batch] = json.load(open(p)) if os.path.exists(p) else {} + m = cache[batch] + for r in m.get("runs", []): + if r.get("run") == run: + return r.get("status", "?"), r + for r in m.get("superseded", []): + if r.get("run") == run: + return "superseded_" + str(r.get("status", "?")), r + return "not_in_manifest", {} + + +def collect(raw_roots, runs_root, batches, task_order): + """Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root.""" + eps, rejected, seen = [], [], set() + for root in raw_roots: + for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))): + rep = json.load(open(rj)) + batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"] + if (batches and batch not in batches) or (batch, run) in seen: + continue + seen.add((batch, run)) + ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff") + status, entry = manifest_status(runs_root, batch, run) + if not ok: + never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked") + rejected.append(dict(run=run, batch=batch, run_status=status, + reason="run never started (no contract, no robot command)" if never else + "replay does not reproduce the log (the log has gaps or the replay diverged)", + detail=rep.get("first_mismatches"))) + continue + for ep in rep.get("episodes", []): + d = os.path.join(root, ep["dir"]) + ann = json.load(open(os.path.join(d, "annotation.json"))) + judged = [a for a in ann["attempts"] if a.get("success") is not None] + if not judged or ep["n_frames"] == 0: + rejected.append(dict(run=run, batch=batch, episode=ep["dir"], + reason="no judged attempt" if not judged else "no frames")) + continue + ann["source"]["run_status"] = status + ann["source"]["manifest_id"] = entry.get("id") + ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"], + max_eef_dev_m=rep["max_eef_dev_m"]) + key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99), + {"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2), + ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"]) + eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann)) + eps.sort(key=lambda x: x["key"]) + return eps, rejected + + +# ------------------------------------------------------------------------------------------------ writing + +def frames_of(path): + import av + with av.open(path) as c: + for fr in c.decode(video=0): + yield fr.to_ndarray(format="rgb24") + + +def flat_row(i, ann, n, idx0): + s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"] + att = ann["attempts"] + a0 = att[0] + return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n, + batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"], + memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"), + episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att], + harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"), + effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"), + task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"), + category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"], + success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att], + feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att], + auto_ended=[a.get("auto_ended") for a in att], + corrected_later_in_run=[a.get("corrected_later_in_run") for a in att], + error_event_in_attempt=[a.get("error_event_in_attempt") for a in att], + run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"), + n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]), + first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None) + + +def cmd_plan(a): + task_order = {} + if a.task_set and os.path.exists(a.task_set): + for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")): + task_order[line.split(":")[0].strip()] = i + batches = [b for b in a.batches.split(",") if b] if a.batches else None + eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order) + if a.limit: + eps = eps[:a.limit] + paper = paper_tasks(a.paper) + idx0 = 0 + for i, e in enumerate(eps): + ann = e["ann"] + tname = ann["task"]["name"] + if tname in paper: + ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"} + ann["episode_index"] = i + ann["dataset_index_range"] = [idx0, idx0 + e["n"]] + e["index"], e["from"] = i, idx0 + idx0 += e["n"] + del e["key"] + os.makedirs(a.work, exist_ok=True) + with open(os.path.join(a.work, "plan.json"), "w") as f: + json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f, + ensure_ascii=False) + print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True) + + +def shard_range(n_eps, i, k): + return (n_eps * i) // k, (n_eps * (i + 1)) // k + + +def cmd_shard(a): + from lerobot.datasets.lerobot_dataset import LeRobotDataset + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + lo, hi = shard_range(len(eps), a.shard, a.nshards) + out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}") + if os.path.exists(os.path.join(out, "DONE")): + print(f"shard {a.shard}: done already", flush=True) + return + shutil.rmtree(out, ignore_errors=True) + ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out, + robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads, + vcodec=a.vcodec) + nfr = 0 + for e in eps[lo:hi]: + d, ann, n = e["dir"], e["ann"], e["n"] + fr = np.load(os.path.join(d, "frames.npz")) + assert len(fr["action"]) == n, d + succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]} + evc = np.zeros(n, np.int64) + for ev in ann["task_events"]: + if 0 <= ev["frame"] < n: + evc[ev["frame"]] += 1 + state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32) + instr = ann["task"]["instruction"] + k = 0 + for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))): + if k >= n: + break + ds.add_frame({ + "observation.images.image": img, "observation.images.wrist_image": wr, + "observation.state": state[k], + "observation.joint_pos": fr["joint_pos"][k].astype(np.float32), + "observation.joint_vel": fr["joint_vel"][k].astype(np.float32), + "observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32), + "observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32), + "action": fr["action"][k].astype(np.float32), + "annotation.attempt_index": np.array([fr["attempt"][k]], np.int64), + "annotation.command_index": np.array([fr["command"][k]], np.int64), + "annotation.phase": np.array([fr["phase"][k]], np.int64), + "annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64), + "annotation.task_event": np.array([evc[k]], np.int64), + "task": instr, + }) + k += 1 + if k != n: + raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames") + ds.save_episode() + nfr += n + ds.finalize() + shutil.rmtree(os.path.join(out, "images"), ignore_errors=True) + open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n") + print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True) + + +def cmd_merge(a): + from pathlib import Path + from lerobot.datasets.aggregate import aggregate_datasets + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + roots, ids = [], [] + for i in range(a.nshards): + lo, hi = shard_range(len(eps), i, a.nshards) + if hi <= lo: + continue + r = os.path.join(a.work, "shards", f"shard_{i:03d}") + if not os.path.exists(os.path.join(r, "DONE")): + raise SystemExit(f"shard {i} is not done") + roots.append(Path(r)) + ids.append(f"{plan['repo_id']}-shard{i:03d}") + if os.path.exists(a.out): + raise SystemExit(f"{a.out} exists; refusing to overwrite") + aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out)) + print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True) + write_sidecars(a, plan) + print(f"merge done in {time.time() - t0:.0f}s", flush=True) + + +def write_sidecars(a, plan): + eps, paper = plan["episodes"], plan["paper"] + lff = os.path.join(a.out, "lff") + for sub in ("annotations", "sim_state", "final", "code"): + os.makedirs(os.path.join(lff, sub), exist_ok=True) + rows, runs, tasks = [], {}, {} + for e in eps: + i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"] + name = f"episode_{i:06d}" + if os.path.exists(os.path.join(d, "sim_state.npy")): + shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy")) + shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz")) + for cam, key in (("agentview", "image"), ("wrist", "wrist_image")): + shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png")) + with open(os.path.join(lff, "annotations", name + ".json"), "w") as f: + json.dump(ann, f, indent=1, ensure_ascii=False) + rows.append(flat_row(i, ann, n, e["from"])) + tname = ann["task"]["name"] + rk = (ann["source"]["batch"], ann["source"]["run"]) + r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"), + run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"], + memory_free_chain_of=ann["source"].get("memory_free_chain_of"), + memory_free_rep=ann["source"].get("memory_free_rep"), task=tname, + seed=ann["task"]["seed"], model=ann["agent"].get("model"), + harness=ann["agent"].get("harness"), + harness_version=ann["agent"].get("harness_version"), + codex_catalog=ann["agent"].get("codex_catalog"), + outcome_class=ann["run_outcome"].get("outcome_class"), + attempt_history=ann["run_outcome"].get("attempt_history"), + agent_final_report=ann["run_outcome"].get("agent_final_report"), + episodes=[])) + for x in ann["attempts"]: + r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success"))) + if tname not in tasks: + tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")} + if tname in paper: + tasks[tname]["paper"] = paper[tname] + tasks[tname]["instances"] = {} + tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"] + # memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id) + by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")} + for r in runs.values(): + if r.get("memory_free_chain_of"): + r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"])) + for (b, rn), r in runs.items(): + r["memory_free_retries"] = sorted((x["run"] for x in runs.values() + if x["batch"] == b and x.get("memory_free_chain_of_run") == rn), + key=lambda q: runs[(b, q)].get("memory_free_rep") or 0) + with open(os.path.join(lff, "episodes.jsonl"), "w") as f: + for row in rows: + f.write(json.dumps(row, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "runs.jsonl"), "w") as f: + for r in runs.values(): + f.write(json.dumps(r, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "tasks.json"), "w") as f: + json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False) + with open(os.path.join(lff, "batches.json"), "w") as f: + json.dump(BATCH_NOTES, f, indent=1) + with open(os.path.join(lff, "rejected.json"), "w") as f: + json.dump(plan["rejected"], f, indent=1) + here = os.path.dirname(os.path.abspath(__file__)) + for s in ("lerobot_replay.py", "lerobot_export.py"): + shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("step", choices=["plan", "shard", "merge"]) + ap.add_argument("--work", required=True) + ap.add_argument("--raw", default="") + ap.add_argument("--runs-root", default="") + ap.add_argument("--out", default="") + ap.add_argument("--paper", default="") + ap.add_argument("--task-set", default="") + ap.add_argument("--repo-id", default="lffbench/agent-replays") + ap.add_argument("--batches", default="") + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--shard", type=int, default=0) + ap.add_argument("--nshards", type=int, default=1) + ap.add_argument("--threads", type=int, default=2) + ap.add_argument("--vcodec", default="libsvtav1") + a = ap.parse_args() + {"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a) + + +if __name__ == "__main__": + main() diff --git a/leaf/code/supp-20261113-g61_evofull_20261025/lerobot_replay.py b/leaf/code/supp-20261113-g61_evofull_20261025/lerobot_replay.py new file mode 100644 index 0000000000000000000000000000000000000000..4c43a69bdb066327b27614bc9efda53d4a74e931 --- /dev/null +++ b/leaf/code/supp-20261113-g61_evofull_20261025/lerobot_replay.py @@ -0,0 +1,744 @@ +"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay +against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the +LeRobot export (scripts/lerobot_export.py). + + python scripts/lerobot_replay.py check [ ...] [--json out.json] # replay only, print fidelity + python scripts/lerobot_replay.py record --out [--res 256] + +Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot +commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite +is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly +like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same +outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width, +ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code +hashes equal the current files are expected to match (check_code()). + +Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB, +proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes: +protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode +per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the +fidelity check runs in record mode too. Per episode the recorder writes ///epNN/: + agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes) + frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase + sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel) + final_*.png, final.npz observation after the last control step (the state the outcome was judged in) + annotation.json episode annotation (build_annotation) +and ///replay.json (fidelity) when the whole run is done. +""" +import argparse +import ast +import hashlib +import importlib +import json +import math +import os +import pkgutil +import re +import shutil +import sys +import time +from collections import defaultdict + +import numpy as np + +LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, LFF_ROOT) + +from lffbench import envs # noqa: E402 +from lffbench import tasks as task_pkg # noqa: E402 +from lffbench.agent import camera as C # noqa: E402 +from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402 +from lffbench.task_base import TASKS # noqa: E402 + +for _m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{_m.name}") + +# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the +# task's outcome() check after `finish` (the arm holds still; not an agent action) +PHASES = {"move": 0, "gripper": 1, "judge": 2} +FPS = 20 +SCHEMA = "lff-replay-1" + +# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR" +ERROR_FLAGS = ("trap_fired", "recovered_in_attempt") +ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events", + "n_missed_strikes", "n_open_gripper_pushes") + + +def load_jsonl(p): + out = [] + if not os.path.exists(p): + return out + with open(p) as f: + for line in f: + line = line.strip() + if line: + try: + out.append(json.loads(line)) + except ValueError: + pass + return out + + +def norm_json(o): + return json.loads(json.dumps(o, default=_json_default)) + + +def sha256(p): + with open(p, "rb") as f: + return hashlib.sha256(f.read()).hexdigest() + + +def check_code(run_dir): + """[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract.""" + p = os.path.join(run_dir, "contract.json") + if not os.path.exists(p): + return [("contract.json", None, None)] + files = json.load(open(p))["contract"].get("server_code_files", {}) + bad = [] + for f, h in files.items(): + q = os.path.join(LFF_ROOT, f) + cur = sha256(q) if os.path.exists(q) else None + if cur != h: + bad.append((f, h, cur)) + return bad + + +def diff_json(a, b, path="", tol=0.0, out=None, limit=20): + """Differences between two JSON values (numbers compared with an absolute tolerance).""" + out = [] if out is None else out + if len(out) >= limit: + return out + if isinstance(a, dict) and isinstance(b, dict): + for k in sorted(set(a) | set(b)): + if k not in a or k not in b: + out.append((f"{path}.{k}", a.get(k, ""), b.get(k, ""))) + else: + diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit) + elif isinstance(a, list) and isinstance(b, list): + if len(a) != len(b): + out.append((path, f"len {len(a)}", f"len {len(b)}")) + else: + for i, (x, y) in enumerate(zip(a, b)): + diff_json(x, y, f"{path}[{i}]", tol, out, limit) + elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))): + if a != b: + out.append((path, a, b)) + elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))): + out.append((path, a, b)) + return out + + +def error_event(o): + """True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none.""" + if not isinstance(o, dict): + return None + keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o] + if not keys: + return None + return any(bool(o[k]) for k in ERROR_FLAGS if k in o) or any((o.get(k) or 0) > 0 for k in ERROR_COUNTS if k in o) + + +# ====================================================================================================== logs -> notes + +class RunLog: + """Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's + narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition.""" + + def __init__(self, run_dir, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run = os.path.basename(self.run_dir) + self.batch = os.path.basename(os.path.dirname(self.run_dir)) + self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl")) + self.start = next(e for e in self.ev if e["ev"] == "session_start") + self.calls, self.dones, self.harness_status = {}, [], [] + last = None + for e in self.ev: + if e["ev"] == "call": + self.calls[(int(e["attempt"]), int(e["step"]))] = e + last = e + elif e["ev"] == "done": + self.dones.append(e) + last = e + elif e["ev"] == "http" and last is not None and "think_s" not in last: + ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \ + (last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe")) + if ok: + last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s") + self.manifest = manifest or {} + self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {} + p = os.path.join(self.run_dir, "harness.json") + self.harness = json.load(open(p)) if os.path.exists(p) else {} + self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl")) + self._narration() + + # ---------------------------------------------------------------- agent narration + def _narration(self): + """notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one; + finish_notes[attempt] likewise for the agent's finish call; final_report = its last message.""" + self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", [] + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + attempt = 1 + + def take(): + nonlocal buf + out = {k: v for k, v in buf.items() if v} + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + return out + + last_msg = "" + for t in self.traj: + if t.get("kind") == "header": + self.headers.append(t.get("agent") or {}) + continue + if t.get("kind") != "step": + continue + if (t.get("message") or "").strip(): + buf["messages"].append(t["message"].strip()) + last_msg = t["message"].strip() + if (t.get("reasoning_content") or "").strip(): + buf["reasoning"].append(t["reasoning_content"].strip()) + res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])} + for c in t.get("tool_calls") or []: + fn, args = c.get("function_name"), c.get("arguments") or {} + if fn == "shell": + buf["shell"].append(str(args.get("command", ""))[:2000]) + elif fn == "view_images": + buf["viewed"].extend(args.get("paths") or []) + elif fn == "robot": + cmd = str(args.get("command", "")).strip() + r = res.get(c.get("tool_call_id")) or {} + try: + rep = json.loads(r.get("content") or "{}") + except ValueError: + rep = {} + word = cmd.split()[0] if cmd else "" + m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", ""))) + if word in ("move_eef", "observe") and m: + a, s = int(m.group(1)), int(m.group(2)) + n = take() + n["command"] = cmd + self.notes[(a, s)] = n + attempt = a + elif word in ("finish", "done"): + n = take() + n["command"] = cmd + n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)} + self.finish_notes.setdefault(attempt, n) + if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"): + attempt += 1 + # status / help / errors: their narration stays in the buffer for the next command + self.final_report = last_msg + + # ---------------------------------------------------------------- run-level labels + def attempts(self): + out = [] + for e in self.dones: + o = e.get("outcome") or {} + if isinstance(o, str): + try: + o = ast.literal_eval(o) + except (ValueError, SyntaxError): + o = {} + out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o, + reason=e.get("reason") or "")) + return sorted(out, key=lambda x: x["attempt"]) + + def condition(self): + s, en = self.start, self.entry + mem = s.get("memory", en.get("mem")) + chain = en.get("chain") + if mem == "full": + cond = "with_history" + elif chain: + cond = "memory_free_retry" + else: + cond = "independent_single_attempt" + return cond, chain + + def outcome_class(self): + """CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None.""" + att = self.attempts() + if not att or self.start.get("memory") != "full": + return None, "".join("S" if a["success"] else "F" for a in att) + hist = "".join("S" if a["success"] else "F" for a in att) + if att[0]["success"]: + ev = error_event(att[0]["outcome"]) + cls = "S?" if ev is None else ("IR" if ev else "CS") + else: + cls = "XR" if any(a["success"] for a in att) else "F" + return cls, hist + + def agent_info(self): + h, en = self.harness, self.entry + hdr = self.headers[0] if self.headers else {} + return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"), + harness_version=h.get("version") or hdr.get("version"), + harness_binary_sha256=(h.get("binary") or {}).get("sha256"), + model=h.get("model") or en.get("model") or hdr.get("model_name"), + effort=h.get("effort") or en.get("effort") or hdr.get("effort"), + provider=h.get("provider") or en.get("provider"), + codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"), + jail=en.get("jail")) + + +# ====================================================================================================== recording + +class EpisodeSink: + """Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed.""" + + def __init__(self, path): + self.path = path + os.makedirs(path, exist_ok=True) + self.w = None + self.num = defaultdict(list) + self.n = 0 + + def add(self, st, imgs): + import imageio + if self.w is None: + self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb", + pixelformat="rgb24", macro_block_size=1, + ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error") + for k in ("agentview", "wrist")] + for w, im in zip(self.w, imgs): + w.append_data(im) + for k, v in st.items(): + self.num[k].append(v) + self.n += 1 + + def close(self, final_state, final_imgs): + from PIL import Image + if self.w is not None: + for w in self.w: + w.close() + arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"} + np.savez(os.path.join(self.path, "frames.npz"), **arr) + if self.num.get("sim_state"): + np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64)) + np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()}) + for k, im in zip(("agentview", "wrist"), final_imgs): + Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png")) + + +class Recorder: + """Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink.""" + + def __init__(self, rp, res): + self.rp, self.res = rp, int(res) + self.active = False + self.sink = None + self.cur = dict(attempt=1, command=-1, phase=PHASES["move"]) + env = rp.task.env + self.env, self.rob = env, env.robots[0] + self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist")) + orig = env.step + + def step(a): + if self.active and self.sink is not None: + self.capture(np.asarray(a, np.float64)) + out = orig(a) + if self.active and self.sink is not None: + self.rp.poll_events(self.sink.n - 1) + return out + + env.step = step + + @property + def n(self): + return self.sink.n if self.sink is not None else 0 + + def state(self): + import robosuite.utils.transform_utils as T + env, rob = self.env, self.rob + d = env.sim.data + eef = np.array(d.site_xpos[rob.eef_site_id], np.float64) + q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw") + gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64) + try: + flat = np.asarray(env.sim.get_state().flatten(), np.float64) + except Exception: + flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64) + sk = self.rp.task.sk + return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64), + gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64), + joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64), + gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64), + eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)), + sim_time=np.float64(d.time), sim_state=flat) + + def images(self): + return [envs.render(self.env, c, self.res) for c in self.cams] + + def capture(self, a): + st = self.state() + st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]), + phase=np.int64(self.cur["phase"])) + self.sink.add(st, self.images()) + + +class RunReplay: + def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run_name = os.path.basename(self.run_dir) + self.log = RunLog(self.run_dir, manifest) + self.ev = self.log.ev + self.start = self.log.start + cp = os.path.join(self.run_dir, "contract.json") + self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {} + spec = self.contract.get("image_spec") or {} + self.image_res = int(spec.get("width", 512)) + self.code_diff = check_code(self.run_dir) + s = self.start + self.task = TASKS[s["task"]](cam_res=self.image_res) + inst = self.task.sample_instance(s["seed"]) + logged = s.get("inst") or {} + sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")}) + self.inst_diff = diff_json(sampled, logged, "inst") + if s.get("arm", "none") not in (None, "none") or logged.get("nominal"): + inst.update(logged) # controlled arms / nominal: the server overrode these instance fields + self.inst_diff = [] + self.inst = inst + self.protocol = getattr(self.task, "protocol", "cross") + self.k = int(s.get("k") or self.task.max_attempts) + self.attempt = 1 + self.mismatch = [] # (where, what, logged, replayed) + self.n_checked = 0 + self.max_dev_m = 0.0 + self.unfinished = None + self.rec = Recorder(self, res) if record else None + self.res = int(res) + self.out_root = out_root + self.n_mon = 0 + self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0 + self.episodes = [] # summaries of the written episodes + self.task.reset_instance(self.inst) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + sim = self.task.env.sim + bid = sim.model.body_name2id("robot0_base") + self.base_off = np.array(sim.data.body_xpos[bid], float).copy() + if self.rec: + self._open_episode() + + # ------------------------------------------------------------------ episodes + def _ep_dir(self): + return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}") + + def _open_episode(self): + self.rec.sink = EpisodeSink(self._ep_dir()) + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.rec.active = True + self.events, self.spans, self.ep_attempts = [], [], [] + self.ep_initial = self.rec.state() # state right after the reset (before frame 0) + + def close_episode(self): + if not self.rec: + self.ep_attempts = [] + return + sink = self.rec.sink + st = self.rec.state() + imgs = self.rec.images() + st.pop("sim_state", None) + sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs) + ann = build_annotation(self, sink) + with open(os.path.join(sink.path, "annotation.json"), "w") as f: + json.dump(ann, f, indent=1, default=_json_default) + self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n, + attempts=[a["attempt"] for a in self.ep_attempts])) + self.rec.active = False + self.rec.sink = None + self.ep_index += 1 + + # ------------------------------------------------------------------ monitor events (task-side error events) + def poll_events(self, frame): + mon = getattr(self.task, "mon", None) + evs = mon.get("events") if isinstance(mon, dict) else None + if not isinstance(evs, list): + return + if len(evs) < self.n_mon: # monitor was rebuilt + self.n_mon = 0 + for e in evs[self.n_mon:]: + self.events.append(dict(frame=int(frame), attempt=self.attempt, + event=norm_json(e) if isinstance(e, dict) else str(e))) + self.n_mon = len(evs) + + # ------------------------------------------------------------------ state as the server reports it + def proprio_la(self): + p = self.ex.proprio() + pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off] + return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"]) + + def compare(self, where, rep_logged, rep): + self.n_checked += 1 + for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"): + if k not in rep_logged or k not in rep: + continue + a, b = rep_logged[k], rep[k] + if k == "eef_pos": + dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float)))) + self.max_dev_m = max(self.max_dev_m, dev) + if dev > 1.5e-4: + self.mismatch.append((where, k, a, b)) + elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4): + self.mismatch.append((where, k, a, b)) + if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)): + self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok"))) + + def _span(self, e, f0, kind): + if self.rec: + self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0, + frame_end=self.rec.n)) + + # ------------------------------------------------------------------ commands (robot_server._handle_v2) + def move_eef(self, e): + args = e.get("args") or {} + where = f"a{e['attempt']}s{e['step']}" + logged = e.get("report") or {} + f0 = self.rec.n if self.rec else 0 + p = self.ex.proprio() + if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}: + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + off = self.base_off + try: + cur = np.asarray(p["eef_pos"], float) - off + tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")] + yaw = float(args.get("yaw", p["eef_yaw_deg"])) + speed = None if args.get("speed") in (None, "") else float(args["speed"]) + except (TypeError, ValueError): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + grip = args.get("gripper") + if grip not in (None, "open", "close"): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + moving = any(k in args for k in ("x", "y", "z", "yaw")) + tgt_w = np.asarray(tgt) + off + if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)): + self._span(e, f0, "rejected") + return self.compare(where, logged, dict(ok=False, **self.proprio_la())) + raw = {} + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"]) + if moving: + mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw) + if speed is not None: + mv["speed"] = speed + raw.update(self.ex.call("move_to", mv).report) + if grip is not None: + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"]) + raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report) + rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la()) + self.compare(where, logged, rep) + lr = e.get("raw") or {} + for k in ("holding_object", "touched_object"): + if k in lr and k in raw and bool(lr[k]) != bool(raw[k]): + self.mismatch.append((where, "raw." + k, lr[k], raw[k])) + self._span(e, f0, "move_eef") + + def observe(self, e): + f0 = self.rec.n if self.rec else 0 + self._span(e, f0, "observe") + + def done(self, e): + f0 = self.rec.n if self.rec else 0 + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"]) + out = self.task.outcome(self.inst) + succ = bool(out["success"]) + where = f"a{e['attempt']}done" + if succ != bool(e.get("success") in (True, "True")): + self.mismatch.append((where, "success", e.get("success"), succ)) + lo = e.get("outcome") or {} + ro = norm_json({k: v for k, v in out.items() if k != "feedback"}) + if isinstance(lo, dict): + for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8): + self.mismatch.append((where,) + d) + info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""), + feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")), + think_s=e.get("think_s")) + try: + info["feedback_f2"] = self.task.feedback(self.inst, out, "F2") + except Exception as ex_: + info["feedback_f2"] = f"" + if self.rec: + info["judge_frames"] = [f0, self.rec.n] + self.ep_attempts.append(info) + last = self.attempt >= self.k or succ or bool(out.get("terminal")) + if self.protocol == "cross" or last: + self.close_episode() + if last: + return True + self.attempt += 1 + if self.protocol == "cross": + self.task.reset_instance(self.inst) + self.n_mon = 0 + if self.rec: + self._open_episode() + elif self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + return False + + def run(self): + t0 = time.time() + finished = False + for e in self.ev: + if e["ev"] == "call": + if e.get("cmd") == "move_eef": + self.move_eef(e) + elif e.get("cmd") == "observe": + self.observe(e) + else: + self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None)) + elif e["ev"] == "done": + finished = self.done(e) + if finished: + break + self.unfinished = not finished + if not finished and self.rec and self.rec.sink is not None: + # the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged + if self.rec.n or self.ep_attempts: + self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True, + finish_reason="", feedback_shown="", auto_ended=False)) + self.close_episode() + else: + shutil.rmtree(self.rec.sink.path, ignore_errors=True) + self.rec.sink = None + self.wall_s = time.time() - t0 + return self + + def summary(self): + return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"], + protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff), + n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6), + unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1), + first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]]) + + +# ====================================================================================================== annotation + +def task_info(task, inst): + cls = type(task) + return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable", + category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"), + max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)), + instruction=cls.instruction) + + +def build_annotation(rp, sink): + """Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2 + failure description), run-level outcome class, every robot command with its frame span and the agent's narration, + task-side error events with frame indices.""" + log = rp.log + s = rp.start + cond, chain = log.condition() + cls, hist = log.outcome_class() + att_all = log.attempts() + attempts = [] + for a in rp.ep_attempts: + a = dict(a) + n = a["attempt"] + later = [x for x in att_all if x["attempt"] > n] + a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later)) + a["is_last_attempt_of_run"] = not later + fn = log.finish_notes.get(n) + if fn: + a["agent_finish"] = fn + a["error_event_in_attempt"] = error_event(a.get("outcome")) + attempts.append(a) + # post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command) + for a in attempts: + nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1]) + if a.get("success") is False and nxt: + note = log.notes[nxt[0]] + a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note} + commands = [] + for sp in rp.spans: + e = log.calls.get((sp["attempt"], sp["step"])) or {} + rep = e.get("report") or {} + c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"], + frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]), + args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"), + stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"), + gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"), + touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"), + agent_obs_images=rep.get("images")) + note = log.notes.get((sp["attempt"], sp["step"])) + if note: + c["agent_note"] = {k: v for k, v in note.items() if k != "command"} + commands.append(c) + t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x] + return dict( + schema=SCHEMA, + source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts], + episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain, + memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None), + feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"), + k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"), + contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256") + if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)), + agent=log.agent_info(), + task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"), + instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}), + run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all), + run_success=any(x["success"] for x in att_all) if att_all else None, + agent_final_report=log.final_report[:6000] or None, + mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)), + attempts=attempts, + commands=commands, + task_events=rp.events, + frames=dict(n=sink.n, fps=FPS, image_res=rp.res, + phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"], + joint_pos=rp.ep_initial["joint_pos"], + gripper_qpos=rp.ep_initial["gripper_qpos"])), + ) + + +# ====================================================================================================== CLI + +def load_manifest(run_dir): + p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json") + return json.load(open(p)) if os.path.exists(p) else {} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("mode", choices=["check", "record"]) + ap.add_argument("runs", nargs="+") + ap.add_argument("--json", default="") + ap.add_argument("--out", default="") + ap.add_argument("--res", type=int, default=256) + ap.add_argument("--force", action="store_true", help="record again even if replay.json exists") + a = ap.parse_args() + rows = [] + for r in a.runs: + r = r.rstrip("/") + try: + if a.mode == "check": + s = RunReplay(r, manifest=load_manifest(r)).run().summary() + else: + batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r) + rd = os.path.join(a.out, batch, name) + if os.path.exists(os.path.join(rd, "replay.json")) and not a.force: + print(json.dumps(dict(run=name, skipped="exists")), flush=True) + continue + shutil.rmtree(rd, ignore_errors=True) + rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run() + s = rp.summary() + s["episodes"] = rp.episodes + with open(os.path.join(rd, "replay.json"), "w") as f: + json.dump(s, f, indent=1) + except Exception: + import traceback + s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:]) + rows.append(s) + print(json.dumps(s), flush=True) + if a.json: + with open(a.json, "w") as f: + json.dump(rows, f, indent=1) + + +if __name__ == "__main__": + main() diff --git a/leaf/code/supp-20261113-g61_evosub_2_20261026/lerobot_export.py b/leaf/code/supp-20261113-g61_evosub_2_20261026/lerobot_export.py new file mode 100644 index 0000000000000000000000000000000000000000..fa4fa0a1be92844c9cf410663f77de5e200bda18 --- /dev/null +++ b/leaf/code/supp-20261113-g61_evosub_2_20261026/lerobot_export.py @@ -0,0 +1,431 @@ +"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars. + +Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding +can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan): + + python scripts/lerobot_export.py plan --raw [,] --runs-root /runs/api \ + --paper --task-set /sets/main_v2_1inst.txt --work [--batches ...] [--limit N] + python scripts/lerobot_export.py shard --work --shard i --nshards N + python scripts/lerobot_export.py merge --work --nshards N --out + +Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0 +mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped. + +LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t): + observation.images.image agentview RGB 256x256 (upright; LIBERO naming) + observation.images.wrist_image wrist (eye-in-hand) RGB 256x256 + observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout) + observation.joint_pos / joint_vel 7 arm joints (rad, rad/s) + observation.eef_quat 4: xyzw; observation.gripper_width 1 (m) + action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad), + gripper (-1 open, +1 close) + annotation.attempt_index attempt (1-based) the frame belongs to + annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`) + annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action) + annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt + annotation.task_event number of task-monitor events (error / progress events) registered at this step +Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table), +runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state +per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/. +""" +import argparse +import glob +import json +import os +import re +import shutil +import time + +import numpy as np + +FPS = 20 +RES = 256 +BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke", + "cc_smoke", "cc_opus_smoke"] +BATCH_NOTES = { + "cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog", + "cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267", + "cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299", + "cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances", + "cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)", + "cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the " + "with-history continuation of failed runs is incomplete", + "cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early", + "cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt", + "cc_opus_smoke": "smoke test: single attempt", +} +PHASES = {"move": 0, "gripper": 1, "judge": 2} +CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)", + "L2": "disturbed state to restore (incl. damage the agent causes)", + "L3": "infeasible manipulation strategy (grasp / contact / tool must change)", + "L4": "misjudged geometry (size, shape, fit, hidden structure)", + "L5": "misjudged physics (mass distribution, friction, dynamics)"} + + +def features(): + vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]} + f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names} + i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None} + return { + "observation.images.image": vid(), + "observation.images.wrist_image": vid(), + "observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z", + "finger_qpos_left", "finger_qpos_right"]), + "observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]), + "observation.gripper_width": f32(1, ["width_m"]), + "action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y", + "eef_delta_rot_aa_z", "gripper_close"]), + "annotation.attempt_index": i64(), + "annotation.command_index": i64(), + "annotation.phase": i64(), + "annotation.attempt_success": i64(), + "annotation.task_event": i64(), + } + + +# ------------------------------------------------------------------------------------------------ paper metadata + +def _clean_tex(s): + s = re.sub(r"%.*", "", s) + for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"), + (r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"), + (r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"), + (r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"), + (r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]: + s = re.sub(a, b, s) + s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s) + s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s) + for _ in range(3): + s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\$([^$]*)\$", r"\1", s) + s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ") + s = re.sub(r"\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\\[a-zA-Z]+\*?", "", s) + return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip() + + +def paper_tasks(paper_dir): + """{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the + paper's task table and task appendix (empty if the paper sources are not there).""" + out = {} + if not paper_dir: + return out + app = os.path.join(paper_dir, "sections", "appendix_tasks.tex") + tab = os.path.join(paper_dir, "sections", "tab_tasks.tex") + if os.path.exists(app): + txt = open(app).read() + parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt) + for i in range(1, len(parts) - 1, 2): + if parts[i] != "\\paragraph{": + continue + body = parts[i + 1] + m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S) + if not m: + continue + name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip() + desc = _clean_tex(body[m.end():]) + out[code] = dict(name=name, cause=_clean_tex(cause), description=desc) + if os.path.exists(tab): + names = {v["name"].lower(): k for k, v in out.items()} + for line in open(tab): + cells = [c.strip() for c in line.split("&")] + if len(cells) != 6 or not cells[-1].endswith("\\\\"): + continue + nm = re.sub(r"\\contscene", "", cells[0]).strip().lower() + code = names.get(nm) + if not code: + continue + out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]), + repair_within_attempt=_clean_tex(cells[3]) == "yes", + oracle_first_attempt_pct=_clean_tex(cells[4]), + naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip())) + return out + + +# ------------------------------------------------------------------------------------------------ collection + +def manifest_status(runs_root, batch, run, cache={}): + if batch not in cache: + p = os.path.join(runs_root, batch, "manifest.json") + cache[batch] = json.load(open(p)) if os.path.exists(p) else {} + m = cache[batch] + for r in m.get("runs", []): + if r.get("run") == run: + return r.get("status", "?"), r + for r in m.get("superseded", []): + if r.get("run") == run: + return "superseded_" + str(r.get("status", "?")), r + return "not_in_manifest", {} + + +def collect(raw_roots, runs_root, batches, task_order): + """Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root.""" + eps, rejected, seen = [], [], set() + for root in raw_roots: + for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))): + rep = json.load(open(rj)) + batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"] + if (batches and batch not in batches) or (batch, run) in seen: + continue + seen.add((batch, run)) + ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff") + status, entry = manifest_status(runs_root, batch, run) + if not ok: + never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked") + rejected.append(dict(run=run, batch=batch, run_status=status, + reason="run never started (no contract, no robot command)" if never else + "replay does not reproduce the log (the log has gaps or the replay diverged)", + detail=rep.get("first_mismatches"))) + continue + for ep in rep.get("episodes", []): + d = os.path.join(root, ep["dir"]) + ann = json.load(open(os.path.join(d, "annotation.json"))) + judged = [a for a in ann["attempts"] if a.get("success") is not None] + if not judged or ep["n_frames"] == 0: + rejected.append(dict(run=run, batch=batch, episode=ep["dir"], + reason="no judged attempt" if not judged else "no frames")) + continue + ann["source"]["run_status"] = status + ann["source"]["manifest_id"] = entry.get("id") + ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"], + max_eef_dev_m=rep["max_eef_dev_m"]) + key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99), + {"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2), + ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"]) + eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann)) + eps.sort(key=lambda x: x["key"]) + return eps, rejected + + +# ------------------------------------------------------------------------------------------------ writing + +def frames_of(path): + import av + with av.open(path) as c: + for fr in c.decode(video=0): + yield fr.to_ndarray(format="rgb24") + + +def flat_row(i, ann, n, idx0): + s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"] + att = ann["attempts"] + a0 = att[0] + return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n, + batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"], + memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"), + episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att], + harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"), + effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"), + task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"), + category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"], + success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att], + feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att], + auto_ended=[a.get("auto_ended") for a in att], + corrected_later_in_run=[a.get("corrected_later_in_run") for a in att], + error_event_in_attempt=[a.get("error_event_in_attempt") for a in att], + run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"), + n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]), + first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None) + + +def cmd_plan(a): + task_order = {} + if a.task_set and os.path.exists(a.task_set): + for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")): + task_order[line.split(":")[0].strip()] = i + batches = [b for b in a.batches.split(",") if b] if a.batches else None + eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order) + if a.limit: + eps = eps[:a.limit] + paper = paper_tasks(a.paper) + idx0 = 0 + for i, e in enumerate(eps): + ann = e["ann"] + tname = ann["task"]["name"] + if tname in paper: + ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"} + ann["episode_index"] = i + ann["dataset_index_range"] = [idx0, idx0 + e["n"]] + e["index"], e["from"] = i, idx0 + idx0 += e["n"] + del e["key"] + os.makedirs(a.work, exist_ok=True) + with open(os.path.join(a.work, "plan.json"), "w") as f: + json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f, + ensure_ascii=False) + print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True) + + +def shard_range(n_eps, i, k): + return (n_eps * i) // k, (n_eps * (i + 1)) // k + + +def cmd_shard(a): + from lerobot.datasets.lerobot_dataset import LeRobotDataset + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + lo, hi = shard_range(len(eps), a.shard, a.nshards) + out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}") + if os.path.exists(os.path.join(out, "DONE")): + print(f"shard {a.shard}: done already", flush=True) + return + shutil.rmtree(out, ignore_errors=True) + ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out, + robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads, + vcodec=a.vcodec) + nfr = 0 + for e in eps[lo:hi]: + d, ann, n = e["dir"], e["ann"], e["n"] + fr = np.load(os.path.join(d, "frames.npz")) + assert len(fr["action"]) == n, d + succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]} + evc = np.zeros(n, np.int64) + for ev in ann["task_events"]: + if 0 <= ev["frame"] < n: + evc[ev["frame"]] += 1 + state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32) + instr = ann["task"]["instruction"] + k = 0 + for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))): + if k >= n: + break + ds.add_frame({ + "observation.images.image": img, "observation.images.wrist_image": wr, + "observation.state": state[k], + "observation.joint_pos": fr["joint_pos"][k].astype(np.float32), + "observation.joint_vel": fr["joint_vel"][k].astype(np.float32), + "observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32), + "observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32), + "action": fr["action"][k].astype(np.float32), + "annotation.attempt_index": np.array([fr["attempt"][k]], np.int64), + "annotation.command_index": np.array([fr["command"][k]], np.int64), + "annotation.phase": np.array([fr["phase"][k]], np.int64), + "annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64), + "annotation.task_event": np.array([evc[k]], np.int64), + "task": instr, + }) + k += 1 + if k != n: + raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames") + ds.save_episode() + nfr += n + ds.finalize() + shutil.rmtree(os.path.join(out, "images"), ignore_errors=True) + open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n") + print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True) + + +def cmd_merge(a): + from pathlib import Path + from lerobot.datasets.aggregate import aggregate_datasets + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + roots, ids = [], [] + for i in range(a.nshards): + lo, hi = shard_range(len(eps), i, a.nshards) + if hi <= lo: + continue + r = os.path.join(a.work, "shards", f"shard_{i:03d}") + if not os.path.exists(os.path.join(r, "DONE")): + raise SystemExit(f"shard {i} is not done") + roots.append(Path(r)) + ids.append(f"{plan['repo_id']}-shard{i:03d}") + if os.path.exists(a.out): + raise SystemExit(f"{a.out} exists; refusing to overwrite") + aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out)) + print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True) + write_sidecars(a, plan) + print(f"merge done in {time.time() - t0:.0f}s", flush=True) + + +def write_sidecars(a, plan): + eps, paper = plan["episodes"], plan["paper"] + lff = os.path.join(a.out, "lff") + for sub in ("annotations", "sim_state", "final", "code"): + os.makedirs(os.path.join(lff, sub), exist_ok=True) + rows, runs, tasks = [], {}, {} + for e in eps: + i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"] + name = f"episode_{i:06d}" + if os.path.exists(os.path.join(d, "sim_state.npy")): + shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy")) + shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz")) + for cam, key in (("agentview", "image"), ("wrist", "wrist_image")): + shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png")) + with open(os.path.join(lff, "annotations", name + ".json"), "w") as f: + json.dump(ann, f, indent=1, ensure_ascii=False) + rows.append(flat_row(i, ann, n, e["from"])) + tname = ann["task"]["name"] + rk = (ann["source"]["batch"], ann["source"]["run"]) + r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"), + run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"], + memory_free_chain_of=ann["source"].get("memory_free_chain_of"), + memory_free_rep=ann["source"].get("memory_free_rep"), task=tname, + seed=ann["task"]["seed"], model=ann["agent"].get("model"), + harness=ann["agent"].get("harness"), + harness_version=ann["agent"].get("harness_version"), + codex_catalog=ann["agent"].get("codex_catalog"), + outcome_class=ann["run_outcome"].get("outcome_class"), + attempt_history=ann["run_outcome"].get("attempt_history"), + agent_final_report=ann["run_outcome"].get("agent_final_report"), + episodes=[])) + for x in ann["attempts"]: + r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success"))) + if tname not in tasks: + tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")} + if tname in paper: + tasks[tname]["paper"] = paper[tname] + tasks[tname]["instances"] = {} + tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"] + # memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id) + by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")} + for r in runs.values(): + if r.get("memory_free_chain_of"): + r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"])) + for (b, rn), r in runs.items(): + r["memory_free_retries"] = sorted((x["run"] for x in runs.values() + if x["batch"] == b and x.get("memory_free_chain_of_run") == rn), + key=lambda q: runs[(b, q)].get("memory_free_rep") or 0) + with open(os.path.join(lff, "episodes.jsonl"), "w") as f: + for row in rows: + f.write(json.dumps(row, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "runs.jsonl"), "w") as f: + for r in runs.values(): + f.write(json.dumps(r, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "tasks.json"), "w") as f: + json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False) + with open(os.path.join(lff, "batches.json"), "w") as f: + json.dump(BATCH_NOTES, f, indent=1) + with open(os.path.join(lff, "rejected.json"), "w") as f: + json.dump(plan["rejected"], f, indent=1) + here = os.path.dirname(os.path.abspath(__file__)) + for s in ("lerobot_replay.py", "lerobot_export.py"): + shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("step", choices=["plan", "shard", "merge"]) + ap.add_argument("--work", required=True) + ap.add_argument("--raw", default="") + ap.add_argument("--runs-root", default="") + ap.add_argument("--out", default="") + ap.add_argument("--paper", default="") + ap.add_argument("--task-set", default="") + ap.add_argument("--repo-id", default="lffbench/agent-replays") + ap.add_argument("--batches", default="") + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--shard", type=int, default=0) + ap.add_argument("--nshards", type=int, default=1) + ap.add_argument("--threads", type=int, default=2) + ap.add_argument("--vcodec", default="libsvtav1") + a = ap.parse_args() + {"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a) + + +if __name__ == "__main__": + main() diff --git a/leaf/code/supp-20261113-g61_evosub_3_20261026/lerobot_export.py b/leaf/code/supp-20261113-g61_evosub_3_20261026/lerobot_export.py new file mode 100644 index 0000000000000000000000000000000000000000..fa4fa0a1be92844c9cf410663f77de5e200bda18 --- /dev/null +++ b/leaf/code/supp-20261113-g61_evosub_3_20261026/lerobot_export.py @@ -0,0 +1,431 @@ +"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars. + +Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding +can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan): + + python scripts/lerobot_export.py plan --raw [,] --runs-root /runs/api \ + --paper --task-set /sets/main_v2_1inst.txt --work [--batches ...] [--limit N] + python scripts/lerobot_export.py shard --work --shard i --nshards N + python scripts/lerobot_export.py merge --work --nshards N --out + +Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0 +mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped. + +LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t): + observation.images.image agentview RGB 256x256 (upright; LIBERO naming) + observation.images.wrist_image wrist (eye-in-hand) RGB 256x256 + observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout) + observation.joint_pos / joint_vel 7 arm joints (rad, rad/s) + observation.eef_quat 4: xyzw; observation.gripper_width 1 (m) + action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad), + gripper (-1 open, +1 close) + annotation.attempt_index attempt (1-based) the frame belongs to + annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`) + annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action) + annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt + annotation.task_event number of task-monitor events (error / progress events) registered at this step +Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table), +runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state +per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/. +""" +import argparse +import glob +import json +import os +import re +import shutil +import time + +import numpy as np + +FPS = 20 +RES = 256 +BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke", + "cc_smoke", "cc_opus_smoke"] +BATCH_NOTES = { + "cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog", + "cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267", + "cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299", + "cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances", + "cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)", + "cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the " + "with-history continuation of failed runs is incomplete", + "cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early", + "cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt", + "cc_opus_smoke": "smoke test: single attempt", +} +PHASES = {"move": 0, "gripper": 1, "judge": 2} +CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)", + "L2": "disturbed state to restore (incl. damage the agent causes)", + "L3": "infeasible manipulation strategy (grasp / contact / tool must change)", + "L4": "misjudged geometry (size, shape, fit, hidden structure)", + "L5": "misjudged physics (mass distribution, friction, dynamics)"} + + +def features(): + vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]} + f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names} + i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None} + return { + "observation.images.image": vid(), + "observation.images.wrist_image": vid(), + "observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z", + "finger_qpos_left", "finger_qpos_right"]), + "observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]), + "observation.gripper_width": f32(1, ["width_m"]), + "action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y", + "eef_delta_rot_aa_z", "gripper_close"]), + "annotation.attempt_index": i64(), + "annotation.command_index": i64(), + "annotation.phase": i64(), + "annotation.attempt_success": i64(), + "annotation.task_event": i64(), + } + + +# ------------------------------------------------------------------------------------------------ paper metadata + +def _clean_tex(s): + s = re.sub(r"%.*", "", s) + for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"), + (r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"), + (r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"), + (r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"), + (r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]: + s = re.sub(a, b, s) + s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s) + s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s) + for _ in range(3): + s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\$([^$]*)\$", r"\1", s) + s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ") + s = re.sub(r"\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\\[a-zA-Z]+\*?", "", s) + return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip() + + +def paper_tasks(paper_dir): + """{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the + paper's task table and task appendix (empty if the paper sources are not there).""" + out = {} + if not paper_dir: + return out + app = os.path.join(paper_dir, "sections", "appendix_tasks.tex") + tab = os.path.join(paper_dir, "sections", "tab_tasks.tex") + if os.path.exists(app): + txt = open(app).read() + parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt) + for i in range(1, len(parts) - 1, 2): + if parts[i] != "\\paragraph{": + continue + body = parts[i + 1] + m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S) + if not m: + continue + name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip() + desc = _clean_tex(body[m.end():]) + out[code] = dict(name=name, cause=_clean_tex(cause), description=desc) + if os.path.exists(tab): + names = {v["name"].lower(): k for k, v in out.items()} + for line in open(tab): + cells = [c.strip() for c in line.split("&")] + if len(cells) != 6 or not cells[-1].endswith("\\\\"): + continue + nm = re.sub(r"\\contscene", "", cells[0]).strip().lower() + code = names.get(nm) + if not code: + continue + out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]), + repair_within_attempt=_clean_tex(cells[3]) == "yes", + oracle_first_attempt_pct=_clean_tex(cells[4]), + naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip())) + return out + + +# ------------------------------------------------------------------------------------------------ collection + +def manifest_status(runs_root, batch, run, cache={}): + if batch not in cache: + p = os.path.join(runs_root, batch, "manifest.json") + cache[batch] = json.load(open(p)) if os.path.exists(p) else {} + m = cache[batch] + for r in m.get("runs", []): + if r.get("run") == run: + return r.get("status", "?"), r + for r in m.get("superseded", []): + if r.get("run") == run: + return "superseded_" + str(r.get("status", "?")), r + return "not_in_manifest", {} + + +def collect(raw_roots, runs_root, batches, task_order): + """Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root.""" + eps, rejected, seen = [], [], set() + for root in raw_roots: + for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))): + rep = json.load(open(rj)) + batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"] + if (batches and batch not in batches) or (batch, run) in seen: + continue + seen.add((batch, run)) + ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff") + status, entry = manifest_status(runs_root, batch, run) + if not ok: + never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked") + rejected.append(dict(run=run, batch=batch, run_status=status, + reason="run never started (no contract, no robot command)" if never else + "replay does not reproduce the log (the log has gaps or the replay diverged)", + detail=rep.get("first_mismatches"))) + continue + for ep in rep.get("episodes", []): + d = os.path.join(root, ep["dir"]) + ann = json.load(open(os.path.join(d, "annotation.json"))) + judged = [a for a in ann["attempts"] if a.get("success") is not None] + if not judged or ep["n_frames"] == 0: + rejected.append(dict(run=run, batch=batch, episode=ep["dir"], + reason="no judged attempt" if not judged else "no frames")) + continue + ann["source"]["run_status"] = status + ann["source"]["manifest_id"] = entry.get("id") + ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"], + max_eef_dev_m=rep["max_eef_dev_m"]) + key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99), + {"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2), + ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"]) + eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann)) + eps.sort(key=lambda x: x["key"]) + return eps, rejected + + +# ------------------------------------------------------------------------------------------------ writing + +def frames_of(path): + import av + with av.open(path) as c: + for fr in c.decode(video=0): + yield fr.to_ndarray(format="rgb24") + + +def flat_row(i, ann, n, idx0): + s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"] + att = ann["attempts"] + a0 = att[0] + return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n, + batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"], + memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"), + episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att], + harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"), + effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"), + task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"), + category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"], + success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att], + feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att], + auto_ended=[a.get("auto_ended") for a in att], + corrected_later_in_run=[a.get("corrected_later_in_run") for a in att], + error_event_in_attempt=[a.get("error_event_in_attempt") for a in att], + run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"), + n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]), + first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None) + + +def cmd_plan(a): + task_order = {} + if a.task_set and os.path.exists(a.task_set): + for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")): + task_order[line.split(":")[0].strip()] = i + batches = [b for b in a.batches.split(",") if b] if a.batches else None + eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order) + if a.limit: + eps = eps[:a.limit] + paper = paper_tasks(a.paper) + idx0 = 0 + for i, e in enumerate(eps): + ann = e["ann"] + tname = ann["task"]["name"] + if tname in paper: + ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"} + ann["episode_index"] = i + ann["dataset_index_range"] = [idx0, idx0 + e["n"]] + e["index"], e["from"] = i, idx0 + idx0 += e["n"] + del e["key"] + os.makedirs(a.work, exist_ok=True) + with open(os.path.join(a.work, "plan.json"), "w") as f: + json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f, + ensure_ascii=False) + print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True) + + +def shard_range(n_eps, i, k): + return (n_eps * i) // k, (n_eps * (i + 1)) // k + + +def cmd_shard(a): + from lerobot.datasets.lerobot_dataset import LeRobotDataset + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + lo, hi = shard_range(len(eps), a.shard, a.nshards) + out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}") + if os.path.exists(os.path.join(out, "DONE")): + print(f"shard {a.shard}: done already", flush=True) + return + shutil.rmtree(out, ignore_errors=True) + ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out, + robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads, + vcodec=a.vcodec) + nfr = 0 + for e in eps[lo:hi]: + d, ann, n = e["dir"], e["ann"], e["n"] + fr = np.load(os.path.join(d, "frames.npz")) + assert len(fr["action"]) == n, d + succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]} + evc = np.zeros(n, np.int64) + for ev in ann["task_events"]: + if 0 <= ev["frame"] < n: + evc[ev["frame"]] += 1 + state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32) + instr = ann["task"]["instruction"] + k = 0 + for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))): + if k >= n: + break + ds.add_frame({ + "observation.images.image": img, "observation.images.wrist_image": wr, + "observation.state": state[k], + "observation.joint_pos": fr["joint_pos"][k].astype(np.float32), + "observation.joint_vel": fr["joint_vel"][k].astype(np.float32), + "observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32), + "observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32), + "action": fr["action"][k].astype(np.float32), + "annotation.attempt_index": np.array([fr["attempt"][k]], np.int64), + "annotation.command_index": np.array([fr["command"][k]], np.int64), + "annotation.phase": np.array([fr["phase"][k]], np.int64), + "annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64), + "annotation.task_event": np.array([evc[k]], np.int64), + "task": instr, + }) + k += 1 + if k != n: + raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames") + ds.save_episode() + nfr += n + ds.finalize() + shutil.rmtree(os.path.join(out, "images"), ignore_errors=True) + open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n") + print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True) + + +def cmd_merge(a): + from pathlib import Path + from lerobot.datasets.aggregate import aggregate_datasets + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + roots, ids = [], [] + for i in range(a.nshards): + lo, hi = shard_range(len(eps), i, a.nshards) + if hi <= lo: + continue + r = os.path.join(a.work, "shards", f"shard_{i:03d}") + if not os.path.exists(os.path.join(r, "DONE")): + raise SystemExit(f"shard {i} is not done") + roots.append(Path(r)) + ids.append(f"{plan['repo_id']}-shard{i:03d}") + if os.path.exists(a.out): + raise SystemExit(f"{a.out} exists; refusing to overwrite") + aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out)) + print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True) + write_sidecars(a, plan) + print(f"merge done in {time.time() - t0:.0f}s", flush=True) + + +def write_sidecars(a, plan): + eps, paper = plan["episodes"], plan["paper"] + lff = os.path.join(a.out, "lff") + for sub in ("annotations", "sim_state", "final", "code"): + os.makedirs(os.path.join(lff, sub), exist_ok=True) + rows, runs, tasks = [], {}, {} + for e in eps: + i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"] + name = f"episode_{i:06d}" + if os.path.exists(os.path.join(d, "sim_state.npy")): + shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy")) + shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz")) + for cam, key in (("agentview", "image"), ("wrist", "wrist_image")): + shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png")) + with open(os.path.join(lff, "annotations", name + ".json"), "w") as f: + json.dump(ann, f, indent=1, ensure_ascii=False) + rows.append(flat_row(i, ann, n, e["from"])) + tname = ann["task"]["name"] + rk = (ann["source"]["batch"], ann["source"]["run"]) + r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"), + run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"], + memory_free_chain_of=ann["source"].get("memory_free_chain_of"), + memory_free_rep=ann["source"].get("memory_free_rep"), task=tname, + seed=ann["task"]["seed"], model=ann["agent"].get("model"), + harness=ann["agent"].get("harness"), + harness_version=ann["agent"].get("harness_version"), + codex_catalog=ann["agent"].get("codex_catalog"), + outcome_class=ann["run_outcome"].get("outcome_class"), + attempt_history=ann["run_outcome"].get("attempt_history"), + agent_final_report=ann["run_outcome"].get("agent_final_report"), + episodes=[])) + for x in ann["attempts"]: + r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success"))) + if tname not in tasks: + tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")} + if tname in paper: + tasks[tname]["paper"] = paper[tname] + tasks[tname]["instances"] = {} + tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"] + # memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id) + by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")} + for r in runs.values(): + if r.get("memory_free_chain_of"): + r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"])) + for (b, rn), r in runs.items(): + r["memory_free_retries"] = sorted((x["run"] for x in runs.values() + if x["batch"] == b and x.get("memory_free_chain_of_run") == rn), + key=lambda q: runs[(b, q)].get("memory_free_rep") or 0) + with open(os.path.join(lff, "episodes.jsonl"), "w") as f: + for row in rows: + f.write(json.dumps(row, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "runs.jsonl"), "w") as f: + for r in runs.values(): + f.write(json.dumps(r, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "tasks.json"), "w") as f: + json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False) + with open(os.path.join(lff, "batches.json"), "w") as f: + json.dump(BATCH_NOTES, f, indent=1) + with open(os.path.join(lff, "rejected.json"), "w") as f: + json.dump(plan["rejected"], f, indent=1) + here = os.path.dirname(os.path.abspath(__file__)) + for s in ("lerobot_replay.py", "lerobot_export.py"): + shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("step", choices=["plan", "shard", "merge"]) + ap.add_argument("--work", required=True) + ap.add_argument("--raw", default="") + ap.add_argument("--runs-root", default="") + ap.add_argument("--out", default="") + ap.add_argument("--paper", default="") + ap.add_argument("--task-set", default="") + ap.add_argument("--repo-id", default="lffbench/agent-replays") + ap.add_argument("--batches", default="") + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--shard", type=int, default=0) + ap.add_argument("--nshards", type=int, default=1) + ap.add_argument("--threads", type=int, default=2) + ap.add_argument("--vcodec", default="libsvtav1") + a = ap.parse_args() + {"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a) + + +if __name__ == "__main__": + main() diff --git a/leaf/code/supp-20261113-rcc_dev09_sonnet_20261111/lerobot_export.py b/leaf/code/supp-20261113-rcc_dev09_sonnet_20261111/lerobot_export.py new file mode 100644 index 0000000000000000000000000000000000000000..fa4fa0a1be92844c9cf410663f77de5e200bda18 --- /dev/null +++ b/leaf/code/supp-20261113-rcc_dev09_sonnet_20261111/lerobot_export.py @@ -0,0 +1,431 @@ +"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars. + +Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding +can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan): + + python scripts/lerobot_export.py plan --raw [,] --runs-root /runs/api \ + --paper --task-set /sets/main_v2_1inst.txt --work [--batches ...] [--limit N] + python scripts/lerobot_export.py shard --work --shard i --nshards N + python scripts/lerobot_export.py merge --work --nshards N --out + +Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0 +mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped. + +LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t): + observation.images.image agentview RGB 256x256 (upright; LIBERO naming) + observation.images.wrist_image wrist (eye-in-hand) RGB 256x256 + observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout) + observation.joint_pos / joint_vel 7 arm joints (rad, rad/s) + observation.eef_quat 4: xyzw; observation.gripper_width 1 (m) + action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad), + gripper (-1 open, +1 close) + annotation.attempt_index attempt (1-based) the frame belongs to + annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`) + annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action) + annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt + annotation.task_event number of task-monitor events (error / progress events) registered at this step +Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table), +runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state +per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/. +""" +import argparse +import glob +import json +import os +import re +import shutil +import time + +import numpy as np + +FPS = 20 +RES = 256 +BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke", + "cc_smoke", "cc_opus_smoke"] +BATCH_NOTES = { + "cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog", + "cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267", + "cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299", + "cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances", + "cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)", + "cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the " + "with-history continuation of failed runs is incomplete", + "cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early", + "cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt", + "cc_opus_smoke": "smoke test: single attempt", +} +PHASES = {"move": 0, "gripper": 1, "judge": 2} +CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)", + "L2": "disturbed state to restore (incl. damage the agent causes)", + "L3": "infeasible manipulation strategy (grasp / contact / tool must change)", + "L4": "misjudged geometry (size, shape, fit, hidden structure)", + "L5": "misjudged physics (mass distribution, friction, dynamics)"} + + +def features(): + vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]} + f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names} + i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None} + return { + "observation.images.image": vid(), + "observation.images.wrist_image": vid(), + "observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z", + "finger_qpos_left", "finger_qpos_right"]), + "observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]), + "observation.gripper_width": f32(1, ["width_m"]), + "action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y", + "eef_delta_rot_aa_z", "gripper_close"]), + "annotation.attempt_index": i64(), + "annotation.command_index": i64(), + "annotation.phase": i64(), + "annotation.attempt_success": i64(), + "annotation.task_event": i64(), + } + + +# ------------------------------------------------------------------------------------------------ paper metadata + +def _clean_tex(s): + s = re.sub(r"%.*", "", s) + for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"), + (r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"), + (r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"), + (r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"), + (r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]: + s = re.sub(a, b, s) + s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s) + s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s) + for _ in range(3): + s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\$([^$]*)\$", r"\1", s) + s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ") + s = re.sub(r"\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\\[a-zA-Z]+\*?", "", s) + return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip() + + +def paper_tasks(paper_dir): + """{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the + paper's task table and task appendix (empty if the paper sources are not there).""" + out = {} + if not paper_dir: + return out + app = os.path.join(paper_dir, "sections", "appendix_tasks.tex") + tab = os.path.join(paper_dir, "sections", "tab_tasks.tex") + if os.path.exists(app): + txt = open(app).read() + parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt) + for i in range(1, len(parts) - 1, 2): + if parts[i] != "\\paragraph{": + continue + body = parts[i + 1] + m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S) + if not m: + continue + name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip() + desc = _clean_tex(body[m.end():]) + out[code] = dict(name=name, cause=_clean_tex(cause), description=desc) + if os.path.exists(tab): + names = {v["name"].lower(): k for k, v in out.items()} + for line in open(tab): + cells = [c.strip() for c in line.split("&")] + if len(cells) != 6 or not cells[-1].endswith("\\\\"): + continue + nm = re.sub(r"\\contscene", "", cells[0]).strip().lower() + code = names.get(nm) + if not code: + continue + out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]), + repair_within_attempt=_clean_tex(cells[3]) == "yes", + oracle_first_attempt_pct=_clean_tex(cells[4]), + naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip())) + return out + + +# ------------------------------------------------------------------------------------------------ collection + +def manifest_status(runs_root, batch, run, cache={}): + if batch not in cache: + p = os.path.join(runs_root, batch, "manifest.json") + cache[batch] = json.load(open(p)) if os.path.exists(p) else {} + m = cache[batch] + for r in m.get("runs", []): + if r.get("run") == run: + return r.get("status", "?"), r + for r in m.get("superseded", []): + if r.get("run") == run: + return "superseded_" + str(r.get("status", "?")), r + return "not_in_manifest", {} + + +def collect(raw_roots, runs_root, batches, task_order): + """Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root.""" + eps, rejected, seen = [], [], set() + for root in raw_roots: + for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))): + rep = json.load(open(rj)) + batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"] + if (batches and batch not in batches) or (batch, run) in seen: + continue + seen.add((batch, run)) + ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff") + status, entry = manifest_status(runs_root, batch, run) + if not ok: + never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked") + rejected.append(dict(run=run, batch=batch, run_status=status, + reason="run never started (no contract, no robot command)" if never else + "replay does not reproduce the log (the log has gaps or the replay diverged)", + detail=rep.get("first_mismatches"))) + continue + for ep in rep.get("episodes", []): + d = os.path.join(root, ep["dir"]) + ann = json.load(open(os.path.join(d, "annotation.json"))) + judged = [a for a in ann["attempts"] if a.get("success") is not None] + if not judged or ep["n_frames"] == 0: + rejected.append(dict(run=run, batch=batch, episode=ep["dir"], + reason="no judged attempt" if not judged else "no frames")) + continue + ann["source"]["run_status"] = status + ann["source"]["manifest_id"] = entry.get("id") + ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"], + max_eef_dev_m=rep["max_eef_dev_m"]) + key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99), + {"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2), + ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"]) + eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann)) + eps.sort(key=lambda x: x["key"]) + return eps, rejected + + +# ------------------------------------------------------------------------------------------------ writing + +def frames_of(path): + import av + with av.open(path) as c: + for fr in c.decode(video=0): + yield fr.to_ndarray(format="rgb24") + + +def flat_row(i, ann, n, idx0): + s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"] + att = ann["attempts"] + a0 = att[0] + return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n, + batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"], + memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"), + episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att], + harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"), + effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"), + task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"), + category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"], + success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att], + feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att], + auto_ended=[a.get("auto_ended") for a in att], + corrected_later_in_run=[a.get("corrected_later_in_run") for a in att], + error_event_in_attempt=[a.get("error_event_in_attempt") for a in att], + run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"), + n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]), + first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None) + + +def cmd_plan(a): + task_order = {} + if a.task_set and os.path.exists(a.task_set): + for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")): + task_order[line.split(":")[0].strip()] = i + batches = [b for b in a.batches.split(",") if b] if a.batches else None + eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order) + if a.limit: + eps = eps[:a.limit] + paper = paper_tasks(a.paper) + idx0 = 0 + for i, e in enumerate(eps): + ann = e["ann"] + tname = ann["task"]["name"] + if tname in paper: + ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"} + ann["episode_index"] = i + ann["dataset_index_range"] = [idx0, idx0 + e["n"]] + e["index"], e["from"] = i, idx0 + idx0 += e["n"] + del e["key"] + os.makedirs(a.work, exist_ok=True) + with open(os.path.join(a.work, "plan.json"), "w") as f: + json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f, + ensure_ascii=False) + print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True) + + +def shard_range(n_eps, i, k): + return (n_eps * i) // k, (n_eps * (i + 1)) // k + + +def cmd_shard(a): + from lerobot.datasets.lerobot_dataset import LeRobotDataset + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + lo, hi = shard_range(len(eps), a.shard, a.nshards) + out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}") + if os.path.exists(os.path.join(out, "DONE")): + print(f"shard {a.shard}: done already", flush=True) + return + shutil.rmtree(out, ignore_errors=True) + ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out, + robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads, + vcodec=a.vcodec) + nfr = 0 + for e in eps[lo:hi]: + d, ann, n = e["dir"], e["ann"], e["n"] + fr = np.load(os.path.join(d, "frames.npz")) + assert len(fr["action"]) == n, d + succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]} + evc = np.zeros(n, np.int64) + for ev in ann["task_events"]: + if 0 <= ev["frame"] < n: + evc[ev["frame"]] += 1 + state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32) + instr = ann["task"]["instruction"] + k = 0 + for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))): + if k >= n: + break + ds.add_frame({ + "observation.images.image": img, "observation.images.wrist_image": wr, + "observation.state": state[k], + "observation.joint_pos": fr["joint_pos"][k].astype(np.float32), + "observation.joint_vel": fr["joint_vel"][k].astype(np.float32), + "observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32), + "observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32), + "action": fr["action"][k].astype(np.float32), + "annotation.attempt_index": np.array([fr["attempt"][k]], np.int64), + "annotation.command_index": np.array([fr["command"][k]], np.int64), + "annotation.phase": np.array([fr["phase"][k]], np.int64), + "annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64), + "annotation.task_event": np.array([evc[k]], np.int64), + "task": instr, + }) + k += 1 + if k != n: + raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames") + ds.save_episode() + nfr += n + ds.finalize() + shutil.rmtree(os.path.join(out, "images"), ignore_errors=True) + open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n") + print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True) + + +def cmd_merge(a): + from pathlib import Path + from lerobot.datasets.aggregate import aggregate_datasets + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + roots, ids = [], [] + for i in range(a.nshards): + lo, hi = shard_range(len(eps), i, a.nshards) + if hi <= lo: + continue + r = os.path.join(a.work, "shards", f"shard_{i:03d}") + if not os.path.exists(os.path.join(r, "DONE")): + raise SystemExit(f"shard {i} is not done") + roots.append(Path(r)) + ids.append(f"{plan['repo_id']}-shard{i:03d}") + if os.path.exists(a.out): + raise SystemExit(f"{a.out} exists; refusing to overwrite") + aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out)) + print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True) + write_sidecars(a, plan) + print(f"merge done in {time.time() - t0:.0f}s", flush=True) + + +def write_sidecars(a, plan): + eps, paper = plan["episodes"], plan["paper"] + lff = os.path.join(a.out, "lff") + for sub in ("annotations", "sim_state", "final", "code"): + os.makedirs(os.path.join(lff, sub), exist_ok=True) + rows, runs, tasks = [], {}, {} + for e in eps: + i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"] + name = f"episode_{i:06d}" + if os.path.exists(os.path.join(d, "sim_state.npy")): + shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy")) + shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz")) + for cam, key in (("agentview", "image"), ("wrist", "wrist_image")): + shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png")) + with open(os.path.join(lff, "annotations", name + ".json"), "w") as f: + json.dump(ann, f, indent=1, ensure_ascii=False) + rows.append(flat_row(i, ann, n, e["from"])) + tname = ann["task"]["name"] + rk = (ann["source"]["batch"], ann["source"]["run"]) + r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"), + run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"], + memory_free_chain_of=ann["source"].get("memory_free_chain_of"), + memory_free_rep=ann["source"].get("memory_free_rep"), task=tname, + seed=ann["task"]["seed"], model=ann["agent"].get("model"), + harness=ann["agent"].get("harness"), + harness_version=ann["agent"].get("harness_version"), + codex_catalog=ann["agent"].get("codex_catalog"), + outcome_class=ann["run_outcome"].get("outcome_class"), + attempt_history=ann["run_outcome"].get("attempt_history"), + agent_final_report=ann["run_outcome"].get("agent_final_report"), + episodes=[])) + for x in ann["attempts"]: + r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success"))) + if tname not in tasks: + tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")} + if tname in paper: + tasks[tname]["paper"] = paper[tname] + tasks[tname]["instances"] = {} + tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"] + # memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id) + by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")} + for r in runs.values(): + if r.get("memory_free_chain_of"): + r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"])) + for (b, rn), r in runs.items(): + r["memory_free_retries"] = sorted((x["run"] for x in runs.values() + if x["batch"] == b and x.get("memory_free_chain_of_run") == rn), + key=lambda q: runs[(b, q)].get("memory_free_rep") or 0) + with open(os.path.join(lff, "episodes.jsonl"), "w") as f: + for row in rows: + f.write(json.dumps(row, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "runs.jsonl"), "w") as f: + for r in runs.values(): + f.write(json.dumps(r, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "tasks.json"), "w") as f: + json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False) + with open(os.path.join(lff, "batches.json"), "w") as f: + json.dump(BATCH_NOTES, f, indent=1) + with open(os.path.join(lff, "rejected.json"), "w") as f: + json.dump(plan["rejected"], f, indent=1) + here = os.path.dirname(os.path.abspath(__file__)) + for s in ("lerobot_replay.py", "lerobot_export.py"): + shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("step", choices=["plan", "shard", "merge"]) + ap.add_argument("--work", required=True) + ap.add_argument("--raw", default="") + ap.add_argument("--runs-root", default="") + ap.add_argument("--out", default="") + ap.add_argument("--paper", default="") + ap.add_argument("--task-set", default="") + ap.add_argument("--repo-id", default="lffbench/agent-replays") + ap.add_argument("--batches", default="") + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--shard", type=int, default=0) + ap.add_argument("--nshards", type=int, default=1) + ap.add_argument("--threads", type=int, default=2) + ap.add_argument("--vcodec", default="libsvtav1") + a = ap.parse_args() + {"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a) + + +if __name__ == "__main__": + main() diff --git a/leaf/code/supp-20261113-rcc_dev09_sonnet_20261111/lerobot_replay.py b/leaf/code/supp-20261113-rcc_dev09_sonnet_20261111/lerobot_replay.py new file mode 100644 index 0000000000000000000000000000000000000000..4c43a69bdb066327b27614bc9efda53d4a74e931 --- /dev/null +++ b/leaf/code/supp-20261113-rcc_dev09_sonnet_20261111/lerobot_replay.py @@ -0,0 +1,744 @@ +"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay +against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the +LeRobot export (scripts/lerobot_export.py). + + python scripts/lerobot_replay.py check [ ...] [--json out.json] # replay only, print fidelity + python scripts/lerobot_replay.py record --out [--res 256] + +Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot +commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite +is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly +like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same +outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width, +ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code +hashes equal the current files are expected to match (check_code()). + +Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB, +proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes: +protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode +per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the +fidelity check runs in record mode too. Per episode the recorder writes ///epNN/: + agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes) + frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase + sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel) + final_*.png, final.npz observation after the last control step (the state the outcome was judged in) + annotation.json episode annotation (build_annotation) +and ///replay.json (fidelity) when the whole run is done. +""" +import argparse +import ast +import hashlib +import importlib +import json +import math +import os +import pkgutil +import re +import shutil +import sys +import time +from collections import defaultdict + +import numpy as np + +LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, LFF_ROOT) + +from lffbench import envs # noqa: E402 +from lffbench import tasks as task_pkg # noqa: E402 +from lffbench.agent import camera as C # noqa: E402 +from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402 +from lffbench.task_base import TASKS # noqa: E402 + +for _m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{_m.name}") + +# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the +# task's outcome() check after `finish` (the arm holds still; not an agent action) +PHASES = {"move": 0, "gripper": 1, "judge": 2} +FPS = 20 +SCHEMA = "lff-replay-1" + +# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR" +ERROR_FLAGS = ("trap_fired", "recovered_in_attempt") +ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events", + "n_missed_strikes", "n_open_gripper_pushes") + + +def load_jsonl(p): + out = [] + if not os.path.exists(p): + return out + with open(p) as f: + for line in f: + line = line.strip() + if line: + try: + out.append(json.loads(line)) + except ValueError: + pass + return out + + +def norm_json(o): + return json.loads(json.dumps(o, default=_json_default)) + + +def sha256(p): + with open(p, "rb") as f: + return hashlib.sha256(f.read()).hexdigest() + + +def check_code(run_dir): + """[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract.""" + p = os.path.join(run_dir, "contract.json") + if not os.path.exists(p): + return [("contract.json", None, None)] + files = json.load(open(p))["contract"].get("server_code_files", {}) + bad = [] + for f, h in files.items(): + q = os.path.join(LFF_ROOT, f) + cur = sha256(q) if os.path.exists(q) else None + if cur != h: + bad.append((f, h, cur)) + return bad + + +def diff_json(a, b, path="", tol=0.0, out=None, limit=20): + """Differences between two JSON values (numbers compared with an absolute tolerance).""" + out = [] if out is None else out + if len(out) >= limit: + return out + if isinstance(a, dict) and isinstance(b, dict): + for k in sorted(set(a) | set(b)): + if k not in a or k not in b: + out.append((f"{path}.{k}", a.get(k, ""), b.get(k, ""))) + else: + diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit) + elif isinstance(a, list) and isinstance(b, list): + if len(a) != len(b): + out.append((path, f"len {len(a)}", f"len {len(b)}")) + else: + for i, (x, y) in enumerate(zip(a, b)): + diff_json(x, y, f"{path}[{i}]", tol, out, limit) + elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))): + if a != b: + out.append((path, a, b)) + elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))): + out.append((path, a, b)) + return out + + +def error_event(o): + """True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none.""" + if not isinstance(o, dict): + return None + keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o] + if not keys: + return None + return any(bool(o[k]) for k in ERROR_FLAGS if k in o) or any((o.get(k) or 0) > 0 for k in ERROR_COUNTS if k in o) + + +# ====================================================================================================== logs -> notes + +class RunLog: + """Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's + narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition.""" + + def __init__(self, run_dir, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run = os.path.basename(self.run_dir) + self.batch = os.path.basename(os.path.dirname(self.run_dir)) + self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl")) + self.start = next(e for e in self.ev if e["ev"] == "session_start") + self.calls, self.dones, self.harness_status = {}, [], [] + last = None + for e in self.ev: + if e["ev"] == "call": + self.calls[(int(e["attempt"]), int(e["step"]))] = e + last = e + elif e["ev"] == "done": + self.dones.append(e) + last = e + elif e["ev"] == "http" and last is not None and "think_s" not in last: + ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \ + (last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe")) + if ok: + last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s") + self.manifest = manifest or {} + self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {} + p = os.path.join(self.run_dir, "harness.json") + self.harness = json.load(open(p)) if os.path.exists(p) else {} + self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl")) + self._narration() + + # ---------------------------------------------------------------- agent narration + def _narration(self): + """notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one; + finish_notes[attempt] likewise for the agent's finish call; final_report = its last message.""" + self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", [] + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + attempt = 1 + + def take(): + nonlocal buf + out = {k: v for k, v in buf.items() if v} + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + return out + + last_msg = "" + for t in self.traj: + if t.get("kind") == "header": + self.headers.append(t.get("agent") or {}) + continue + if t.get("kind") != "step": + continue + if (t.get("message") or "").strip(): + buf["messages"].append(t["message"].strip()) + last_msg = t["message"].strip() + if (t.get("reasoning_content") or "").strip(): + buf["reasoning"].append(t["reasoning_content"].strip()) + res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])} + for c in t.get("tool_calls") or []: + fn, args = c.get("function_name"), c.get("arguments") or {} + if fn == "shell": + buf["shell"].append(str(args.get("command", ""))[:2000]) + elif fn == "view_images": + buf["viewed"].extend(args.get("paths") or []) + elif fn == "robot": + cmd = str(args.get("command", "")).strip() + r = res.get(c.get("tool_call_id")) or {} + try: + rep = json.loads(r.get("content") or "{}") + except ValueError: + rep = {} + word = cmd.split()[0] if cmd else "" + m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", ""))) + if word in ("move_eef", "observe") and m: + a, s = int(m.group(1)), int(m.group(2)) + n = take() + n["command"] = cmd + self.notes[(a, s)] = n + attempt = a + elif word in ("finish", "done"): + n = take() + n["command"] = cmd + n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)} + self.finish_notes.setdefault(attempt, n) + if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"): + attempt += 1 + # status / help / errors: their narration stays in the buffer for the next command + self.final_report = last_msg + + # ---------------------------------------------------------------- run-level labels + def attempts(self): + out = [] + for e in self.dones: + o = e.get("outcome") or {} + if isinstance(o, str): + try: + o = ast.literal_eval(o) + except (ValueError, SyntaxError): + o = {} + out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o, + reason=e.get("reason") or "")) + return sorted(out, key=lambda x: x["attempt"]) + + def condition(self): + s, en = self.start, self.entry + mem = s.get("memory", en.get("mem")) + chain = en.get("chain") + if mem == "full": + cond = "with_history" + elif chain: + cond = "memory_free_retry" + else: + cond = "independent_single_attempt" + return cond, chain + + def outcome_class(self): + """CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None.""" + att = self.attempts() + if not att or self.start.get("memory") != "full": + return None, "".join("S" if a["success"] else "F" for a in att) + hist = "".join("S" if a["success"] else "F" for a in att) + if att[0]["success"]: + ev = error_event(att[0]["outcome"]) + cls = "S?" if ev is None else ("IR" if ev else "CS") + else: + cls = "XR" if any(a["success"] for a in att) else "F" + return cls, hist + + def agent_info(self): + h, en = self.harness, self.entry + hdr = self.headers[0] if self.headers else {} + return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"), + harness_version=h.get("version") or hdr.get("version"), + harness_binary_sha256=(h.get("binary") or {}).get("sha256"), + model=h.get("model") or en.get("model") or hdr.get("model_name"), + effort=h.get("effort") or en.get("effort") or hdr.get("effort"), + provider=h.get("provider") or en.get("provider"), + codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"), + jail=en.get("jail")) + + +# ====================================================================================================== recording + +class EpisodeSink: + """Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed.""" + + def __init__(self, path): + self.path = path + os.makedirs(path, exist_ok=True) + self.w = None + self.num = defaultdict(list) + self.n = 0 + + def add(self, st, imgs): + import imageio + if self.w is None: + self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb", + pixelformat="rgb24", macro_block_size=1, + ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error") + for k in ("agentview", "wrist")] + for w, im in zip(self.w, imgs): + w.append_data(im) + for k, v in st.items(): + self.num[k].append(v) + self.n += 1 + + def close(self, final_state, final_imgs): + from PIL import Image + if self.w is not None: + for w in self.w: + w.close() + arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"} + np.savez(os.path.join(self.path, "frames.npz"), **arr) + if self.num.get("sim_state"): + np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64)) + np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()}) + for k, im in zip(("agentview", "wrist"), final_imgs): + Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png")) + + +class Recorder: + """Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink.""" + + def __init__(self, rp, res): + self.rp, self.res = rp, int(res) + self.active = False + self.sink = None + self.cur = dict(attempt=1, command=-1, phase=PHASES["move"]) + env = rp.task.env + self.env, self.rob = env, env.robots[0] + self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist")) + orig = env.step + + def step(a): + if self.active and self.sink is not None: + self.capture(np.asarray(a, np.float64)) + out = orig(a) + if self.active and self.sink is not None: + self.rp.poll_events(self.sink.n - 1) + return out + + env.step = step + + @property + def n(self): + return self.sink.n if self.sink is not None else 0 + + def state(self): + import robosuite.utils.transform_utils as T + env, rob = self.env, self.rob + d = env.sim.data + eef = np.array(d.site_xpos[rob.eef_site_id], np.float64) + q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw") + gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64) + try: + flat = np.asarray(env.sim.get_state().flatten(), np.float64) + except Exception: + flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64) + sk = self.rp.task.sk + return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64), + gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64), + joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64), + gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64), + eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)), + sim_time=np.float64(d.time), sim_state=flat) + + def images(self): + return [envs.render(self.env, c, self.res) for c in self.cams] + + def capture(self, a): + st = self.state() + st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]), + phase=np.int64(self.cur["phase"])) + self.sink.add(st, self.images()) + + +class RunReplay: + def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run_name = os.path.basename(self.run_dir) + self.log = RunLog(self.run_dir, manifest) + self.ev = self.log.ev + self.start = self.log.start + cp = os.path.join(self.run_dir, "contract.json") + self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {} + spec = self.contract.get("image_spec") or {} + self.image_res = int(spec.get("width", 512)) + self.code_diff = check_code(self.run_dir) + s = self.start + self.task = TASKS[s["task"]](cam_res=self.image_res) + inst = self.task.sample_instance(s["seed"]) + logged = s.get("inst") or {} + sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")}) + self.inst_diff = diff_json(sampled, logged, "inst") + if s.get("arm", "none") not in (None, "none") or logged.get("nominal"): + inst.update(logged) # controlled arms / nominal: the server overrode these instance fields + self.inst_diff = [] + self.inst = inst + self.protocol = getattr(self.task, "protocol", "cross") + self.k = int(s.get("k") or self.task.max_attempts) + self.attempt = 1 + self.mismatch = [] # (where, what, logged, replayed) + self.n_checked = 0 + self.max_dev_m = 0.0 + self.unfinished = None + self.rec = Recorder(self, res) if record else None + self.res = int(res) + self.out_root = out_root + self.n_mon = 0 + self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0 + self.episodes = [] # summaries of the written episodes + self.task.reset_instance(self.inst) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + sim = self.task.env.sim + bid = sim.model.body_name2id("robot0_base") + self.base_off = np.array(sim.data.body_xpos[bid], float).copy() + if self.rec: + self._open_episode() + + # ------------------------------------------------------------------ episodes + def _ep_dir(self): + return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}") + + def _open_episode(self): + self.rec.sink = EpisodeSink(self._ep_dir()) + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.rec.active = True + self.events, self.spans, self.ep_attempts = [], [], [] + self.ep_initial = self.rec.state() # state right after the reset (before frame 0) + + def close_episode(self): + if not self.rec: + self.ep_attempts = [] + return + sink = self.rec.sink + st = self.rec.state() + imgs = self.rec.images() + st.pop("sim_state", None) + sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs) + ann = build_annotation(self, sink) + with open(os.path.join(sink.path, "annotation.json"), "w") as f: + json.dump(ann, f, indent=1, default=_json_default) + self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n, + attempts=[a["attempt"] for a in self.ep_attempts])) + self.rec.active = False + self.rec.sink = None + self.ep_index += 1 + + # ------------------------------------------------------------------ monitor events (task-side error events) + def poll_events(self, frame): + mon = getattr(self.task, "mon", None) + evs = mon.get("events") if isinstance(mon, dict) else None + if not isinstance(evs, list): + return + if len(evs) < self.n_mon: # monitor was rebuilt + self.n_mon = 0 + for e in evs[self.n_mon:]: + self.events.append(dict(frame=int(frame), attempt=self.attempt, + event=norm_json(e) if isinstance(e, dict) else str(e))) + self.n_mon = len(evs) + + # ------------------------------------------------------------------ state as the server reports it + def proprio_la(self): + p = self.ex.proprio() + pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off] + return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"]) + + def compare(self, where, rep_logged, rep): + self.n_checked += 1 + for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"): + if k not in rep_logged or k not in rep: + continue + a, b = rep_logged[k], rep[k] + if k == "eef_pos": + dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float)))) + self.max_dev_m = max(self.max_dev_m, dev) + if dev > 1.5e-4: + self.mismatch.append((where, k, a, b)) + elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4): + self.mismatch.append((where, k, a, b)) + if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)): + self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok"))) + + def _span(self, e, f0, kind): + if self.rec: + self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0, + frame_end=self.rec.n)) + + # ------------------------------------------------------------------ commands (robot_server._handle_v2) + def move_eef(self, e): + args = e.get("args") or {} + where = f"a{e['attempt']}s{e['step']}" + logged = e.get("report") or {} + f0 = self.rec.n if self.rec else 0 + p = self.ex.proprio() + if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}: + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + off = self.base_off + try: + cur = np.asarray(p["eef_pos"], float) - off + tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")] + yaw = float(args.get("yaw", p["eef_yaw_deg"])) + speed = None if args.get("speed") in (None, "") else float(args["speed"]) + except (TypeError, ValueError): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + grip = args.get("gripper") + if grip not in (None, "open", "close"): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + moving = any(k in args for k in ("x", "y", "z", "yaw")) + tgt_w = np.asarray(tgt) + off + if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)): + self._span(e, f0, "rejected") + return self.compare(where, logged, dict(ok=False, **self.proprio_la())) + raw = {} + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"]) + if moving: + mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw) + if speed is not None: + mv["speed"] = speed + raw.update(self.ex.call("move_to", mv).report) + if grip is not None: + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"]) + raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report) + rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la()) + self.compare(where, logged, rep) + lr = e.get("raw") or {} + for k in ("holding_object", "touched_object"): + if k in lr and k in raw and bool(lr[k]) != bool(raw[k]): + self.mismatch.append((where, "raw." + k, lr[k], raw[k])) + self._span(e, f0, "move_eef") + + def observe(self, e): + f0 = self.rec.n if self.rec else 0 + self._span(e, f0, "observe") + + def done(self, e): + f0 = self.rec.n if self.rec else 0 + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"]) + out = self.task.outcome(self.inst) + succ = bool(out["success"]) + where = f"a{e['attempt']}done" + if succ != bool(e.get("success") in (True, "True")): + self.mismatch.append((where, "success", e.get("success"), succ)) + lo = e.get("outcome") or {} + ro = norm_json({k: v for k, v in out.items() if k != "feedback"}) + if isinstance(lo, dict): + for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8): + self.mismatch.append((where,) + d) + info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""), + feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")), + think_s=e.get("think_s")) + try: + info["feedback_f2"] = self.task.feedback(self.inst, out, "F2") + except Exception as ex_: + info["feedback_f2"] = f"" + if self.rec: + info["judge_frames"] = [f0, self.rec.n] + self.ep_attempts.append(info) + last = self.attempt >= self.k or succ or bool(out.get("terminal")) + if self.protocol == "cross" or last: + self.close_episode() + if last: + return True + self.attempt += 1 + if self.protocol == "cross": + self.task.reset_instance(self.inst) + self.n_mon = 0 + if self.rec: + self._open_episode() + elif self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + return False + + def run(self): + t0 = time.time() + finished = False + for e in self.ev: + if e["ev"] == "call": + if e.get("cmd") == "move_eef": + self.move_eef(e) + elif e.get("cmd") == "observe": + self.observe(e) + else: + self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None)) + elif e["ev"] == "done": + finished = self.done(e) + if finished: + break + self.unfinished = not finished + if not finished and self.rec and self.rec.sink is not None: + # the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged + if self.rec.n or self.ep_attempts: + self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True, + finish_reason="", feedback_shown="", auto_ended=False)) + self.close_episode() + else: + shutil.rmtree(self.rec.sink.path, ignore_errors=True) + self.rec.sink = None + self.wall_s = time.time() - t0 + return self + + def summary(self): + return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"], + protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff), + n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6), + unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1), + first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]]) + + +# ====================================================================================================== annotation + +def task_info(task, inst): + cls = type(task) + return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable", + category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"), + max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)), + instruction=cls.instruction) + + +def build_annotation(rp, sink): + """Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2 + failure description), run-level outcome class, every robot command with its frame span and the agent's narration, + task-side error events with frame indices.""" + log = rp.log + s = rp.start + cond, chain = log.condition() + cls, hist = log.outcome_class() + att_all = log.attempts() + attempts = [] + for a in rp.ep_attempts: + a = dict(a) + n = a["attempt"] + later = [x for x in att_all if x["attempt"] > n] + a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later)) + a["is_last_attempt_of_run"] = not later + fn = log.finish_notes.get(n) + if fn: + a["agent_finish"] = fn + a["error_event_in_attempt"] = error_event(a.get("outcome")) + attempts.append(a) + # post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command) + for a in attempts: + nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1]) + if a.get("success") is False and nxt: + note = log.notes[nxt[0]] + a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note} + commands = [] + for sp in rp.spans: + e = log.calls.get((sp["attempt"], sp["step"])) or {} + rep = e.get("report") or {} + c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"], + frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]), + args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"), + stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"), + gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"), + touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"), + agent_obs_images=rep.get("images")) + note = log.notes.get((sp["attempt"], sp["step"])) + if note: + c["agent_note"] = {k: v for k, v in note.items() if k != "command"} + commands.append(c) + t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x] + return dict( + schema=SCHEMA, + source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts], + episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain, + memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None), + feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"), + k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"), + contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256") + if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)), + agent=log.agent_info(), + task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"), + instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}), + run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all), + run_success=any(x["success"] for x in att_all) if att_all else None, + agent_final_report=log.final_report[:6000] or None, + mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)), + attempts=attempts, + commands=commands, + task_events=rp.events, + frames=dict(n=sink.n, fps=FPS, image_res=rp.res, + phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"], + joint_pos=rp.ep_initial["joint_pos"], + gripper_qpos=rp.ep_initial["gripper_qpos"])), + ) + + +# ====================================================================================================== CLI + +def load_manifest(run_dir): + p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json") + return json.load(open(p)) if os.path.exists(p) else {} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("mode", choices=["check", "record"]) + ap.add_argument("runs", nargs="+") + ap.add_argument("--json", default="") + ap.add_argument("--out", default="") + ap.add_argument("--res", type=int, default=256) + ap.add_argument("--force", action="store_true", help="record again even if replay.json exists") + a = ap.parse_args() + rows = [] + for r in a.runs: + r = r.rstrip("/") + try: + if a.mode == "check": + s = RunReplay(r, manifest=load_manifest(r)).run().summary() + else: + batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r) + rd = os.path.join(a.out, batch, name) + if os.path.exists(os.path.join(rd, "replay.json")) and not a.force: + print(json.dumps(dict(run=name, skipped="exists")), flush=True) + continue + shutil.rmtree(rd, ignore_errors=True) + rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run() + s = rp.summary() + s["episodes"] = rp.episodes + with open(os.path.join(rd, "replay.json"), "w") as f: + json.dump(s, f, indent=1) + except Exception: + import traceback + s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:]) + rows.append(s) + print(json.dumps(s), flush=True) + if a.json: + with open(a.json, "w") as f: + json.dump(rows, f, indent=1) + + +if __name__ == "__main__": + main() diff --git a/leaf/code/v1.5/backfill-20261102-l4i_fx_test/lerobot_export.py b/leaf/code/v1.5/backfill-20261102-l4i_fx_test/lerobot_export.py new file mode 100644 index 0000000000000000000000000000000000000000..fa4fa0a1be92844c9cf410663f77de5e200bda18 --- /dev/null +++ b/leaf/code/v1.5/backfill-20261102-l4i_fx_test/lerobot_export.py @@ -0,0 +1,431 @@ +"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars. + +Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding +can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan): + + python scripts/lerobot_export.py plan --raw [,] --runs-root /runs/api \ + --paper --task-set /sets/main_v2_1inst.txt --work [--batches ...] [--limit N] + python scripts/lerobot_export.py shard --work --shard i --nshards N + python scripts/lerobot_export.py merge --work --nshards N --out + +Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0 +mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped. + +LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t): + observation.images.image agentview RGB 256x256 (upright; LIBERO naming) + observation.images.wrist_image wrist (eye-in-hand) RGB 256x256 + observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout) + observation.joint_pos / joint_vel 7 arm joints (rad, rad/s) + observation.eef_quat 4: xyzw; observation.gripper_width 1 (m) + action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad), + gripper (-1 open, +1 close) + annotation.attempt_index attempt (1-based) the frame belongs to + annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`) + annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action) + annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt + annotation.task_event number of task-monitor events (error / progress events) registered at this step +Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table), +runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state +per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/. +""" +import argparse +import glob +import json +import os +import re +import shutil +import time + +import numpy as np + +FPS = 20 +RES = 256 +BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke", + "cc_smoke", "cc_opus_smoke"] +BATCH_NOTES = { + "cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog", + "cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267", + "cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299", + "cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances", + "cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)", + "cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the " + "with-history continuation of failed runs is incomplete", + "cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early", + "cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt", + "cc_opus_smoke": "smoke test: single attempt", +} +PHASES = {"move": 0, "gripper": 1, "judge": 2} +CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)", + "L2": "disturbed state to restore (incl. damage the agent causes)", + "L3": "infeasible manipulation strategy (grasp / contact / tool must change)", + "L4": "misjudged geometry (size, shape, fit, hidden structure)", + "L5": "misjudged physics (mass distribution, friction, dynamics)"} + + +def features(): + vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]} + f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names} + i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None} + return { + "observation.images.image": vid(), + "observation.images.wrist_image": vid(), + "observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z", + "finger_qpos_left", "finger_qpos_right"]), + "observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]), + "observation.gripper_width": f32(1, ["width_m"]), + "action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y", + "eef_delta_rot_aa_z", "gripper_close"]), + "annotation.attempt_index": i64(), + "annotation.command_index": i64(), + "annotation.phase": i64(), + "annotation.attempt_success": i64(), + "annotation.task_event": i64(), + } + + +# ------------------------------------------------------------------------------------------------ paper metadata + +def _clean_tex(s): + s = re.sub(r"%.*", "", s) + for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"), + (r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"), + (r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"), + (r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"), + (r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]: + s = re.sub(a, b, s) + s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s) + s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s) + for _ in range(3): + s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\$([^$]*)\$", r"\1", s) + s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ") + s = re.sub(r"\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\\[a-zA-Z]+\*?", "", s) + return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip() + + +def paper_tasks(paper_dir): + """{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the + paper's task table and task appendix (empty if the paper sources are not there).""" + out = {} + if not paper_dir: + return out + app = os.path.join(paper_dir, "sections", "appendix_tasks.tex") + tab = os.path.join(paper_dir, "sections", "tab_tasks.tex") + if os.path.exists(app): + txt = open(app).read() + parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt) + for i in range(1, len(parts) - 1, 2): + if parts[i] != "\\paragraph{": + continue + body = parts[i + 1] + m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S) + if not m: + continue + name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip() + desc = _clean_tex(body[m.end():]) + out[code] = dict(name=name, cause=_clean_tex(cause), description=desc) + if os.path.exists(tab): + names = {v["name"].lower(): k for k, v in out.items()} + for line in open(tab): + cells = [c.strip() for c in line.split("&")] + if len(cells) != 6 or not cells[-1].endswith("\\\\"): + continue + nm = re.sub(r"\\contscene", "", cells[0]).strip().lower() + code = names.get(nm) + if not code: + continue + out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]), + repair_within_attempt=_clean_tex(cells[3]) == "yes", + oracle_first_attempt_pct=_clean_tex(cells[4]), + naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip())) + return out + + +# ------------------------------------------------------------------------------------------------ collection + +def manifest_status(runs_root, batch, run, cache={}): + if batch not in cache: + p = os.path.join(runs_root, batch, "manifest.json") + cache[batch] = json.load(open(p)) if os.path.exists(p) else {} + m = cache[batch] + for r in m.get("runs", []): + if r.get("run") == run: + return r.get("status", "?"), r + for r in m.get("superseded", []): + if r.get("run") == run: + return "superseded_" + str(r.get("status", "?")), r + return "not_in_manifest", {} + + +def collect(raw_roots, runs_root, batches, task_order): + """Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root.""" + eps, rejected, seen = [], [], set() + for root in raw_roots: + for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))): + rep = json.load(open(rj)) + batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"] + if (batches and batch not in batches) or (batch, run) in seen: + continue + seen.add((batch, run)) + ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff") + status, entry = manifest_status(runs_root, batch, run) + if not ok: + never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked") + rejected.append(dict(run=run, batch=batch, run_status=status, + reason="run never started (no contract, no robot command)" if never else + "replay does not reproduce the log (the log has gaps or the replay diverged)", + detail=rep.get("first_mismatches"))) + continue + for ep in rep.get("episodes", []): + d = os.path.join(root, ep["dir"]) + ann = json.load(open(os.path.join(d, "annotation.json"))) + judged = [a for a in ann["attempts"] if a.get("success") is not None] + if not judged or ep["n_frames"] == 0: + rejected.append(dict(run=run, batch=batch, episode=ep["dir"], + reason="no judged attempt" if not judged else "no frames")) + continue + ann["source"]["run_status"] = status + ann["source"]["manifest_id"] = entry.get("id") + ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"], + max_eef_dev_m=rep["max_eef_dev_m"]) + key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99), + {"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2), + ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"]) + eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann)) + eps.sort(key=lambda x: x["key"]) + return eps, rejected + + +# ------------------------------------------------------------------------------------------------ writing + +def frames_of(path): + import av + with av.open(path) as c: + for fr in c.decode(video=0): + yield fr.to_ndarray(format="rgb24") + + +def flat_row(i, ann, n, idx0): + s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"] + att = ann["attempts"] + a0 = att[0] + return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n, + batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"], + memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"), + episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att], + harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"), + effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"), + task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"), + category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"], + success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att], + feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att], + auto_ended=[a.get("auto_ended") for a in att], + corrected_later_in_run=[a.get("corrected_later_in_run") for a in att], + error_event_in_attempt=[a.get("error_event_in_attempt") for a in att], + run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"), + n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]), + first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None) + + +def cmd_plan(a): + task_order = {} + if a.task_set and os.path.exists(a.task_set): + for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")): + task_order[line.split(":")[0].strip()] = i + batches = [b for b in a.batches.split(",") if b] if a.batches else None + eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order) + if a.limit: + eps = eps[:a.limit] + paper = paper_tasks(a.paper) + idx0 = 0 + for i, e in enumerate(eps): + ann = e["ann"] + tname = ann["task"]["name"] + if tname in paper: + ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"} + ann["episode_index"] = i + ann["dataset_index_range"] = [idx0, idx0 + e["n"]] + e["index"], e["from"] = i, idx0 + idx0 += e["n"] + del e["key"] + os.makedirs(a.work, exist_ok=True) + with open(os.path.join(a.work, "plan.json"), "w") as f: + json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f, + ensure_ascii=False) + print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True) + + +def shard_range(n_eps, i, k): + return (n_eps * i) // k, (n_eps * (i + 1)) // k + + +def cmd_shard(a): + from lerobot.datasets.lerobot_dataset import LeRobotDataset + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + lo, hi = shard_range(len(eps), a.shard, a.nshards) + out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}") + if os.path.exists(os.path.join(out, "DONE")): + print(f"shard {a.shard}: done already", flush=True) + return + shutil.rmtree(out, ignore_errors=True) + ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out, + robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads, + vcodec=a.vcodec) + nfr = 0 + for e in eps[lo:hi]: + d, ann, n = e["dir"], e["ann"], e["n"] + fr = np.load(os.path.join(d, "frames.npz")) + assert len(fr["action"]) == n, d + succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]} + evc = np.zeros(n, np.int64) + for ev in ann["task_events"]: + if 0 <= ev["frame"] < n: + evc[ev["frame"]] += 1 + state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32) + instr = ann["task"]["instruction"] + k = 0 + for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))): + if k >= n: + break + ds.add_frame({ + "observation.images.image": img, "observation.images.wrist_image": wr, + "observation.state": state[k], + "observation.joint_pos": fr["joint_pos"][k].astype(np.float32), + "observation.joint_vel": fr["joint_vel"][k].astype(np.float32), + "observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32), + "observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32), + "action": fr["action"][k].astype(np.float32), + "annotation.attempt_index": np.array([fr["attempt"][k]], np.int64), + "annotation.command_index": np.array([fr["command"][k]], np.int64), + "annotation.phase": np.array([fr["phase"][k]], np.int64), + "annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64), + "annotation.task_event": np.array([evc[k]], np.int64), + "task": instr, + }) + k += 1 + if k != n: + raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames") + ds.save_episode() + nfr += n + ds.finalize() + shutil.rmtree(os.path.join(out, "images"), ignore_errors=True) + open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n") + print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True) + + +def cmd_merge(a): + from pathlib import Path + from lerobot.datasets.aggregate import aggregate_datasets + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + roots, ids = [], [] + for i in range(a.nshards): + lo, hi = shard_range(len(eps), i, a.nshards) + if hi <= lo: + continue + r = os.path.join(a.work, "shards", f"shard_{i:03d}") + if not os.path.exists(os.path.join(r, "DONE")): + raise SystemExit(f"shard {i} is not done") + roots.append(Path(r)) + ids.append(f"{plan['repo_id']}-shard{i:03d}") + if os.path.exists(a.out): + raise SystemExit(f"{a.out} exists; refusing to overwrite") + aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out)) + print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True) + write_sidecars(a, plan) + print(f"merge done in {time.time() - t0:.0f}s", flush=True) + + +def write_sidecars(a, plan): + eps, paper = plan["episodes"], plan["paper"] + lff = os.path.join(a.out, "lff") + for sub in ("annotations", "sim_state", "final", "code"): + os.makedirs(os.path.join(lff, sub), exist_ok=True) + rows, runs, tasks = [], {}, {} + for e in eps: + i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"] + name = f"episode_{i:06d}" + if os.path.exists(os.path.join(d, "sim_state.npy")): + shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy")) + shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz")) + for cam, key in (("agentview", "image"), ("wrist", "wrist_image")): + shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png")) + with open(os.path.join(lff, "annotations", name + ".json"), "w") as f: + json.dump(ann, f, indent=1, ensure_ascii=False) + rows.append(flat_row(i, ann, n, e["from"])) + tname = ann["task"]["name"] + rk = (ann["source"]["batch"], ann["source"]["run"]) + r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"), + run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"], + memory_free_chain_of=ann["source"].get("memory_free_chain_of"), + memory_free_rep=ann["source"].get("memory_free_rep"), task=tname, + seed=ann["task"]["seed"], model=ann["agent"].get("model"), + harness=ann["agent"].get("harness"), + harness_version=ann["agent"].get("harness_version"), + codex_catalog=ann["agent"].get("codex_catalog"), + outcome_class=ann["run_outcome"].get("outcome_class"), + attempt_history=ann["run_outcome"].get("attempt_history"), + agent_final_report=ann["run_outcome"].get("agent_final_report"), + episodes=[])) + for x in ann["attempts"]: + r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success"))) + if tname not in tasks: + tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")} + if tname in paper: + tasks[tname]["paper"] = paper[tname] + tasks[tname]["instances"] = {} + tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"] + # memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id) + by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")} + for r in runs.values(): + if r.get("memory_free_chain_of"): + r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"])) + for (b, rn), r in runs.items(): + r["memory_free_retries"] = sorted((x["run"] for x in runs.values() + if x["batch"] == b and x.get("memory_free_chain_of_run") == rn), + key=lambda q: runs[(b, q)].get("memory_free_rep") or 0) + with open(os.path.join(lff, "episodes.jsonl"), "w") as f: + for row in rows: + f.write(json.dumps(row, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "runs.jsonl"), "w") as f: + for r in runs.values(): + f.write(json.dumps(r, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "tasks.json"), "w") as f: + json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False) + with open(os.path.join(lff, "batches.json"), "w") as f: + json.dump(BATCH_NOTES, f, indent=1) + with open(os.path.join(lff, "rejected.json"), "w") as f: + json.dump(plan["rejected"], f, indent=1) + here = os.path.dirname(os.path.abspath(__file__)) + for s in ("lerobot_replay.py", "lerobot_export.py"): + shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("step", choices=["plan", "shard", "merge"]) + ap.add_argument("--work", required=True) + ap.add_argument("--raw", default="") + ap.add_argument("--runs-root", default="") + ap.add_argument("--out", default="") + ap.add_argument("--paper", default="") + ap.add_argument("--task-set", default="") + ap.add_argument("--repo-id", default="lffbench/agent-replays") + ap.add_argument("--batches", default="") + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--shard", type=int, default=0) + ap.add_argument("--nshards", type=int, default=1) + ap.add_argument("--threads", type=int, default=2) + ap.add_argument("--vcodec", default="libsvtav1") + a = ap.parse_args() + {"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a) + + +if __name__ == "__main__": + main() diff --git a/leaf/code/v1.5/backfill-20261102-l4i_fx_test/lerobot_replay.py b/leaf/code/v1.5/backfill-20261102-l4i_fx_test/lerobot_replay.py new file mode 100644 index 0000000000000000000000000000000000000000..4c43a69bdb066327b27614bc9efda53d4a74e931 --- /dev/null +++ b/leaf/code/v1.5/backfill-20261102-l4i_fx_test/lerobot_replay.py @@ -0,0 +1,744 @@ +"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay +against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the +LeRobot export (scripts/lerobot_export.py). + + python scripts/lerobot_replay.py check [ ...] [--json out.json] # replay only, print fidelity + python scripts/lerobot_replay.py record --out [--res 256] + +Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot +commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite +is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly +like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same +outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width, +ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code +hashes equal the current files are expected to match (check_code()). + +Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB, +proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes: +protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode +per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the +fidelity check runs in record mode too. Per episode the recorder writes ///epNN/: + agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes) + frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase + sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel) + final_*.png, final.npz observation after the last control step (the state the outcome was judged in) + annotation.json episode annotation (build_annotation) +and ///replay.json (fidelity) when the whole run is done. +""" +import argparse +import ast +import hashlib +import importlib +import json +import math +import os +import pkgutil +import re +import shutil +import sys +import time +from collections import defaultdict + +import numpy as np + +LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, LFF_ROOT) + +from lffbench import envs # noqa: E402 +from lffbench import tasks as task_pkg # noqa: E402 +from lffbench.agent import camera as C # noqa: E402 +from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402 +from lffbench.task_base import TASKS # noqa: E402 + +for _m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{_m.name}") + +# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the +# task's outcome() check after `finish` (the arm holds still; not an agent action) +PHASES = {"move": 0, "gripper": 1, "judge": 2} +FPS = 20 +SCHEMA = "lff-replay-1" + +# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR" +ERROR_FLAGS = ("trap_fired", "recovered_in_attempt") +ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events", + "n_missed_strikes", "n_open_gripper_pushes") + + +def load_jsonl(p): + out = [] + if not os.path.exists(p): + return out + with open(p) as f: + for line in f: + line = line.strip() + if line: + try: + out.append(json.loads(line)) + except ValueError: + pass + return out + + +def norm_json(o): + return json.loads(json.dumps(o, default=_json_default)) + + +def sha256(p): + with open(p, "rb") as f: + return hashlib.sha256(f.read()).hexdigest() + + +def check_code(run_dir): + """[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract.""" + p = os.path.join(run_dir, "contract.json") + if not os.path.exists(p): + return [("contract.json", None, None)] + files = json.load(open(p))["contract"].get("server_code_files", {}) + bad = [] + for f, h in files.items(): + q = os.path.join(LFF_ROOT, f) + cur = sha256(q) if os.path.exists(q) else None + if cur != h: + bad.append((f, h, cur)) + return bad + + +def diff_json(a, b, path="", tol=0.0, out=None, limit=20): + """Differences between two JSON values (numbers compared with an absolute tolerance).""" + out = [] if out is None else out + if len(out) >= limit: + return out + if isinstance(a, dict) and isinstance(b, dict): + for k in sorted(set(a) | set(b)): + if k not in a or k not in b: + out.append((f"{path}.{k}", a.get(k, ""), b.get(k, ""))) + else: + diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit) + elif isinstance(a, list) and isinstance(b, list): + if len(a) != len(b): + out.append((path, f"len {len(a)}", f"len {len(b)}")) + else: + for i, (x, y) in enumerate(zip(a, b)): + diff_json(x, y, f"{path}[{i}]", tol, out, limit) + elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))): + if a != b: + out.append((path, a, b)) + elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))): + out.append((path, a, b)) + return out + + +def error_event(o): + """True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none.""" + if not isinstance(o, dict): + return None + keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o] + if not keys: + return None + return any(bool(o[k]) for k in ERROR_FLAGS if k in o) or any((o.get(k) or 0) > 0 for k in ERROR_COUNTS if k in o) + + +# ====================================================================================================== logs -> notes + +class RunLog: + """Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's + narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition.""" + + def __init__(self, run_dir, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run = os.path.basename(self.run_dir) + self.batch = os.path.basename(os.path.dirname(self.run_dir)) + self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl")) + self.start = next(e for e in self.ev if e["ev"] == "session_start") + self.calls, self.dones, self.harness_status = {}, [], [] + last = None + for e in self.ev: + if e["ev"] == "call": + self.calls[(int(e["attempt"]), int(e["step"]))] = e + last = e + elif e["ev"] == "done": + self.dones.append(e) + last = e + elif e["ev"] == "http" and last is not None and "think_s" not in last: + ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \ + (last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe")) + if ok: + last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s") + self.manifest = manifest or {} + self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {} + p = os.path.join(self.run_dir, "harness.json") + self.harness = json.load(open(p)) if os.path.exists(p) else {} + self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl")) + self._narration() + + # ---------------------------------------------------------------- agent narration + def _narration(self): + """notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one; + finish_notes[attempt] likewise for the agent's finish call; final_report = its last message.""" + self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", [] + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + attempt = 1 + + def take(): + nonlocal buf + out = {k: v for k, v in buf.items() if v} + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + return out + + last_msg = "" + for t in self.traj: + if t.get("kind") == "header": + self.headers.append(t.get("agent") or {}) + continue + if t.get("kind") != "step": + continue + if (t.get("message") or "").strip(): + buf["messages"].append(t["message"].strip()) + last_msg = t["message"].strip() + if (t.get("reasoning_content") or "").strip(): + buf["reasoning"].append(t["reasoning_content"].strip()) + res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])} + for c in t.get("tool_calls") or []: + fn, args = c.get("function_name"), c.get("arguments") or {} + if fn == "shell": + buf["shell"].append(str(args.get("command", ""))[:2000]) + elif fn == "view_images": + buf["viewed"].extend(args.get("paths") or []) + elif fn == "robot": + cmd = str(args.get("command", "")).strip() + r = res.get(c.get("tool_call_id")) or {} + try: + rep = json.loads(r.get("content") or "{}") + except ValueError: + rep = {} + word = cmd.split()[0] if cmd else "" + m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", ""))) + if word in ("move_eef", "observe") and m: + a, s = int(m.group(1)), int(m.group(2)) + n = take() + n["command"] = cmd + self.notes[(a, s)] = n + attempt = a + elif word in ("finish", "done"): + n = take() + n["command"] = cmd + n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)} + self.finish_notes.setdefault(attempt, n) + if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"): + attempt += 1 + # status / help / errors: their narration stays in the buffer for the next command + self.final_report = last_msg + + # ---------------------------------------------------------------- run-level labels + def attempts(self): + out = [] + for e in self.dones: + o = e.get("outcome") or {} + if isinstance(o, str): + try: + o = ast.literal_eval(o) + except (ValueError, SyntaxError): + o = {} + out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o, + reason=e.get("reason") or "")) + return sorted(out, key=lambda x: x["attempt"]) + + def condition(self): + s, en = self.start, self.entry + mem = s.get("memory", en.get("mem")) + chain = en.get("chain") + if mem == "full": + cond = "with_history" + elif chain: + cond = "memory_free_retry" + else: + cond = "independent_single_attempt" + return cond, chain + + def outcome_class(self): + """CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None.""" + att = self.attempts() + if not att or self.start.get("memory") != "full": + return None, "".join("S" if a["success"] else "F" for a in att) + hist = "".join("S" if a["success"] else "F" for a in att) + if att[0]["success"]: + ev = error_event(att[0]["outcome"]) + cls = "S?" if ev is None else ("IR" if ev else "CS") + else: + cls = "XR" if any(a["success"] for a in att) else "F" + return cls, hist + + def agent_info(self): + h, en = self.harness, self.entry + hdr = self.headers[0] if self.headers else {} + return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"), + harness_version=h.get("version") or hdr.get("version"), + harness_binary_sha256=(h.get("binary") or {}).get("sha256"), + model=h.get("model") or en.get("model") or hdr.get("model_name"), + effort=h.get("effort") or en.get("effort") or hdr.get("effort"), + provider=h.get("provider") or en.get("provider"), + codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"), + jail=en.get("jail")) + + +# ====================================================================================================== recording + +class EpisodeSink: + """Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed.""" + + def __init__(self, path): + self.path = path + os.makedirs(path, exist_ok=True) + self.w = None + self.num = defaultdict(list) + self.n = 0 + + def add(self, st, imgs): + import imageio + if self.w is None: + self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb", + pixelformat="rgb24", macro_block_size=1, + ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error") + for k in ("agentview", "wrist")] + for w, im in zip(self.w, imgs): + w.append_data(im) + for k, v in st.items(): + self.num[k].append(v) + self.n += 1 + + def close(self, final_state, final_imgs): + from PIL import Image + if self.w is not None: + for w in self.w: + w.close() + arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"} + np.savez(os.path.join(self.path, "frames.npz"), **arr) + if self.num.get("sim_state"): + np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64)) + np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()}) + for k, im in zip(("agentview", "wrist"), final_imgs): + Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png")) + + +class Recorder: + """Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink.""" + + def __init__(self, rp, res): + self.rp, self.res = rp, int(res) + self.active = False + self.sink = None + self.cur = dict(attempt=1, command=-1, phase=PHASES["move"]) + env = rp.task.env + self.env, self.rob = env, env.robots[0] + self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist")) + orig = env.step + + def step(a): + if self.active and self.sink is not None: + self.capture(np.asarray(a, np.float64)) + out = orig(a) + if self.active and self.sink is not None: + self.rp.poll_events(self.sink.n - 1) + return out + + env.step = step + + @property + def n(self): + return self.sink.n if self.sink is not None else 0 + + def state(self): + import robosuite.utils.transform_utils as T + env, rob = self.env, self.rob + d = env.sim.data + eef = np.array(d.site_xpos[rob.eef_site_id], np.float64) + q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw") + gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64) + try: + flat = np.asarray(env.sim.get_state().flatten(), np.float64) + except Exception: + flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64) + sk = self.rp.task.sk + return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64), + gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64), + joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64), + gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64), + eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)), + sim_time=np.float64(d.time), sim_state=flat) + + def images(self): + return [envs.render(self.env, c, self.res) for c in self.cams] + + def capture(self, a): + st = self.state() + st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]), + phase=np.int64(self.cur["phase"])) + self.sink.add(st, self.images()) + + +class RunReplay: + def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run_name = os.path.basename(self.run_dir) + self.log = RunLog(self.run_dir, manifest) + self.ev = self.log.ev + self.start = self.log.start + cp = os.path.join(self.run_dir, "contract.json") + self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {} + spec = self.contract.get("image_spec") or {} + self.image_res = int(spec.get("width", 512)) + self.code_diff = check_code(self.run_dir) + s = self.start + self.task = TASKS[s["task"]](cam_res=self.image_res) + inst = self.task.sample_instance(s["seed"]) + logged = s.get("inst") or {} + sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")}) + self.inst_diff = diff_json(sampled, logged, "inst") + if s.get("arm", "none") not in (None, "none") or logged.get("nominal"): + inst.update(logged) # controlled arms / nominal: the server overrode these instance fields + self.inst_diff = [] + self.inst = inst + self.protocol = getattr(self.task, "protocol", "cross") + self.k = int(s.get("k") or self.task.max_attempts) + self.attempt = 1 + self.mismatch = [] # (where, what, logged, replayed) + self.n_checked = 0 + self.max_dev_m = 0.0 + self.unfinished = None + self.rec = Recorder(self, res) if record else None + self.res = int(res) + self.out_root = out_root + self.n_mon = 0 + self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0 + self.episodes = [] # summaries of the written episodes + self.task.reset_instance(self.inst) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + sim = self.task.env.sim + bid = sim.model.body_name2id("robot0_base") + self.base_off = np.array(sim.data.body_xpos[bid], float).copy() + if self.rec: + self._open_episode() + + # ------------------------------------------------------------------ episodes + def _ep_dir(self): + return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}") + + def _open_episode(self): + self.rec.sink = EpisodeSink(self._ep_dir()) + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.rec.active = True + self.events, self.spans, self.ep_attempts = [], [], [] + self.ep_initial = self.rec.state() # state right after the reset (before frame 0) + + def close_episode(self): + if not self.rec: + self.ep_attempts = [] + return + sink = self.rec.sink + st = self.rec.state() + imgs = self.rec.images() + st.pop("sim_state", None) + sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs) + ann = build_annotation(self, sink) + with open(os.path.join(sink.path, "annotation.json"), "w") as f: + json.dump(ann, f, indent=1, default=_json_default) + self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n, + attempts=[a["attempt"] for a in self.ep_attempts])) + self.rec.active = False + self.rec.sink = None + self.ep_index += 1 + + # ------------------------------------------------------------------ monitor events (task-side error events) + def poll_events(self, frame): + mon = getattr(self.task, "mon", None) + evs = mon.get("events") if isinstance(mon, dict) else None + if not isinstance(evs, list): + return + if len(evs) < self.n_mon: # monitor was rebuilt + self.n_mon = 0 + for e in evs[self.n_mon:]: + self.events.append(dict(frame=int(frame), attempt=self.attempt, + event=norm_json(e) if isinstance(e, dict) else str(e))) + self.n_mon = len(evs) + + # ------------------------------------------------------------------ state as the server reports it + def proprio_la(self): + p = self.ex.proprio() + pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off] + return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"]) + + def compare(self, where, rep_logged, rep): + self.n_checked += 1 + for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"): + if k not in rep_logged or k not in rep: + continue + a, b = rep_logged[k], rep[k] + if k == "eef_pos": + dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float)))) + self.max_dev_m = max(self.max_dev_m, dev) + if dev > 1.5e-4: + self.mismatch.append((where, k, a, b)) + elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4): + self.mismatch.append((where, k, a, b)) + if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)): + self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok"))) + + def _span(self, e, f0, kind): + if self.rec: + self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0, + frame_end=self.rec.n)) + + # ------------------------------------------------------------------ commands (robot_server._handle_v2) + def move_eef(self, e): + args = e.get("args") or {} + where = f"a{e['attempt']}s{e['step']}" + logged = e.get("report") or {} + f0 = self.rec.n if self.rec else 0 + p = self.ex.proprio() + if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}: + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + off = self.base_off + try: + cur = np.asarray(p["eef_pos"], float) - off + tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")] + yaw = float(args.get("yaw", p["eef_yaw_deg"])) + speed = None if args.get("speed") in (None, "") else float(args["speed"]) + except (TypeError, ValueError): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + grip = args.get("gripper") + if grip not in (None, "open", "close"): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + moving = any(k in args for k in ("x", "y", "z", "yaw")) + tgt_w = np.asarray(tgt) + off + if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)): + self._span(e, f0, "rejected") + return self.compare(where, logged, dict(ok=False, **self.proprio_la())) + raw = {} + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"]) + if moving: + mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw) + if speed is not None: + mv["speed"] = speed + raw.update(self.ex.call("move_to", mv).report) + if grip is not None: + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"]) + raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report) + rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la()) + self.compare(where, logged, rep) + lr = e.get("raw") or {} + for k in ("holding_object", "touched_object"): + if k in lr and k in raw and bool(lr[k]) != bool(raw[k]): + self.mismatch.append((where, "raw." + k, lr[k], raw[k])) + self._span(e, f0, "move_eef") + + def observe(self, e): + f0 = self.rec.n if self.rec else 0 + self._span(e, f0, "observe") + + def done(self, e): + f0 = self.rec.n if self.rec else 0 + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"]) + out = self.task.outcome(self.inst) + succ = bool(out["success"]) + where = f"a{e['attempt']}done" + if succ != bool(e.get("success") in (True, "True")): + self.mismatch.append((where, "success", e.get("success"), succ)) + lo = e.get("outcome") or {} + ro = norm_json({k: v for k, v in out.items() if k != "feedback"}) + if isinstance(lo, dict): + for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8): + self.mismatch.append((where,) + d) + info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""), + feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")), + think_s=e.get("think_s")) + try: + info["feedback_f2"] = self.task.feedback(self.inst, out, "F2") + except Exception as ex_: + info["feedback_f2"] = f"" + if self.rec: + info["judge_frames"] = [f0, self.rec.n] + self.ep_attempts.append(info) + last = self.attempt >= self.k or succ or bool(out.get("terminal")) + if self.protocol == "cross" or last: + self.close_episode() + if last: + return True + self.attempt += 1 + if self.protocol == "cross": + self.task.reset_instance(self.inst) + self.n_mon = 0 + if self.rec: + self._open_episode() + elif self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + return False + + def run(self): + t0 = time.time() + finished = False + for e in self.ev: + if e["ev"] == "call": + if e.get("cmd") == "move_eef": + self.move_eef(e) + elif e.get("cmd") == "observe": + self.observe(e) + else: + self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None)) + elif e["ev"] == "done": + finished = self.done(e) + if finished: + break + self.unfinished = not finished + if not finished and self.rec and self.rec.sink is not None: + # the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged + if self.rec.n or self.ep_attempts: + self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True, + finish_reason="", feedback_shown="", auto_ended=False)) + self.close_episode() + else: + shutil.rmtree(self.rec.sink.path, ignore_errors=True) + self.rec.sink = None + self.wall_s = time.time() - t0 + return self + + def summary(self): + return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"], + protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff), + n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6), + unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1), + first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]]) + + +# ====================================================================================================== annotation + +def task_info(task, inst): + cls = type(task) + return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable", + category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"), + max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)), + instruction=cls.instruction) + + +def build_annotation(rp, sink): + """Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2 + failure description), run-level outcome class, every robot command with its frame span and the agent's narration, + task-side error events with frame indices.""" + log = rp.log + s = rp.start + cond, chain = log.condition() + cls, hist = log.outcome_class() + att_all = log.attempts() + attempts = [] + for a in rp.ep_attempts: + a = dict(a) + n = a["attempt"] + later = [x for x in att_all if x["attempt"] > n] + a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later)) + a["is_last_attempt_of_run"] = not later + fn = log.finish_notes.get(n) + if fn: + a["agent_finish"] = fn + a["error_event_in_attempt"] = error_event(a.get("outcome")) + attempts.append(a) + # post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command) + for a in attempts: + nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1]) + if a.get("success") is False and nxt: + note = log.notes[nxt[0]] + a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note} + commands = [] + for sp in rp.spans: + e = log.calls.get((sp["attempt"], sp["step"])) or {} + rep = e.get("report") or {} + c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"], + frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]), + args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"), + stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"), + gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"), + touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"), + agent_obs_images=rep.get("images")) + note = log.notes.get((sp["attempt"], sp["step"])) + if note: + c["agent_note"] = {k: v for k, v in note.items() if k != "command"} + commands.append(c) + t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x] + return dict( + schema=SCHEMA, + source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts], + episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain, + memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None), + feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"), + k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"), + contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256") + if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)), + agent=log.agent_info(), + task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"), + instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}), + run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all), + run_success=any(x["success"] for x in att_all) if att_all else None, + agent_final_report=log.final_report[:6000] or None, + mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)), + attempts=attempts, + commands=commands, + task_events=rp.events, + frames=dict(n=sink.n, fps=FPS, image_res=rp.res, + phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"], + joint_pos=rp.ep_initial["joint_pos"], + gripper_qpos=rp.ep_initial["gripper_qpos"])), + ) + + +# ====================================================================================================== CLI + +def load_manifest(run_dir): + p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json") + return json.load(open(p)) if os.path.exists(p) else {} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("mode", choices=["check", "record"]) + ap.add_argument("runs", nargs="+") + ap.add_argument("--json", default="") + ap.add_argument("--out", default="") + ap.add_argument("--res", type=int, default=256) + ap.add_argument("--force", action="store_true", help="record again even if replay.json exists") + a = ap.parse_args() + rows = [] + for r in a.runs: + r = r.rstrip("/") + try: + if a.mode == "check": + s = RunReplay(r, manifest=load_manifest(r)).run().summary() + else: + batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r) + rd = os.path.join(a.out, batch, name) + if os.path.exists(os.path.join(rd, "replay.json")) and not a.force: + print(json.dumps(dict(run=name, skipped="exists")), flush=True) + continue + shutil.rmtree(rd, ignore_errors=True) + rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run() + s = rp.summary() + s["episodes"] = rp.episodes + with open(os.path.join(rd, "replay.json"), "w") as f: + json.dump(s, f, indent=1) + except Exception: + import traceback + s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:]) + rows.append(s) + print(json.dumps(s), flush=True) + if a.json: + with open(a.json, "w") as f: + json.dump(rows, f, indent=1) + + +if __name__ == "__main__": + main() diff --git a/leaf/code/v1.5/backfill-20261102-l4i_v_test/lerobot_export.py b/leaf/code/v1.5/backfill-20261102-l4i_v_test/lerobot_export.py new file mode 100644 index 0000000000000000000000000000000000000000..fa4fa0a1be92844c9cf410663f77de5e200bda18 --- /dev/null +++ b/leaf/code/v1.5/backfill-20261102-l4i_v_test/lerobot_export.py @@ -0,0 +1,431 @@ +"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars. + +Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding +can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan): + + python scripts/lerobot_export.py plan --raw [,] --runs-root /runs/api \ + --paper --task-set /sets/main_v2_1inst.txt --work [--batches ...] [--limit N] + python scripts/lerobot_export.py shard --work --shard i --nshards N + python scripts/lerobot_export.py merge --work --nshards N --out + +Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0 +mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped. + +LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t): + observation.images.image agentview RGB 256x256 (upright; LIBERO naming) + observation.images.wrist_image wrist (eye-in-hand) RGB 256x256 + observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout) + observation.joint_pos / joint_vel 7 arm joints (rad, rad/s) + observation.eef_quat 4: xyzw; observation.gripper_width 1 (m) + action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad), + gripper (-1 open, +1 close) + annotation.attempt_index attempt (1-based) the frame belongs to + annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`) + annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action) + annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt + annotation.task_event number of task-monitor events (error / progress events) registered at this step +Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table), +runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state +per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/. +""" +import argparse +import glob +import json +import os +import re +import shutil +import time + +import numpy as np + +FPS = 20 +RES = 256 +BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke", + "cc_smoke", "cc_opus_smoke"] +BATCH_NOTES = { + "cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog", + "cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267", + "cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299", + "cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances", + "cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)", + "cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the " + "with-history continuation of failed runs is incomplete", + "cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early", + "cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt", + "cc_opus_smoke": "smoke test: single attempt", +} +PHASES = {"move": 0, "gripper": 1, "judge": 2} +CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)", + "L2": "disturbed state to restore (incl. damage the agent causes)", + "L3": "infeasible manipulation strategy (grasp / contact / tool must change)", + "L4": "misjudged geometry (size, shape, fit, hidden structure)", + "L5": "misjudged physics (mass distribution, friction, dynamics)"} + + +def features(): + vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]} + f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names} + i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None} + return { + "observation.images.image": vid(), + "observation.images.wrist_image": vid(), + "observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z", + "finger_qpos_left", "finger_qpos_right"]), + "observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]), + "observation.gripper_width": f32(1, ["width_m"]), + "action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y", + "eef_delta_rot_aa_z", "gripper_close"]), + "annotation.attempt_index": i64(), + "annotation.command_index": i64(), + "annotation.phase": i64(), + "annotation.attempt_success": i64(), + "annotation.task_event": i64(), + } + + +# ------------------------------------------------------------------------------------------------ paper metadata + +def _clean_tex(s): + s = re.sub(r"%.*", "", s) + for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"), + (r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"), + (r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"), + (r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"), + (r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]: + s = re.sub(a, b, s) + s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s) + s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s) + for _ in range(3): + s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\$([^$]*)\$", r"\1", s) + s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ") + s = re.sub(r"\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\\[a-zA-Z]+\*?", "", s) + return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip() + + +def paper_tasks(paper_dir): + """{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the + paper's task table and task appendix (empty if the paper sources are not there).""" + out = {} + if not paper_dir: + return out + app = os.path.join(paper_dir, "sections", "appendix_tasks.tex") + tab = os.path.join(paper_dir, "sections", "tab_tasks.tex") + if os.path.exists(app): + txt = open(app).read() + parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt) + for i in range(1, len(parts) - 1, 2): + if parts[i] != "\\paragraph{": + continue + body = parts[i + 1] + m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S) + if not m: + continue + name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip() + desc = _clean_tex(body[m.end():]) + out[code] = dict(name=name, cause=_clean_tex(cause), description=desc) + if os.path.exists(tab): + names = {v["name"].lower(): k for k, v in out.items()} + for line in open(tab): + cells = [c.strip() for c in line.split("&")] + if len(cells) != 6 or not cells[-1].endswith("\\\\"): + continue + nm = re.sub(r"\\contscene", "", cells[0]).strip().lower() + code = names.get(nm) + if not code: + continue + out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]), + repair_within_attempt=_clean_tex(cells[3]) == "yes", + oracle_first_attempt_pct=_clean_tex(cells[4]), + naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip())) + return out + + +# ------------------------------------------------------------------------------------------------ collection + +def manifest_status(runs_root, batch, run, cache={}): + if batch not in cache: + p = os.path.join(runs_root, batch, "manifest.json") + cache[batch] = json.load(open(p)) if os.path.exists(p) else {} + m = cache[batch] + for r in m.get("runs", []): + if r.get("run") == run: + return r.get("status", "?"), r + for r in m.get("superseded", []): + if r.get("run") == run: + return "superseded_" + str(r.get("status", "?")), r + return "not_in_manifest", {} + + +def collect(raw_roots, runs_root, batches, task_order): + """Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root.""" + eps, rejected, seen = [], [], set() + for root in raw_roots: + for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))): + rep = json.load(open(rj)) + batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"] + if (batches and batch not in batches) or (batch, run) in seen: + continue + seen.add((batch, run)) + ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff") + status, entry = manifest_status(runs_root, batch, run) + if not ok: + never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked") + rejected.append(dict(run=run, batch=batch, run_status=status, + reason="run never started (no contract, no robot command)" if never else + "replay does not reproduce the log (the log has gaps or the replay diverged)", + detail=rep.get("first_mismatches"))) + continue + for ep in rep.get("episodes", []): + d = os.path.join(root, ep["dir"]) + ann = json.load(open(os.path.join(d, "annotation.json"))) + judged = [a for a in ann["attempts"] if a.get("success") is not None] + if not judged or ep["n_frames"] == 0: + rejected.append(dict(run=run, batch=batch, episode=ep["dir"], + reason="no judged attempt" if not judged else "no frames")) + continue + ann["source"]["run_status"] = status + ann["source"]["manifest_id"] = entry.get("id") + ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"], + max_eef_dev_m=rep["max_eef_dev_m"]) + key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99), + {"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2), + ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"]) + eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann)) + eps.sort(key=lambda x: x["key"]) + return eps, rejected + + +# ------------------------------------------------------------------------------------------------ writing + +def frames_of(path): + import av + with av.open(path) as c: + for fr in c.decode(video=0): + yield fr.to_ndarray(format="rgb24") + + +def flat_row(i, ann, n, idx0): + s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"] + att = ann["attempts"] + a0 = att[0] + return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n, + batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"], + memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"), + episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att], + harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"), + effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"), + task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"), + category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"], + success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att], + feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att], + auto_ended=[a.get("auto_ended") for a in att], + corrected_later_in_run=[a.get("corrected_later_in_run") for a in att], + error_event_in_attempt=[a.get("error_event_in_attempt") for a in att], + run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"), + n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]), + first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None) + + +def cmd_plan(a): + task_order = {} + if a.task_set and os.path.exists(a.task_set): + for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")): + task_order[line.split(":")[0].strip()] = i + batches = [b for b in a.batches.split(",") if b] if a.batches else None + eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order) + if a.limit: + eps = eps[:a.limit] + paper = paper_tasks(a.paper) + idx0 = 0 + for i, e in enumerate(eps): + ann = e["ann"] + tname = ann["task"]["name"] + if tname in paper: + ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"} + ann["episode_index"] = i + ann["dataset_index_range"] = [idx0, idx0 + e["n"]] + e["index"], e["from"] = i, idx0 + idx0 += e["n"] + del e["key"] + os.makedirs(a.work, exist_ok=True) + with open(os.path.join(a.work, "plan.json"), "w") as f: + json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f, + ensure_ascii=False) + print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True) + + +def shard_range(n_eps, i, k): + return (n_eps * i) // k, (n_eps * (i + 1)) // k + + +def cmd_shard(a): + from lerobot.datasets.lerobot_dataset import LeRobotDataset + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + lo, hi = shard_range(len(eps), a.shard, a.nshards) + out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}") + if os.path.exists(os.path.join(out, "DONE")): + print(f"shard {a.shard}: done already", flush=True) + return + shutil.rmtree(out, ignore_errors=True) + ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out, + robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads, + vcodec=a.vcodec) + nfr = 0 + for e in eps[lo:hi]: + d, ann, n = e["dir"], e["ann"], e["n"] + fr = np.load(os.path.join(d, "frames.npz")) + assert len(fr["action"]) == n, d + succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]} + evc = np.zeros(n, np.int64) + for ev in ann["task_events"]: + if 0 <= ev["frame"] < n: + evc[ev["frame"]] += 1 + state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32) + instr = ann["task"]["instruction"] + k = 0 + for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))): + if k >= n: + break + ds.add_frame({ + "observation.images.image": img, "observation.images.wrist_image": wr, + "observation.state": state[k], + "observation.joint_pos": fr["joint_pos"][k].astype(np.float32), + "observation.joint_vel": fr["joint_vel"][k].astype(np.float32), + "observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32), + "observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32), + "action": fr["action"][k].astype(np.float32), + "annotation.attempt_index": np.array([fr["attempt"][k]], np.int64), + "annotation.command_index": np.array([fr["command"][k]], np.int64), + "annotation.phase": np.array([fr["phase"][k]], np.int64), + "annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64), + "annotation.task_event": np.array([evc[k]], np.int64), + "task": instr, + }) + k += 1 + if k != n: + raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames") + ds.save_episode() + nfr += n + ds.finalize() + shutil.rmtree(os.path.join(out, "images"), ignore_errors=True) + open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n") + print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True) + + +def cmd_merge(a): + from pathlib import Path + from lerobot.datasets.aggregate import aggregate_datasets + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + roots, ids = [], [] + for i in range(a.nshards): + lo, hi = shard_range(len(eps), i, a.nshards) + if hi <= lo: + continue + r = os.path.join(a.work, "shards", f"shard_{i:03d}") + if not os.path.exists(os.path.join(r, "DONE")): + raise SystemExit(f"shard {i} is not done") + roots.append(Path(r)) + ids.append(f"{plan['repo_id']}-shard{i:03d}") + if os.path.exists(a.out): + raise SystemExit(f"{a.out} exists; refusing to overwrite") + aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out)) + print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True) + write_sidecars(a, plan) + print(f"merge done in {time.time() - t0:.0f}s", flush=True) + + +def write_sidecars(a, plan): + eps, paper = plan["episodes"], plan["paper"] + lff = os.path.join(a.out, "lff") + for sub in ("annotations", "sim_state", "final", "code"): + os.makedirs(os.path.join(lff, sub), exist_ok=True) + rows, runs, tasks = [], {}, {} + for e in eps: + i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"] + name = f"episode_{i:06d}" + if os.path.exists(os.path.join(d, "sim_state.npy")): + shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy")) + shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz")) + for cam, key in (("agentview", "image"), ("wrist", "wrist_image")): + shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png")) + with open(os.path.join(lff, "annotations", name + ".json"), "w") as f: + json.dump(ann, f, indent=1, ensure_ascii=False) + rows.append(flat_row(i, ann, n, e["from"])) + tname = ann["task"]["name"] + rk = (ann["source"]["batch"], ann["source"]["run"]) + r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"), + run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"], + memory_free_chain_of=ann["source"].get("memory_free_chain_of"), + memory_free_rep=ann["source"].get("memory_free_rep"), task=tname, + seed=ann["task"]["seed"], model=ann["agent"].get("model"), + harness=ann["agent"].get("harness"), + harness_version=ann["agent"].get("harness_version"), + codex_catalog=ann["agent"].get("codex_catalog"), + outcome_class=ann["run_outcome"].get("outcome_class"), + attempt_history=ann["run_outcome"].get("attempt_history"), + agent_final_report=ann["run_outcome"].get("agent_final_report"), + episodes=[])) + for x in ann["attempts"]: + r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success"))) + if tname not in tasks: + tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")} + if tname in paper: + tasks[tname]["paper"] = paper[tname] + tasks[tname]["instances"] = {} + tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"] + # memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id) + by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")} + for r in runs.values(): + if r.get("memory_free_chain_of"): + r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"])) + for (b, rn), r in runs.items(): + r["memory_free_retries"] = sorted((x["run"] for x in runs.values() + if x["batch"] == b and x.get("memory_free_chain_of_run") == rn), + key=lambda q: runs[(b, q)].get("memory_free_rep") or 0) + with open(os.path.join(lff, "episodes.jsonl"), "w") as f: + for row in rows: + f.write(json.dumps(row, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "runs.jsonl"), "w") as f: + for r in runs.values(): + f.write(json.dumps(r, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "tasks.json"), "w") as f: + json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False) + with open(os.path.join(lff, "batches.json"), "w") as f: + json.dump(BATCH_NOTES, f, indent=1) + with open(os.path.join(lff, "rejected.json"), "w") as f: + json.dump(plan["rejected"], f, indent=1) + here = os.path.dirname(os.path.abspath(__file__)) + for s in ("lerobot_replay.py", "lerobot_export.py"): + shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("step", choices=["plan", "shard", "merge"]) + ap.add_argument("--work", required=True) + ap.add_argument("--raw", default="") + ap.add_argument("--runs-root", default="") + ap.add_argument("--out", default="") + ap.add_argument("--paper", default="") + ap.add_argument("--task-set", default="") + ap.add_argument("--repo-id", default="lffbench/agent-replays") + ap.add_argument("--batches", default="") + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--shard", type=int, default=0) + ap.add_argument("--nshards", type=int, default=1) + ap.add_argument("--threads", type=int, default=2) + ap.add_argument("--vcodec", default="libsvtav1") + a = ap.parse_args() + {"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a) + + +if __name__ == "__main__": + main() diff --git a/leaf/code/v1.5/backfill-20261102-l4i_v_test/lerobot_replay.py b/leaf/code/v1.5/backfill-20261102-l4i_v_test/lerobot_replay.py new file mode 100644 index 0000000000000000000000000000000000000000..4c43a69bdb066327b27614bc9efda53d4a74e931 --- /dev/null +++ b/leaf/code/v1.5/backfill-20261102-l4i_v_test/lerobot_replay.py @@ -0,0 +1,744 @@ +"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay +against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the +LeRobot export (scripts/lerobot_export.py). + + python scripts/lerobot_replay.py check [ ...] [--json out.json] # replay only, print fidelity + python scripts/lerobot_replay.py record --out [--res 256] + +Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot +commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite +is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly +like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same +outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width, +ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code +hashes equal the current files are expected to match (check_code()). + +Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB, +proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes: +protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode +per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the +fidelity check runs in record mode too. Per episode the recorder writes ///epNN/: + agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes) + frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase + sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel) + final_*.png, final.npz observation after the last control step (the state the outcome was judged in) + annotation.json episode annotation (build_annotation) +and ///replay.json (fidelity) when the whole run is done. +""" +import argparse +import ast +import hashlib +import importlib +import json +import math +import os +import pkgutil +import re +import shutil +import sys +import time +from collections import defaultdict + +import numpy as np + +LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, LFF_ROOT) + +from lffbench import envs # noqa: E402 +from lffbench import tasks as task_pkg # noqa: E402 +from lffbench.agent import camera as C # noqa: E402 +from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402 +from lffbench.task_base import TASKS # noqa: E402 + +for _m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{_m.name}") + +# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the +# task's outcome() check after `finish` (the arm holds still; not an agent action) +PHASES = {"move": 0, "gripper": 1, "judge": 2} +FPS = 20 +SCHEMA = "lff-replay-1" + +# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR" +ERROR_FLAGS = ("trap_fired", "recovered_in_attempt") +ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events", + "n_missed_strikes", "n_open_gripper_pushes") + + +def load_jsonl(p): + out = [] + if not os.path.exists(p): + return out + with open(p) as f: + for line in f: + line = line.strip() + if line: + try: + out.append(json.loads(line)) + except ValueError: + pass + return out + + +def norm_json(o): + return json.loads(json.dumps(o, default=_json_default)) + + +def sha256(p): + with open(p, "rb") as f: + return hashlib.sha256(f.read()).hexdigest() + + +def check_code(run_dir): + """[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract.""" + p = os.path.join(run_dir, "contract.json") + if not os.path.exists(p): + return [("contract.json", None, None)] + files = json.load(open(p))["contract"].get("server_code_files", {}) + bad = [] + for f, h in files.items(): + q = os.path.join(LFF_ROOT, f) + cur = sha256(q) if os.path.exists(q) else None + if cur != h: + bad.append((f, h, cur)) + return bad + + +def diff_json(a, b, path="", tol=0.0, out=None, limit=20): + """Differences between two JSON values (numbers compared with an absolute tolerance).""" + out = [] if out is None else out + if len(out) >= limit: + return out + if isinstance(a, dict) and isinstance(b, dict): + for k in sorted(set(a) | set(b)): + if k not in a or k not in b: + out.append((f"{path}.{k}", a.get(k, ""), b.get(k, ""))) + else: + diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit) + elif isinstance(a, list) and isinstance(b, list): + if len(a) != len(b): + out.append((path, f"len {len(a)}", f"len {len(b)}")) + else: + for i, (x, y) in enumerate(zip(a, b)): + diff_json(x, y, f"{path}[{i}]", tol, out, limit) + elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))): + if a != b: + out.append((path, a, b)) + elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))): + out.append((path, a, b)) + return out + + +def error_event(o): + """True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none.""" + if not isinstance(o, dict): + return None + keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o] + if not keys: + return None + return any(bool(o[k]) for k in ERROR_FLAGS if k in o) or any((o.get(k) or 0) > 0 for k in ERROR_COUNTS if k in o) + + +# ====================================================================================================== logs -> notes + +class RunLog: + """Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's + narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition.""" + + def __init__(self, run_dir, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run = os.path.basename(self.run_dir) + self.batch = os.path.basename(os.path.dirname(self.run_dir)) + self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl")) + self.start = next(e for e in self.ev if e["ev"] == "session_start") + self.calls, self.dones, self.harness_status = {}, [], [] + last = None + for e in self.ev: + if e["ev"] == "call": + self.calls[(int(e["attempt"]), int(e["step"]))] = e + last = e + elif e["ev"] == "done": + self.dones.append(e) + last = e + elif e["ev"] == "http" and last is not None and "think_s" not in last: + ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \ + (last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe")) + if ok: + last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s") + self.manifest = manifest or {} + self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {} + p = os.path.join(self.run_dir, "harness.json") + self.harness = json.load(open(p)) if os.path.exists(p) else {} + self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl")) + self._narration() + + # ---------------------------------------------------------------- agent narration + def _narration(self): + """notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one; + finish_notes[attempt] likewise for the agent's finish call; final_report = its last message.""" + self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", [] + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + attempt = 1 + + def take(): + nonlocal buf + out = {k: v for k, v in buf.items() if v} + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + return out + + last_msg = "" + for t in self.traj: + if t.get("kind") == "header": + self.headers.append(t.get("agent") or {}) + continue + if t.get("kind") != "step": + continue + if (t.get("message") or "").strip(): + buf["messages"].append(t["message"].strip()) + last_msg = t["message"].strip() + if (t.get("reasoning_content") or "").strip(): + buf["reasoning"].append(t["reasoning_content"].strip()) + res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])} + for c in t.get("tool_calls") or []: + fn, args = c.get("function_name"), c.get("arguments") or {} + if fn == "shell": + buf["shell"].append(str(args.get("command", ""))[:2000]) + elif fn == "view_images": + buf["viewed"].extend(args.get("paths") or []) + elif fn == "robot": + cmd = str(args.get("command", "")).strip() + r = res.get(c.get("tool_call_id")) or {} + try: + rep = json.loads(r.get("content") or "{}") + except ValueError: + rep = {} + word = cmd.split()[0] if cmd else "" + m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", ""))) + if word in ("move_eef", "observe") and m: + a, s = int(m.group(1)), int(m.group(2)) + n = take() + n["command"] = cmd + self.notes[(a, s)] = n + attempt = a + elif word in ("finish", "done"): + n = take() + n["command"] = cmd + n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)} + self.finish_notes.setdefault(attempt, n) + if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"): + attempt += 1 + # status / help / errors: their narration stays in the buffer for the next command + self.final_report = last_msg + + # ---------------------------------------------------------------- run-level labels + def attempts(self): + out = [] + for e in self.dones: + o = e.get("outcome") or {} + if isinstance(o, str): + try: + o = ast.literal_eval(o) + except (ValueError, SyntaxError): + o = {} + out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o, + reason=e.get("reason") or "")) + return sorted(out, key=lambda x: x["attempt"]) + + def condition(self): + s, en = self.start, self.entry + mem = s.get("memory", en.get("mem")) + chain = en.get("chain") + if mem == "full": + cond = "with_history" + elif chain: + cond = "memory_free_retry" + else: + cond = "independent_single_attempt" + return cond, chain + + def outcome_class(self): + """CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None.""" + att = self.attempts() + if not att or self.start.get("memory") != "full": + return None, "".join("S" if a["success"] else "F" for a in att) + hist = "".join("S" if a["success"] else "F" for a in att) + if att[0]["success"]: + ev = error_event(att[0]["outcome"]) + cls = "S?" if ev is None else ("IR" if ev else "CS") + else: + cls = "XR" if any(a["success"] for a in att) else "F" + return cls, hist + + def agent_info(self): + h, en = self.harness, self.entry + hdr = self.headers[0] if self.headers else {} + return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"), + harness_version=h.get("version") or hdr.get("version"), + harness_binary_sha256=(h.get("binary") or {}).get("sha256"), + model=h.get("model") or en.get("model") or hdr.get("model_name"), + effort=h.get("effort") or en.get("effort") or hdr.get("effort"), + provider=h.get("provider") or en.get("provider"), + codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"), + jail=en.get("jail")) + + +# ====================================================================================================== recording + +class EpisodeSink: + """Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed.""" + + def __init__(self, path): + self.path = path + os.makedirs(path, exist_ok=True) + self.w = None + self.num = defaultdict(list) + self.n = 0 + + def add(self, st, imgs): + import imageio + if self.w is None: + self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb", + pixelformat="rgb24", macro_block_size=1, + ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error") + for k in ("agentview", "wrist")] + for w, im in zip(self.w, imgs): + w.append_data(im) + for k, v in st.items(): + self.num[k].append(v) + self.n += 1 + + def close(self, final_state, final_imgs): + from PIL import Image + if self.w is not None: + for w in self.w: + w.close() + arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"} + np.savez(os.path.join(self.path, "frames.npz"), **arr) + if self.num.get("sim_state"): + np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64)) + np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()}) + for k, im in zip(("agentview", "wrist"), final_imgs): + Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png")) + + +class Recorder: + """Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink.""" + + def __init__(self, rp, res): + self.rp, self.res = rp, int(res) + self.active = False + self.sink = None + self.cur = dict(attempt=1, command=-1, phase=PHASES["move"]) + env = rp.task.env + self.env, self.rob = env, env.robots[0] + self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist")) + orig = env.step + + def step(a): + if self.active and self.sink is not None: + self.capture(np.asarray(a, np.float64)) + out = orig(a) + if self.active and self.sink is not None: + self.rp.poll_events(self.sink.n - 1) + return out + + env.step = step + + @property + def n(self): + return self.sink.n if self.sink is not None else 0 + + def state(self): + import robosuite.utils.transform_utils as T + env, rob = self.env, self.rob + d = env.sim.data + eef = np.array(d.site_xpos[rob.eef_site_id], np.float64) + q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw") + gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64) + try: + flat = np.asarray(env.sim.get_state().flatten(), np.float64) + except Exception: + flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64) + sk = self.rp.task.sk + return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64), + gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64), + joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64), + gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64), + eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)), + sim_time=np.float64(d.time), sim_state=flat) + + def images(self): + return [envs.render(self.env, c, self.res) for c in self.cams] + + def capture(self, a): + st = self.state() + st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]), + phase=np.int64(self.cur["phase"])) + self.sink.add(st, self.images()) + + +class RunReplay: + def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run_name = os.path.basename(self.run_dir) + self.log = RunLog(self.run_dir, manifest) + self.ev = self.log.ev + self.start = self.log.start + cp = os.path.join(self.run_dir, "contract.json") + self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {} + spec = self.contract.get("image_spec") or {} + self.image_res = int(spec.get("width", 512)) + self.code_diff = check_code(self.run_dir) + s = self.start + self.task = TASKS[s["task"]](cam_res=self.image_res) + inst = self.task.sample_instance(s["seed"]) + logged = s.get("inst") or {} + sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")}) + self.inst_diff = diff_json(sampled, logged, "inst") + if s.get("arm", "none") not in (None, "none") or logged.get("nominal"): + inst.update(logged) # controlled arms / nominal: the server overrode these instance fields + self.inst_diff = [] + self.inst = inst + self.protocol = getattr(self.task, "protocol", "cross") + self.k = int(s.get("k") or self.task.max_attempts) + self.attempt = 1 + self.mismatch = [] # (where, what, logged, replayed) + self.n_checked = 0 + self.max_dev_m = 0.0 + self.unfinished = None + self.rec = Recorder(self, res) if record else None + self.res = int(res) + self.out_root = out_root + self.n_mon = 0 + self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0 + self.episodes = [] # summaries of the written episodes + self.task.reset_instance(self.inst) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + sim = self.task.env.sim + bid = sim.model.body_name2id("robot0_base") + self.base_off = np.array(sim.data.body_xpos[bid], float).copy() + if self.rec: + self._open_episode() + + # ------------------------------------------------------------------ episodes + def _ep_dir(self): + return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}") + + def _open_episode(self): + self.rec.sink = EpisodeSink(self._ep_dir()) + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.rec.active = True + self.events, self.spans, self.ep_attempts = [], [], [] + self.ep_initial = self.rec.state() # state right after the reset (before frame 0) + + def close_episode(self): + if not self.rec: + self.ep_attempts = [] + return + sink = self.rec.sink + st = self.rec.state() + imgs = self.rec.images() + st.pop("sim_state", None) + sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs) + ann = build_annotation(self, sink) + with open(os.path.join(sink.path, "annotation.json"), "w") as f: + json.dump(ann, f, indent=1, default=_json_default) + self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n, + attempts=[a["attempt"] for a in self.ep_attempts])) + self.rec.active = False + self.rec.sink = None + self.ep_index += 1 + + # ------------------------------------------------------------------ monitor events (task-side error events) + def poll_events(self, frame): + mon = getattr(self.task, "mon", None) + evs = mon.get("events") if isinstance(mon, dict) else None + if not isinstance(evs, list): + return + if len(evs) < self.n_mon: # monitor was rebuilt + self.n_mon = 0 + for e in evs[self.n_mon:]: + self.events.append(dict(frame=int(frame), attempt=self.attempt, + event=norm_json(e) if isinstance(e, dict) else str(e))) + self.n_mon = len(evs) + + # ------------------------------------------------------------------ state as the server reports it + def proprio_la(self): + p = self.ex.proprio() + pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off] + return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"]) + + def compare(self, where, rep_logged, rep): + self.n_checked += 1 + for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"): + if k not in rep_logged or k not in rep: + continue + a, b = rep_logged[k], rep[k] + if k == "eef_pos": + dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float)))) + self.max_dev_m = max(self.max_dev_m, dev) + if dev > 1.5e-4: + self.mismatch.append((where, k, a, b)) + elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4): + self.mismatch.append((where, k, a, b)) + if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)): + self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok"))) + + def _span(self, e, f0, kind): + if self.rec: + self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0, + frame_end=self.rec.n)) + + # ------------------------------------------------------------------ commands (robot_server._handle_v2) + def move_eef(self, e): + args = e.get("args") or {} + where = f"a{e['attempt']}s{e['step']}" + logged = e.get("report") or {} + f0 = self.rec.n if self.rec else 0 + p = self.ex.proprio() + if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}: + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + off = self.base_off + try: + cur = np.asarray(p["eef_pos"], float) - off + tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")] + yaw = float(args.get("yaw", p["eef_yaw_deg"])) + speed = None if args.get("speed") in (None, "") else float(args["speed"]) + except (TypeError, ValueError): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + grip = args.get("gripper") + if grip not in (None, "open", "close"): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + moving = any(k in args for k in ("x", "y", "z", "yaw")) + tgt_w = np.asarray(tgt) + off + if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)): + self._span(e, f0, "rejected") + return self.compare(where, logged, dict(ok=False, **self.proprio_la())) + raw = {} + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"]) + if moving: + mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw) + if speed is not None: + mv["speed"] = speed + raw.update(self.ex.call("move_to", mv).report) + if grip is not None: + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"]) + raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report) + rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la()) + self.compare(where, logged, rep) + lr = e.get("raw") or {} + for k in ("holding_object", "touched_object"): + if k in lr and k in raw and bool(lr[k]) != bool(raw[k]): + self.mismatch.append((where, "raw." + k, lr[k], raw[k])) + self._span(e, f0, "move_eef") + + def observe(self, e): + f0 = self.rec.n if self.rec else 0 + self._span(e, f0, "observe") + + def done(self, e): + f0 = self.rec.n if self.rec else 0 + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"]) + out = self.task.outcome(self.inst) + succ = bool(out["success"]) + where = f"a{e['attempt']}done" + if succ != bool(e.get("success") in (True, "True")): + self.mismatch.append((where, "success", e.get("success"), succ)) + lo = e.get("outcome") or {} + ro = norm_json({k: v for k, v in out.items() if k != "feedback"}) + if isinstance(lo, dict): + for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8): + self.mismatch.append((where,) + d) + info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""), + feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")), + think_s=e.get("think_s")) + try: + info["feedback_f2"] = self.task.feedback(self.inst, out, "F2") + except Exception as ex_: + info["feedback_f2"] = f"" + if self.rec: + info["judge_frames"] = [f0, self.rec.n] + self.ep_attempts.append(info) + last = self.attempt >= self.k or succ or bool(out.get("terminal")) + if self.protocol == "cross" or last: + self.close_episode() + if last: + return True + self.attempt += 1 + if self.protocol == "cross": + self.task.reset_instance(self.inst) + self.n_mon = 0 + if self.rec: + self._open_episode() + elif self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + return False + + def run(self): + t0 = time.time() + finished = False + for e in self.ev: + if e["ev"] == "call": + if e.get("cmd") == "move_eef": + self.move_eef(e) + elif e.get("cmd") == "observe": + self.observe(e) + else: + self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None)) + elif e["ev"] == "done": + finished = self.done(e) + if finished: + break + self.unfinished = not finished + if not finished and self.rec and self.rec.sink is not None: + # the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged + if self.rec.n or self.ep_attempts: + self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True, + finish_reason="", feedback_shown="", auto_ended=False)) + self.close_episode() + else: + shutil.rmtree(self.rec.sink.path, ignore_errors=True) + self.rec.sink = None + self.wall_s = time.time() - t0 + return self + + def summary(self): + return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"], + protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff), + n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6), + unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1), + first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]]) + + +# ====================================================================================================== annotation + +def task_info(task, inst): + cls = type(task) + return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable", + category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"), + max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)), + instruction=cls.instruction) + + +def build_annotation(rp, sink): + """Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2 + failure description), run-level outcome class, every robot command with its frame span and the agent's narration, + task-side error events with frame indices.""" + log = rp.log + s = rp.start + cond, chain = log.condition() + cls, hist = log.outcome_class() + att_all = log.attempts() + attempts = [] + for a in rp.ep_attempts: + a = dict(a) + n = a["attempt"] + later = [x for x in att_all if x["attempt"] > n] + a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later)) + a["is_last_attempt_of_run"] = not later + fn = log.finish_notes.get(n) + if fn: + a["agent_finish"] = fn + a["error_event_in_attempt"] = error_event(a.get("outcome")) + attempts.append(a) + # post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command) + for a in attempts: + nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1]) + if a.get("success") is False and nxt: + note = log.notes[nxt[0]] + a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note} + commands = [] + for sp in rp.spans: + e = log.calls.get((sp["attempt"], sp["step"])) or {} + rep = e.get("report") or {} + c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"], + frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]), + args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"), + stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"), + gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"), + touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"), + agent_obs_images=rep.get("images")) + note = log.notes.get((sp["attempt"], sp["step"])) + if note: + c["agent_note"] = {k: v for k, v in note.items() if k != "command"} + commands.append(c) + t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x] + return dict( + schema=SCHEMA, + source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts], + episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain, + memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None), + feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"), + k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"), + contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256") + if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)), + agent=log.agent_info(), + task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"), + instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}), + run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all), + run_success=any(x["success"] for x in att_all) if att_all else None, + agent_final_report=log.final_report[:6000] or None, + mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)), + attempts=attempts, + commands=commands, + task_events=rp.events, + frames=dict(n=sink.n, fps=FPS, image_res=rp.res, + phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"], + joint_pos=rp.ep_initial["joint_pos"], + gripper_qpos=rp.ep_initial["gripper_qpos"])), + ) + + +# ====================================================================================================== CLI + +def load_manifest(run_dir): + p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json") + return json.load(open(p)) if os.path.exists(p) else {} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("mode", choices=["check", "record"]) + ap.add_argument("runs", nargs="+") + ap.add_argument("--json", default="") + ap.add_argument("--out", default="") + ap.add_argument("--res", type=int, default=256) + ap.add_argument("--force", action="store_true", help="record again even if replay.json exists") + a = ap.parse_args() + rows = [] + for r in a.runs: + r = r.rstrip("/") + try: + if a.mode == "check": + s = RunReplay(r, manifest=load_manifest(r)).run().summary() + else: + batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r) + rd = os.path.join(a.out, batch, name) + if os.path.exists(os.path.join(rd, "replay.json")) and not a.force: + print(json.dumps(dict(run=name, skipped="exists")), flush=True) + continue + shutil.rmtree(rd, ignore_errors=True) + rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run() + s = rp.summary() + s["episodes"] = rp.episodes + with open(os.path.join(rd, "replay.json"), "w") as f: + json.dump(s, f, indent=1) + except Exception: + import traceback + s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:]) + rows.append(s) + print(json.dumps(s), flush=True) + if a.json: + with open(a.json, "w") as f: + json.dump(rows, f, indent=1) + + +if __name__ == "__main__": + main() diff --git a/leaf/code/v1.5/backfill-20261102-lf2_sonnet_r2/lerobot_replay.py b/leaf/code/v1.5/backfill-20261102-lf2_sonnet_r2/lerobot_replay.py new file mode 100644 index 0000000000000000000000000000000000000000..4c43a69bdb066327b27614bc9efda53d4a74e931 --- /dev/null +++ b/leaf/code/v1.5/backfill-20261102-lf2_sonnet_r2/lerobot_replay.py @@ -0,0 +1,744 @@ +"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay +against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the +LeRobot export (scripts/lerobot_export.py). + + python scripts/lerobot_replay.py check [ ...] [--json out.json] # replay only, print fidelity + python scripts/lerobot_replay.py record --out [--res 256] + +Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot +commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite +is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly +like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same +outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width, +ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code +hashes equal the current files are expected to match (check_code()). + +Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB, +proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes: +protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode +per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the +fidelity check runs in record mode too. Per episode the recorder writes ///epNN/: + agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes) + frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase + sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel) + final_*.png, final.npz observation after the last control step (the state the outcome was judged in) + annotation.json episode annotation (build_annotation) +and ///replay.json (fidelity) when the whole run is done. +""" +import argparse +import ast +import hashlib +import importlib +import json +import math +import os +import pkgutil +import re +import shutil +import sys +import time +from collections import defaultdict + +import numpy as np + +LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, LFF_ROOT) + +from lffbench import envs # noqa: E402 +from lffbench import tasks as task_pkg # noqa: E402 +from lffbench.agent import camera as C # noqa: E402 +from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402 +from lffbench.task_base import TASKS # noqa: E402 + +for _m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{_m.name}") + +# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the +# task's outcome() check after `finish` (the arm holds still; not an agent action) +PHASES = {"move": 0, "gripper": 1, "judge": 2} +FPS = 20 +SCHEMA = "lff-replay-1" + +# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR" +ERROR_FLAGS = ("trap_fired", "recovered_in_attempt") +ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events", + "n_missed_strikes", "n_open_gripper_pushes") + + +def load_jsonl(p): + out = [] + if not os.path.exists(p): + return out + with open(p) as f: + for line in f: + line = line.strip() + if line: + try: + out.append(json.loads(line)) + except ValueError: + pass + return out + + +def norm_json(o): + return json.loads(json.dumps(o, default=_json_default)) + + +def sha256(p): + with open(p, "rb") as f: + return hashlib.sha256(f.read()).hexdigest() + + +def check_code(run_dir): + """[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract.""" + p = os.path.join(run_dir, "contract.json") + if not os.path.exists(p): + return [("contract.json", None, None)] + files = json.load(open(p))["contract"].get("server_code_files", {}) + bad = [] + for f, h in files.items(): + q = os.path.join(LFF_ROOT, f) + cur = sha256(q) if os.path.exists(q) else None + if cur != h: + bad.append((f, h, cur)) + return bad + + +def diff_json(a, b, path="", tol=0.0, out=None, limit=20): + """Differences between two JSON values (numbers compared with an absolute tolerance).""" + out = [] if out is None else out + if len(out) >= limit: + return out + if isinstance(a, dict) and isinstance(b, dict): + for k in sorted(set(a) | set(b)): + if k not in a or k not in b: + out.append((f"{path}.{k}", a.get(k, ""), b.get(k, ""))) + else: + diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit) + elif isinstance(a, list) and isinstance(b, list): + if len(a) != len(b): + out.append((path, f"len {len(a)}", f"len {len(b)}")) + else: + for i, (x, y) in enumerate(zip(a, b)): + diff_json(x, y, f"{path}[{i}]", tol, out, limit) + elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))): + if a != b: + out.append((path, a, b)) + elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))): + out.append((path, a, b)) + return out + + +def error_event(o): + """True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none.""" + if not isinstance(o, dict): + return None + keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o] + if not keys: + return None + return any(bool(o[k]) for k in ERROR_FLAGS if k in o) or any((o.get(k) or 0) > 0 for k in ERROR_COUNTS if k in o) + + +# ====================================================================================================== logs -> notes + +class RunLog: + """Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's + narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition.""" + + def __init__(self, run_dir, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run = os.path.basename(self.run_dir) + self.batch = os.path.basename(os.path.dirname(self.run_dir)) + self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl")) + self.start = next(e for e in self.ev if e["ev"] == "session_start") + self.calls, self.dones, self.harness_status = {}, [], [] + last = None + for e in self.ev: + if e["ev"] == "call": + self.calls[(int(e["attempt"]), int(e["step"]))] = e + last = e + elif e["ev"] == "done": + self.dones.append(e) + last = e + elif e["ev"] == "http" and last is not None and "think_s" not in last: + ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \ + (last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe")) + if ok: + last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s") + self.manifest = manifest or {} + self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {} + p = os.path.join(self.run_dir, "harness.json") + self.harness = json.load(open(p)) if os.path.exists(p) else {} + self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl")) + self._narration() + + # ---------------------------------------------------------------- agent narration + def _narration(self): + """notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one; + finish_notes[attempt] likewise for the agent's finish call; final_report = its last message.""" + self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", [] + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + attempt = 1 + + def take(): + nonlocal buf + out = {k: v for k, v in buf.items() if v} + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + return out + + last_msg = "" + for t in self.traj: + if t.get("kind") == "header": + self.headers.append(t.get("agent") or {}) + continue + if t.get("kind") != "step": + continue + if (t.get("message") or "").strip(): + buf["messages"].append(t["message"].strip()) + last_msg = t["message"].strip() + if (t.get("reasoning_content") or "").strip(): + buf["reasoning"].append(t["reasoning_content"].strip()) + res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])} + for c in t.get("tool_calls") or []: + fn, args = c.get("function_name"), c.get("arguments") or {} + if fn == "shell": + buf["shell"].append(str(args.get("command", ""))[:2000]) + elif fn == "view_images": + buf["viewed"].extend(args.get("paths") or []) + elif fn == "robot": + cmd = str(args.get("command", "")).strip() + r = res.get(c.get("tool_call_id")) or {} + try: + rep = json.loads(r.get("content") or "{}") + except ValueError: + rep = {} + word = cmd.split()[0] if cmd else "" + m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", ""))) + if word in ("move_eef", "observe") and m: + a, s = int(m.group(1)), int(m.group(2)) + n = take() + n["command"] = cmd + self.notes[(a, s)] = n + attempt = a + elif word in ("finish", "done"): + n = take() + n["command"] = cmd + n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)} + self.finish_notes.setdefault(attempt, n) + if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"): + attempt += 1 + # status / help / errors: their narration stays in the buffer for the next command + self.final_report = last_msg + + # ---------------------------------------------------------------- run-level labels + def attempts(self): + out = [] + for e in self.dones: + o = e.get("outcome") or {} + if isinstance(o, str): + try: + o = ast.literal_eval(o) + except (ValueError, SyntaxError): + o = {} + out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o, + reason=e.get("reason") or "")) + return sorted(out, key=lambda x: x["attempt"]) + + def condition(self): + s, en = self.start, self.entry + mem = s.get("memory", en.get("mem")) + chain = en.get("chain") + if mem == "full": + cond = "with_history" + elif chain: + cond = "memory_free_retry" + else: + cond = "independent_single_attempt" + return cond, chain + + def outcome_class(self): + """CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None.""" + att = self.attempts() + if not att or self.start.get("memory") != "full": + return None, "".join("S" if a["success"] else "F" for a in att) + hist = "".join("S" if a["success"] else "F" for a in att) + if att[0]["success"]: + ev = error_event(att[0]["outcome"]) + cls = "S?" if ev is None else ("IR" if ev else "CS") + else: + cls = "XR" if any(a["success"] for a in att) else "F" + return cls, hist + + def agent_info(self): + h, en = self.harness, self.entry + hdr = self.headers[0] if self.headers else {} + return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"), + harness_version=h.get("version") or hdr.get("version"), + harness_binary_sha256=(h.get("binary") or {}).get("sha256"), + model=h.get("model") or en.get("model") or hdr.get("model_name"), + effort=h.get("effort") or en.get("effort") or hdr.get("effort"), + provider=h.get("provider") or en.get("provider"), + codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"), + jail=en.get("jail")) + + +# ====================================================================================================== recording + +class EpisodeSink: + """Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed.""" + + def __init__(self, path): + self.path = path + os.makedirs(path, exist_ok=True) + self.w = None + self.num = defaultdict(list) + self.n = 0 + + def add(self, st, imgs): + import imageio + if self.w is None: + self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb", + pixelformat="rgb24", macro_block_size=1, + ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error") + for k in ("agentview", "wrist")] + for w, im in zip(self.w, imgs): + w.append_data(im) + for k, v in st.items(): + self.num[k].append(v) + self.n += 1 + + def close(self, final_state, final_imgs): + from PIL import Image + if self.w is not None: + for w in self.w: + w.close() + arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"} + np.savez(os.path.join(self.path, "frames.npz"), **arr) + if self.num.get("sim_state"): + np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64)) + np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()}) + for k, im in zip(("agentview", "wrist"), final_imgs): + Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png")) + + +class Recorder: + """Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink.""" + + def __init__(self, rp, res): + self.rp, self.res = rp, int(res) + self.active = False + self.sink = None + self.cur = dict(attempt=1, command=-1, phase=PHASES["move"]) + env = rp.task.env + self.env, self.rob = env, env.robots[0] + self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist")) + orig = env.step + + def step(a): + if self.active and self.sink is not None: + self.capture(np.asarray(a, np.float64)) + out = orig(a) + if self.active and self.sink is not None: + self.rp.poll_events(self.sink.n - 1) + return out + + env.step = step + + @property + def n(self): + return self.sink.n if self.sink is not None else 0 + + def state(self): + import robosuite.utils.transform_utils as T + env, rob = self.env, self.rob + d = env.sim.data + eef = np.array(d.site_xpos[rob.eef_site_id], np.float64) + q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw") + gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64) + try: + flat = np.asarray(env.sim.get_state().flatten(), np.float64) + except Exception: + flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64) + sk = self.rp.task.sk + return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64), + gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64), + joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64), + gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64), + eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)), + sim_time=np.float64(d.time), sim_state=flat) + + def images(self): + return [envs.render(self.env, c, self.res) for c in self.cams] + + def capture(self, a): + st = self.state() + st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]), + phase=np.int64(self.cur["phase"])) + self.sink.add(st, self.images()) + + +class RunReplay: + def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run_name = os.path.basename(self.run_dir) + self.log = RunLog(self.run_dir, manifest) + self.ev = self.log.ev + self.start = self.log.start + cp = os.path.join(self.run_dir, "contract.json") + self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {} + spec = self.contract.get("image_spec") or {} + self.image_res = int(spec.get("width", 512)) + self.code_diff = check_code(self.run_dir) + s = self.start + self.task = TASKS[s["task"]](cam_res=self.image_res) + inst = self.task.sample_instance(s["seed"]) + logged = s.get("inst") or {} + sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")}) + self.inst_diff = diff_json(sampled, logged, "inst") + if s.get("arm", "none") not in (None, "none") or logged.get("nominal"): + inst.update(logged) # controlled arms / nominal: the server overrode these instance fields + self.inst_diff = [] + self.inst = inst + self.protocol = getattr(self.task, "protocol", "cross") + self.k = int(s.get("k") or self.task.max_attempts) + self.attempt = 1 + self.mismatch = [] # (where, what, logged, replayed) + self.n_checked = 0 + self.max_dev_m = 0.0 + self.unfinished = None + self.rec = Recorder(self, res) if record else None + self.res = int(res) + self.out_root = out_root + self.n_mon = 0 + self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0 + self.episodes = [] # summaries of the written episodes + self.task.reset_instance(self.inst) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + sim = self.task.env.sim + bid = sim.model.body_name2id("robot0_base") + self.base_off = np.array(sim.data.body_xpos[bid], float).copy() + if self.rec: + self._open_episode() + + # ------------------------------------------------------------------ episodes + def _ep_dir(self): + return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}") + + def _open_episode(self): + self.rec.sink = EpisodeSink(self._ep_dir()) + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.rec.active = True + self.events, self.spans, self.ep_attempts = [], [], [] + self.ep_initial = self.rec.state() # state right after the reset (before frame 0) + + def close_episode(self): + if not self.rec: + self.ep_attempts = [] + return + sink = self.rec.sink + st = self.rec.state() + imgs = self.rec.images() + st.pop("sim_state", None) + sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs) + ann = build_annotation(self, sink) + with open(os.path.join(sink.path, "annotation.json"), "w") as f: + json.dump(ann, f, indent=1, default=_json_default) + self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n, + attempts=[a["attempt"] for a in self.ep_attempts])) + self.rec.active = False + self.rec.sink = None + self.ep_index += 1 + + # ------------------------------------------------------------------ monitor events (task-side error events) + def poll_events(self, frame): + mon = getattr(self.task, "mon", None) + evs = mon.get("events") if isinstance(mon, dict) else None + if not isinstance(evs, list): + return + if len(evs) < self.n_mon: # monitor was rebuilt + self.n_mon = 0 + for e in evs[self.n_mon:]: + self.events.append(dict(frame=int(frame), attempt=self.attempt, + event=norm_json(e) if isinstance(e, dict) else str(e))) + self.n_mon = len(evs) + + # ------------------------------------------------------------------ state as the server reports it + def proprio_la(self): + p = self.ex.proprio() + pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off] + return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"]) + + def compare(self, where, rep_logged, rep): + self.n_checked += 1 + for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"): + if k not in rep_logged or k not in rep: + continue + a, b = rep_logged[k], rep[k] + if k == "eef_pos": + dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float)))) + self.max_dev_m = max(self.max_dev_m, dev) + if dev > 1.5e-4: + self.mismatch.append((where, k, a, b)) + elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4): + self.mismatch.append((where, k, a, b)) + if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)): + self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok"))) + + def _span(self, e, f0, kind): + if self.rec: + self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0, + frame_end=self.rec.n)) + + # ------------------------------------------------------------------ commands (robot_server._handle_v2) + def move_eef(self, e): + args = e.get("args") or {} + where = f"a{e['attempt']}s{e['step']}" + logged = e.get("report") or {} + f0 = self.rec.n if self.rec else 0 + p = self.ex.proprio() + if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}: + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + off = self.base_off + try: + cur = np.asarray(p["eef_pos"], float) - off + tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")] + yaw = float(args.get("yaw", p["eef_yaw_deg"])) + speed = None if args.get("speed") in (None, "") else float(args["speed"]) + except (TypeError, ValueError): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + grip = args.get("gripper") + if grip not in (None, "open", "close"): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + moving = any(k in args for k in ("x", "y", "z", "yaw")) + tgt_w = np.asarray(tgt) + off + if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)): + self._span(e, f0, "rejected") + return self.compare(where, logged, dict(ok=False, **self.proprio_la())) + raw = {} + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"]) + if moving: + mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw) + if speed is not None: + mv["speed"] = speed + raw.update(self.ex.call("move_to", mv).report) + if grip is not None: + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"]) + raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report) + rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la()) + self.compare(where, logged, rep) + lr = e.get("raw") or {} + for k in ("holding_object", "touched_object"): + if k in lr and k in raw and bool(lr[k]) != bool(raw[k]): + self.mismatch.append((where, "raw." + k, lr[k], raw[k])) + self._span(e, f0, "move_eef") + + def observe(self, e): + f0 = self.rec.n if self.rec else 0 + self._span(e, f0, "observe") + + def done(self, e): + f0 = self.rec.n if self.rec else 0 + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"]) + out = self.task.outcome(self.inst) + succ = bool(out["success"]) + where = f"a{e['attempt']}done" + if succ != bool(e.get("success") in (True, "True")): + self.mismatch.append((where, "success", e.get("success"), succ)) + lo = e.get("outcome") or {} + ro = norm_json({k: v for k, v in out.items() if k != "feedback"}) + if isinstance(lo, dict): + for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8): + self.mismatch.append((where,) + d) + info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""), + feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")), + think_s=e.get("think_s")) + try: + info["feedback_f2"] = self.task.feedback(self.inst, out, "F2") + except Exception as ex_: + info["feedback_f2"] = f"" + if self.rec: + info["judge_frames"] = [f0, self.rec.n] + self.ep_attempts.append(info) + last = self.attempt >= self.k or succ or bool(out.get("terminal")) + if self.protocol == "cross" or last: + self.close_episode() + if last: + return True + self.attempt += 1 + if self.protocol == "cross": + self.task.reset_instance(self.inst) + self.n_mon = 0 + if self.rec: + self._open_episode() + elif self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + return False + + def run(self): + t0 = time.time() + finished = False + for e in self.ev: + if e["ev"] == "call": + if e.get("cmd") == "move_eef": + self.move_eef(e) + elif e.get("cmd") == "observe": + self.observe(e) + else: + self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None)) + elif e["ev"] == "done": + finished = self.done(e) + if finished: + break + self.unfinished = not finished + if not finished and self.rec and self.rec.sink is not None: + # the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged + if self.rec.n or self.ep_attempts: + self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True, + finish_reason="", feedback_shown="", auto_ended=False)) + self.close_episode() + else: + shutil.rmtree(self.rec.sink.path, ignore_errors=True) + self.rec.sink = None + self.wall_s = time.time() - t0 + return self + + def summary(self): + return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"], + protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff), + n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6), + unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1), + first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]]) + + +# ====================================================================================================== annotation + +def task_info(task, inst): + cls = type(task) + return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable", + category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"), + max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)), + instruction=cls.instruction) + + +def build_annotation(rp, sink): + """Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2 + failure description), run-level outcome class, every robot command with its frame span and the agent's narration, + task-side error events with frame indices.""" + log = rp.log + s = rp.start + cond, chain = log.condition() + cls, hist = log.outcome_class() + att_all = log.attempts() + attempts = [] + for a in rp.ep_attempts: + a = dict(a) + n = a["attempt"] + later = [x for x in att_all if x["attempt"] > n] + a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later)) + a["is_last_attempt_of_run"] = not later + fn = log.finish_notes.get(n) + if fn: + a["agent_finish"] = fn + a["error_event_in_attempt"] = error_event(a.get("outcome")) + attempts.append(a) + # post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command) + for a in attempts: + nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1]) + if a.get("success") is False and nxt: + note = log.notes[nxt[0]] + a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note} + commands = [] + for sp in rp.spans: + e = log.calls.get((sp["attempt"], sp["step"])) or {} + rep = e.get("report") or {} + c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"], + frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]), + args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"), + stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"), + gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"), + touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"), + agent_obs_images=rep.get("images")) + note = log.notes.get((sp["attempt"], sp["step"])) + if note: + c["agent_note"] = {k: v for k, v in note.items() if k != "command"} + commands.append(c) + t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x] + return dict( + schema=SCHEMA, + source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts], + episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain, + memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None), + feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"), + k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"), + contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256") + if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)), + agent=log.agent_info(), + task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"), + instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}), + run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all), + run_success=any(x["success"] for x in att_all) if att_all else None, + agent_final_report=log.final_report[:6000] or None, + mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)), + attempts=attempts, + commands=commands, + task_events=rp.events, + frames=dict(n=sink.n, fps=FPS, image_res=rp.res, + phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"], + joint_pos=rp.ep_initial["joint_pos"], + gripper_qpos=rp.ep_initial["gripper_qpos"])), + ) + + +# ====================================================================================================== CLI + +def load_manifest(run_dir): + p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json") + return json.load(open(p)) if os.path.exists(p) else {} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("mode", choices=["check", "record"]) + ap.add_argument("runs", nargs="+") + ap.add_argument("--json", default="") + ap.add_argument("--out", default="") + ap.add_argument("--res", type=int, default=256) + ap.add_argument("--force", action="store_true", help="record again even if replay.json exists") + a = ap.parse_args() + rows = [] + for r in a.runs: + r = r.rstrip("/") + try: + if a.mode == "check": + s = RunReplay(r, manifest=load_manifest(r)).run().summary() + else: + batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r) + rd = os.path.join(a.out, batch, name) + if os.path.exists(os.path.join(rd, "replay.json")) and not a.force: + print(json.dumps(dict(run=name, skipped="exists")), flush=True) + continue + shutil.rmtree(rd, ignore_errors=True) + rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run() + s = rp.summary() + s["episodes"] = rp.episodes + with open(os.path.join(rd, "replay.json"), "w") as f: + json.dump(s, f, indent=1) + except Exception: + import traceback + s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:]) + rows.append(s) + print(json.dumps(s), flush=True) + if a.json: + with open(a.json, "w") as f: + json.dump(rows, f, indent=1) + + +if __name__ == "__main__": + main() diff --git a/leaf/code/v1.5/v1.4/prepare_verified.py b/leaf/code/v1.5/v1.4/prepare_verified.py new file mode 100644 index 0000000000000000000000000000000000000000..82101c84f6ed16c785299c1f3fab9de101541eb7 --- /dev/null +++ b/leaf/code/v1.5/v1.4/prepare_verified.py @@ -0,0 +1,29 @@ +"""Select only exact replay candidates, preserving rejected fidelity reports.""" +import json +from pathlib import Path + +J=Path(__file__).resolve().parent +B=J.parent +selected=json.loads((J/'selected.json').read_text()) +accepted=[];rejected=[];missing=[] +for row in selected: + prefix='legacy_raw' if row['cohort']=='legacy' else 'raw' + rel=Path(row['batch'])/row['run'] + candidates=[] + for root in [prefix+'_local',prefix]: + p=B/root/rel/'replay.json' + if p.exists():candidates.append((p,json.loads(p.read_text()))) + passing=[(p,r) for p,r in candidates if not r.get('error') and r.get('n_mismatch')==0 and not r.get('code_diff') and not r.get('inst_diff')] + if passing: + p,r=passing[0] + target=B/('legacy_verified_raw' if row['cohort']=='legacy' else 'verified_raw')/rel + target.parent.mkdir(parents=True,exist_ok=True) + if not target.exists():target.symlink_to(p.parent,target_is_directory=True) + accepted.append(dict(row,replay_path=str(p),reports_checked=r['n_checked'],frames=sum(e['n_frames'] for e in r['episodes']))) + elif candidates: + rejected.append(dict(row,reason='no exact replay candidate',candidates=[dict(path=str(p),report=r) for p,r in candidates])) + else:missing.append(row) +assert not missing, [r['run'] for r in missing] +report=dict(accepted=accepted,rejected=rejected,missing=missing) +(J/'verified_selection.json').write_text(json.dumps(report,indent=2)) +print(json.dumps(dict(accepted=len(accepted),rejected=len(rejected),missing=len(missing)))) diff --git a/leaf/code/v1.5/v1.4/run.sh b/leaf/code/v1.5/v1.4/run.sh new file mode 100644 index 0000000000000000000000000000000000000000..3d207328ec7a90dfc1861255bfbfc70c22346ab8 --- /dev/null +++ b/leaf/code/v1.5/v1.4/run.sh @@ -0,0 +1,35 @@ +#!/bin/bash +set -euo pipefail +BASE=/mnt/cpfs/shared/outputs/peter/lffbench/20261025-0615-v1.4-backfill +J=$BASE/job +L=$J/source +LPY=/mnt/cpfs/workspace/env/libero-cpu/bin/python +EPY=/mnt/cpfs/workspace/env/zeva-cosmos-cu128/bin/python +export OMP_NUM_THREADS=1 LP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 PYTHONUNBUFFERED=1 +export MUJOCO_GL=osmesa PYOPENGL_PLATFORM=osmesa +export LIBERO_CONFIG_PATH=/mnt/cpfs/workspace/env/libero-cpu/.libero +export PYTHONPATH=$L:/mnt/cpfs/workspace/RSS/LIBERO-Recovery/LIBERO +export LD_LIBRARY_PATH=$J/osmesa_libs +cd "$L" +if [ "${EXPORT_ONLY:-0}" != 1 ]; then + REF=$(find /mnt/cpfs/workspace/agentic-robotics/lerobot_job/preflight_ref/cx_main1 -mindepth 1 -maxdepth 1 -type d | head -1) + "$LPY" "$J/osmesa_run.py" "$L/scripts/lerobot_replay.py" record \ + "/mnt/cpfs/workspace/agentic-robotics/lffbench/runs/api/cx_main1/$(basename "$REF")" --out "$J/preflight" > "$J/logs/preflight.log" 2>&1 + "$LPY" "$J/preflight_check.py" "$J/preflight/cx_main1/$(basename "$REF")" "$REF" + xargs -P 64 -n 1 "$LPY" "$J/record_one.py" < "$J/runlist.txt" > "$J/logs/record.jsonl" 2> "$J/logs/record.err" +fi +"$LPY" "$J/audit_replays.py" +for prefix in delta legacy; do + if [ "$prefix" = delta ]; then + RAW=$BASE/raw_local,$BASE/raw + else + RAW=$BASE/legacy_raw_local,$BASE/legacy_raw + fi + "$EPY" "$L/scripts/lerobot_export.py" plan --work "$BASE/${prefix}_work" \ + --raw "$RAW" --runs-root "$J/runs_index" --paper "$J/paper" \ + --task-set "$L/sets/main_v2_1inst.txt" --repo-id "lffbench/${prefix}-backfill" + seq 0 23 | xargs -P 24 -I{} bash -c '"$1" "$2/scripts/lerobot_export.py" shard --work "$3/${5}_work" --shard "$4" --nshards 24 --threads 2 > "$3/job/logs/${5}_shard_$4.log" 2>&1' _ "$EPY" "$L" "$BASE" {} "$prefix" + "$EPY" "$L/scripts/lerobot_export.py" merge --work "$BASE/${prefix}_work" --nshards 24 --out "$BASE/${prefix}_dataset" > "$J/logs/merge_${prefix}.log" 2>&1 +done +"$EPY" "$J/merge_cumulative.py" > "$J/logs/merge_cumulative.log" 2>&1 +echo 'EXPORT COMPLETE; validation and publication pending' diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/backends/chat_completions.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/backends/chat_completions.py new file mode 100644 index 0000000000000000000000000000000000000000..ec6c2cebb3976390ef7ed172d4b8edbb870a092f --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/backends/chat_completions.py @@ -0,0 +1,150 @@ +"""OpenAI-compatible Chat Completions backend (function calling), e.g. for a local open-source VLM served +by scripts/qwen_vl_server.py or any vLLM / SGLang endpoint. Same conversation, different wire format. + +Reasoning models on this API (Kimi, DeepSeek, vLLM reasoning parsers) return their thinking as the non-standard +message field `reasoning_content`. It is logged as the reasoning summary and, with replay_reasoning (default), sent +back unchanged on that assistant message, so the model keeps its reasoning across tool calls like the Anthropic and +Responses backends do (Kimi's docs ask for this in multi-step tool use).""" +import json +import os +import time + +from ..context import ToolCall, prune_live_images +from .base import Backend, BackendResponse, import_openai + + +def chat_tools(specs): + return [dict(type="function", function=dict(name=s["name"], description=s["description"], + parameters=s["parameters"])) for s in specs] + + +class ChatCompletionsBackend(Backend): + name = "chat" + + def __init__(self, model="qwen3-vl-8b", base_url=None, api_key=None, temperature=0.0, max_tokens=1024, + max_live_images=4, jpeg_quality=90, timeout=600.0, client=None, extra_body=None, + replay_reasoning=True): + self.model = model + self.base_url = base_url or os.environ.get("LFF_CHAT_BASE_URL", "http://127.0.0.1:8765/v1") + self.api_key = api_key or os.environ.get("LFF_CHAT_API_KEY", "EMPTY") + self.temperature = temperature + self.max_tokens = max_tokens + self.max_live_images = max_live_images + self.jpeg_quality = jpeg_quality + self.timeout = timeout + self.extra_body = extra_body + self.replay_reasoning = replay_reasoning + self._client = client + + def config(self): + return dict(name=self.name, model=self.model, base_url=self.base_url, temperature=self.temperature, + max_tokens=self.max_tokens, max_live_images=self.max_live_images, + replay_reasoning=self.replay_reasoning) + + def client(self): + if self._client is None: + openai = import_openai() + kw = dict(api_key=self.api_key, base_url=self.base_url, timeout=self.timeout, max_retries=1) + if any(h in self.base_url for h in ("://127.0.0.1", "://localhost")): + # local server: ignore the machine's proxy variables (ALL_PROXY=socks5h://... is set here) + kw["http_client"] = openai.DefaultHttpxClient(trust_env=False, timeout=self.timeout) + self._client = openai.OpenAI(**kw) + return self._client + + def build_request(self, conv, tools): + msgs = [dict(role="system", content=conv.system)] + for it in prune_live_images(conv.items, self.max_live_images): + if it["kind"] == "user": + content = [] + for p in it["parts"]: + if p["type"] == "text": + content.append(dict(type="text", text=p["text"])) + else: + content.append(dict(type="image_url", image_url=dict(url=p["image"].data_url(self.jpeg_quality)))) + msgs.append(dict(role="user", content=content)) + elif it["kind"] == "assistant": + if not it.get("text") and not it["tool_calls"]: + # a reasoning-only turn (no text, no tool call; seen with DeepSeek at effort=max): the player still + # counts it and nudges, but OpenAI-compatible APIs reject an assistant message with neither content + # nor tool_calls (DeepSeek: 400 "content or tool_calls must be set"), so it is left out of the request + continue + m = dict(role="assistant", content=it.get("text") or None) + rc = (it.get("raw") or [{}])[0].get("reasoning_content") if it.get("backend") == self.name else None + if rc and self.replay_reasoning: + m["reasoning_content"] = rc + if it["tool_calls"]: + m["tool_calls"] = [dict(id=tc.id, type="function", + function=dict(name=tc.name, + arguments=tc.raw_arguments or json.dumps(tc.arguments))) + for tc in it["tool_calls"]] + msgs.append(m) + elif it["kind"] == "tool_output": + msgs.append(dict(role="tool", tool_call_id=it["call_id"], content=it["text"])) + req = dict(model=self.model, messages=tool_results_first(msgs), tools=chat_tools(tools), tool_choice="auto", + max_tokens=self.max_tokens) + if self.temperature is not None: # None: the endpoint's default (reasoning models may reject a temperature) + req["temperature"] = self.temperature + if self.extra_body: + req["extra_body"] = dict(self.extra_body) + return req + + def act(self, conv, tools): + req = self.build_request(conv, tools) + n_img = sum(1 for m in req["messages"] if isinstance(m.get("content"), list) + for c in m["content"] if c.get("type") == "image_url") + t0 = time.time() + resp = self.client().chat.completions.create(**req) + lat = time.time() - t0 + stats = dict(n_images=n_img, n_messages=len(req["messages"])) + if not getattr(resp, "choices", None): # gateway hiccup: nothing to append, the player asks again + return BackendResponse(latency_s=lat, request_stats=stats, status="incomplete", + error="empty response (no choices)") + msg = resp.choices[0].message + rc = getattr(msg, "reasoning_content", None) or (getattr(msg, "model_extra", None) or {}).get("reasoning_content") + calls = [] + for i, tc in enumerate(msg.tool_calls or []): + raw = tc.function.arguments or "" + try: + args = json.loads(raw) if raw else {} + except json.JSONDecodeError: + args = {} + calls.append(ToolCall(id=tc.id or f"call_{i}", name=tc.function.name, arguments=args, raw_arguments=raw)) + u = resp.usage + ctd = getattr(u, "completion_tokens_details", None) if u else None + usage = dict(input_tokens=getattr(u, "prompt_tokens", 0) or 0, cached_tokens=0, + output_tokens=getattr(u, "completion_tokens", 0) or 0, + reasoning_tokens=(getattr(ctd, "reasoning_tokens", 0) or 0) if ctd else 0) if u else {} + if not calls and not msg.content and not rc and not u: + return BackendResponse(latency_s=lat, request_stats=stats, status="incomplete", + error="empty response (no output, no usage)") + return BackendResponse(tool_calls=calls, text=msg.content or None, reasoning_summary=rc or None, usage=usage, + latency_s=lat, raw=[dict(reasoning_content=rc)] if rc else None, request_stats=stats) + + +def tool_results_first(msgs): + """OpenAI-compatible APIs require every tool_call of an assistant message to be answered by tool messages directly + after it. The player adds the images a tool returned (view_images, robot) as a user message right after that tool's + output, so a turn with several tool calls (e.g. view_images then shell) would put a user message between the tool + messages (DeepSeek: 400 "insufficient tool messages following tool_calls message"). Move such user messages after + the last tool message of the turn; nothing else changes order.""" + out, i = [], 0 + while i < len(msgs): + m = msgs[i] + out.append(m) + i += 1 + if m["role"] != "assistant" or not m.get("tool_calls"): + continue + need = {tc["id"] for tc in m["tool_calls"]} + held = [] + while i < len(msgs) and need: + n = msgs[i] + if n["role"] == "tool" and n.get("tool_call_id") in need: + out.append(n) + need.discard(n["tool_call_id"]) + elif n["role"] == "user": + held.append(n) + else: + break + i += 1 + out.extend(held) + return out diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/fakeapi.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/fakeapi.py new file mode 100644 index 0000000000000000000000000000000000000000..ba9482378574fd6e4fec4b25b958f94103ff4fee --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/fakeapi.py @@ -0,0 +1,188 @@ +"""Local fake model APIs for offline harness checks (no real model, no cost). + +Both servers listen on 127.0.0.1, record every request body (auth headers dropped) and answer from a script, so a +native harness can be driven turn by turn without a model: + FakeAnthropic Anthropic Messages API (streaming SSE), used by Claude Code and by api_player --provider anthropic + FakeResponses OpenAI Responses API (streaming SSE), used by Codex through a custom model provider + +A script is a list of turns; turn i is answered to the request that already holds i assistant turns, so retries get +the same answer. Past the end of the script the server answers with a final text. A turn is a list of steps: + ("tool", name, args) Anthropic: tool_use block (name as given, e.g. "mcp__lff__robot" or "Read") + ("text", s) a text block / assistant message + ("exec", js) Responses: one `exec` custom tool call (Codex code mode) with this JavaScript + ("fcall", name, args) Responses: a plain function call + ("nscall", ns, name, args) Responses: a function call into a tool namespace (Codex without code mode calls our MCP + tools this way: name "robot", namespace "mcp__lff"; measured with 0.163) + + srv = FakeAnthropic(script, record_dir).start(); ... srv.base_url ...; srv.stop() +""" +import itertools +import json +import os +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +DROP_HEADERS = ("x-api-key", "authorization", "cookie", "chatgpt-account-id") + + +class _Base: + final_text = "done" + + def __init__(self, script=None, record_dir=None, port=0): + self.script = list(script or []) + self.record_dir = record_dir + self.port = port + self.lock = threading.Lock() + self.counter = itertools.count(1) + self.requests = [] # (n, path, body) + if record_dir: + os.makedirs(record_dir, exist_ok=True) + + # ------------------------------------------------------------------ plumbing + def start(self): + outer = self + + class H(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *a): + pass + + def _record(self, body): + with outer.lock: + n = next(outer.counter) + outer.requests.append((n, self.path, body)) + if outer.record_dir: + with open(os.path.join(outer.record_dir, f"req_{n:03d}.json"), "w") as f: + json.dump(dict(method=self.command, path=self.path, body=body, + headers={k: v for k, v in self.headers.items() if k.lower() not in DROP_HEADERS}), + f, indent=1, ensure_ascii=False) + return n + + def do_GET(self): + self._record(None) + self._send(404, b"{}", "application/json") + + def do_HEAD(self): + self._send(404, b"", "application/json") + + def do_POST(self): + raw = self.rfile.read(int(self.headers.get("content-length", 0) or 0)) + try: + body = json.loads(raw) + except ValueError: + body = raw[:4000].decode("utf-8", "replace") + n = self._record(body) + outer.handle(self, n, body) + + def _send(self, code, data, ctype): + self.send_response(code) + self.send_header("content-type", ctype) + self.send_header("content-length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + self.httpd = ThreadingHTTPServer(("127.0.0.1", self.port), H) + self.httpd.daemon_threads = True + self.port = self.httpd.server_address[1] + threading.Thread(target=self.httpd.serve_forever, daemon=True).start() + return self + + def stop(self): + self.httpd.shutdown() + self.httpd.server_close() + + def turn(self, i): + return self.script[i] if i < len(self.script) else [("text", self.final_text)] + + @staticmethod + def send_sse(h, events): + data = b"".join(f"event: {ev}\ndata: {json.dumps(d)}\n\n".encode() for ev, d in events) + h._send(200, data, "text/event-stream") + + +class FakeAnthropic(_Base): + @property + def base_url(self): + return f"http://127.0.0.1:{self.port}" + + def handle(self, h, n, body): + if not h.path.startswith("/v1/messages") or "count_tokens" in h.path or not isinstance(body, dict): + h._send(200, json.dumps({"input_tokens": 10}).encode(), "application/json") + return + msgs = body.get("messages", []) + i = sum(1 for m in msgs if m.get("role") == "assistant") + steps = self.turn(i) + blocks = [] + for j, st in enumerate(steps): + if st[0] == "tool": + blocks.append(dict(type="tool_use", id=f"toolu_fake_{i:03d}_{j}", name=st[1], input=st[2])) + else: + blocks.append(dict(type="text", text=st[1])) + stop = "tool_use" if any(b["type"] == "tool_use" for b in blocks) else "end_turn" + model = body.get("model", "fake") + evs = [("message_start", dict(type="message_start", message=dict( + id=f"msg_fake_{n}", type="message", role="assistant", model=model, content=[], stop_reason=None, + stop_sequence=None, usage=dict(input_tokens=100, output_tokens=1))))] + for k, b in enumerate(blocks): + if b["type"] == "tool_use": + evs.append(("content_block_start", dict(type="content_block_start", index=k, content_block=dict( + type="tool_use", id=b["id"], name=b["name"], input={})))) + evs.append(("content_block_delta", dict(type="content_block_delta", index=k, delta=dict( + type="input_json_delta", partial_json=json.dumps(b["input"]))))) + else: + evs.append(("content_block_start", dict(type="content_block_start", index=k, + content_block=dict(type="text", text="")))) + evs.append(("content_block_delta", dict(type="content_block_delta", index=k, + delta=dict(type="text_delta", text=b["text"])))) + evs.append(("content_block_stop", dict(type="content_block_stop", index=k))) + evs.append(("message_delta", dict(type="message_delta", delta=dict(stop_reason=stop, stop_sequence=None), + usage=dict(output_tokens=5)))) + evs.append(("message_stop", dict(type="message_stop"))) + self.send_sse(h, evs) + + def message_requests(self): + return [(n, b) for n, p, b in self.requests if isinstance(b, dict) and p.startswith("/v1/messages") + and "count_tokens" not in p] + + +class FakeResponses(_Base): + @property + def base_url(self): + return f"http://127.0.0.1:{self.port}/v1" + + def handle(self, h, n, body): + if not isinstance(body, dict) or "input" not in body: + h._send(404, b"{}", "application/json") + return + items = body.get("input") or [] + i = sum(1 for it in items if isinstance(it, dict) and it.get("type") in + ("custom_tool_call", "function_call") or (isinstance(it, dict) and it.get("type") == "message" + and it.get("role") == "assistant")) + steps = self.turn(i) + out = [] + for j, st in enumerate(steps): + if st[0] == "exec": + out.append(dict(type="custom_tool_call", id=f"ctc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}", + name="exec", status="completed", input=st[1])) + elif st[0] == "fcall": + out.append(dict(type="function_call", id=f"fc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}", + name=st[1], arguments=json.dumps(st[2]), status="completed")) + elif st[0] == "nscall": + out.append(dict(type="function_call", id=f"fc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}", + namespace=st[1], name=st[2], arguments=json.dumps(st[3]), status="completed")) + else: + out.append(dict(type="message", id=f"msg_fake_{n}_{j}", role="assistant", status="completed", + content=[dict(type="output_text", text=st[1], annotations=[])])) + rid = f"resp_fake_{n}" + evs = [("response.created", dict(type="response.created", response=dict(id=rid, status="in_progress")))] + for k, it in enumerate(out): + evs.append(("response.output_item.done", dict(type="response.output_item.done", output_index=k, item=it))) + evs.append(("response.completed", dict(type="response.completed", response=dict( + id=rid, status="completed", output=out, usage=dict( + input_tokens=100, input_tokens_details=dict(cached_tokens=0), output_tokens=3, + output_tokens_details=dict(reasoning_tokens=0), total_tokens=103))))) + self.send_sse(h, evs) + + def model_requests(self): + return [(n, b) for n, p, b in self.requests if isinstance(b, dict) and "input" in b] diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-flash_high.json b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-flash_high.json new file mode 100644 index 0000000000000000000000000000000000000000..2d09a5b6233607bf6538692ac28f560bd8aeba66 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-flash_high.json @@ -0,0 +1,15 @@ +{ + "key": "dsh|0.2.1-rc.5|aa65546cc1f51674|deepseek-flash|high", + "fingerprint_sha256": "18044f5deb7b4d0d662d620fce120e85e3f94103fa2699346221fa46d093fc8f", + "written": "2026-10-31 06:05:50", + "summary": { + "system_chars": 109, + "tools": [ + "mcp__lff__robot", + "mcp__lff__shell", + "mcp__lff__view_images" + ], + "effort_in_request": "high", + "model_in_request": "deepseek-flash" + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/rpent_codex-generic-9f0e3aafc10c_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/rpent_codex-generic-9f0e3aafc10c_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json new file mode 100644 index 0000000000000000000000000000000000000000..ba747d0da48ab2822af1e855e0ada532dd0a8fd5 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/rpent_codex-generic-9f0e3aafc10c_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json @@ -0,0 +1,27 @@ +{ + "key": "rpent_codex-generic-9f0e3aafc10c|0.163.0|399ff69c431c066e|gpt-6.1-sol|high", + "fingerprint_sha256": "6e63c24ad13895ebfbb0bc76a17ebbdc9765414a3f4351fe442480afa50b5ce9", + "written": "2026-10-24 07:27:13", + "summary": { + "developer_chars": 16979, + "top_tools": [ + "list_mcp_resource_templates", + "list_mcp_resources", + "mcp__lff.robot", + "mcp__lff.shell", + "mcp__lff.view_images", + "read_mcp_resource", + "request_user_input" + ], + "effort_in_request": "high", + "model_in_request": "gpt-6.1-sol", + "sandbox": { + "sandbox": "seccomp", + "sandbox_mode": "read-only" + }, + "middle_fingerprint_sha256": "3dc06d7d7d7c5fb03c550905ba2d16faecefde695afc17f1f9f77da16c376e8c", + "rpent_prefix_sha256": "f0d0e0a62990cb7028bfb3889e49423b12635347aaddbda40e4d2fc4cb408e25", + "rpent_prefix_chars": 2789, + "anchor_status": "match" + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/real/executor.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/real/executor.py new file mode 100644 index 0000000000000000000000000000000000000000..edb5a9a3932e891684f2a2c17bb8024c994d46dd --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/real/executor.py @@ -0,0 +1,138 @@ +"""RealToolExecutor: the real-robot counterpart of lffbench.agent.tools.ToolExecutor. + +robot_server's LA interface needs only this from its executor: observe(label) -> [ImageRef], proprio() -> dict, and +call("move_to" | "open_gripper" | "close_gripper", args) -> ToolResult. Here every call goes to a robot driver +(lffbench/real/protocol.py) instead of the simulator. + +Calibration bias (L1 tasks), as Skills / ToolExecutor do it in simulation: the driver is sent commanded + bias and +reports the true pose; the agent is told true - bias (what a miscalibrated robot believes). Joint angles are then the +ones that put the grasp point at the believed pose (driver /ik), as robot_server._believed_joints does in simulation. +""" +import math +import time + +import numpy as np + +from ..agent.images import ImageRef +from ..agent.tools import ToolResult, parse_args +from .protocol import CAMERAS, DriverError, square_resize, state_problems + +SPEED_MIN = 0.01 # m/s; below this a straight-line move takes too long to be useful + + +def _r(v, nd=4): + return [round(float(x), nd) for x in v] + + +class RealToolExecutor: + def __init__(self, driver, info, bias=None, image_res=512, cams=CAMERAS): + self.driver, self.info = driver, info + self.bias = np.zeros(3) if bias is None else np.asarray(bias, float) + self.image_res = int(image_res) + self.cams = tuple(cams) + self.n_joints = int(info["n_joints"]) + self.yaw_lo, self.yaw_hi = (float(v) for v in info["yaw_range_deg"]) + self.max_speed = float(info["max_speed"]) + self.motion_s = 0.0 # robot motion time of this executor (= this attempt), as reported by the driver + self.n_calls = 0 + self._state = None + self.grip_closed = False # last gripper command of this attempt (the driver's home pose has it open) + self.yaw_cmd = None # last commanded yaw (degrees), for choosing among the gripper-symmetric equivalents + self.refresh() + self.yaw_cmd = float(self._state["eef_yaw_deg"]) + + # ------------------------------------------------------------------ state + def _set_state(self, st): + prob = state_problems(st, self.n_joints) + if prob: + raise DriverError("driver state: " + "; ".join(prob)) + self._state = st + + def refresh(self): + self._set_state(self.driver.state()) + + def true_eef(self): + return np.asarray(self._state["eef_pos"], float) + + def believed_eef(self): + return self.true_eef() - self.bias + + def proprio(self): + st = self._state + return dict(eef_pos=_r(self.believed_eef()), eef_yaw_deg=round(float(st["eef_yaw_deg"]), 1), + gripper="closed" if self.grip_closed else "open", + gripper_width_m=round(float(st["gripper_width_m"]), 4)) + + def joints(self): + """Joint angles as the robot's encoders would report them under the hidden calibration error.""" + if not np.any(self.bias): + return [float(v) for v in self._state["joint_pos_rad"]] + key = (tuple(self._state["eef_pos"]), float(self._state["eef_yaw_deg"])) + if getattr(self, "_ik_key", None) != key: # one /ik per new state (the server asks several times per command) + self._ik_key = key + self._ik_val = [float(v) for v in self.driver.ik(self.believed_eef(), key[1])] + return list(self._ik_val) + + def observe(self, label=""): + frames, st = self.driver.observe() + self._set_state(st) + return [ImageRef(camera=c, array=square_resize(frames[c], self.image_res), label=f"{label} {c}".strip()) + for c in self.cams] + + # ------------------------------------------------------------------ helpers + def wrap_yaw(self, yaw): + """The two-finger gripper is symmetric: among yaw + k*180 inside the driver's yaw range, use the one closest to + the last commanded yaw (Skills.wrap_yaw does the same with its +-113 deg limit).""" + cands = [yaw + 180.0 * k for k in range(-3, 4)] + ok = [c for c in cands if self.yaw_lo <= c <= self.yaw_hi] or cands + return float(min(ok, key=lambda c: abs(c - self.yaw_cmd))) + + # ------------------------------------------------------------------ dispatch (same signature as ToolExecutor.call) + def call(self, name, raw_args): + t0 = time.time() + self.n_calls += 1 + args = parse_args(raw_args) + fn = getattr(self, f"_t_{name}", None) + if fn is None: + return ToolResult(name, args, False, dict(ok=False, error=f"unknown tool {name!r}"), wall_s=time.time() - t0) + res = fn(**args) + res.args, res.wall_s = args, time.time() - t0 + return res + + def _report(self, name, extra=None): + rep = dict(ok=True, tool=name) + rep.update(extra or {}) + rep.update(self.proprio()) + return rep + + def _t_move_to(self, x, y, z, yaw, speed=None): + tgt = np.array([x, y, z], float) + if not np.all(np.isfinite(tgt)): + return ToolResult("move_to", {}, False, dict(ok=False, error="non-finite coordinates")) + spd = None if speed is None else float(np.clip(float(speed), SPEED_MIN, self.max_speed)) + yaw_used = self.wrap_yaw(float(yaw)) + cmd = tgt + self.bias # the hidden calibration error acts on every commanded position + rep = self.driver.move(cmd[0], cmd[1], cmd[2], yaw_used, spd) + self.motion_s += float(rep.get("motion_s") or 0.0) + self._set_state(rep["state"]) + if not rep["ok"]: # rejected before moving (driver hard limits / no IK solution) + return ToolResult("move_to", {}, False, dict(ok=False, error="target rejected: the arm cannot reach it; " + "the arm did not move", driver_error=rep.get("error", ""))) + self.yaw_cmd = yaw_used + reached = bool(np.linalg.norm(cmd - self.true_eef()) < 0.02) + return ToolResult("move_to", {}, True, self._report("move_to", dict(reached=reached, + yaw_used_deg=round(yaw_used, 1)))) + + def _gripper(self, close): + rep = self.driver.gripper(close) + self.grip_closed = bool(close) + self.motion_s += float(rep.get("motion_s") or 0.0) + self._set_state(rep["state"]) + name = "close_gripper" if close else "open_gripper" + return ToolResult(name, {}, True, self._report(name)) + + def _t_open_gripper(self): + return self._gripper(False) + + def _t_close_gripper(self): + return self._gripper(True) diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/client/lffbench_client/__init__.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/client/lffbench_client/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b5701a1adf87d05ade8ed619db6e6bf1e1c0f796 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/client/lffbench_client/__init__.py @@ -0,0 +1,139 @@ +"""LFF-Bench Python client: the three agent tools of one episode, for any robot harness framework (docs/18 §6.3). + +Only the standard library; it never imports the simulator. It talks to the episode's tool gateway +(scripts/tool_gateway.py), which runs next to the robot server and owns the per-attempt tool-call budget, the jailed +shell and the workspace images. A framework registers the three tools with the schemas from tool_specs() and calls +them through a Session: + + from lffbench_client import Session + s = Session.from_env() # LFF_GATEWAY_URL, LFF_GATEWAY_TOKEN (set by the launcher) + first = s.first_message() # README + first status, as every harness gets it + tools = s.tool_specs("openai_responses") # or raw / mcp / anthropic / openai_chat + r = s.robot("move_eef x=0.5 y=0.0 z=0.2") # -> ToolResult + r.json() # the robot server's reply as a dict + s.view_images(["obs/s001_agentview.jpg"]).images # [(mime, bytes)] + +A ToolResult's content is the list a model should see, in MCP form (text items and base64 image items); finished +says that the episode is over (stop calling tools). Nothing here can reset the scene or read the verdict: the only +feedback is what the robot server writes into the tool results. +""" +import base64 +import dataclasses +import json +import os +import urllib.error +import urllib.parse +import urllib.request + +__all__ = ["Session", "ToolResult", "GatewayError", "STYLES"] +__version__ = "0.1.0" + +STYLES = ("raw", "mcp", "anthropic", "openai_responses", "openai_chat") + + +class GatewayError(RuntimeError): + pass + + +@dataclasses.dataclass +class ToolResult: + content: list # [{"type": "text", "text"} | {"type": "image", "mimeType", "data" (base64)}] + is_error: bool + finished: bool # the episode is over: stop calling tools and report + calls_in_attempt: int # tool calls used in the current attempt (after an automatic finish: 0) + + @property + def text(self): + """All text items, joined by newlines.""" + return "\n".join(c["text"] for c in self.content if c.get("type") == "text") + + def json(self): + """The first text item parsed as JSON (robot / shell / view_images replies are JSON objects).""" + for c in self.content: + if c.get("type") == "text": + return json.loads(c["text"]) + raise ValueError("no text item") + + @property + def images(self): + """[(mime type, bytes)] of the image items.""" + return [(c["mimeType"], base64.b64decode(c["data"])) for c in self.content if c.get("type") == "image"] + + +class Session: + """One episode's tools through its gateway. face labels this access path in the gateway transcript.""" + + def __init__(self, url, token, face="sdk", timeout_s=900.0): + self.url, self.token, self.face, self.timeout_s = url.rstrip("/"), token, face, timeout_s + self._opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) # loopback: never via a proxy + + @classmethod + def from_env(cls, face="sdk", **kw): + url, token = os.environ.get("LFF_GATEWAY_URL"), os.environ.get("LFF_GATEWAY_TOKEN") + if not url or not token: + raise GatewayError("LFF_GATEWAY_URL / LFF_GATEWAY_TOKEN are not set") + return cls(url, token, face=face, **kw) + + @classmethod + def from_gateway_file(cls, path, face="sdk", **kw): + """gateway.json written by the gateway in the run's log dir (launchers only; harness processes get env vars).""" + d = json.load(open(path)) + return cls(d["url"], d["token"], face=face, **kw) + + # ------------------------------------------------------------------------------------------------ http + def _request(self, method, path, body=None): + req = urllib.request.Request(self.url + path, method=method, + data=None if body is None else json.dumps(body).encode(), + headers={"Authorization": f"Bearer {self.token}", "X-LFF-Face": self.face, + "Content-Type": "application/json"}) + try: + with self._opener.open(req, timeout=self.timeout_s) as r: + return r.read(), r.headers.get("Content-Type", "") + except urllib.error.HTTPError as e: + raise GatewayError(f"{method} {path}: HTTP {e.code}: {e.read()[:500].decode('utf-8', 'replace')}") from None + except urllib.error.URLError as e: + raise GatewayError(f"{method} {path}: {e.reason}") from None + + def _get_json(self, path): + return json.loads(self._request("GET", path)[0]) + + # ------------------------------------------------------------------------------------------------ tools + def call(self, name, arguments=None): + raw, _ = self._request("POST", "/tool", dict(name=name, arguments=arguments or {})) + d = json.loads(raw) + return ToolResult(content=d["content"], is_error=bool(d["is_error"]), finished=bool(d["finished"]), + calls_in_attempt=d.get("calls_in_attempt")) + + def robot(self, command): + """One robot command, exactly as in the instructions (e.g. 'status', 'move_eef x=0.5 z=0.2', 'finish ...').""" + return self.call("robot", dict(command=command)) + + def shell(self, command): + """A bash command in the episode workspace (jailed: no network, nothing outside the workspace).""" + return self.call("shell", dict(command=command)) + + def view_images(self, paths): + """Image files of the workspace (e.g. obs/s001_agentview.jpg); the images come back as image items.""" + return self.call("view_images", dict(paths=list(paths))) + + # ------------------------------------------------------------------------------------------------ instructions + def tool_specs(self, style="raw"): + """The three tool schemas with the reference descriptions, in one of STYLES.""" + if style not in STYLES: + raise ValueError(f"style must be one of {STYLES}") + return self._get_json("/tool_specs?style=" + urllib.parse.quote(style))["tools"] + + def readme(self): + return self._request("GET", "/readme")[0].decode("utf-8") + + def first_message(self): + """Preamble + README + first status report: the first user message every harness gets.""" + return self._request("GET", "/first_message")[0].decode("utf-8") + + def health(self): + return self._get_json("/health") + + def status(self): + """robot_server's `status` for the framework's own loop (e.g. a "continue" nudge that names the attempt): not + a tool call of the model, not counted in the per-attempt budget. Never show it to the model as a tool result.""" + return self._get_json("/status") diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.267_0399c793ff571d59_claude-opus-5-5_high.json b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.267_0399c793ff571d59_claude-opus-5-5_high.json new file mode 100644 index 0000000000000000000000000000000000000000..e9dcf0fa1fc46a47f147f3fb280512d628d35c65 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.267_0399c793ff571d59_claude-opus-5-5_high.json @@ -0,0 +1,15 @@ +{ + "key": "claude_code_full-oauth|2.1.267|0399c793ff571d59|claude-opus-5-5|high", + "fingerprint_sha256": "06d6245468d20e3550a7ea4b8b4e7d9eda296ae16915dffa1b5bd7d12066efa6", + "written": "2026-10-20 02:16:17", + "summary": { + "system_chars": 6048, + "tools": [ + "mcp__lff__robot", + "mcp__lff__shell", + "mcp__lff__view_images" + ], + "effort_in_request": "high", + "model_in_request": "claude-opus-5-5" + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/__init__.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/l2_restore_layout.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/l2_restore_layout.py new file mode 100644 index 0000000000000000000000000000000000000000..d926c362024dece29de84cdc1074180f7b196ceb --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/l2_restore_layout.py @@ -0,0 +1,502 @@ +"""L2-B restore_layout: put the ketchup into the basket; every other item must stay exactly where it was. + +Scene: the ketchup (upright) and three flat boxes (cream cheese, butter, chocolate pudding) stand on the bare +table in an irregular layout (random positions and yaws, no tray, no markers, no grid), the basket on the +robot's left. Nothing in the scene marks where an item "belongs": its original pose exists only in the +first frame. + +Constructed L2 event (physical, continuous): the first time the ketchup is grasped and lifted 3 cm, the +neighbouring box (the "victim", a hidden variable) is knocked: it receives a velocity impulse away from the +ketchup (+-35 deg) and a spin, slides 9-14 cm over the table and comes to rest turned by 45-80 deg. It is +real MuJoCo motion over ~0.2 s (no teleport), so a video shows it sliding away. The main task itself still +succeeds; an agent that stops after it fails. To repair the side effect the agent has to put the victim +back where it was -- within 3 cm and 25 deg (mod 180, the boxes are symmetric) -- and that pose is only in +its memory of the start of the episode (the F2 text says *which* item is out of place, never where it was). + +Protocol: within (one episode, no reset). Attempt 1 = the main task, every later attempt = one corrective +round chosen by the policy; the outcome (success + F2 text) is computed after each round. + +Scripted references + oracle knows the victim: right after the main task it puts the victim back at its saved start pose. + naive main task, then done. + adaptive saves the start layout from the first frame (Save); after a failure reads from F2 which items are + out of place (Retrieve their saved poses) and puts them back (Utilize). + blind no history, no feedback: every later round redoes the main task (lifts the ketchup out of the + basket and puts it back, grasp jittered by 5 mm), like l2_knock_restore's blind. + nomem (extra control, not in the acceptance table) gets the F2 text but has no start frame: it knows + which box is out of place and guesses where to put it (random free spot within 15 cm, random yaw). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..task_base import LFFTask, register_task + +TARGET = "ketchup_1" +BOXES = ("cream_cheese_1", "butter_1", "chocolate_pudding_1") +BASKET = "basket_1" +ITEMS = (TARGET,) + BOXES + +# LIBERO basket (body frame = world frame at yaw 0), measured by the l2_knock_restore developer +BASKET_IN = 0.060 # half size of the inner floor +BASKET_RIM = 0.150 # rim height above the basket's lowest point +BASKET_FLOOR = 0.017 # floor top above the basket's lowest point +BASKET_OUT = 0.11 # conservative half size of the outer footprint (keep-out radius for the layout) + +POS_TOL = 0.03 # success: box centre within 3 cm of its start +YAW_TOL = np.radians(25.0) # ... and long axis within 25 deg of its start (mod 180) +STILL_TOL = 0.02 # the knock only fires if the victim is still within 2 cm of its start + +REGION = (-0.26, 0.06, -0.27, 0.10) # x0, x1, y0, y1 (world) for item centres +KNOCK_REGION = (-0.28, 0.08, -0.29, 0.12) # where the victim may come to rest +MAX_REACH = 0.70 # max horizontal distance of an item centre from the robot base +BASE_X = -0.66 +R_BOX, R_KETCHUP = 0.046, 0.034 # footprint circumradii (boxes 8 x 4.3 cm; ketchup 5.7 x 3.7 cm) +GAP = 0.03 # free space between footprints (finger room) +SLIDE_K = 0.0522 # measured: slide distance [m] = SLIDE_K * v0^2 [m/s] for these boxes on the table +SPIN_W = 40.0 # rad/s, applied each control step until the target turn is reached + +NAMES = {"ketchup_1": "ketchup", "cream_cheese_1": "cream cheese", "butter_1": "butter", + "chocolate_pudding_1": "chocolate pudding", BASKET: "basket"} +DESCR = {"ketchup_1": "red bottle", "cream_cheese_1": "blue box", "butter_1": "small orange box", + "chocolate_pudding_1": "brown box", BASKET: "wicker basket"} + + +def _qz(a): + return np.array([np.cos(a / 2), 0.0, 0.0, np.sin(a / 2)]) + + +def _wrap_half(a): + """wrap an angle to [-pi/2, pi/2) (boxes and parallel grippers are symmetric under 180 deg)""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def _seg_dist(p, a, b): + """distance from point p to segment a-b (2D)""" + p, a, b = (np.asarray(v, float) for v in (p, a, b)) + ab = b - a + t = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0.0, 1.0) + return float(np.linalg.norm(p - (a + t * ab))) + + +def _in_rect(xy, r): + return r[0] <= xy[0] <= r[1] and r[2] <= xy[1] <= r[3] + + +def _reach_ok(xy): + return np.hypot(xy[0] - BASE_X, xy[1]) <= MAX_REACH + + +@register_task +class RestoreLayout(LFFTask): + name = "l2_restore_layout" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Save", "Retrieve", "Utilize") + protocol = "within" + max_attempts = 5 + instruction = ("Put the ketchup into the basket. Every other item on the table must stay exactly where it " + "is now, in the same position and orientation.") + instruction_indirect = ("Put the red bottle into the wicker basket. Every other item on the table must stay " + "exactly where it is now, in the same position and orientation.") + knock_lift = 0.03 # trigger: ketchup grasped and lifted this far above its resting height + + def __init__(self, cam_res=None): + super().__init__(cam_res) + # upright orientations (wxyz), fixed like in l2_knock_restore: the ketchup mesh is modelled lying down; + # basket and boxes are upright in their mesh frame + self.q_up = {n: np.array([1.0, 0.0, 0.0, 0.0]) for n in self.env.objects_dict} + self.q_up[TARGET] = np.array([0.5, 0.5, 0.5, 0.5]) + self._inj = None + self.start = {} + self._home = None + # per-control-step monitor on env.step: also sees attempts driven by the agent harness + orig_step = self.env.step + + def step(action): + ret = orig_step(action) + if self._inj is not None: + self._knock_step() + return ret + + self.env.step = step + + # ------------------------------------------------------------ scene + def make_bddl(self): + names = [*ITEMS, BASKET] + objs = [] + for i, n in enumerate(names): # layout is overridden in apply_instance; regions only need to be valid + x0 = -0.30 + 0.13 * (i % 3) + y0 = -0.25 + 0.25 * (i // 3) + objs.append((n, n[:-2], f"r_{i}", (x0, y0, x0 + 0.02, y0 + 0.02))) + return write_bddl(self.name, self.instruction, objs) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + for _ in range(5000): + basket = np.array([rng.uniform(-0.08, 0.0), rng.uniform(0.25, 0.27)]) + k = np.array([rng.uniform(-0.17, -0.03), rng.uniform(-0.14, -0.02)]) + victim = str(rng.choice(BOXES)) + others = [b for b in BOXES if b != victim] + a_v = rng.uniform(0, 2 * np.pi) + r_v = rng.uniform(R_BOX + R_KETCHUP + GAP, R_BOX + R_KETCHUP + GAP + 0.02) + pos = {TARGET: k, victim: k + r_v * np.array([np.cos(a_v), np.sin(a_v)])} + ok = _in_rect(pos[victim], REGION) and _reach_ok(pos[victim]) + for o in others: + if not ok: + break + for _ in range(200): + p = np.array([rng.uniform(*REGION[:2]), rng.uniform(*REGION[2:])]) + if not _reach_ok(p): + continue + if np.linalg.norm(p - k) < R_BOX + R_KETCHUP + GAP: + continue + if any(np.linalg.norm(p - pos[q]) < 2 * R_BOX + GAP for q in pos if q != TARGET): + continue + pos[o] = p + break + else: + ok = False + if not ok: + continue + if any(np.linalg.norm(pos[n] - basket) < BASKET_OUT + R_BOX + 0.02 for n in ITEMS): + continue + # the knock: away from the ketchup +-35 deg, 9-14 cm, turn 45-80 deg (random sign) + ang = a_v + rng.uniform(-np.radians(35), np.radians(35)) + dist = rng.uniform(0.09, 0.14) + u = np.array([np.cos(ang), np.sin(ang)]) + end = pos[victim] + dist * u + if not (_in_rect(end, KNOCK_REGION) and _reach_ok(end)): + continue + if np.linalg.norm(end - basket) < BASKET_OUT + R_BOX + 0.03: + continue + # the path and the resting spot keep clear of the other boxes (finger room around the victim too) + if any(_seg_dist(pos[o], pos[victim], end) < 2 * R_BOX + 0.01 for o in others): + continue + if any(np.linalg.norm(end - pos[o]) < 2 * R_BOX + GAP for o in others): + continue + if np.linalg.norm(end - k) < R_BOX + R_KETCHUP + GAP: + continue + turn = float(rng.choice([-1, 1]) * rng.uniform(np.radians(45), np.radians(80))) + return dict(seed=int(seed), + basket_xy=basket.round(4).tolist(), + xy={n: pos[n].round(4).tolist() for n in ITEMS}, + yaw={**{b: float(rng.uniform(-np.pi / 2, np.pi / 2)) for b in BOXES}, + TARGET: float(np.pi / 2 + rng.uniform(-0.3, 0.3))}, + # hidden variables of the injected failure + victim=victim, knock_dir=float(ang), knock_dist=float(dist), knock_turn=turn, + knock_end=end.round(4).tolist()) + raise RuntimeError("could not sample a layout") + + def place(self, name, xy, yaw, surface_z=envs.TABLE_Z): + """Teleport an object upright (yaw about world z) with its lowest point 2 mm above surface_z (reset only).""" + q = envs._quat_mul(_qz(yaw), self.q_up[name]) + envs.set_obj_pose(self.env, name, [xy[0], xy[1], surface_z + 0.3], quat_wxyz=q) + self.env.sim.forward() + dz = envs.obj_min_z(self.env, name) - (surface_z + 0.002) + qa, _ = envs.free_joint_addr(self.env, name) + self.env.sim.data.qpos[qa + 2] -= dz + self.env.sim.forward() + + def apply_instance(self, inst): + envs.scale_mass(self.env, BASKET, 2.0) # heavy enough not to be dragged by the gripper (as in l2_knock) + self.place(BASKET, inst["basket_xy"], 0.0) + for n in ITEMS: + self.place(n, inst["xy"][n], inst["yaw"][n]) + self.env.sim.forward() + + def reset_instance(self, inst, recorder=None): + self._inj = None + sk = super().reset_instance(inst, recorder) + self.start = {n: self.footprint(n) for n in ITEMS} + self._inj = dict(inst=inst, done=False, knocked=False, step=None, spin_left=0.0, spin_steps=0) + self._home = sk.eef_pos() + return sk + + # ------------------------------------------------------------ measurements + def footprint(self, name): + """Measured pose summary: AABB centre, yaw of the long horizontal axis, half sizes, z range. + Scripted policies use it as a stand-in for perception.""" + m, d = self.env.sim.model, self.env.sim.data + lo, hi = np.full(3, np.inf), np.full(3, -np.inf) + best = None + for g in envs.obj_geom_ids(self.env, name): + R = d.geom_xmat[g].reshape(3, 3) + c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3] + e = np.abs(R) @ m.geom_aabb[g, 3:] + lo, hi = np.minimum(lo, c - e), np.maximum(hi, c + e) + vol = float(np.prod(m.geom_aabb[g, 3:])) + if best is None or vol > best[0]: + best = (vol, R, m.geom_aabb[g, 3:]) + _, R, half = best + horiz = sorted([(half[k], R[:, k]) for k in range(3) if abs(R[2, k]) < 0.5], key=lambda t: -t[0]) + ax = horiz[0][1] if horiz else np.array([1.0, 0.0, 0.0]) + return dict(center=[float(v) for v in (lo + hi) / 2], yaw=float(np.arctan2(ax[1], ax[0])), + half_xy=[float(v) for v in ((hi - lo) / 2)[:2]], zmin=float(lo[2]), zmax=float(hi[2])) + + def body_yaw(self, name): + R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3) + return float(np.arctan2(R[1, 0], R[0, 0])) + + # ------------------------------------------------------------ failure injection (physical knock) + def _knock_step(self): + st = self._inj + if st["done"]: + if st["spin_steps"] > 0: # keep spinning until the target turn is reached (<= 6 control steps) + self._spin(st) + return + if self.sk is None: + return + if envs.obj_min_z(self.env, TARGET) < self.start[TARGET]["zmin"] + self.knock_lift: + return + if not self.sk.holding(TARGET): + return + st["done"] = True + inst = st["inst"] + v = inst["victim"] + if np.linalg.norm(np.array(self.footprint(v)["center"][:2]) - np.array(self.start[v]["center"][:2])) > STILL_TOL: + return # the victim was moved beforehand: nothing happens + qa, da = envs.free_joint_addr(self.env, v) + v0 = np.sqrt(inst["knock_dist"] / SLIDE_K) + dvec = np.array([np.cos(inst["knock_dir"]), np.sin(inst["knock_dir"])]) + d = self.env.sim.data + d.qvel[da:da + 3] = [v0 * dvec[0], v0 * dvec[1], 0.0] + st.update(knocked=True, step=int(self.sk.n_steps), yaw0=self.body_yaw(v), spin_left=inst["knock_turn"], + spin_steps=6) + self._spin(st) + + def _spin(self, st): + v = st["inst"]["victim"] + _, da = envs.free_joint_addr(self.env, v) + turned = _wrap_half(self.body_yaw(v) - st["yaw0"]) if abs(st["spin_left"]) < np.pi / 2 else 0.0 + rest = st["spin_left"] - turned + st["spin_steps"] -= 1 + if abs(rest) < np.radians(4) or np.sign(rest) != np.sign(st["spin_left"]): + st["spin_steps"] = 0 + return + # measured: one control step at w rad/s turns these boxes by ~0.35-0.8 deg per rad/s; aim a bit short + w = float(np.clip(np.degrees(abs(rest)) / 0.6, 5.0, SPIN_W)) + self.env.sim.data.qvel[da + 5] = np.sign(rest) * w + + # ------------------------------------------------------------ outcome + def where_target(self): + """'basket', 'gripper', 'table' or 'other' for the ketchup.""" + f = self.footprint(TARGET) + c = np.array(f["center"]) + if self.sk is not None and self.sk.holding(TARGET) and f["zmin"] > envs.TABLE_Z + 0.02: + return "gripper", f + bp = envs.obj_pos(self.env, BASKET) + if np.all(np.abs(c[:2] - bp[:2]) <= BASKET_IN + 0.01) and f["zmin"] < envs.obj_min_z(self.env, BASKET) + BASKET_RIM: + return "basket", f + if f["zmin"] < envs.TABLE_Z + 0.01: + return "table", f + return "other", f + + def box_state(self, name): + """Pose error of a box w.r.t. its start pose and where it is.""" + f = self.footprint(name) + s = self.start[name] + c, c0 = np.array(f["center"][:2]), np.array(s["center"][:2]) + dpos = float(np.linalg.norm(c - c0)) + dyaw = _wrap_half(f["yaw"] - s["yaw"]) + held = bool(self.sk is not None and self.sk.holding(name)) + upright = envs.obj_upright_cos(self.env, name) > 0.9 + on_table = f["zmin"] < envs.TABLE_Z + 0.01 + bp = envs.obj_pos(self.env, BASKET) + loc = ("gripper" if held else + "basket" if np.all(np.abs(c - bp[:2]) <= BASKET_IN + 0.02) and not on_table else + "table" if on_table and upright else + "table_tipped" if on_table else "other") + ok = bool(loc == "table" and dpos <= POS_TOL and abs(dyaw) <= YAW_TOL) + return dict(ok=ok, loc=loc, dpos=dpos, dyaw=float(dyaw), center=f["center"], yaw=f["yaw"], + offset=(c - c0).tolist()) + + @staticmethod + def _offset_words(off, dyaw): + """robot-centric words for a displacement (current - start) and turn (for the offset tier only)""" + parts = [] + if abs(off[0]) >= 0.005: + parts.append(f"{100 * abs(off[0]):.0f} cm {'forward' if off[0] > 0 else 'backward'}") + if abs(off[1]) >= 0.005: + parts.append(f"{100 * abs(off[1]):.0f} cm to the {'left' if off[1] > 0 else 'right'}") + s = (" and ".join(parts) + " of its starting spot") if parts else "at its starting spot" + if abs(dyaw) >= np.radians(3): + s += f", turned {abs(np.degrees(dyaw)):.0f} deg {'counter-clockwise' if dyaw > 0 else 'clockwise'} (seen from above)" + return s + + def _describe(self, tloc, boxes, names, offset=False): + tn = names[TARGET] + msgs = [] + if tloc != "basket": + msgs.append({"gripper": f"The {tn} is still in the gripper, not in the basket.", + "table": f"The {tn} is on the table, not in the basket."} + .get(tloc, f"The {tn} is not in the basket.")) + for n in BOXES: + b = boxes[n] + if b["ok"]: + continue + if b["loc"] == "gripper": + msgs.append(f"The {names[n]} is in the gripper; it must be back where it was at the start.") + continue + if b["loc"] == "basket": + msgs.append(f"The {names[n]} is in the basket; it must be back where it was at the start.") + continue + if b["loc"] == "table_tipped": + msgs.append(f"The {names[n]} has tipped over and is not where it was at the start.") + continue + if b["loc"] != "table": + msgs.append(f"The {names[n]} is not where it was at the start.") + continue + what = [] + if b["dpos"] > POS_TOL: + what.append("position") + if abs(b["dyaw"]) > YAW_TOL: + what.append("orientation") + m = f"The {names[n]} is not where it was at the start ({' and '.join(what)} changed)." + if offset: + m += f" It is {self._offset_words(b['offset'], b['dyaw'])}." + msgs.append(m) + if not msgs: + msgs.append(f"The {tn} is in the basket and every other item is where it was at the start.") + return " ".join(msgs) + + def outcome(self, inst): + envs.settle(self.env, 30) + tloc, tf = self.where_target() + boxes = {n: self.box_state(n) for n in BOXES} + moved = [n for n in BOXES if not boxes[n]["ok"]] + success = bool(tloc == "basket" and not moved) + return dict(success=success, target_loc=tloc, moved=moved, + boxes={n: dict(ok=b["ok"], loc=b["loc"], dpos=round(b["dpos"], 4), + dyaw_deg=round(float(np.degrees(b["dyaw"])), 1)) for n, b in boxes.items()}, + knocked=bool(self._inj and self._inj["knocked"]), + detail=self._describe(tloc, boxes, NAMES), + detail_indirect=self._describe(tloc, boxes, DESCR), + detail_offset=self._describe(tloc, boxes, NAMES, offset=True)) + + def feedback(self, inst, out, level="F2", indirect=False, offset=False): + """F0: nothing, F1: success flag, F2: which item is out of place (never where it was). + offset=True (ablation tier 'F2+offset'): also the displacement from the start pose in robot-centric + words -- this externalises the memory and is not the default.""" + if level == "F2": + key = "detail_offset" if offset else ("detail_indirect" if indirect else "detail") + out = dict(out, detail=out.get(key, out["detail"])) + return super().feedback(inst, out, level) + + # ------------------------------------------------------------ scripted motions (Skills.move_to / set_gripper only) + def go_home(self): + """End of an attempt: lift the arm out of the camera's way.""" + sk = self.sk + p = sk.eef_pos() + sk.move_to([p[0], p[1], max(p[2], self._home[2])]) + sk.move_to(self._home) + + def pick_place(self, name, dest_xy, support_z, dest_yaw=None, carry_z=1.10, clearance=0.006, fp=None, + travel_z=1.15): + """Top-down pick of `name` at its (measured) footprint, carry at eef height `carry_z`, release with the + object bottom `clearance` above `support_z` at dest_xy; `dest_yaw` = desired yaw of the long axis.""" + sk = self.sk + f = fp or self.footprint(name) + c = np.array(f["center"]) + h = f["zmax"] - f["zmin"] + gyaw = _wrap_half(f["yaw"]) # fingers close along eef y (= world y at yaw 0): across the short side + if name == TARGET: + zg = f["zmax"] - 0.035 + else: + zg = max(f["zmin"] + 0.5 * h, f["zmin"] + 0.0145) # finger tips reach ~1.3 cm below the grip site + sk.set_gripper(False, steps=6) + p = sk.eef_pos() + if p[2] < travel_z - 0.02: + sk.move_to([p[0], p[1], travel_z]) + sk.move_to([c[0], c[1], travel_z], yaw=gyaw) + sk.move_to([c[0], c[1], f["zmax"] + 0.03], speed=0.4) + sk.move_to([c[0], c[1], zg], tol=0.003, max_steps=80) + sk.set_gripper(True, steps=12) + sk.move_to([c[0], c[1], carry_z], speed=0.3) + gyaw2 = gyaw if dest_yaw is None else gyaw + _wrap_half(dest_yaw - f["yaw"]) + sk.move_to([dest_xy[0], dest_xy[1], carry_z], yaw=gyaw2) + sk.move_to([dest_xy[0], dest_xy[1], support_z + (zg - f["zmin"]) + clearance], tol=0.003, speed=0.2, + max_steps=150) + sk.hold(4) + sk.set_gripper(False, steps=10) + sk.move_to([dest_xy[0], dest_xy[1], travel_z], speed=0.4) + + def main_task(self, fp=None): + """Ketchup -> basket (the instruction, as an agent without failure knowledge would do it).""" + b = envs.obj_pos(self.env, BASKET) + floor = envs.obj_min_z(self.env, BASKET) + BASKET_FLOOR + self.pick_place(TARGET, b[:2], floor, carry_z=1.27, clearance=0.006, fp=fp) + + def restore(self, name, pose): + """Put box `name` back at `pose` (a remembered footprint: centre xy + long-axis yaw).""" + self.pick_place(name, pose["center"][:2], envs.TABLE_Z, dest_yaw=pose["yaw"], carry_z=1.05, + clearance=0.004) + + def do(self, actions, inst): + for act in actions: + if act[0] == "ketchup_to_basket": + self.main_task(fp=act[1] if len(act) > 1 else None) + elif act[0] == "restore": # ["restore", name, pose] + self.restore(act[1], act[2]) + else: + raise ValueError(act) + + # ------------------------------------------------------------ scripted reference policies + def _guess_pose(self, name, rng): + """nomem control: a random free spot within 15 cm of where the box is now, random yaw.""" + cur = np.array(self.footprint(name)["center"][:2]) + others = [np.array(self.footprint(o)["center"][:2]) for o in BOXES if o != name] + for _ in range(200): + r, a = rng.uniform(0.03, 0.15), rng.uniform(0, 2 * np.pi) + p = cur + r * np.array([np.cos(a), np.sin(a)]) + if _in_rect(p, KNOCK_REGION) and _reach_ok(p) and all(np.linalg.norm(p - o) > 2 * R_BOX + 0.01 for o in others): + return dict(center=[float(p[0]), float(p[1]), 0.0], yaw=float(rng.uniform(-np.pi / 2, np.pi / 2))) + return dict(center=[float(cur[0]), float(cur[1]), 0.0], yaw=float(rng.uniform(-np.pi / 2, np.pi / 2))) + + def _plan(self, kind, inst, a, history, rng, memory): + """Actions of one round: ["ketchup_to_basket"] / ["restore", name, pose].""" + if kind == "naive" or (a == 0 and kind in ("adaptive", "blind", "nomem")): + return [["ketchup_to_basket"]] + if kind == "oracle": # knows the victim: restores it right after the main task (start pose from memory) + return [["ketchup_to_basket"], ["restore", inst["victim"], memory[inst["victim"]]]] + last = history[-1]["outcome"] + if kind == "adaptive": # F2 says which items are out of place; the saved first frame says where they were + acts = [] if last["target_loc"] == "basket" else [["ketchup_to_basket"]] + return acts + [["restore", n, memory[n]] for n in last["moved"]] + if kind == "nomem": # F2 but no start frame: guesses + acts = [] if last["target_loc"] == "basket" else [["ketchup_to_basket"]] + return acts + [["restore", n, self._guess_pose(n, rng)] for n in last["moved"]] + if kind == "blind": # ignores the outcome: redoes the main task (ketchup wherever it is now, jittered grasp) + fp = self.footprint(TARGET) + fp["center"] = (np.array(fp["center"]) + np.r_[rng.normal(0, 0.005, 2), 0.0]).tolist() + return [["ketchup_to_basket", fp]] + raise ValueError(kind) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """Within-episode protocol: one reset, attempt 1 = main task, attempts 2..k = corrective rounds.""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + self.reset_instance(inst) + memory = {n: dict(center=self.start[n]["center"], yaw=self.start[n]["yaw"]) for n in BOXES} # Save + for a in range(k): + actions = self._plan(kind, inst, a, history, rng, memory) + self.do(actions, inst) + self.go_home() + out = self.outcome(inst) + params = dict(actions=[x[:1] if x[0] == "ketchup_to_basket" else + [x[0], x[1], [round(v, 3) for v in x[2]["center"][:2]], round(float(x[2]["yaw"]), 3)] + for x in actions]) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history + + # cross-protocol hooks are not used by this task + def default_params(self, inst): + return dict(policy="naive") + + def oracle_params(self, inst): + return dict(policy="oracle") diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/l6_count.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/l6_count.py new file mode 100644 index 0000000000000000000000000000000000000000..8bfcc8725cbfb523898ced10b2974c65b5b3b82f --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/l6_count.py @@ -0,0 +1,562 @@ +"""L6-B count_into_box: put exactly N identical cubes into an opaque drop box; one carry is interrupted by a slip. + +Scene: T identical orange 4 cm cubes scattered on the table and a dark, closed drop box (static fixture) at +one side of the table. The box lid has a square opening on the robot side; a cube released above it falls in, +lands on a low-friction ramp and slides under the closed part of the lid, where no camera can see it (once past +the opening it is moved to a storage slot at the far end, so that cubes never queue back under the opening). +Cubes cannot be taken back out. + +Instruction: put exactly N cubes into the box (N in {4, 5}, given in the instruction). + +Interruption: during the (p+1)-th carry (p cubes are already in the box, p in {1..N-1}, hidden) the carried +cube "slips": the gripper opens and the cube lands back on the table next to the spot it was picked from. The +number of cubes left on the table is R = N + e with e in {0, 1} drawn independently of p (T = R + p), so +neither the box nor the table tells how many cubes are inside: progress ("how many have I put in already") +is only in the agent's own history. Over-filling is irreversible (terminal failure); under-filling can be +completed in a later segment. + +Protocol: within (one episode, no reset), like l6_swap_interrupt. An attempt (segment) ends when the agent +declares done; the outcome is measured; if the box holds fewer than N cubes the agent continues from the +current state. The slip is injected once per episode, inside attempt 1, by a per-control-step monitor (so it +also fires for agents driven by the harness). Events reported immediately (`drain_events`): "A cube dropped +into the box." after every cube that falls in, and the slip. + +Scripted references (perception = simulator state, as in l6_swap): + oracle privileged box count: carries cubes until the box holds N. + adaptive counts its own successful drops (Save), notices the slip (the cube is back on the table, the + drop count is unchanged), carries cubes until its count reaches N (Retrieve + Utilize). Later + segments: if F2 says the box holds fewer than N, adds one cube per segment. + naive memoryless continuation (1 attempt): loses its count at the slip; re-plans from the current frame, + which shows no progress, so it guesses how many cubes are already inside (uniform over 0..N-1) + and adds the rest. + blind memoryless restart (k attempts): at the slip it does not know where it was and starts over + ("the box must get N cubes"), every later segment again puts N cubes in (repeated steps). +Extra controls (not in the acceptance table): `skip` (counts carries instead of drops, i.e. counts the +slipped carry; with memory + F2 it adds the missing cube in segment 2) and `inc1` (stateless, adds one cube +per segment; shows that the within protocol's stop-at-first-success leaks progress to such a policy). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, box_xml, register_generated +from ..task_base import LFFTask, register_task + +CUBE_HALF = 0.02 +CUBE_RGBA = (0.95, 0.50, 0.10, 1.0) +N_CUBES = 11 # objects declared in the BDDL; unused ones are parked on the floor out of view +LETTERS = "ABCDEFGHIJK" +CUBES = [f"cube_{i + 1}" for i in range(N_CUBES)] + +# drop box (local frame: origin at the centre of the footprint on the table top, +x away from the robot) +WALL_T = 0.008 +IN_HX, IN_HY = 0.100, 0.110 # inner half sizes +LID_Z = 0.095 # underside of the lid above the table +LID_T = 0.008 +HOLE_X = (-0.090, -0.020) # opening in the lid (local x range), on the robot side +HOLE_HY = 0.035 +RAMP_Z = (0.045, 0.006) # top surface of the ramp at the near (-x) and far (+x) inner walls +RAMP_T = 0.006 +RAMP_MU = 0.03 +BOX_RGBA = (0.30, 0.20, 0.13, 1.0) +INNER_RGBA = (0.08, 0.07, 0.06, 1.0) +HOLE_C = np.array([(HOLE_X[0] + HOLE_X[1]) / 2, 0.0]) +OUT_HX, OUT_HY = IN_HX + WALL_T, IN_HY + WALL_T +RAMP_SLOPE = (RAMP_Z[0] - RAMP_Z[1]) / (2 * IN_HX) +RAMP_TH = float(np.arctan(RAMP_SLOPE)) +# Storage slots under the closed part of the lid. A cube that has slid past the opening is moved to the next free +# slot (out of every camera's view) so that the cubes do not queue up along the slide line back under the opening. +# Order: the lane straight behind the opening (y = 0) is filled last, so that a newly dropped cube can always slide +# past the opening before it is moved; then a second layer on the far row. (x, y, layer) +_ROW = [IN_HX - CUBE_HALF - 0.002 - 0.044 * r for r in range(2)] +SLOTS = ([(_ROW[r], y, 0) for r in range(2) for y in (-0.088, 0.088, -0.044, 0.044)] + + [(_ROW[0], 0.0, 0), (_ROW[1], 0.0, 0)] + [(_ROW[0], y, 1) for y in (-0.088, 0.088, -0.044, 0.044, 0.0)]) + +BASE_X = -0.66 +REACH = 0.70 # max horizontal distance of a cube from the robot base +CUBE_REGION = (-0.30, 0.07, -0.28, 0.28) +CUBE_MIN_DIST = 0.085 +BOX_CLEAR = 0.12 # cube centre at least this far from the box footprint (the hand must not hit the lid) +Z_GRASP = envs.TABLE_Z + CUBE_HALF +Z_CARRY = envs.TABLE_Z + 0.20 +Z_RELEASE = envs.TABLE_Z + LID_Z + LID_T + 0.012 + CUBE_HALF # cube bottom ~1.2 cm above the lid +PARK = [(-0.5 + 0.1 * i, 1.25) for i in range(N_CUBES)] +LIFTED = 0.05 # slip trigger: cube at least this far above its resting height +HAND_HALF = 0.11 # the Panda hand reaches about this far along the closing axis (it hits 4 cm cubes there) +HAND_CLEAR = 0.06 # neighbour centre at least this far from that segment for a collision-free grasp + + +def hand_box_clear(p, a, box, half=HAND_HALF): + """Smallest distance from the hand segment (closing axis at yaw a) to the drop box footprint.""" + ax = np.array([-np.sin(a), np.cos(a)]) + return min(float(np.linalg.norm(np.maximum(np.abs(np.asarray(p) + t * ax - box) - [OUT_HX, OUT_HY], 0.0))) + for t in np.linspace(-half, half, 9)) + + +def axis_clear(p, a, others, half=HAND_HALF): + """Smallest distance from a neighbour centre to the hand segment p +- half * (closing axis at yaw a).""" + ax = np.array([-np.sin(a), np.cos(a)]) + best = 1.0 + for o in others: + v = np.asarray(o) - p + t = float(np.clip(v @ ax, -half, half)) + best = min(best, float(np.linalg.norm(v - t * ax))) + return best + + +def drop_box_xml(model_name): + """Closed box with a square opening in the lid and an internal ramp (static fixture, collisions on).""" + parts = [] # (pos, half size, rgba, quat or None, friction or None) + H = LID_Z / 2 + # walls + parts.append(((IN_HX + WALL_T / 2, 0, H), (WALL_T / 2, OUT_HY, H), BOX_RGBA)) + parts.append(((-IN_HX - WALL_T / 2, 0, H), (WALL_T / 2, OUT_HY, H), BOX_RGBA)) + parts.append(((0, IN_HY + WALL_T / 2, H), (IN_HX, WALL_T / 2, H), BOX_RGBA)) + parts.append(((0, -IN_HY - WALL_T / 2, H), (IN_HX, WALL_T / 2, H), BOX_RGBA)) + # lid around the opening + zc = LID_Z + LID_T / 2 + x0, x1 = HOLE_X + parts.append((((-OUT_HX + x0) / 2, 0, zc), ((x0 + OUT_HX) / 2, OUT_HY, LID_T / 2), BOX_RGBA)) # near strip + parts.append((((x1 + OUT_HX) / 2, 0, zc), ((OUT_HX - x1) / 2, OUT_HY, LID_T / 2), BOX_RGBA)) # far part + for s in (-1, 1): + parts.append((((x0 + x1) / 2, s * (HOLE_HY + OUT_HY) / 2, zc), ((x1 - x0) / 2, (OUT_HY - HOLE_HY) / 2, + LID_T / 2), BOX_RGBA)) + # floor (dark) and ramp + parts.append(((0, 0, 0.002), (IN_HX, IN_HY, 0.002), INNER_RGBA)) + dz = RAMP_Z[0] - RAMP_Z[1] + th = float(np.arctan2(dz, 2 * IN_HX)) + L = float(np.hypot(dz, 2 * IN_HX)) / 2 + zmid = (RAMP_Z[0] + RAMP_Z[1]) / 2 - RAMP_T / 2 / np.cos(th) + ramp = ((0, 0, zmid), (L, IN_HY - 0.001, RAMP_T / 2), INNER_RGBA, (np.cos(th / 2), 0, np.sin(th / 2), 0), RAMP_MU) + geoms = [] + for k, p in enumerate(parts + [ramp]): + pos, half, rgba = p[:3] + quat = p[3] if len(p) > 3 else None + mu = p[4] if len(p) > 4 else None + q = f' quat="{_fmt(quat)}"' if quat is not None else "" + fr = f' friction="{mu} 0.005 0.0001" priority="2"' if mu is not None else ' friction="1.0 0.005 0.0001"' + geoms.append(f' ') + geoms.append(f' ') + return _wrap(model_name, "\n".join(geoms), (LID_Z + LID_T) / 2, float(np.hypot(OUT_HX, OUT_HY))) + + +def _wrap_q(a): + """cubes are symmetric under 90 deg rotations: wrap to [-pi/4, pi/4)""" + return float((a + np.pi / 4) % (np.pi / 2) - np.pi / 4) + + +@register_task +class CountIntoBox(LFFTask): + name = "l6_count_into_box" + level = "L6" + category = "procedural_memory" + capabilities = ("Perceive", "Save", "Retrieve", "Utilize") + protocol = "within" + agent_max_steps = 80 # robot commands per attempt for agents (a VLM needs ~40-55) + max_attempts = 5 + _TEMPLATE = ("Put exactly {n} of the orange cubes into the dark box, through the opening in its lid. " + "Cubes cannot be taken back out of the box.") + _TEMPLATE_INDIRECT = ("Drop exactly {n} of the small orange blocks into the closed brown container through the " + "square hole in its top. Blocks cannot be taken back out of the container.") + instruction = _TEMPLATE.format(n="N") # replaced per instance (sample_instance / agent_instruction) + instruction_indirect = _TEMPLATE_INDIRECT.format(n="N") + inject = True + announce_drops = True # False: no "A cube dropped into the box." event (harder variant, counting from images) + agent_object_names = ["orange cube (several identical)", "drop box"] + + WORDS = {3: "three", 4: "four", 5: "five", 6: "six"} + + def agent_instruction(self, inst, variant="direct"): + t = self._TEMPLATE_INDIRECT if variant == "indirect" else self._TEMPLATE + return t.format(n=self.WORDS[inst["n_target"]]) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + self._mon = False + orig_step = self.env.step + + def step(action): # per-control-step monitor: also sees attempts driven by the agent harness + ret = orig_step(action) + if self._mon: + self._monitor() + return ret + + self.env.step = step + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs = [] + for i, L in enumerate(LETTERS[:N_CUBES]): + cat = register_generated(f"LffCountCube{L}", box_xml(f"lff_count_cube_{L.lower()}", (CUBE_HALF,) * 3, + CUBE_RGBA, density=600)) + gx, gy = -0.30 + 0.15 * (i % 4), -0.40 + 0.2 * (i // 4) + objs.append((CUBES[i], cat, f"c{i + 1}_region", (gx - 0.01, gy - 0.01, gx + 0.01, gy + 0.01))) + box = register_generated("LffDropBox", drop_box_xml("lff_drop_box"), free=False) + fx = [("drop_box_1", box, "box_region", (0.19, 0.39, 0.21, 0.41))] + return write_bddl(self.name, self._TEMPLATE.format(n="N"), objs, fx) + + def _box_body(self): + return self.env.sim.model.body_name2id(self.env.fixtures_dict["drop_box_1"].root_body) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + n = int(rng.choice([4, 5])) + p = int(rng.integers(1, n)) # cubes already inside when the slip happens + e = int(rng.integers(0, 2)) + T = n + e + p + for _ in range(500): + side = int(rng.choice([-1, 1])) + box = np.array([rng.uniform(-0.08, -0.02), side * rng.uniform(0.22, 0.25)]) + P = np.column_stack([rng.uniform(*CUBE_REGION[:2], 800), rng.uniform(*CUBE_REGION[2:], 800)]) + P = P[np.hypot(P[:, 0] - BASE_X, P[:, 1]) <= REACH] + P = P[np.linalg.norm(np.maximum(np.abs(P - box) - np.array([OUT_HX, OUT_HY]), 0.0), axis=1) >= BOX_CLEAR] + cubes = [] + for c in P: # random sequential addition + if all(np.linalg.norm(c - q) >= CUBE_MIN_DIST for q in cubes): + cubes.append(c) + if len(cubes) == T: + break + if len(cubes) < T: + continue + yaws = [] # each cube gets a yaw whose (small-rotation) grasp axis is free for the hand + for i in range(T): + oth = [cubes[j] for j in range(T) if j != i] + for _ in range(30): + y = float(rng.uniform(-np.pi / 4, np.pi / 4)) + if axis_clear(cubes[i], y, oth) >= HAND_CLEAR and hand_box_clear(cubes[i], y, box) >= 0.035: + # |y| <= 45 deg: the grasp needs no large wrist rotation + yaws.append(y) + break + else: + break + if len(yaws) == T: + break + else: + raise RuntimeError("could not sample a layout") + inst = dict(seed=int(seed), n_target=n, p=p, e=e, n_cubes=T, box_xy=box.round(4).tolist(), + cubes=np.array(cubes).round(4).tolist(), + yaws=yaws, + trigger_dist=float(rng.uniform(0.05, 0.09)), + slip_r=float(rng.uniform(0.005, 0.02)), slip_ang=float(rng.uniform(0, 2 * np.pi)), + slip_yaw=float(rng.uniform(-np.pi / 4, np.pi / 4))) + # make_video prints task.instruction: keep it in sync with the last sampled instance + self.instruction = self.agent_instruction(inst, "direct") + self.instruction_indirect = self.agent_instruction(inst, "indirect") + return inst + + def apply_instance(self, inst): + m = self.env.sim.model + bid = self._box_body() + m.body_pos[bid] = [inst["box_xy"][0], inst["box_xy"][1], envs.TABLE_Z] + m.body_quat[bid] = [1, 0, 0, 0] + T = inst["n_cubes"] + for i, c in enumerate(CUBES): + if i < T: + envs.set_obj_pose(self.env, c, [*inst["cubes"][i], envs.TABLE_Z + CUBE_HALF + 0.001], + yaw=inst["yaws"][i]) + else: + envs.set_obj_pose(self.env, c, [*PARK[i], CUBE_HALF + 0.001]) + self.env.sim.forward() + self._inst = inst + self.active = CUBES[:T] + self.slip = None + self.events = [] + self._event_cursor = 0 + self._outcome_cursor = 0 + self.in_box = [] # cubes that fell into the box, in order + self.stored = [] # cubes moved to a storage slot + self._bad = set() # scripted policies: cubes whose grasp failed + self.rest_xy = {c: np.array(inst["cubes"][i]) for i, c in enumerate(self.active)} + self._mon = False + + def reset_instance(self, inst, recorder=None): + self._mon = False + sk = super().reset_instance(inst, recorder=recorder) + self._home = sk.eef_pos() + self._mon = True + return sk + + def go_home(self): + p = self.sk.eef_pos() + self.sk.move_to([p[0], p[1], max(p[2], self._home[2])]) + self.sk.move_to(self._home) + + # ------------------------------------------------------------ geometry helpers + def box_local(self, xyz): + b = self._inst["box_xy"] + return np.array([xyz[0] - b[0], xyz[1] - b[1], xyz[2] - envs.TABLE_Z]) + + def hole_world(self): + b = self._inst["box_xy"] + return np.array([b[0] + HOLE_C[0], b[1] + HOLE_C[1]]) + + def inside_box(self, c): + q = self.box_local(envs.obj_pos(self.env, c)) + return bool(abs(q[0]) < IN_HX and abs(q[1]) < IN_HY and q[2] < LID_Z) + + def on_lid(self, c): + q = self.box_local(envs.obj_pos(self.env, c)) + return bool(abs(q[0]) < OUT_HX + 0.01 and abs(q[1]) < OUT_HY + 0.01 and q[2] >= LID_Z) + + def on_table(self, c): + p = envs.obj_pos(self.env, c) + return bool(p[2] < envs.TABLE_Z + CUBE_HALF + 0.01 and not self.inside_box(c)) + + # ------------------------------------------------------------ monitor (every control step) + def _monitor(self): + env = self.env + for c in self.active: + if c in self.in_box: + if c not in self.stored and self.box_local(envs.obj_pos(env, c))[0] > HOLE_X[1] + 0.02: + self._store(c) + continue + p = envs.obj_pos(env, c) + if self.inside_box(c): + self.in_box.append(c) + if self.announce_drops: + self.events.append(dict(step=int(self.sk.n_steps), kind="drop", obj=c, + text="A cube dropped into the box.")) + continue + if p[2] < envs.TABLE_Z + CUBE_HALF + 0.005: # resting on the table: remember where + self.rest_xy[c] = p[:2].copy() + continue + if (self.inject and self.slip is None and p[2] > envs.TABLE_Z + CUBE_HALF + LIFTED + and len(self.in_box) == self._inst["p"] + and np.linalg.norm(p[:2] - self.rest_xy[c]) >= self._inst["trigger_dist"] + and self.sk.holding(c)): + self._do_slip(c) + + def _store(self, c): + sx, sy, layer = SLOTS[min(len(self.stored), len(SLOTS) - 1)] + b = self._inst["box_xy"] + z = RAMP_Z[0] - (sx + IN_HX) * RAMP_SLOPE + CUBE_HALF / np.cos(RAMP_TH) + 0.002 + layer * (2 * CUBE_HALF + 0.003) + envs.set_obj_pose(self.env, c, [b[0] + sx, b[1] + sy, envs.TABLE_Z + z], + quat_wxyz=[np.cos(RAMP_TH / 2), 0.0, np.sin(RAMP_TH / 2), 0.0]) + self.stored.append(c) + + def _do_slip(self, c): + inst = self._inst + src = self.rest_xy[c] + others = [envs.obj_pos(self.env, o)[:2] for o in self.active if o != c and o not in self.in_box] + xy, yaw = src, inst["slip_yaw"] + found = False + for r in (inst["slip_r"], inst["slip_r"] / 2, 0.0): # next to the pick-up spot, still graspable + cand = src + r * np.array([np.cos(inst["slip_ang"]), np.sin(inst["slip_ang"])]) + if not all(np.linalg.norm(cand - o) >= 0.07 for o in others): + continue + for dy in (0.0, 0.3, -0.3, 0.6, -0.6): + y = _wrap_q(inst["slip_yaw"] + dy) + if axis_clear(cand, y, others) >= HAND_CLEAR and \ + hand_box_clear(cand, y, np.asarray(inst["box_xy"])) >= 0.035: + xy, yaw, found = cand, y, True + break + if found: + break + envs.set_obj_pose(self.env, c, [xy[0], xy[1], envs.TABLE_Z + CUBE_HALF + 0.002], yaw=yaw) + self.sk.grip = -1.0 # the gripper opens + self.env.sim.forward() + text = "A cube slipped out of the gripper and fell back onto the table." + self.slip = dict(obj=c, xy=[float(v) for v in xy], from_xy=[float(v) for v in src], step=int(self.sk.n_steps), + in_box=len(self.in_box)) + self.events.append(dict(step=int(self.sk.n_steps), kind="slip", obj=c, text=text)) + + def drain_events(self): + ev = self.events[self._event_cursor:] + self._event_cursor = len(self.events) + return [e["text"] for e in ev] + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + envs.settle(self.env, 20) + n_in = len(self.in_box) + N = inst["n_target"] + held = [c for c in self.active if self.sk.holding(c)] + n_table = sum(self.on_table(c) for c in self.active if c not in self.in_box) + n_lid = sum(self.on_lid(c) for c in self.active if c not in self.in_box) + success = bool(n_in == N and not held) + terminal = bool(n_in > N) + if success: + head = f"The box holds exactly {N} cubes." + elif terminal: + head = (f"The box holds more than {N} cubes. Cubes cannot be taken out of the box, so the task can no " + f"longer be completed.") + elif n_in == N: + head = f"The gripper is still holding a cube." + else: + head = f"The box holds fewer than {N} cubes." + state = f"Now {n_table} cube{'s are' if n_table != 1 else ' is'} on the table" + if n_lid: + state += f" and {n_lid} on the box lid" + state += "." + # F2 = verdict + currently observable state + the slip of this segment (never the number inside) + new = [e for e in self.events[self._outcome_cursor:] if e["kind"] == "slip"] + self._outcome_cursor = len(self.events) + detail = head + " " + state + if new: + detail = "During this attempt: " + " ".join(e["text"] for e in new) + " " + detail + return dict(success=success, terminal=terminal, n_in_box=n_in, n_target=N, n_table=n_table, n_lid=n_lid, + held=len(held), slip=self.slip, detail=detail) + + # ------------------------------------------------------------ motion (scripted policies) + def _grasp_yaw(self, c): + """The cube's grasp axis with the smaller wrist rotation (|yaw| <= 45 deg). Rotations near +-90 deg drive + the Panda wrist into its joint-6 limit at some positions (measured), so the other axis is used only if + the hand would hit a neighbour or the box on this one.""" + R = self.env.sim.data.body_xmat[envs.body_id(self.env, c)].reshape(3, 3) + yaw = _wrap_q(float(np.arctan2(R[1, 0], R[0, 0]))) + p = envs.obj_pos(self.env, c)[:2] + others = [envs.obj_pos(self.env, o)[:2] for o in self.active if o != c and o not in self.in_box] + box = np.asarray(self._inst["box_xy"]) + + def score(a): + return min(axis_clear(p, a, others), hand_box_clear(p, a, box) + 0.03) + if score(yaw) >= HAND_CLEAR: + return yaw + alt = yaw - np.pi / 2 if yaw >= 0 else yaw + np.pi / 2 + return alt if score(alt) > score(yaw) + 0.02 else yaw + + def _pick(self, c): + sk = self.sk + for _ in range(2): + p = envs.obj_pos(self.env, c) + sk.grasp_at(p[:2], Z_GRASP, yaw=self._grasp_yaw(c), lift=0.12) + if sk.holding(c): + return True + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], Z_GRASP + 0.12]) + return False + + def _carry(self, c): + """Pick cube c and release it above the opening. Returns 'in', 'slipped', 'missed' or 'no_grasp'.""" + n_ev = len(self.events) + n_in = len(self.in_box) + if not self._pick(c): + self._bad.add(c) + self.go_home() # un-wind the arm before the next try + return "no_grasp" + h = self.hole_world() + sk = self.sk + sk.move_to([h[0], h[1], Z_CARRY], yaw=0.0) # the slip may fire here; any yaw fits the opening + if any(e["kind"] == "slip" for e in self.events[n_ev:]): + return "slipped" + sk.move_to([h[0], h[1], Z_RELEASE], tol=0.004) + sk.set_gripper(False, steps=12) + sk.move_to([h[0], h[1], Z_CARRY]) + sk.hold(10) + return "in" if len(self.in_box) > n_in else "missed" + + def _next_cube(self): + """nearest table cube to the opening (what any policy sees in the current frame)""" + h = self.hole_world() + cands = [c for c in self.active if c not in self.in_box and (self.on_table(c) or self.on_lid(c))] + cands = [c for c in cands if c not in self._bad] or cands # try another cube after a failed grasp + if not cands: + return None + return min(cands, key=lambda c: np.linalg.norm(envs.obj_pos(self.env, c)[:2] - h)) + + def _add(self, k, log, stop_on_slip=False): + """Carry until k cubes went in (by the policy's own observation of each drop). Returns (added, slipped).""" + added, slipped = 0, False + guard = 0 + while added < k and guard < 3 * k + 3: + guard += 1 + c = self._next_cube() + if c is None: + break + r = self._carry(c) + log.append(r) + if r == "in": + added += 1 + elif r == "slipped": + slipped = True + if stop_on_slip: + break + return added, slipped + + # ------------------------------------------------------------ scripted references (within protocol) + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed + 7919) + self.reset_instance(inst) + N = inst["n_target"] + history = [] + for a in range(k): + log = [] + plan = dict(kind=kind, carries=log) + if a == 0: + if kind == "oracle": + while len(self.in_box) < N and len(log) < 3 * N + 3: # privileged count + c = self._next_cube() + if c is None: + break + log.append(self._carry(c)) + plan["recovery"] = "oracle: privileged box count" + elif kind in ("adaptive", "skip"): + added, slipped = self._add(N, log) if kind == "adaptive" else (0, False) + if kind == "skip": # counts carries, not drops + n_car = 0 + while n_car < N and len(log) < 3 * N: + c = self._next_cube() + if c is None: + break + r = self._carry(c) + log.append(r) + if r in ("in", "slipped"): + n_car += 1 + if r == "in": + added += 1 + plan["recovery"] = "counts carries (the slipped one too)" + else: + plan["recovery"] = "own drop count; the slipped carry is not counted" + else: # memoryless after the slip + added, slipped = self._add(N, log, stop_on_slip=True) + if slipped: + if kind == "naive": + guess = int(rng.integers(0, N)) + plan["recovery"] = f"memoryless: guesses {guess} already inside, adds {N - guess}" + self._add(N - guess, log) + elif kind == "blind": + plan["recovery"] = f"memoryless restart: puts {N} cubes in" + self._add(N, log) + elif kind == "inc1": + plan["recovery"] = "stateless: adds one cube per segment" + self._add(1, log) + else: + raise ValueError(kind) + else: + plan["recovery"] = "none (no slip)" + else: + if kind in ("adaptive", "skip"): + plan["recovery"] = "memory + F2 'fewer than N': add one cube" + self._add(1, log) + elif kind == "blind": + plan["recovery"] = f"memoryless restart: puts {N} cubes in" + self._add(N, log) + elif kind == "inc1": + plan["recovery"] = "stateless: adds one cube" + self._add(1, log) + elif kind == "oracle": + while len(self.in_box) < N and len(log) < 3 * N + 3: + c = self._next_cube() + if c is None: + break + log.append(self._carry(c)) + else: + raise ValueError(kind) + self.go_home() + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=plan, outcome=out)) + if on_attempt: + on_attempt(a, plan, out) + if out["success"] or out["terminal"] or kind in ("oracle", "naive"): + break + return history + + # cross-protocol hooks are not used by this task + def default_params(self, inst): + return dict(policy="naive") + + def oracle_params(self, inst): + return dict(policy="oracle") diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/lh_bystander.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/lh_bystander.py new file mode 100644 index 0000000000000000000000000000000000000000..d29e80c05aadc9cd8aa5e69c81d724f4cd45d971 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/lh_bystander.py @@ -0,0 +1,830 @@ +"""LH bystander: put three cubes into an open box while a tall glass bottle that is not part of the task stands right +in front of the box -- lowering a cube into the box, the robot's own forearm comes down onto the bottle and knocks it +over. + +Family: long-horizon self-disturbance, environment level ("state_restoration"; LIBERO-Recover's damage category L4: the +damaged thing is not part of the task). Three easy pick-and-place stages; the instruction says plainly that nothing +else may be moved and that the bottle must be left standing where it is. The agent has to notice the fallen bottle and +stand it up again on its spot before finishing (within an attempt), or learn to keep its arm off the bottle (across +attempts). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * an open wooden box (fixture): cavity 14 x 14 cm, walls 6 cm high (rim 6.6 cm above the table), 0.8 cm thick; + centre x in [0.00, 0.04], 6-10 cm left or right of the middle; + * three 4 cm cubes (red / yellow / blue, 32 g) in a row beside the box on the other side (19-23 cm from the middle, + from 10 cm behind to 2 cm in front of the box centre, shuffled, yaw +-17 deg), so that a straight carry to the box + never passes over the bottle; + * the bystander: a square green glass bottle with a label and a round red cap, 28.4 cm tall (body 6 x 6 x 18.5 cm, + shoulder, neck, cap; a rounded base whose flat contact is 3.6 x 3.6 cm), 0.25 kg, centre of mass 12 cm up (an empty + bottle: it tips beyond 8.5 deg; pressed down on its cap, beyond 3.7 deg). + +Instance variable (where the bottle stands): "hazard" (15 of every 20 consecutive seeds): right in front of the box, +between the box and the robot, 1.0-2.5 cm from its front wall, 1 cm right to 4 cm left of its centre line; "benign": +beside the box on its outer side, 8-11 cm from the wall. Both look like "a bottle standing next to the box"; nothing in +the physics is hidden. What the agent cannot see before acting is its own arm: the wrist camera shows the fingers, not +the forearm, and the agent steers the grasp point. + +Disturbance (physics, no teleport): lowering a cube onto the box floor (grasp point ~4 cm above the table), the +fingers and the cube stay 3-5 cm clear of the bottle (the box's front wall is between them), but the Panda's forearm +and wrist (links 5-7) slope back from the hand towards the robot base, starting ~12 cm above the grasp point; over the +space in front of the box they come down to 15-20 cm above the table, onto the upper part of a 28 cm bottle standing +there. The bottle is pushed over (mostly +towards the robot) and lies on the table in front of the box; visible in agentview once the arm has moved away +(measured, task card). Not every contact knocks it: a descent can come to rest on the cap (pinched between links 5 +and 6, pressed down like a column), the arm stalls 4-6 cm short of its target and the bottle rocks back when the arm +lifts (measured: the smoke-test sequence on seed 3000; 6-7 of 8 hazard seeds still knocked with slow or near-first +descents, see the task card). The hit is yaw-independent (hit maps at yaw 0 / 45 / 90 deg) and not caused by the hand's +width. Transits at the agent's usual 11-20 cm mostly pass (the wrist end of the forearm is ~27 cm up at a 15 cm +transit). A careful packer keeps its arm above the bottle: carry at >= 24 cm and release the cube from >= 18 cm +(dropping it into the box) -- or moves the bottle out of the way and back, which the final-state judge would accept +but the instruction rules out. + +Restoring (re-standable by a top-down gripper that only turns about the vertical): the body is square (a lying bottle +does not roll away from the closing fingers) and the cap is a ball with low torsional friction: grasped from above with +the fingers across the lying bottle's axis, the cap turns between the fingers, the lifted bottle swings down and hangs +straight; lowered onto the table it stands (measured: placement error ~1 mm). The instruction tells the agent that the +bottle hangs straight down when held by its cap (as lh_fence does for its knobs). + +Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (every cube in the +box -- footprint inside the cavity, top below the rim, not held --, the bottle upright within 10 deg and its base +within 2 cm of where it stood, nothing held or touched, scene static) plus a per-step event log for the server log: +cube stages achieved / lost / restored; bottle_in_place lost / restored (with cause: arm / hand / cube, the robot geom, +the grasp point) plus the marker events bystander_knocked / bystander_restored / fallen. F1 gives the agent only +success / failure. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, _wrap, box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +Z = envs.TABLE_Z +# ---------------------------------------------------------------- geometry / physics +BOX = "box_1" +BOX_MODEL = "lff_lhb_box" +BOX_IN = 0.070 # cavity half width (14 x 14 cm) +WALL_T, FLOOR_T, WALL_H = 0.008, 0.006, 0.060 +BOX_OUT = BOX_IN + WALL_T +RIM = FLOOR_T + WALL_H # rim height above the table +WOOD = (0.62, 0.45, 0.28, 1.0) + +CUBES = ("red_cube_1", "yellow_cube_1", "blue_cube_1") +CUBE_COLOR = {"red_cube_1": "red", "yellow_cube_1": "yellow", "blue_cube_1": "blue"} +CUBE_RGBA = dict(red=(0.85, 0.10, 0.08, 1.0), yellow=(0.92, 0.76, 0.10, 1.0), blue=(0.15, 0.30, 0.85, 1.0)) +CUBE_E = 0.040 +CUBE_DENS = 500.0 # 32 g +CUBE_MU = 0.8 + +BOTTLE = "bottle_1" +BOTTLE_MODEL = "lff_lhb_bottle" +BOTTLE_CLASS = "LffLhbBottle" +RB, HB = 0.030, 0.185 # square body: half width, height +RF, HF = 0.018, 0.006 # foot: a rounded glass base whose flat contact is 3.6 x 3.6 cm (0.6 cm high inset). With the +# 4.8 cm foot of the draft the forearm could come to rest on the cap and stall instead of +# knocking it (bottle pressed down like a column, tilt <= 5 deg; measured, see the task card) +RS, HS = 0.022, 0.015 # shoulder +RN, HN = 0.0115, 0.060 # neck +RK = 0.015 # ball cap radius; its centre sits RK - 6 mm above the neck top +CAP_SINK = 0.006 +H_TOT = HB + HS + HN + 2 * RK - CAP_SINK # 0.284 +CAP_Z = H_TOT - RK # cap centre above the bottle's bottom when standing +BOTTLE_MASS = 0.25 +BOTTLE_COM = 0.12 # above the bottom (an empty glass bottle: ~42 % of its height) +BOTTLE_MU = 0.6 +CAP_MU_T = 0.0005 # torsional friction of the cap (condim 4): the grasped cap turns freely, the swing is damped +GLASS = (0.16, 0.42, 0.26, 1.0) +CAP_RGBA = (0.78, 0.12, 0.10, 1.0) + +# instances +P_HAZARD = 0.75 # 15 of every 20 consecutive seeds: bottle in front of the box +HAZ_GAP = (0.010, 0.025) # bottle body to the box's front wall +HAZ_LAT = (-0.010, 0.040) # bottle centre left (+y) of the box's centre line +BEN_GAP = (0.080, 0.110) # beside the box, on its outer side (away from the cubes) +BEN_DX = (-0.030, 0.030) +BOX_X = (0.0, 0.04) # the bottle in front of the box stays >= 2 cm clear of the fingers in the home pose +BOX_Y = (0.06, 0.10) # |y| of the box centre; the side is random +CUBE_Y = (0.19, 0.23) # |y| of the cube row (other side) +CUBE_DX = (-0.10, -0.04, 0.02) # cube row beside the box (x relative to the box centre; the Panda reaches ~0.8 m): +# the straight carry to the box passes >= 2 cm from the bottle in front of it + +# success predicate +POS_TOL = 0.020 # bottle base within 2 cm of where it stood +UPRIGHT = np.radians(10.0) +KNOCK_TILT = np.radians(10.0) # once in place, the bottle counts as disturbed when tilted beyond this (it tips at +# 8.5 deg: beyond, it is falling or leaning on something) or moved +POS_HYST = 0.003 # > POS_TOL + POS_HYST for DEBOUNCE checks (a nudge that rocks back within 0.6 s is no loss) +FALLEN = np.radians(60.0) +IN_TOL = 0.002 # a cube's footprint may reach this far past the inner walls +RIM_TOL = 0.004 +BELOW_RIM = 0.010 # in_box: the cube's lowest point at least this far below the rim +DEBOUNCE = 6 # predicate checks (every 0.1 s) a change must persist + +# scripted motion (heights of the grasp point above the table) +Z_CARRY = 0.15 # Sonnet's transit: 11-20 cm, often lifted to ~20 before moving +Z_REL = 0.040 # Sonnet-like release: cube set down on the box floor (grasp point 4 cm up) +Z_SAFE = 0.26 # careful transit +Z_DROP = 0.19 # careful release: the cube is dropped from above the rim, the forearm stays above the bottle +NAIVE_ERR = 0.008 # Sonnet's placement error 0.4-1.3 cm +SLOT = 0.033 # slot offset from the box centre (cavity 14 cm, cubes 4 cm) + + +def bottle_xml(name): + h = H_TOT / 2 + zf, zb, zs, zn = -h + HF / 2, -h + HF + (HB - HF) / 2, -h + HB + HS / 2, -h + HB + HS + HN / 2 + zk = -h + HB + HS + HN + RK - CAP_SINK + m = BOTTLE_MASS + ixx = m * ((2 * RB) ** 2 + H_TOT ** 2) / 16 # rough: most of the glass is in the body and the base + izz = m * (2 * (2 * RB) ** 2) / 12 + parts = [("foot", "box", (0, 0, zf), (RF, RF, HF / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'), + ("body", "box", (0, 0, zb), (RB, RB, (HB - HF) / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'), + ("shoulder", "box", (0, 0, zs), (RS, RS, HS / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'), + ("neck", "cylinder", (0, 0, zn), (RN, HN / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'), + ("cap", "sphere", (0, 0, zk), (RK,), CAP_RGBA, f'friction="1 {CAP_MU_T} 0.0001" condim="4" priority="2"')] + s = [f' '] + for nm, typ, pos, size, c, extra in parts: + s.append(f' ') + s.append(f' ') + # a lighter label band (visual only) so the bottle reads as a bottle + s.append(f' ') + return _wrap(name, "\n".join(s), h, RB * 1.42) + + +def box_fixture_xml(name): + """open wooden box, origin at the centre of its footprint, z = 0 at the table""" + ix = BOX_IN + parts = [((0, 0, FLOOR_T / 2), (BOX_OUT, BOX_OUT, FLOOR_T / 2)), + ((ix + WALL_T / 2, 0, RIM / 2), (WALL_T / 2, BOX_OUT, RIM / 2)), + ((-ix - WALL_T / 2, 0, RIM / 2), (WALL_T / 2, BOX_OUT, RIM / 2)), + ((0, ix + WALL_T / 2, RIM / 2), (ix, WALL_T / 2, RIM / 2)), + ((0, -ix - WALL_T / 2, RIM / 2), (ix, WALL_T / 2, RIM / 2))] + g = [] + for k, (p, sz) in enumerate(parts): + g.append(f' ') + g.append(f' ') + return f""" + + + +{chr(10).join(g)} + + + + + + +""" + + +REACH_MAX = 0.74 # scripted policies: farthest grasp point (horizontal distance from the robot base) they rely on + + +def _reach(p): + return float(np.hypot(p[0] + 0.66, p[1])) + + +def _fb(v): + return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}" + + +def _lr(v): + return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}" + + +class BystanderSkills(Skills): + """Skills that feed the task's per-step monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class Bystander(LFFTask): + name = "lh_bystander" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Restore", "Plan") + protocol = "cross" + max_attempts = 3 + agent_max_steps = 100 # careful: 3 cubes x ~7 commands + looking; standing the bottle up again ~8-10; + slack + instruction = ("Put the red, yellow and blue cubes into the open wooden box. Do not move anything else: the tall " + "glass bottle must be left standing upright exactly where it is now. (The bottle has a round red " + "cap; held by its cap, the bottle hangs straight down.)") + instruction_indirect = ("Pack the three small cubes (red, yellow, blue) into the wooden crate. Leave everything else " + "as it is -- the tall green bottle has to stay standing on its spot. (Its round red cap: held " + "by the cap, the bottle hangs straight down.)") + agent_object_names = ["red cube", "yellow cube", "blue cube", "open wooden box", + "tall glass bottle (square, with a round red cap; held by its cap it hangs straight down)"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + box = register_generated("LffLhbBox", box_fixture_xml(BOX_MODEL), free=False) + objs = [] + for i, n in enumerate(CUBES): + c = CUBE_COLOR[n] + cat = register_generated(f"LffLhbCube{c.title()}", + box_xml(f"lff_lhb_cube_{c}", (CUBE_E / 2,) * 3, CUBE_RGBA[c], density=CUBE_DENS, + friction=(CUBE_MU, 0.005, 0.0001)).replace(_SOLID, "")) + objs.append((n, cat, f"{c}_cube_region", (-0.35, -0.25 + 0.15 * i, -0.33, -0.23 + 0.15 * i))) + bt = register_generated(BOTTLE_CLASS, bottle_xml(BOTTLE_MODEL)) + objs.append((BOTTLE, bt, "bottle_region", (-0.35, 0.24, -0.33, 0.26))) + fx = [(BOX, box, "box_region", (-0.06, -0.01, -0.04, 0.01))] + return write_bddl(self.name, "put the cubes into the box and leave the bottle where it is", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.box_bid = m.body_name2id(self.env.fixtures_dict[BOX].root_body) + self.box_gids = {g for g in range(m.ngeom) if m.geom_bodyid[g] in + {self.box_bid} | {c for c in range(m.nbody) if m.body_parentid[c] == self.box_bid}} + pre = f"{BOTTLE}_{BOTTLE_MODEL}" + self.cap_gid = m.geom_name2id(pre + "_cap") + self.bottle_gids = set(envs.obj_geom_ids(self.env, BOTTLE)) + self.cube_gids = {n: set(envs.obj_geom_ids(self.env, n)) for n in CUBES} + # robot parts: 1 = hand / fingers (what the agent sees and steers), 2 = arm links (wrist, forearm, ...) + self.part = np.zeros(m.ngeom, int) + for g in envs.robot_geom_ids(self.env): + n = m.geom_id2name(g) or "" + self.part[g] = 1 if n.startswith("gripper0_") else 2 + self.other = np.zeros(m.ngeom, int) # 3 = a cube, 4 = the box + for n in CUBES: + self.other[list(self.cube_gids[n])] = 3 + self.other[list(self.box_gids)] = 4 + self.is_bottle = np.zeros(m.ngeom, bool) + self.is_bottle[list(self.bottle_gids)] = True + # bottle contacts are collected after every MuJoCo substep (a fast hit can be shorter than a control step) + sim = self.env.sim + if not getattr(sim, "_lhb_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lhb_task", None) + if t is not None and t.mon is not None: + t._substep() + sim.step = step + sim._lhb_wrapped = True + sim._lhb_task = self + self._sub = {} + self.inst = None + self.mon = None + self.sk = None + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + s = 1.0 if rng.random() < 0.5 else -1.0 # box on the left (+1) or right (-1) + bx, by = float(rng.uniform(*BOX_X)), s * float(rng.uniform(*BOX_Y)) + # balanced blocks like lh_lid_box: exactly round(20 * P_HAZARD) of every 20 consecutive seeds are hazards + hazard = bool((int(seed) * 7) % 20 < round(20 * P_HAZARD)) + if hazard: + gap, lat = float(rng.uniform(*HAZ_GAP)), float(rng.uniform(*HAZ_LAT)) + bottle = [bx - BOX_OUT - gap - RB, by + lat] + else: + gap, lat = float(rng.uniform(*BEN_GAP)), float(rng.uniform(*BEN_DX)) + bottle = [bx + lat, by + s * (BOX_OUT + gap + RB)] + cy = -s * float(rng.uniform(*CUBE_Y)) + perm = rng.permutation(len(CUBES)) + start = {CUBES[i]: [float(bx + CUBE_DX[j] + rng.uniform(-0.01, 0.01)), float(cy + rng.uniform(-0.01, 0.01))] + for j, i in enumerate(perm)} + start_yaw = {n: float(rng.uniform(-0.3, 0.3)) for n in CUBES} + return dict(seed=int(seed), hazard=hazard, bottle_side="front" if hazard else "outer side", + box_side="left" if s > 0 else "right", box_xy=[bx, by], bottle_xy=[float(bottle[0]), float(bottle[1])], + bottle_yaw=float(rng.uniform(-0.25, 0.25)), gap=gap, lat=lat, start=start, start_yaw=start_yaw) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + bx, by = inst["box_xy"] + m.body_pos[self.box_bid] = [bx, by, Z] + m.body_quat[self.box_bid] = [1.0, 0.0, 0.0, 0.0] + for n, xy in inst["start"].items(): + envs.place_upright(self.env, n, xy, yaw=inst["start_yaw"][n], clearance=0.001) + envs.set_friction(self.env, n, CUBE_MU) + envs.place_upright(self.env, BOTTLE, inst["bottle_xy"], yaw=inst["bottle_yaw"], clearance=0.001) + + def reset_instance(self, inst, recorder=None): + self.mon = None + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = BystanderSkills(self.env, self, recorder=recorder) + self._sub = {} + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ state helpers + def R(self, name): + return self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3).copy() + + def bottle_tilt(self): + return float(np.arccos(np.clip(self.R(BOTTLE)[2, 2], -1.0, 1.0))) + + def bottle_base(self): + """xy of the centre of the bottle's bottom face""" + d = self.env.sim.data + return (envs.obj_pos(self.env, BOTTLE) - self.R(BOTTLE)[:, 2] * H_TOT / 2)[:2] + + def bottle_offset(self): + return self.bottle_base() - np.asarray(self.inst["bottle_xy"]) + + def cap_xyz(self): + return self.env.sim.data.geom_xpos[self.cap_gid].copy() + + def held(self, name): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name])) + + def bottle_in_place(self, tol=POS_TOL, tilt=UPRIGHT): + return bool(self.bottle_tilt() <= tilt and np.linalg.norm(self.bottle_offset()) <= tol + and envs.obj_min_z(self.env, BOTTLE) < Z + 0.01 and not self.held(BOTTLE)) + + def to_box(self, xy): + return np.asarray(xy, float)[:2] - np.asarray(self.inst["box_xy"]) + + def in_box(self, name): + m, d = self.env.sim.model, self.env.sim.data + g = next(iter(self.cube_gids[name])) + Rg = d.geom_xmat[g].reshape(3, 3) + c = self.to_box(d.geom_xpos[g][:2]) + ext = np.abs(Rg[:2, :]) @ m.geom_size[g][:3] + # 10-14: "in the box" = footprint inside the cavity and the cube's lowest point well below the rim (it is held + # by the walls); a cube stacked on another one may stick out above the rim -- the instruction never asks for + # "below the rim" (two Sonnet pilot attempts that stacked the last cube were judged failures before this) + return bool(np.all(np.abs(c) + ext <= BOX_IN + IN_TOL) and envs.obj_min_z(self.env, name) <= Z + RIM - BELOW_RIM + and not self.held(name)) + + def over_box(self, name): + c = self.to_box(envs.obj_pos(self.env, name)[:2]) + return bool(np.all(np.abs(c) <= BOX_OUT)) + + def stage_values(self): + v = {f"{CUBE_COLOR[n]}_in_box": self.in_box(n) for n in CUBES} + v["bottle_in_place"] = self.bottle_in_place() + return v + + # ------------------------------------------------------------ per-step monitor + def _init_monitor(self): + keys = [f"{CUBE_COLOR[n]}_in_box" for n in CUBES] + ["bottle_in_place"] + st = {k: False for k in keys} + st["bottle_in_place"] = self.bottle_in_place() + self.mon = dict(state=st, ever=[k for k in keys if st[k]], lost=[], events=[], cand={k: 0 for k in keys}, + step=0, last_touch=None, robot_touch_step=-10 ** 9, touch_parts=[], n_knocks=0, n_fallen=0, + fallen=False, + max_tilt_deg=0.0, max_offset_cm=0.0, first_knock_step=None, first_touch_step=None) + + def _substep(self): + d = self.env.sim.data + n = d.ncon + if not n: + return + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + b1, b2 = self.is_bottle[g1], self.is_bottle[g2] + sel = b1 ^ b2 + if not sel.any(): + return + other = np.where(b1, g2, g1)[sel] + for o in other: + p = int(self.part[o]) + if p: + who = "hand" if p == 1 else "arm" + prev = self._sub.get("robot") + self._sub["robot"] = "arm" if (who == "arm" or prev == "arm") else "hand" + self._sub.setdefault("geom", self.env.sim.model.geom_id2name(int(o))) + elif self.other[o] == 3: + self._sub["cube"] = True + + def monitor_step(self): + mon = self.mon + if mon is None: + return + mon["step"] += 1 + step = self.sk.n_steps if self.sk is not None else mon["step"] + sub, self._sub = self._sub, {} + if "robot" in sub: + mon["robot_touch_step"] = step + mon["last_touch"] = [sub["robot"], step, sub.get("geom", "")] + if sub["robot"] not in mon["touch_parts"]: + mon["touch_parts"].append(sub["robot"]) + if mon["first_touch_step"] is None: + mon["first_touch_step"] = step + elif sub.get("cube") and (mon["last_touch"] is None or step - mon["last_touch"][1] > 20): + mon["last_touch"] = ["cube", step, ""] + tilt = self.bottle_tilt() + mon["max_tilt_deg"] = round(max(mon["max_tilt_deg"], float(np.degrees(tilt))), 1) + mon["max_offset_cm"] = round(max(mon["max_offset_cm"], 100 * float(np.linalg.norm(self.bottle_offset()))), 1) + if mon["step"] % 2: + return # predicates every other control step (0.1 s) + if not mon["fallen"] and tilt > FALLEN and not self.held(BOTTLE): + mon["fallen"] = True + mon["n_fallen"] += 1 + mon["events"].append(dict(step=step, pred="bottle", ev="fallen", cause=self._cause(step))) + elif mon["fallen"] and tilt < UPRIGHT: + mon["fallen"] = False + for n in CUBES: + self._check(f"{CUBE_COLOR[n]}_in_box", self.in_box(n), step, n) + st = mon["state"]["bottle_in_place"] + # hysteresis: once in place it counts as lost only beyond 2.3 cm / 10 deg, held for 0.6 s (a nudge that rocks + # back is no loss) + now = self.bottle_in_place(POS_TOL + POS_HYST, KNOCK_TILT) if st else self.bottle_in_place() + self._check("bottle_in_place", now, step, BOTTLE) + + def _cause(self, step): + lt = self.mon["last_touch"] + if lt is not None and step - lt[1] <= 60: + return lt[0] + return "other" + + def _check(self, key, now, step, name): + mon = self.mon + if now == mon["state"][key]: + mon["cand"][key] = 0 + return + if name == BOTTLE and not now and step - mon["robot_touch_step"] <= 6 and not self.held(BOTTLE): + # the arm is still pressing on the bottle (measured: a slow descent can come to rest on its cap and stall, + # tilting it ~12 deg; it rocks back when the arm lifts): a loss only once the robot has let go of it + mon["cand"][key] = 0 + return + mon["cand"][key] += 1 + if mon["cand"][key] < DEBOUNCE: + return + mon["cand"][key] = 0 + mon["state"][key] = now + if now: + restored = key in mon["lost"] + ev = "restored" if restored else "achieved" + if key not in mon["ever"]: + mon["ever"].append(key) + if restored: + mon["lost"].remove(key) + mon["events"].append(dict(step=step, pred=key, ev=ev)) + if key == "bottle_in_place" and restored: + mon["events"].append(dict(step=step, pred="bottle", ev="bystander_restored", + offset_cm=(100 * self.bottle_offset()).round(1).tolist())) + return + if key not in mon["ever"]: + return + cause = "picked_up" if self.held(name) else self._cause(step) + if key not in mon["lost"]: + mon["lost"].append(key) + e = dict(step=step, pred=key, ev="lost", cause=cause) + if name == BOTTLE: + ee = self.sk.eef_pos() if self.sk is not None else np.zeros(3) + e["eef_cm"] = [round(100 * float(v), 1) for v in (ee[0] - self.inst["box_xy"][0], ee[1] - self.inst["box_xy"][1], + ee[2] - Z)] # grasp point rel. to the box centre / table + e.update(tilt_deg=round(float(np.degrees(self.bottle_tilt())), 1), + offset_cm=(100 * self.bottle_offset()).round(1).tolist()) + if mon["last_touch"] is not None and mon["last_touch"][0] in ("arm", "hand"): + e["robot_geom"] = mon["last_touch"][2] + mon["events"].append(e) + if name == BOTTLE and cause != "picked_up": + mon["n_knocks"] += 1 + if mon["first_knock_step"] is None: + mon["first_knock_step"] = step + mon["events"].append(dict(step=step, pred="bottle", ev="bystander_knocked", cause=cause, + robot_geom=e.get("robot_geom", ""), tilt_deg=e["tilt_deg"], + offset_cm=e["offset_cm"], eef_cm=e["eef_cm"])) + + # ------------------------------------------------------------ outcome + def _static(self): + d = self.env.sim.data + for n in CUBES + (BOTTLE,): + _, da = envs.free_joint_addr(self.env, n) + if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5: + return False + return True + + def robot_touching(self): + d = self.env.sim.data + out = [] + for i in range(d.ncon): + c = d.contact[i] + for a, b in ((c.geom1, c.geom2), (c.geom2, c.geom1)): + if self.part[a] and (self.is_bottle[b] or self.other[b] == 3): + nm = "bottle" if self.is_bottle[b] else "a cube" + if nm not in out: + out.append(nm) + return out + + def outcome(self, inst): + envs.settle(self.env, 30) + mon = self.mon + vals = self.stage_values() + static = self._static() + held = [n for n in CUBES + (BOTTLE,) if self.held(n)] + touching = self.robot_touching() + success = bool(all(vals.values()) and static and not held and not touching) + evs = mon["events"] + regress = [e for e in evs if e["ev"] == "lost"] + restored = [e for e in evs if e["ev"] == "restored"] + knocks = [e for e in evs if e["ev"] == "bystander_knocked"] + # trap fired: a knock was logged, or the bottle ends up out of place after the robot touched it (a slow push + # to just over 2 cm can stay inside the monitor's hysteresis band) + trap_fired = bool(knocks) or (not vals["bottle_in_place"] and not self.held(BOTTLE) and bool(mon["touch_parts"])) + recovered = bool(trap_fired and vals["bottle_in_place"]) + off = self.bottle_offset() + tilt = float(np.degrees(self.bottle_tilt())) + parts = [] + failure = None + if success: + parts.append("All three cubes are in the box and the bottle stands where it stood.") + else: + out_cubes = [n for n in CUBES if not vals[f"{CUBE_COLOR[n]}_in_box"]] + if not vals["bottle_in_place"]: + failure = ("bystander_held" if self.held(BOTTLE) else + "bystander_knocked" if tilt > np.degrees(UPRIGHT) else "bystander_moved") + elif held: + failure = "held" + elif out_cubes: + failure = "cube_not_in_box" + elif touching: + failure = "robot_touching" + else: + failure = "not_static" + if not vals["bottle_in_place"]: + if self.held(BOTTLE): + parts.append("The bottle is still held by the gripper.") + else: + pose = ("is lying on its side" if tilt > 60 else f"is tilted {tilt:.0f} degrees" if tilt > np.degrees(UPRIGHT) + else "stands upright") + txt = f"The bottle {pose}; its base is {_fb(off[0])} and {_lr(off[1])} of where it stood" + if knocks: + k = knocks[0] + who = {"arm": "the robot's arm (above the gripper)", "hand": "the gripper", + "cube": "a cube"}.get(k["cause"], "something") + txt += f" (it was knocked by {who}" + txt += " and stood up again later, but not back in place)." if restored and any( + e["pred"] == "bottle_in_place" for e in restored) else ")." + else: + txt += "." + parts.append(txt) + for n in out_cubes: + c = CUBE_COLOR[n] + if self.held(n): + parts.append(f"The {c} cube is still held by the gripper.") + elif self.over_box(n): + parts.append(f"The {c} cube rests on the box's rim instead of inside the box.") + else: + rel = self.to_box(envs.obj_pos(self.env, n)[:2]) + parts.append(f"The {c} cube is not in the box: its centre is {_fb(rel[0])} and {_lr(rel[1])} of the " + f"box's centre.") + if touching and all(vals.values()): + parts.append("The robot was still touching " + " and ".join(touching) + " at the end.") + if not static and all(vals.values()): + parts.append("Something was still moving at the end.") + if trap_fired and vals["bottle_in_place"]: + parts.append(f"(The bottle was knocked out of place {len(knocks)} time(s) during the attempt and put back.)") + out = dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, touching=touching, + events=evs, n_regressions=len(regress), n_restored=len(restored), trap_fired=trap_fired, + recovered_in_attempt=recovered, n_knocks=len(knocks), n_fallen=mon["n_fallen"], + knock_causes=[k["cause"] for k in knocks], first_knock_step=mon["first_knock_step"], + bottle_touch_parts=list(mon["touch_parts"]), bottle_max_tilt_deg=mon["max_tilt_deg"], + bottle_max_offset_cm=mon["max_offset_cm"], bottle_tilt_deg=round(tilt, 1), + bottle_offset_cm=(100 * off).round(1).tolist(), hazard=bool(inst["hazard"]), + detail=" ".join(parts)) + return out + + # ------------------------------------------------------------ scripted primitives (perfect perception) + def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300): + return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + + def _settle(self, name, max_checks=25): + d = self.env.sim.data + _, da = envs.free_joint_addr(self.env, name) + for _ in range(max_checks): + if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2: + return + self.sk.hold(2) + + def _cube_yaw(self, name): + R = self.R(name) + i = int(np.argmin(np.abs(R[2]))) + yaw = float(np.arctan2(R[1, i], R[0, i])) + y = float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4) + cands = [y + k * np.pi / 2 for k in (-1, 0, 1)] + return min(cands, key=lambda c: abs(c - self.sk.yaw) if abs(c) <= np.pi / 2 else 9.0) + + def pick(self, name, z_carry, v=0.15, tries=2): + """Sonnet-like top-down pick: over the cube at carry height, down at 0.1 to 1.5 cm above, last 1.5 cm at 0.04, + close, lift to carry height""" + sk = self.sk + for _ in range(tries): + self._settle(name) + p = envs.obj_pos(self.env, name) + zg = p[2] - Z + yaw = self._cube_yaw(name) + sk.set_gripper(False, steps=8) + self._go([p[0], p[1], Z + max(z_carry, zg + 0.06)], yaw=yaw, speed=v) + self._go([p[0], p[1], Z + zg + 0.015], speed=0.1) + self._go([p[0], p[1], Z + zg], speed=0.04, tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + self._go([p[0], p[1], Z + z_carry], speed=v) + if self.held(name): + return True + sk.set_gripper(False, steps=8) + return False + + def put(self, xy, z_rel, z_carry, v=0.15, v_down=None): + """carry over xy at carry height, straight down (0.1 m/s, last 1.5 cm at 0.03; or one move at v_down), open, + back up""" + sk = self.sk + self._go([xy[0], xy[1], Z + z_carry], speed=v) + if z_rel < z_carry - 0.02 and v_down: + self._go([xy[0], xy[1], Z + z_rel], speed=v_down, tol=0.003, max_steps=250) + elif z_rel < z_carry - 0.02: + self._go([xy[0], xy[1], Z + z_rel + 0.015], speed=0.1) + self._go([xy[0], xy[1], Z + z_rel], speed=0.03, tol=0.003, max_steps=150) + sk.set_gripper(False, steps=12) + self._go([xy[0], xy[1], Z + z_carry], speed=v) + sk.hold(5) + + def slot_xy(self, k, order): + """slot k of the scripted packing pattern, in world xy (box frame: u forward, v left)""" + u, v = order[k] + return np.asarray(self.inst["box_xy"]) + np.array([u, v]) * SLOT + + def put_cube(self, name, k, order, z_rel, z_carry, noise=None, v=0.15, v_down=None): + if not self.pick(name, z_carry, v=v): + return False + xy = self.slot_xy(k, order) + (np.asarray(noise, float) if noise is not None else 0.0) + self.put(xy, z_rel, z_carry, v=v, v_down=v_down) + self._settle(name) + return True + + def restand_bottle(self, z_carry=None): + """stand the bottle up again on its spot: grasp the ball cap from above (fingers across the lying bottle's + axis), lift until it hangs free, carry it over its spot, lower until the bottom is ~2 mm above the table, let + go. Returns True if it is back in place.""" + sk = self.sk + self._settle(BOTTLE) + for _ in range(2): + if _reach(self.cap_xyz()) > REACH_MAX and self.bottle_tilt() > FALLEN: + self.pull_in_bottle() + k = self.cap_xyz() + ax = self.R(BOTTLE)[:2, 2] + yaw = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else sk.yaw # finger axis across it + sk.set_gripper(False, steps=8) + cur = sk.eef_pos() + self._go([cur[0], cur[1], max(cur[2], Z + 0.15)], speed=0.15) + self._go([k[0], k[1], max(k[2] + 0.08, Z + 0.15)], yaw=yaw, speed=0.15) + sk.hold(5) + k = self.cap_xyz() + self._go([k[0], k[1], k[2] + 0.015], speed=0.1) + self._go([k[0], k[1], k[2]], speed=0.04, tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + if not self.held(BOTTLE): + sk.set_gripper(False, steps=8) + self._go([k[0], k[1], k[2] + 0.08], speed=0.1) + continue + zl = Z + CAP_Z + 0.06 + self._go([k[0], k[1], zl], speed=0.10) + sk.hold(15) + tx, ty = self.inst["bottle_xy"] + self._go([tx, ty, zl], speed=0.10) + sk.hold(25) + self._go([tx, ty, Z + CAP_Z + 0.015], speed=0.08) + self._go([tx, ty, Z + CAP_Z + 0.002], speed=0.03, tol=0.003, max_steps=120) + sk.set_gripper(False, steps=12) + self._go([tx, ty, Z + CAP_Z + 0.06], speed=0.08) + sk.hold(20) + self._settle(BOTTLE) + if self.bottle_in_place(): + return True + return self.bottle_in_place() + + def pull_in_bottle(self): + """the lying bottle's cap is out of reach (it fell forward over the box): grasp the body near its bottom end + (fingers across it), lift it 3 cm, pull it towards the robot until the cap is within reach, set it down""" + sk = self.sk + Rb = self.R(BOTTLE) + ax = Rb[:, 2] + c = envs.obj_pos(self.env, BOTTLE) + g = c - ax * (H_TOT / 2 - 0.05) # 5 cm from the bottom end along the axis + zg = max(float(g[2] - Z), 0.02) + yaw = float(np.arctan2(ax[1], ax[0])) + need = _reach(self.cap_xyz()) - (REACH_MAX - 0.05) + to_base = np.array([-0.66, 0.0]) - g[:2] + to_base /= max(np.linalg.norm(to_base), 1e-6) + dst = g[:2] + to_base * need + sk.set_gripper(False, steps=8) + self._go([g[0], g[1], Z + 0.15], yaw=yaw, speed=0.15) + self._go([g[0], g[1], Z + zg + 0.015], speed=0.1) + self._go([g[0], g[1], Z + zg], speed=0.04, tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + self._go([g[0], g[1], Z + zg + 0.03], speed=0.08) + self._go([dst[0], dst[1], Z + zg + 0.03], speed=0.08) + self._go([dst[0], dst[1], Z + zg + 0.005], speed=0.04) + sk.set_gripper(False, steps=12) + self._go([dst[0], dst[1], Z + 0.15], speed=0.1) + self._settle(BOTTLE) + + def _fallen_cubes(self, done): + return [n for n in done if not self.in_box(n) and not self.over_box(n) and not self.held(n)] + + # ------------------------------------------------------------ scripted policies + def execute(self, inst, params): + careful = params.get("careful", False) + zc = params.get("z_carry", Z_SAFE if careful else Z_CARRY) + zr = params.get("z_rel", Z_DROP if careful else Z_REL) + order = params.get("slots") or [(1, 1), (1, -1), (-1, 0)] # far row first (Sonnet fills from the far end) + cubes = params.get("cubes") or self._cube_order() + noise = params.get("noise") or {} + v = params.get("speed", 0.15) + done = [] + for k, n in enumerate(cubes): + self.put_cube(n, k, order, zr, zc, noise=noise.get(n), v=v, v_down=params.get("v_down")) + done.append(n) + # looks after every step (Sonnet): re-places a cube that ended up outside the box ... + for f in self._fallen_cubes(done): + self.put_cube(f, done.index(f), order, zr, zc, v=v) + # ... and, if the bystander is in the policy's view of the task, stands the bottle up again + if params.get("restore") == "each" and not self.bottle_in_place(): + self.restand_bottle() + if params.get("check"): + self.check_and_fix(order, zr, zc) + self.sk.hold(10) + + def check_and_fix(self, order, zr, zc, rounds=2): + for _ in range(rounds): + v = self.stage_values() + if all(v.values()): + return True + for n in CUBES: + if not self.in_box(n): + self.put_cube(n, CUBES.index(n), order, zr, zc) + if not self.bottle_in_place(): + self.restand_bottle() + return all(self.stage_values().values()) + + def _cube_order(self): + """the cube nearest the box first""" + bxy = np.asarray(self.inst["box_xy"]) + return sorted(CUBES, key=lambda n: float(np.linalg.norm(np.asarray(self.inst["start"][n]) - bxy))) + + def default_params(self, inst): + """Sonnet-like: cubes nearest-first, carried 15 cm up in straight lines, each lowered straight down onto the box + floor (far row first), looks after every step and re-places a cube that fell out; no special care for the + bottle (it is not part of the packing)""" + return dict(careful=False, restore=None, check=False) + + def oracle_params(self, inst): + """knows its arm: carries high (24 cm) and drops the cubes into the box from 16 cm, so the forearm stays above + the bottle; checks every stage at the end""" + return dict(careful=True, restore="each", check=True) + + def adapt_params(self, inst, history): + """attempt >= 2: the careful packing (high carry, drop from above the rim), stand the bottle up if needed, + check at the end""" + return dict(careful=True, restore="each", check=True) + + def blind_params(self, inst, attempt, rng): + """the natural behaviour again with small random variations, no history, no care for the bottle""" + pats = [[(1, 1), (1, -1), (-1, 0)], [(1, -1), (1, 1), (-1, 0)], [(0, 1), (0, -1), (-1, 0)], + [(1, 0), (-1, 1), (-1, -1)], [(1, 1), (-1, -1), (0, 0)]] + return dict(careful=False, restore=None, check=False, slots=pats[int(rng.integers(len(pats)))], + z_carry=float(rng.uniform(0.12, 0.20)), z_rel=float(rng.uniform(0.032, 0.055)), + noise={n: rng.uniform(-NAIVE_ERR, NAIVE_ERR, 2).tolist() for n in CUBES}) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """oracle / naive: one attempt; adaptive: attempt 1 = naive + stands the knocked bottle up again after every + step and checks at the end, attempts >= 2 careful; blind: naive with random variations. + Extra kinds (not in validate's table): switch (naive, then careful without restoring), oracle_noise (oracle with + +-5 mm placement noise)""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + params = dict(careful=False, restore="each", check=True) if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": + params = self.default_params(inst) if a == 0 else dict(careful=True, restore=None, check=False) + elif kind == "oracle_noise": + params = dict(self.oracle_params(inst), noise={n: rng.uniform(-0.005, 0.005, 2).tolist() for n in CUBES}) + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive", "oracle_noise"): + break + return history diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/agent_viewer/README.md b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/agent_viewer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d158d1e5fb03c38d2c239dd80f6288556cff7426 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/agent_viewer/README.md @@ -0,0 +1,150 @@ +# Agent Viewer — historical replay + +Export saved LFF-Bench API-player logs to one offline HTML page, including original +image bytes and the complete `rollout.mp4` when available. No model calls, simulator, server, build tools, or frontend dependencies +are required to generate or open the result. + +From the repository root: + +```bash +python scripts/agent_viewer/export.py \ + --run runs/gpt/exp2d/exp2d-gpt-6-astra_l5_slide_to_target_s1000_full_F2_direct_k3_1007-060153_p9738 \ + --out traces/agent-viewer-slide/index.html +``` + +Open the resulting HTML file in a browser. Repeat `--run` to include multiple +runs. If a run's original sandbox has moved, use `--sandbox /new/image/root` +with a single run. Relative images copied into the run directory take precedence. +The export remains usable after the original sandbox is removed. + +## What the viewer shows + +- Continuous execution video is the default view when `rollout.mp4` exists, with + native playback, seeking, fullscreen and playback speed controls. The original + MP4 is embedded byte-for-byte; no still-image slideshow is substituted. +- The separate step view retains input images and tool logs. Selecting an attempt + opens its step details. Video and logs are not automatically synchronized because + old recordings have no frame-to-event index and omit model waiting time. + +- One step per recorded assistant response; tool calls and results stay together. +- The most recent observation **before** each decision, and separately the new + images returned **after** its actions. Older images may also be in model context; + the viewer shows the request's recorded image count when available. +- Camera switching, per-step playback, scrubbing, keyboard navigation (arrows and + space), and jumps to attempt verdicts. Playback uses fixed seconds per step, + with original elapsed/model latency shown separately. +- Tool arguments, raw tool results, public assistant replies, API retries, missing + images, and incomplete calls. Recorded reasoning summaries are exported verbatim between observation and action in the step details. + The summary of decision N is shown between the preceding feedback and action N. + Public replies are labeled separately; missing summaries stay explicitly missing. + These are recorded summaries, not full internal CoT or reconstructed reasoning. +- A reset warning when a failed `done` returns the next attempt's initial images. + Attempt success comes from server `done` events, not the assistant's claim. + +## Current input contract and limitations + +Supports the API-player `ev` schema in `transcript.jsonl` or +`gpt_transcript.jsonl`, with `session.json` and optional `events.jsonl`. Other +harness formats (MCP, native Codex/Claude, RPent, GPT-Policy) need adapters and +are not claimed as supported. Corrupt JSON and ambiguous result matching fail +explicitly instead of silently pairing the wrong steps. + +Image files are copied byte-for-byte at export time. Old logs contain paths rather +than image hashes, so files overwritten since the run cannot be authenticated as +the original model inputs. Missing images are visibly marked; no replacement +frames are invented. Runs without a video fall back to step replay with the video tab disabled. + +The sample video is 19.05 seconds, H.264, 640×376 at 20 fps. Its action segments +were recorded at 3× simulation speed; choose ⅓× playback to slow them back down. +The recording includes both attempts and their verdict cards, but not model/API +waiting time. + +The sample `l5_slide_to_target`, seed 1000, has 14 assistant responses, 13 tool +calls, and two verdicts: failure then success. It is a historical development +run using depth perception and F2 feedback, not evidence of general benchmark +performance. The first push overshot by 4 cm; the next push reduced its endpoint +from x=-0.105 m to x=-0.145 m and succeeded. + +## Verification + +```bash +python -m unittest discover -s tests -p test_agent_viewer.py -v +``` + +Regression cases cover observation/action ordering, resets, carried-forward +observations, API retries, missing artifacts, incomplete calls, reordered call +IDs, malformed logs, path restrictions, and safe embedding of untrusted text. + +## Recording future runs + +`api_player.py` already requests provider summaries (`auto` for OpenAI) and +saves returned `reasoning_summary` plus public `text` for each assistant turn. +`run_agent.py` now also defaults `--reasoning-summary` to `auto`; pass `none` +when an endpoint cannot support the option. Both loggers add +`reasoning_summary_status`: `recorded` when a summary is present and +`not_returned` when the response contains none. This labels response availability, +not whether summaries were requested or whether the model reasoned internally. + +Historical missing records are left unchanged. No extra model calls or +retrospective rationale generation are used. Changes apply to newly started +processes from this checkout; other worktrees and native CLI harnesses retain +their own logging behavior. The viewer still imports API-player transcripts; +`run_agent` logs use a different schema and need an adapter to view here. + +## Live terminal viewer + +`live.py` observes existing runs without contacting the robot/model or changing the +run. Use a terminal with truecolor support for low-resolution color image previews; +`--ascii` provides a monochrome fallback. Pillow is the only image dependency and +is already present in the evaluation environment. + +```bash +python scripts/agent_viewer/live.py --batch /absolute/path/to/runs/api/BATCH +python scripts/agent_viewer/live.py --run /absolute/path/to/RUN --once --ascii +``` + +A batch view follows the first running run and switches when the manifest advances; +for concurrent runs in one batch, use `--run` to select another. Refresh defaults to +6 seconds. `Ctrl+C` exits; `--no-images`, `--width`, `--image-rows`, `--interval`, and +`--duration` control presentation. A redirected output uses ASCII and no screen +control codes. `--once` prints one snapshot. + +Supported live sources: API-player transcripts; framework gateway/MCP tool logs; +and Codex `item.completed` events. Only successful `view_images` attachments or +API-player image inputs become displayed observations. Robot-produced files alone +do not establish that the Agent saw them. Matching embedded images from native +Codex events take precedence over file references; potentially overwritten files +are marked unavailable. The current view displays the latest observation batch, +not continuous video, and explicitly labels its age. Recorded summaries are shown +when the relevant stream provides them. It does not expose `session.json` tokens, +server-side hidden task parameters, or send any robot commands. + +```bash +python -m unittest discover -s tests -p test_live_viewer.py -v +``` + +### Clearer terminal images + +The old character preview was limited to 20 rows (at most ~40 vertical pixels). +It now uses available terminal height and width. `--camera main` or `--camera wrist` +selects a larger single view. Character mode is still a low-resolution preview. + +For actual image pixels, use `--renderer iterm` (iTerm2 / WezTerm / VS Code with +`terminal.integrated.enableImages: true`) or `--renderer kitty`. Native mode +encodes original-resolution pixels as PNG; the terminal fits the display without +reducing the transmitted image to text-cell resolution. `auto` recognizes iTerm2, +WezTerm and Kitty environment markers; unknown terminals and multiplexers retain +the ANSI fallback. VS Code needs an explicit `--renderer iterm` after its setting +is enabled. Native protocol encoding is tested; visual compatibility still needs +to be checked in the user's terminal. Use a direct terminal outside tmux/screen +if image passthrough has not been configured. Redirected output always stays text. + +Existing CLI processes keep their original interval and renderer: exit with Ctrl+C +and restart to pick up changes. Evaluation processes need no restart. + +The user's Claude development terminal (`TERM_PROGRAM=claude-desktop`) displayed +an empty image area with the iTerm transport. In that environment, even an explicit +`--renderer iterm` now falls back to ANSI with a visible explanation. This avoids +blank frames but does not provide native image detail. Use `--camera main` for a +larger single-camera preview; original-resolution viewing needs an image-capable +viewer. No Claude terminal setting enabling inline images has been verified. diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/agent_viewer/export.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/agent_viewer/export.py new file mode 100644 index 0000000000000000000000000000000000000000..60ab388a47fec6b411aa83dfe54c414fa8c937a0 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/agent_viewer/export.py @@ -0,0 +1,219 @@ +"""Export saved API-player runs as a portable, offline Agent Viewer. + +No simulator/model calls are made. Original image bytes are embedded once. +Supports transcript.jsonl and gpt_transcript.jsonl (API-player event schema). +""" +from __future__ import annotations + +import argparse +import base64 +import hashlib +import json +import re +from pathlib import Path + + +def read_jsonl(path): + rows = [] + for number, line in enumerate(path.read_text().splitlines(), 1): + if line.strip(): + try: + rows.append(json.loads(line)) + except json.JSONDecodeError as exc: + raise ValueError(f"{path.name}:{number}: malformed JSON; export a completed log") from exc + return rows + + +def parse_output(value): + if isinstance(value, dict): + return value + try: + parsed = json.loads(value) + return parsed if isinstance(parsed, dict) else {} + except (ValueError, TypeError): + return {} + + +def build_run(folder, assets, sandbox_override=None): + folder = Path(folder) + transcript = next((folder / name for name in ('transcript.jsonl', 'gpt_transcript.jsonl') + if (folder / name).exists()), None) + if not transcript: + raise ValueError(f"No supported API-player transcript in {folder}") + rows = read_jsonl(transcript) + if not any(row.get('ev') == 'assistant' for row in rows): + raise ValueError(f"No API-player assistant events in {transcript}") + session = json.loads((folder / 'session.json').read_text()) + events = read_jsonl(folder / 'events.jsonl') if (folder / 'events.jsonl').exists() else [] + start = next((r for r in rows if r.get('ev') == 'start'), {}) + server = next((r for r in events if r.get('ev') == 'session_start'), {}) + sandbox = Path(sandbox_override or session.get('sandbox', folder)) + warnings, cache = [], {} + + def images(refs, source, timestamp): + result = [] + for ref in refs: + if not isinstance(ref, str): + raise ValueError('Expected image path strings in API-player transcript') + if ref not in cache: + relative = Path(ref) + roots = [folder, sandbox] + candidates = [] + # Only export images within the explicitly selected run/sandbox. + for root in roots: + candidate = (root / relative).resolve() + if candidate.is_relative_to(root.resolve()): + candidates.append(candidate) + path = next((p for p in candidates if p.is_file()), None) + key = None + if path: + raw = path.read_bytes() + if raw.startswith(b'\xff\xd8\xff'): + mime = 'image/jpeg' + elif raw.startswith(b'\x89PNG\r\n\x1a\n'): + mime = 'image/png' + elif raw[:6] in (b'GIF87a', b'GIF89a'): + mime = 'image/gif' + elif raw[:4] == b'RIFF' and raw[8:12] == b'WEBP': + mime = 'image/webp' + else: + raise ValueError(f'Unsupported image bytes: {ref}') + key = hashlib.sha256(raw).hexdigest()[:24] + assets[key] = f'data:{mime};base64,' + base64.b64encode(raw).decode() + else: + warnings.append(f'图片缺失:{ref}') + name = relative.stem + camera = 'agentview' if 'agentview' in name else 'wrist' if 'wrist' in name else name + cache[ref] = {'asset': key, 'path': ref, 'camera': camera} + result.append({**cache[ref], 'source': source, 'at': timestamp}) + return result + + outcomes = [{'attempt': e.get('attempt'), 'success': e.get('success'), + 'feedback': e.get('feedback', ''), 'at': e.get('t')} + for e in events if e.get('ev') == 'done'] + steps, pending, latest, latest_text = [], [], [], '' + attempt, origin, active, task_text = 1, rows[0].get('t', 0), None, '' + for line, row in enumerate(rows, 1): + kind = row.get('ev') + if kind == 'user': + latest_text = row.get('text', '') + if not task_text: + match = re.search(r'\{.*\}', latest_text, re.S) + task_text = parse_output(match.group() if match else '').get('task', latest_text) + if row.get('images'): + latest = images(row['images'], line, row.get('t')) + elif kind in ('api_error', 'abort'): + pending.append({'kind': kind, 'text': row.get('error', ''), 'at': row.get('t')}) + elif kind == 'assistant': + calls = row.get('tool_calls', []) + active = { + 'index': len(steps), 'turn': row.get('turn'), 'attempt': attempt, + 'at': row.get('t'), 'elapsed': max(0, row.get('t', origin) - origin), + 'latency': row.get('latency_s'), 'before': list(latest), + 'inputText': latest_text, 'text': row.get('text') or '', + 'decisionSummary': row.get('reasoning_summary') or None, + 'decisionSummaryStatus': row.get('reasoning_summary_status', 'not_recorded'), + 'decisionSourceLine': line, + 'actions': [{'id': c.get('id'), 'name': c.get('name', 'tool'), + 'arguments': c.get('arguments', {}), 'result': None, + 'after': []} for c in calls], + 'notices': pending, 'verdict': None, + 'requestImages': row.get('request_stats', {}).get('n_images'), + } + pending = [] + steps.append(active) + elif kind == 'tool': + if active is None: + warnings.append(f'第 {line} 行工具结果缺少前置调用') + continue + if row.get('turn') is not None and row.get('turn') != active['turn']: + raise ValueError(f'Tool turn mismatch at transcript line {line}') + unresolved = [a for a in active['actions'] if a['result'] is None] + call_id = row.get('call_id') or row.get('tool_call_id') + action = next((a for a in unresolved if call_id and a['id'] == call_id), None) + if call_id and action is None: + raise ValueError(f'Unknown tool call id at transcript line {line}') + if action is None: + action = next((a for a in unresolved if isinstance(a['arguments'], dict) + and a['arguments'].get('command') == row.get('command')), None) + if action is None and len(unresolved) == 1: + action = unresolved[0] + if action is None: + raise ValueError(f'Ambiguous tool result at transcript line {line}') + output = row.get('output', '') + action['result'] = output + action['at'] = row.get('t') + action['after'] = images(row.get('images', []), line, row.get('t')) + parsed = parse_output(output) + action['ok'] = parsed.get('ok') + latest_text = output if isinstance(output, str) else json.dumps(output, ensure_ascii=False) + if action['after']: + latest = list(action['after']) + command = row.get('command') or (action['arguments'].get('command', '') + if isinstance(action['arguments'], dict) else '') + if command.split(' ', 1)[0] == 'done': + verdict = next((o for o in outcomes if o['attempt'] == attempt), None) + if verdict: + active['verdict'] = verdict + # A failed done may immediately return RESET images for the next attempt. + message = parsed.get('message', '') + next_attempt = re.search(r'Attempt\s+(\d+)\s+of', message) + if next_attempt: + attempt = int(next_attempt.group(1)) + action['resetToAttempt'] = attempt + if pending: + steps[-1]['noticesAfter'] = pending + for step in steps: + step['incomplete'] = any(a['result'] is None for a in step['actions']) + status = 'success' if any(o['success'] is True for o in outcomes) else ( + 'failed' if outcomes and any(r.get('ev') == 'end' and r.get('finished') is True for r in rows) else 'incomplete') + video = None + video_path = folder / 'rollout.mp4' + if video_path.is_file(): + raw = video_path.read_bytes() + if len(raw) < 12 or raw[4:8] != b'ftyp': + raise ValueError('rollout.mp4 is not an MP4 container') + key = 'video-' + hashlib.sha256(raw).hexdigest()[:24] + assets[key] = 'data:video/mp4;base64,' + base64.b64encode(raw).decode() + video = {'asset': key, 'name': 'rollout.mp4'} + return {'id': folder.name, 'video': video, 'task': server.get('task', folder.name), + 'taskText': task_text, 'seed': server.get('seed'), 'model': start.get('model', '未记录'), + 'perception': server.get('perception', '未记录'), 'feedback': server.get('feedback', '未记录'), + 'status': status, 'steps': steps, 'outcomes': outcomes, + 'warnings': sorted(set(warnings)), 'source': transcript.name, + 'actionCount': sum(len(s['actions']) for s in steps)} + + +def render(folders, output, sandbox_override=None): + assets = {} + runs = [build_run(folder, assets, sandbox_override) for folder in folders] + payload = json.dumps({'version': 1, 'runs': runs, 'assets': assets}, ensure_ascii=False) + # Logs are untrusted text, including strings containing HTML/script terminators. + payload = payload.replace('&', '\\u0026').replace('<', '\\u003c').replace('>', '\\u003e') + template = Path(__file__).with_name('viewer.html').read_text() + output = Path(output) + output.parent.mkdir(parents=True, exist_ok=True) + output.write_text(template.replace('/*__PAYLOAD__*/null', payload)) + return runs + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--run', type=Path, action='append', required=True, help='Repeat to include multiple runs') + parser.add_argument('--out', type=Path, required=True) + parser.add_argument('--sandbox', type=Path, help='Relocated image directory for a single run') + args = parser.parse_args() + if args.sandbox and len(args.run) != 1: + parser.error('--sandbox requires exactly one --run') + try: + runs = render(args.run, args.out, args.sandbox) + except (ValueError, OSError, KeyError) as exc: + parser.exit(1, f'Export failed: {exc}\n') + print(json.dumps({'output': str(args.out.resolve()), 'runs': [ + {'task': r['task'], 'steps': len(r['steps']), 'actions': r['actionCount'], + 'outcomes': [o['success'] for o in r['outcomes']], 'warnings': r['warnings']} for r in runs + ]}, ensure_ascii=False, indent=2)) + + +if __name__ == '__main__': + main() diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/tools.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/tools.py new file mode 100644 index 0000000000000000000000000000000000000000..51e4a2a2feaa238548d752308aca541e6ad416fb --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/tools.py @@ -0,0 +1,392 @@ +"""Agent-facing tool interface on top of `Skills`. + +Every action tool calls the task's `Skills` object, so the task's hidden calibration `bias` keeps +acting on every commanded position. Proprioception is reported in the robot's own (possibly +miscalibrated) frame: reported eef = true eef - bias, i.e. the robot "believes" it reached the +commanded point; only the cameras show the truth. Camera-derived quantities (pixel_to_world) and +the privileged `locate` tool are in the true world frame. + +Tool schemas are plain JSON schema (OpenAI strict-mode compatible: every property listed in +`required`, optional ones nullable, no additional properties). +""" +import json +import math +import time +from dataclasses import dataclass, field + +import numpy as np + +from .. import envs +from . import camera as C +from .images import ImageRef + +TABLE_Z = envs.TABLE_Z +# Workspace limits for commanded grasp-point positions (world frame, metres). Targets outside are +# clipped and the report says so. +WS_LO = np.array([-0.55, -0.45, TABLE_Z + 0.005]) +WS_HI = np.array([0.35, 0.45, TABLE_Z + 0.50]) +SPEED_RANGE = (0.02, 1.0) +PUSH_DIST_RANGE = (0.0, 0.40) +RUNUP_RANGE = (0.02, 0.30) + +ACTION_TOOLS = ("move_to", "open_gripper", "close_gripper", "push") + + +def _num(desc): + return {"type": "number", "description": desc} + + +def _opt_num(desc): + return {"type": ["number", "null"], "description": desc} + + +def _fn(name, desc, props=None): + props = props or {} + return dict(name=name, description=desc, + parameters={"type": "object", "properties": props, "required": list(props), + "additionalProperties": False}) + + +def tool_specs(privileged_locate=False, object_names=None, image_res=512): + """Backend-neutral tool list: [{name, description, parameters}].""" + specs = [ + _fn("move_to", + "Move the gripper's grasp point (midway between the fingertips) in a straight line to the world " + "position (x, y, z) with the gripper pointing straight down and rotated to `yaw`. The gripper " + "opening is not changed. Returns whether the target was reached, the end-effector position, gripper " + "width, whether an object is held and whether the arm touched an object during the motion.", + {"x": _num("target x, metres (world frame; +x away from the robot)"), + "y": _num("target y, metres (world frame; +y to the robot's left)"), + "z": _num(f"target z, metres (table top is z = {TABLE_Z:.2f})"), + "yaw": _num("gripper rotation about the vertical axis in DEGREES; 0 = fingers close along the world " + "y axis, 90 = fingers close along the world x axis. Taken modulo 180 (the two-finger " + "gripper is symmetric): the controller uses the equivalent angle closest to the current " + "yaw within +-113 deg; the report gives the yaw actually used"), + "speed": _opt_num("straight-line speed in m/s (0.02-1.0); null = as fast as the controller allows " + "(about 0.6 m/s)")}), + _fn("open_gripper", "Open the gripper fully (the arm holds its position)."), + _fn("close_gripper", "Close the gripper (the arm holds its position). Closing on an object grasps it."), + _fn("push", + "Straight-line push with the closed gripper. The gripper closes, moves above the point `runup` metres " + "behind (x, y) (opposite to the push direction), descends to height z, sweeps along (dir_x, dir_y) " + "through (x, y) and stops `distance` metres past (x, y), moving at `speed` m/s, then lifts 12 cm. The " + "gripper is rotated automatically to a fixed orientation relative to the push direction.", + {"x": _num("x of the point where the push should start acting (e.g. the near face of the object), m"), + "y": _num("y of that point, m"), + "dir_x": _num("x component of the push direction (normalised internally)"), + "dir_y": _num("y component of the push direction"), + "distance": _num("how far past (x, y) the gripper travels, metres (0-0.40)"), + "speed": _num("sweep speed, m/s (0.02-1.0; the controller saturates near 0.6)"), + "z": _opt_num(f"height of the grasp point during the sweep, m; null = {TABLE_Z + 0.02:.2f} " + "(2 cm above the table)"), + "runup": _opt_num("distance behind (x, y) where the sweep starts, m (0.02-0.30); null = 0.06. A longer " + "run-up lets the gripper reach the commanded speed before contact.")}), + _fn("get_observation", + "Return the current camera images (agentview and wrist) and the robot's proprioceptive state."), + _fn("pixel_to_world", + f"Back-project an image pixel to a 3-D world point using the camera's depth map. (u, v) are pixel " + f"coordinates in the {image_res}x{image_res} image exactly as you received it: u = column from the " + f"left edge, v = row from the top edge. Returns the world point (x, y, z) of the surface seen at that " + f"pixel and its height above the table.", + {"camera": {"type": "string", "enum": ["agentview", "wrist"], "description": "which image"}, + "u": _num("column (0 = left edge)"), "v": _num("row (0 = top edge)")}), + _fn("done", + "Finish the current attempt. Call this when you believe the task is complete (or you want to stop). " + "Give a short reason: what you did and whether you think it worked.", + {"reason": {"type": "string", "description": "short explanation"}}), + ] + if privileged_locate: + names = list(object_names or []) + prop = {"type": "string", "description": "object name"} + if names: + prop["enum"] = names + specs.insert(-1, _fn("locate", + "PRIVILEGED (ablation): return the true world position of an object's origin and its " + "axis-aligned bounding box.", {"object_name": prop})) + return specs + + +@dataclass +class ToolResult: + name: str + args: dict + ok: bool + report: dict + images: list = field(default_factory=list) + ended: bool = False + wall_s: float = 0.0 + sim_steps: int = 0 + + def text(self): + return json.dumps(self.report, separators=(", ", ": "), default=_json_default) + + +def _json_default(o): + if isinstance(o, (np.floating,)): + return float(o) + if isinstance(o, (np.integer,)): + return int(o) + if isinstance(o, np.ndarray): + return o.tolist() + if isinstance(o, (np.bool_,)): + return bool(o) + raise TypeError(type(o)) + + +def _r(v, nd=4): + return [round(float(x), nd) for x in v] + + +class ContactTracker: + """Collects the objects the robot touches. Contacts are checked after every MuJoCo substep (a control + step is 25 substeps; a fast push touches the object for less than one control step, so checking only at + control-step boundaries misses it -- measured). Implemented by wrapping `env.sim.step` once per env; the + wrapper only reads contacts and dispatches to the currently active tracker.""" + + def __init__(self, env): + self.env = env + m = env.sim.model + self.is_robot = np.zeros(m.ngeom, bool) + self.is_robot[envs.robot_geom_ids(env)] = True + self.names = [] + self.obj_of = np.full(m.ngeom, -1, int) + for name in list(env.objects_dict) + list(getattr(env, "fixtures_dict", {}) or {}): + try: + ids = envs.obj_geom_ids(env, name) + except Exception: # fixtures without contact geoms + continue + self.obj_of[ids] = len(self.names) + self.names.append(name) + self.touched = set() + sim = env.sim + if not getattr(sim, "_lff_step_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lff_tracker", None) + if t is not None: + t.check() + sim.step = step + sim._lff_step_wrapped = True + sim._lff_tracker = self + + def reset(self): + self.touched = set() + + def check(self): + d = self.env.sim.data + n = d.ncon + if not n: + return + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + hit = np.concatenate([self.obj_of[g2[self.is_robot[g1]]], self.obj_of[g1[self.is_robot[g2]]]]) + for i in set(hit[hit >= 0].tolist()): + self.touched.add(self.names[i]) + + +def parse_args(raw): + if raw is None: + return {} + if isinstance(raw, dict): + return dict(raw) + raw = raw.strip() + return json.loads(raw) if raw else {} + + +class ToolExecutor: + """Executes agent tool calls on a task whose instance has just been reset (task.sk is live).""" + + def __init__(self, task, inst, image_res=512, cams=("agentview", "wrist"), privileged_locate=False, + grasp_report="bool", jpeg_quality=90, image_sink=None): + self.task = task + self.inst = inst + self.env = task.env + self.sk = task.sk # keep our own reference: the scripted backend may swap task.sk for a proxy + self.image_res = int(image_res) + self.cams = tuple(cams) + self.privileged_locate = privileged_locate + self.grasp_report = grasp_report # "bool" | "name" | "none" + self.jpeg_quality = jpeg_quality + self.image_sink = image_sink # callable(ImageRef) -> path (saves the image) + self.objects = list(self.env.objects_dict) + self.tracker = ContactTracker(self.env) # task recorders / hooks on Skills are left untouched + self._depth_cache = {} + self.n_calls = 0 + + # ------------------------------------------------------------------ state + def eef_yaw_deg(self): + R = self.sk.eef_mat() @ self.sk.R0.T + return math.degrees(math.atan2(R[1, 0], R[0, 0])) + + def held(self): + names = [o for o in self.objects if self.sk.holding(o)] + return names + + def _holding_field(self, names): + if self.grasp_report == "name": + return names[0] if names else None + if self.grasp_report == "none": + return None + return bool(names) + + def proprio(self): + believed = self.sk.eef_pos() - self.sk.bias + p = dict(eef_pos=_r(believed), eef_yaw_deg=round(self.eef_yaw_deg(), 1), + gripper="closed" if self.sk.grip > 0 else "open", + gripper_width_m=round(self.sk.gripper_width(), 4)) + if self.grasp_report != "none": + p["holding_object"] = self._holding_field(self.held()) + return p + + def render(self, cam, res=None): + res = res or self.image_res + return envs.render(self.env, C.mj_cam(cam), res) + + def observe(self, label=""): + imgs = [] + for cam in self.cams: + ref = ImageRef(camera=cam, array=self.render(cam), label=f"{label} {cam}".strip()) + if self.image_sink is not None: + self.image_sink(ref) + imgs.append(ref) + self._depth_cache = {} + return imgs + + # ------------------------------------------------------------------ dispatch + def call(self, name, raw_args): + t0 = time.time() + n0 = self.sk.n_steps + self.n_calls += 1 + try: + args = parse_args(raw_args) + except Exception as e: + return ToolResult(name, {"_raw": str(raw_args)}, False, dict(ok=False, error=f"arguments are not valid JSON: {e}"), + wall_s=time.time() - t0) + fn = getattr(self, f"_t_{name}", None) + if fn is None or (name == "locate" and not self.privileged_locate): + return ToolResult(name, args, False, dict(ok=False, error=f"unknown tool {name!r}"), wall_s=time.time() - t0) + try: + res = fn(**args) + except TypeError as e: + res = ToolResult(name, args, False, dict(ok=False, error=f"bad arguments: {e}")) + except ValueError as e: + res = ToolResult(name, args, False, dict(ok=False, error=str(e))) + res.args = args + res.wall_s = time.time() - t0 + res.sim_steps = self.sk.n_steps - n0 + if res.sim_steps: + self._depth_cache = {} + hook = getattr(self.task, "on_agent_tool", None) + if hook is not None: + hook(self.inst, name, args, res.report) + drain = getattr(self.task, "drain_events", None) # task-side events (e.g. L6: an item slipped) + if drain is not None: + ev = drain() + if ev: + res.report["events"] = list(ev) + return res + + # ------------------------------------------------------------------ helpers + def _clip_xyz(self, xyz): + xyz = np.asarray(xyz, float) + if not np.all(np.isfinite(xyz)): + raise ValueError("non-finite coordinates") + c = np.clip(xyz, WS_LO, WS_HI) + return c, (None if np.allclose(c, xyz) else _r(c)) + + @staticmethod + def _clip(v, lo_hi, what): + v = float(v) + if not math.isfinite(v): + raise ValueError(f"{what} must be finite") + return float(np.clip(v, *lo_hi)) + + def _action_report(self, name, extra=None): + names = self.held() + rep = dict(ok=True, tool=name) + if extra: + rep.update(extra) + rep.update(self.proprio()) + if self.grasp_report == "name": + rep["touched_objects"] = sorted(self.tracker.touched) + elif self.grasp_report == "bool": + rep["touched_object"] = bool(self.tracker.touched) + rep["sim_time_s"] = round(self.sk.n_steps * 0.05, 2) + return rep + + # ------------------------------------------------------------------ tools + def _t_move_to(self, x, y, z, yaw, speed=None): + tgt, clipped = self._clip_xyz([x, y, z]) + spd = None if speed is None else self._clip(speed, SPEED_RANGE, "speed") + self.tracker.reset() + rep = self.sk.move_to(tgt, yaw=math.radians(float(yaw)), speed=spd) # Skills wraps yaw mod pi + extra = dict(reached=bool(rep["reached"]), yaw_used_deg=round(math.degrees(self.sk.yaw), 1)) + if clipped: + extra["target_clipped_to"] = clipped + return ToolResult("move_to", {}, True, self._action_report("move_to", extra)) + + def _t_open_gripper(self): + self.tracker.reset() + self.sk.set_gripper(False) + return ToolResult("open_gripper", {}, True, self._action_report("open_gripper")) + + def _t_close_gripper(self): + self.tracker.reset() + self.sk.set_gripper(True) + return ToolResult("close_gripper", {}, True, self._action_report("close_gripper")) + + def _t_push(self, x, y, dir_x, dir_y, distance, speed, z=None, runup=None): + d = np.array([float(dir_x), float(dir_y)]) + if not np.all(np.isfinite(d)) or np.linalg.norm(d) < 1e-6: + raise ValueError("push direction must be a non-zero vector") + start, clipped = self._clip_xyz([x, y, TABLE_Z + 0.02 if z is None else z]) + dist = self._clip(distance, PUSH_DIST_RANGE, "distance") + spd = self._clip(speed, SPEED_RANGE, "speed") + pre = 0.06 if runup is None else self._clip(runup, RUNUP_RANGE, "runup") + self.tracker.reset() + rep = self.sk.push(start[:2], d, dist, spd, z=float(start[2]), pre=pre) + extra = dict(sweep_reached=bool(rep["reached"])) + if clipped: + extra["start_clipped_to"] = clipped + return ToolResult("push", {}, True, self._action_report("push", extra)) + + def _t_get_observation(self): + imgs = self.observe(label="requested") + return ToolResult("get_observation", {}, True, dict(ok=True, images=[i.camera for i in imgs], **self.proprio()), + images=imgs) + + def _t_pixel_to_world(self, camera, u, v): + cam = str(camera) + if cam not in C.CAMERAS: + raise ValueError(f"camera must be one of {sorted(C.CAMERAS)}") + if cam not in self._depth_cache: + self._depth_cache[cam] = C.render_depth(self.env, cam, self.image_res) + r = C.pixel_to_world(self.env, cam, float(u), float(v), self.image_res, depth=self._depth_cache[cam]) + rep = dict(ok=True, camera=cam, u=float(u), v=float(v), world_xyz=_r(r["xyz"]), + height_above_table_m=round(float(r["xyz"][2] - TABLE_Z), 4), depth_m=round(r["depth"], 4)) + if not r["valid"]: + rep["warning"] = "pixel shows the far background; the point is unreliable" + return ToolResult("pixel_to_world", {}, True, rep) + + def _t_locate(self, object_name): + if object_name not in self.env.objects_dict: + raise ValueError(f"unknown object {object_name!r}; known: {self.objects}") + lo, hi = self._aabb(object_name) + p = envs.obj_pos(self.env, object_name) + return ToolResult("locate", {}, True, dict(ok=True, object=object_name, position=_r(p), bbox_min=_r(lo), + bbox_max=_r(hi))) + + def _aabb(self, name): + m, d = self.env.sim.model, self.env.sim.data + lo, hi = np.full(3, np.inf), np.full(3, -np.inf) + for g in envs.obj_geom_ids(self.env, name): + R = d.geom_xmat[g].reshape(3, 3) + c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3] + h = np.abs(R) @ m.geom_aabb[g, 3:] + lo, hi = np.minimum(lo, c - h), np.maximum(hi, c + h) + return lo, hi + + def _t_done(self, reason=""): + return ToolResult("done", {}, True, dict(ok=True, ended=True), ended=True) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/agent/__init__.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/agent/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8ffd9af077f968176127cbd3767912005f648ac3 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/agent/__init__.py @@ -0,0 +1 @@ +"""LFF-Bench agent harness: tool interface, context packing, model backends, protocol runner.""" diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/l5_iterative.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/l5_iterative.py new file mode 100644 index 0000000000000000000000000000000000000000..eec94ac61e9f0b98925237971a1da808aded8ef3 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/l5_iterative.py @@ -0,0 +1,136 @@ +"""[PARKED 2026-10-06 — fails acceptance: oracle 50% (n=12, k=3). The push response is not stationary: +the same commanded speed carries the cube 7.9 cm on one push and 11.4 cm on the next, because the arm reaches +different speeds at different extensions. Needs a configuration-independent striker before use.] + +L5-B iterative_push: several pushes in ONE episode (MemMimic "Iterative Pushing" analogue). + +The cube starts far from the target zone; each push is a straight strike away from the robot whose +only free parameter is the speed. Overshooting past the zone is unrecoverable (episode fails). +Hidden variable: cube-table friction mu, as in l5_slide_to_target. The information needed to choose +the next push (how far a push of a given speed carries the cube) is only available from the +outcomes of the previous pushes in the same episode -> within-episode learning from failure. + +"Attempt" granularity for the history: one push. +""" +import numpy as np + +from .. import envs +from ..task_base import register_task +from .l5_slide import CUBE_HALF, V_MAX, V_MIN, Z_PUSH, SlideToTarget + + +@register_task +class IterativePush(SlideToTarget): + name = "l5_iterative_push" + level = "L5" + capabilities = ("Reason", "Save", "Utilize") + protocol = "within" + max_attempts = 3 # pushes per episode: too few to creep up on the target with small taps + instruction = ("Push the red cube away from the robot so that it comes to rest inside the green target zone. " + "You have at most three separate pushes. If the cube passes the zone, the task fails.") + instruction_indirect = instruction + tol_along = 0.015 + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + return dict(seed=int(seed), + cube_xy=[float(rng.uniform(-0.27, -0.23)), float(rng.uniform(-0.08, 0.08))], + target_dist=float(rng.uniform(0.22, 0.30)), + mu=float(np.exp(rng.uniform(np.log(0.035), np.log(0.08))))) + + def make_bddl(self): + return super().make_bddl() + + # --------------------------------------------------------------- one push from the current cube pose + def push_once(self, inst, speed): + c = envs.obj_pos(self.env, "cube_1") + x, y = c[0], c[1] + sk = self.sk + sk.set_gripper(True, steps=3) + sk.move_to([x - self.runup, y, Z_PUSH + 0.10], yaw=0.0) + sk.move_to([x - self.runup, y, Z_PUSH], tol=0.003) + sk.move_to([x - CUBE_HALF + 0.015, y, Z_PUSH], speed=float(np.clip(speed, V_MIN, V_MAX)), tol=0.01, + max_steps=80) + sk.move_to([x - CUBE_HALF + 0.015, y, Z_PUSH + 0.10], speed=0.3) + envs.settle(self.env, 40) + c1 = envs.obj_pos(self.env, "cube_1") + return float(c1[0] - x) + + def outcome(self, inst): + x0, y0 = inst["cube_xy"] + c = envs.obj_pos(self.env, "cube_1") + along = (c[0] - x0) - inst["target_dist"] + across = c[1] - y0 + success = bool(abs(along) <= self.tol_along and abs(across) <= self.tol_across and c[2] > envs.TABLE_Z) + overshoot = bool(along > self.tol_along) + if success: + detail = "The cube is inside the target zone." + elif overshoot: + detail = f"The cube passed the target zone: it is {100 * along:.1f} cm beyond its centre. The task has failed." + else: + detail = f"The cube is {100 * -along:.1f} cm short of the centre of the target zone." + return dict(success=success, overshoot=overshoot, along_err=float(along), across_err=float(across), + detail=detail) + + # --------------------------------------------------------------- scripted references + S0 = 0.02 # distance the cube travels during the contact stroke itself + + def _plan_speed(self, remaining, model, pushes_left=1): + """Model: push distance d(v) = s0 + k v^2. With more than one push left, cover all but a short + final leg (a short push is more predictable); with one push left, aim at the zone centre.""" + if model is None: + return 0.30 + s0, k = model + goal = remaining if pushes_left <= 1 else max(remaining - 0.07, 0.0) + v = np.sqrt(max(goal - s0, 0.0) / max(k, 1e-6)) + return float(np.clip(v, V_MIN, V_MAX)) + + @classmethod + def _fit(cls, pts): + """pts: [(v, d)]. One point -> fix s0; two or more -> least squares on (s0, k).""" + if len(pts) == 1: + v, d = pts[0] + return cls.S0, max(d - cls.S0, 1e-4) / v ** 2 + A = np.array([[1.0, v ** 2] for v, _ in pts]) + b = np.array([d for _, d in pts]) + s0, k = np.linalg.lstsq(A, b, rcond=None)[0] + if k <= 0: + return cls.S0, max(np.mean(b) - cls.S0, 1e-4) / np.mean([v ** 2 for v, _ in pts]) + return float(np.clip(s0, 0.0, 0.05)), float(k) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + self.reset_instance(inst) + history = [] + model = None + if kind == "oracle": + model = self._oracle_model(inst) + for a in range(k): + out0 = self.outcome(inst) + remaining = -out0["along_err"] + if kind == "naive" or kind == "blind": + speed = 0.30 if kind == "naive" else float(np.clip(0.30 + rng.normal(0, 0.05), V_MIN, V_MAX)) + if remaining < 0.06: # naive heuristic: tap gently near the end + speed = 0.20 + else: + speed = self._plan_speed(remaining, model, pushes_left=k - a) + moved = self.push_once(inst, speed) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=dict(speed=speed), outcome=dict(out, moved=moved))) + if kind == "adaptive" and moved > 0.005: + pts = [(h["params"]["speed"], h["outcome"]["moved"]) for h in history if h["outcome"]["moved"] > 0.005] + model = self._fit(pts) + if out["success"] or out["overshoot"]: + break + # mark only the final state as the episode outcome + return history + + def _oracle_model(self, inst): + """Privileged: measure the push model with the true mu in scratch rollouts.""" + pts = [] + for v in (0.2, 0.35, 0.5): + self.reset_instance(inst) + pts.append((v, self.push_once(inst, v))) + self.reset_instance(inst) + return self._fit(pts) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/agent_compare.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/agent_compare.py new file mode 100644 index 0000000000000000000000000000000000000000..4f53b5126adc0eadae0498f1de5e8a3fd60f0cdb --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/agent_compare.py @@ -0,0 +1,40 @@ +"""ΔICL between two agent run directories on the same seeds. + + python scripts/agent_compare.py --with runs/agent// --iid runs/agent// + +ΔICL = succ@k(with history) - pass@k_iid(independent retries), paired by instance seed, with a paired +bootstrap 95% interval. Also prints the analytic i.i.d. reference 1-(1-p1)^k from the 'with' run. +""" +import argparse +import json +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from lffbench.agent.metrics import paired_delta # noqa: E402 + + +def load(d): + with open(os.path.join(d, "summary.json")) as f: + return json.load(f) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--with", dest="with_", required=True) + ap.add_argument("--iid", required=True) + ap.add_argument("--k", type=int, default=None) + a = ap.parse_args() + w, i = load(a.with_), load(a.iid) + k = a.k or min(w["k"], i["k"]) + res = paired_delta(w["runs"], i["runs"], k) + res["k"] = k + res["with"] = dict(memory=w["memory"], feedback=w["feedback"], attempt1=w["aggregate"]["attempt1_success"], + pass_at_k_iid_analytic=w["aggregate"]["pass_at_k_iid_analytic"]) + res["iid"] = dict(memory=i["memory"], feedback=i["feedback"]) + print(json.dumps(res, indent=1)) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/check_breakfast_mechanisms.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/check_breakfast_mechanisms.py new file mode 100644 index 0000000000000000000000000000000000000000..64994a6c04651a3a106850a61e337a9c2bff29b6 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/check_breakfast_mechanisms.py @@ -0,0 +1,79 @@ +"""Mechanism-on/off controls and negative judge fixtures, separate from rollouts.""" +import argparse, copy, json +from pathlib import Path +import numpy as np +from lffbench.tasks.lh_breakfast_service import BreakfastService +from lffbench import envs + +def main(): + p=argparse.ArgumentParser();p.add_argument('--liquid-only',action='store_true') + p.add_argument('--judge-only',action='store_true');args=p.parse_args() + out=Path(__file__).resolve().parents[1]/'results/lh_breakfast_service/mechanisms' + out.mkdir(parents=True,exist_ok=True);t=BreakfastService();rows=[] + if args.judge_only:rows=json.loads((out/'controls_progress.json').read_text()) + for seed in ([] if args.liquid_only or args.judge_only else range(1000,1003)): + for enabled in (True,False): + inst=t.sample_instance(seed);inst['mechanisms']['L1']=enabled;t.reset_instance(inst) + t.calibration_probe();row=dict(seed=seed,mechanism='L1',enabled=enabled,triggered=t.traps['L1']) + rows.append(row);print(json.dumps(row),flush=True) + assert row['triggered']==enabled,row + inst=t.sample_instance(seed);inst['mechanisms']['L3']=enabled;t.reset_instance(inst);t.sk.correction=t.sk.bias.copy() + t.direct_carton_lift();row=dict(seed=seed,mechanism='L3',enabled=enabled,**t.pull_probe) + rows.append(row);print(json.dumps(row),flush=True) + assert row['held_before'] and ((row['displacement_m']<.01) if enabled else (row['displacement_m']>.04)),row + inst=t.sample_instance(seed);inst['mechanisms']['L2']=enabled;t.reset_instance(inst);t.sk.correction=t.sk.bias.copy() + for _ in range(2):t.open_lid();t.close_lid(False) + t.sk.hold(300);failure=t.lid_deg() + if enabled:t.open_lid();t.close_lid(True);t.sk.hold(300) + row=dict(seed=seed,mechanism='L2',enabled=enabled,lid_after_quick_closes=failure,final_lid=t.lid_deg()) + rows.append(row);print(json.dumps(row),flush=True) + assert (failure>10 if enabled else failure<4) and row['final_lid']<4,row + (out/'controls_progress.json').write_text(json.dumps(rows,indent=2)) + liquid_controls=json.loads((out/'liquid_controls.json').read_text()) if args.judge_only else [] + for case in ([] if args.judge_only else ('upright','tilted_aligned','tilted_misaligned')): + inst=t.sample_instance(1000);t.reset_instance(inst) + if case!='upright':t.env.sim.data.qpos[t.pour_qa]=1.35 + if case=='tilted_misaligned':t.env.sim.model.body_pos[t.cup_bid,0]+=.20 + t.env.sim.forward();t.sk.hold(160) + q=t.liquid;inflight=sum(p['ml'] for p in q['parcels']) + row=dict(case=case,cup_ml=q['cup'],spill_ml=q['spill'],reservoir_ml=q['reservoir'], + conservation_error_ml=abs(300-q['cup']-q['spill']-q['reservoir']-inflight)) + liquid_controls.append(row);print(json.dumps(row),flush=True) + assert row['conservation_error_ml']<1e-8,row + if case=='upright':assert q['cup']==q['spill']==0,row + elif case=='tilted_aligned':assert q['cup']>=179 and q['spill']>50,row + else:assert q['cup']==0 and q['spill']>200,row + if args.liquid_only: + (out/'liquid_controls.json').write_text(json.dumps(liquid_controls,indent=2)) + t.env.close();return + # Obtain a successful physical endpoint before mutating diagnostic scoring fixtures. + inst=t.sample_instance(1000);t.reset_instance(inst);t.execute(inst,{'mode':'oracle'});baseline=t.outcome(inst) + assert baseline['success'],baseline + state=copy.deepcopy(t.env.sim.get_state());liquid=copy.deepcopy(t.liquid) + mon=copy.deepcopy(t.mon);closes=t.closes_done;latch=t.active_latch + negatives=[] + for case in ('no_milk','too_much_milk','spill','bread_off_plate','butter_outside','lid_open','carton_tilted','gripper_closed'): + t.env.sim.set_state(state);t.env.sim.forward();t.liquid=copy.deepcopy(liquid);t.sk.grip=-1.;t.drift_active=False + t.mon=copy.deepcopy(mon);t.closes_done=closes;t.active_latch=latch + if case=='no_milk':t.liquid['reservoir']+=t.liquid['cup'];t.liquid['cup']=0 + elif case=='too_much_milk': + t.liquid['reservoir']-=175-t.liquid['cup'];t.liquid['cup']=175 + elif case=='spill':t.liquid['reservoir']-=25;t.liquid['spill']=25;t.liquid['spill_xy']=[.2,0] + elif case=='bread_off_plate':envs.set_obj_pose(t.env,'bread_1',[-.30,.03,.912]) + elif case=='butter_outside':envs.set_obj_pose(t.env,'butter_1',[-.35,-.32,.914]) + elif case=='lid_open':t.env.sim.data.qpos[t.qa]=1.0 + elif case=='carton_tilted':t.env.sim.data.qpos[t.pour_qa]=1.35 + elif case=='gripper_closed':t.sk.grip=1. + t.env.sim.forward();result=t.outcome(inst) + negatives.append(dict(case=case,accepted=result['success'],failure=result['failure'],stages=result['stages'])) + print(json.dumps(negatives[-1],default=lambda v:v.item()),flush=True) + predicate={'no_milk':'milk_served','too_much_milk':'milk_served','spill':'spill_ok', + 'bread_off_plate':'bread_on_plate','butter_outside':'butter_in_box','lid_open':'lid_closed', + 'carton_tilted':'carton_upright','gripper_closed':'gripper_open'}[case] + assert not result['success'] and not result['stages'][predicate],case + data=dict(controls=rows,liquid_controls=liquid_controls,negative_fixtures=negatives, + scope='Controlled interventions are diagnostics, not agent rollouts') + (out/'result.json').write_text(json.dumps(data,indent=2,default=lambda v:v.item())) + t.env.close() + +if __name__=='__main__':main() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/full_report.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/full_report.py new file mode 100644 index 0000000000000000000000000000000000000000..517955b7426d6e4e08a16504d9451a7c2689d873 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/full_report.py @@ -0,0 +1,89 @@ +"""Summarise a full run (all tasks x harnesses) from the robot-server logs only, so every harness is measured +the same way. + +python scripts/full_report.py --batch full1 [--out ../docs/full1_table.md] + +Per run: outcome of every attempt, attempts used, robot commands, close_gripper calls that ended holding an +object, "empty done" attempts (the agent ended an attempt without a single move / gripper command in it), and +wall time from the first to the last server request. +""" +import argparse +import collections +import json +import os + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +LEVEL = {"l1": "L1", "l2": "L2", "l3": "L3", "l4": "L4", "l5": "L5", "l6": "L6", "l7": "L7"} +HARNESS_NAME = {"gpt_player": "ours", "rpent": "RPent", "gptpolicy": "GPT-Policy", "claude": "ours (Claude CLI)"} + + +def run_info(r): + ev = [json.loads(l) for l in open(os.path.join(r["log"], "events.jsonl"))] + calls = [e for e in ev if e["ev"] == "call"] + dones = [e for e in ev if e["ev"] == "done"] + http = [e for e in ev if e["ev"] == "http"] + # v1: move_to / open_gripper / close_gripper; v2 and la: move_eef [gripper=open|close] (holding is only in `raw`, + # the agent never sees it) + acts_per_attempt = collections.Counter(e["attempt"] for e in calls if e["cmd"] in ("move_to", "open_gripper", "close_gripper") + or (e["cmd"] == "move_eef" and (e.get("report") or {}).get("ok"))) + empty = sum(1 for d in dones if acts_per_attempt.get(d["attempt"], 0) == 0) + closes = [e for e in calls if e["cmd"] == "close_gripper" + or (e["cmd"] == "move_eef" and (e.get("args") or {}).get("gripper") == "close" and (e.get("report") or {}).get("ok"))] + held = sum(1 for e in closes if (e.get("report") or {}).get("holding_object") or (e.get("raw") or {}).get("holding_object")) + first = next((d["attempt"] for d in dones if d["success"]), None) + wall = (http[-1]["t_send"] - http[0]["t_recv"]) / 60 if http else None + return dict(outcomes="".join("S" if d["success"] else "F" for d in dones), attempts=len(dones), first=first, + cmds=len(calls), closes=len(closes), held=held, empty=empty, wall=wall) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--batch", default="full1") + ap.add_argument("--out", default=None) + ap.add_argument("--runs", default="gpt", help="runs///manifest.json (gpt or claude)") + a = ap.parse_args() + m = json.load(open(os.path.join(ROOT, "runs", a.runs, a.batch, "manifest.json"))) + rows = {} + for r in m["runs"]: + try: + h = r.get("harness") or ("claude" if r.get("cond") in ("harness", "noharness") else "gpt_player") + rows[(r["task"], h)] = dict(run_info(r), k=r["k"]) + except FileNotFoundError: + pass + tasks = sorted({t for t, _ in rows}, key=lambda t: (t[:2], t)) + hs = [h for h in ("gpt_player", "rpent", "gptpolicy", "claude") if any(k[1] == h for k in rows)] + L = [f"# {a.batch}: one run per task x harness (see manifest for model / perception / style)", "", + "Cell = outcome of each attempt (S success, F failure); `·` = run missing. Measured from robot-server logs.", "", + "| task | level | " + " | ".join(HARNESS_NAME[h] for h in hs) + " |", "|---|---|" + "---|" * len(hs)] + for t in tasks: + cells = [] + for h in hs: + x = rows.get((t, h)) + cells.append("·" if x is None else (x["outcomes"] or "—")) + L.append(f"| {t} | {LEVEL.get(t[:2], '?')} | " + " | ".join(cells) + " |") + L += ["", "| harness | runs | success @1 | success @3 | grasps held / close_gripper | empty-done attempts | " + "commands / attempt | wall min / run |", "|---|---|---|---|---|---|---|---|"] + for h in hs: + xs = [x for (t, hh), x in rows.items() if hh == h and x["attempts"] > 0] + n = len(xs) + att = sum(x["attempts"] for x in xs) + L.append(f"| {HARNESS_NAME[h]} | {n} | {sum(1 for x in xs if x['first'] == 1)} | " + f"{sum(1 for x in xs if x['first'])} | {sum(x['held'] for x in xs)} / {sum(x['closes'] for x in xs)} | " + f"{sum(x['empty'] for x in xs)} / {att} | {sum(x['cmds'] for x in xs) / max(att, 1):.1f} | " + f"{sum(x['wall'] or 0 for x in xs) / max(n, 1):.0f} |") + by_level = collections.defaultdict(lambda: [0, 0]) + for (t, h), x in rows.items(): + if x["attempts"]: + by_level[LEVEL.get(t[:2], "?")][0] += bool(x["first"]) + by_level[LEVEL.get(t[:2], "?")][1] += 1 + L += ["", "Success @3 by level (all harnesses pooled): " + + ", ".join(f"{lv} {s}/{n}" for lv, (s, n) in sorted(by_level.items()))] + txt = "\n".join(L) + print(txt) + if a.out: + with open(a.out, "w") as f: + f.write(txt + "\n") + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/harness_run.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/harness_run.py new file mode 100644 index 0000000000000000000000000000000000000000..90c518dbaae11f1096d2f1a97627dbaf3957d9d3 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/harness_run.py @@ -0,0 +1,431 @@ +"""Run one robot_server session (style la) with one agent harness through its adapter (lffbench/harnesses, docs/15). + + python scripts/harness_run.py --harness claude_code --session runs/<...>/session.json --model claude-sonnet-5-5 --effort high + python scripts/harness_run.py --harness codex --session ... --model gpt-6-astra --effort high + python scripts/harness_run.py --harness ours --session ... --provider anthropic --model ... --effort high + +Harnesses: ours (scripts/api_player.py, unchanged), claude_code (arm B, --bare), claude_code_full (arm B', no --bare), +codex (arm F), rpent_codex (RPent, a robot harness framework, on the same Codex; tools through the episode's tool +gateway, lffbench/harnesses/rpent.py). Native harnesses get the reference driver's instructions + first status report as their first user +message (byte-identical README), only our MCP server (scripts/mcp_robot_server.py) as tools, a one-time HOME / config +dir, an opaque work dir /tmp/lffrun/<12 hex> and a process environment that is exactly a whitelist. + +API variables (never inherited from the calling Claude Code / Codex session): + claude_code*: --claude-auth oauth (default for claude_code_full): a Claude subscription, the long-lived token of + `claude setup-token` from LFF_CLAUDE_OAUTH_TOKEN or the KEY=value file LFF_CLAUDE_OAUTH_FILE (key + LFF_CLAUDE_OAUTH_TOKEN or CLAUDE_CODE_OAUTH_TOKEN), passed as CLAUDE_CODE_OAUTH_TOKEN; + --claude-auth apikey (default and only choice for claude_code, which is --bare): key + LFF_ANTHROPIC_API_KEY or ANTHROPIC_API_KEY; + endpoint --api-base-url or LFF_ANTHROPIC_BASE_URL (default: the CLI's own default, the official API) + codex: --codex-provider deepseek: DeepSeek's Responses endpoint (https://api.deepseek.com/), key + LFF_DEEPSEEK_API_KEY or DEEPSEEK_API_KEY (passed to Codex as its provider's OPENAI_API_KEY); + --codex-provider opencode: OpenCode Go's Responses endpoint (OPENCODE_GO_URL), key LFF_OPENCODE_API_KEY + or OPENCODE_API_KEY (the model gateway adds the x-opencode-session header OpenCode Go requires); + --codex-auth chatgpt (default): the ChatGPT subscription login of LFF_CODEX_AUTH_HOME / CODEX_HOME + (a copy of its auth.json, no API key; endpoint the ChatGPT Codex backend unless --api-base-url); + --codex-auth apikey: key LFF_OPENAI_API_KEY or OPENAI_API_KEY; endpoint --api-base-url, + LFF_OPENAI_BASE_URL or OPENAI_BASE_URL (as api_player), else https://api.openai.com/v1 + dsh: DeepSeek's Messages endpoint (DEEPSEEK_ANTHROPIC_URL), or --api-base-url / LFF_DSH_BASE_URL (OpenCode Go: + https://opencode.ai/inference/go), key LFF_DEEPSEEK_API_KEY or DEEPSEEK_API_KEY (passed as DEEPSEEK_API_KEY) + ours: as api_player.py (its own environment) + +Writes into the run's log dir: contract.json, first_message.txt, harness.json (harness name, version, argv with the +first message replaced by its sha256, env key names, contract_sha256, first_message_sha256, config_sha256, preflight +result), harness_preflight.json (full normalised fingerprint), the native event stream, trajectory.jsonl, +harness_audit.json. Exit codes: 0 done, 2 refused at launch (fail-closed), 3 harness error, 143 stopped. +""" +import argparse +import json +import os +import signal +import sys +import time +import traceback + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) +from lffbench.harnesses import NAMES, ROBOT_HARNESSES, PROVIDER, EpisodeSpec, HarnessRefused, get_adapter, render_first_message # noqa: E402 +from lffbench.harnesses import contract as C # noqa: E402 +from lffbench.harnesses import redteam as RT # noqa: E402 + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from api_player import MAX_NO_TOOL, call_server, continue_nudge # noqa: E402 +from tool_gateway import start_gateway, stop_gateway # noqa: E402 +import model_gateway as MG # noqa: E402 + +ANTHROPIC_API = "https://api.anthropic.com" + + +def claude_oauth_token(): + """The subscription token for claude_code_full --claude-auth oauth: LFF_CLAUDE_OAUTH_TOKEN, else the KEY=value + file LFF_CLAUDE_OAUTH_FILE. Never CLAUDE_CODE_OAUTH_TOKEN of the calling environment (that may be the calling + Claude Code session's own login).""" + tok = os.environ.get("LFF_CLAUDE_OAUTH_TOKEN") + if tok: + return tok.strip() + path = os.environ.get("LFF_CLAUDE_OAUTH_FILE") + if path and os.path.isfile(path): + for line in open(path): + k, _, v = line.strip().partition("=") + if k.strip().removeprefix("export ").strip() in ("LFF_CLAUDE_OAUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN") and v: + return v.strip().strip("'\"") + raise SystemExit("claude --claude-auth oauth: no token; run `claude setup-token` and put LFF_CLAUDE_OAUTH_TOKEN=... " + "into the file named by LFF_CLAUDE_OAUTH_FILE (or export LFF_CLAUDE_OAUTH_TOKEN)") + + +def default_claude_auth(harness): + return "apikey" if harness == "claude_code" else "oauth" + + +def api_env_for(harness, base_url, codex_auth="apikey", claude_auth="apikey", codex_provider="openai"): + """-> (variables passed to the harness, endpoint or None, endpoint label for harness.json). Endpoints are never + written to the logs, only where they came from.""" + if harness in ROBOT_HARNESSES: + if harness == "rpent_codex": + codex_auth = "apikey" # historical RPent implementation stays unchanged + harness = "codex" + if harness.startswith("claude_code"): + e = {} + if claude_auth == "oauth": + e["CLAUDE_CODE_OAUTH_TOKEN"] = claude_oauth_token() + else: + key = os.environ.get("LFF_ANTHROPIC_API_KEY") or os.environ.get("ANTHROPIC_API_KEY") + if key: + e["ANTHROPIC_API_KEY"] = key + url = base_url or os.environ.get("LFF_ANTHROPIC_BASE_URL") + if url: + e["ANTHROPIC_BASE_URL"] = url + dflt = "CLI default (official)" + (", subscription token" if claude_auth == "oauth" else "") + return e, url, ("--api-base-url" if base_url else "LFF_ANTHROPIC_BASE_URL") if url else dflt + if harness == "dsh": + key = os.environ.get("LFF_DEEPSEEK_API_KEY") or os.environ.get("DEEPSEEK_API_KEY") + from lffbench.harnesses.dsh import DEEPSEEK_ANTHROPIC_URL + url = base_url or os.environ.get("LFF_DSH_BASE_URL") + return ({"DEEPSEEK_API_KEY": key} if key else {}), url or DEEPSEEK_ANTHROPIC_URL, \ + ("--api-base-url" if base_url else "LFF_DSH_BASE_URL") if url else \ + "DeepSeek (DEEPSEEK_ANTHROPIC_URL, key LFF_DEEPSEEK_API_KEY / DEEPSEEK_API_KEY)" + if harness == "codex" and codex_provider == "deepseek": # DeepSeek's own Responses endpoint, an API key + key = os.environ.get("LFF_DEEPSEEK_API_KEY") or os.environ.get("DEEPSEEK_API_KEY") + from lffbench.harnesses.codex import DEEPSEEK_URL + return ({"OPENAI_API_KEY": key} if key else {}), base_url or DEEPSEEK_URL, \ + "--api-base-url" if base_url else "DeepSeek (DEEPSEEK_URL, key LFF_DEEPSEEK_API_KEY / DEEPSEEK_API_KEY)" + if harness == "codex" and codex_provider == "opencode": # OpenCode Go's Responses endpoint, an API key + key = os.environ.get("LFF_OPENCODE_API_KEY") or os.environ.get("OPENCODE_API_KEY") + from lffbench.harnesses.codex import OPENCODE_GO_URL + return ({"OPENAI_API_KEY": key} if key else {}), base_url or OPENCODE_GO_URL, \ + "--api-base-url" if base_url else "OpenCode Go (OPENCODE_GO_URL, key LFF_OPENCODE_API_KEY / OPENCODE_API_KEY)" + if harness == "codex" and codex_auth == "chatgpt": + return {}, base_url, "--api-base-url" if base_url else "ChatGPT Codex backend (subscription login)" + if harness == "codex": + key = os.environ.get("LFF_OPENAI_API_KEY") or os.environ.get("OPENAI_API_KEY") + src = ("--api-base-url" if base_url else "LFF_OPENAI_BASE_URL" if os.environ.get("LFF_OPENAI_BASE_URL") + else "OPENAI_BASE_URL (same as api_player)" if os.environ.get("OPENAI_BASE_URL") else "official default") + url = base_url or os.environ.get("LFF_OPENAI_BASE_URL") or os.environ.get("OPENAI_BASE_URL") + return ({"OPENAI_API_KEY": key} if key else {}), url, src + return {}, None, "api_player's own environment" + + +RESUME_RETRIES = 3 # a resumed CLI that exits before writing any event is started again (nothing reached the model) + + +def mcp_tool_state(log_dir): + """-> (number of MCP tool calls so far, whether our MCP server saw the episode end) from mcp_transcript.jsonl.""" + n, finished = 0, False + try: + for line in open(os.path.join(log_dir, "mcp_transcript.jsonl")): + try: + d = json.loads(line) + except ValueError: + continue + if d.get("ev") == "tool": + n, finished = n + 1, bool(d.get("finished")) + except OSError: + pass + return n, finished + + +def continue_episode(ad, h, ep, stop): + """The CLI exited although the episode is not over (it ends when the model replies without a tool call): send + the reference driver's nudge as a user turn, as api_player does after such a reply, and wait again. Same rule: + after MAX_NO_TOOL nudges in a row without a tool call in between, the next such reply ends the run. -> log list.""" + out, no_tool, (n_calls, _) = [], 0, mcp_tool_state(ep.log_dir) + deadline = h.t_start + h.spec.timeout_s + while ad.can_resume and h.exit_reason == "exited" and not stop["flag"]: + n, finished = mcp_tool_state(ep.log_dir) + if finished: # api_player stops here too, without a status call + break + try: # the status call api_player makes for its nudge + stx = json.loads(call_server(ep.port, ep.token, "status", {})) + except Exception as e: + out.append(dict(ev="status_failed", error=f"{type(e).__name__}: {e}"[:300], t=time.time())) + break + if stx.get("finished"): + break + no_tool = 1 if n > n_calls else no_tool + 1 + n_calls = n + if no_tool > MAX_NO_TOOL: + out.append(dict(ev="abort", reason=f"no tool call {no_tool} times", t=time.time())) + break + if time.time() >= deadline: + h.exit_reason = "timeout" + break + msg = continue_nudge(ep.port, ep.token, stx) + out.append(dict(ev="resume", message=msg, attempt=stx.get("attempt"), mcp_tool_calls=n, t=time.time())) + for retry in range(RESUME_RETRIES + 1): + size0 = os.path.getsize(h.spec.stdout_path) if os.path.exists(h.spec.stdout_path) else 0 + ad.resume(h, msg) + ad.wait(h, timeout=max(1.0, deadline - time.time())) + grew = os.path.exists(h.spec.stdout_path) and os.path.getsize(h.spec.stdout_path) > size0 + if h.exit_reason == "exited" or grew or stop["flag"] or retry == RESUME_RETRIES \ + or time.time() + 30 >= deadline: + break + # the resumed CLI exited before writing any event (2026-10-20: the MCP handshake timed out on a loaded + # machine), so nothing reached the model: start the same resume again + out.append(dict(ev="resume_retry", exit_reason=h.exit_reason, t=time.time())) + time.sleep(30) + return out + + +def model_upstream(harness, url, codex_auth): + """-> (gateway kind, the model API the harness would call without the gateway).""" + if harness.startswith("claude_code") or harness == "dsh": + return "anthropic", url or ANTHROPIC_API + from lffbench.harnesses.codex import CHATGPT_BACKEND, OFFICIAL_API + if harness == "rpent_codex": + return "openai", url or OFFICIAL_API + return "openai", url or (CHATGPT_BACKEND if codex_auth == "chatgpt" else OFFICIAL_API) + + +def plain_config_sha256(ad, spec, ep, mg): + """config_sha256 as if the harness called its model API directly: the model gateway is plumbing (like the + proxy variables, base.py PROXY_KEYS), so runs with and without it keep the same configuration hash.""" + if not mg: + return ad.config_sha256(spec, ep) + import copy + s2 = copy.copy(spec) + s2.argv = [a.replace(mg["url"], mg["upstream"]) if isinstance(a, str) else a for a in spec.argv] + s2.env = {k: (v.replace(mg["url"], mg["upstream"]) if isinstance(v, str) else v) for k, v in spec.env.items()} + return ad.config_sha256(s2, ep) + + +def write_json(path, d): + tmp = path + ".tmp" + with open(tmp, "w") as f: + json.dump(d, f, indent=1, ensure_ascii=False, default=str) + os.replace(tmp, path) + + +def run(a, adapter_kw=None): + """Returns (exit code, harness.json dict). adapter_kw overrides adapter construction (self-check).""" + provider = a.provider or PROVIDER.get(a.harness, "") + ep = EpisodeSpec.from_session(a.session, a.model, a.effort, provider) + if getattr(a, "red_team", False): # before the contract: red-team runs get their own contract_sha256 + if a.harness == "ours": + raise SystemExit("--red-team is for native harnesses") + RT.mark(ep.log_dir) + contract, csha = C.write_contract(ep.log_dir) + mg_box = {} # the model gateway process, stopped whatever happens below + try: + return _run(a, adapter_kw, provider, ep, csha, mg_box) + finally: + MG.stop_model_gateway(mg_box.get("proc")) + + +def _run(a, adapter_kw, provider, ep, csha, mg_box): + mg = None + if adapter_kw is None: + a.codex_auth = getattr(a, "codex_auth", None) or ("apikey" if a.harness in ROBOT_HARNESSES else "chatgpt") + if a.harness == "rpent_codex" and a.codex_auth != "apikey": + raise SystemExit("Historical RPent adapter supports apikey only") + claude_auth = getattr(a, "claude_auth", None) or default_claude_auth(a.harness) + if getattr(a, "codex_provider", "openai") in ("deepseek", "opencode"): + a.codex_auth = "apikey" # no subscription login for DeepSeek / OpenCode Go + api_env, url, endpoint = api_env_for(a.harness, a.api_base_url, getattr(a, "codex_auth", "apikey"), + claude_auth, getattr(a, "codex_provider", "openai")) + if a.harness != "ours" and not getattr(a, "no_model_gateway", False): + # the harness reaches its model API only through the model gateway (scripts/model_gateway.py) + kind, upstream = model_upstream(a.harness, url, a.codex_auth) + mg_box["proc"], mginfo = MG.start_model_gateway(upstream, kind, ep.log_dir, + getattr(a, "token_budget_in", None), + getattr(a, "token_budget_out", None), + allow_files=a.harness == "dsh") + mg = dict(url=mginfo["url"], upstream=upstream, kind=kind, upstream_host=mginfo["upstream_host"], + pid=mginfo["pid"]) + url = mg["url"] + if a.harness.startswith("claude_code"): + api_env["ANTHROPIC_BASE_URL"] = url + adapter_kw = dict(timeout_s=a.timeout) + if a.harness.startswith("claude_code"): + adapter_kw.update(api_env=api_env, max_budget_usd=a.max_budget_usd, allow_unpinned=a.allow_unpinned, + auth=claude_auth) + elif a.harness == "codex": + adapter_kw.update(api_env=api_env, base_url=url, allow_unpinned=a.allow_unpinned, auth=a.codex_auth, + catalog=a.codex_catalog) + elif a.harness == "dsh": + adapter_kw.update(api_env=api_env, base_url=url, allow_unpinned=a.allow_unpinned) + elif a.harness in ROBOT_HARNESSES: + adapter_kw.update(api_env=api_env, base_url=url, allow_unpinned=a.allow_unpinned, + auth=a.codex_auth, catalog=a.codex_catalog) + if a.harness == "rpent_codex": # historical, explicitly exposed RPent experiment settings + adapter_kw.update(sessions=a.rpent_sessions, attempts_per_session=a.rpent_attempts_per_session, + max_turns=a.rpent_max_turns) + if getattr(a, "jail", False): + if a.harness == "ours": + raise SystemExit("--jail is for native harnesses") + adapter_kw["jail"] = True + else: + adapter_kw.update(provider=provider) + else: + endpoint = "set by the caller (self-check)" + ad = get_adapter(a.harness, **adapter_kw) + ver = ad.version() + hj_path = os.path.join(ep.log_dir, "harness.json") + hj = dict(harness=ad.name, version=ver.get("version"), binary=ver.get("binary"), model=a.model, effort=a.effort, + provider=provider, capabilities={k: vars(c) for k, c in ad.capabilities.items()}, + contract_sha256=csha, task=ep.task, seed=ep.seed, api_endpoint_from=endpoint, status="preparing", + t_prepare=time.time(), jail=ad.jail_info(), auth=ad.auth_info() if ad.name != "ours" else None, + config=ad.config_info() if hasattr(ad, "config_info") else None, + model_gateway=({k: mg[k] for k in ("kind", "upstream_host", "pid")} if mg else None)) + if ad.name == "ours": + first = None + spec = ad.prepare(ep) + else: + first, _ = render_first_message(ep) + if getattr(a, "red_team", False): + first = RT.first_message(first) + hj["red_team"] = RT.marker(ep.log_dir) + with open(os.path.join(ep.log_dir, "first_message.txt"), "w") as f: + f.write(first) + spec = ad.prepare(ep, first, **(dict(reuse_state=a.reuse_state) if getattr(a, "reuse_state", None) else {})) + hj["first_message_sha256"] = C.sha256_text(first) + hj.update(argv=ad.logged_argv(spec), cwd=spec.cwd, env_keys=sorted(spec.env), + env_mode="exact whitelist (Popen env=, same as env -i)" if ad.name != "ours" else "inherited (own code)", + state_dirs=spec.state_dirs, config_sha256=plain_config_sha256(ad, spec, ep, mg), status="launching") + write_json(hj_path, hj) + h, code, gw = None, 0, None + stop = dict(flag=False) + + def on_term(*_): + stop["flag"] = True + if h is not None and h.proc is not None: + ad.kill(h) + signal.signal(signal.SIGTERM, on_term) + try: + if (ad.uses_mcp or ad.uses_gateway) and not getattr(a, "no_gateway", False): # the episode's tools, for + # every MCP process of the run / every SDK client of a framework adapter (base.HarnessAdapter.uses_gateway) + gw, ginfo = start_gateway(ep.session_path) + hj["gateway"] = dict(url=ginfo["url"], pid=ginfo["pid"]) + try: + h = ad.launch(spec, ep, skip_preflight=getattr(a, "skip_preflight", False)) + except HarnessRefused as e: + pre = dict(spec.preflight or {}) + hj.update(status="refused", refused=str(e), preflight={k: v for k, v in pre.items() if k != "fingerprint"}) + write_json(hj_path, hj) + print("REFUSED:", e, flush=True) + return 2, hj + pre = dict(spec.preflight or {}) + if "fingerprint" in pre: + write_json(os.path.join(ep.log_dir, "harness_preflight.json"), pre) + hj.update(status="running", pid=h.pid, env_observed_keys=h.env_observed_keys, t_start=h.t_start, + preflight={k: v for k, v in pre.items() if k != "fingerprint"}, init=h.info.get("init")) + write_json(hj_path, hj) + ad.wait(h) + cont = [] if getattr(a, "no_continue", False) else continue_episode(ad, h, ep, stop) + if cont: + hj["continuation"] = cont + write_json(hj_path, hj) + if stop["flag"]: + h.exit_reason, code = "stopped", 143 + tw = ad.collect(h) + au = ad.audit(h) + if ad.name == "ours" and spec.first_message: + hj["first_message_sha256"] = C.sha256_text(spec.first_message) + hj.update(status="done" if code == 0 else "stopped", exit_code=h.exit_code, exit_reason=h.exit_reason, + t_end=h.t_end, wall_s=round(h.t_end - h.t_start, 1), audit_ok=au.get("ok"), + violations=au.get("violations"), final_metrics=(tw.final or {}).get("final_metrics")) + if mg: # refusals do not void the trial; they flag it for a look (EFE running.md "Usage gateway") + tot = MG.read_totals(ep.log_dir) or {} + hj["model_gateway"].update({k: tot.get(k) for k in MG.Totals.KEYS}, tokens=tot.get("tokens"), + models=tot.get("models"), budget_stop=tot.get("budget_stop")) + hj["review_flags"] = ["model_gateway:" + k for k in MG.flagged(tot)] + ( + ["model_gateway:other_model"] if set(tot.get("models") or {}) - {a.model} else []) + if code == 0 and h.exit_code not in (0, None): + code = 3 + write_json(hj_path, hj) + return code, hj + except Exception as e: + hj.update(status="error", error=f"{type(e).__name__}: {e}", traceback=traceback.format_exc()[-3000:]) + write_json(hj_path, hj) + if h is not None and h.proc is not None and h.proc.poll() is None: + ad.kill(h) + return 3, hj + finally: + stop_gateway(gw) + if not getattr(a, "keep_run_dir", False): + ad.cleanup(spec) + + +def parser(): + ap = argparse.ArgumentParser() + ap.add_argument("--harness", required=True, choices=NAMES) + ap.add_argument("--session", required=True) + ap.add_argument("--provider", default=None, help="ours: openai / anthropic / gemini / chat") + ap.add_argument("--model", required=True) + ap.add_argument("--effort", default="high") + ap.add_argument("--api-base-url", default=None) + ap.add_argument("--codex-auth", default=None, choices=["chatgpt", "apikey"], + help="Codex authentication: chatgpt defaults for codex; apikey defaults for Robot Harnesses. " + "SenseNova/EmbodiedEvo also support chatgpt; historical RPent is apikey only") + ap.add_argument("--claude-auth", default=None, choices=["oauth", "apikey"], + help="claude_code*: subscription token (default for claude_code_full) or an API key (claude_code, " + "--bare, takes only an API key); see above") + ap.add_argument("--codex-provider", default="openai", choices=["openai", "deepseek", "opencode"], + help="codex: model provider; deepseek = DeepSeek's Responses endpoint with LFF_DEEPSEEK_API_KEY / " + "DEEPSEEK_API_KEY, opencode = OpenCode Go's with LFF_OPENCODE_API_KEY / OPENCODE_API_KEY " + "(both imply --codex-auth apikey)") + ap.add_argument("--codex-catalog", default="generic", choices=["generic", "native"], + help="codex: model catalog, the main table's shared configuration (default) or Codex's native " + "one (control); see lffbench/harnesses/codex.py") + ap.add_argument("--max-budget-usd", type=float, default=None, help="claude_code*: --max-budget-usd") + ap.add_argument("--rpent-sessions", type=int, default=5, + help="rpent_codex: planner sessions per episode (RPent --explore-sessions; default 5 = k + 2 spare)") + ap.add_argument("--rpent-attempts-per-session", type=int, default=1, + help="rpent_codex: attempts one session may use (RPent --explore-attempts-per-session): 1 = " + "variant H, a fresh session with a handoff after each failed attempt (default); 0 = no limit") + ap.add_argument("--rpent-max-turns", type=int, default=100, + help="rpent_codex: model responses per session (RPent --max-turns)") + ap.add_argument("--timeout", type=float, default=10800) + ap.add_argument("--allow-unpinned", action="store_true", + help="launch even if no pin exists for this version / model / effort (the preflight still runs)") + ap.add_argument("--keep-run-dir", action="store_true", help="do not delete the one-time dirs (debugging)") + ap.add_argument("--no-gateway", action="store_true", + help="native harnesses: run the tools inside each MCP server process instead of the episode's " + "tool gateway (scripts/tool_gateway.py; same ToolCore, budget carried over via the transcript)") + ap.add_argument("--no-model-gateway", action="store_true", + help="native harnesses: call the model API directly instead of through the run's model gateway " + "(scripts/model_gateway.py: model calls only, provider-side tools refused, tokens counted)") + ap.add_argument("--token-budget-in", type=int, default=None, + help="model gateway: refuse further model calls once this many input tokens were used (cached " + "input counts in full)") + ap.add_argument("--token-budget-out", type=int, default=None, + help="model gateway: ... output tokens (reasoning included)") + ap.add_argument("--red-team", action="store_true", + help="adversarial acceptance run (lffbench/harnesses/redteam.py): the first message starts with the " + "red-team notice; own contract_sha256; read with scripts/redteam_report.py") + ap.add_argument("--no-continue", action="store_true", + help="do not resume a CLI that exited before the episode was over (self-check / debugging)") + ap.add_argument("--jail", action="store_true", + help="native harnesses: run the CLI in the native-harness jail (docs/15 §3.4): as uid 65534, no host " + "path visible, MCP server outside behind a socket relay") + return ap + + +def main(): + code, hj = run(parser().parse_args()) + print(json.dumps({k: hj.get(k) for k in ("harness", "status", "exit_reason", "audit_ok", "violations", + "contract_sha256", "final_metrics")}, default=str), flush=True) + sys.exit(code) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/lerobot_export.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/lerobot_export.py new file mode 100644 index 0000000000000000000000000000000000000000..fa4fa0a1be92844c9cf410663f77de5e200bda18 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/lerobot_export.py @@ -0,0 +1,431 @@ +"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars. + +Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding +can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan): + + python scripts/lerobot_export.py plan --raw [,] --runs-root /runs/api \ + --paper --task-set /sets/main_v2_1inst.txt --work [--batches ...] [--limit N] + python scripts/lerobot_export.py shard --work --shard i --nshards N + python scripts/lerobot_export.py merge --work --nshards N --out + +Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0 +mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped. + +LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t): + observation.images.image agentview RGB 256x256 (upright; LIBERO naming) + observation.images.wrist_image wrist (eye-in-hand) RGB 256x256 + observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout) + observation.joint_pos / joint_vel 7 arm joints (rad, rad/s) + observation.eef_quat 4: xyzw; observation.gripper_width 1 (m) + action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad), + gripper (-1 open, +1 close) + annotation.attempt_index attempt (1-based) the frame belongs to + annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`) + annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action) + annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt + annotation.task_event number of task-monitor events (error / progress events) registered at this step +Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table), +runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state +per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/. +""" +import argparse +import glob +import json +import os +import re +import shutil +import time + +import numpy as np + +FPS = 20 +RES = 256 +BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke", + "cc_smoke", "cc_opus_smoke"] +BATCH_NOTES = { + "cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog", + "cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267", + "cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299", + "cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances", + "cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)", + "cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the " + "with-history continuation of failed runs is incomplete", + "cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early", + "cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt", + "cc_opus_smoke": "smoke test: single attempt", +} +PHASES = {"move": 0, "gripper": 1, "judge": 2} +CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)", + "L2": "disturbed state to restore (incl. damage the agent causes)", + "L3": "infeasible manipulation strategy (grasp / contact / tool must change)", + "L4": "misjudged geometry (size, shape, fit, hidden structure)", + "L5": "misjudged physics (mass distribution, friction, dynamics)"} + + +def features(): + vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]} + f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names} + i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None} + return { + "observation.images.image": vid(), + "observation.images.wrist_image": vid(), + "observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z", + "finger_qpos_left", "finger_qpos_right"]), + "observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]), + "observation.gripper_width": f32(1, ["width_m"]), + "action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y", + "eef_delta_rot_aa_z", "gripper_close"]), + "annotation.attempt_index": i64(), + "annotation.command_index": i64(), + "annotation.phase": i64(), + "annotation.attempt_success": i64(), + "annotation.task_event": i64(), + } + + +# ------------------------------------------------------------------------------------------------ paper metadata + +def _clean_tex(s): + s = re.sub(r"%.*", "", s) + for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"), + (r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"), + (r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"), + (r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"), + (r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]: + s = re.sub(a, b, s) + s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s) + s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s) + for _ in range(3): + s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\$([^$]*)\$", r"\1", s) + s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ") + s = re.sub(r"\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\\[a-zA-Z]+\*?", "", s) + return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip() + + +def paper_tasks(paper_dir): + """{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the + paper's task table and task appendix (empty if the paper sources are not there).""" + out = {} + if not paper_dir: + return out + app = os.path.join(paper_dir, "sections", "appendix_tasks.tex") + tab = os.path.join(paper_dir, "sections", "tab_tasks.tex") + if os.path.exists(app): + txt = open(app).read() + parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt) + for i in range(1, len(parts) - 1, 2): + if parts[i] != "\\paragraph{": + continue + body = parts[i + 1] + m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S) + if not m: + continue + name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip() + desc = _clean_tex(body[m.end():]) + out[code] = dict(name=name, cause=_clean_tex(cause), description=desc) + if os.path.exists(tab): + names = {v["name"].lower(): k for k, v in out.items()} + for line in open(tab): + cells = [c.strip() for c in line.split("&")] + if len(cells) != 6 or not cells[-1].endswith("\\\\"): + continue + nm = re.sub(r"\\contscene", "", cells[0]).strip().lower() + code = names.get(nm) + if not code: + continue + out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]), + repair_within_attempt=_clean_tex(cells[3]) == "yes", + oracle_first_attempt_pct=_clean_tex(cells[4]), + naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip())) + return out + + +# ------------------------------------------------------------------------------------------------ collection + +def manifest_status(runs_root, batch, run, cache={}): + if batch not in cache: + p = os.path.join(runs_root, batch, "manifest.json") + cache[batch] = json.load(open(p)) if os.path.exists(p) else {} + m = cache[batch] + for r in m.get("runs", []): + if r.get("run") == run: + return r.get("status", "?"), r + for r in m.get("superseded", []): + if r.get("run") == run: + return "superseded_" + str(r.get("status", "?")), r + return "not_in_manifest", {} + + +def collect(raw_roots, runs_root, batches, task_order): + """Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root.""" + eps, rejected, seen = [], [], set() + for root in raw_roots: + for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))): + rep = json.load(open(rj)) + batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"] + if (batches and batch not in batches) or (batch, run) in seen: + continue + seen.add((batch, run)) + ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff") + status, entry = manifest_status(runs_root, batch, run) + if not ok: + never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked") + rejected.append(dict(run=run, batch=batch, run_status=status, + reason="run never started (no contract, no robot command)" if never else + "replay does not reproduce the log (the log has gaps or the replay diverged)", + detail=rep.get("first_mismatches"))) + continue + for ep in rep.get("episodes", []): + d = os.path.join(root, ep["dir"]) + ann = json.load(open(os.path.join(d, "annotation.json"))) + judged = [a for a in ann["attempts"] if a.get("success") is not None] + if not judged or ep["n_frames"] == 0: + rejected.append(dict(run=run, batch=batch, episode=ep["dir"], + reason="no judged attempt" if not judged else "no frames")) + continue + ann["source"]["run_status"] = status + ann["source"]["manifest_id"] = entry.get("id") + ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"], + max_eef_dev_m=rep["max_eef_dev_m"]) + key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99), + {"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2), + ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"]) + eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann)) + eps.sort(key=lambda x: x["key"]) + return eps, rejected + + +# ------------------------------------------------------------------------------------------------ writing + +def frames_of(path): + import av + with av.open(path) as c: + for fr in c.decode(video=0): + yield fr.to_ndarray(format="rgb24") + + +def flat_row(i, ann, n, idx0): + s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"] + att = ann["attempts"] + a0 = att[0] + return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n, + batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"], + memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"), + episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att], + harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"), + effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"), + task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"), + category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"], + success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att], + feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att], + auto_ended=[a.get("auto_ended") for a in att], + corrected_later_in_run=[a.get("corrected_later_in_run") for a in att], + error_event_in_attempt=[a.get("error_event_in_attempt") for a in att], + run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"), + n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]), + first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None) + + +def cmd_plan(a): + task_order = {} + if a.task_set and os.path.exists(a.task_set): + for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")): + task_order[line.split(":")[0].strip()] = i + batches = [b for b in a.batches.split(",") if b] if a.batches else None + eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order) + if a.limit: + eps = eps[:a.limit] + paper = paper_tasks(a.paper) + idx0 = 0 + for i, e in enumerate(eps): + ann = e["ann"] + tname = ann["task"]["name"] + if tname in paper: + ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"} + ann["episode_index"] = i + ann["dataset_index_range"] = [idx0, idx0 + e["n"]] + e["index"], e["from"] = i, idx0 + idx0 += e["n"] + del e["key"] + os.makedirs(a.work, exist_ok=True) + with open(os.path.join(a.work, "plan.json"), "w") as f: + json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f, + ensure_ascii=False) + print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True) + + +def shard_range(n_eps, i, k): + return (n_eps * i) // k, (n_eps * (i + 1)) // k + + +def cmd_shard(a): + from lerobot.datasets.lerobot_dataset import LeRobotDataset + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + lo, hi = shard_range(len(eps), a.shard, a.nshards) + out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}") + if os.path.exists(os.path.join(out, "DONE")): + print(f"shard {a.shard}: done already", flush=True) + return + shutil.rmtree(out, ignore_errors=True) + ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out, + robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads, + vcodec=a.vcodec) + nfr = 0 + for e in eps[lo:hi]: + d, ann, n = e["dir"], e["ann"], e["n"] + fr = np.load(os.path.join(d, "frames.npz")) + assert len(fr["action"]) == n, d + succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]} + evc = np.zeros(n, np.int64) + for ev in ann["task_events"]: + if 0 <= ev["frame"] < n: + evc[ev["frame"]] += 1 + state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32) + instr = ann["task"]["instruction"] + k = 0 + for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))): + if k >= n: + break + ds.add_frame({ + "observation.images.image": img, "observation.images.wrist_image": wr, + "observation.state": state[k], + "observation.joint_pos": fr["joint_pos"][k].astype(np.float32), + "observation.joint_vel": fr["joint_vel"][k].astype(np.float32), + "observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32), + "observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32), + "action": fr["action"][k].astype(np.float32), + "annotation.attempt_index": np.array([fr["attempt"][k]], np.int64), + "annotation.command_index": np.array([fr["command"][k]], np.int64), + "annotation.phase": np.array([fr["phase"][k]], np.int64), + "annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64), + "annotation.task_event": np.array([evc[k]], np.int64), + "task": instr, + }) + k += 1 + if k != n: + raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames") + ds.save_episode() + nfr += n + ds.finalize() + shutil.rmtree(os.path.join(out, "images"), ignore_errors=True) + open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n") + print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True) + + +def cmd_merge(a): + from pathlib import Path + from lerobot.datasets.aggregate import aggregate_datasets + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + roots, ids = [], [] + for i in range(a.nshards): + lo, hi = shard_range(len(eps), i, a.nshards) + if hi <= lo: + continue + r = os.path.join(a.work, "shards", f"shard_{i:03d}") + if not os.path.exists(os.path.join(r, "DONE")): + raise SystemExit(f"shard {i} is not done") + roots.append(Path(r)) + ids.append(f"{plan['repo_id']}-shard{i:03d}") + if os.path.exists(a.out): + raise SystemExit(f"{a.out} exists; refusing to overwrite") + aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out)) + print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True) + write_sidecars(a, plan) + print(f"merge done in {time.time() - t0:.0f}s", flush=True) + + +def write_sidecars(a, plan): + eps, paper = plan["episodes"], plan["paper"] + lff = os.path.join(a.out, "lff") + for sub in ("annotations", "sim_state", "final", "code"): + os.makedirs(os.path.join(lff, sub), exist_ok=True) + rows, runs, tasks = [], {}, {} + for e in eps: + i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"] + name = f"episode_{i:06d}" + if os.path.exists(os.path.join(d, "sim_state.npy")): + shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy")) + shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz")) + for cam, key in (("agentview", "image"), ("wrist", "wrist_image")): + shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png")) + with open(os.path.join(lff, "annotations", name + ".json"), "w") as f: + json.dump(ann, f, indent=1, ensure_ascii=False) + rows.append(flat_row(i, ann, n, e["from"])) + tname = ann["task"]["name"] + rk = (ann["source"]["batch"], ann["source"]["run"]) + r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"), + run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"], + memory_free_chain_of=ann["source"].get("memory_free_chain_of"), + memory_free_rep=ann["source"].get("memory_free_rep"), task=tname, + seed=ann["task"]["seed"], model=ann["agent"].get("model"), + harness=ann["agent"].get("harness"), + harness_version=ann["agent"].get("harness_version"), + codex_catalog=ann["agent"].get("codex_catalog"), + outcome_class=ann["run_outcome"].get("outcome_class"), + attempt_history=ann["run_outcome"].get("attempt_history"), + agent_final_report=ann["run_outcome"].get("agent_final_report"), + episodes=[])) + for x in ann["attempts"]: + r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success"))) + if tname not in tasks: + tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")} + if tname in paper: + tasks[tname]["paper"] = paper[tname] + tasks[tname]["instances"] = {} + tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"] + # memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id) + by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")} + for r in runs.values(): + if r.get("memory_free_chain_of"): + r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"])) + for (b, rn), r in runs.items(): + r["memory_free_retries"] = sorted((x["run"] for x in runs.values() + if x["batch"] == b and x.get("memory_free_chain_of_run") == rn), + key=lambda q: runs[(b, q)].get("memory_free_rep") or 0) + with open(os.path.join(lff, "episodes.jsonl"), "w") as f: + for row in rows: + f.write(json.dumps(row, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "runs.jsonl"), "w") as f: + for r in runs.values(): + f.write(json.dumps(r, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "tasks.json"), "w") as f: + json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False) + with open(os.path.join(lff, "batches.json"), "w") as f: + json.dump(BATCH_NOTES, f, indent=1) + with open(os.path.join(lff, "rejected.json"), "w") as f: + json.dump(plan["rejected"], f, indent=1) + here = os.path.dirname(os.path.abspath(__file__)) + for s in ("lerobot_replay.py", "lerobot_export.py"): + shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("step", choices=["plan", "shard", "merge"]) + ap.add_argument("--work", required=True) + ap.add_argument("--raw", default="") + ap.add_argument("--runs-root", default="") + ap.add_argument("--out", default="") + ap.add_argument("--paper", default="") + ap.add_argument("--task-set", default="") + ap.add_argument("--repo-id", default="lffbench/agent-replays") + ap.add_argument("--batches", default="") + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--shard", type=int, default=0) + ap.add_argument("--nshards", type=int, default=1) + ap.add_argument("--threads", type=int, default=2) + ap.add_argument("--vcodec", default="libsvtav1") + a = ap.parse_args() + {"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/lerobot_replay.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/lerobot_replay.py new file mode 100644 index 0000000000000000000000000000000000000000..4c43a69bdb066327b27614bc9efda53d4a74e931 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/lerobot_replay.py @@ -0,0 +1,744 @@ +"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay +against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the +LeRobot export (scripts/lerobot_export.py). + + python scripts/lerobot_replay.py check [ ...] [--json out.json] # replay only, print fidelity + python scripts/lerobot_replay.py record --out [--res 256] + +Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot +commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite +is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly +like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same +outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width, +ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code +hashes equal the current files are expected to match (check_code()). + +Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB, +proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes: +protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode +per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the +fidelity check runs in record mode too. Per episode the recorder writes ///epNN/: + agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes) + frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase + sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel) + final_*.png, final.npz observation after the last control step (the state the outcome was judged in) + annotation.json episode annotation (build_annotation) +and ///replay.json (fidelity) when the whole run is done. +""" +import argparse +import ast +import hashlib +import importlib +import json +import math +import os +import pkgutil +import re +import shutil +import sys +import time +from collections import defaultdict + +import numpy as np + +LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, LFF_ROOT) + +from lffbench import envs # noqa: E402 +from lffbench import tasks as task_pkg # noqa: E402 +from lffbench.agent import camera as C # noqa: E402 +from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402 +from lffbench.task_base import TASKS # noqa: E402 + +for _m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{_m.name}") + +# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the +# task's outcome() check after `finish` (the arm holds still; not an agent action) +PHASES = {"move": 0, "gripper": 1, "judge": 2} +FPS = 20 +SCHEMA = "lff-replay-1" + +# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR" +ERROR_FLAGS = ("trap_fired", "recovered_in_attempt") +ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events", + "n_missed_strikes", "n_open_gripper_pushes") + + +def load_jsonl(p): + out = [] + if not os.path.exists(p): + return out + with open(p) as f: + for line in f: + line = line.strip() + if line: + try: + out.append(json.loads(line)) + except ValueError: + pass + return out + + +def norm_json(o): + return json.loads(json.dumps(o, default=_json_default)) + + +def sha256(p): + with open(p, "rb") as f: + return hashlib.sha256(f.read()).hexdigest() + + +def check_code(run_dir): + """[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract.""" + p = os.path.join(run_dir, "contract.json") + if not os.path.exists(p): + return [("contract.json", None, None)] + files = json.load(open(p))["contract"].get("server_code_files", {}) + bad = [] + for f, h in files.items(): + q = os.path.join(LFF_ROOT, f) + cur = sha256(q) if os.path.exists(q) else None + if cur != h: + bad.append((f, h, cur)) + return bad + + +def diff_json(a, b, path="", tol=0.0, out=None, limit=20): + """Differences between two JSON values (numbers compared with an absolute tolerance).""" + out = [] if out is None else out + if len(out) >= limit: + return out + if isinstance(a, dict) and isinstance(b, dict): + for k in sorted(set(a) | set(b)): + if k not in a or k not in b: + out.append((f"{path}.{k}", a.get(k, ""), b.get(k, ""))) + else: + diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit) + elif isinstance(a, list) and isinstance(b, list): + if len(a) != len(b): + out.append((path, f"len {len(a)}", f"len {len(b)}")) + else: + for i, (x, y) in enumerate(zip(a, b)): + diff_json(x, y, f"{path}[{i}]", tol, out, limit) + elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))): + if a != b: + out.append((path, a, b)) + elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))): + out.append((path, a, b)) + return out + + +def error_event(o): + """True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none.""" + if not isinstance(o, dict): + return None + keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o] + if not keys: + return None + return any(bool(o[k]) for k in ERROR_FLAGS if k in o) or any((o.get(k) or 0) > 0 for k in ERROR_COUNTS if k in o) + + +# ====================================================================================================== logs -> notes + +class RunLog: + """Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's + narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition.""" + + def __init__(self, run_dir, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run = os.path.basename(self.run_dir) + self.batch = os.path.basename(os.path.dirname(self.run_dir)) + self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl")) + self.start = next(e for e in self.ev if e["ev"] == "session_start") + self.calls, self.dones, self.harness_status = {}, [], [] + last = None + for e in self.ev: + if e["ev"] == "call": + self.calls[(int(e["attempt"]), int(e["step"]))] = e + last = e + elif e["ev"] == "done": + self.dones.append(e) + last = e + elif e["ev"] == "http" and last is not None and "think_s" not in last: + ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \ + (last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe")) + if ok: + last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s") + self.manifest = manifest or {} + self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {} + p = os.path.join(self.run_dir, "harness.json") + self.harness = json.load(open(p)) if os.path.exists(p) else {} + self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl")) + self._narration() + + # ---------------------------------------------------------------- agent narration + def _narration(self): + """notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one; + finish_notes[attempt] likewise for the agent's finish call; final_report = its last message.""" + self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", [] + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + attempt = 1 + + def take(): + nonlocal buf + out = {k: v for k, v in buf.items() if v} + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + return out + + last_msg = "" + for t in self.traj: + if t.get("kind") == "header": + self.headers.append(t.get("agent") or {}) + continue + if t.get("kind") != "step": + continue + if (t.get("message") or "").strip(): + buf["messages"].append(t["message"].strip()) + last_msg = t["message"].strip() + if (t.get("reasoning_content") or "").strip(): + buf["reasoning"].append(t["reasoning_content"].strip()) + res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])} + for c in t.get("tool_calls") or []: + fn, args = c.get("function_name"), c.get("arguments") or {} + if fn == "shell": + buf["shell"].append(str(args.get("command", ""))[:2000]) + elif fn == "view_images": + buf["viewed"].extend(args.get("paths") or []) + elif fn == "robot": + cmd = str(args.get("command", "")).strip() + r = res.get(c.get("tool_call_id")) or {} + try: + rep = json.loads(r.get("content") or "{}") + except ValueError: + rep = {} + word = cmd.split()[0] if cmd else "" + m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", ""))) + if word in ("move_eef", "observe") and m: + a, s = int(m.group(1)), int(m.group(2)) + n = take() + n["command"] = cmd + self.notes[(a, s)] = n + attempt = a + elif word in ("finish", "done"): + n = take() + n["command"] = cmd + n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)} + self.finish_notes.setdefault(attempt, n) + if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"): + attempt += 1 + # status / help / errors: their narration stays in the buffer for the next command + self.final_report = last_msg + + # ---------------------------------------------------------------- run-level labels + def attempts(self): + out = [] + for e in self.dones: + o = e.get("outcome") or {} + if isinstance(o, str): + try: + o = ast.literal_eval(o) + except (ValueError, SyntaxError): + o = {} + out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o, + reason=e.get("reason") or "")) + return sorted(out, key=lambda x: x["attempt"]) + + def condition(self): + s, en = self.start, self.entry + mem = s.get("memory", en.get("mem")) + chain = en.get("chain") + if mem == "full": + cond = "with_history" + elif chain: + cond = "memory_free_retry" + else: + cond = "independent_single_attempt" + return cond, chain + + def outcome_class(self): + """CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None.""" + att = self.attempts() + if not att or self.start.get("memory") != "full": + return None, "".join("S" if a["success"] else "F" for a in att) + hist = "".join("S" if a["success"] else "F" for a in att) + if att[0]["success"]: + ev = error_event(att[0]["outcome"]) + cls = "S?" if ev is None else ("IR" if ev else "CS") + else: + cls = "XR" if any(a["success"] for a in att) else "F" + return cls, hist + + def agent_info(self): + h, en = self.harness, self.entry + hdr = self.headers[0] if self.headers else {} + return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"), + harness_version=h.get("version") or hdr.get("version"), + harness_binary_sha256=(h.get("binary") or {}).get("sha256"), + model=h.get("model") or en.get("model") or hdr.get("model_name"), + effort=h.get("effort") or en.get("effort") or hdr.get("effort"), + provider=h.get("provider") or en.get("provider"), + codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"), + jail=en.get("jail")) + + +# ====================================================================================================== recording + +class EpisodeSink: + """Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed.""" + + def __init__(self, path): + self.path = path + os.makedirs(path, exist_ok=True) + self.w = None + self.num = defaultdict(list) + self.n = 0 + + def add(self, st, imgs): + import imageio + if self.w is None: + self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb", + pixelformat="rgb24", macro_block_size=1, + ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error") + for k in ("agentview", "wrist")] + for w, im in zip(self.w, imgs): + w.append_data(im) + for k, v in st.items(): + self.num[k].append(v) + self.n += 1 + + def close(self, final_state, final_imgs): + from PIL import Image + if self.w is not None: + for w in self.w: + w.close() + arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"} + np.savez(os.path.join(self.path, "frames.npz"), **arr) + if self.num.get("sim_state"): + np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64)) + np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()}) + for k, im in zip(("agentview", "wrist"), final_imgs): + Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png")) + + +class Recorder: + """Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink.""" + + def __init__(self, rp, res): + self.rp, self.res = rp, int(res) + self.active = False + self.sink = None + self.cur = dict(attempt=1, command=-1, phase=PHASES["move"]) + env = rp.task.env + self.env, self.rob = env, env.robots[0] + self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist")) + orig = env.step + + def step(a): + if self.active and self.sink is not None: + self.capture(np.asarray(a, np.float64)) + out = orig(a) + if self.active and self.sink is not None: + self.rp.poll_events(self.sink.n - 1) + return out + + env.step = step + + @property + def n(self): + return self.sink.n if self.sink is not None else 0 + + def state(self): + import robosuite.utils.transform_utils as T + env, rob = self.env, self.rob + d = env.sim.data + eef = np.array(d.site_xpos[rob.eef_site_id], np.float64) + q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw") + gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64) + try: + flat = np.asarray(env.sim.get_state().flatten(), np.float64) + except Exception: + flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64) + sk = self.rp.task.sk + return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64), + gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64), + joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64), + gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64), + eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)), + sim_time=np.float64(d.time), sim_state=flat) + + def images(self): + return [envs.render(self.env, c, self.res) for c in self.cams] + + def capture(self, a): + st = self.state() + st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]), + phase=np.int64(self.cur["phase"])) + self.sink.add(st, self.images()) + + +class RunReplay: + def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run_name = os.path.basename(self.run_dir) + self.log = RunLog(self.run_dir, manifest) + self.ev = self.log.ev + self.start = self.log.start + cp = os.path.join(self.run_dir, "contract.json") + self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {} + spec = self.contract.get("image_spec") or {} + self.image_res = int(spec.get("width", 512)) + self.code_diff = check_code(self.run_dir) + s = self.start + self.task = TASKS[s["task"]](cam_res=self.image_res) + inst = self.task.sample_instance(s["seed"]) + logged = s.get("inst") or {} + sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")}) + self.inst_diff = diff_json(sampled, logged, "inst") + if s.get("arm", "none") not in (None, "none") or logged.get("nominal"): + inst.update(logged) # controlled arms / nominal: the server overrode these instance fields + self.inst_diff = [] + self.inst = inst + self.protocol = getattr(self.task, "protocol", "cross") + self.k = int(s.get("k") or self.task.max_attempts) + self.attempt = 1 + self.mismatch = [] # (where, what, logged, replayed) + self.n_checked = 0 + self.max_dev_m = 0.0 + self.unfinished = None + self.rec = Recorder(self, res) if record else None + self.res = int(res) + self.out_root = out_root + self.n_mon = 0 + self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0 + self.episodes = [] # summaries of the written episodes + self.task.reset_instance(self.inst) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + sim = self.task.env.sim + bid = sim.model.body_name2id("robot0_base") + self.base_off = np.array(sim.data.body_xpos[bid], float).copy() + if self.rec: + self._open_episode() + + # ------------------------------------------------------------------ episodes + def _ep_dir(self): + return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}") + + def _open_episode(self): + self.rec.sink = EpisodeSink(self._ep_dir()) + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.rec.active = True + self.events, self.spans, self.ep_attempts = [], [], [] + self.ep_initial = self.rec.state() # state right after the reset (before frame 0) + + def close_episode(self): + if not self.rec: + self.ep_attempts = [] + return + sink = self.rec.sink + st = self.rec.state() + imgs = self.rec.images() + st.pop("sim_state", None) + sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs) + ann = build_annotation(self, sink) + with open(os.path.join(sink.path, "annotation.json"), "w") as f: + json.dump(ann, f, indent=1, default=_json_default) + self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n, + attempts=[a["attempt"] for a in self.ep_attempts])) + self.rec.active = False + self.rec.sink = None + self.ep_index += 1 + + # ------------------------------------------------------------------ monitor events (task-side error events) + def poll_events(self, frame): + mon = getattr(self.task, "mon", None) + evs = mon.get("events") if isinstance(mon, dict) else None + if not isinstance(evs, list): + return + if len(evs) < self.n_mon: # monitor was rebuilt + self.n_mon = 0 + for e in evs[self.n_mon:]: + self.events.append(dict(frame=int(frame), attempt=self.attempt, + event=norm_json(e) if isinstance(e, dict) else str(e))) + self.n_mon = len(evs) + + # ------------------------------------------------------------------ state as the server reports it + def proprio_la(self): + p = self.ex.proprio() + pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off] + return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"]) + + def compare(self, where, rep_logged, rep): + self.n_checked += 1 + for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"): + if k not in rep_logged or k not in rep: + continue + a, b = rep_logged[k], rep[k] + if k == "eef_pos": + dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float)))) + self.max_dev_m = max(self.max_dev_m, dev) + if dev > 1.5e-4: + self.mismatch.append((where, k, a, b)) + elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4): + self.mismatch.append((where, k, a, b)) + if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)): + self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok"))) + + def _span(self, e, f0, kind): + if self.rec: + self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0, + frame_end=self.rec.n)) + + # ------------------------------------------------------------------ commands (robot_server._handle_v2) + def move_eef(self, e): + args = e.get("args") or {} + where = f"a{e['attempt']}s{e['step']}" + logged = e.get("report") or {} + f0 = self.rec.n if self.rec else 0 + p = self.ex.proprio() + if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}: + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + off = self.base_off + try: + cur = np.asarray(p["eef_pos"], float) - off + tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")] + yaw = float(args.get("yaw", p["eef_yaw_deg"])) + speed = None if args.get("speed") in (None, "") else float(args["speed"]) + except (TypeError, ValueError): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + grip = args.get("gripper") + if grip not in (None, "open", "close"): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + moving = any(k in args for k in ("x", "y", "z", "yaw")) + tgt_w = np.asarray(tgt) + off + if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)): + self._span(e, f0, "rejected") + return self.compare(where, logged, dict(ok=False, **self.proprio_la())) + raw = {} + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"]) + if moving: + mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw) + if speed is not None: + mv["speed"] = speed + raw.update(self.ex.call("move_to", mv).report) + if grip is not None: + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"]) + raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report) + rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la()) + self.compare(where, logged, rep) + lr = e.get("raw") or {} + for k in ("holding_object", "touched_object"): + if k in lr and k in raw and bool(lr[k]) != bool(raw[k]): + self.mismatch.append((where, "raw." + k, lr[k], raw[k])) + self._span(e, f0, "move_eef") + + def observe(self, e): + f0 = self.rec.n if self.rec else 0 + self._span(e, f0, "observe") + + def done(self, e): + f0 = self.rec.n if self.rec else 0 + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"]) + out = self.task.outcome(self.inst) + succ = bool(out["success"]) + where = f"a{e['attempt']}done" + if succ != bool(e.get("success") in (True, "True")): + self.mismatch.append((where, "success", e.get("success"), succ)) + lo = e.get("outcome") or {} + ro = norm_json({k: v for k, v in out.items() if k != "feedback"}) + if isinstance(lo, dict): + for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8): + self.mismatch.append((where,) + d) + info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""), + feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")), + think_s=e.get("think_s")) + try: + info["feedback_f2"] = self.task.feedback(self.inst, out, "F2") + except Exception as ex_: + info["feedback_f2"] = f"" + if self.rec: + info["judge_frames"] = [f0, self.rec.n] + self.ep_attempts.append(info) + last = self.attempt >= self.k or succ or bool(out.get("terminal")) + if self.protocol == "cross" or last: + self.close_episode() + if last: + return True + self.attempt += 1 + if self.protocol == "cross": + self.task.reset_instance(self.inst) + self.n_mon = 0 + if self.rec: + self._open_episode() + elif self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + return False + + def run(self): + t0 = time.time() + finished = False + for e in self.ev: + if e["ev"] == "call": + if e.get("cmd") == "move_eef": + self.move_eef(e) + elif e.get("cmd") == "observe": + self.observe(e) + else: + self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None)) + elif e["ev"] == "done": + finished = self.done(e) + if finished: + break + self.unfinished = not finished + if not finished and self.rec and self.rec.sink is not None: + # the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged + if self.rec.n or self.ep_attempts: + self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True, + finish_reason="", feedback_shown="", auto_ended=False)) + self.close_episode() + else: + shutil.rmtree(self.rec.sink.path, ignore_errors=True) + self.rec.sink = None + self.wall_s = time.time() - t0 + return self + + def summary(self): + return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"], + protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff), + n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6), + unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1), + first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]]) + + +# ====================================================================================================== annotation + +def task_info(task, inst): + cls = type(task) + return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable", + category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"), + max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)), + instruction=cls.instruction) + + +def build_annotation(rp, sink): + """Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2 + failure description), run-level outcome class, every robot command with its frame span and the agent's narration, + task-side error events with frame indices.""" + log = rp.log + s = rp.start + cond, chain = log.condition() + cls, hist = log.outcome_class() + att_all = log.attempts() + attempts = [] + for a in rp.ep_attempts: + a = dict(a) + n = a["attempt"] + later = [x for x in att_all if x["attempt"] > n] + a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later)) + a["is_last_attempt_of_run"] = not later + fn = log.finish_notes.get(n) + if fn: + a["agent_finish"] = fn + a["error_event_in_attempt"] = error_event(a.get("outcome")) + attempts.append(a) + # post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command) + for a in attempts: + nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1]) + if a.get("success") is False and nxt: + note = log.notes[nxt[0]] + a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note} + commands = [] + for sp in rp.spans: + e = log.calls.get((sp["attempt"], sp["step"])) or {} + rep = e.get("report") or {} + c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"], + frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]), + args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"), + stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"), + gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"), + touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"), + agent_obs_images=rep.get("images")) + note = log.notes.get((sp["attempt"], sp["step"])) + if note: + c["agent_note"] = {k: v for k, v in note.items() if k != "command"} + commands.append(c) + t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x] + return dict( + schema=SCHEMA, + source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts], + episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain, + memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None), + feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"), + k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"), + contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256") + if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)), + agent=log.agent_info(), + task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"), + instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}), + run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all), + run_success=any(x["success"] for x in att_all) if att_all else None, + agent_final_report=log.final_report[:6000] or None, + mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)), + attempts=attempts, + commands=commands, + task_events=rp.events, + frames=dict(n=sink.n, fps=FPS, image_res=rp.res, + phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"], + joint_pos=rp.ep_initial["joint_pos"], + gripper_qpos=rp.ep_initial["gripper_qpos"])), + ) + + +# ====================================================================================================== CLI + +def load_manifest(run_dir): + p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json") + return json.load(open(p)) if os.path.exists(p) else {} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("mode", choices=["check", "record"]) + ap.add_argument("runs", nargs="+") + ap.add_argument("--json", default="") + ap.add_argument("--out", default="") + ap.add_argument("--res", type=int, default=256) + ap.add_argument("--force", action="store_true", help="record again even if replay.json exists") + a = ap.parse_args() + rows = [] + for r in a.runs: + r = r.rstrip("/") + try: + if a.mode == "check": + s = RunReplay(r, manifest=load_manifest(r)).run().summary() + else: + batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r) + rd = os.path.join(a.out, batch, name) + if os.path.exists(os.path.join(rd, "replay.json")) and not a.force: + print(json.dumps(dict(run=name, skipped="exists")), flush=True) + continue + shutil.rmtree(rd, ignore_errors=True) + rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run() + s = rp.summary() + s["episodes"] = rp.episodes + with open(os.path.join(rd, "replay.json"), "w") as f: + json.dump(s, f, indent=1) + except Exception: + import traceback + s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:]) + rows.append(s) + print(json.dumps(s), flush=True) + if a.json: + with open(a.json, "w") as f: + json.dump(rows, f, indent=1) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/qwen_vl_server.sh b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/qwen_vl_server.sh new file mode 100644 index 0000000000000000000000000000000000000000..a824c708ab1fd0a44bc70f5991649fee9d8390c5 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/qwen_vl_server.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# Launch the Qwen3-VL OpenAI-compatible server on the local PPU. +# Usage: bash scripts/qwen_vl_server.sh [--port 8765] [--host 127.0.0.1] [other qwen_vl_server.py args] +# Uses the system python3.12 (torch 2.6 PPU build) + a private overlay dir that only +# holds transformers==4.57.6 / tokenizers==0.22.1 / huggingface_hub==0.36.0; the +# overlay is put on PYTHONPATH for this process only. +set -eo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# PPU runtime libs (libhggcrt1.so etc.); without this torch spins printing load errors. +source /usr/local/PPU_SDK/envsetup.sh cuda >/dev/null +[ -n "${QWEN_OVERLAY:-}" ] && export PYTHONPATH="${QWEN_OVERLAY}${PYTHONPATH:+:${PYTHONPATH}}" +export OMP_NUM_THREADS="${OMP_NUM_THREADS:-1}" +export MKL_NUM_THREADS="${MKL_NUM_THREADS:-1}" +export TOKENIZERS_PARALLELISM=false +export HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 +export PYTHONUNBUFFERED=1 +exec /usr/local/bin/python3.12 "${HERE}/qwen_vl_server.py" "$@" diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/validate.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/validate.py new file mode 100644 index 0000000000000000000000000000000000000000..cbb5365e77822d5dc2d8ad2fd3489c4d6c82a77b --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/validate.py @@ -0,0 +1,79 @@ +"""Headroom validation of LFF-Bench tasks with scripted reference policies. + +python scripts/validate.py --task l5_slide_to_target --n 20 --k 5 +Writes results//validate.json and thumbnails. +""" +import argparse +import importlib +import json +import os +import pkgutil +import sys +import time + +import numpy as np + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) + +import imageio # noqa: E402 + +import lffbench.tasks as task_pkg # noqa: E402 +from lffbench.task_base import TASKS # noqa: E402 + +for m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{m.name}") + + +def succ_curve(results, k): + """run-level succ@j for j = 1..k (a run = one instance, attempts share the run's state).""" + out = [] + for j in range(1, k + 1): + out.append(float(np.mean([r is not None and r <= j for r in results]))) + return out + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--task", required=True) + ap.add_argument("--n", type=int, default=20) + ap.add_argument("--k", type=int, default=5) + ap.add_argument("--seed0", type=int, default=1000) + ap.add_argument("--kinds", default="oracle,naive,adaptive,blind") + ap.add_argument("--thumbs", type=int, default=3) + args = ap.parse_args() + + task = TASKS[args.task]() + outdir = os.path.join(ROOT, "results", args.task) + os.makedirs(outdir, exist_ok=True) + kinds = args.kinds.split(",") + first_success = {k: [] for k in kinds} + runs = [] + t0 = time.time() + for i in range(args.n): + seed = args.seed0 + i + inst = task.sample_instance(seed) + if i < args.thumbs: + task.reset_instance(inst) + imageio.imwrite(os.path.join(outdir, f"init_{seed}.png"), task.snapshot(res=384)) + for kind in kinds: + hist = task.run_scripted(kind, inst, k=args.k, seed=seed) + s = next((h["attempt"] for h in hist if h["outcome"]["success"]), None) + first_success[kind].append(s) + runs.append(dict(seed=seed, kind=kind, inst={k: v for k, v in inst.items() if not k.startswith("_")}, + history=hist)) + if i < args.thumbs and kind == "naive": + imageio.imwrite(os.path.join(outdir, f"naive_end_{seed}.png"), task.snapshot(res=384)) + print(f"[{i + 1}/{args.n}] seed={seed} " + " ".join(f"{k}={first_success[k][-1]}" for k in kinds) + + f" ({time.time() - t0:.0f}s)", flush=True) + + summary = {k: succ_curve(v, args.k) for k, v in first_success.items()} + res = dict(task=args.task, level=task.level, capabilities=list(task.capabilities), n=args.n, k=args.k, + succ_at_k=summary, runs=runs, seconds=time.time() - t0) + with open(os.path.join(outdir, "validate.json"), "w") as f: + json.dump(res, f, indent=1, default=float) + print(json.dumps({k: [round(x, 2) for x in v] for k, v in summary.items()})) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/validate_ladder_fix.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/validate_ladder_fix.py new file mode 100644 index 0000000000000000000000000000000000000000..d80168eaa6cf7ce8c79aacac8a0f8d3e25e63e05 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/validate_ladder_fix.py @@ -0,0 +1,168 @@ +"""Check the Fix-rung texts of the layer-3 feedback ladder (docs/20 §4) on every ladder instance. + + python scripts/validate_ladder_fix.py [--out results/_ladder/fix_validate.json] [--only TASK] + +Per instance (task:seed from runs/api/mismatch_20261027//own.json, both models, deduplicated): + 1. the sampled instance equals the one logged in the main-table run (session_start inst); + 2. the scripted oracle succeeds in one attempt; the Fix text is built from the parameters that oracle executed; + 3. the text has no coordinate-axis labels (strip_axes leaves it unchanged) and no internal instance key names; + 4. slide_to_target / tablecloth_pull only: the strike / pull the text describes, issued as LA `move_eef` + commands in the robot-base frame through the same path as robot_server (ToolExecutor move_to with the given + speed), also succeeds -- this checks that "speed" in the text means what move_eef does. The success window is + narrow (~+-0.02) and the LA path does not hit it at exactly the oracle's speed (tablecloth 3001: oracle 0.475 + fails as LA commands, 0.48-0.52 succeed), so for these two the text's speed is the middle of the longest run of + LA successes on a 0.01 grid within +-0.10 of the oracle speed (`la_speed`). +""" +import argparse +import importlib +import json +import os +import pkgutil +import sys +import time + +import numpy as np + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) + +from lffbench import arm_specs, envs # noqa: E402 +from lffbench import tasks as task_pkg # noqa: E402 +from lffbench.agent.robot_server import strip_axes # noqa: E402 +from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor # noqa: E402 +from lffbench.task_base import TASKS # noqa: E402 + +for _m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{_m.name}") + +OUT = os.path.join(ROOT, "runs", "api", "mismatch_20261027") +BANNED = ("com_offset", "com_total", "heavy_edge", "heavy_near", "pane_side", "_oracle", " mu ", "inst[") + + +def instances(): + seen = {} + for m in ("opus", "sonnet"): + for key, d in json.load(open(os.path.join(OUT, m, "own.json"))).items(): + src = json.load(open(d + ".source.json")) + start = json.loads(open(os.path.join(src["log"], "events.jsonl")).readline()) + seen.setdefault(key, dict(task=src["task"], seed=src["seed"], logged=start["inst"], models=[])) + seen[key]["models"].append(m) + return seen + + +def same(a, b): + if isinstance(a, dict): + return isinstance(b, dict) and set(a) == set(b) and all(same(a[k], b[k]) for k in a) + if isinstance(a, (list, tuple)): + return isinstance(b, (list, tuple)) and len(a) == len(b) and all(same(x, y) for x, y in zip(a, b)) + if isinstance(a, float) or isinstance(b, float): + return abs(float(a) - float(b)) < 1e-9 + return a == b + + +def la_move(task, ex, off, **args): + """one LA move_eef, as robot_server._handle_v2: absolute base-frame target, move then gripper""" + p = ex.proprio() + cur = np.asarray(p["eef_pos"], float) - off + tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")] + tgt_w = np.asarray(tgt) + off + if any(k in args for k in ("x", "y", "z", "yaw")): + assert np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI), f"target rejected {tgt}" + mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=float(args.get("yaw", p["eef_yaw_deg"]))) + if args.get("speed") is not None: + mv["speed"] = float(args["speed"]) + ex.call("move_to", mv) + if args.get("gripper"): + ex.call("open_gripper" if args["gripper"] == "open" else "close_gripper", {}) + + +def la_replay(task, inst, params): + """the Fix text of slide / tablecloth as LA commands; returns the outcome""" + task.reset_instance(inst) + sim = task.env.sim + off = np.array(sim.data.body_xpos[sim.model.body_name2id("robot0_base")], float).copy() + ex = ToolExecutor(task, inst, image_res=64, cams=("agentview",)) + zt = envs.TABLE_Z - off[2] # tabletop height in the base frame + v = float(params["speed"]) + if task.name == "l5_slide_to_target": + x0, y0 = (np.asarray(inst["cube_xy"], float) - off[:2]) + la_move(task, ex, off, gripper="close") + la_move(task, ex, off, x=x0 - 0.22, y=y0, z=zt + 0.12, yaw=0) + la_move(task, ex, off, x=x0 - 0.22, y=y0, z=zt + 0.02) + la_move(task, ex, off, x=x0 - 0.005, y=y0, z=zt + 0.02, speed=v) + la_move(task, ex, off, z=zt + 0.10, speed=0.3) + else: + from lffbench.tasks.l5_tablecloth_pull import B_HALF, BOARD, H_HALF + b = envs.obj_pos(task.env, BOARD) - off + hx, hy, zg = b[0] - B_HALF[0] + H_HALF[0], b[1], zt + 2 * B_HALF[2] + H_HALF[2] + la_move(task, ex, off, gripper="open") + la_move(task, ex, off, x=hx, y=hy, z=zg + 0.08, yaw=0) + la_move(task, ex, off, x=hx, y=hy, z=zg, gripper="close") + la_move(task, ex, off, x=hx - 0.25, y=hy, z=zg, speed=v, gripper="open") + la_move(task, ex, off, z=zg + 0.10, speed=0.3) + return task.outcome(inst) + + +def la_speed(task, inst, v0): + """middle of the longest run of LA-replay successes on a 0.01 grid around the oracle speed""" + from importlib import import_module + mod = import_module(type(task).__module__) + grid = [round(v, 2) for v in np.arange(round(v0 - 0.10, 2), round(v0 + 0.10, 2) + 1e-9, 0.01) + if mod.V_MIN <= v <= mod.V_MAX] + ok = [bool(la_replay(task, inst, dict(speed=v))["success"]) for v in grid] + best, run = [], [] + for v, s in zip(grid, ok): + run = run + [v] if s else [] + if len(run) > len(best): + best = run + if not best: + return None, dict(zip(map(str, grid), ok)) + return best[len(best) // 2], dict(zip(map(str, grid), ok)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", default=os.path.join(ROOT, "results", "_ladder", "fix_validate.json")) + ap.add_argument("--only", default="") + a = ap.parse_args() + rows, tasks = [], {} + for key, it in sorted(instances().items()): + if a.only and it["task"] != a.only: + continue + t0 = time.time() + task = tasks.setdefault(it["task"], TASKS[it["task"]](cam_res=64)) + inst = task.sample_instance(it["seed"]) + clean = {k: v for k, v in inst.items() if not k.startswith("_")} + row = dict(key=key, models=it["models"], inst_matches_log=same(json.loads(json.dumps(clean, default=float)), + it["logged"])) + hist = task.run_scripted("oracle", inst, k=1) + params = hist[0]["params"] + row["oracle_success"] = bool(hist[0]["outcome"]["success"]) + row["oracle_failure"] = hist[0]["outcome"].get("failure") + row["params"] = json.loads(json.dumps(params, default=float)) + if it["task"] in ("l5_slide_to_target", "l5_tablecloth_pull"): + v, sweep = la_speed(task, inst, float(params["speed"])) + row["oracle_speed"], row["la_sweep"] = float(params["speed"]), sweep + params = dict(params, speed=v if v is not None else float(params["speed"])) + row["params"] = json.loads(json.dumps(params, default=float)) + text = arm_specs.fix(it["task"], clean, params) + row["fix"] = text + row["no_axis_labels"] = strip_axes(text) == text + row["no_internal_names"] = not any(b in text for b in BANNED) + if it["task"] in ("l5_slide_to_target", "l5_tablecloth_pull"): + out = la_replay(task, inst, params) + row["la_replay_success"] = bool(out["success"]) + row["la_replay_failure"] = out.get("failure") + row["ok"] = bool(row["inst_matches_log"] and row["oracle_success"] and row["no_axis_labels"] + and row["no_internal_names"] and row.get("la_replay_success", True)) + row["seconds"] = round(time.time() - t0, 1) + rows.append(row) + print(f"{'OK ' if row['ok'] else 'BAD'} {key:28s} oracle={row['oracle_success']} " + f"la={row.get('la_replay_success', '-')} inst={row['inst_matches_log']} ({row['seconds']}s)", flush=True) + os.makedirs(os.path.dirname(a.out), exist_ok=True) + json.dump(dict(rows=rows, n=len(rows), n_ok=sum(r["ok"] for r in rows)), open(a.out, "w"), indent=1) + print(f"{sum(r['ok'] for r in rows)}/{len(rows)} ok -> {a.out}") + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/agent/backends/base.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/agent/backends/base.py new file mode 100644 index 0000000000000000000000000000000000000000..214f2e2f1a11942180f655914409b7d43b45723d --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/agent/backends/base.py @@ -0,0 +1,82 @@ +"""Backend interface: a backend maps a conversation (+ tool specs) to the next tool call(s).""" +import os +import sys +from dataclasses import dataclass, field +from typing import Optional + +# Normally the API SDKs (`openai`, `anthropic`, `google-genai`) are installed in the venv (setup/install.sh). +# Optionally they can live in a separate `pip install --target` directory, given by LFF_API_SDK_DIR (older name: +# LFF_OPENAI_SDK_DIR), that is APPENDED to sys.path so every package already in the venv keeps precedence. +API_SDK_DIR = os.environ.get("LFF_API_SDK_DIR") or os.environ.get("LFF_OPENAI_SDK_DIR", "") +OPENAI_SDK_DIR = API_SDK_DIR # old name + + +def import_sdk(module): + """Import an API SDK module ("openai", "anthropic", "google.genai").""" + import importlib + try: + return importlib.import_module(module) + except ImportError: + if API_SDK_DIR and os.path.isdir(API_SDK_DIR) and API_SDK_DIR not in sys.path: + sys.path.append(API_SDK_DIR) + return importlib.import_module(module) + + +def import_openai(): + return import_sdk("openai") + + +@dataclass +class BackendResponse: + tool_calls: list = field(default_factory=list) # [ToolCall] + text: Optional[str] = None # visible assistant text (e.g. the diagnosis) + reasoning_summary: Optional[str] = None + usage: dict = field(default_factory=dict) # input_tokens, cached_tokens, output_tokens, reasoning_tokens + latency_s: float = 0.0 + raw: Optional[list] = None # backend-specific items to replay in later requests (e.g. reasoning items) + request_stats: dict = field(default_factory=dict) # n_images, n_items, bytes, ... + status: str = "ok" + error: Optional[str] = None + + +@dataclass +class RunInfo: + task: object # privileged: only the scripted backend may look at task / inst + inst: dict + seed: int + k: int + protocol: str + feedback: str + memory: str + + +@dataclass +class AttemptInfo: + attempt: int + history: list # AttemptRecords visible to the agent under the memory mode (already selected) + continuing: bool = False # within protocol: continuing after a failed done + + +class Backend: + name = "base" + + def begin_run(self, info: RunInfo): + pass + + def begin_attempt(self, info: AttemptInfo): + pass + + def act(self, conv, tools) -> BackendResponse: + raise NotImplementedError + + def on_tool_result(self, call, result): + pass + + def end_attempt(self) -> dict: + return {} + + def end_run(self): + pass + + def config(self) -> dict: + return dict(name=self.name) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/agent/backends/openai_responses.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/agent/backends/openai_responses.py new file mode 100644 index 0000000000000000000000000000000000000000..853ba2d0cafd5859a689816ee7541ea3f0d41ca4 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/agent/backends/openai_responses.py @@ -0,0 +1,240 @@ +"""OpenAI Responses API backend (default model gpt-6-astra). + +Stateless requests: every call re-sends instructions + tools + the full (pruned) conversation with +store=False; reasoning items are replayed with their encrypted content so the model keeps its chain +of thought across tool calls within an attempt. The request prefix (instructions, tools, task text, +packed history of earlier attempts) is byte-identical across the calls of an attempt, which is what +OpenAI's automatic prompt caching needs. Images go in as base64 JPEG data URLs. + +Key and endpoint come from OPENAI_API_KEY / OPENAI_BASE_URL. Nothing here is executed at import time; +the client is created lazily on the first real call (tests inject a mock client). +""" +import json +import os +import time + +from ..context import ToolCall, prune_live_images +from .base import Backend, BackendResponse, import_openai + +# GPT-6 Astra: reasoning.effort supports low/medium/high/xhigh/max; `none` is NOT supported. +GPT6_ASTRA_EFFORTS = ("low", "medium", "high", "xhigh", "max") + + +def _get(obj, key, default=None): + if isinstance(obj, dict): + return obj.get(key, default) + return getattr(obj, key, default) + + +def _to_dict(item): + if isinstance(item, dict): + return dict(item) + if hasattr(item, "to_dict"): + return item.to_dict(mode="json") + if hasattr(item, "model_dump"): + return item.model_dump(mode="json", exclude_none=True) + return dict(vars(item)) + + +def responses_tools(specs, strict=True): + return [dict(type="function", name=s["name"], description=s["description"], parameters=s["parameters"], + strict=strict) for s in specs] + + +class OpenAIResponsesBackend(Backend): + name = "openai" + + def __init__(self, model="gpt-6-astra", reasoning_effort="medium", reasoning_summary=None, image_detail="auto", + max_output_tokens=None, service_tier=None, prompt_cache_key=None, prompt_cache_retention=None, + store=False, replay_reasoning=True, max_live_images=16, jpeg_quality=90, timeout=900.0, + max_retries=4, extra_body=None, strict_tools=True, cache_breakpoints="history+last", + prompt_cache_options=None, client=None, http_client=None): + if model.startswith("gpt-6-astra") and reasoning_effort not in GPT6_ASTRA_EFFORTS: + raise ValueError(f"gpt-6-astra supports reasoning effort {GPT6_ASTRA_EFFORTS} (no 'none'), " + f"got {reasoning_effort!r}") + self.model = model + self.reasoning_effort = reasoning_effort + self.reasoning_summary = reasoning_summary + self.image_detail = image_detail + self.max_output_tokens = max_output_tokens + self.service_tier = service_tier + self.prompt_cache_key = prompt_cache_key + self.prompt_cache_retention = prompt_cache_retention + self.store = store + self.replay_reasoning = replay_reasoning + self.max_live_images = max_live_images + self.jpeg_quality = jpeg_quality + self.timeout = timeout + self.max_retries = max_retries + self.extra_body = extra_body + self.strict_tools = strict_tools + # explicit prompt-cache breakpoints (Responses API, gpt-5.6+): "none" | "history" | "history+last" + assert cache_breakpoints in ("none", "history", "history+last"), cache_breakpoints + self.cache_breakpoints = cache_breakpoints + self.prompt_cache_options = prompt_cache_options + self._client = client + self._http_client = http_client # optional custom transport (tests, proxies) + self._cache_key = prompt_cache_key + + def config(self): + return dict(name=self.name, model=self.model, reasoning_effort=self.reasoning_effort, + reasoning_summary=self.reasoning_summary, image_detail=self.image_detail, + max_output_tokens=self.max_output_tokens, service_tier=self.service_tier, + prompt_cache_key=self.prompt_cache_key, prompt_cache_retention=self.prompt_cache_retention, + store=self.store, replay_reasoning=self.replay_reasoning, max_live_images=self.max_live_images, + jpeg_quality=self.jpeg_quality, timeout=self.timeout, max_retries=self.max_retries, + extra_body=self.extra_body, cache_breakpoints=self.cache_breakpoints, + prompt_cache_options=self.prompt_cache_options, base_url=os.environ.get("OPENAI_BASE_URL")) + + # ------------------------------------------------------------------ client + def client(self): + if self._client is None: + key = os.environ.get("OPENAI_API_KEY") + if not key: + raise RuntimeError("OPENAI_API_KEY is not set; the OpenAI backend cannot run without it") + openai = import_openai() + kw = dict(api_key=key, base_url=os.environ.get("OPENAI_BASE_URL") or None, timeout=self.timeout, + max_retries=self.max_retries) + if self._http_client is not None: + kw["http_client"] = self._http_client + self._client = openai.OpenAI(**kw) + return self._client + + def begin_run(self, info): + if self.prompt_cache_key is None: + # route all calls of one run to the same cache shard + self._cache_key = f"lffbench:{getattr(info.task, 'name', 'task')}:{info.seed}" + + # ------------------------------------------------------------------ request + def convert_items(self, items): + out = [] + last_user = max((i for i, it in enumerate(items) if it["kind"] == "user"), default=-1) + for i, it in enumerate(items): + kind = it["kind"] + if kind == "user": + content = [] + for p in it["parts"]: + if p["type"] == "text": + content.append(dict(type="input_text", text=p["text"])) + else: + content.append(dict(type="input_image", image_url=p["image"].data_url(self.jpeg_quality), + detail=self.image_detail)) + # explicit cache breakpoints: end of the stable history item (byte-identical for the whole + # attempt) and end of the newest input (reused by the next call of the attempt) + if content and ((self.cache_breakpoints != "none" and not it.get("live")) + or (self.cache_breakpoints == "history+last" and i == last_user)): + content[-1]["prompt_cache_breakpoint"] = dict(mode="explicit") + out.append(dict(role="user", content=content)) + elif kind == "assistant": + if it.get("raw") and it.get("backend") == self.name: + for r in it["raw"]: + if r.get("type") == "reasoning" and not self.replay_reasoning: + continue + out.append(r) + else: + if it.get("text"): + out.append(dict(role="assistant", content=it["text"])) + for tc in it["tool_calls"]: + out.append(dict(type="function_call", call_id=tc.id, name=tc.name, + arguments=tc.raw_arguments or json.dumps(tc.arguments))) + elif kind == "tool_output": + out.append(dict(type="function_call_output", call_id=it["call_id"], output=it["text"])) + else: + raise ValueError(kind) + return out + + def build_request(self, conv, tools): + items = prune_live_images(conv.items, self.max_live_images) + req = dict(model=self.model, instructions=conv.system, input=self.convert_items(items), + tools=responses_tools(tools, self.strict_tools), tool_choice="auto", parallel_tool_calls=False, + store=self.store) + reasoning = dict(effort=self.reasoning_effort) + if self.reasoning_summary: + reasoning["summary"] = self.reasoning_summary + req["reasoning"] = reasoning + if not self.store and self.replay_reasoning: + req["include"] = ["reasoning.encrypted_content"] + if self.max_output_tokens: + req["max_output_tokens"] = int(self.max_output_tokens) + if self.service_tier: + req["service_tier"] = self.service_tier + if self._cache_key: + req["prompt_cache_key"] = self._cache_key + if self.prompt_cache_retention: + req["prompt_cache_retention"] = self.prompt_cache_retention + if self.prompt_cache_options: + req["prompt_cache_options"] = dict(self.prompt_cache_options) + if self.extra_body: + req["extra_body"] = dict(self.extra_body) + return req + + @staticmethod + def request_stats(req): + n_img, img_bytes, txt = 0, 0, len(req.get("instructions") or "") + for it in req["input"]: + for c in (it.get("content") if isinstance(it.get("content"), list) else []): + if c.get("type") == "input_image": + n_img += 1 + img_bytes += len(c["image_url"]) + elif "text" in c: + txt += len(c["text"]) + if isinstance(it.get("content"), str): + txt += len(it["content"]) + if it.get("type") == "function_call_output": + txt += len(it["output"]) if isinstance(it["output"], str) else 0 + if it.get("type") == "function_call": + txt += len(it.get("arguments", "")) + tools_chars = len(json.dumps(req.get("tools", []))) + return dict(n_images=n_img, image_payload_bytes=img_bytes, text_chars=txt + tools_chars, + n_input_items=len(req["input"])) + + # ------------------------------------------------------------------ call + def act(self, conv, tools): + req = self.build_request(conv, tools) + stats = self.request_stats(req) + t0 = time.time() + resp = self.client().responses.create(**req) + out = self.parse_response(resp) + out.latency_s = time.time() - t0 + out.request_stats = stats + return out + + def parse_response(self, resp): + calls, texts, summ = [], [], [] + output = _get(resp, "output") or [] + for item in output: + t = _get(item, "type") + if t == "function_call": + raw = _get(item, "arguments") or "" + try: + args = json.loads(raw) if raw else {} + except json.JSONDecodeError: + args = {} + calls.append(ToolCall(id=_get(item, "call_id"), name=_get(item, "name"), arguments=args, + raw_arguments=raw)) + elif t == "message": + for c in _get(item, "content") or []: + if _get(c, "type") == "output_text": + texts.append(_get(c, "text") or "") + elif t == "reasoning": + for s in _get(item, "summary") or []: + summ.append(_get(s, "text") or "") + u = _get(resp, "usage") + usage = {} + if u is not None: + itd = _get(u, "input_tokens_details") + otd = _get(u, "output_tokens_details") + usage = dict(input_tokens=_get(u, "input_tokens", 0) or 0, + cached_tokens=(_get(itd, "cached_tokens", 0) or 0) if itd is not None else 0, + cache_write_tokens=(_get(itd, "cache_write_tokens", 0) or 0) if itd is not None else 0, + output_tokens=_get(u, "output_tokens", 0) or 0, + reasoning_tokens=(_get(otd, "reasoning_tokens", 0) or 0) if otd is not None else 0) + status = _get(resp, "status") or "completed" + err = None + if status == "incomplete": + err = "incomplete: " + str(_get(_get(resp, "incomplete_details"), "reason")) + elif not output and u is None: # seen through a gateway: no output and no usage; the player asks again + status, err = "incomplete", "empty response (no output, no usage)" + return BackendResponse(tool_calls=calls, text="\n".join(t for t in texts if t) or None, + reasoning_summary="\n".join(s for s in summ if s) or None, usage=usage, + raw=[_to_dict(i) for i in output], status=status, error=err) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/arm_specs/l2_turntable_restore.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/arm_specs/l2_turntable_restore.py new file mode 100644 index 0000000000000000000000000000000000000000..2f83f3b7e5ff6a3aea813f12af38833b11db7818 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/arm_specs/l2_turntable_restore.py @@ -0,0 +1,73 @@ +"""Controlled-arm spec for l2_turntable_restore (2026-10-12). + +Hidden variable: inst["q0"], the turntable's start angle (rad, + = counter-clockwise seen from above). It is the only +thing the agent has to remember: the main task forces a large turn of the disc (to bring the butter out from under the +shelf), after which nothing in the scene shows the start angle. apply_instance() places the disc at q0 and puts the +butter at disc-frame angle theta (so its world azimuth is theta + q0) on every reset, and reset_instance() records the +start angle from the simulator, so overriding "q0" alone is enough. + +Geometry used below (TurntableRestore.butter_to_basket): with the butter at world azimuth az (about the disc axis) +and box yaw az + tilt, the main task turns the disc by T = wrap(PICK_AZ - tilt - az), PICK_AZ = +90 deg (open side). +Its sign flips at az = flip = -90 deg - tilt (the middle of the covered side); |T| = 180 deg - |az - flip|. + +h0 -> q0 with the butter already at PICK_AZ (open side, long axis along world y): the main task needs no turn + (T ~ 0), so the scripted naive (main task, then stop) leaves the disc at its start angle and succeeds. + NB: the instruction's "under the shelf" is then not literally true (the butter is on the open half). +twin -> q0 with the butter still under the shelf but 35 deg on the OTHER side of flip: the main task turns the disc + the opposite way (|T| = 145 deg, inside the measured 136-179 deg range), so naive still fails visibly, and the + correction (turn back) has the opposite sign; the twin's start angle differs from the original's by + 35 deg + |az - flip| >= 35 deg (tolerance 15 deg), so restoring to the twin's remembered marks fails here. +reveal -> the start angle stated as the direction the yellow stripe points (seen from above), in robot-centric words + (forward = away from the robot, counter-clockwise as in the F2 feedback). +""" +import numpy as np + +HIDDEN_KEYS = ("q0",) + +TARGET = "butter_1" +PICK_AZ = np.pi / 2 # TurntableRestore.PICK_AZ +TWIN_OFF = np.radians(35.0) +STRIPE_ANG = np.pi # disc-frame angle of the yellow stripe (l2_turntable.STRIPE_ANG) + + +def _wrap(a): + return float((a + np.pi) % (2 * np.pi) - np.pi) + + +def _geom(inst): + th, tilt = float(inst["theta"][TARGET]), float(inst["tilt"][TARGET]) + return th, tilt, -np.pi / 2 - tilt + + +def h0(inst): + th, tilt, _ = _geom(inst) + return {"q0": _wrap(PICK_AZ - tilt - th)} + + +def twin(inst): + th, tilt, flip = _geom(inst) + s = 1.0 if _wrap(th + float(inst["q0"]) - flip) >= 0 else -1.0 + return {"q0": _wrap(flip - s * TWIN_OFF - th)} + + +def _compass(deg): + names = ("forward", "forward-left", "left", "backward-left", "backward", "backward-right", "right", "forward-right") + return names[int(np.floor(((deg % 360) + 22.5) / 45.0)) % 8] + + +def reveal(inst): + az = np.degrees(_wrap(float(inst["q0"]) + STRIPE_ANG)) + side = "counter-clockwise" if az >= 0 else "clockwise" + return (f"Note: at the start, seen from above, the yellow stripe on the turntable points out from the turntable's " + f"centre {abs(az):.0f} deg {side} from straight forward (roughly {_compass(az)}); that is the angle the " + f"turntable is at now.") + + +def fix(inst, params): + """Ladder Fix rung (docs/20): the oracle turns the disc back to the saved start angle after the butter is out.""" + az = np.degrees(_wrap(float(inst["q0"]) + STRIPE_ANG)) + side = "counter-clockwise" if az >= 0 else "clockwise" + return (f"A way to succeed: after the butter is in the basket, turn the turntable back to its start angle before " + f"you finish. At the start, seen from above, the yellow stripe pointed {abs(az):.0f} deg {side} from " + f"straight forward (roughly {_compass(az)}). Grasp a red peg and move the gripper along the rim to turn " + f"the disc until the stripe points that way again (within 15 deg), then release the peg and finish.") diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/arm_specs/l5_tablecloth_pull.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/arm_specs/l5_tablecloth_pull.py new file mode 100644 index 0000000000000000000000000000000000000000..d72cb9403cf21f0b5deead7e856fccc350305744 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/arm_specs/l5_tablecloth_pull.py @@ -0,0 +1,61 @@ +"""Controlled arms for l5_tablecloth_pull (docs/14 §6). + +Hidden variable: mu, the cube's friction (cube-board and cube-table contacts; apply_instance() sets it on every reset, +oracle_params() bisects the pull speed with it). The layout keys (board_xy, band_d) are left alone: band_d was sampled +from the original mu, but it is the visible band position, so H0 and the twin keep it and move only mu. + +Physics (measured, 2026-10-12): the cube's displacement toward the robot grows with mu and shrinks with the pull speed +up to ~0.8 m/s (0.8 and 1.0 m/s give identical results: the controller saturates). The naive policy yanks at 0.6 m/s. +Every original instance lands SHORT of the band (cube forward of it, err -1.6 .. -3.5 cm): the lesson is "pull +slower". + + h0 mu at which the 0.6 m/s yank lands the cube on the band's centre line (calibrated per full5 seed by a + simulated sweep; a linear fit in band_d for other seeds). + twin the opposite trap: mu high enough that the 0.6 m/s yank drags the cube PAST the band toward the robot + (err +1.5 .. +2.7 cm), so the lesson is "pull faster" (the twin's oracle pulls at 0.64-0.79 m/s; agents can + command up to 1.0 m/s). Applying that lesson to the original makes its cube land even further short. + The window is narrow: above it the cube cannot be stopped in the band even at the saturated top speed, so the + twin's naive error is only ~1.5-2.7 cm (similar size to the original's short-fall) and the twin's oracle is + within 0.2-0.5 cm of the band tolerance on some seeds. Calibrated per seed; for other seeds 1.2 x the H0 mu. + reveal states the cube's friction coefficient (the only fact that differs between instances). +""" + +HIDDEN_KEYS = ("mu",) + +# Calibrated 2026-10-12 with the scripted policies (scratchpad arms/fine.py; deterministic sim). +# seed: (h0 mu, naive err at h0 [cm]), (twin mu, naive err [cm], twin oracle speed [m/s], twin oracle err [cm]) +_CAL = { + 3000: dict(h0=0.1543, twin=0.1876), # h0 +0.08; twin naive +1.65, oracle 0.719 m/s +0.60 + 3001: dict(h0=0.1744, twin=0.1995), # h0 +0.13; twin naive +2.17, oracle 0.638 m/s +0.47 + 3002: dict(h0=0.1393, twin=0.1716), # h0 -0.11; twin naive +1.48, oracle 0.759 m/s +0.78 + 3003: dict(h0=0.1442, twin=0.1775), # h0 +0.08; twin naive +2.18, oracle 0.759 m/s +0.44 + 3004: dict(h0=0.1944, twin=0.2250), # h0 +0.06; twin naive +2.74, oracle 0.790 m/s +0.51 +} + + +def _h0_mu(inst): + c = _CAL.get(int(inst.get("seed", -1))) + return c["h0"] if c else 0.0835 + 1.485 * float(inst["band_d"]) + + +def h0(inst): + return {"mu": float(_h0_mu(inst))} + + +def twin(inst): + c = _CAL.get(int(inst.get("seed", -1))) + return {"mu": float(c["twin"] if c else 1.2 * _h0_mu(inst))} + + +def reveal(inst): + return (f"The red cube's friction coefficient (against the board and against the table) is about " + f"{float(inst['mu']):.3f}.") + + +def fix(inst, params): + """Ladder Fix rung (docs/20): one pull of 25 cm at the oracle speed (bisection with the true mu), as + l5_tablecloth_pull.execute; move_eef speed = Skills.move_to speed.""" + v = float(params["speed"]) + return (f"A way to succeed: pull at the right speed. Grasp the black handle (jaws closing across its 4 cm width), " + f"then in one move_eef command pull the board straight towards the robot by 25 cm at speed {v:.2f}; then " + f"open the gripper and lift. The cube then lands in the green band.") diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/arm_specs/lh_tidy_stack.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/arm_specs/lh_tidy_stack.py new file mode 100644 index 0000000000000000000000000000000000000000..a842f619205b88ccc9da3943f48f4f06bfb8e630 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/arm_specs/lh_tidy_stack.py @@ -0,0 +1,18 @@ +"""Layer-4 intervention texts for lh_tidy_stack (2026-10-30, reports/layer4_intervention_20261030). No h0 / twin: this task is +not in the controlled arms of full5. + +Hidden variable: inst["soft_colour"] -- the empty soft carton among the four boxes (None in benign instances). +reveal says which box is soft and how much it carries; not where to put it. +fix the oracle's order (lh_tidy_stack.oracle_params: rigid boxes first, the soft box last, then the cup). +""" +HIDDEN_KEYS = ("soft_colour",) + + +def reveal(inst): + return (f"The {inst['soft_colour']} box is an empty, soft carton. It carries one thing, but gives way as soon as a " + f"second thing rests above it, and everything above it slides off the pile.") + + +def fix(inst, params): + return (f"A way to succeed: stack the other three boxes first, put the {inst['soft_colour']} box on top of them last, " + f"and stand the cup on it. It then carries only the cup.") diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/harnesses/framework_codex.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/harnesses/framework_codex.py new file mode 100644 index 0000000000000000000000000000000000000000..68a8d7d09835f053760d9d0ca718cd79959b97e4 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/harnesses/framework_codex.py @@ -0,0 +1,542 @@ +"""Shared launcher for robot frameworks using a native Codex backend. + +The external integration contract is Session.first_message(), Session.tool_specs(), +and Session.call(name, arguments). This launcher owns isolation, model configuration, +pins, trajectory collection and audits; framework plugins own their native loop. +Based on the validated RPent launcher; RPent's historical launcher remains frozen. +""" +import hashlib +import json +import os +import shutil +import subprocess +import time + +from . import contract as C +from . import pins +from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info, + gateway_env, new_run_dir, proxy_env, snapshot_tree) +from .codex import (AUTH_FILE, Codex, CATALOG_FILE, CATALOGS, DISABLE, EXPECTED_TOP_GENERIC, OFFICIAL_API, codex_bin, model_catalog, + request_fingerprint, toml_str) +from .fakeapi import FakeResponses +from .trajectory import TrajWriter + +ROOT = C.ROOT +JAIL_FRAMEWORK_DIR = "/opt/lffjail/hjail/framework" +BASE_PATH = "/usr/bin:/bin" +MCP_SERVER = "lff" +MCP_TOOLS = ["robot", "shell", "view_images"] +TREE_SKIP = {".git", "__pycache__", ".pytest_cache", ".ruff_cache", ".mypy_cache", "docs", "tests", ".github"} + + + +def tree_sha256(root, skip=TREE_SKIP): + """sha256 over (relative path, file sha256 / symlink target) of every file under root, skipping `skip` dirs.""" + h = hashlib.sha256() + for dp, dn, fn in os.walk(root): + dn[:] = sorted(d for d in dn if d not in skip) + for f in sorted(fn): + if f.endswith(".pyc"): + continue + p = os.path.join(dp, f) + rel = os.path.relpath(p, root) + if os.path.islink(p): + h.update(f"L {rel} {os.readlink(p)}\n".encode()) + else: + h.update(f"F {rel} {C.sha256_file(p)}\n".encode()) + return h.hexdigest() + + +def runtime_info(home): + """The robot framework runtime: upstream commit, our patch on top, and the tree hash of src + venv.""" + src, venv = os.path.join(home, "src"), os.path.join(home, "venv") + for d in (src, venv): + if not os.path.isdir(d): + raise HarnessRefused(f"robot framework runtime incomplete: {d} missing (run the selected framework setup script under integrations/)") + + def git(*a): + r = subprocess.run(["git", "-C", src] + list(a), capture_output=True, text=True, timeout=60) + return r.stdout.strip() if r.returncode == 0 else None + commit = git("rev-parse", "HEAD") + patch = subprocess.run(["git", "-C", src, "diff", "HEAD"], capture_output=True, timeout=60).stdout + untracked = (git("ls-files", "--others", "--exclude-standard") or "").split() + return dict(home=home, commit=commit, patch_sha256=hashlib.sha256(patch).hexdigest(), + untracked=sorted(u for u in untracked if "__pycache__" not in u), + tree_sha256=hashlib.sha256((tree_sha256(src) + tree_sha256(venv)).encode()).hexdigest()) + + +def jail_runtime_copy(home, tree): + """A verified read-only copy of the runtime under /opt/lffjail/hjail/framework (visible in the jail; /mnt is not).""" + dst = os.path.join(JAIL_FRAMEWORK_DIR, f"framework-{tree[:12]}") + stamp = os.path.join(dst, ".tree_sha256") + if os.path.exists(stamp) and open(stamp).read().strip() == tree: + return dst + os.makedirs(JAIL_FRAMEWORK_DIR, mode=0o755, exist_ok=True) + tmp = dst + ".tmp-" + os.urandom(3).hex() + shutil.copytree(os.path.join(home, "src"), os.path.join(tmp, "src"), symlinks=True, + ignore=shutil.ignore_patterns(".git", "__pycache__", "*.pyc")) + shutil.copytree(os.path.join(home, "venv"), os.path.join(tmp, "venv"), symlinks=True, + ignore=shutil.ignore_patterns("__pycache__", "*.pyc")) + got = hashlib.sha256((tree_sha256(os.path.join(tmp, "src")) + tree_sha256(os.path.join(tmp, "venv"))).encode() + ).hexdigest() + if got != tree: + shutil.rmtree(tmp, ignore_errors=True) + raise HarnessRefused(f"copy of the robot framework runtime does not match its tree hash ({got[:12]} != {tree[:12]})") + for dp, dn, fn in os.walk(tmp): + os.chmod(dp, 0o755) + for f in fn: + p = os.path.join(dp, f) + if not os.path.islink(p): + os.chmod(p, os.stat(p).st_mode | 0o444) + with open(os.path.join(tmp, ".tree_sha256"), "w") as f: + f.write(tree) + if os.path.exists(dst): + shutil.rmtree(dst) + os.rename(tmp, dst) + return dst + + +def codex_overrides(effort, catalog_path): + """The main table's Codex configuration (lffbench/harnesses/codex.py Codex.config_args / --disable), as -c + overrides for robot framework's planner; the provider and the MCP server URL are robot framework's own (CODEX_BASE_URL, in-process).""" + return (["model_reasoning_effort=" + toml_str(effort), + "include_permissions_instructions=false", "include_environment_context=false", + "include_collaboration_mode_instructions=false", "skills.include_instructions=false", + "skills.bundled.enabled=false", 'web_search="disabled"', + f"mcp_servers.{MCP_SERVER}.enabled_tools=" + json.dumps(MCP_TOOLS), + f'mcp_servers.{MCP_SERVER}.default_tools_approval_mode="approve"', + f"mcp_servers.{MCP_SERVER}.required=true", f"mcp_servers.{MCP_SERVER}.startup_timeout_sec=60", + f"mcp_servers.{MCP_SERVER}.tool_timeout_sec=900", + "model_catalog_json=" + toml_str(catalog_path)] + + [f"features.{f}=false" for f in DISABLE]) + + +def _items(stream_path): + """Codex app-server notifications of one robot framework session (robot framework writes them as JSONL).""" + out = [] + if not os.path.exists(stream_path): + return out + for line in open(stream_path, encoding="utf-8", errors="replace"): + try: + out.append(json.loads(line)) + except ValueError: + continue + return out + + +def _item_of(ev): + it = (ev.get("payload") or {}).get("item") or {} + return it.get("root", it) if isinstance(it, dict) else {} + + +class RobotFrameworkCodex(HarnessAdapter): + name = "framework_codex" + runtime_home = "/nonexistent" + runtime_module = "lff_integration.run" + default_steps = 500 + uses_mcp = False + uses_gateway = True + can_resume = False + clean_dirs = ("home", "codex_home", "tmp", "out") + clean_allowed = {"codex_home": (CATALOG_FILE,)} + ancestor_files = ("AGENTS.md", "AGENTS.override.md", ".codex") + capabilities = dict( + only_benchmark_tools=Cap("partial", "preflight", "Codex generic catalog (as the main table): our 3 tools as " + "mcp__lff functions + residual resource×3 / request_user_input; robot framework registers " + "no tool of its own (no file tools, no finish)"), + images_reach_model=Cap("yes", "probe", "gateway content blocks preserved by the framework bridge, " + "JPEG with its own MIME type"), + non_persistent_session=Cap("yes", "probe", "robot framework's threads only in the one-time CODEX_HOME, removed after the " + "run; no preloaded or cross-episode framework memory"), + pinned_version=Cap("yes", "launch", "codex binary sha256 + robot framework commit / patch / tree hash (src + venv) in " + "harness.json; pin per version and tree"), + machine_readable_events=Cap("yes", "stream", "Codex app-server notifications per robot framework session " + "(codex.out.stream.jsonl) + robot framework run.json"), + tool_calls_logged=Cap("yes", "stream", "mcpToolCall items + gateway_transcript (named framework face) + events.jsonl"), + model_and_effort=Cap("yes", "preflight", "model and effort in the request checked"), + persistent_memory=Cap("absent", "probe", "memories feature off; empty one-time CODEX_HOME; robot framework memory not " + "constructed"), + instruction_file_injection=Cap("absent", "probe", "project_doc_max_bytes=0, empty CODEX_HOME, no skills"), + web_access=Cap("absent", "preflight", "web_search disabled (not in the tool list)"), + host_file_read=Cap("absent", "preflight", "no file tools; the only shell is the gateway's jailed shell"), + builtin_shell=Cap("absent", "preflight", "shell_tool and unified_exec disabled (not in the tool list)"), + subagent_delegation=Cap("absent", "preflight", "multi_agent disabled; no collaboration tools in the request"), + background_execution=Cap("absent", "preflight", "no background tool in the request"), + ) + + def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False, + jail=False, auth="apikey", catalog="generic", sessions=1, attempts_per_session=0, max_turns=500, + home=None, provider=None, auth_home=None): + """Common controlled Codex SDK launcher. + + The plugin entrypoint interprets its declared loop options. For SenseNova, + max_turns is the upstream SDK-step limit, not a provider-response count. + Robot commands, simulation time and tool budgets are always server-owned. + """ + if auth not in ("apikey", "chatgpt"): + raise ValueError("framework_codex auth must be apikey or chatgpt") + if catalog not in CATALOGS: + raise ValueError(f"catalog must be one of {CATALOGS}") + self.auth, self.catalog = auth, catalog + self._auth_manager = Codex(auth=auth, auth_home=auth_home, api_env=api_env, base_url=base_url, catalog=catalog) + self.api_env = self._auth_manager.api_env + self.base_url = self._auth_manager.base_url + self.clean_allowed = {"codex_home": ((AUTH_FILE,) if auth == "chatgpt" else ()) + (CATALOG_FILE,)} + self.timeout_s, self.pins_dir, self.allow_unpinned = timeout_s, pins_dir, allow_unpinned + self.sessions, self.attempts_per_session, self.max_turns = int(sessions), int(attempts_per_session), \ + int(max_turns) + self.home = home or os.environ.get("LFF_FRAMEWORK_HOME") or self.runtime_home + self.proxy = proxy_env() + self._version = None + self._runtime = None + self.runtime_dir = self.home + if jail: + from .jail import HarnessJail + self.jail = HarnessJail(codex_bin(), proc="static") + + # ------------------------------------------------------------------------------------------------ identity + def runtime(self): + if self._runtime is None: + self._runtime = runtime_info(self.home) + if self.jail is not None: + self.runtime_dir = jail_runtime_copy(self.home, self._runtime["tree_sha256"]) + return self._runtime + + def version(self): + if self._version is None: + b = codex_bin() + out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent", + CODEX_HOME="/nonexistent"), + capture_output=True, text=True, timeout=60) + v = (out.stdout.strip().split() or ["?"])[-1] + rt = self.runtime() + self._version = dict(version=v, binary=binary_info(b), + framework=dict(commit=rt["commit"], patch_sha256=rt["patch_sha256"], + tree_sha256=rt["tree_sha256"], untracked=rt["untracked"])) + return self._version + + def pin_key(self, ep): + v = self.version() + mode = "" if self.auth == "apikey" else "-chatgpt" + name = f"{self.name}{mode}-{self.catalog}-{v['framework']['tree_sha256'][:12]}" + return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort) + + def anchor_pin_key(self, ep): + """The main table's codex pin for the same model / effort (apikey, same catalog).""" + v = self.version() + name = "codex" + ("" if self.auth == "apikey" else "-chatgpt") + ("" if self.catalog == "native" else f"-{self.catalog}") + return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort) + + def auth_info(self): + if self.auth == "chatgpt": + return self._auth_manager.auth_info() + return dict(mode="apikey", credential_var="CODEX_API_KEY", credential_set=bool(self.api_env.get( + "OPENAI_API_KEY")), keys=["CODEX_API_KEY"]) + + def config_info(self): + return dict(auth=self.auth, catalog=self.catalog, sessions=self.sessions, attempts_per_session=self.attempts_per_session, + max_turns=self.max_turns, framework=self.version()["framework"]) + + # ------------------------------------------------------------------------------------------------ prepare + def _state_dirs(self, hexname=None): + root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate") + os.makedirs(root, exist_ok=True) + state = dict(state=root, **{k: os.path.join(root, k) for k in ("home", "codex_home", "tmp", "out")}) + for k in ("home", "codex_home", "tmp", "out"): + os.makedirs(state[k], exist_ok=True) + return state + + def _install_catalog(self, codex_home, ep): + cat, src = model_catalog(self.catalog, self.version()["version"], ep.model, None, ep.effort) + path = os.path.join(codex_home, CATALOG_FILE) + with open(path, "w") as f: + json.dump(cat, f) + return path, C.sha256_file(path), os.path.relpath(src, ROOT) + + def argv(self, ep, out_dir, sessions=None, preflight=False): + py = os.path.join(self.runtime_dir, "venv", "bin", "python") + return [py, "-m", self.runtime_module, "--model", ep.model, "--effort", ep.effort, "--out", out_dir, + "--sessions", str(sessions or self.sessions), "--attempts-per-session", str(self.attempts_per_session), + "--max-turns", str(self.max_turns), "--timeout-s", str(int(self.timeout_s) - 60)] \ + + (["--no-continue"] if preflight else []) + + def env(self, state, ep, base_url, work): + e = dict(PATH=BASE_PATH, HOME=state["home"], TMPDIR=state["tmp"], CODEX_HOME=state["codex_home"], + CODEX_BIN=(self.jail.binary_jailed if self.jail is not None else codex_bin()), + CODEX_BASE_URL=base_url, FRAMEWORK_CODEX_SANDBOX="read_only", FRAMEWORK_MCP_SERVER_NAME=MCP_SERVER, + FRAMEWORK_CODEX_CONFIG_OVERRIDES=json.dumps(codex_overrides( + ep.effort, os.path.join(state["codex_home"], CATALOG_FILE))), + FRAMEWORK_REPO_ROOT=work, LFF_FRAMEWORK_FACE=self.name, PYTHONPATH=os.path.join(self.runtime_dir, "src"), + PYTHONDONTWRITEBYTECODE="1", PYTHONUNBUFFERED="1", LANG="C.UTF-8") + if self.auth == "chatgpt": + # The native API provider declares env_key. Codex app-server still requires that + # variable even with requires_openai_auth=true, so select a separate provider + # with no env_key. Do not inject a dummy key or modify the upstream runtime. + provider_id = "lffsubscription" + overrides = json.loads(e["FRAMEWORK_CODEX_CONFIG_OVERRIDES"]) + overrides += ["model_provider=" + toml_str(provider_id), + f"model_providers.{provider_id}.name=" + toml_str(provider_id), + f"model_providers.{provider_id}.wire_api=\"responses\"", + f"model_providers.{provider_id}.base_url=" + toml_str(base_url), + f"model_providers.{provider_id}.requires_openai_auth=true"] + e["FRAMEWORK_CODEX_CONFIG_OVERRIDES"] = json.dumps(overrides) + e.update(self.proxy) + if self.api_env.get("OPENAI_API_KEY"): + e["CODEX_API_KEY"] = self.api_env["OPENAI_API_KEY"] + return e + + def prepare(self, ep, first_message, reuse_state=None): + self.version() + work = new_run_dir("/tmp/lffrun") + state = reuse_state or self._state_dirs(os.path.basename(work)) + if self.jail is not None: + self.jail.stderr_dir = ep.log_dir + if not reuse_state and os.listdir(state["codex_home"]): + raise HarnessRefused("CODEX_HOME is not empty") + cat_path, cat_sha, cat_src = self._install_catalog(state["codex_home"], ep) + return LaunchSpec(argv=self.argv(ep, state["out"]), env=self.env(state, ep, self.base_url, work), cwd=work, + run_dir=work, state_dirs=state, first_message=first_message, + stdout_path=os.path.join(ep.log_dir, "framework_stdout.txt"), + stderr_path=os.path.join(ep.log_dir, "framework_stderr.txt"), + config_files=dict(model_catalog_json=dict(path=cat_path, sha256=cat_sha, source=cat_src, + catalog=self.catalog, code_mode=False)), + timeout_s=self.timeout_s) + + def config_sha256(self, spec, ep): + argv = [a.replace(spec.state_dirs["out"], "").replace(self.runtime_dir, "") + for a in spec.argv] + hidden = ("HOME", "TMPDIR", "CODEX_HOME", "CODEX_BIN", "CODEX_API_KEY", "FRAMEWORK_REPO_ROOT", "PYTHONPATH", + "LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") + PROXY_KEYS + NO_PROXY_KEYS + env = {k: v for k, v in spec.env.items() if k not in hidden} + env["FRAMEWORK_CODEX_CONFIG_OVERRIDES"] = env.get("FRAMEWORK_CODEX_CONFIG_OVERRIDES", "").replace( + spec.state_dirs["codex_home"], "") + cat = (spec.config_files.get("model_catalog_json") or {}).get("sha256") + return C.sha256_json(dict(argv=argv, env=env, model_catalog_sha256=cat, + framework_tree_sha256=self.version()["framework"]["tree_sha256"])) + + # ------------------------------------------------------------------------------------------------ launch + def launch(self, spec, ep, skip_preflight=False): + """harness_run starts the gateway after prepare(), right before launch: hand its address to the process.""" + self._auth_manager._install_auth(spec.state_dirs["codex_home"]) + spec.env.update(gateway_env(ep.log_dir)) + return super().launch(spec, ep, skip_preflight=skip_preflight) + + def cleanup(self, spec): + self._auth_manager._sync_auth_back(spec.state_dirs.get("codex_home", "")) + super().cleanup(spec) + + def preflight(self, spec, ep, record_dir=None): + """The same framework process, one session, against a local fake Responses server that answers with text + only: no tool call reaches the gateway. Checks the first request (tools, developer message, parameters, + sandbox, robot framework's prefix + our first message) against the pins.""" + t0 = time.time() + fake = FakeResponses([[("text", "preflight ok")]], record_dir=record_dir).start() + pre = self._state_dirs() + try: + self._auth_manager._install_auth(pre["codex_home"]) + self._install_catalog(pre["codex_home"], ep) + env = self.env(pre, ep, fake.base_url, spec.cwd) + if self.auth == "apikey": + env["CODEX_API_KEY"] = "sk-preflight-not-a-key" + env.update({k: spec.env[k] for k in ("LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") if k in spec.env}) + argv = self.argv(ep, pre["out"], sessions=1, preflight=True) # no status call on the episode + r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd, + stdin=subprocess.DEVNULL, capture_output=True, timeout=300) + reqs = fake.model_requests() + if not reqs: + # Native planners may record failures only in run.json, with empty stdout/stderr. + record = os.path.join(pre["out"], "run.json") + detail = "" + if os.path.isfile(record): + with open(record) as f: + failed_run = json.load(f) + detail = "; ".join(str(s.get("error")) for s in failed_run.get("sessions", []) if s.get("error")) + raise HarnessRefused(f"preflight: no model request (rc={r.returncode}): " + f"{(r.stdout + r.stderr).decode('utf-8', 'replace')[-1200:]} {detail[-1200:]}") + body = reqs[0][1] + fp, problems = request_fingerprint(body, spec.cwd, spec.first_message, EXPECTED_TOP_GENERIC) + problems = [p for p in problems if not p.startswith("user input is not exactly our first message")] + users = [c.get("text") for it in body.get("input") or [] if it.get("type") == "message" + and it.get("role") == "user" for c in it.get("content") or []] + prefix = None + if len(users) != 1 or not users[0].endswith(spec.first_message): + problems.append(f"the first user message does not end with our first message ({len(users)} blocks)") + else: + prefix = users[0][:-len(spec.first_message)] + effort = (fp["params"].get("reasoning") or {}).get("effort") + if effort != ep.effort: + problems.append(f"reasoning.effort in request {effort!r} != {ep.effort!r}") + if fp["params"].get("model") != ep.model: + problems.append(f"model in request {fp['params'].get('model')!r} != {ep.model!r}") + if os.listdir(spec.cwd): + problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}") + mid_sha = C.sha256_json(fp) + full = dict(middle=fp, framework_prefix=prefix) + fp_sha = C.sha256_json(full) + anchor = pins.load(self.anchor_pin_key(ep), self.pins_dir) + out = dict(fingerprint_sha256=fp_sha, middle_fingerprint_sha256=mid_sha, + framework_prefix_sha256=C.sha256_text(prefix) if prefix is not None else None, + framework_prefix_chars=len(prefix) if prefix is not None else None, + developer_chars=fp["developer_chars"], n_requests=len(reqs), + top_tools=[t["name"] for t in fp["tools"]], catalog=self.catalog, effort_in_request=effort, + model_in_request=fp["params"].get("model"), sandbox=fp["sandbox"], + dt_s=round(time.time() - t0, 1), problems=problems, + anchor_pin=anchor and dict(key=anchor["key"], fingerprint_sha256=anchor["fingerprint_sha256"])) + if anchor is None: + out["anchor_status"] = "no main-table pin for this model / effort" + elif anchor["fingerprint_sha256"] != mid_sha: + problems.append(f"Codex request {mid_sha[:12]} != main-table pin {anchor['fingerprint_sha256'][:12]} " + f"({anchor['key']}): the middle layer is not the main table's") + else: + out["anchor_status"] = "match" + pin = pins.load(self.pin_key(ep), self.pins_dir) + out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"]) + out["fingerprint"] = full + if problems: + raise HarnessRefused("preflight: " + "; ".join(problems)) + if pin is None: + if not self.allow_unpinned: + raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck " + f"with --write-pins after the self-check passes)") + out["pin_status"] = "unpinned (allowed)" + elif pin["fingerprint_sha256"] != fp_sha: + raise HarnessRefused(f"preflight: fingerprint {fp_sha[:12]} != pinned {pin['fingerprint_sha256'][:12]} " + f"({pin['key']})") + else: + out["pin_status"] = "match" + return out + finally: + fake.stop() + self._auth_manager._sync_auth_back(pre["codex_home"]) + shutil.rmtree(pre["state"], ignore_errors=True) + + # ------------------------------------------------------------------------------------------------ collect + def collect(self, h): + spec, ep = h.spec, h.ep + dst = os.path.join(ep.log_dir, "framework") + if os.path.isdir(spec.state_dirs["out"]): + shutil.copytree(spec.state_dirs["out"], dst, dirs_exist_ok=True) + run = {} + if os.path.exists(os.path.join(dst, "run.json")): + run = json.load(open(os.path.join(dst, "run.json"))) + tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl")) + usage = dict(input=0, cached=0, output=0, reasoning=0) + items, threads, errors = [], [], [] + for sdir in sorted(os.listdir(os.path.join(dst, "sessions"))) if os.path.isdir(os.path.join(dst, "sessions")) \ + else []: + last = None + for ev in _items(os.path.join(dst, "sessions", sdir, "codex.out.stream.jsonl")): + m = ev.get("method") or ev.get("type") + p = ev.get("payload") or {} + if m == "thread/tokenUsage/updated": + last = (p.get("token_usage") or {}).get("total") or last + if p.get("thread_id") and p["thread_id"] not in threads: + threads.append(p["thread_id"]) + elif m in ("error", "fatal", "timeout"): + errors.append(ev) + elif m == "item/completed": + it = _item_of(ev) + t = it.get("type") + items.append(t) + if t == "agentMessage": + tw.add_step("agent", message=it.get("text", "")) + elif t == "reasoning": + tw.add_step("agent", reasoning=json.dumps(it.get("summary") or it.get("content") or "")) + elif t in ("mcpToolCall", "dynamicToolCall", "commandExecution", "fileChange"): + name = it.get("tool") or t + tw.add_step("agent", tool_calls=[dict(tool_call_id=it.get("id"), function_name=name, + native_name=f"{it.get('server', '')}.{name}", + item_type=t, arguments=it.get("arguments"), + session=sdir)]) + res = it.get("result") or {} + texts = [c.get("text", "") for c in res.get("content") or [] if c.get("type") == "text"] + imgs = sum(1 for c in res.get("content") or [] if c.get("type") == "image") + tw.add_result(it.get("id"), "\n".join(texts) if texts else json.dumps(it.get("error")), + bool(it.get("error")) or it.get("status") == "failed", imgs) + if last: + usage["input"] += last.get("input_tokens") or 0 + usage["cached"] += last.get("cached_input_tokens") or 0 + usage["output"] += last.get("output_tokens") or 0 + usage["reasoning"] += last.get("reasoning_output_tokens") or 0 + # Framework close-out uses the same counted gateway shell, outside + # the model stream. Keep it visible in trajectories and tool totals. + session_record = next((s for s in run.get("sessions", []) + if sdir == f"session_{s['number']:03d}"), {}) + handoff = session_record.get("handoff") or {} + if handoff: + call_id = f"framework-handoff-{sdir}" + tw.add_step("framework", tool_calls=[dict( + tool_call_id=call_id, function_name="shell", native_name=f"{MCP_SERVER}.shell", + item_type="frameworkToolCall", arguments=handoff["arguments"], session=sdir)]) + tw.add_result(call_id, "\n".join(c.get("text", "") for c in handoff["content"] + if c.get("type") == "text")) + v = self.version() + tw.set_header(session_id=",".join(threads), source="framework/sessions/*/codex.out.stream.jsonl", + agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort, + framework=v["framework"]), tools=EXPECTED_TOP_GENERIC) + tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], item_types=sorted(set(items)), + run={k: run.get(k) for k in ("stop", "finished", + "attempts_failed", "tool_calls")}, + sessions=len(run.get("sessions") or [])), + total_prompt_tokens=usage["input"], total_completion_tokens=usage["output"], + total_cached_tokens=usage["cached"], total_cost_usd=None, reasoning_tokens=usage["reasoning"]) + tw.write() + h.info.update(items=items, traj=tw, threads=threads, errors=errors, run=run) + return tw + + # ------------------------------------------------------------------------------------------------ audit + def audit(self, h): + spec, ep = h.spec, h.ep + v, notes = [], [] + items = h.info.get("items") or [] + bad = sorted({i for i in items if i not in ("userMessage", "agentMessage", "reasoning", "mcpToolCall", + "plan", "hookPrompt")}) + if bad: + v.append(f"items other than messages / reasoning / MCP calls: {bad}") + residual = [] + tw = h.info.get("traj") + for st in (tw.steps if tw else []): + for tc in st["tool_calls"]: + if tc["native_name"] == f"{MCP_SERVER}.{tc['function_name']}" and tc["function_name"] in MCP_TOOLS: + continue + if tc["function_name"] in ("list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"): + residual.append(tc["function_name"]) + else: + v.append(f"unexpected tool call {tc['native_name']}") + if residual: + notes.append(f"residual MCP-resource tool calls (empty): {residual}") + if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env): + v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}") + run = h.info.get("run") or {} + nsess = len(run.get("sessions") or []) + if len(h.info.get("threads") or []) > max(1, nsess): + v.append(f"{len(h.info['threads'])} Codex threads for {nsess} robot framework sessions") + if nsess > 1: + notes.append(f"{nsess} robot framework sessions (handoff after a session ended before the episode was over)") + if run.get("stop") not in (None, "episode over"): + notes.append(f"robot framework stopped: {run.get('stop')}") + left = dict(codex_home=snapshot_tree(spec.state_dirs["codex_home"]), home=snapshot_tree(spec.state_dirs["home"]), + work=snapshot_tree(spec.cwd)) + if left["work"]: + v.append(f"files in the work dir: {left['work']}") + foreign = [f for f in left["codex_home"] if f.startswith(("sessions/", "archived_sessions/")) + and not any(t in f for t in (h.info.get("threads") or []))] + if foreign: + v.append(f"session files other than this run's threads: {foreign}") + gt = os.path.join(ep.log_dir, "gateway_transcript.jsonl") + faces = set() + if os.path.exists(gt): + for line in open(gt): + try: + d = json.loads(line) + except ValueError: + continue + if d.get("ev") == "tool" and d.get("face"): + faces.add(d["face"]) + if faces - {self.name}: + v.append(f"gateway calls from other access paths: {sorted(faces)}") + out = dict(harness=self.name, violations=v, notes=notes, files_left=left, gateway_faces=sorted(faces), + item_types=sorted(set(items)), errors=h.info.get("errors"), run_stop=run.get("stop"), ok=not v) + with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f: + json.dump(out, f, indent=1) + return out diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/l1_height.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/l1_height.py new file mode 100644 index 0000000000000000000000000000000000000000..2f646b10c0ee78aeac6f5ce86d655bc26a42dc86 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/l1_height.py @@ -0,0 +1,448 @@ +"""L1-B height_bias: pick up a thin tile from the top of a wooden block and put it on the plate, with an arm whose +vertical calibration is off. + +Category system_identification (level L1, action fine-tuning): the method (top-down pick across the tile's short +side with the fingertips just above the block's top, carry, release above the plate) and the scene understanding +are right; only the robot's own vertical execution is off. + +Hidden variable: a fixed vertical calibration offset dz ~ U[2.0, 3.5] cm (always upward), added to every +commanded gripper position (`Skills(bias=(0, 0, dz))`): the gripper stops dz higher than commanded. The agent never +sees dz; positions reported back to it are in the commanded frame (`HeightSkills.reported_eef_pos`, and the agent +harness reports eef - bias), so the robot "believes" it reached the commanded height. + +Why the prior fails: the tile is 1.0 cm thick. Sent to the right height (fingertips just above the block's top), the +fingertips actually stop 2-3.5 cm higher, i.e. 1.1-2.6 cm above the tile's top face, and the jaws close in the air +above it (measured tolerance, 6 layouts: upward errors up to 0.4 cm still grasp, >= 0.7 cm never do, i.e. the fingers +must overlap the tile by ~4 mm). dz >= 2 cm also defeats a prior that aims lower: even with the grasp point commanded +level with the block's top (fingertips ~1 cm into the block), the fingertips end up >= 1.05 cm above the block's +top, i.e. not below the tile's top face -> missed. +Visible in the agentview image (gap between the closed fingers and the tile) and in the wrist image (fingers closed +over the tile). +A downward error would not fail (the fingertips land on the block's top and the compliant OSC still closes on the +tile; measured for -1 and -2 cm), so the offset is upward only. + +Why a raised block: the agent's move_to clips commanded targets to >= table + 0.5 cm. With the tile on the table, +compensating a 2-3.5 cm upward offset would need commands below the table top, which the interface refuses; on a +6-10 cm block the compensated commands stay well inside the workspace. + +What has to be learned: F2 reports how far above the tile's top face the grasp point and the fingertips were when the +jaws closed. Compared with where the policy meant to put them, that is dz itself, so after one failure dz can be +estimated and subtracted from every commanded height (pick and place alike). +""" +import re + +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +TILE, STAND, PLATE = "tile_1", "stand_1", "plate_1" +DISTRACTORS = ("butter_1", "chocolate_pudding_1") +FREE_OBJECTS = (TILE, PLATE) + DISTRACTORS +NAMES = {TILE: "red tile", STAND: "wooden block", PLATE: "plate", "butter_1": "butter", + "chocolate_pudding_1": "chocolate pudding"} +DESCR = {TILE: "thin red slab", STAND: "large wooden pedestal", PLATE: "round white dish", "butter_1": "small orange box", + "chocolate_pudding_1": "brown box"} + +TILE_HALF = (0.040, 0.0225, 0.005) # 8.0 x 4.5 x 1.0 cm (long side along the tile's x axis) +TILE_T = 2 * TILE_HALF[2] +STAND_HALF_XY = (0.075, 0.085) # 15 x 17 cm top +STAND_H_RANGE = (0.06, 0.10) +MASS = {TILE: 0.072, "butter_1": 0.250, "chocolate_pudding_1": 0.200, PLATE: 0.350} + +FINGER_BELOW_SITE = 0.0095 # lowest point of the finger collision meshes below the grasp site (measured 0.95 cm) +SITE_ABOVE_SURFACE = 0.0105 # scripted grasp height: grasp point 1.05 cm above the block top (fingertips ~1 mm above) +CARRY_ABOVE = 0.12 # carry height above the block top +RELEASE_GAP = 0.012 # tile bottom this far above the plate's rim at release +PLATE_R_OK = 0.040 # success: tile centre within this horizontal distance of the plate centre +DZ_MIN, DZ_MAX = 0.020, 0.035 +TILE_YAW_MAX = np.deg2rad(40) +HOME_XY = np.array([-0.21, 0.0]) + + +def _seg_dist(p, a, b): + ab = b - a + u = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0, 1) + return float(np.linalg.norm(a + u * ab - p)) + + +def _q(axis, a): + h = a / 2 + return {"z": np.array([np.cos(h), 0, 0, np.sin(h)])}[axis] + + +def _qmul(a, b): + w1, x1, y1, z1 = a + w2, x2, y2, z2 = b + return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, + w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2]) + + +def dir_words(dx, dy): + """Robot-frame description: +x = forward (away from the robot), +y = the robot's left.""" + parts = [] + if abs(dy) >= 0.0005: + parts.append(f"{100 * abs(dy):.1f} cm to the robot's {'left (+y)' if dy > 0 else 'right (-y)'}") + if abs(dx) >= 0.0005: + parts.append(f"{100 * abs(dx):.1f} cm {'forward (+x, away from the robot)' if dx > 0 else 'backward (-x, toward the robot)'}") + return " and ".join(parts) if parts else "exactly at the position" + + +def vert_words(h, what): + if h >= 0.0005: + return f"{100 * h:.1f} cm above {what}" + if h <= -0.0005: + return f"{100 * -h:.1f} cm below {what}" + return f"level with {what}" + + +class HeightSkills(Skills): + """Skills that log what the outcome measurement needs, whoever drives them (scripted policy or agent).""" + + def __init__(self, env, bias=None, recorder=None, stand_geoms=()): + super().__init__(env, bias=bias, recorder=recorder) + self.events = [] + m = env.sim.model + self._finger_geoms = { + side: [m.geom_name2id(g) for g in env.robots[0].gripper.important_geoms[side]] + for side in ("left_finger", "right_finger")} + self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_")] + self._obj_geoms = {n: envs.obj_geom_ids(env, n) for n in FREE_OBJECTS} + self._obj_geoms[STAND] = list(stand_geoms) + self.tile_z0 = float(envs.obj_pos(env, TILE)[2]) + self.tile_zmax = self.tile_z0 + self.tile_ref = envs.obj_pos(env, TILE) # tile position before the fingers last touched it + self.tile_ref_yaw = self.tile_yaw() + + def reported_eef_pos(self): + """End-effector position as the miscalibrated robot believes it to be (commanded frame). Anything shown to + the agent must use this, never eef_pos(), which is the true position and reveals the bias.""" + return self.eef_pos() - self.bias + + def move_to(self, target, *args, **kwargs): + rep = super().move_to(target, *args, **kwargs) + rep["pos"] = np.round(self.reported_eef_pos(), 4).tolist() + return rep + + def touching(self): + return [n for n, gs in self._obj_geoms.items() if envs.contacts_between(self.env, self._grip_geoms, gs)] + + def holding_tile(self): + """Both fingers in contact with the tile (robosuite's _check_grasp needs the finger *pads*, which miss a + 1 cm tile when it is gripped low on the finger meshes).""" + tg = self._obj_geoms[TILE] + return all(envs.contacts_between(self.env, gs, tg) for gs in self._finger_geoms.values()) + + def holding(self, obj_name): + """The agent harness reports `holding_object` through this; use the finger-contact test for the tile so a + tile gripped low on the fingers is not reported as dropped.""" + if obj_name == TILE: + return self.holding_tile() + return super().holding(obj_name) + + def tile_yaw(self): + xmat = self.env.sim.data.body_xmat[envs.body_id(self.env, TILE)].reshape(3, 3) + return float(np.arctan2(xmat[1, 0], xmat[0, 0])) + + def finger_min_z(self): + return float(self.eef_pos()[2] - FINGER_BELOW_SITE) + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.tile_zmax = max(self.tile_zmax, float(envs.obj_pos(self.env, TILE)[2])) + if self.grip < 0 and not envs.contacts_between(self.env, self._grip_geoms, self._obj_geoms[TILE]): + self.tile_ref = envs.obj_pos(self.env, TILE) + self.tile_ref_yaw = self.tile_yaw() + + def set_gripper(self, close, steps=15): + if close and self.grip < 0: + self.events.append(dict(kind="close", eef=self.eef_pos().tolist(), finger_z=self.finger_min_z(), + tile=envs.obj_pos(self.env, TILE).tolist(), + tile_ref=np.asarray(self.tile_ref).tolist(), tile_ref_yaw=self.tile_ref_yaw, + touching=self.touching(), + step=self.n_steps)) + elif not close and self.grip > 0 and self.holding_tile(): + self.events.append(dict(kind="release", eef=self.eef_pos().tolist(), + tile=envs.obj_pos(self.env, TILE).tolist(), + plate=envs.obj_pos(self.env, PLATE).tolist(), step=self.n_steps)) + return super().set_gripper(close, steps) + + +@register_task +class HeightBias(LFFTask): + name = "l1_height_bias" + level = "L1" + category = "system_identification" + capabilities = ("Perceive", "Utilize") + protocol = "cross" + instruction = "Pick up the red tile from the top of the wooden block and put it on the plate." + instruction_indirect = ("Pick up the thin flat red slab lying on the large wooden pedestal and put it on the " + "round white dish.") + pick_lift_min = 0.03 + + # ------------------------------------------------------------ scene + def make_bddl(self): + tile = register_generated("LffHbTile", box_xml("lff_hb_tile", TILE_HALF, (0.80, 0.16, 0.12, 1.0), + density=2000)) + stand = register_generated("LffHbStand", box_xml("lff_hb_stand", STAND_HALF_XY + (STAND_H_RANGE[1] / 2,), + (0.62, 0.47, 0.30, 1.0), density=1000), free=False) + objs = [(TILE, tile, "tile_region", (-0.21, -0.26, -0.19, -0.24)), + (PLATE, "plate", "plate_region", (-0.01, 0.24, 0.01, 0.26)), + ("butter_1", "butter", "butter_region", (-0.21, 0.24, -0.19, 0.26)), + ("chocolate_pudding_1", "chocolate_pudding", "pudding_region", (0.15, -0.26, 0.17, -0.24))] + fx = [(STAND, stand, "stand_region", (0.09, -0.01, 0.11, 0.01))] + return write_bddl(self.name, self.instruction, objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + self._base_quat = {n: envs.obj_quat(self.env, n) for n in FREE_OBJECTS} + m = self.env.sim.model + bid = m.body_name2id(self.env.fixtures_dict[STAND].root_body) + + def under(b): + while b > 0: + if b == bid: + return True + b = m.body_parentid[b] + return False + + self._stand_bid = bid + self._stand_geoms = [g for g in range(m.ngeom) if under(m.geom_bodyid[g])] + + def _place(self, name, xy, yaw, z0=envs.TABLE_Z): + q = _qmul(_q("z", yaw), self._base_quat[name]) + envs.set_obj_pose(self.env, name, [xy[0], xy[1], z0 + 0.3], quat_wxyz=q) + self.env.sim.forward() + qa, _ = envs.free_joint_addr(self.env, name) + self.env.sim.data.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (z0 + 0.0005) + self.env.sim.forward() + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + while True: + s = np.array([rng.uniform(-0.10, 0.02), rng.uniform(-0.17, 0.17)]) + plate = np.array([rng.uniform(-0.17, 0.08), rng.uniform(-0.25, 0.25)]) + if np.linalg.norm(plate - s) < 0.24 or abs(plate[1] - s[1]) < 0.12: + continue # not right behind the block as seen from the front camera + placed = [s, plate] + dis = {} + for name in DISTRACTORS: + for _ in range(300): + p = np.array([rng.uniform(-0.22, 0.12), rng.uniform(-0.27, 0.27)]) + if np.linalg.norm(p - s) < 0.16 or any(np.linalg.norm(p - o) < 0.12 for o in placed[1:]): + continue + if any(_seg_dist(p, a, b) < 0.09 for a, b in ((s, plate), (HOME_XY, s))): + continue + break + else: + break + placed.append(p) + dis[name] = dict(xy=p.round(5).tolist(), yaw=float(rng.uniform(-np.pi, np.pi))) + if len(dis) == len(DISTRACTORS): + break + stand_h = float(rng.uniform(*STAND_H_RANGE)) + tile_xy = s + rng.uniform(-0.02, 0.02, 2) + tile_yaw = float(rng.uniform(-TILE_YAW_MAX, TILE_YAW_MAX)) + dz = float(rng.uniform(DZ_MIN, DZ_MAX)) + return dict(seed=int(seed), stand_xy=s.round(5).tolist(), stand_h=stand_h, tile_xy=tile_xy.round(5).tolist(), + tile_yaw=tile_yaw, plate_xy=plate.round(5).tolist(), distractors=dis, bias=[0.0, 0.0, dz], + bias_dz=dz) + + def stand_top(self, inst): + return envs.TABLE_Z + inst["stand_h"] + + def apply_instance(self, inst): + m = self.env.sim.model + h = inst["stand_h"] + for g in self._stand_geoms: + m.geom_size[g, 2] = h / 2 + m.body_pos[self._stand_bid] = [inst["stand_xy"][0], inst["stand_xy"][1], envs.TABLE_Z + h / 2] + m.body_quat[self._stand_bid] = [1, 0, 0, 0] + for name, mass in MASS.items(): + envs.scale_mass(self.env, name, mass) + self.env.sim.forward() + self._place(TILE, inst["tile_xy"], inst["tile_yaw"], z0=self.stand_top(inst)) + self._place(PLATE, inst["plate_xy"], 0.0) + for name, v in inst["distractors"].items(): + self._place(name, v["xy"], v["yaw"]) + + def skill_bias(self, inst): + return np.array(inst["bias"], float) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.sk = HeightSkills(self.env, bias=self.skill_bias(inst), recorder=recorder, stand_geoms=self._stand_geoms) + self.start_pos = {n: envs.obj_pos(self.env, n) for n in FREE_OBJECTS} + return self.sk + + # ------------------------------------------------------------ outcome + def plate_rim_z(self): + lo, hi = self._aabb(PLATE) + return float(hi[2]) + + def _aabb(self, name): + m, d = self.env.sim.model, self.env.sim.data + lo, hi = np.full(3, np.inf), np.full(3, -np.inf) + for g in envs.obj_geom_ids(self.env, name): + R = d.geom_xmat[g].reshape(3, 3) + c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3] + hh = np.abs(R) @ m.geom_aabb[g, 3:] + lo, hi = np.minimum(lo, c - hh), np.maximum(hi, c + hh) + return lo, hi + + def on_plate(self): + p = envs.obj_pos(self.env, PLATE) + t = envs.obj_pos(self.env, TILE) + return bool(np.linalg.norm(t[:2] - p[:2]) < PLATE_R_OK and t[2] < self.plate_rim_z() + 0.015 + and envs.obj_upright_cos(self.env, PLATE) > 0.9 and envs.obj_min_z(self.env, PLATE) < envs.TABLE_Z + 0.01) + + def outcome(self, inst): + envs.settle(self.env, 40) + sk = self.sk + top = self.stand_top(inst) + p = envs.obj_pos(self.env, PLATE) + t = envs.obj_pos(self.env, TILE) + held = sk.holding_tile() + success = bool(self.on_plate() and not held) + picked = sk.tile_zmax > sk.tile_z0 + self.pick_lift_min + closes = [e for e in sk.events if e["kind"] == "close"] + last_close = closes[-1] if closes else None + releases = [e for e in sk.events if e["kind"] == "release" and last_close and e["step"] >= last_close["step"]] + end_off = t[:2] - p[:2] + on_stand = bool(t[2] > top - 0.005) + out = dict(success=success, picked=bool(picked), held_at_end=bool(held), tile_end=t.round(4).tolist(), + plate_end=p.round(4).tolist(), end_offset=end_off.round(4).tolist(), grasp_height=None, + fingertip_gap=None, grasp_xy_offset=None, touched_at_close=None, release_offset=None) + grasp_txt = "" + over_tile = True + if last_close is not None: + tile_top = last_close["tile_ref"][2] + TILE_HALF[2] + gh = last_close["eef"][2] - tile_top + fg = last_close["finger_z"] - tile_top + go = np.array(last_close["eef"][:2]) - np.array(last_close["tile_ref"][:2]) + a = last_close.get("tile_ref_yaw", 0.0) + along, across = go @ [np.cos(a), np.sin(a)], go @ [-np.sin(a), np.cos(a)] + # grasp point over the tile's footprint (the open fingers straddle it across its short side) + over_tile = bool(abs(along) <= TILE_HALF[0] and abs(across) <= TILE_HALF[1] + 0.01) + out["grasp_height"] = round(gh, 4) + out["fingertip_gap"] = round(fg, 4) + out["grasp_xy_offset"] = go.round(4).tolist() + out["grasp_over_tile"] = over_tile + out["touched_at_close"] = last_close["touching"] + face = "the top face of the red tile" if over_tile else "the level of the red tile's top face" + grasp_txt = (f"When the jaws closed, the grasp point (midway between the fingertips) was " + f"{vert_words(gh, face)} and the lowest points of the fingertips " + f"were {vert_words(fg, 'it')} (the tile is {100 * TILE_T:.1f} cm thick)") + if not over_tile or np.linalg.norm(go) >= 0.01: + grasp_txt += (f"; horizontally the grasp point was {dir_words(*go)} of the tile's centre" + + ("" if over_tile else ", i.e. not over the tile")) + if success: + out["failure"] = None + detail = "The red tile is on the plate." + if grasp_txt: + detail += f" {grasp_txt}." + elif not picked: + out["failure"] = "missed_grasp" + if last_close is None: + detail = "The gripper never closed; the red tile was not picked up." + else: + touch = last_close["touching"] + if not over_tile and TILE not in touch: + why = " The gripper was not over the tile when it closed." + elif fg > 0.0005 and TILE not in touch: + why = " The fingers closed in the air above the tile without touching it." + elif STAND in touch and TILE not in touch: + why = " The fingertips were pressed on the top of the wooden block but did not grip the tile." + elif TILE in touch: + why = " The fingers touched the tile but did not get a grip on it." + else: + why = "" + where = "still on the wooden block" if on_stand else "no longer on the wooden block" + detail = f"{grasp_txt}, and the tile was not picked up.{why} The tile is {where}." + elif held: + out["failure"] = "not_released" + detail = f"{grasp_txt}, and the tile was picked up, but it is still in the gripper." + elif releases: + r = releases[-1] + out["release_offset"] = (np.array(r["tile"][:2]) - np.array(r["plate"][:2])).round(4).tolist() + out["failure"] = "missed_place" + detail = (f"{grasp_txt}, and the tile was picked up. When the gripper opened, the tile was " + f"{dir_words(*out['release_offset'])} of the plate's centre; it did not end up on the plate " + f"(it is now {dir_words(*end_off)} of the plate's centre).") + else: + out["failure"] = "dropped" + detail = (f"{grasp_txt}, and the tile was lifted, but it slipped out of the fingers before it was " + f"released; it is now {dir_words(*end_off)} of the plate's centre.") + out["detail"] = detail + ind = detail + for k in sorted(NAMES, key=lambda n: -len(NAMES[n])): + ind = ind.replace(NAMES[k], DESCR[k]) + ind = re.sub(r"\btile\b", "slab", ind) # the bare noun would give the direct name away + out["detail_indirect"] = ind + return out + + def feedback(self, inst, out, level="F2", indirect=False): + if indirect and level == "F2": + out = dict(out, detail=out.get("detail_indirect", out["detail"])) + return super().feedback(inst, out, level) + + # ------------------------------------------------------------ scripted execution (cross protocol) + def grasp_yaw(self): + """Gripper yaw that closes the jaws across the tile's short side (yaw 0 closes along world y).""" + xmat = self.env.sim.data.body_xmat[envs.body_id(self.env, TILE)].reshape(3, 3) + a = np.arctan2(xmat[1, 0], xmat[0, 0]) + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + def execute(self, inst, params): + """Top-down pick across the tile's short side with the fingertips just above the block top, carry, release + above the plate. params['dz'] is the policy's own height correction, added to every commanded z.""" + sk = self.sk + dz = float(params.get("dz", 0.0)) + t = envs.obj_pos(self.env, TILE) # perfect perception of the current scene + top = self.stand_top(inst) + yaw = self.grasp_yaw() + p = envs.obj_pos(self.env, PLATE) + z_grasp = top + SITE_ABOVE_SURFACE + dz + z_carry = top + CARRY_ABOVE + dz + z_rel = self.plate_rim_z() + RELEASE_GAP + SITE_ABOVE_SURFACE + dz + sk.set_gripper(False, steps=8) + sk.move_to([t[0], t[1], z_carry], yaw=yaw) + sk.move_to([t[0], t[1], z_grasp + 0.05], tol=0.002) + sk.move_to([t[0], t[1], z_grasp], tol=0.003, max_steps=80) + sk.set_gripper(True, steps=15) + sk.move_to([t[0], t[1], z_carry], speed=0.3) + if not sk.holding_tile(): # missed: a real controller sees the jaws closed on nothing and stops + return + sk.move_to([p[0], p[1], z_carry], tol=0.003) + sk.move_to([p[0], p[1], z_rel], tol=0.003, max_steps=100) + sk.set_gripper(False, steps=12) + sk.move_to([p[0], p[1], z_carry], speed=0.3) + + def default_params(self, inst): + return dict(dz=0.0) + + def oracle_params(self, inst): + return dict(dz=-float(inst["bias"][2])) + + def adapt_params(self, inst, history): + """Scripted F2 learner: the reported grasp height above the tile's top face, minus the height this policy + meant to put the grasp point at (SITE_ABOVE_SURFACE - tile thickness), is the vertical offset; accumulate + it into the correction subtracted from every commanded height.""" + last = history[-1] + dz = float(last["params"]["dz"]) + o = last["outcome"] + if o.get("grasp_height") is not None: + dz -= o["grasp_height"] - (SITE_ABOVE_SURFACE - TILE_T) + return dict(dz=round(dz, 4)) + + blind_sigma = 0.005 + + def blind_params(self, inst, attempt, rng): + """Retry the same plan with a small random perturbation of the commanded heights; no use of history.""" + return dict(dz=round(float(rng.normal(0.0, self.blind_sigma)), 4)) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/l2_turntable.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/l2_turntable.py new file mode 100644 index 0000000000000000000000000000000000000000..6cde2c1b38e0e5287e6df47831e640e545bf1f43 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/l2_turntable.py @@ -0,0 +1,469 @@ +"""L2-C turntable_restore: take the butter off a turntable that stands half under a shelf, then turn the +turntable back exactly the way it was. + +Replaces the planned l2_drawer_reclosed (feasibility test 2026-10-07, see the task card): with the gripper +always pointing straight down, the handle of LIBERO's wooden_cabinet top drawer (3.8 cm below the cabinet +top) cannot be reached -- the descent stops 1.5-4.5 cm above it, closing grasps nothing (4/4 cabinet +placements) and a pull opened the drawer only 1/4 times, by accident. The turntable keeps the idea (an +articulated fixture the agent *has to* change to get the object and has to put back afterwards) and is +operable with move_to + open/close only. + +Scene: a turntable (lazy susan; disc radius 17 cm on a damped hinge about z) on the robot's right; a fixed +shelf board 10 cm above the disc covers its -y half (robot's right), so nothing under the board can be +grasped from above (measured, 20 seeds x 2 grasp yaws: the hand stops on the board 10-14 cm above the grasp +height, 0/40 lifts). Four red pegs stand near the rim; grasping a peg and moving the gripper along the rim +turns the disc. The butter lies on the disc under the board; painted marks (yellow stripe, blue square, +green dot; visual only) make the disc's angle readable. The basket stands on the robot's left. + +Why the first attempt fails (the L2 event is the agent's own, necessary change): to reach the butter the +agent must turn the disc by 136-179 deg (start angle random; measured on seeds 1000-1019). An agent that puts the butter into the basket +and stops leaves the turntable turned -> failure. To repair it the agent has to turn it back to its start +angle (+-15 deg); after the main turn the marks are elsewhere and nothing in the scene shows the start angle: +it is only in the first frame (or in the agent's memory of how far it turned). The F2 text says *that* the +turntable is not turned the way it was, never by how much or which way. + +Protocol: within (one episode, no reset). Attempt 1 = the main task, every later attempt = one corrective +round; the outcome (success + F2 text) is computed after each round. + +Scripted references (perception stand-in: simulator poses; motions: Skills.move_to / set_gripper only) + oracle turns, takes the butter, then immediately turns the disc back to the saved start angle. + naive turns, takes the butter, done. + adaptive saves the start angle (Save); after F2 "not turned the way it was" turns back to it (Retrieve + + Utilize); redoes the main task if the butter is not in the basket. + blind no history, no feedback: every later round redoes the main task (lifts the butter out of the + basket and drops it back, grasp jittered by 5 mm). + nomem (extra control, not in the acceptance table) gets F2 but has no start frame: turns the disc by a + random angle in (-180, 180] deg each round. + +Physics notes (all measured while building the task, 2026-10-07): the HOPE butter weighs 5 g -> set to 0.2 kg; +a box on a cylinder gets a single contact point and no torsional friction, so the butter span on the disc at +~4 deg/s even at rest -> the disc's collision surface is the inscribed square plate (visual disc stays round). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, register_generated +from ..task_base import LFFTask, register_task + +TT = "turntable_1" +TARGET = "butter_1" +ITEMS = (TARGET,) +BASKET = "basket_1" +MASS = {"butter_1": 0.20} # real-world order (the HOPE box weighs 5 g) + +# turntable geometry (fixture frame: origin on the table top at the disc axis) +R = 0.17 # disc radius +DISC_T = 0.012 # disc thickness +BASE_H = 0.012 # pedestal height +DISC_TOP = BASE_H + DISC_T # disc top above the table +PEG_R, PEG_RAD, PEG_H = 0.009, 0.155, 0.035 # radius, distance from the axis, height above the disc +# (low enough that the hand clears the pegs by 1 cm when it grasps the butter between them) +PEG_ANG = tuple(np.pi / 4 + k * np.pi / 2 for k in range(4)) # disc frame +STRIPE_ANG = np.pi # disc frame +BOARD_Z = DISC_TOP + 0.10 # underside of the shelf board above the table +BOARD_EDGE = 0.01 # the board covers fixture y < +1 cm (the -y half of the disc) +HINGE = dict(damping=1.0, armature=0.3, frictionloss=0.01) # the disc stops within ~1 deg when released +ITEM_R = 0.07 # butter's distance from the axis (disc frame); open fingers at a held peg clear it by >= 1.2 cm + +ANG_TOL = np.radians(15.0) # success: disc within 15 deg of its start angle (4 cm at the pegs, 2.6 cm at the stripe end) +BASKET_IN = 0.060 # LIBERO basket: half size of the inner floor +BASKET_RIM = 0.150 +BASKET_FLOOR = 0.017 +SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"' + +NAMES = {TARGET: "butter"} +DESCR = {TARGET: "small orange box"} + + +def _wrap(a): + return float((a + np.pi) % (2 * np.pi) - np.pi) + + +def _wrap_half(a): + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def _rot(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s], [s, c]]) + + +def turntable_xml(model_name): + """Static pedestal + shelf board + side wall; a hinged disc (child body) with 4 pegs and painted marks.""" + def geoms(kind, pos, size, rgba, coll=True, vis=True): + s = f'type="{kind}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(rgba)}"' + out = [f''] if vis else [] + if coll: + out.insert(0, f'') + return out + + shelf = (0.82, 0.82, 0.80, 1.0) + fixed = geoms("cylinder", (0, 0, BASE_H / 2), (0.06, BASE_H / 2), (0.3, 0.3, 0.3, 1.0)) + by0, by1, bx = -(R + 0.04), BOARD_EDGE, R + 0.04 + fixed += geoms("box", (0, (by0 + by1) / 2, BOARD_Z + 0.004), (bx, (by1 - by0) / 2, 0.004), shelf) + fixed += geoms("box", (0, by0 + 0.005, BOARD_Z / 2), (bx, 0.005, BOARD_Z / 2), shelf) + # the round disc is visual only; its collision surface is the inscribed square plate: a box on a cylinder gets a + # single contact point and no torsional friction, and the butter span on the disc at ~4 deg/s even at rest (measured) + disc = geoms("cylinder", (0, 0, 0), (R, DISC_T / 2), (0.62, 0.42, 0.24, 1.0), coll=False) + disc += geoms("box", (0, 0, 0), (R / np.sqrt(2), R / np.sqrt(2), DISC_T / 2), (0.62, 0.42, 0.24, 1.0), vis=False) + for a in PEG_ANG: + disc += geoms("cylinder", (PEG_RAD * np.cos(a), PEG_RAD * np.sin(a), DISC_T / 2 + PEG_H / 2), + (PEG_R, PEG_H / 2), (0.75, 0.08, 0.08, 1.0)) + # painted marks (visual only) that make the disc's angle readable: yellow stripe, blue square, green dot + disc += geoms("box", (0.085 * np.cos(STRIPE_ANG), 0.085 * np.sin(STRIPE_ANG), DISC_T / 2 + 0.0006), + (0.055, 0.007, 0.0006), (0.95, 0.85, 0.10, 1.0), coll=False) + disc += geoms("box", (0.10 * np.cos(np.pi / 2), 0.10 * np.sin(np.pi / 2), DISC_T / 2 + 0.0006), + (0.016, 0.016, 0.0006), (0.15, 0.35, 0.85, 1.0), coll=False) + disc += geoms("cylinder", (0.10 * np.cos(-np.pi / 2), 0.10 * np.sin(-np.pi / 2), DISC_T / 2 + 0.0006), + (0.016, 0.0006), (0.15, 0.65, 0.25, 1.0), coll=False) + nl = "\n " + return f""" + + + + {nl.join(fixed)} + + + {nl.join(disc)} + + + + + + + + +""" + + +@register_task +class TurntableRestore(LFFTask): + name = "l2_turntable_restore" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Save", "Retrieve", "Utilize") + protocol = "within" + max_attempts = 5 + instruction = ("Put the butter into the basket. The butter is on the turntable, under the shelf. You can turn the " + "turntable by its red pegs. When you are done, the turntable must be turned exactly the way it is now.") + instruction_indirect = ("Put the small orange box into the wicker basket. It is on the round turntable, under the " + "shelf. You can turn the turntable by its red pegs. When you are done, the turntable must be " + "turned exactly the way it is now.") + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self._tt_bid = m.body_name2id(self.env.fixtures_dict[TT].root_body) + jid = m.joint_name2id(f"{TT}_spin") + self._qa, self._qv = m.jnt_qposadr[jid], m.jnt_dofadr[jid] + self.start = {} + self.turn_log = [] # per peg grasp: commanded sweep vs measured disc rotation (diagnostics) + self._home = None + self._c = np.zeros(2) + + # ------------------------------------------------------------ scene + def make_bddl(self): + tt = register_generated("LffTurntableShelf", turntable_xml("lff_turntable_shelf"), free=False) + objs = [(n, n[:-2], f"r_{i}", (0.20, -0.25 + 0.15 * i, 0.22, -0.23 + 0.15 * i)) for i, n in enumerate(ITEMS)] + objs.append((BASKET, "basket", "r_basket", (-0.10, 0.24, -0.08, 0.26))) + fx = [(TT, tt, "tt_region", (0.25, 0.30, 0.27, 0.32))] # moved in apply_instance + return write_bddl(self.name, self.instruction.replace(";", ","), objs, fixtures=fx) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + c = np.array([rng.uniform(-0.08, -0.02), rng.uniform(-0.12, -0.08)]) + th = {TARGET: float(rng.uniform(-0.14, 0.14))} # disc-frame angle of the butter (stripe at 180 deg) + rad = {n: float(ITEM_R + rng.uniform(-0.005, 0.005)) for n in ITEMS} + tilt = {n: float(rng.uniform(-0.17, 0.17)) for n in ITEMS} # box yaw relative to radial + # start angle: the butter sits under the board (world azimuth -90 +- 40 deg about the axis) + q0 = float(_wrap(-np.pi / 2 - th[TARGET] + rng.uniform(-np.radians(40), np.radians(40)))) + return dict(seed=int(seed), center=c.round(4).tolist(), q0=q0, theta=th, rad=rad, tilt=tilt, + basket_xy=[float(rng.uniform(-0.12, -0.06)), float(rng.uniform(0.25, 0.28))]) + + def disc_angle(self): + return float(self.env.sim.data.qpos[self._qa]) + + def to_world(self, r, th, q=None): + q = self.disc_angle() if q is None else q + return self._c + r * np.array([np.cos(th + q), np.sin(th + q)]) + + def to_disc(self, xy, q=None): + q = self.disc_angle() if q is None else q + return _rot(-q) @ (np.asarray(xy, float)[:2] - self._c) + + def place(self, name, xy, yaw, surface_z): + """Teleport a box flat (its mesh frame is flat) with yaw about world z, lowest point 2 mm above surface_z.""" + envs.set_obj_pose(self.env, name, [xy[0], xy[1], surface_z + 0.3], + quat_wxyz=np.array([np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)])) + self.env.sim.forward() + dz = envs.obj_min_z(self.env, name) - (surface_z + 0.002) + qa, _ = envs.free_joint_addr(self.env, name) + self.env.sim.data.qpos[qa + 2] -= dz + self.env.sim.forward() + + def apply_instance(self, inst): + m, d = self.env.sim.model, self.env.sim.data + self._c = np.array(inst["center"], float) + m.body_pos[self._tt_bid] = [self._c[0], self._c[1], envs.TABLE_Z] + m.body_quat[self._tt_bid] = [1, 0, 0, 0] + d.qpos[self._qa] = inst["q0"] + d.qvel[self._qv] = 0.0 + self.env.sim.forward() + for n in ITEMS: + envs.scale_mass(self.env, n, MASS[n]) + th = inst["theta"][n] + # long axis radial (+ tilt): the gripper then closes tangentially and keeps clear of the board + self.place(n, self.to_world(inst["rad"][n], th, inst["q0"]), th + inst["q0"] + inst["tilt"][n], + envs.TABLE_Z + DISC_TOP) + envs.scale_mass(self.env, BASKET, 2.0) + self.place(BASKET, inst["basket_xy"], 0.0, envs.TABLE_Z) + self.env.sim.forward() + + def reset_instance(self, inst, recorder=None): + sk = super().reset_instance(inst, recorder) + self.start = dict(q=self.disc_angle()) + self._home = sk.eef_pos() + return sk + + # ------------------------------------------------------------ measurements + def footprint(self, name): + """AABB centre, yaw of the long horizontal axis, z range (scripted 'perception').""" + m, d = self.env.sim.model, self.env.sim.data + lo, hi = np.full(3, np.inf), np.full(3, -np.inf) + best = None + for g in envs.obj_geom_ids(self.env, name): + Rg = d.geom_xmat[g].reshape(3, 3) + c = d.geom_xpos[g] + Rg @ m.geom_aabb[g, :3] + e = np.abs(Rg) @ m.geom_aabb[g, 3:] + lo, hi = np.minimum(lo, c - e), np.maximum(hi, c + e) + vol = float(np.prod(m.geom_aabb[g, 3:])) + if best is None or vol > best[0]: + best = (vol, Rg, m.geom_aabb[g, 3:]) + _, Rg, half = best + horiz = sorted([(half[k], Rg[:, k]) for k in range(3) if abs(Rg[2, k]) < 0.5], key=lambda t: -t[0]) + ax = horiz[0][1] if horiz else np.array([1.0, 0.0, 0.0]) + return dict(center=[float(v) for v in (lo + hi) / 2], yaw=float(np.arctan2(ax[1], ax[0])), + zmin=float(lo[2]), zmax=float(hi[2])) + + def item_loc(self, name): + f = self.footprint(name) + c = np.array(f["center"]) + held = self.sk is not None and self.sk.holding(name) + if held and f["zmin"] > envs.TABLE_Z + DISC_TOP + 0.01: + return "gripper", f + bp = envs.obj_pos(self.env, BASKET) + if np.all(np.abs(c[:2] - bp[:2]) <= BASKET_IN + 0.01) and f["zmin"] < envs.obj_min_z(self.env, BASKET) + BASKET_RIM \ + and f["zmin"] > envs.TABLE_Z + 0.005: + return "basket", f + on_disc = np.linalg.norm(c[:2] - self._c) < R and abs(f["zmin"] - (envs.TABLE_Z + DISC_TOP)) < 0.012 + if on_disc: + return "turntable", f + if f["zmin"] < envs.TABLE_Z + 0.01: + return "table", f + return "other", f + + def outcome(self, inst): + envs.settle(self.env, 30) + tloc, _ = self.item_loc(TARGET) + dq = _wrap(self.disc_angle() - self.start["q"]) + turned_ok = abs(dq) <= ANG_TOL + success = bool(tloc == "basket" and turned_ok) + return dict(success=success, target_loc=tloc, angle_err_deg=round(float(np.degrees(dq)), 1), + turned_ok=bool(turned_ok), + detail=self._describe(tloc, turned_ok, dq, NAMES), + detail_indirect=self._describe(tloc, turned_ok, dq, DESCR), + detail_offset=self._describe(tloc, turned_ok, dq, NAMES, offset=True)) + + @staticmethod + def _describe(tloc, turned_ok, dq, names, offset=False): + tn = names[TARGET] + msgs = [] + if tloc != "basket": + msgs.append({"gripper": f"The {tn} is still in the gripper, not in the basket.", + "turntable": f"The {tn} is still on the turntable, not in the basket.", + "table": f"The {tn} is on the table, not in the basket."} + .get(tloc, f"The {tn} is not in the basket.")) + if not turned_ok: + m = "The turntable is not turned the way it was at the start." + if offset: # ablation tier: relative measurement, externalises the memory + m += (f" It is turned {abs(np.degrees(dq)):.0f} deg " + f"{'counter-clockwise' if dq > 0 else 'clockwise'} (seen from above) from its starting angle.") + msgs.append(m) + if not msgs: + msgs.append(f"The {tn} is in the basket and the turntable is turned the way it was at the start.") + return " ".join(msgs) + + def feedback(self, inst, out, level="F2", indirect=False, offset=False): + """F0: nothing, F1: success flag, F2: what is wrong (never by how much the turntable is off). + offset=True (ablation tier 'F2+offset'): also the relative turn from the start angle.""" + if level == "F2": + key = "detail_offset" if offset else ("detail_indirect" if indirect else "detail") + out = dict(out, detail=out.get(key, out["detail"])) + return super().feedback(inst, out, level) + + # ------------------------------------------------------------ scripted motions (Skills.move_to / set_gripper) + SAFE_Z = envs.TABLE_Z + 0.22 # travel height between pegs / items + PICK_AZ = np.pi / 2 # where the butter is brought: middle of the open side (at 135 deg the open finger lands on + # the board edge -- measured); grasp yaw ~ +-90 deg, so the wrist is turned back to 0 while + # carrying (arriving at the basket with yaw -103 deg left the arm stalled near a joint limit) + WIN = (np.radians(30), np.radians(150)) # world azimuths where a peg can be held (open side, clear of the board) + + def go_home(self): + sk = self.sk + p = sk.eef_pos() + sk.move_to([p[0], p[1], max(p[2], self._home[2])]) + sk.move_to(self._home, yaw=0.0) + + def _settle_yaw(self, tol=np.radians(3), max_steps=40): + """move_to stops on position only; after a large wrist rotation hold until the yaw has converged (a descent + that starts mid-rotation swipes the open fingers across the pegs -- measured).""" + sk = self.sk + for _ in range(max_steps // 5): + R = sk.eef_mat() @ sk.R0.T + if abs(_wrap(np.arctan2(R[1, 0], R[0, 0]) - sk.yaw)) < tol: + return + sk.hold(5) + + def peg_azimuths(self): + return [_wrap(self.disc_angle() + a) for a in PEG_ANG] + + def turn(self, delta, step=np.radians(10)): + """Turn the disc by `delta` rad (+ = counter-clockwise seen from above): grasp a peg on the open side, + move the gripper along the rim in short straight segments, release, repeat.""" + sk = self.sk + zg = envs.TABLE_Z + DISC_TOP + PEG_H - 0.012 + rem = float(delta) + for _ in range(6): + if abs(rem) < np.radians(1.0): + break + az = self.peg_azimuths() + if rem > 0: + cands = [a for a in az if self.WIN[0] - 1e-6 <= a <= self.WIN[1] - np.radians(10)] + a0 = min(cands) + sweep = min(rem, self.WIN[1] - a0) + else: + cands = [a for a in az if self.WIN[0] + np.radians(10) <= a <= self.WIN[1] + 1e-6] + a0 = max(cands) + sweep = max(rem, self.WIN[0] - a0) + q_before = self.disc_angle() + p = self._c + PEG_RAD * np.array([np.cos(a0), np.sin(a0)]) + sk.set_gripper(False, steps=6) + # up, across, straight down: a long diagonal move at full speed sags ~5 cm below its line and the open + # fingers sweep the disc (measured: turned it 38 deg the wrong way) + cur = sk.eef_pos() + if cur[2] < self.SAFE_Z - 0.02: + sk.move_to([cur[0], cur[1], self.SAFE_Z]) + sk.move_to([p[0], p[1], self.SAFE_Z], yaw=np.pi / 2) # fingers close along world x + self._settle_yaw() + sk.move_to([p[0], p[1], zg + 0.03], speed=0.4) + sk.move_to([p[0], p[1], zg], tol=0.003, max_steps=80) + sk.set_gripper(True, steps=12) + dbg = dict(off=np.round((sk.eef_pos() - np.r_[self._c + PEG_RAD * np.array([np.cos(a0), np.sin(a0)]), zg]) * 100, 1).tolist(), + w=round(sk.gripper_width() * 100, 1), q_close=round(float(np.degrees(_wrap(self.disc_angle() - q_before))), 1), + yaw=round(float(np.degrees(sk.yaw)), 0)) + k = max(1, int(np.ceil(abs(sweep) / step))) + for i in range(1, k + 1): + w = self._c + PEG_RAD * np.array([np.cos(a0 + sweep * i / k), np.sin(a0 + sweep * i / k)]) + sk.move_to([w[0], w[1], zg], tol=0.003, max_steps=40) + sk.set_gripper(False, steps=8) + pe = sk.eef_pos() + sk.move_to([pe[0], pe[1], zg + 0.10]) + got = _wrap(self.disc_angle() - q_before) + self.turn_log.append(dict(peg_az=round(float(np.degrees(a0)), 1), sweep=round(float(np.degrees(sweep)), 1), + got=round(float(np.degrees(got)), 1), **dbg)) + rem -= got + + def pick_place(self, name, dest_xy, support_z, fp=None, carry_z=1.20, travel_z=1.15, carry_yaw=0.0): + """Top-down pick across the short side, carry, release just above support_z at dest_xy.""" + sk = self.sk + f = fp or self.footprint(name) + c = np.array(f["center"]) + gyaw = _wrap_half(f["yaw"]) + zg = max(f["zmin"] + 0.5 * (f["zmax"] - f["zmin"]), f["zmin"] + 0.0145) + sk.set_gripper(False, steps=6) + p = sk.eef_pos() + if p[2] < travel_z - 0.02: + sk.move_to([p[0], p[1], travel_z]) + sk.move_to([c[0], c[1], travel_z], yaw=gyaw) + self._settle_yaw() + sk.move_to([c[0], c[1], f["zmax"] + 0.03], speed=0.4) + sk.move_to([c[0], c[1], zg], tol=0.003, max_steps=80) + sk.set_gripper(True, steps=12) + sk.move_to([c[0], c[1], carry_z], speed=0.3) + sk.move_to([dest_xy[0], dest_xy[1], carry_z], yaw=carry_yaw) + sk.move_to([dest_xy[0], dest_xy[1], support_z + (zg - f["zmin"]) + 0.006], tol=0.003, speed=0.2, max_steps=150) + sk.hold(4) + sk.set_gripper(False, steps=10) + sk.move_to([dest_xy[0], dest_xy[1], travel_z], speed=0.4) + + def butter_to_basket(self, fp=None): + """The main task: if the butter is on the turntable, turn it to the open side first.""" + loc, f = self.item_loc(TARGET) + if loc == "turntable": + az = np.arctan2(f["center"][1] - self._c[1], f["center"][0] - self._c[0]) + # bring the butter's long axis parallel to world y (then the hand lies along x, away from the board edge; + # a hand turned 26 deg off caught the board -- measured); its centre ends within ~30 deg of PICK_AZ + delta = _wrap_half(f["yaw"] - az) + self.turn(_wrap(self.PICK_AZ - delta - az)) + b = envs.obj_pos(self.env, BASKET) + # release with the hand above the rim and let the box drop in: lowering it to the floor puts the 20 cm long + # hand below the rim of the 12 cm basket and the contact flips the wrist (joint 5 at its limit -- measured) + self.pick_place(TARGET, b[:2], envs.obj_min_z(self.env, BASKET) + BASKET_RIM + 0.02, fp=fp) + + def do(self, actions): + for act in actions: + if act[0] == "butter_to_basket": + self.butter_to_basket(fp=act[1] if len(act) > 1 else None) + elif act[0] == "turn_to": # ["turn_to", absolute disc angle (the agent's remembered start angle)] + self.turn(_wrap(act[1] - self.disc_angle())) + elif act[0] == "turn_by": + self.turn(act[1]) + else: + raise ValueError(act) + + # ------------------------------------------------------------ scripted reference policies + def _plan(self, kind, inst, a, history, rng, memory): + if kind == "naive" or (a == 0 and kind in ("adaptive", "blind", "nomem")): + return [["butter_to_basket"]] + if kind == "oracle": + return [["butter_to_basket"], ["turn_to", memory["q"]]] + last = history[-1]["outcome"] + acts = [] if last["target_loc"] == "basket" else [["butter_to_basket"]] + if kind == "adaptive": + return acts + ([] if last["turned_ok"] else [["turn_to", memory["q"]]]) + if kind == "nomem": + return acts + ([] if last["turned_ok"] else [["turn_by", float(rng.uniform(-np.pi, np.pi))]]) + if kind == "blind": + fp = self.footprint(TARGET) + fp["center"] = (np.array(fp["center"]) + np.r_[rng.normal(0, 0.005, 2), 0.0]).tolist() + return [["butter_to_basket", fp]] + raise ValueError(kind) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """Within-episode protocol: one reset, attempt 1 = main task, attempts 2..k = corrective rounds.""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + self.reset_instance(inst) + memory = dict(q=self.disc_angle()) # Save: the start angle (an agent reads it off the first frame) + for a in range(k): + actions = self._plan(kind, inst, a, history, rng, memory) + self.do(actions) + self.go_home() + out = self.outcome(inst) + params = dict(actions=[[x[0]] + ([round(float(np.degrees(x[1])), 1)] if x[0] != "butter_to_basket" else []) + for x in actions]) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history + + # cross-protocol hooks are not used by this task + def default_params(self, inst): + return dict(policy="naive") + + def oracle_params(self, inst): + return dict(policy="oracle") diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/l3_card_shelf.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/l3_card_shelf.py new file mode 100644 index 0000000000000000000000000000000000000000..b56ab0538cd4224af8137664eacbda47e028a0ad --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/l3_card_shelf.py @@ -0,0 +1,587 @@ +"""L3 card_shelf (2026-10-12): a deepened l3_card_edge. The thin card lies on a raised SHELF (thin top on four legs) +and hides a weight in one end; sliding the heavy end over the edge far enough to grasp it tips the card off the shelf +onto the table, where it lies flat and cannot be picked up: the attempt is lost. + +Why (../research_notes/P1P2_加深与常识任务设计.md sec. 1, 3.2): l3_card_edge saturated. Sonnet 5.5 (cla4) failed one +flat grasp, then in the same attempt slid the card 2-3 cm over the board's edge and grasped the overhang (both runs +succeeded on attempt 1): the failed grasp costs one command and changes nothing. Here the first common-sense +interaction (slide the nearest end out ~3 cm) has an irreversible cost whenever that end is the heavy one. + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): a wooden shelf +(top 22 x 26 x 1 cm on four 2 x 2 cm legs, top surface 10 cm above the table) with a thin red card (9.0 x 5.6 x 0.2 cm) +lying flat on it, long side along x or along y (+-8 deg). Its near end is 2.5-4 cm from the shelf edge it points to (an +x-card's near end is always the FORWARD one: a card that tips off the backward edge lands behind the shelf, hidden from +the front camera), the far end 9-14 cm from the opposite edge, both long sides >= 5 cm inside; a grey bin (16 x 16 cm +inside, 5 cm high) stands on the table beside the shelf (left or right, 6 cm gap). Same card size, mass (10 g), +friction and bin as l3_card_edge. + +Hidden variable (instance level, the same in every attempt, invisible): 8 of the card's 10 g are a weight hidden in one +end; its centre of mass sits COM_E = 2.8 cm from the middle towards that end. Both ends look identical. In 14 of every +20 consecutive seeds the heavy end is the NEAR end (the end a Sonnet-like agent slides out), else the far end. + +Mechanism (physics, no teleport): an end slid out by h tips over the edge once the centre of mass passes it. Measured +(card teleported with overhang h, 2 s): heavy end stays for h <= 1.7 cm, tips for h >= 1.8 cm; light end stays up to +7.0 cm; a uniform card up to ~4.5 cm. The grasp of an overhang needs the fingers past the edge: light end 1.8-3.8 cm +out -> 11/12 grasped; the heavy end only in a narrow window (1.3-1.5 cm out, grasp 0.8-1.2 cm beyond the edge: 12/36). +A tipped card is flat on the table within 0.4 s (56/56 tilt 0), where it cannot be gripped (0/56 regrasps) and no edge +is in reach. The fix is to slide the OTHER end out (a longer slide across the shelf), learnable from the failure: "only +~2 cm out and it already tipped -> that end is heavy" (the cheaper explanation "I pushed too far" leads to pushing +less, which leaves too little overhang to grasp). Validation (seeds 1000-1019): Sonnet-like naive tips 14/14 heavy-near +instances and succeeds on 6/6 light-near ones; the same habit succeeds 20/20 on l3_card_edge and 20/20 here with a +uniform card. + +Implementation notes: the centre of mass is fixed in the generated MJCF (explicit ) and the +heavy end is chosen by the card's yaw (the card is symmetric), so the body's inertial frame is never changed at runtime +(no bounding-volume refit needed; see lh_fence / envs.refit_bounds for that MuJoCo pitfall). The inertia is written in +scientific notation: objects._fmt (5 decimals) rounds a 10-30 g card's inertia to ~0 (a 10 g card does not compile; a +30 g card with rounded inertia got pinched and lifted by the flat grasp 4/16). Mass 10 g as in l3_card_edge: the flat +grasp then fails 20/20 (fingers slide over the card). The shelf is a static multi-geom fixture; its legs stand inside +its top's footprint (robot-leg contacts: 0 in all scripted runs). + +Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: success = the card lies in the bin, +not held; plus a per-step event log (end / side slid over an edge, tipped_off, lifted, released, in_bin, hand_hit_leg) +and R6 fields (tipped_off, trap_fired, grasp_tries) for the server log; F1 gives the agent only success / failure. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, _wrap, bin_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +TZ = envs.TABLE_Z +CARD_HALF = (0.045, 0.028, 0.001) # 9.0 x 5.6 x 0.2 cm (as l3_card_edge) +CARD_MASS = 0.010 # as l3_card_edge (flat grasp fails 20/20; a 30 g card was pinched and lifted 4/16) +SLUG_MASS = 0.008 # hidden weight (+ 2 g of card); slug centre 3.5 cm from the middle +COM_E = 0.028 # centre of mass this far from the card's middle, towards the heavy end (the card's local +x) +MU = 0.3 # card and shelf sliding friction (as l3_card_edge) +SHELF_HALF = (0.11, 0.13) # top half extents (as l3_card_edge's board) +SHELF_H = 0.10 # top surface above the table +TOP_T = 0.01 # top thickness +LEG = 0.01 # leg half width (2 x 2 cm legs) +LEG_IN = 0.012 # leg centre to the top's edges +SHELF_TOP = TZ + SHELF_H +CARD_REST_Z = SHELF_TOP + CARD_HALF[2] +BIN_IN = 0.08 # inner half width +BIN_WALL_H = 0.05 +BIN_GAP = 0.06 # shelf edge to bin outer wall +BIN_T = 0.006 +BIN_HALF_OUT = BIN_IN + BIN_T +TIP_BELOW_SITE = envs.FINGERTIP_BELOW_SITE +LOW_CLOSE = 0.02 # a close counts as a grasp try when the fingertips are at most this far above the card + +# instance ranges +P_HEAVY_NEAR = 0.7 # 14 of every 20 consecutive seeds +NEAR_GAP = (0.025, 0.040) # near end to its shelf edge +SIDE_CLEAR = 0.05 # long sides to the shelf's side edges, at least +YAW_JIT = np.radians(8.0) + +# scripted policies +GRASP_OUT = 0.022 # grasp point this far beyond the edge (fingers must clear the edge) +DRAG_SPEED = 0.08 +NAIVE_STEPS = (0.0, 0.01, 0.02, 0.03) # Sonnet-like: slide the end to the edge, then out in 1 cm steps, lift & look +ORACLE_STEPS = (0.02, 0.03) # l3_card_edge oracle: to 1 cm short, look, the rest + +EDGES = ("forward", "backward", "left", "right") # shelf edges in robot-centric words (+x, -x, +y, -y) +EDGE_U = {"forward": (1.0, 0.0), "backward": (-1.0, 0.0), "left": (0.0, 1.0), "right": (0.0, -1.0)} +OPPOSITE = {"forward": "backward", "backward": "forward", "left": "right", "right": "left"} + + +def card_xml(name, rgba=(0.85, 0.15, 0.12, 1.0)): + """Uniform-looking card; the inertial (10 g, centre of mass COM_E along local +x) models an 8 g weight hidden in + the +x end. Explicit inertial pos != 0, so MuJoCo keeps a separate inertial frame (see module doc).""" + h = CARD_HALF + ms = CARD_MASS - SLUG_MASS + xs = COM_E * CARD_MASS / SLUG_MASS # slug centre + sl = (0.0075, 0.021, h[2]) # slug half extents (1.5 x 4.2 x 0.2 cm) + box_i = lambda mm, a: mm / 3 * np.array([a[1] ** 2 + a[2] ** 2, a[0] ** 2 + a[2] ** 2, a[0] ** 2 + a[1] ** 2]) + par = lambda mm, r: mm * np.array([r[1] ** 2 + r[2] ** 2, r[0] ** 2 + r[2] ** 2, r[0] ** 2 + r[1] ** 2]) + c = np.array([COM_E, 0.0, 0.0]) + inertia = box_i(ms, h) + par(ms, -c) + box_i(SLUG_MASS, sl) + par(SLUG_MASS, np.array([xs, 0.0, 0.0]) - c) + g = (f' \n' + f' \n' + f' ') + return _wrap(name, g, h[2], float(np.hypot(h[0], h[1]))) + + +def shelf_xml(name, rgba=(0.62, 0.45, 0.27, 1.0), leg_rgba=(0.50, 0.36, 0.21, 1.0)): + """Static shelf: top plate on four legs; body origin at mid height (top surface at +SHELF_H / 2).""" + hx, hy = SHELF_HALF + H = SHELF_H / 2 + parts = [((0.0, 0.0, H - TOP_T / 2), (hx, hy, TOP_T / 2), rgba)] + for sx in (-1, 1): + for sy in (-1, 1): + parts.append(((sx * (hx - LEG_IN), sy * (hy - LEG_IN), -TOP_T / 2), (LEG, LEG, H - TOP_T / 2), leg_rgba)) + g = [] + for k, (p, s, c) in enumerate(parts): + g.append(f' ') + g.append(f' ') + return _wrap(name, "\n".join(g), H, float(np.hypot(hx, hy))) + + +def _yaw_of(quat_wxyz): + w, x, y, z = quat_wxyz + return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))) + + +class ShelfSkills(Skills): + """Skills that feed the task's per-step monitor and log every close of the gripper.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + self.closes = [] + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + def set_gripper(self, close, steps=15): + was_open = self.grip < 0 + before = self.task.close_context() if (close and was_open) else None + rep = super().set_gripper(close, steps) + if before is not None: + before.update(held=self.holding("card_1"), width=round(self.gripper_width(), 4)) + self.closes.append(before) + return rep + + +@register_task +class CardShelf(LFFTask): + name = "l3_card_shelf" + level = "L3" + category = "strategy_switching" + capabilities = ("Perceive", "Reason", "Plan") + protocol = "cross" + max_attempts = 3 + agent_max_steps = 40 + instruction = "Pick up the thin red card lying on the wooden shelf and put it into the grey bin." + instruction_indirect = "Put the flat red rectangle that lies on the raised wooden platform into the grey container." + + # ------------------------------------------------------------ scene + def make_bddl(self): + card = register_generated("LffShelfCard", card_xml("lff_shelf_card")) + shelf = register_generated("LffCardShelf", shelf_xml("lff_card_shelf"), free=False) + bin_ = register_generated("LffShelfBin", bin_xml("lff_shelf_bin", (BIN_IN, BIN_IN), BIN_WALL_H, wall_t=BIN_T, + rgba=(0.55, 0.56, 0.60, 1.0)), free=False) + objs = [("card_1", card, "card_region", (0.10, 0.20, 0.12, 0.22))] + fx = [("shelf_1", shelf, "shelf_region", (-0.11, -0.01, -0.09, 0.01)), + ("bin_1", bin_, "bin_region", (-0.11, -0.31, -0.09, -0.29))] + return write_bddl(self.name, self.instruction, objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.shelf_bid = m.body_name2id(self.env.fixtures_dict["shelf_1"].root_body) + self.bin_bid = m.body_name2id(self.env.fixtures_dict["bin_1"].root_body) + g0 = int(m.body_geomadr[self.shelf_bid]) + self.leg_geoms = {g for g in range(g0, g0 + int(m.body_geomnum[self.shelf_bid])) + if (m.geom_id2name(g) or "").endswith(("_g1", "_g2", "_g3", "_g4"))} + self.robot_geoms = set(envs.robot_geom_ids(self.env)) + self.inst = None + self.mon = None + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + bx, by = float(rng.uniform(-0.14, -0.06)), float(rng.uniform(-0.08, 0.08)) + along = str(rng.choice(["x", "y"])) + near_sign = 1.0 if rng.random() < 0.5 else -1.0 + if along == "x": # the near end of an x-card is the forward one: a card that tips off the backward edge lands + near_sign = 1.0 # behind the shelf, hidden from the front camera (measured); forward = nearest = away from the robot + jit = float(rng.uniform(-YAW_JIT, YAW_JIT)) + gap = float(rng.uniform(*NEAR_GAP)) + heavy_near = bool((int(seed) * 7) % 20 < round(20 * P_HEAVY_NEAR)) # balanced per 20 consecutive seeds + a_long, a_side = (0, 1) if along == "x" else (1, 0) # world axis of the card's long / short side + ext_long = CARD_HALF[0] * abs(np.cos(jit)) + CARD_HALF[1] * abs(np.sin(jit)) # half extents incl. the jitter + ext_side = CARD_HALF[0] * abs(np.sin(jit)) + CARD_HALF[1] * abs(np.cos(jit)) + c = [bx, by] + c[a_long] += near_sign * (SHELF_HALF[a_long] - gap - ext_long) + room = SHELF_HALF[a_side] - ext_side - SIDE_CLEAR + c[a_side] += float(rng.uniform(-room, room)) + u_near = np.zeros(2) + u_near[a_long] = near_sign + near_edge = {(1.0, 0.0): "forward", (-1.0, 0.0): "backward", (0.0, 1.0): "left", (0.0, -1.0): "right"}[ + (float(u_near[0]), float(u_near[1]))] + heavy_dir = u_near if heavy_near else -u_near # the card's local +x (heavy end) points this way (+- jitter) + yaw = float(np.arctan2(heavy_dir[1], heavy_dir[0]) + jit) + side = 1.0 if rng.random() < 0.5 else -1.0 + bin_xy = [bx + float(rng.uniform(-0.04, 0.04)), by + side * (SHELF_HALF[1] + BIN_GAP + BIN_HALF_OUT)] + return dict(seed=int(seed), shelf_xy=[bx, by], card_xy=[float(c[0]), float(c[1])], card_yaw=yaw, + card_along=along, near_edge=near_edge, far_edge=OPPOSITE[near_edge], near_gap=gap, + heavy_near=heavy_near, heavy_edge=near_edge if heavy_near else OPPOSITE[near_edge], + com_offset=COM_E, bin_xy=bin_xy, bin_side="left" if side > 0 else "right") + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + bx, by = inst["shelf_xy"] + m.body_pos[self.shelf_bid] = [bx, by, TZ + SHELF_H / 2] + m.body_quat[self.shelf_bid] = [1.0, 0.0, 0.0, 0.0] + cx, cy = inst["bin_xy"] + m.body_pos[self.bin_bid] = [cx, cy, TZ + (BIN_WALL_H + BIN_T) / 2] + m.body_quat[self.bin_bid] = [1.0, 0.0, 0.0, 0.0] + x, y = inst["card_xy"] + envs.set_obj_pose(self.env, "card_1", [x, y, CARD_REST_Z + 0.0003], yaw=inst["card_yaw"]) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = ShelfSkills(self.env, self, recorder=recorder) + p = self.card_pose() + self.mon = dict(start_xy=p["xy"].copy(), max_lift=0.0, max_overhang=0.0, fell=False, lifted=False, + out=dict(heavy=0.0, light=0.0, side=0.0), out_edge=dict(heavy=None, light=None, side=None), + flagged=set(), events=[], in_bin=False, tip=None, leg_hits=0, edge_used=None) + return self.sk + + # ------------------------------------------------------------ geometry + def card_pose(self): + p = envs.obj_pos(self.env, "card_1") + return dict(xy=p[:2].copy(), z=float(p[2]), yaw=_yaw_of(envs.obj_quat(self.env, "card_1"))) + + def _card_frame(self): + d = self.env.sim.data + bid = envs.body_id(self.env, "card_1") + return d.body_xpos[bid].copy(), d.body_xmat[bid].reshape(3, 3).copy() + + def card_corners(self): + p, R = self._card_frame() + h = np.array(CARD_HALF) + return np.array([p + R @ (h * [sx, sy, 0.0]) for sx in (-1, 1) for sy in (-1, 1)]) + + def _beyond(self, xy): + """{edge: how far the point lies beyond that edge of the shelf top (m, negative = inside)}""" + b = np.asarray(xy, float) - np.asarray(self.inst["shelf_xy"]) + return {"forward": b[0] - SHELF_HALF[0], "backward": -b[0] - SHELF_HALF[0], + "left": b[1] - SHELF_HALF[1], "right": -b[1] - SHELF_HALF[1]} + + def overhang(self): + """(how far the card sticks out beyond the shelf's edges (m, max over its corners), edge word)""" + best = (-1.0, None) + for c in self.card_corners(): + for e, v in self._beyond(c[:2]).items(): + if v > best[0]: + best = (float(v), e) + return best + + def part_overhangs(self): + """{'heavy' | 'light' | 'side': (overhang m, edge)}: the heavy end (local +x), light end and long sides, + each measured at its two corners.""" + p, R = self._card_frame() + h = np.array(CARD_HALF) + groups = {"heavy": [(1, -1), (1, 1)], "light": [(-1, -1), (-1, 1)]} + out = {} + for k, cs in groups.items(): + best = (-1.0, None) + for sx, sy in cs: + c = p + R @ (h * [sx, sy, 0.0]) + for e, v in self._beyond(c[:2]).items(): + if v > best[0]: + best = (float(v), e) + out[k] = best + best = (-1.0, None) # a long side: its middle point (an end pushed out also moves two corners out) + for sy in (-1, 1): + c = p + R @ (h * [0.0, sy, 0.0]) + for e, v in self._beyond(c[:2]).items(): + if v > best[0]: + best = (float(v), e) + out["side"] = best + return out + + def end_edge(self, which): + """shelf edge that the card's `which` end ('heavy' | 'light' | 'near' | 'far') points to, from the live pose""" + p = self.card_pose() + d = np.array([np.cos(p["yaw"]), np.sin(p["yaw"])]) # heavy end direction + if which == "near" or which == "far": + gaps = {} + for s in (1.0, -1.0): + u = d * s + e = max(EDGE_U, key=lambda k: float(np.asarray(EDGE_U[k]) @ u)) + tip = p["xy"] + u * CARD_HALF[0] + gaps[e] = -self._beyond(tip)[e] + near = min(gaps, key=gaps.get) + return near if which == "near" else OPPOSITE[near] + u = d if which == "heavy" else -d + return max(EDGE_U, key=lambda k: float(np.asarray(EDGE_U[k]) @ u)) + + def on_shelf(self): + p = self.card_pose() + rel = np.abs(p["xy"] - np.asarray(self.inst["shelf_xy"])) + return bool(rel[0] <= SHELF_HALF[0] and rel[1] <= SHELF_HALF[1] and abs(p["z"] - CARD_REST_Z) < 0.012) + + def on_table(self): + return bool(self.card_pose()["z"] < TZ + 0.03 and not self.in_bin()) + + def tilt_deg(self): + _, R = self._card_frame() + return float(np.degrees(np.arccos(np.clip(abs(R[2, 2]), 0.0, 1.0)))) + + def in_bin(self): + p = self.card_pose() + rel = np.abs(p["xy"] - np.asarray(self.inst["bin_xy"])) + return bool(rel[0] <= BIN_IN and rel[1] <= BIN_IN and p["z"] < TZ + BIN_T + BIN_WALL_H) + + # ------------------------------------------------------------ monitor + def _event(self, ev, **kw): + self.mon["events"].append(dict(event=ev, step=int(self.sk.n_steps), **kw)) + + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + p = self.card_pose() + held = self.sk.holding("card_1") + zmin = float(self.card_corners()[:, 2].min()) + mon["max_lift"] = max(mon["max_lift"], zmin - SHELF_TOP) + if held and zmin - SHELF_TOP > 0.02 and not mon["lifted"]: + mon["lifted"] = True + self._event("lifted") + rel = np.abs(p["xy"] - np.asarray(self.inst["shelf_xy"])) + if (not held and abs(p["z"] - CARD_REST_Z) < 0.004 and self.tilt_deg() < 5.0 and rel[0] <= SHELF_HALF[0] + and rel[1] <= SHELF_HALF[1]): # lying flat on the shelf + mon["max_overhang"] = max(mon["max_overhang"], self.overhang()[0]) + for k, (v, e) in self.part_overhangs().items(): + if v > mon["out"][k]: + mon["out"][k], mon["out_edge"][k] = v, e + if v >= 0.005 and k not in mon["flagged"]: + mon["flagged"].add(k) + self._event("side_over_edge" if k == "side" else "end_over_edge", part=k, edge=e) + if p["z"] < SHELF_TOP - 0.02 and not held and not mon["fell"]: + mon["fell"] = True + if not mon["lifted"]: # never lifted: it tipped (or was pushed) off the shelf + part = max(("heavy", "light", "side"), key=lambda k: mon["out"][k]) + mon["tip"] = dict(part=part, edge=mon["out_edge"][part], overhang=round(mon["out"][part], 4)) + self._event("tipped_off", **mon["tip"]) + else: + self._event("released") + d = self.env.sim.data + for i in range(d.ncon): # the hand / arm touching a shelf leg (should not happen in normal grasps) + c = d.contact[i] + if (c.geom1 in self.leg_geoms and c.geom2 in self.robot_geoms) or (c.geom2 in self.leg_geoms and + c.geom1 in self.robot_geoms): + if mon["leg_hits"] == 0: + self._event("hand_hit_leg") + mon["leg_hits"] += 1 + break + if not mon["in_bin"] and self.in_bin() and not held: + mon["in_bin"] = True + self._event("in_bin") + + def close_context(self): + """Where the gripper is relative to the card and the shelf just before it closes.""" + sk, p = self.sk, self.card_pose() + e = sk.eef_pos() + c, s = np.cos(p["yaw"]), np.sin(p["yaw"]) + rel = e[:2] - p["xy"] + local = [float(rel @ [c, s]), float(rel @ [-s, c])] # along the card's long / short side (+ = heavy end) + beyond = self._beyond(e[:2]) + edge = max(beyond, key=beyond.get) + ov, ov_edge = self.overhang() + return dict(step=sk.n_steps, local=[round(v, 4) for v in local], + tips_above_card=round(float(e[2] - TIP_BELOW_SITE - (p["z"] + CARD_HALF[2])), 4), + beyond_edge=round(float(beyond[edge]), 4), beyond_edge_name=edge, + card_on_shelf=self.on_shelf(), overhang=round(ov, 4), overhang_edge=ov_edge, + width_before=round(sk.gripper_width(), 4)) + + # ------------------------------------------------------------ outcome / F2 + def outcome(self, inst): + envs.settle(self.env, 30) + self.monitor_step() + sk, mon = self.sk, self.mon + p = self.card_pose() + held = bool(sk.holding("card_1")) + in_bin = self.in_bin() and not held + success = bool(in_bin) + moved = float(np.linalg.norm(p["xy"] - mon["start_xy"])) + lifted = mon["max_lift"] > 0.02 + tries = [c for c in sk.closes if c["tips_above_card"] <= LOW_CLOSE and c["width_before"] > 0.02] + parts, mode = [], "success" + rel = p["xy"] - np.asarray(inst["bin_xy"]) + where = (f"{100 * abs(rel[0]):.1f} cm {'forward' if rel[0] > 0 else 'backward'} and " + f"{100 * abs(rel[1]):.1f} cm {'left' if rel[1] > 0 else 'right'} of the bin's centre") + tip = mon["tip"] + if success: + parts.append("The card is in the bin.") + elif held: + mode = "held" + parts.append(f"The card is still held by the gripper, {where}.") + elif lifted: + mode = "dropped" + loc = ("on the shelf" if self.on_shelf() else "on the table" if self.on_table() else + "partly on the shelf" if p["z"] > SHELF_TOP - 0.02 else "off the shelf") + parts.append(f"The card was lifted {100 * mon['max_lift']:.1f} cm above the shelf but is not in the " + f"bin: it lies {loc}, its centre {where}.") + elif mon["fell"]: + mode = "fell_off" + what = "a long side" if tip["part"] == "side" else "one end" + parts.append(f"The card was never lifted: after {what} of it had been slid {100 * max(tip['overhang'], 0):.1f}" + f" cm beyond the shelf's {tip['edge']} edge, it tipped over that edge and fell off the shelf; " + + ("it lies flat on the table." if self.on_table() and self.tilt_deg() < 10 else + f"it rests off the shelf, tilted {self.tilt_deg():.0f} degrees.")) + else: + mode = "not_lifted" + parts.append("The card was never lifted; it still lies flat on the shelf" + + (f" (it was slid {100 * moved:.1f} cm" + (f" and stuck out up to " + f"{100 * mon['max_overhang']:.1f} cm beyond the shelf's edge)" if mon["max_overhang"] > 0.003 + else ")") if moved > 0.005 else "") + ".") + if not success and not lifted and tries: + c = tries[-1] + n = f"{len(tries)} grasp tries; in the last one, " if len(tries) > 1 else "" + if c["card_on_shelf"] and c["overhang"] <= 0.0 and c["beyond_edge"] < 0.0: + txt = ("when the gripper closed on the card lying flat on the shelf, its fingertips were on either side " + "of the card, at shelf level") + else: + pos = (f"{100 * c['beyond_edge']:.1f} cm beyond the shelf's {c['beyond_edge_name']} edge" + if c["beyond_edge"] >= 0.0 else + f"over the shelf, {100 * -c['beyond_edge']:.1f} cm inside its {c['beyond_edge_name']} edge") + txt = (f"when the gripper closed, the card stuck out {100 * max(c['overhang'], 0.0):.1f} cm beyond the " + f"shelf's {c['overhang_edge']} edge and the gripper's centre was {pos}") + txt += f" ({100 * c['tips_above_card']:+.1f} cm from the fingertips to the top of the card); the fingers closed " + txt += ("fully, sliding over the top of the card instead of gripping its edges." + if c["width"] < 2 * CARD_HALF[1] - 0.01 and not c["held"] else + ("on the card." if c["held"] else f"to {100 * c['width']:.1f} cm without holding the card.")) + parts.append(n + txt if n else txt[0].upper() + txt[1:]) + elif not success and not lifted and not mon["fell"]: + parts.append("The gripper never closed with its fingertips down at the card.") + failure = "none" if success else mode + out = dict(success=success, mode=mode, failure=failure, held=held, lifted=bool(lifted), + max_lift=round(mon["max_lift"], 4), max_overhang=round(mon["max_overhang"], 4), moved=round(moved, 4), + fell=bool(mon["fell"]), tipped_off=tip is not None, trap_fired=bool(tip is not None and + tip["part"] == "heavy"), + tip=tip, end_out={k: round(v, 4) for k, v in mon["out"].items()}, + end_out_edge=dict(mon["out_edge"]), card_final=dict(xy=[round(float(v), 4) for v in p["xy"]], + z_above_table=round(p["z"] - TZ, 4), + tilt_deg=round(self.tilt_deg(), 1)), + leg_hits=int(mon["leg_hits"]), slid_edge=mon["edge_used"], + events=list(mon["events"]), grasp_tries=tries, closes=sk.closes, detail=" ".join(parts)) + return out + + # ------------------------------------------------------------ scripted policies (move_to + gripper only) + def grasp_and_bin(self, xy, yaw, z_site, lift=0.12): + sk = self.sk + sk.set_gripper(False, steps=8) + sk.move_to([xy[0], xy[1], z_site + 0.08], yaw=yaw) + sk.move_to([xy[0], xy[1], z_site], tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + sk.move_to([xy[0], xy[1], z_site + lift], speed=0.2) + if not sk.holding("card_1"): + sk.set_gripper(False, steps=8) + return False + bx, by = self.inst["bin_xy"] + hi = SHELF_TOP + 0.10 + sk.move_to([bx, by, hi]) + sk.move_to([bx, by, TZ + BIN_WALL_H + 0.05], speed=0.2) + sk.set_gripper(False, steps=12) + sk.move_to([bx, by, hi]) + return True + + def slide_card(self, delta, press=0.004, at=(0.0, 0.0)): + """closed fingertips pressed on the card (at its centre + `at`), straight move by `delta` (xy), lift""" + sk, p = self.sk, self.card_pose() + z = p["z"] + CARD_HALF[2] + TIP_BELOW_SITE - press + s = p["xy"] + np.asarray(at, float) + sk.set_gripper(True, steps=8) + sk.move_to([s[0], s[1], z + 0.06], yaw=p["yaw"]) + sk.move_to([s[0], s[1], z], tol=0.003, max_steps=100) + e = s + np.asarray(delta, float) + sk.move_to([e[0], e[1], z], speed=DRAG_SPEED, tol=0.004, max_steps=300) + sk.move_to([e[0], e[1], z + 0.06], speed=0.2) + sk.hold(10) # look + + def push_end(self, u, dist, behind=0.015): + """closed fingers at shelf level `behind` m behind the card's trailing end, push it `dist` along u, lift""" + sk, p = self.sk, self.card_pose() + d = np.array([np.cos(p["yaw"]), np.sin(p["yaw"])]) + la = d * np.sign(d @ u) if abs(d @ u) > 0.5 else d + tail = p["xy"] - la * CARD_HALF[0] + s = tail - u * behind + z = SHELF_TOP + TIP_BELOW_SITE - 0.001 # fingertips on the shelf top (2 mm above: they pass over the card) + yaw = float(np.arctan2(u[1], u[0]) - np.pi / 2) # finger axis across the push direction + sk.set_gripper(True, steps=8) + sk.move_to([s[0], s[1], z + 0.05], yaw=yaw) + sk.move_to([s[0], s[1], z], tol=0.003, max_steps=100) + e = s + u * (behind + dist) + sk.move_to([e[0], e[1], z], speed=0.04, tol=0.004, max_steps=300) + sk.move_to([e[0], e[1], z + 0.05], speed=0.2) + sk.hold(10) + + def execute(self, inst, params): + p = self.card_pose() + rng = np.random.default_rng(params.get("noise_seed")) if params.get("noise_seed") is not None else None + if params.get("probe_grasp", False) or params["mode"] == "grasp": # flat grasp at the card's middle + dxy = np.asarray(params.get("probe_dxy", (0.0, 0.0))) + self.grasp_and_bin(p["xy"] + dxy, p["yaw"], SHELF_TOP + params.get("probe_dz", 0.0)) + if params["mode"] == "grasp" or self.sk.holding("card_1") or self.mon["lifted"]: + return + # slide one end of the card along its long side out over the edge it points to, in strokes + edge = params.get("edge") or self.end_edge(params.get("end", "near")) + self.mon["edge_used"] = edge + u = np.asarray(EDGE_U[edge], float) + b = np.asarray(inst["shelf_xy"]) + half = SHELF_HALF[0] if edge in ("forward", "backward") else SHELF_HALF[1] + edge_pos = float(b @ u) + half + for k, target in enumerate(params.get("steps", ORACLE_STEPS)): + if not self.on_shelf(): + return # tipped off: nothing left to grasp (the attempt is lost) + p = self.card_pose() + d = np.array([np.cos(p["yaw"]), np.sin(p["yaw"])]) + la = d * np.sign(d @ u) if abs(d @ u) >= 0.5 else np.array([-d[1], d[0]]) * np.sign(np.array([-d[1], d[0]]) @ u) + ext = max(float(c[:2] @ u) for c in self.card_corners()) - float(p["xy"] @ u) + tgt = float(target) + (float(rng.uniform(-1, 1)) * params.get("step_noise", 0.0) if rng is not None else 0.0) + need = edge_pos + tgt - (float(p["xy"] @ u) + ext) # travel still needed along u + if need > 0.003: + if params.get("style", "press") == "endpush": + self.push_end(u, need) + else: + at = (np.asarray(params.get("press_at", (0.0, 0.0))) if rng is None else + rng.normal(0.0, params.get("press_noise", 0.0), 2)) + self.slide_card(la * need / max(float(la @ u), 1e-6), at=at) + self.sk.hold(10) + if not self.on_shelf(): + return + q = self.card_pose() + d = np.array([np.cos(q["yaw"]), np.sin(q["yaw"])]) + la = d * np.sign(d @ u) if abs(d @ u) >= 0.5 else np.array([-d[1], d[0]]) * np.sign(np.array([-d[1], d[0]]) @ u) + cu = float(q["xy"] @ u) + tip_u = max(float(c[:2] @ u) for c in self.card_corners()) # outermost point of the card along u + target_u = min(tip_u - 0.008, edge_pos + params.get("grasp_out", GRASP_OUT)) + g = q["xy"] + la * (target_u - cu) / max(float(la @ u), 1e-6) + g = g + np.asarray(params.get("grasp_dxy", (0.0, 0.0))) + self.grasp_and_bin(g, q["yaw"], SHELF_TOP - 0.003 + params.get("grasp_dz", 0.0)) + + def default_params(self, inst): + """Sonnet-like (cla4 l3_card_edge): one flat grasp, then the nearest end out to the edge and 1 cm at a time + to ~3 cm, lifting the finger and looking after each stroke; grasp the overhang.""" + return dict(mode="edge", probe_grasp=True, end="near", steps=list(NAIVE_STEPS)) + + def oracle_params(self, inst): + """Knows the hidden weight: slides the light end out 3 cm (two strokes, as the l3_card_edge oracle).""" + return dict(mode="edge", end="light", steps=list(ORACLE_STEPS)) + + def blind_params(self, inst, attempt, rng): + """naive with small random variations, no history: nearest end, 2.5-3.5 cm, pressing point / grasp jitter""" + return dict(mode="edge", probe_grasp=True, end="near", steps=[0.0, 0.01, 0.02, float(rng.uniform(0.025, 0.035))], + noise_seed=int(rng.integers(1 << 30)), press_noise=0.005, + grasp_dxy=rng.uniform(-0.005, 0.005, 2).tolist(), grasp_dz=float(rng.uniform(-0.004, 0.003))) + + def adapt_params(self, inst, history): + """Tipped off the shelf (never lifted) -> slide the OTHER end next time (it tipped although only ~2 cm stuck + out: that end must be heavy). Slid out but not gripped -> 1 cm more overhang. Otherwise repeat.""" + out, prm = history[-1]["outcome"], history[-1]["params"] + used = out.get("slid_edge") or prm.get("edge") + nxt = dict(mode="edge", probe_grasp=False, edge=used, steps=list(ORACLE_STEPS)) + if out["mode"] == "fell_off": + e = (out.get("tip") or {}).get("edge") or used + nxt["edge"] = OPPOSITE.get(e) + elif out["mode"] == "not_lifted" and used is not None: + last = float((prm.get("steps") or ORACLE_STEPS)[-1]) + nxt["steps"] = [s + 0.01 for s in ORACLE_STEPS] if last < 0.035 else list(ORACLE_STEPS) + if nxt["edge"] is None: + nxt.pop("edge") + nxt["end"] = "near" + return nxt diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/l3_wall.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/l3_wall.py new file mode 100644 index 0000000000000000000000000000000000000000..85c1d73ef0922858d68710e01a64b66eafeb9650 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/l3_wall.py @@ -0,0 +1,501 @@ +"""L3-A wall_flush: a flat long box lies flush against a low fixed wall; put it on the plate. + +Why the prior fails: the only graspable dimension of the box is its 6 cm width (the Panda opens to +~7.9 cm; the box is 16 cm long). Grasping across the width needs one finger between the box and the +wall, but the box touches the wall (gap 0-3 mm) along its whole length, so that finger lands on top of +the wall (4.5 cm high; the box is 3.5 cm high) and the gripper closes above the box. Retrying the same +grasp with small variations fails the same way. + +What must be learned from the failure: this grasp is infeasible in this state -> change the manipulation +mode: first slide the box along the wall until it clears the wall's end (non-prehensile pre-grasp +manipulation), then grasp it across its width. + +Layout: the wall runs along y (left-right as seen from the robot). Randomised per instance: wall length +(24-30 cm), wall position, whether the wall is on the far (+x) or near (-x) side of the box, where the +box sits along the wall (always fully alongside it, >= 2 cm of wall beyond each end), box-wall gap +(0-3 mm, below camera resolution), plate position (on the open side of the box). + +Protocols: `l3_wall_flush` (cross: reset to the same instance before every attempt) and +`l3_wall_flush_within` (one episode; each attempt starts from wherever the previous one left things). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import box_xml, register_generated +from ..skills import DT, _rot_err +from ..task_base import LFFTask, register_task + +BOX_HALF = np.array([0.03, 0.08, 0.0175]) # 6 (x) x 16 (y) x 3.5 cm; long axis along y +WALL_HALF_T = 0.015 # 3 cm thick (x) +WALL_HALF_H = 0.0225 # 4.5 cm high +WALL_HALF_L_MAX = 0.16 # registered half length (y); shrunk per instance +WALL_MU = 2.0 # wall sliding friction (MuJoCo uses the max of the two geoms: finger-wall and box-wall contacts get 2.0) +BOX_DENSITY = 1500.0 # -> 0.50 kg +GRIP_OPEN = 0.079 # measured distance between the finger pads when fully open +FINGER_NEEDS = 0.012 # free space a finger needs beside the box (pad + finger shell), measured +Z_GRASP = envs.TABLE_Z + 0.022 # gripper-site height for grasping (pads cover 1.7-3.4 cm above the table) +Z_PUSH = envs.TABLE_Z + 0.022 # site height while pushing: finger tips 1.2 cm above the table, hand ~7 mm above the wall +PUSH_SPEED = 0.08 +FINGER_BELOW_SITE = 0.0096 # finger tips are this far below the gripper site (measured) +PLACE_Z = envs.TABLE_Z + 0.048 # site height at release over the plate (box bottom ~8 mm above the rim) + + +def _wrap_half_pi(a): + """wrap to [-pi/2, pi/2): box and parallel gripper are both symmetric under 180 deg""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def _yaw_of(quat_wxyz): + w, x, y, z = quat_wxyz + return _wrap_half_pi(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))) + + +@register_task +class WallFlush(LFFTask): + name = "l3_wall_flush" + level = "L3" + category = "strategy_switching" + capabilities = ("Perceive", "Reason", "Plan") + protocol = "cross" + instruction = "Put the long box on the plate." + instruction_indirect = "Put the flat blue block onto the round dish." + + def __init__(self, cam_res=None): + super().__init__(cam_res) + self._mon = None + # Per-control-step event monitor. It wraps env.step so that it also sees attempts driven by the agent + # harness (whose tools call Skills / env.step directly), not only the scripted `execute`. + orig_step = self.env.step + + def step(action): + ret = orig_step(action) + if self._mon is not None: + self._monitor_step() + return ret + + self.env.step = step + + def reset_instance(self, inst, recorder=None): + self._mon = None + sk = super().reset_instance(inst, recorder=recorder) + self._start_monitor() + return sk + + # ------------------------------------------------------------ scene + def make_bddl(self): + # 0.5 kg box and a grippy wall top (mu 2): with mu 1 / 0.13 kg an *unguarded* press onto the wall top (plain + # move_to down, as an agent would do) let the finger slide ~5 cm off the wall and, on the wall-far side, + # flipped the box onto its 3.5 cm side (10/60 instances) -- an accidental, graspable state (see task card). + box = register_generated("LffFlushBox", box_xml("lff_flush_box", BOX_HALF, (0.12, 0.30, 0.80, 1.0), + density=BOX_DENSITY)) + wall = register_generated("LffFlushWall", box_xml("lff_flush_wall", (WALL_HALF_T, WALL_HALF_L_MAX, WALL_HALF_H), + (0.62, 0.50, 0.36, 1.0), density=1000, + friction=(WALL_MU, 0.005, 0.0001)), free=False) + # regions only need to be valid and far apart; the layout is overridden in apply_instance + objs = [("box_1", box, "box_region", (-0.21, -0.26, -0.19, -0.24)), + ("plate_1", "plate", "plate_region", (-0.01, 0.24, 0.01, 0.26))] + fx = [("wall_1", wall, "wall_region", (0.19, -0.01, 0.21, 0.01))] + return write_bddl(self.name, self.instruction, objs, fx) + + def _wall(self): + """(root body id, geom ids) of the wall fixture""" + if not hasattr(self, "_wall_cache"): + m = self.env.sim.model + bid = m.body_name2id(self.env.fixtures_dict["wall_1"].root_body) + + def under(b): + while b > 0: + if b == bid: + return True + b = m.body_parentid[b] + return False + + self._wall_cache = (bid, [g for g in range(m.ngeom) if under(m.geom_bodyid[g])]) + return self._wall_cache + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + side = int(rng.choice([-1, 1])) # +1: wall on the far (+x) side of the box, -1: near (-x) side + wall_hl = float(rng.uniform(0.12, 0.15)) + wall_y = float(rng.uniform(-0.06, 0.06)) + u_max = wall_hl - BOX_HALF[1] - 0.02 # >= 2 cm of wall beyond each end of the box + box_y = wall_y + float(rng.uniform(-u_max, u_max)) + gap = float(rng.uniform(0.0, 0.003)) + box_x = float(rng.uniform(-0.12, -0.04)) if side > 0 else float(rng.uniform(-0.20, -0.12)) + wall_x = box_x + side * (WALL_HALF_T + BOX_HALF[0] + gap) + plate_xy = [box_x - side * float(rng.uniform(0.16, 0.18)), box_y + float(rng.uniform(-0.06, 0.06))] + return dict(seed=int(seed), side=side, wall_hl=wall_hl, wall_xy=[wall_x, wall_y], gap=gap, + box_xy=[box_x, box_y], plate_xy=plate_xy) + + def apply_instance(self, inst): + m = self.env.sim.model + bid, geoms = self._wall() + for g in geoms: # shrink the (collision + visual) wall boxes to this instance's length + m.geom_size[g, 1] = inst["wall_hl"] + m.body_pos[bid] = [inst["wall_xy"][0], inst["wall_xy"][1], envs.TABLE_Z + WALL_HALF_H] + m.body_quat[bid] = [1, 0, 0, 0] + bx, by = inst["box_xy"] + envs.set_obj_pose(self.env, "box_1", [bx, by, envs.TABLE_Z + BOX_HALF[2] + 0.0005]) + self._move_keep_orientation("plate_1", inst["plate_xy"]) + + def _move_keep_orientation(self, name, xy, clearance=0.002): + """Move a LIBERO mesh object to xy keeping the orientation LIBERO's sampler gave it at reset (that + orientation is the upright one; see task card), lowest collision point `clearance` above the table.""" + qa, da = envs.free_joint_addr(self.env, name) + d = self.env.sim.data + d.qpos[qa:qa + 2] = xy + d.qvel[da:da + 6] = 0.0 + self.env.sim.forward() + d.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (envs.TABLE_Z + clearance) + self.env.sim.forward() + + # ------------------------------------------------------------ perception stand-in + def observe(self): + """What a perfect perceiver reads off the camera image: box centre / yaw, the wall's footprint and the + plate centre. (Not the box-wall gap: 0-3 mm is below the camera resolution.)""" + bid, geoms = self._wall() + m = self.env.sim.model + wx, wy = m.body_pos[bid][:2] + hl = m.geom_size[geoms[0], 1] + b = envs.obj_pos(self.env, "box_1") + return dict(box_xy=b[:2].copy(), box_yaw=_yaw_of(envs.obj_quat(self.env, "box_1")), + wall_x=float(wx), wall_y=(float(wy - hl), float(wy + hl)), + plate_xy=envs.obj_pos(self.env, "plate_1")[:2].copy()) + + def _gap_now(self, o=None): + o = o or self.observe() + return float(abs(o["box_xy"][0] - o["wall_x"]) - WALL_HALF_T - BOX_HALF[0]) + + def alongside_wall(self, o=None): + """box (centre) still beside the wall and too close to it for a finger""" + o = o or self.observe() + return bool(o["wall_y"][0] < o["box_xy"][1] < o["wall_y"][1] and self._gap_now(o) < FINGER_NEEDS) + + # ------------------------------------------------------------ contacts + def _finger_landings(self): + """Surfaces the finger tips are resting on: contacts between a finger and a non-robot geom whose normal is + mostly vertical (a tip landing on a top surface). Returns {label: contact z}, label in 'wall' | 'box' | + 'plate' | 'table' | 'other'. Side contacts (a finger brushing the box's side, the push stroke) are ignored.""" + m, d = self.env.sim.model, self.env.sim.data + if not hasattr(self, "_geom_groups"): + fg = {g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_finger")} + robot = set(envs.robot_geom_ids(self.env)) + self._geom_groups = (fg, robot, set(self._wall()[1]), set(envs.obj_geom_ids(self.env, "box_1")), + set(envs.obj_geom_ids(self.env, "plate_1"))) + fg, robot, wall, box, plate = self._geom_groups + out = {} + for i in range(d.ncon): + c = d.contact[i] + if c.geom1 in fg and c.geom2 not in robot: + other = c.geom2 + elif c.geom2 in fg and c.geom1 not in robot: + other = c.geom1 + else: + continue + if abs(c.frame[2]) < 0.7: + continue + if other in wall: + lab = "wall" + elif other in box: + lab = "box" + elif other in plate: + lab = "plate" + else: + lab = "table" if (m.geom_id2name(other) or "").startswith("table") else "other" + out.setdefault(lab, float(c.pos[2])) + return out + + def _finger_landing(self): + hits = self._finger_landings() + for lab in ("wall", "box", "plate", "table", "other"): + if lab in hits: + return lab + return None + + # ------------------------------------------------------------ event monitor (what happened in this attempt) + def _closing_axis(self): + m, d = self.env.sim.model, self.env.sim.data + jid = m.joint_name2id(self.env.robots[0].gripper.joints[0]) + a = d.xaxis[jid][:2] + return a / max(np.linalg.norm(a), 1e-9) + + def _snapshot(self, contact_z): + """state at the moment a finger lands on something""" + o = self.observe() + e = self.sk.eef_pos() if self.sk is not None else self.env.sim.data.site_xpos[self.env.robots[0].eef_site_id] + bx = self.env.sim.data.body_xmat[envs.body_id(self.env, "box_1")].reshape(3, 3)[:2, 0] # box short axis + cosang = abs(float(self._closing_axis() @ (bx / max(np.linalg.norm(bx), 1e-9)))) + yaw_err = float(np.arccos(np.clip(cosang, 0.0, 1.0))) + wy0, wy1 = o["wall_y"] + return dict(contact_z=float(contact_z - envs.TABLE_Z), eef=[float(e[0]), float(e[1]), float(e[2])], + box_xy=[float(o["box_xy"][0]), float(o["box_xy"][1])], gap=self._gap_now(o), + alongside=self.alongside_wall(o), yaw_err=yaw_err, + span=float(2 * (BOX_HALF[0] * np.cos(yaw_err) + BOX_HALF[1] * np.sin(yaw_err))), + box_offset=float(np.linalg.norm(np.array(e[:2]) - o["box_xy"])), + # signed wall length beside the gripper towards each end (< 0: gripper is past that end) + wall_left={1: float(wy1 - e[1]), -1: float(e[1] - wy0)}) + + def _start_monitor(self): + b = envs.obj_pos(self.env, "box_1") + self._mon = dict(start_xy=b[:2].copy(), rest_z=float(b[2]), max_dz=0.0, wall_hit=None, box_top_hit=None, + prev=set()) + + def _monitor_step(self): + mon = self._mon + hits = self._finger_landings() + mon["max_dz"] = max(mon["max_dz"], float(envs.obj_pos(self.env, "box_1")[2] - mon["rest_z"])) + for lab, key in (("wall", "wall_hit"), ("box", "box_top_hit")): + if lab in hits and lab not in mon["prev"]: # onset of a landing; keep the latest one + mon[key] = self._snapshot(hits[lab]) + mon["prev"] = set(hits) + + def _finger_front(self, direction): + """how far the (closed) fingers stick out from the gripper site along `direction` (xy unit vector)""" + m, d = self.env.sim.model, self.env.sim.data + e = self.sk.eef_pos() + best = 0.0 + for g in range(m.ngeom): + if not (m.geom_id2name(g) or "").startswith("gripper0_finger") or m.geom_type[g] != 7: + continue + mid = m.geom_dataid[g] + v = m.mesh_vert[m.mesh_vertadr[mid]:m.mesh_vertadr[mid] + m.mesh_vertnum[mid]] + w = v @ d.geom_xmat[g].reshape(3, 3).T + d.geom_xpos[g] - e + best = max(best, float((w[:, :2] @ direction).max())) + return best + + # ------------------------------------------------------------ primitives used by the scripted policies + def _yaw_near(self, yaw): + """The parallel gripper (and the box) are symmetric under 180 deg, so pick yaw + k*pi closest to the current + commanded yaw: the OSC's axis-angle error is ill-defined at 180 deg and a half-turn request can flip the + hand over (measured: in the within protocol it twisted the arm into a state it never recovered from).""" + cands = [yaw + k * np.pi for k in (-1, 0, 1)] + cands = [c for c in cands if abs(c) <= np.pi / 2 + 0.4] or cands + return float(min(cands, key=lambda c: abs(c - self.sk.yaw))) + + def _align(self, tol=0.03, max_steps=60): + """Skills.move_to stops on position only; hold until the commanded yaw has actually been reached.""" + sk = self.sk + for _ in range(max_steps): + R = sk._R() @ sk.eef_mat().T + if np.arccos(np.clip((np.trace(R) - 1) / 2, -1, 1)) < tol: + break + sk.hold(1) + + def _guarded_descent(self, xyz, speed=0.12, max_steps=60): + """Straight-line descent that stops as soon as a finger lands on a surface above the target (the way a + grasp approach with contact sensing behaves). Without it, the OSC keeps pressing the finger into the + wall top and the compliant arm slides ~2 cm sideways off it. Returns what the finger landed on.""" + sk = self.sk + p0 = sk.eef_pos() + tgt = np.asarray(xyz, float) + sk.bias + dist = max(np.linalg.norm(tgt - p0), 1e-6) + R = sk._R() + landed = None + for k in range(max_steps): + ref = p0 + (tgt - p0) * min(1.0, (k + 1) * speed * DT / dist) + sk._act(ref - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip) + hit = self._finger_landing() + if hit is not None and sk.eef_pos()[2] > tgt[2] + 0.005: + landed = hit + break + if np.linalg.norm(tgt - sk.eef_pos()) < 0.003: + break + sk.hold(4) + return landed + + def push_along_wall(self, end, margin): + """Closed gripper (fingers side by side across the box) behind the box's trailing end face; slide the + box along y (towards the wall's +y end if end=+1, -y end if end=-1) until the box centre is `margin` + beyond that end of the wall.""" + sk, o = self.sk, self.observe() + bx, by = o["box_xy"] + wall_end = o["wall_y"][1] if end > 0 else o["wall_y"][0] + dist = float(np.clip(end * (wall_end + end * margin - by), 0.0, 0.32)) + yaw = self._yaw_near(o["box_yaw"] + np.pi / 2) # fingers close along the box's short axis + u = np.array([0.0, float(end)]) + sk.set_gripper(True, steps=6) + sk.move_to([bx, by - end * (BOX_HALF[1] + 0.06), Z_PUSH + 0.10], yaw=yaw) + self._align() + front = self._finger_front(u) + face = by - end * BOX_HALF[1] + start_y = face - end * (front + 0.035) + stop_y = face + end * (dist - front) + sk.move_to([bx, start_y, Z_PUSH + 0.10]) + sk.move_to([bx, start_y, Z_PUSH], tol=0.003) + sk.move_to([bx, stop_y, Z_PUSH], speed=PUSH_SPEED, tol=0.005, max_steps=300) + sk.hold(3) + sk.move_to([bx, stop_y, Z_PUSH + 0.10], speed=0.2) + + def grasp_and_place(self, dx=0.0, dy=0.0, dyaw=0.0): + """Top-down grasp across the box's width at the observed box centre (+ offsets), lift; if the box is + held, carry it to the plate and release it there.""" + sk, o = self.sk, self.observe() + gx, gy = o["box_xy"][0] + dx, o["box_xy"][1] + dy + yaw = self._yaw_near(o["box_yaw"] + np.pi / 2 + dyaw) + sk.set_gripper(False, steps=8) + sk.move_to([gx, gy, Z_GRASP + 0.10], yaw=yaw) + self._align() + self._guarded_descent([gx, gy, Z_GRASP]) + sk.set_gripper(True, steps=15) + z0 = envs.obj_pos(self.env, "box_1")[2] + sk.move_to([gx, gy, Z_GRASP + 0.15], speed=0.25) + if not (sk.holding("box_1") and envs.obj_pos(self.env, "box_1")[2] > z0 + 0.08): + sk.set_gripper(False, steps=8) + return + px, py = o["plate_xy"] + sk.move_to([px, py, PLACE_Z + 0.10]) + sk.move_to([px, py, PLACE_Z], tol=0.004) + sk.set_gripper(False, steps=12) + sk.move_to([px, py, PLACE_Z + 0.10]) + + def execute(self, inst, params): + if params["mode"] == "push_grasp": + self.push_along_wall(params["end"], params["margin"]) + self.grasp_and_place(params.get("dx", 0.0), params.get("dy", 0.0), params.get("dyaw", 0.0)) + + # ------------------------------------------------------------ outcome / F2 feedback + def outcome(self, inst): + """Success = box resting flat on the plate, released. The F2 text is built from the event monitor, so it + describes agent-driven attempts as well as scripted ones. Ends the current monitoring segment.""" + envs.settle(self.env, 30) + env, mon = self.env, self._mon or {} + b = envs.obj_pos(env, "box_1") + p = envs.obj_pos(env, "plate_1") + dxy = float(np.linalg.norm(b[:2] - p[:2])) + flat = abs(envs.obj_upright_cos(env, "box_1")) > 0.9 + held = bool(self.sk.holding("box_1")) if self.sk is not None else False + on_plate = envs.contacts_between(env, envs.obj_geom_ids(env, "box_1"), envs.obj_geom_ids(env, "plate_1")) + success = bool(dxy < 0.05 and envs.obj_min_z(env, "box_1") > envs.TABLE_Z + 0.004 and flat and not held + and on_plate) + lifted = mon.get("max_dz", 0.0) > 0.03 + start = mon.get("start_xy", b[:2]) + moved_y = float(b[1] - start[1]) + pushed = (not lifted) and abs(moved_y) > 0.02 + wall_hit, top_hit = mon.get("wall_hit"), mon.get("box_top_hit") + side_txt = "far (+x)" if inst["side"] > 0 else "near (-x)" + mode, parts, wall_left = "success", [], None + if success: + parts.append("The box is resting on the plate.") + else: + if pushed: + parts.append(f"The box was pushed {100 * abs(moved_y):.1f} cm along the wall (towards " + f"{'+y' if moved_y > 0 else '-y'}).") + if lifted: + if held: + mode = "still_held" + parts.append("The box is still in the gripper; it was not released on the plate.") + elif on_plate: + mode = "placed_off" + parts.append(f"The box was put on the plate but is not resting on it properly ({100 * dxy:.1f} cm " + f"from the plate centre{'' if flat else ', tilted'}).") + else: + mode = "placed_off" + parts.append(f"The box was lifted but ended on the table, {100 * dxy:.1f} cm from the plate " + f"centre.") + elif wall_hit is not None: + mode = "wall_blocked" + parts.append( + f"The gripper could not get around the box: the finger on the wall side ({side_txt} side) came down " + f"on top of the wall, {100 * wall_hit['contact_z']:.1f} cm above the table, which is higher than " + f"the top of the box ({200 * BOX_HALF[2]:.1f} cm), so the box was not grasped or lifted. Where the " + f"gripper came down, the box is flush against the wall (gap {1000 * max(wall_hit['gap'], 0):.0f} mm).") + if pushed: + e = 1 if moved_y > 0 else -1 + wall_left = wall_hit["wall_left"][e] + if wall_left > 0: + parts.append(f"The wall still continues {100 * wall_left:.1f} cm beyond the grasp point in the " + f"{'+y' if e > 0 else '-y'} direction.") + else: + parts.append(f"The grasp point was only {100 * -wall_left:.1f} cm past the " + f"{'+y' if e > 0 else '-y'} end of the wall, so the finger still came down on it.") + elif top_hit is not None: + mode = "box_top" + if top_hit["yaw_err"] > np.radians(30): + parts.append(f"The fingers came down on top of the box: along the gripper's closing direction the " + f"box measures {100 * top_hit['span']:.0f} cm, more than the {100 * GRIP_OPEN:.1f} cm " + f"maximum opening. The box was not lifted.") + else: + parts.append(f"A finger came down on top of the box (the gripper was {100 * top_hit['box_offset']:.1f}" + f" cm from the box centre), so the box was not grasped or lifted.") + else: + mode = "not_lifted" + parts.append(f"The box was not lifted; it is {100 * dxy:.1f} cm from the plate centre.") + if b[2] < envs.TABLE_Z - 0.05: + mode = "fell_off" + parts.append("The box fell off the table.") + elif not flat and mode != "placed_off": + parts.append("The box is no longer lying flat.") + out = dict(success=success, mode=mode, plate_dist=dxy, box_xy=[float(b[0]), float(b[1])], lifted=bool(lifted), + pushed_y=moved_y, alongside_wall=self.alongside_wall(), wall_left=wall_left, + terminal=bool(b[2] < envs.TABLE_Z - 0.05), detail=" ".join(parts)) + self._start_monitor() # next segment (within protocol) starts here + return out + + # ------------------------------------------------------------ scripted references + def _nearer_end(self): + o = self.observe() + by = o["box_xy"][1] + return 1 if (o["wall_y"][1] - by) < (by - o["wall_y"][0]) else -1 + + def default_params(self, inst): + return dict(mode="grasp") + + def oracle_params(self, inst): + return dict(mode="push_grasp", end=self._nearer_end(), margin=0.045) + + def blind_params(self, inst, attempt, rng): + return dict(mode="grasp", dx=float(rng.normal(0, 0.008)), dy=float(rng.normal(0, 0.008)), + dyaw=float(rng.normal(0, 0.12))) + + def adapt_params(self, inst, history): + """Uses the F2 measurements of the previous attempt: + wall_blocked / box_top on a direct grasp -> switch mode: slide the box out past the nearer wall end + (wall ends read off the image), then grasp; + wall_blocked after a push -> push further by the reported remaining wall length + 2 cm; + anything else (missed, dropped, ...) -> keep the strategy (the state is re-observed).""" + out, prm = history[-1]["outcome"], history[-1]["params"] + if prm["mode"] != "push_grasp": + if out["mode"] in ("wall_blocked", "box_top"): + return dict(mode="push_grasp", end=self._nearer_end(), margin=0.045) + return dict(prm) + if out["mode"] == "wall_blocked": + return dict(mode="push_grasp", end=prm["end"], + margin=float(prm["margin"] + max(out["wall_left"] or 0.0, 0.0) + 0.02)) + return dict(prm) + + # ------------------------------------------------------------ protocols + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + if self.protocol != "within": + return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt) + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + self.reset_instance(inst) + for a in range(k): + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + params = self.default_params(inst) if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + else: + raise ValueError(kind) + if params["mode"] == "push_grasp" and not self.alongside_wall(): + params = dict(params, mode="grasp") # already pushed clear in an earlier attempt of this episode + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history + + +@register_task +class WallFlushWithin(WallFlush): + name = "l3_wall_flush_within" + protocol = "within" diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/l4_nest.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/l4_nest.py new file mode 100644 index 0000000000000000000000000000000000000000..1176314e28197c49c48a0dcb3c29ba649f2b2780 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/l4_nest.py @@ -0,0 +1,644 @@ +"""L4-C nest_order: nest three cups one inside another; the tallest cup is not the widest. + +Scene: three open round cups (red, green, blue; 1.5 mm walls leaning outwards by TAPER_DEG = 5 deg, like slightly +flared tumblers) stand apart on the table. Each cup has its own bottom width and its own height (re-drawn per +instance, 3.5-10 cm tall). Cups are resized per instance by editing their geoms in sim.model (wall segments + +floor), so one env serves every instance (same technique as l4_fit_container). + +Trap (common sense): "the bigger cup goes outside", and a cup looks big mostly by its height. On (1 - P_AGREE) of +the instances the tallest cup is the middle one by width: it is at least INV_DH = 3.5 cm taller than the widest cup. +Their openings then differ by only 3-9 mm in diameter, and from the wrist camera at its start height the taller +one's opening is closer to the camera and looks about as big (about half the instances: bigger); from the front +camera the taller one looks clearly bigger. The narrowest cup is the shortest, so the very first move of the naive +order (widest cup into the tallest one) already fails, out on the table. + +A variant where the innermost cup was taller than the middle one (and the widest cup the tallest) was dropped +2026-10-08: its failure (middle cup on the rim of the innermost cup, both inside the outer one) looked like a nest +from both cameras -- the same flaw as the 14-deg version. + +What the failure looks like (the point of this version, user review 2026-10-08): which cup fits into which is +decided by the bottoms (same flare for all cups), and the sizes are drawn so that a cup whose bottom is too wide +does not go in at all -- it stays on the other cup's rim or wedges in the opening, its bottom at most STUCK_MAX += 0.5 cm below the rim. So a wrong placement leaves a cup standing on top of another one, its whole body above the +rim: visible in both cameras without any text feedback. A cup that fits goes down to the floor (centring tolerance +>= TOL_MIN = 7.5 mm thanks to the flare); in the right nest the taller, narrower cups stick out of the shorter, +wider ones, but each stands inside the next. + +Prior (naive): tallest cup outermost, then the next tallest. Learner: a cup that ended up on top of another cup +must go outside it; swap that pair. Feedback F1 (default) says only failed / succeeded; F2 (ablation) describes +which cup stands in / on which, in words, with no sizes or positions. + +Only move_to / open / close are needed: grasp a cup across its upper wall, carry it over the other cup, release it +just above that cup's rim. +""" +import itertools + +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, _wrap, register_generated +from ..skills import _rot_err +from ..task_base import LFFTask, register_task + +N_SEG = 20 # wall segments per cup (regular polygon) +TAN_SEG = float(np.tan(np.pi / N_SEG)) +COS_SEG = float(np.cos(np.pi / N_SEG)) +TAPER_DEG = 5.0 # wall lean (from vertical) +TAPER = float(np.radians(TAPER_DEG)) +TT = float(np.tan(TAPER)) +WALL_T = 0.0015 # wall thickness (normal to the wall) +WALL_TH = WALL_T / float(np.cos(TAPER)) # horizontal wall thickness +FLOOR_T = 0.003 +Z0 = 0.0003 # walls start this far above the cup's underside (the floor disc carries the cup) +H_RANGE = (0.035, 0.100) # total cup height +RB_WIDE = (0.023, 0.030) # bottom outer apothem of the cup with the widest bottom +STEP = (0.0055, 0.0075) # bottom apothem difference between neighbours in the true order +RIM_MAX = 0.033 # outer apothem of the widest opening (gripper opens 7.9 cm) +CLEAR_MIN = 0.003 # radial gap (worst case) of a fitting cup standing on the other cup's floor +TOL_MIN = 0.0075 # a fitting cup goes in if its bottom lands within this of the other cup's axis +STUCK_MAX = 0.005 # a too-wide cup's bottom stops no deeper than this below the other cup's rim (5-deg walls +# self-lock: a cup pressed 1.2 cm into the opening wedged, and the narrow cup tipped over with it) +INV_DH = 0.035 # in the swapped pair the narrower cup is taller by at least this +KEEP_DH = 0.010 # in an unswapped pair the wider cup is taller by at least this +P_AGREE = 0.15 # share of instances whose height order is the right nesting order +SEAT_H = 0.010 # "standing on the floor": bottom less than this above the other cup's floor +SEAT_TILT = 15.0 # deg; a tall cup in a short, wider one can lean a little +WRIST_CAM_H = 0.367 # wrist camera height above the table at the start pose (measured 2026-10-08) +COLORS = {"red": (0.78, 0.22, 0.20, 1.0), "green": (0.28, 0.62, 0.32, 1.0), "blue": (0.22, 0.42, 0.80, 1.0)} +CUP_NAMES = ("cup_1", "cup_2", "cup_3") +DENSITY = 600.0 +# execution +GRASP_BELOW_RIM = 0.012 # gripper site this far below the rim when grasping +Z_CARRY = envs.TABLE_Z + 0.24 +DROP = 0.006 # held cup's bottom this far above the receiving rim at release +FINGER_CLEAR = 0.015 # gripper site at least this far above any rim around the target at release: fingers opened +# inside a taller outer cup press on its wall and carry it away on the way up (seed 1009, 2026-10-08) +PARK = (-0.45, 0.0, envs.TABLE_Z + 0.35) +H_NOISE = 0.03 # relative noise of the blind policy's height judgement + + +# ---------------------------------------------------------------- cup geometry +def _quat_mul(a, b): + w1, x1, y1, z1 = a + w2, x2, y2, z2 = b + return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, + w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2]) + + +def _seg_quat(phi): + """segment frame: about z by phi, then tilted about its own y (tangential) axis by TAPER, so that its local z + (along the wall) leans outwards and its local x is the wall's outward normal""" + qz = np.array([np.cos(phi / 2), 0.0, 0.0, np.sin(phi / 2)]) + qy = np.array([np.cos(TAPER / 2), 0.0, np.sin(TAPER / 2), 0.0]) + return _quat_mul(qz, qy) + + +def seg_half_len(rb, H): + """tangential half length of a wall segment: one polygon side at the rim (+0.2 mm overlap)""" + return (rb + TT * H) * TAN_SEG + 0.0002 + + +def rim_radius(rb, H): + """outer apothem of the opening""" + return rb + TT * H + + +def inner_radius(rb, z): + """inner apothem at height z above the cup's underside""" + return rb + TT * z - WALL_TH + + +def bottom_reach(rb, H): + """largest horizontal radius of the cup's outside at its bottom (the segment tips stick out a little beyond + the polygon because every segment is as wide as a rim-level polygon side)""" + return float(np.hypot(rb + TT * Z0, seg_half_len(rb, H))) + + +def fit_clearance(rb_in, H_in, rb_out): + """radial clearance (worst case over relative yaw) of cup `in` standing on the floor of cup `out`; + negative = does not go down to the floor. The flare is the same for both cups, so the bottom is the tightest + height.""" + return inner_radius(rb_out, FLOOR_T) - bottom_reach(rb_in, H_in) + + +def centring_tol(rb_in, H_in, rb_out, H_out): + """how far (worst case) cup `in`'s bottom centre may be off cup `out`'s axis when it is lowered in at the rim + and still get inside (the flared wall then guides it down)""" + return inner_radius(rb_out, H_out) - bottom_reach(rb_in, H_in) + + +def stop_height(rb_in, rb_out, H_out): + """height (above cup `out`'s underside) where a too-wide cup `in`, lowered centred, stops: where its bottom + meets the sloping inner wall, or on the rim if that is higher than the cup""" + return min((rb_in - rb_out + WALL_TH) / TT, H_out) + + +def _cup_parts(rb, H): + """[(pos, half size, quat)] of the wall segments in the cup body frame (origin at mid height).""" + zc = (Z0 + H) / 2 + hs = (H - Z0) / (2 * np.cos(TAPER)) + rc = rb + TT * zc - WALL_T / 2 * np.cos(TAPER) + zz = zc + WALL_T / 2 * np.sin(TAPER) - H / 2 + hl = seg_half_len(rb, H) + out = [] + for k in range(N_SEG): + phi = 2 * np.pi * k / N_SEG + out.append(((rc * np.cos(phi), rc * np.sin(phi), zz), (WALL_T / 2, hl, hs), _seg_quat(phi))) + return out + + +def _floor_part(rb, H): + return (0.0, 0.0, -H / 2 + FLOOR_T / 2), (rb - 0.0003, FLOOR_T / 2, 0.0), np.array([1.0, 0.0, 0.0, 0.0]) + + +def cup_xml(model_name, rgba): + """Open flared cup: N_SEG tilted wall boxes + a cylinder floor (sizes are overwritten per instance).""" + geoms = [] + rb, H = RB_WIDE[1], H_RANGE[1] + for k, (p, s, q) in enumerate(_cup_parts(rb, H)): + geoms.append(f' ') + geoms.append(f' ') + fp, fs, _ = _floor_part(rb, H) + geoms.append(f' ') + geoms.append(f' ') + return _wrap(model_name, "\n".join(geoms), H / 2, rim_radius(rb, H) / COS_SEG) + + +def disable_midphase(env): + """The cups are resized at run time by editing geom pos / size in sim.model, but MuJoCo's per-body bounding + volume hierarchy (bvh_aabb, used by the collision mid-phase) is computed once at compile time for the registered + maximum size. A resized wall that lies outside its compiled leaf box is silently skipped: the gripper fingers + passed straight through the walls of the smaller cups (found 2026-10-07). Without the mid-phase MuJoCo tests all + geom pairs of two nearby bodies (still filtered by the run-time geom_rbound set in _reshape_cup).""" + import mujoco + m = env.sim.model._model + m.opt.disableflags |= int(mujoco.mjtDisableBit.mjDSBL_MIDPHASE) + + +def kendall(a, b): + """number of pairs ordered differently in the two orders""" + pa, pb = {c: k for k, c in enumerate(a)}, {c: k for k, c in enumerate(b)} + return sum((pa[x] < pa[y]) != (pb[x] < pb[y]) for x, y in itertools.combinations(a, 2)) + + +@register_task +class NestOrder(LFFTask): + name = "l4_nest_order" + level = "L4" + category = "geometry_inference" + capabilities = ("Perceive", "Reason", "Plan") + instruction = "Nest the red, green and blue cups one inside another." + instruction_indirect = "Put the three cups one inside another, like a set of nesting cups." + + # ------------------------------------------------------------ scene + def make_bddl(self): + cats = [register_generated(f"LffNestCup{c.capitalize()}", cup_xml(f"lff_nest_cup_{c}", COLORS[c])) + for c in COLORS] + regions = [(-0.25, -0.15), (-0.05, 0.0), (-0.25, 0.15)] + objs = [(n, cat, f"{n}_region", (x - 0.01, y - 0.01, x + 0.01, y + 0.01)) + for n, cat, (x, y) in zip(CUP_NAMES, cats, regions)] + return write_bddl(self.name, self.instruction, objs) + + @staticmethod + def _heights_ok(case, h): + """h[s] = height of the cup with the s-th narrowest bottom (0 = innermost in the true nest)""" + if case == "agree": # taller = wider: the height order is the nesting order + return h[2] >= h[1] + KEEP_DH and h[1] >= h[0] + KEEP_DH + if case == "swap_wide": # the middle cup is the tallest, the narrowest one the shortest + return h[1] >= h[2] + INV_DH and h[2] >= h[0] + KEEP_DH + raise ValueError(case) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + u = rng.random() + case = "agree" if u < P_AGREE else "swap_wide" + for _ in range(200000): + heights = [float(rng.uniform(*H_RANGE)) for _ in range(3)] # by true size: 0 = narrowest bottom + if not self._heights_ok(case, heights): + continue + rb3 = float(rng.uniform(*RB_WIDE)) + rb2 = rb3 - float(rng.uniform(*STEP)) + rb1 = rb2 - float(rng.uniform(*STEP)) + rbs = [rb1, rb2, rb3] + rims = [rim_radius(rb, h) for rb, h in zip(rbs, heights)] + if max(rims) > RIM_MAX: + continue + ok = True + for p, q in itertools.permutations(range(3), 2): # p into q + if p < q: + ok &= (fit_clearance(rbs[p], heights[p], rbs[q]) >= CLEAR_MIN + and centring_tol(rbs[p], heights[p], rbs[q], heights[q]) >= TOL_MIN) + else: + ok &= heights[q] - stop_height(rbs[p], rbs[q], heights[q]) <= STUCK_MAX + if ok: + break + else: + raise RuntimeError("could not sample cup sizes") + xy = [] + while len(xy) < 3: + xy = [] + for _k in range(3): + for _t in range(200): + p = [float(rng.uniform(-0.27, 0.02)), float(rng.uniform(-0.17, 0.17))] + if all(np.hypot(p[0] - q[0], p[1] - q[1]) >= 0.14 for q in xy): + xy.append(p) + break + # the colour is fixed per object (cup_1 red, cup_2 green, cup_3 blue: one generated class each); shuffle + # which object gets which size / height / position + perm = [int(i) for i in rng.permutation(3)] # perm[size index] = object slot + cups = [None] * 3 + for s in range(3): + cups[perm[s]] = dict(name=CUP_NAMES[perm[s]], color=list(COLORS)[perm[s]], rb=rbs[s], height=heights[s], + rim=rims[s], xy=xy[s], size_rank=s) + order = sorted(range(3), key=lambda j: -cups[j]["rb"]) # outermost first (indices into cups) + naive = sorted(range(3), key=lambda j: -cups[j]["height"]) + assert (naive == order) == (case == "agree"), (seed, case) + by = lambda s: perm[s] # noqa: E731 object index of size rank s + return dict(seed=int(seed), case=case, cups=cups, order=order, naive_order=naive, + bottom_cm=[round(200 * c["rb"], 2) for c in cups], + opening_cm=[round(200 * c["rim"], 2) for c in cups], + height_cm=[round(100 * c["height"], 2) for c in cups], + # relative size of each opening in the wrist camera at its start height (1 = largest) + wrist_apparent=[round(float(v), 3) for v in (lambda a: a / a.max())(np.array( + [c["rim"] / (WRIST_CAM_H - c["height"]) for c in cups]))], + clear_mm=[round(1000 * fit_clearance(rbs[s], heights[s], rbs[s + 1]), 2) for s in range(2)], + tol_mm=[round(1000 * centring_tol(rbs[s], heights[s], rbs[s + 1], heights[s + 1]), 2) + for s in range(2)], + # wrong neighbour pairs: how deep (cm) the wider cup's bottom gets below the narrower cup's rim + stuck_cm={f"{by(s + 1)}in{by(s)}": round(100 * (heights[s] - stop_height( + rbs[s + 1], rbs[s], heights[s])), 2) for s in range(2)}) + + def _reshape_cup(self, name, rb, H): + m = self.env.sim.model + o = self.env.objects_dict[name] + parts = _cup_parts(rb, H) + [_floor_part(rb, H)] + for names in (o.contact_geoms, o.visual_geoms): + assert len(names) == len(parts), (name, len(names)) + for k, n in enumerate(names): + g = m.geom_name2id(n) + pos, size, quat = parts[k] + m.geom_pos[g] = pos + m.geom_size[g] = size + m.geom_quat[g] = quat + if k < N_SEG: + m.geom_rbound[g] = float(np.linalg.norm(size)) + m.geom_aabb[g] = [0, 0, 0, *size] + else: + m.geom_rbound[g] = float(np.hypot(size[0], size[1])) + m.geom_aabb[g] = [0, 0, 0, size[0], size[0], size[1]] + # mass / inertia of the resized cup: conical shell + disc floor + bid = int(m.geom_bodyid[m.geom_name2id(o.contact_geoms[0])]) + slant = (H - Z0) / np.cos(TAPER) + r_mid = rb + TT * (H + Z0) / 2 + wall_m = DENSITY * 2 * np.pi * r_mid * WALL_T * slant + floor_m = DENSITY * np.pi * rb ** 2 * FLOOR_T + mass = wall_m + floor_m + # wall centroid height (from the underside): area-weighted, r grows linearly with z + r0, r1 = rb + TT * Z0, rb + TT * H + z_w = Z0 + (H - Z0) * (r0 + 2 * r1) / (3 * (r0 + r1)) + z_cm = (wall_m * z_w + floor_m * FLOOR_T / 2) / mass + Izz = wall_m * r_mid ** 2 + floor_m * rb ** 2 / 2 + Ixx = (wall_m * (r_mid ** 2 / 2 + (H - Z0) ** 2 / 12 + (z_w - z_cm) ** 2) + + floor_m * (rb ** 2 / 4 + (FLOOR_T / 2 - z_cm) ** 2)) + m.body_mass[bid] = mass + m.body_inertia[bid] = [Ixx, Ixx, Izz] + m.body_ipos[bid] = [0.0, 0.0, z_cm - H / 2] + m.body_iquat[bid] = [1.0, 0.0, 0.0, 0.0] + + def apply_instance(self, inst): + disable_midphase(self.env) + for c in inst["cups"]: + self._reshape_cup(c["name"], c["rb"], c["height"]) + envs.set_obj_pose(self.env, c["name"], [*c["xy"], envs.TABLE_Z + c["height"] / 2 + 0.0005]) + + # ------------------------------------------------------------ state + def _cup_state(self, inst, j): + c = inst["cups"][j] + bid = envs.body_id(self.env, c["name"]) + p = self.env.sim.data.body_xpos[bid].copy() + R = self.env.sim.data.body_xmat[bid].reshape(3, 3) + tilt = float(np.degrees(np.arccos(np.clip(R[2, 2], -1, 1)))) + bottom = p - R[:, 2] * c["height"] / 2 # centre of the floor's underside + rim = p + R[:, 2] * c["height"] / 2 + return dict(p=p, tilt=tilt, bottom=bottom, rim=rim, floor_top=bottom[2] + FLOOR_T * R[2, 2]) + + def relations(self, inst): + """For each cup: which cup it stands in / on (if any), how high, seated or not.""" + st = [self._cup_state(inst, j) for j in range(3)] + rel = [] + for j in range(3): + sj = st[j] + best = None + for i in range(3): + if i == j: + continue + ci, si = inst["cups"][i], st[i] + if si["tilt"] > 45: + continue + d = float(np.hypot(*(sj["bottom"][:2] - si["p"][:2]))) + if d > rim_radius(ci["rb"], ci["height"]) + 0.01: + continue # not above / in cup i + hb = float(sj["bottom"][2] - si["floor_top"]) # j's bottom above i's floor + # (the last test keeps a cup from being reported as standing in the cup it contains) + if hb < -0.004 or hb > ci["height"] + 0.02 or sj["bottom"][2] < si["bottom"][2] + FLOOR_T / 2: + continue + if best is None or hb < best[1]: + best = (i, hb, d) + if best is None: + on_table = sj["bottom"][2] < envs.TABLE_Z + 0.01 and sj["tilt"] < 30 + rel.append(dict(cup=j, on=None, table=bool(on_table), tilt=sj["tilt"], xy=sj["p"][:2].tolist(), + fallen=bool(sj["tilt"] > 45))) + continue + i, hb, d = best + ci = inst["cups"][i] + seated = hb < SEAT_H and sj["tilt"] < SEAT_TILT + on_rim = hb > ci["height"] - FLOOR_T - 0.004 + rel.append(dict(cup=j, on=i, height=hb, seated=bool(seated), on_rim=bool(on_rim), tilt=sj["tilt"], + offset=d, xy=sj["p"][:2].tolist(), fallen=bool(sj["tilt"] > 45))) + return rel + + def outcome(self, inst): + envs.settle(self.env, 40) + cups = inst["cups"] + rel = self.relations(inst) + held = [j for j in range(3) if self.sk is not None and self.sk.holding(cups[j]["name"])] + col = [c["color"] for c in cups] + seated_in = {r["cup"]: r["on"] for r in rel if r.get("on") is not None and r["seated"]} + # success: a chain outer <- mid <- inner, all seated and upright, the outer cup standing on the table + success = False + for a, b, c in itertools.permutations(range(3)): + if seated_in.get(b) == a and seated_in.get(c) == b and _on_table_upright(rel, a): + success = True + success = bool(success and not held) + fb = dict(seated=[[j, i] for j, i in seated_in.items()], blocked=[], offcentre=[], held=held) + lines = [] + res = dict(success=success, relations=rel, feedback=fb) + if held: + lines.append(f"The {col[held[0]]} cup is still in the gripper.") + if success: + a = [j for j in range(3) if j not in seated_in][0] + b = [j for j, i in seated_in.items() if i == a][0] + c = [j for j, i in seated_in.items() if i == b][0] + res["detail"] = (f"All three cups are nested: the {col[c]} cup stands inside the {col[b]} cup, " + f"which stands inside the {col[a]} cup.") + res["failure"] = None + return res + # bottom-up description + st = {r["cup"]: self._cup_state(inst, r["cup"]) for r in rel} + for r in sorted(rel, key=lambda r: st[r["cup"]]["bottom"][2]): + j = r["cup"] + if j in held: + continue + if r.get("on") is None: + if r["fallen"]: + lines.append(f"The {col[j]} cup has fallen over.") + elif r["table"]: + lines.append(f"The {col[j]} cup is standing on the table, not in another cup.") + else: + lines.append(f"The {col[j]} cup is neither standing on the table nor inside another cup.") + continue + i = r["on"] + if r["seated"]: + lines.append(f"The {col[j]} cup is inside the {col[i]} cup, standing on its bottom.") + continue + # did not go in. The text says only what a camera shows (no sizes); the structured field keeps the + # nominal verdict for the scripted learner + tilt = f", tilted about {r['tilt']:.0f} degrees" if r["tilt"] >= 8 else "" + if r["on_rim"]: + lines.append(f"The {col[j]} cup is sitting on the rim of the {col[i]} cup, not inside it{tilt}.") + else: + lines.append(f"The {col[j]} cup is stuck in the opening of the {col[i]} cup, not down inside " + f"it{tilt}.") + over = cups[j]["rb"] - cups[i]["rb"] + if over > 0: + fb["blocked"].append([j, i, round(100 * r["height"], 1)]) + else: + fb["offcentre"].append([j, i, round(100 * r["height"], 1)]) + res["detail"] = " ".join(lines) if lines else "The cups are not nested." + res["failure"] = "blocked" if fb["blocked"] else ("offcentre" if fb["offcentre"] else + ("held" if held else "incomplete")) + return res + + # ------------------------------------------------------------ execution + def execute(self, inst, params): + """params: order = [outer, middle, inner] (indices into inst['cups']). Puts the middle cup into the outer + one; if it went in (judged from the scene, as an agent would see it), puts the inner cup into the middle + one. Optional (robustness checks): dxy = (dx, dy) release offset (m), drop (m), grasp_below (m), + carry_speed (m/s or None = as fast as the controller allows).""" + o, mid, inn = [int(v) for v in params["order"]] + ok = self._move_cup(inst, mid, o, params) + if ok: + self._move_cup(inst, inn, mid, params) + self.sk.move_to(list(PARK), yaw=0.0) + + def _move_cup(self, inst, j, i, params): + sk = self.sk + sj = self._cup_state(inst, j) + x, y = sj["p"][:2] + rim = sj["rim"][2] + sk.set_gripper(False, steps=5) + sk.move_to([x, y, Z_CARRY], yaw=0.0) + sk.move_to([x, y, rim + 0.06], tol=0.004) + sk.move_to([x, y, rim - params.get("grasp_below", GRASP_BELOW_RIM)], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([x, y, Z_CARRY], speed=params.get("carry_speed", 0.3)) + si = self._cup_state(inst, i) + dx, dy = params.get("dxy", (0.0, 0.0)) + tx, ty = si["p"][0] + dx, si["p"][1] + dy + drop = params.get("drop", DROP) + sk.move_to([tx, ty, Z_CARRY], tol=0.004) + off = self._cup_state(inst, j)["bottom"] - sk.eef_pos() + # approach above the highest rim there (the target cup may stand inside a taller one) + top = max(s["rim"][2] for s in (self._cup_state(inst, q) for q in range(3) if q != j) + if np.hypot(s["p"][0] - tx, s["p"][1] - ty) < 0.04) + sk.move_to([tx - off[0], ty - off[1], max(top, si["rim"][2]) + drop + 0.03 - off[2]], tol=0.003) + z_rel = si["rim"][2] + drop + if top > si["rim"][2] + 0.002: # the target stands inside a taller cup: let go above that rim + z_rel = max(z_rel, top + FINGER_CLEAR - (inst["cups"][j]["height"] + - params.get("grasp_below", GRASP_BELOW_RIM))) + tgt = self._servo_cup(inst, j, [tx, ty], z_rel) + sk.grip = -1.0 + self._hold_at(tgt, 12) + sk.move_to([tgt[0], tgt[1], Z_CARRY], speed=0.3) + envs.settle(self.env, 20) + r = [q for q in self.relations(inst) if q["cup"] == j][0] + return bool(r.get("on") == i and r["seated"]) + + def _hold_at(self, target, steps): + sk = self.sk + R = sk._R() + for _ in range(steps): + sk._act(np.asarray(target) - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip) + + def _servo_cup(self, inst, j, xy, z_bottom, max_steps=60, tol=0.0015): + """closed loop on the held cup's bottom centre (scripted policies only). Stops where the cup is held up + (a too-wide cup on / in another cup's rim) instead of pressing on: a person lets go there too, and + pressing on tips the cups over.""" + sk = self.sk + R = sk._R() + goal = np.array([xy[0], xy[1], z_bottom]) + tgt = e_prev = sk.eef_pos() + zs = [] + for k in range(max_steps): + b, e = self._cup_state(inst, j)["bottom"], sk.eef_pos() + if k >= 8 and np.linalg.norm(b - goal) < tol and np.linalg.norm(e - e_prev) < 0.0005: + break + zs.append(b[2]) + if k >= 12 and b[2] - goal[2] > 0.003 and zs[-6] - b[2] < 0.0005: + return e # blocked: release here + tgt = goal - (b - e) + sk._act(tgt - e, _rot_err(R, sk.eef_mat()), sk.grip) + e_prev = e + return tgt + + # ------------------------------------------------------------ scripted policies + def default_params(self, inst): + """prior: the bigger-looking cup goes outside, and the cups look big by their height: tallest outermost""" + return dict(order=list(inst["naive_order"])) + + def oracle_params(self, inst): + return dict(order=list(inst["order"])) + + def blind_params(self, inst, attempt, rng): + """no history: the same height judgement again, with a little noise""" + est = [c["height"] * (1 + rng.normal(0, H_NOISE)) for c in inst["cups"]] + return dict(order=[int(i) for i in np.argsort(est)[::-1]]) + + @staticmethod + def constraints(history): + """pairs (outer, inner) implied by the F2 feedback of earlier attempts""" + pairs = set() + for h in history: + fb = h["outcome"].get("feedback") or {} + for j, i in fb.get("seated", []): + pairs.add((int(i), int(j))) # j sits in i -> i is outside j + for j, i, _ in fb.get("blocked", []): + pairs.add((int(j), int(i))) # j does not fit into i -> j must be outside i + for j, i, _ in fb.get("offcentre", []): + pairs.add((int(i), int(j))) # j would fit into i + return pairs + + def adapt_params(self, inst, history): + """Scripted learner. It does not perceive the bottoms at all; it uses only which cup went into / stayed on + top of which (visible in the camera images; the structured part of the outcome): every such relation gives + an (outer, inner) pair; among the untried orders consistent with all pairs it takes the one closest (fewest + swapped pairs) to its prior, the height order; ties go to the larger height agreement.""" + pairs = self.constraints(history) + rims = [c["height"] for c in inst["cups"]] + prior = list(inst["naive_order"]) + tried = {tuple(h["params"]["order"]) for h in history if (h["outcome"].get("feedback") or {}).get("blocked")} + cands = [] + for order in itertools.permutations(range(3)): + pos = {c: k for k, c in enumerate(order)} + consistent = all(pos[a] < pos[b] for a, b in pairs) + agree = sum(rims[order[k]] - rims[order[k + 1]] for k in range(2)) + cands.append((consistent, tuple(order) not in tried, -kendall(order, prior), agree, order)) + best = max(cands) + return dict(order=list(best[4])) + + def random_order_params(self, inst, history, rng): + """sensitivity variant: a random order each retry, no history""" + return dict(order=[int(i) for i in rng.permutation(3)]) + + EXTRA_KINDS = ("random_order",) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + if kind not in self.EXTRA_KINDS: + return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt) + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + params = self.default_params(inst) if a == 0 else self.random_order_params(inst, history, rng) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"]: + break + return history + + +def _on_table_upright(rel, j): + r = [q for q in rel if q["cup"] == j][0] + return r.get("on") is None and r["table"] and r["tilt"] < 8.0 and not r["fallen"] + + +# ---------------------------------------------------------------- physical validity checks +def physics_check(seed0=1000, n=8, out=None): + """All 6 orders on each instance; expect success iff the order is the true one.""" + import json + task = NestOrder() + rows = [] + for seed in range(seed0, seed0 + n): + inst = task.sample_instance(seed) + for order in itertools.permutations(range(3)): + task.reset_instance(inst) + task.execute(inst, dict(order=list(order))) + o = task.outcome(inst) + expect = list(order) == inst["order"] + # for a cup that did not go in: how far (cm) its bottom is below the other cup's rim + below_rim = [round(100 * (inst["cups"][r["on"]]["height"] - FLOOR_T - r["height"]), 2) + for r in o["relations"] if r.get("on") is not None and not r["seated"]] + rows.append(dict(seed=seed, case=inst["case"], order=list(order), success=o["success"], expect=expect, + failure=o["failure"], detail=o["detail"], below_rim_cm=below_rim, + clear_mm=inst["clear_mm"], tol_mm=inst["tol_mm"], bottom_cm=inst["bottom_cm"], + opening_cm=inst["opening_cm"], height_cm=inst["height_cm"])) + print(f"seed {seed} order {order} succ={o['success']} expect={expect} | {o['detail']}" + + ("" if o["success"] == expect else " <-- MISMATCH"), flush=True) + if out: + with open(out, "w") as f: + json.dump(rows, f, indent=1) + print("total", len(rows), "mismatches", sum(r["success"] != r["expect"] for r in rows)) + return rows + + +def robustness_check(seed0=1000, n=6, out=None): + """True order with execution errors: release off-centre (both moves) by 0-9 mm in a random direction, released + 3 cm above the rim, grasped lower, carried at full controller speed.""" + import json + task = NestOrder() + rows = [] + cases = [("centred", {}), ("off3", dict(off=0.003)), ("off5", dict(off=0.005)), ("off7", dict(off=0.007)), + ("off9", dict(off=0.009)), ("drop3cm", dict(drop=0.03)), ("off4_drop3cm", dict(off=0.004, drop=0.03)), + ("grasp2cm", dict(grasp_below=0.02)), ("fast_carry", dict(carry_speed=None))] + for seed in range(seed0, seed0 + n): + inst = task.sample_instance(seed) + rng = np.random.default_rng(seed) + for name, c in cases: + a = rng.uniform(0, 2 * np.pi) + off = c.get("off", 0.0) + params = dict(order=list(inst["order"]), dxy=(off * np.cos(a), off * np.sin(a))) + params.update({k: v for k, v in c.items() if k != "off"}) + task.reset_instance(inst) + task.execute(inst, params) + o = task.outcome(inst) + rows.append(dict(seed=seed, case=name, success=o["success"], detail=o["detail"], tol_mm=inst["tol_mm"], + height_cm=inst["height_cm"])) + print(f"seed {seed} {name:13s} succ={o['success']} | {o['detail']}", flush=True) + if out: + with open(out, "w") as f: + json.dump(rows, f, indent=1) + for name, _ in cases: + r = [x["success"] for x in rows if x["case"] == name] + print(f"{name:13s} {sum(r)}/{len(r)}") + return rows + + +if __name__ == "__main__": + # python -m lffbench.tasks.l4_nest physics results/l4_nest_order/physics_check.json [n] + # python -m lffbench.tasks.l4_nest robust results/l4_nest_order/robustness_check.json [n] + import sys + n_arg = int(sys.argv[3]) if len(sys.argv) > 3 else None + if sys.argv[1] == "physics": + physics_check(out=sys.argv[2] if len(sys.argv) > 2 else None, n=n_arg or 8) + elif sys.argv[1] == "robust": + robustness_check(out=sys.argv[2] if len(sys.argv) > 2 else None, n=n_arg or 6) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/l5_tablecloth_pull.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/l5_tablecloth_pull.py new file mode 100644 index 0000000000000000000000000000000000000000..d80d949cb344b6f76199ae9a4dbdeaa0ca800a66 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/l5_tablecloth_pull.py @@ -0,0 +1,392 @@ +"""L5-C tablecloth_pull: yank a board out from under a cube so that the cube lands inside a band. + +Category dynamics_adaptation (L5): "figure out how this object moves". Replaces l5_tip_threshold, which could not +be built robustly with this robot (see task_cards/l5_tip_threshold.md). + +Scene: a 30 x 8 x 1 cm wooden board lies on the table, pointing away from the robot, with a black handle block +at its near end. A red 4 cm cube stands on the far part of the board. A green band (6 cm deep, across the +table) is painted on the table under the board, a few cm closer to the robot than the cube. The agent may touch +only the board / handle, never the cube. + +Physics. If the board is pulled slowly the cube rides along on it (static friction). If it is yanked, the board +slides out from under the cube; while it slides, friction drags the cube a little towards the robot, so the +cube drops onto the table having moved d towards the robot. d DEcreases with the pull speed (counter-intuitive: +a harder yank moves the cube less) and increases with the cube-board friction mu. + +Hidden variable: the cube's friction mu (0.08-0.15; the cube looks the same for every mu), which shifts the whole +speed -> displacement curve and the speed below which the cube rides along. + +Why the prior fails. The classic tablecloth prior is to yank as fast as possible (0.6 m/s, the arm's top speed); +the band is always placed >= 1.3 cm beyond the displacement such a yank produces, so the cube lands short of it. F2 reports where the cube ended relative to the band (robot-frame words, cm) or that it +rode along; the agent has to infer which way to change the pull speed (faster = less displacement) and by how +much. + +Rule (stated in the instruction and enforced, 2026-10-08): ONE pull. Only one move command may drive the board +(>= PULL_EPS), the cube must still be where it started (<= PRE_TOL, grasp nudges) when that pull begins, and all +other move commands together may drive the board at most STRAY_MAX. Gripper open / close commands never count. +Without it every cla2 success (Sonnet, 4/4) dragged the board slowly first so that the cube rode to the band and the +last pull only added a little (one dragged it 4 cm, then yanked it sideways; one moved it with 11 commands, most +of them open-gripper strikes): the friction never mattered. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +BOARD, CUBE, BAND = "board_1", "cube_1", "band_1" +B_HALF = (0.15, 0.04, 0.005) # 30 x 8 x 1 cm +H_HALF = (0.0125, 0.02, 0.015) # handle 2.5 x 4 x 3 cm on top of the near end +C_HALF = 0.02 # 4 cm cube +LF = 0.05 # cube centre to the board's far edge +BAND_HALF_X = 0.03 # band 6 cm deep: the 4 cm cube must be fully inside -> centre within +-1 cm +BAND_HALF_Y = 0.12 +LINE_W = 0.005 +TOL = BAND_HALF_X - C_HALF +MU_BOARD = 0.3 # board-table friction (fixed) +STROKE = 0.25 # scripted pull length +V_MIN, V_MAX = 0.15, 0.80 +# one-pull rule (2026-10-08). Board motion is the larger of its two ends' 3-D paths and is only counted while the robot +# drives the board (touches it, or it speeds up; a board sliding on its own only slows down), so coasting after a +# strike or a release is not charged to the next command. Measured on the cla2 agent runs and the scripted policy: +# approach moves 0 mm; closing on the handle 0.6-2 mm (agents) / 4.6 mm (script); release after the pull 3-10 mm +# (gripper commands never count as pulls); the loophole drags 13-41 mm per command, open-gripper strikes 11-54 mm. +PULL_EPS = 0.003 # a move command that drives the board this far is a pull +PRE_TOL = 0.01 # the cube may have moved at most this much (grasp nudges) when the pull starts +STRAY_MAX = 0.005 # board motion driven by all the other move commands together (each below PULL_EPS) +ACC_EPS = 0.0002 # board speed-up per control step (m/step) that counts as the robot driving it +_SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"' + + +def board_xml(name): + hp = (-B_HALF[0] + H_HALF[0], 0.0, B_HALF[2] + H_HALF[2]) + wood, black = (0.62, 0.45, 0.28, 1.0), (0.12, 0.12, 0.12, 1.0) + g = (f' \n' + f' \n' + f' \n' + f' \n' + f' ') + # small horizontal radius: only LIBERO's reset-time sampler reads it (the layout is overridden anyway) + return _wrap(name, g, B_HALF[2], 0.03) + + +def band_xml(name, line_rgba=(0.1, 0.55, 0.15, 1.0), fill_rgba=(0.75, 0.92, 0.75, 1.0)): + """Flat visual band across the table (no collisions): light fill + dark lines on its two long edges.""" + hx, hy = BAND_HALF_X, BAND_HALF_Y + parts = [((0, 0, 0.0004), (hx, hy, 0.0004), fill_rgba), + ((hx + LINE_W / 2, 0, 0.0010), (LINE_W / 2, hy, 0.0002), line_rgba), + ((-hx - LINE_W / 2, 0, 0.0010), (LINE_W / 2, hy, 0.0002), line_rgba)] + g = "\n".join(f' ' for p, sz, c in parts) + return _wrap(name, g, 0.0012, 0.03) + + +def d_range(mu): + """Band distances sampled for a given mu (m). Calibrated 2026-10-07 (LF 5 cm, board at x 0.05): the cube + moves d(0.6 m/s) ~ 0.33 * mu - 0.85 cm when yanked at the controller's top speed (mu 0.08 -> 1.8 cm, + 0.10 -> 2.3, 0.12 -> 3.1, 0.15 -> 4.3 cm) and >= 0.5 * mu at a pull ~0.05 m/s above the ride-along speed (0.08 -> 4.1 cm at + 0.35 m/s, 0.15 -> 7.6 cm at 0.45 m/s). The band centre is put ~1.5 cm beyond the top-speed displacement, so + the 'yank as fast as possible' prior always lands the cube short of the band.""" + return 0.33 * mu + 0.0065, 0.50 * mu + + +class ClothSkills(Skills): + """Skills that watch, every control step, whether the robot touches the cube (not allowed) and how each + move_to / gripper command moves the board and the cube (one pull only).""" + + def __init__(self, env, bias=None, recorder=None): + super().__init__(env, bias=bias, recorder=recorder) + m = env.sim.model + self._robot = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith(("gripper0_", "robot0_"))] + self._cube = envs.obj_geom_ids(env, CUBE) + self._board = envs.obj_geom_ids(env, BOARD) + self.touched_cube = False + self.cube0 = envs.obj_pos(env, CUBE) + self._ends = self._board_ends() + self._bstep = 0.0 # board motion in the previous control step + self._seg = None + self.segments = [] # one entry per move_to / set_gripper command + + def _board_ends(self): + """Both ends of the board's long axis (world xyz): their motion also catches turning and tilting.""" + b = envs.obj_pos(self.env, BOARD) + R = self.env.sim.data.body_xmat[envs.body_id(self.env, BOARD)].reshape(3, 3) + return np.stack([b - R[:, 0] * B_HALF[0], b + R[:, 0] * B_HALF[0]]) + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + if not self.touched_cube and envs.contacts_between(self.env, self._robot, self._cube): + self.touched_cube = True + ends = self._board_ends() + step = float(np.max(np.linalg.norm(ends - self._ends, axis=1))) + touch = envs.contacts_between(self.env, self._robot, self._board) + speed_up = step - self._bstep > ACC_EPS + self._ends, self._bstep = ends, step + s = self._seg + if s is not None: + s["path"] += step + s["touch"] += int(touch) + if touch or speed_up: + s["driven"] += step + + def _segment(self, kind, fn, *args, **kwargs): + c0, b0 = envs.obj_pos(self.env, CUBE), envs.obj_pos(self.env, BOARD) + self._seg = dict(kind=kind, step0=self.n_steps, path=0.0, driven=0.0, touch=0) + try: + rep = fn(*args, **kwargs) + finally: + s, self._seg = self._seg, None + c1, b1 = envs.obj_pos(self.env, CUBE), envs.obj_pos(self.env, BOARD) + s.update(steps=self.n_steps - s["step0"], board_dxy=(b1 - b0)[:2].round(4).tolist(), + cube_dxy=(c1 - c0)[:2].round(4).tolist(), cube_from_start=(c0 - self.cube0)[:2].round(4).tolist()) + self.segments.append(s) + return rep + + def move_to(self, target, *args, **kwargs): + return self._segment("move", super().move_to, target, *args, **kwargs) + + def set_gripper(self, close, steps=15): + return self._segment("close" if close else "open", super().set_gripper, close, steps) + + def pull_check(self): + """Pulls (move commands that drove the board >= PULL_EPS), where the cube was when the (first) pull started, + and the board motion driven by the other move commands.""" + moves = [s for s in self.segments if s["kind"] == "move"] + pulls = [s for s in moves if s["driven"] >= PULL_EPS] + stray = sum(s["driven"] for s in moves if s["driven"] < PULL_EPS) + pre = (float(np.linalg.norm(pulls[0]["cube_from_start"])) if pulls + else float(np.linalg.norm((envs.obj_pos(self.env, CUBE) - self.cube0)[:2]))) + return dict(n_pulls=len(pulls), pulls_cm=[round(100 * s["driven"], 1) for s in pulls], + pre_pull_cube_cm=round(100 * pre, 1), stray_cm=round(100 * stray, 2)) + + +@register_task +class TableclothPull(LFFTask): + name = "l5_tablecloth_pull" + level = "L5" + category = "dynamics_adaptation" + capabilities = ("Perceive", "Reason", "Utilize") + protocol = "cross" + instruction = ("Pull the wooden board out from under the red cube so that the cube ends up standing on the table " + "completely inside the green band. Touch only the board and its black handle, never the cube. " + "Only one pull is allowed per attempt: grasp the black handle, pull the board out with ONE move " + "command, then release it. Any other move that drags, pushes or nudges the board, before or after " + "the pull, counts as another pull.") + instruction_indirect = ("Pull the long brown plank out from under the small red block so that the block ends up " + "standing on the table completely inside the green stripe. Touch only the plank and its " + "black handle, never the block. Only one pull is allowed per attempt: grasp the black " + "handle, pull the plank out with ONE move command, then release it. Any other move that " + "drags, pushes or nudges the plank, before or after the pull, counts as another pull.") + + # ------------------------------------------------------------ scene + def make_bddl(self): + board = register_generated("LffClothBoard", board_xml("lff_cloth_board")) + cube = register_generated("LffClothCube", box_xml("lff_cloth_cube", (C_HALF,) * 3, (0.85, 0.15, 0.15, 1.0), + density=2300)) + band = register_generated("LffClothBand", band_xml("lff_cloth_band"), free=False) + objs = [(BOARD, board, "board_region", (0.09, -0.26, 0.11, -0.24)), + (CUBE, cube, "cube_region", (-0.21, 0.24, -0.19, 0.26))] + fixtures = [(BAND, band, "band_region", (-0.31, -0.01, -0.29, 0.01))] + return write_bddl(self.name, "pull the board out from under the cube", objs, fixtures=fixtures) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + mu = float(np.exp(rng.uniform(np.log(0.08), np.log(0.15)))) + lo, hi = d_range(mu) + d = float(rng.uniform(lo, max(lo, hi))) + return dict(seed=int(seed), board_xy=[float(rng.uniform(0.03, 0.08)), float(rng.uniform(-0.08, 0.08))], + mu=mu, band_d=d) + + def cube_start(self, inst): + bx, by = inst["board_xy"] + return np.array([bx + B_HALF[0] - LF, by]) + + def band_center(self, inst): + c = self.cube_start(inst) + return np.array([c[0] - inst["band_d"], c[1]]) + + def apply_instance(self, inst): + m = self.env.sim.model + for g in range(m.ngeom): # the band is a flat marker: no collisions + if (m.geom_id2name(g) or "").startswith(BAND + "_"): + m.geom_contype[g] = 0 + m.geom_conaffinity[g] = 0 + bx, by = inst["board_xy"] + envs.set_obj_pose(self.env, BOARD, [bx, by, envs.TABLE_Z + B_HALF[2] + 0.0005]) + c = self.cube_start(inst) + envs.set_obj_pose(self.env, CUBE, [c[0], c[1], envs.TABLE_Z + 2 * B_HALF[2] + C_HALF + 0.0005]) + envs.set_friction(self.env, BOARD, MU_BOARD, priority=1) + envs.set_friction(self.env, CUBE, inst["mu"], priority=2) # cube-board and cube-table contacts use mu + bid = m.body_name2id(self.env.fixtures_dict[BAND].root_body) + bc = self.band_center(inst) + m.body_pos[bid] = [bc[0], bc[1], envs.TABLE_Z + 0.0002] + m.body_quat[bid] = [1.0, 0.0, 0.0, 0.0] + + def reset_instance(self, inst, recorder=None): + from robosuite.utils.errors import RandomizationError + for _ in range(20): # LIBERO's reset-time placement sampler occasionally fails; the layout is overridden + try: + self.env.reset() + break + except RandomizationError: + continue + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.sk = ClothSkills(self.env, bias=self.skill_bias(inst), recorder=recorder) + return self.sk + + # ------------------------------------------------------------ outcome + def cube_on_board(self): + c = envs.obj_pos(self.env, CUBE) + b = envs.obj_pos(self.env, BOARD) + R = self.env.sim.data.body_xmat[envs.body_id(self.env, BOARD)].reshape(3, 3) + local = R.T @ (c - b) + return bool(abs(local[0]) < B_HALF[0] + 0.005 and abs(local[1]) < B_HALF[1] + 0.005 + and c[2] > envs.TABLE_Z + 2 * B_HALF[2] + C_HALF - 0.004) + + def outcome(self, inst): + sk = self.sk + envs.settle(self.env, 60) + c = envs.obj_pos(self.env, CUBE) + c0 = self.cube_start(inst) + bc = self.band_center(inst) + moved = float(c0[0] - c[0]) # towards the robot + off = c[:2] - bc # + x: cube forward (away from the robot) of the band's centre line + upright = envs.obj_upright_cos(self.env, CUBE) > 0.95 + on_board = self.cube_on_board() + on_table = c[2] < envs.TABLE_Z + C_HALF + 0.004 + in_band = bool(abs(off[0]) <= TOL and abs(off[1]) <= BAND_HALF_Y - C_HALF) + pc = sk.pull_check() + rule = [] + if pc["n_pulls"] > 1: + rule.append(f"The board was moved by {pc['n_pulls']} separate move commands " + f"({', '.join(f'{v:.1f}' for v in pc['pulls_cm'])} cm); only one pull is allowed.") + if pc["n_pulls"] and pc["pre_pull_cube_cm"] > 100 * PRE_TOL: + rule.append(f"When the pull started the cube had already been moved {pc['pre_pull_cube_cm']:.1f} cm by " + f"earlier small moves of the board; only one pull is allowed.") + if pc["stray_cm"] > 100 * STRAY_MAX: + rule.append(f"Besides the pull, other move commands moved the board {pc['stray_cm']:.1f} cm in total; " + f"only one pull is allowed.") + success = bool(in_band and on_table and upright and not on_board and not sk.touched_cube and not rule) + b_moved = float(np.linalg.norm(envs.obj_pos(self.env, BOARD)[:2] - np.asarray(inst["board_xy"]))) + out = dict(success=success, touched_cube=bool(sk.touched_cube), on_board=on_board, upright=bool(upright), + moved_toward_robot=round(moved, 4), band_offset_x=round(float(off[0]), 4), + err=round(float(moved - inst["band_d"]), 4), board_moved=round(b_moved, 4), + one_pull=not rule, **pc) + side = ("forward (+x, away from the robot)" if off[0] > 0 else "backward (-x, toward the robot)") + where = (f"its centre is {100 * abs(off[0]):.1f} cm {side} of the band's centre line" + if abs(off[0]) >= 0.0005 else "its centre is on the band's centre line") + if sk.touched_cube: + out["failure"] = "touched_cube" + detail = "The robot touched the cube, which is not allowed." + elif on_board and b_moved < 0.02: + out["failure"] = "board_not_moved" + detail = "The board was not pulled; the cube is still standing on it." + elif on_board: + out["failure"] = "rode_along" + detail = (f"The board was pulled {100 * b_moved:.0f} cm, but the cube rode along on it: it is still on the " + f"board and moved {100 * moved:.1f} cm toward the robot.") + elif not upright: + out["failure"] = "toppled" + detail = f"The board came out from under the cube, but the cube fell over; {where}." + elif in_band and on_table and upright: + out["failure"] = None + detail = (f"The board came out from under the cube and the cube is standing inside the green band; {where}. " + f"It moved {100 * moved:.1f} cm toward the robot.") + else: + out["failure"] = "missed_band" + detail = (f"The board came out from under the cube and the cube is standing on the table, but not " + f"completely inside the green band: {where}. It moved {100 * moved:.1f} cm toward the robot.") + if rule and not sk.touched_cube: + out["failure"] = "several_pulls" + detail = " ".join(rule) + " " + detail + out["detail"] = detail + out["detail_indirect"] = (detail.replace("board", "plank").replace("cube", "block") + .replace("green band", "green stripe").replace("band's", "stripe's")) + return out + + def feedback(self, inst, out, level="F2", indirect=False): + if indirect and level == "F2": + out = dict(out, detail=out.get("detail_indirect", out["detail"])) + return super().feedback(inst, out, level) + + # ------------------------------------------------------------ scripted execution (cross protocol) + def execute(self, inst, params): + """Grasp the handle (jaws across its 4 cm width) and pull the board STROKE m toward the robot at `speed`.""" + sk = self.sk + b = envs.obj_pos(self.env, BOARD) + hx, hy = b[0] - B_HALF[0] + H_HALF[0], b[1] + zg = envs.TABLE_Z + 2 * B_HALF[2] + H_HALF[2] + sk.set_gripper(False, steps=5) + sk.move_to([hx, hy, zg + 0.08], yaw=0.0) + sk.move_to([hx, hy, zg], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([hx - STROKE, hy, zg], speed=float(np.clip(params["speed"], V_MIN, V_MAX)), tol=0.01, + max_steps=300) + sk.set_gripper(False, steps=8) + sk.move_to([hx - STROKE, hy, zg + 0.10], speed=0.3) + + def default_params(self, inst): + """Prior: the classic tablecloth trick -- yank as fast as the arm can.""" + return dict(speed=0.60) + + def blind_params(self, inst, attempt, rng): + return dict(speed=float(np.clip(0.60 + rng.normal(0, 0.06), V_MIN, V_MAX))) + + def adapt_params(self, inst, history): + """Bracketing search on the pull speed with the signed displacement error (riding along = far too much + displacement). Faster -> less displacement.""" + pts = [] + for h in history: + o = h["outcome"] + if o.get("failure") in ("rode_along", "board_not_moved"): + e = 0.10 + elif o.get("failure") in ("touched_cube", "several_pulls"): + continue + else: + e = o["err"] + pts.append((h["params"]["speed"], e)) + hi_err = [p for p in pts if p[1] > 0] # moved too much -> needs a faster pull + lo_err = [p for p in pts if p[1] < 0] # moved too little -> needs a slower pull + if hi_err and lo_err: + (v0, e0) = max(hi_err, key=lambda p: p[0]) # fastest pull that still moved it too much + (v1, e1) = min(lo_err, key=lambda p: p[0]) # slowest pull that moved it too little + if e0 >= 0.05: # rode along: no usable slope -> bisect + v = 0.5 * (v0 + v1) + else: + v = v0 + (v1 - v0) * e0 / (e0 - e1) + elif hi_err: + v = max(p[0] for p in hi_err) * 1.25 + else: + v = min(p[0] for p in lo_err) * 0.8 + return dict(speed=float(np.clip(v, V_MIN, V_MAX))) + + def oracle_params(self, inst): + """Privileged: bisection on the speed by simulating pulls with the true mu.""" + if "_oracle_speed" in inst: + return dict(speed=inst["_oracle_speed"]) + lo, hi = V_MIN, V_MAX + best = None + for _ in range(10): + mid = 0.5 * (lo + hi) + self.reset_instance(inst) + self.execute(inst, dict(speed=mid)) + o = self.outcome(inst) + e = 0.10 if o["failure"] in ("rode_along", "board_not_moved") else o["err"] + if o["success"]: + best = (mid, e) + break + if best is None or abs(e) < abs(best[1]): + best = (mid, e) + if e > 0: + lo = mid + else: + hi = mid + inst["_oracle_speed"] = best[0] + self.reset_instance(inst) + return dict(speed=best[0]) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/lh_breakfast_service.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/lh_breakfast_service.py new file mode 100644 index 0000000000000000000000000000000000000000..76f751d6bb88f22613915c975ca99bba920e21ea --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/lh_breakfast_service.py @@ -0,0 +1,546 @@ +"""Breakfast revision 2: food meshes, hinged milk pourer, L1/L3/L4 recovery. + +Rigid bodies use MuJoCo contacts. Milk is an explicitly reduced-order, volume- +conserving discharge / ballistic parcel model, NOT Navier-Stokes fluid simulation. +Only the physical carton angle controls discharge. No policy/stage success gates. +An upright butter stick physically obstructs the lid. Lay it flat to recover. +There is no latch fatigue, artificial opening torque, or forced orientation. +""" +from pathlib import Path +import copy +import xml.etree.ElementTree as ET +import numpy as np +import robosuite +import libero.libero as libero_pkg + +from .. import envs +from ..bddl import write_bddl +from ..objects import register_generated, _wrap, _fmt +from ..skills import Skills +from ..task_base import register_task +from .lh_pantry_relatch import (PantryRelatch, RelatchSkills, BREAD_HALF, + BOX, BOX_MODEL, FLOOR_T, WALL_H, BOX_D, box_lid_xml) + +LIB_ASSETS = Path(libero_pkg.__file__).parent / 'assets' +RS_ASSETS = Path(robosuite.__file__).parent / 'models/assets' +BUTTER_HALF = (.010,.020,.040) # standing: 8 cm tall; lying: 2 cm tall, fits the 2.6 cm cavity + + +def food_xml(kind, half): + """Reuse installed textured visual meshes, normalized to the tested food collision hull.""" + if kind == 'bread': + source = RS_ASSETS / 'objects/bread.xml' + meshpath = RS_ASSETS / 'objects/meshes/bread.stl' + data = meshpath.read_bytes() + n = int.from_bytes(data[80:84], 'little') + dtype = np.dtype([('normal','') + xml = ET.fromstring(_wrap('breakfast_'+kind, hull+ET.tostring(visual,encoding='unicode'),half[2],.05)) + xml.insert(0,asset) + return ET.tostring(xml,encoding='unicode') + + +def milk_station_xml(): + source = LIB_ASSETS/'stable_hope_objects/milk/milk.xml' + root = ET.parse(source).getroot() + asset = root.find('asset') + for el in asset: + if el.get('file'): el.set('file', str(source.parent/el.get('file'))) + carton = copy.deepcopy(root.find('worldbody/body/body')) + carton.set('name','carton_visual'); carton.set('quat','.5 .5 .5 .5') + # A carton held in a tabletop tipping cradle. The hinge is physical, unactuated. + parts = ''' + + + + + + + + + + + + ''' + xml = ET.fromstring(_wrap('breakfast_milk_station',parts,0,.08)) + xml.insert(0,asset) + xml.find(".//body[@name='tilting_carton']").append(carton) + for parent in xml.iter('body'): + for geom in list(parent.findall('geom')): + if geom.get('group') is None: + geom.set('group','0') + vis=copy.deepcopy(geom);vis.set('group','1');vis.set('contype','0');vis.set('conaffinity','0') + vis.attrib.pop('name',None);vis.set('mass','0');parent.append(vis) + return ET.tostring(xml,encoding='unicode') + + +def liquid_visual_xml(): + geoms = [''] + for i in range(80): + geoms.append(f'') + geoms.append('') + return _wrap('breakfast_liquid', ''.join(geoms),0,.001) + + +def fixed_cup_xml(): + source=LIB_ASSETS/'turbosquid_objects/porcelain_mug/porcelain_mug.xml' + root=ET.parse(source).getroot() + for el in root.find('asset'): + if el.get('file'):el.set('file',str(source.parent/el.get('file'))) + return ET.tostring(root,encoding='unicode') + + +def serving_plate_xml(): + source=LIB_ASSETS/'stable_scanned_objects/plate/plate.xml' + root=ET.parse(source).getroot();scale=1.5 + for el in root.find('asset'): + if el.get('file'):el.set('file',str(source.parent/el.get('file'))) + if el.tag=='mesh':el.set('scale',_fmt(np.fromstring(el.get('scale'),sep=' ')*scale)) + for el in root.iter(): + if el.tag in ('geom','site'): + if el.get('pos'):el.set('pos',_fmt(np.fromstring(el.get('pos'),sep=' ')*scale)) + if el.get('size'):el.set('size',_fmt(np.fromstring(el.get('size'),sep=' ')*scale)) + return ET.tostring(root,encoding='unicode') + + +class BreakfastSkills(RelatchSkills): + def __init__(self,env,task,recorder=None): + super().__init__(env,task,recorder) + self.bias=np.asarray(task.inst['bias'] if task.inst['mechanisms']['L1'] else [0,0,0],float) + self.correction=np.zeros(3) + self.pour_latched=False + self.pour_rad=0. + self.pour_y=0. + + def move_to(self,target,*args,**kwargs): + return super().move_to(np.asarray(target)-self.correction,*args,**kwargs) + + def set_gripper(self,close,steps=15): + rep=super().set_gripper(close,steps) + if close and self.task.holding_pour_knob(): + self.pour_latched=True + e=self.eef_pos(); h=self.task.pour_pivot() + self.pour_rad=float(np.linalg.norm((e-h)[[0,2]]));self.pour_y=float(e[1]) + elif not close:self.pour_latched=False + return rep + + def _act(self,dpos,drot,grip): + if self.pour_latched and self.task.inst['mechanisms']['L3']: + e=self.eef_pos(); k=self.task.pour_knob() + if grip<0 or np.linalg.norm(e-k)>.04:self.pour_latched=False + else: + h=self.task.pour_pivot();r=(e-h)[[0,2]];rn=max(np.linalg.norm(r),1e-6) + t=np.array([-r[1],r[0]])/rn + s=np.clip(np.asarray(dpos)[[0,2]]@t,-.008,.008) + corr=(self.pour_rad-rn)*r/rn + dpos=np.array([s*t[0]+corr[0], self.pour_y-e[1],s*t[1]+corr[1]]) + super()._act(dpos,drot,grip) + + +@register_task +class BreakfastService(PantryRelatch): + name='lh_breakfast_service' + level='L1' + category='system_identification' + failure_causes=('L1','L3','L4') + failure_types=failure_causes + agent_max_steps=360 + instruction=('Prepare breakfast: put the bread from the wooden box onto the plate and close the box; ' + 'pour 80 to 160 mL of milk into the cup using the milk carton in its cradle. ' + 'Then store the butter inside the box and leave its lid shut. Finish with the carton upright, ' + 'bread on the plate, cup upright, and gripper open and clear. Spill at most 15 mL. ' + 'The cradle can be tipped with its gold side handle using ordinary gripper motions.') + instruction_indirect=instruction + agent_object_names=['bread','butter','plate','cup','milk carton','gold cradle handle','wooden box','lid knob'] + + def make_bddl(self): + boxroot=ET.fromstring(box_lid_xml(BOX_MODEL)) + inertial=boxroot.find('.//inertial');ratio=.08/float(inertial.get('mass')) + inertial.set('mass','.08');inertial.set('diaginertia',_fmt(np.fromstring(inertial.get('diaginertia'),sep=' ')*ratio)) + box=register_generated('LffBreakfastBox',ET.tostring(boxroot,encoding='unicode'),free=False) + bread=register_generated('LffBreakfastBread',food_xml('bread',BREAD_HALF)) + butter=register_generated('LffBreakfastButter',food_xml('butter',BUTTER_HALF)) + milk=register_generated('LffBreakfastMilk',milk_station_xml(),free=False) + liquid=register_generated('LffBreakfastLiquid',liquid_visual_xml(),free=False) + cup=register_generated('LffBreakfastCup',fixed_cup_xml(),free=False) + plate=register_generated('LffBreakfastPlate',serving_plate_xml()) + objs=[('bread_1',bread,'bread_region',(-.31,-.01,-.29,.01)), + ('butter_1',butter,'butter_region',(-.31,.24,-.29,.26)), + ('plate_1',plate,'plate_region',(.02,-.26,.04,-.24))] + fx=[(BOX,box,'box_region',(-.18,-.12,-.16,-.10)), + ('milk_1',milk,'milk_region',(.24,-.01,.26,.01)), + ('liquid_1',liquid,'liquid_region',(.34,-.34,.35,-.33)), + ('cup_1',cup,'cup_region',(.14,.26,.16,.28))] + return write_bddl(self.name,self.instruction.replace(';',','),objs,fx) + + def __init__(self,cam_res=None): + super().__init__(cam_res) + m=self.env.sim.model + self.milk_bid=m.body_name2id(self.env.fixtures_dict['milk_1'].root_body) + self.pour_jid=m.joint_name2id('milk_1_pour_hinge') + self.slide_jid=m.joint_name2id('milk_1_pull_slide');self.slide_qa=int(m.jnt_qposadr[self.slide_jid]) + self.pour_qa=int(m.jnt_qposadr[self.pour_jid]);self.pour_dof=int(m.jnt_dofadr[self.pour_jid]) + self.pour_gid=m.geom_name2id('milk_1_pour_knob') + self.nozzle_sid=m.site_name2id('milk_1_nozzle') + self.liquid_bid=m.body_name2id(self.env.fixtures_dict['liquid_1'].root_body) + self.cup_bid=m.body_name2id(self.env.fixtures_dict['cup_1'].root_body) + self.drop_gids=[m.geom_name2id('liquid_1_drop_'+str(i)) for i in range(80)] + self.surface_gid=m.geom_name2id('liquid_1_milk_surface');self.spill_gid=m.geom_name2id('liquid_1_spill') + self.liquid=None;self.phase_hook=None + + def sample_instance(self,seed): + inst=super().sample_instance(seed) + rng=np.random.default_rng(seed) + inst.update(box_xy=[-.20,-.10],plate_xy=[-.09,-.32],butter_xy=[-.36,-.32], + milk_xy=[-.14,.24],cup_xy=[-.075,.24], + bias=[0,float(rng.choice([-1,1])*.10),0], + mechanisms={'L1':True,'L3':True,'L4':True},flow_ml_s=float(rng.uniform(42,48))) + return inst + + def apply_instance(self,inst): + super().apply_instance(inst) + m,d=self.env.sim.model,self.env.sim.data + half_z=BUTTER_HALF[2] if inst['mechanisms']['L4'] else BUTTER_HALF[0] + quat=[1,0,0,0] if inst['mechanisms']['L4'] else [np.sqrt(.5),0,np.sqrt(.5),0] + envs.set_obj_pose(self.env,'butter_1',[*inst['butter_xy'],envs.TABLE_Z+half_z+.001],quat_wxyz=quat) + self.drift_active=False;self.active_latch=0. + envs.scale_mass(self.env,'plate_1',.4) + envs.set_friction(self.env,'plate_1',.8) + m.body_pos[self.milk_bid]=[*inst['milk_xy'],envs.TABLE_Z] + m.body_quat[self.milk_bid]=[1,0,0,0] + m.body_pos[self.liquid_bid]=[0,0,0];m.body_quat[self.liquid_bid]=[1,0,0,0] + d.qpos[self.pour_qa]=0;d.qvel[self.pour_dof]=0 + d.qpos[self.slide_qa]=0 + m.jnt_range[self.slide_jid]=[-.00001,.00001] if inst['mechanisms']['L3'] else [-.11,.01] + m.body_pos[self.cup_bid]=[*inst['cup_xy'],envs.TABLE_Z-.0024] + m.body_quat[self.cup_bid]=[1,0,0,0] + for gid in self.drop_gids+[self.surface_gid,self.spill_gid]:m.geom_rgba[gid,3]=0 + self.liquid=dict(reservoir=300.,cup=0.,spill=0.,parcels=[],emitted=0.,spill_xy=None) + self.trace=[] + + def reset_instance(self,inst,recorder=None): + self.mon=None + np.random.seed(int(inst['seed'])) + self.env.reset();self.apply_instance(inst);self.env.sim.forward();envs.settle(self.env,10) + self.mon=dict(events=[],lid_open_max=0.,armed=False) + self.sk=BreakfastSkills(self.env,self,recorder) + self.traps={k:False for k in self.failure_causes} + self.recovered={k:False for k in self.failure_causes} + self.initial_pour_pivot=self.pour_pivot().copy() + return self.sk + + def _register_close(self,seated): + self.closes_done+=1;self.active_latch=0.;self.drift_active=False + self.mon['events'].append(dict(ev='closed',n=self.closes_done,mechanism='ordinary rigid-body hinge')) + + def _bracket(self): + # Disable the predecessor's modeled spring/catch completely, at every physics substep. + self.env.sim.data.qfrc_applied[self.dof]=0. + + def butter_corners(self): + p=envs.obj_pos(self.env,'butter_1') + R=self.env.sim.data.body_xmat[envs.body_id(self.env,'butter_1')].reshape(3,3) + return np.array([p+R@(np.array([a,b,c])*BUTTER_HALF) for a in (-1,1) for b in (-1,1) for c in (-1,1)]) + + def butter_height(self): + c=self.butter_corners();return float(np.ptp(c[:,2])) + + def butter_in_box(self): + from .lh_lid_box import IN_X,IN_Y + c=self.butter_corners();b=np.asarray(self.inst['box_xy']) + inside=np.all(np.abs(c[:,:2]-b)<[IN_X+.001,IN_Y+.001]) + return bool(inside and c[:,2].max()envs.TABLE_Z+FLOOR_T-.002 and not self.held('butter_1')) + + def butter_lid_contact(self): + m=self.env.sim.model + lid=m.geom_name2id('box_1_'+BOX_MODEL+'_lid') + return envs.contacts_between(self.env,envs.obj_geom_ids(self.env,'butter_1'),[lid]) + + def pick_place(self,name,dest_xy,z_rel,z_carry=.18,dest_yaw=0.): + if name!='butter_1':return super().pick_place(name,dest_xy,z_rel,z_carry,dest_yaw) + s=self.sk;p=envs.obj_pos(self.env,name).copy() + tall=self.butter_height()>.045 + grasp=p+np.array([0,0,.025 if tall else 0.]) + s.set_gripper(False,8);s.move_to([p[0],p[1],1.12],yaw=0) + s.move_to(grasp,speed=.10,tol=.002,max_steps=120);s.set_gripper(True,20) + s.move_to([p[0],p[1],1.12],speed=.15) + if not self.held(name):s.set_gripper(False,8);return False + offset=envs.obj_pos(self.env,name)-s.eef_pos() + target=np.array([*dest_xy,envs.TABLE_Z+z_rel])-offset + s.move_to([target[0],target[1],1.12],yaw=dest_yaw) + s.move_to(target,speed=.10,tol=.003,max_steps=120) + s.set_gripper(False,12);s.move_to([target[0],target[1],1.14]);s.hold(10) + return True + + def put_butter(self): + # Place the standing stick near the front wall; lay-flat placement uses the box centre. + standing=self.butter_height()>.045 + target=np.array(self.inst['box_xy'])+([-0.030,0] if standing else [0,0]) + return self.pick_place('butter_1',target,FLOOR_T+self.butter_height()/2+.003,z_carry=.18) + + def lay_butter_flat(self): + """Extract, tip on the table through contact, then pick the horizontal stick. No pose writes.""" + s=self.sk;xy=np.asarray(self.inst['butter_xy']) + self.label('L4 recovery: take the upright stick out of the box') + if not self.pick_place('butter_1',xy,self.butter_height()/2+.003,z_carry=.18):return False + p=envs.obj_pos(self.env,'butter_1').copy() + self.label('Recovery: tip the butter stick onto its broad side') + s.set_gripper(True,8) + s.move_to([p[0]-.055,p[1],1.07],yaw=0) + s.move_to([p[0]-.055,p[1],envs.TABLE_Z+.055],speed=.10) + s.move_to([p[0]+.025,p[1],envs.TABLE_Z+.055],speed=.06) + s.move_to([p[0]+.025,p[1],1.10],speed=.12);s.set_gripper(False,8);s.hold(60) + self.label('Recovery: the butter stick is now lying flat on the table') + return self.butter_height()<.029 + + def pour_pivot(self): + return np.array([self.inst['milk_xy'][0]+self.env.sim.data.qpos[self.slide_qa],self.inst['milk_xy'][1],envs.TABLE_Z+.21]) + def pour_knob(self):return self.env.sim.data.geom_xpos[self.pour_gid].copy() + def pour_angle(self):return float(self.env.sim.data.qpos[self.pour_qa]) + def holding_pour_knob(self): + g=self.env.robots[0].gripper + return bool(self.env._check_grasp(gripper=[g.important_geoms['left_finger'],g.important_geoms['right_finger']], + object_geoms=['milk_1_pour_knob','milk_1_pour_bar'])) + + def monitor_step(self): + super().monitor_step() + if getattr(self,'liquid',None) is None or self.mon is None:return + if self.pour_angle()0: + # small outward speed along the spout, transformed by the actual hinge angle + vel=np.array([np.cos(a),0,-np.sin(a)])*.04 + q['parcels'].append(dict(p=origin.copy(),v=vel,ml=dv)) + q['reservoir']-=dv;q['emitted']+=dv + cup_origin=d.body_xpos[self.cup_bid] + cup_rot=d.body_xmat[self.cup_bid].reshape(3,3) + cup=cup_origin+cup_rot@np.array([.015,-.0016,.10]);top=cup[2] + keep=[] + for drop in q['parcels']: + p=drop['p'];v=drop['v'];end=p+v*dt+np.array([0,0,-.5*9.81*dt*dt]) + caught=False + if p[2]>=top>end[2]: + hit=p+(end-p)*(p[2]-top)/(p[2]-end[2]) + if np.linalg.norm(hit[:2]-cup[:2])<.029 and self.cup_upright(): + q['cup']+=drop['ml'];caught=True + excess=max(0.,q['cup']-180.) + if excess: + q['cup']-=excess;q['spill']+=excess;q['spill_xy']=cup[:2].tolist() + if not caught and end[2]<=envs.TABLE_Z+.002: + q['spill']+=drop['ml'];q['spill_xy']=end[:2].tolist();caught=True + if not caught: + drop['p']=end;drop['v']=v+np.array([0,0,-9.81*dt]);keep.append(drop) + q['parcels']=keep + if not render_update:return + for i,gid in enumerate(self.drop_gids): + if i.1) + if q['spill']>.1: + m.geom_pos[self.spill_gid]=[*q['spill_xy'],envs.TABLE_Z+.002] + m.geom_size[self.spill_gid,0]=min(.08,.009*np.sqrt(q['spill'])) + m.geom_rgba[self.spill_gid,3]=1 + self.env.sim.forward() + + def cup_upright(self): + # Native mug uses world Z as its vertical in the loaded LIBERO pose. + return bool(self.env.sim.data.body_xmat[self.cup_bid].reshape(3,3)[2,2]>.94) + + def label(self,text): + state=dict(text=text,step=self.sk.n_steps,lid_deg=self.lid_deg(), + pour_deg=float(np.degrees(self.pour_angle())),cup_ml=self.liquid['cup'],spill_ml=self.liquid['spill'], + butter_height_cm=100*self.butter_height(),butter_lid_contact=bool(self.butter_lid_contact()), + lid_applied_torque=float(self.env.sim.data.qfrc_applied[self.dof])) + self.trace.append(state) + if self.phase_hook:self.phase_hook(text,state) + + def calibration_probe(self): + # Attempt the loose butter first, away from fixture walls; fixed bias is present for ALL motions. + p=envs.obj_pos(self.env,'butter_1').copy();s=self.sk + s.set_gripper(False,8);s.move_to([p[0],p[1],envs.TABLE_Z+.14],yaw=0,tol=.0005,max_steps=120) + observed=s.eef_pos()-np.array([p[0],p[1],envs.TABLE_Z+.14]) + s.move_to(p,tol=.002,max_steps=100) + s.set_gripper(True,15);s.move_to([p[0],p[1],envs.TABLE_Z+.15]) + failed=not s.holding('butter_1') + self.traps['L1']=bool(failed) + self.label('L1: grasp missed the butter' if failed else 'Calibration grasp succeeded') + s.set_gripper(False,8) + return observed + + def direct_carton_lift(self): + s=self.sk;k=self.pour_knob();start=k.copy() + s.set_gripper(False,8) + s.move_to(k+[0,0,.10],yaw=0) + s.move_to(k,speed=.12,max_steps=100) + s.set_gripper(True,20) + held_before=self.holding_pour_knob() + # Pulling along the radius cannot translate a hinged cradle. Same low-level interface as agents. + s.move_to(k+[-.07,0,0],speed=.08,max_steps=30) + lift=float(np.linalg.norm(self.pour_knob()-start)) + self.pull_probe=dict(held_before=held_before,held_after=self.holding_pour_knob(),displacement_m=lift, + angle_deg=float(np.degrees(self.pour_angle()))) + self.traps['L3']=bool(held_before and lift<.01 and self.liquid['cup']<1) + self.label('L3: straight pull failed; the cradle only rotates') + s.set_gripper(False,10);s.move_to(s.eef_pos()+[0,0,.10]) + return lift + + def tip_carton(self,target_ml=110.): + s=self.sk;k=self.pour_knob();h=self.pour_pivot() + s.set_gripper(False,8);s.move_to(k+[0,0,.09],yaw=0) + s.move_to(k,tol=.002,max_steps=120);s.set_gripper(True,20) + self.label('Recovery: grasp the gold handle and tip the carton') + if not s.pour_latched:return False + for deg in range(10,81,10): + a=np.radians(deg) + target=h+[-.09*np.cos(a),-.065,.09*np.sin(a)] + s.move_to(target,speed=.06,max_steps=90,tol=.003) + self.label(f'Tipping handle: target {deg}, actual {np.degrees(self.pour_angle()):.1f}, held {s.pour_latched}') + self.label('Pouring milk into the cup') + for _ in range(120): + if self.liquid['cup']+sum(p['ml'] for p in self.liquid['parcels'])>=target_ml:break + s.hold(1) + for deg in range(70,-1,-10): + a=np.radians(deg) + s.move_to(h+[-.09*np.cos(a),-.065,.09*np.sin(a)],speed=.10,max_steps=90,tol=.003) + self.label(f'Returning handle: target {deg}, actual {np.degrees(self.pour_angle()):.1f}, held {s.pour_latched}') + s.set_gripper(False,10);e=s.eef_pos();s.move_to(e+[0,0,.12]);s.hold(15) + self.recovered['L3']=bool(80<=self.liquid['cup']<=160 and self.liquid['spill']<=15) + self.label('Milk poured; carton returned upright') + return self.recovered['L3'] + + def bread_on_plate(self): + p=envs.obj_pos(self.env,'bread_1');plate=envs.obj_pos(self.env,'plate_1') + return bool(np.linalg.norm(p[:2]-plate[:2])<.05 and p[2].045: + if not self.lay_butter_flat():self.label('Butter reorientation failed');return + if not self.put_butter():self.label('Butter storage failed');return + self.label('Upright butter stick: too tall for the shallow box' if self.butter_height()>.045 + else 'Butter stick laid flat inside the box') + self.close_lid(False) + if mode not in ('oracle','naive','blind'): + self.label('Check whether the upright butter stick fits beneath the lid') + s.hold(80) + self.traps['L4']=bool(self.lid_deg()>5 and self.butter_lid_contact()) + self.label('L4: upright butter stick physically blocks the lid' if self.traps['L4'] else 'No lid obstruction detected') + if not self.lid_closed(): + self.open_lid() + if not self.lay_butter_flat():self.label('Butter reorientation failed');return + if not self.put_butter():self.label('Horizontal butter placement failed');return + self.label('Butter stick laid flat inside the box') + self.close_lid(False) + s.hold(60) + self.recovered['L4']=bool(self.lid_closed() and self.butter_in_box()) + self.label('L4 recovery: butter laid flat; the lid closes normally') + if not self.bread_on_plate(): + self.label('Final check: restore the bread disturbed during cleanup') + self.take_bread() + s.set_gripper(False,8);s.move_to([-.35,-.30,1.20]);s.hold(15) + + def default_params(self,inst):return {'mode':'naive'} + def oracle_params(self,inst):return {'mode':'oracle'} + def adapt_params(self,inst,history):return {'mode':'adaptive'} + def run_scripted(self,kind,inst,k=None,seed=0,on_attempt=None): + rng=np.random.default_rng(seed);hist=[] + for attempt in range((k or 5) if kind=='blind' else 1): + self.reset_instance(inst) + if kind=='blind':self.sk.correction[:2]=rng.uniform(-.012,.012,2) + self.execute(inst,{'mode':kind}) + out=self.outcome(inst);hist.append(dict(attempt=attempt+1,params={'mode':kind},outcome=out)) + if on_attempt:on_attempt(attempt,hist[-1]['params'],out) + if out['success']:break + return hist + + def outcome(self,inst): + out=super().outcome(inst);q=self.liquid + inflight=sum(p['ml'] for p in q['parcels']) + out.update(cup_ml=round(q['cup'],3),spill_ml=round(q['spill'],3),reservoir_ml=round(q['reservoir'],3), + inflight_ml=round(inflight,3),conservation_error_ml=abs(300-q['reservoir']-q['cup']-q['spill']-inflight), + pour_deg=round(float(np.degrees(self.pour_angle())),2),traps=dict(self.traps),recovered=dict(self.recovered)) + out['stages'].update(milk_served=bool(80<=q['cup']<=160),spill_ok=bool(q['spill']<=15), + carton_upright=bool(abs(self.pour_angle())<.15),cup_upright=self.cup_upright(), + gripper_open=bool(self.sk.grip<0), + gripper_clear=bool(min(np.linalg.norm(self.sk.eef_pos()-envs.obj_pos(self.env,n)) + for n in ('bread_1','butter_1'))>.06), + carton_static=bool(abs(self.env.sim.data.qvel[self.pour_dof])<.1)) + out['success']=bool(out['success'] and all(out['stages'].values())) + if not out['success'] and out['failure'] is None: + out['failure']=next((k for k,v in out['stages'].items() if not v),'not_static') + out['detail']=(f"Bread on plate: {out['stages']['bread_on_plate']}; butter fully below the box rim: " + f"{out['stages']['butter_in_box']}; lid angle: {self.lid_deg():.1f} degrees. " + f"Milk in cup: {q['cup']:.1f} mL; spilled: {q['spill']:.1f} mL. " + f"Butter height: {100*self.butter_height():.1f} cm.") + if self.butter_lid_contact() and not self.lid_closed():out['detail']+=' The upright butter stick is touching and obstructing the lid.' + out.update(geometry_version=2,butter_height_cm=round(100*self.butter_height(),3), + butter_lid_contact=bool(self.butter_lid_contact()),lid_applied_torque=float(self.env.sim.data.qfrc_applied[self.dof])) + return out diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/lh_shelf_droop.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/lh_shelf_droop.py new file mode 100644 index 0000000000000000000000000000000000000000..d12da555297b5861b08e66421b794b164dd5281e --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/lh_shelf_droop.py @@ -0,0 +1,1009 @@ +"""LH lh_shelf_droop (2026-10-16; v2 the same day): put four jars on a wall shelf. The shelf board hangs on a loose, +spring-loaded fold-down bracket with a weak catch: it stays level as long as the moment of its load about the hinge at +the wall is below the bracket's preload; once the load exceeds it the catch slips and the board folds down to its stop +within about a second, and the jars on it slide off its free edge onto the table, where they lie on their sides. +Jars set down in the middle of the board's depth -- where a careful agent puts them -- push the moment over the preload +with the third jar: a median 0.4 s (90 % within 0.8 s) after that jar is down the board is past 8 deg, and the first +jar slides off a median 1.5 s (1-3 s) after it, while the arm lifts away. The same four jars standing near the wall +(centres up to ~6 cm from it) stay under the preload. Unloaded, the board springs back level. + +Family: long-horizon self-damage ("state_restoration"): a later stage (the third placement) undoes the earlier ones, a +moment after it was done, once the gripper has let go. Within an attempt the agent has to notice the fallen jars, stand +them up again (by their knobs) and put them back -- near the wall, or they slide off again; across attempts it has to +load the shelf near the wall. R4: "I put them down badly / dropped them too hard / my arm knocked them" vs "the shelf +gives way under a load far from the wall". + +v1 -> v2 (measured, scratchpad risk sweeps): v1 had a preloaded spring without a catch (preload 0.45-0.49 N m, 0.6 N m/rad, +damping 2.6-3.4, a slow first-order droop). Jars placed with their centres 6-7 cm from the wall overloaded it only with +the fourth jar, and the board drooped (or the jars slid off) only during the final settle, after `finish` -- 15 of 74 +failing scripted attempts (20 %) showed nothing before finish; 4 jars 6 cm from the wall failed in 9 / 9 seeds. v2 raises +the preload (4 jars up to ~6 cm from the wall hold) and adds the catch + a soft spring + light damping, so every overload +folds the board down within a second, before the agent's next look. + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a wall panel (2.5 cm thick, 34 cm + 4 cm long) along x on the robot's right or left (|y| of its face 25-27 cm, centre + x in [-0.17, -0.12]), rising 4.5 cm above the shelf board; + * the shelf board: 34 cm (along the wall) x 20 cm (deep) x 1.2 cm, light wood, top 11 cm above the table, hinged at + the wall face (axis along x at mid-thickness); hard stop at 25 deg of droop. The agentview camera (behind the table, + +x, looking at the robot) sees the board from its end, so the droop is an in-image rotation of the slab; + * four square jars (red, green, blue, yellow; body 5 x 5 x 6 cm, white lid, a 2.2 cm dark ball knob on a 1.2 cm stem; + 10.2 cm tall, 0.24-0.26 kg, centre of mass 2.6 cm up) standing in a row on the table on the other side (|y| 13-17 + cm), 9 cm apart, in random order. + +Hidden variable: the bracket. "loose" (14 of every 20 consecutive seeds): preload 0.62-0.68 N m; "stiff" (6 of 20): +preload 2.5 N m (no placement on the board reaches it). Both look identical. The preload is a spring (0.25 N m/rad +beyond the preload) plus a catch of 0.12 N m that fades out over the first 3 deg of droop; damping 0.45-0.60 N m s/rad. +As the board droops the jars' centres of mass (3.2 cm above the hinge axis) move outwards (+0.08 N m/rad per jar), so +with two or more jars on it nothing stops a board whose catch has slipped before its 25 deg stop. Jar-on-board friction +0.27-0.33 per jar (they slide at ~14.5 deg at 0.30 in MuJoCo's soft contacts). +Moments (jar weight 2.45 N x lever arm of its centre of mass): four jars against the wall (centres 3.5 cm from the +hinge) 0.34 N m; four at 6 cm 0.59 (holds); four at 7 cm 0.69 (over); in the middle of the depth (10.4 cm) one jar 0.25, +two 0.51 (holds), three 0.76 (over). + +Repair: fallen jars lie on the table in front of the board's free edge. Held by the knob (ball, torsional friction +0.0005, condim 4) a lying jar turns between the fingers and hangs straight down (like lh_bystander's bottle cap); the +instruction says so. Put back near the wall, the board stays level. + +Success (final-state judge after a settle of at least 15 s of simulated time with the arm holding still -- longer if +the board is still moving -- so that finishing right after the last placement does not beat the bracket): every jar +stands upright on the board (its bottom on the board's top, within its outline, axis within 10 deg of the board's +normal), not held; the board within 15 deg of level (a board that has folded down holds no standing jar anyway), +touched by nothing but the jars (closes "prop the board" loopholes), the gripper not touching a jar or the board, the +scene static. + +Per-step monitor (server log only; F1 gives the agent success / failure): stage achieved / lost (cause: slid_off, +robot, jar:, picked_up, other) / restored per jar; board sag_start (> 1.5 deg), sag (> 8 deg = trap_fired) and +sag_end, each with the time since the placement that pushed the moment over the preload and the moment itself; +jar_fell (with the time since its own placement and since the sag started). outcome() also reports what the agent's +last images showed at `finish` (board angle, jars already off the board). + +Protocol: cross (reset to the same instance before every attempt), k = 3. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +TZ = envs.TABLE_Z +G = 9.81 +DT = 0.05 # control period + +# ---------------------------------------------------------------- jars (square glass jars with a ball knob on the lid) +COLOURS = ["red", "green", "blue", "yellow"] +JARS = [f"jar_{c}_1" for c in COLOURS] +GLASS_RGBA = {"red": (0.78, 0.20, 0.16, 1.0), "green": (0.20, 0.58, 0.28, 1.0), "blue": (0.20, 0.38, 0.80, 1.0), + "yellow": (0.90, 0.72, 0.15, 1.0)} +LID_RGBA = (0.93, 0.93, 0.91, 1.0) +KNOB_RGBA = (0.22, 0.22, 0.24, 1.0) +JB = 0.025 # half width of the square body (5 x 5 cm) +BODY_H = 0.060 +LID_H, LID_B = 0.008, 0.026 # lid height, half width +NECK_R, NECK_H = 0.006, 0.012 +KNOB_R = 0.011 +JAR_H = BODY_H + LID_H + NECK_H + 2 * KNOB_R # 0.102 +KNOB_Z = BODY_H + LID_H + NECK_H + KNOB_R # knob centre above the jar's bottom (0.091) +JAR_COM = 0.026 # centre of mass above the bottom (a filled jar) +JAR_MASS = (0.24, 0.26) +JAR_MU = (0.27, 0.33) # jar body friction (per jar); the board's own is lower, so this one applies on the board +LID_MU = 0.8 +KNOB_MU_T = 0.0005 # torsional friction of the knob (condim 4): a jar held by its knob swings down and hangs straight +JAR_ROT_DAMP = 0.004 # free-joint angular damping (air drag; damps the swing of a jar hanging from its knob) + +# ---------------------------------------------------------------- shelf (fixture: wall panel + hinged board) +SHELF = "shelf_1" +SHELF_MODEL = "lff_lhs_shelf" +BOARD_L = 0.34 # along the wall (world x) +BOARD_D = 0.20 # depth, from the wall to the free edge +BOARD_T = 0.012 +BOARD_TOP = 0.110 # top surface above the table when level +PANEL_T = 0.025 +LIP = 0.045 # the wall rises this far above the board's top +BOARD_MASS = 0.30 +BOARD_MU = 0.10 # (max rule: the jars' 0.27-0.33 applies) +GAP = 0.004 # board edge to the wall face (the board's lower corner swings towards the wall when it droops) +WOOD = (0.72, 0.55, 0.36, 1.0) +WALL_RGBA = (0.86, 0.86, 0.84, 1.0) +DROOP_MAX = np.radians(25.0) # hard stop of the hinge (at 28 deg the free edge would touch the table) +K_SPRING = 0.25 # N m / rad: the bracket's spring beyond the preload (soft: once the catch slips the board folds down) +LATCH = 0.12 # N m: part of the preload held by the bracket's catch, released over the first LATCH_TH of droop +LATCH_TH = np.radians(3.0) +PRELOAD_LOOSE = (0.62, 0.68) # N m (spring + catch at level) +PRELOAD_STIFF = 2.5 +DAMPING = (0.45, 0.60) # N m s / rad +P_LOOSE = 0.70 # 14 of every 20 consecutive seeds +WALL_Y = (0.25, 0.27) # |y| of the wall face +SHELF_X = (-0.17, -0.12) # centre of the board along the wall +SLOT_U = (-0.12, -0.04, 0.04, 0.12) # slot positions along the board (scripted policies) +SUP_Y = (0.13, 0.17) # |y| of the supply row (other side of the table) +SUP_U = (-0.135, -0.045, 0.045, 0.135) + +# predicates / monitor +TILT_OK = np.radians(10.0) # jar axis vs the board's normal +BOARD_OK = np.radians(15.0) # final judge: the board within 15 deg of level (jars slide off at ~13-16 deg) +SAG0 = np.radians(1.5) # sag_start +SAG_END = np.radians(0.5) +SAG_DEG = np.radians(8.0) # trap fired +DEBOUNCE = 10 # control steps (0.5 s) +SETTLE_MIN, SETTLE_MAX = 300, 600 # final judge: 15-30 s of simulated time with the arm holding still + +# scripted motion +Z_CARRY = 0.25 # grasp point above the table while carrying a jar (its bottom then clears the board by ~5 cm) +R_MID = GAP + BOARD_D / 2 # 0.104: the middle of the board's depth (from the wall face) +R_BACK = JB + 0.010 # 0.035: a jar against the wall (1 cm gap) +NAIVE_BIAS = 0.010 # per instance: Sonnet aims at the middle +- 1 cm (towards the wall or the free edge) +NAIVE_RAND = 0.006 # per jar +NAIVE_V, NAIVE_V_DOWN, NAIVE_WAITS = 0.35, 0.15, 0.5 # pace: ~8 s of simulated time from one placement to the next +# (Sonnet, lh_nudge_row pilot np2: 3.2-8.3 s, median 5.1 s) + + +def jar_xml(name, rgba): + h = JAR_H / 2 + z0 = -h # bottom + m = 0.25 + parts = [("body", "box", (0, 0, z0 + BODY_H / 2), (JB, JB, BODY_H / 2), rgba, 'friction="0.3 0.005 0.0001"'), + ("lid", "box", (0, 0, z0 + BODY_H + LID_H / 2), (LID_B, LID_B, LID_H / 2), LID_RGBA, + f'friction="{LID_MU} 0.005 0.0001"'), + ("neck", "cylinder", (0, 0, z0 + BODY_H + LID_H + NECK_H / 2), (NECK_R, NECK_H / 2), KNOB_RGBA, + f'friction="{LID_MU} 0.005 0.0001"'), + ("knob", "sphere", (0, 0, z0 + KNOB_Z), (KNOB_R,), KNOB_RGBA, + f'friction="1 {KNOB_MU_T} 0.0001" condim="4" priority="2"')] + ixx = m * ((2 * JB) ** 2 + BODY_H ** 2) / 12 + izz = m * (2 * (2 * JB) ** 2) / 12 + s = [f' '] + for nm, typ, pos, size, c, extra in parts: + s.append(f' ') + s.append(f' ') + # a lighter label band on the body (visual only) + s.append(f' ') + return _wrap(name, "\n".join(s), h, JB * 1.42) + + +def shelf_xml(name): + """fixture frame: origin on the table top below the middle of the hinge line; local +y points from the wall towards + the board's free edge, local x along the wall. Wall panel (static) + board (child body on a hinge about -x at the + wall face, so a positive joint angle lowers the free edge). Wall and board do not collide with each other + (contype 2 / conaffinity 1); both collide with everything else.""" + zc = BOARD_TOP - BOARD_T / 2 # hinge axis height (board mid-thickness) + wall_h = BOARD_TOP + LIP + hw = (BOARD_L + 0.04) / 2 + wall = (f'type="box" pos="0 {-PANEL_T / 2:.5f} {wall_h / 2:.5f}" size="{hw:.5f} {PANEL_T / 2:.5f} {wall_h / 2:.5f}" ' + f'rgba="{_fmt(WALL_RGBA)}"') + g = [f'', + f''] + slab = (f'type="box" pos="0 {BOARD_D / 2 + GAP:.5f} 0" size="{BOARD_L / 2:.5f} {BOARD_D / 2:.5f} {BOARD_T / 2:.5f}" ' + f'rgba="{_fmt(WOOD)}"') + b = [f'', + # stiffness / springref / damping are set per instance (apply_instance) + f'', + f'', + f'', + # darker front edge strip and hinge barrel (visual) + f'', + f''] + nl = "\n " + return f""" + + + + {nl.join(g)} + + {nl.join(b)} + + + + + + + + +""" + + +def _wrap_h(a): + """wrap to [-pi/2, pi/2) (the gripper is symmetric under 180 deg)""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +class DroopSkills(Skills): + """Skills that feed the task's per-step monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class ShelfDroop(LFFTask): + name = "lh_shelf_droop" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Restore", "Plan") + protocol = "cross" + max_attempts = 3 + # careful: ~10 commands per jar (40) + standing up and re-placing three fallen jars (~40) + looking / corrections + agent_max_steps = 120 + instruction = ("Put the four jars (red, green, blue, yellow) on the shelf. At the end all four must be standing " + "upright on the shelf board, and the gripper must be open and clear of the jars and the shelf. " + "(Each jar has a round knob on its lid; held by the knob, a jar hangs straight down.)") + instruction_indirect = ("Put the four little square jars with knobbed lids up on the wooden shelf by the wall. " + "When you are done, all of them have to stand upright on the shelf board, and the gripper " + "must be open and away from the jars and the shelf. (Held by its round knob, a jar hangs " + "straight down.)") + agent_object_names = ["jars (red, green, blue, yellow; each with a round knob on its lid -- held by the knob it " + "hangs straight down)", "wooden shelf board on the wall panel"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs = [] + for i, (c, j) in enumerate(zip(COLOURS, JARS)): + cat = register_generated(f"LffLhsJar{c.capitalize()}", jar_xml(f"lff_lhs_jar_{c}", GLASS_RGBA[c])) + objs.append((j, cat, f"jar{i}_region", (-0.30 + 0.12 * i, 0.30, -0.29 + 0.12 * i, 0.31))) + sh = register_generated("LffLhsShelf", shelf_xml(SHELF_MODEL), free=False) + fx = [(SHELF, sh, "shelf_region", (0.20, -0.31, 0.21, -0.30))] # moved in apply_instance + return write_bddl(self.name, "Put the four jars on the shelf", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.shelf_bid = m.body_name2id(self.env.fixtures_dict[SHELF].root_body) + self.jid = m.joint_name2id(f"{SHELF}_hinge") + self.qa, self.da = int(m.jnt_qposadr[self.jid]), int(m.jnt_dofadr[self.jid]) + self.board_bid = int(m.jnt_bodyid[self.jid]) + pre = f"{SHELF}_{SHELF_MODEL}" + self.board_gid = m.geom_name2id(pre + "_board") + self.wall_gid = m.geom_name2id(pre + "_wall") + self.jgeoms = {j: envs.obj_geom_ids(self.env, j) for j in JARS} + self.jbid = {j: int(m.geom_bodyid[self.jgeoms[j][0]]) for j in JARS} # body that carries the inertial + self.body_gid = {j: m.geom_name2id(f"{j}_lff_lhs_jar_{c}_body") for c, j in zip(COLOURS, JARS)} + self.knob_gid = {j: m.geom_name2id(f"{j}_lff_lhs_jar_{c}_knob") for c, j in zip(COLOURS, JARS)} + self.jdof = {j: envs.free_joint_addr(self.env, j)[1] for j in JARS} + # per-geom lookup tables for the substep contact check + self.owner = np.full(m.ngeom, -1, int) # jar index + for i, j in enumerate(JARS): + self.owner[self.jgeoms[j]] = i + self.is_robot = np.zeros(m.ngeom, bool) + self.is_robot[envs.robot_geom_ids(self.env)] = True + self.is_board = np.zeros(m.ngeom, bool) + self.is_board[self.board_gid] = True + self._sub_rob, self._sub_obj, self._sub_board = {}, {}, set() + sim = self.env.sim + if not getattr(sim, "_lhs_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lhs_task", None) + if t is not None: + t._bracket() + if t.mon is not None: + t._substep() + sim.step = step + sim._lhs_wrapped = True + sim._lhs_task = self + self.inst = None + self.mon = None + self.sk = None + + def _bracket(self): + """the bracket's catch (every MuJoCo substep): a torque holding the board up that fades out over the first + LATCH_TH of droop, so a board that starts to droop does not stop part-way but folds down to its stop""" + d = self.env.sim.data + th = float(d.qpos[self.qa]) + d.qfrc_applied[self.da] = -LATCH * float(np.clip(1.0 - th / LATCH_TH, 0.0, 1.0)) + + def _substep(self): + d = self.env.sim.data + n = d.ncon + if not n: + return + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + for a, b in zip(g1, g2): + pa, pb = self.owner[a], self.owner[b] + if self.is_board[a] or self.is_board[b]: + o = b if self.is_board[a] else a + if self.owner[o] < 0: # the board touched by something that is not a jar (robot, table, ...) + self._sub_board.add("robot" if self.is_robot[o] else (self.env.sim.model.geom_id2name(int(o)) or "?")) + continue + if pa < 0 and pb < 0: + continue + if pa >= 0 and pb >= 0: + if pa != pb: + self._sub_obj[int(pa)] = int(pb) + self._sub_obj[int(pb)] = int(pa) + continue + p, o = (pa, b) if pa >= 0 else (pb, a) + if self.is_robot[o]: + self._sub_rob[int(p)] = True + + # ------------------------------------------------------------ instances + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + loose = bool((int(seed) * 7) % 20 < round(20 * P_LOOSE)) # balanced: 14 of every 20 consecutive seeds + side = "right" if rng.random() < 0.5 else "left" # where the wall stands (robot's view) + s = -1.0 if side == "right" else 1.0 + x0 = float(rng.uniform(*SHELF_X)) + yw = float(rng.uniform(*WALL_Y)) + preload = float(rng.uniform(*PRELOAD_LOOSE)) if loose else PRELOAD_STIFF + damping = float(rng.uniform(*DAMPING)) + ys = -s * float(rng.uniform(*SUP_Y)) + order = rng.permutation(4) + start = {COLOURS[i]: [float(x0 + SUP_U[order[i]] + rng.uniform(-0.01, 0.01)), float(ys + rng.uniform(-0.008, 0.008))] + for i in range(4)} + yaw0 = {c: float(rng.uniform(-0.3, 0.3)) for c in COLOURS} + mu = {c: float(rng.uniform(*JAR_MU)) for c in COLOURS} + mass = {c: float(rng.uniform(*JAR_MASS)) for c in COLOURS} + return dict(seed=int(seed), loose=loose, bracket="loose" if loose else "stiff", side=side, shelf_x=x0, + wall_y=float(s * yw), preload=preload, damping=damping, stiffness=K_SPRING, start=start, yaw0=yaw0, + mu=mu, mass=mass, naive_bias=float(rng.uniform(-NAIVE_BIAS, NAIVE_BIAS))) + + def apply_instance(self, inst): + self.inst = inst + m, d = self.env.sim.model, self.env.sim.data + s = -1.0 if inst["side"] == "right" else 1.0 + # fixture local +y (towards the free edge) = world -s*y + m.body_pos[self.shelf_bid] = [inst["shelf_x"], inst["wall_y"], TZ] + m.body_quat[self.shelf_bid] = [1.0, 0.0, 0.0, 0.0] if s < 0 else [0.0, 0.0, 0.0, 1.0] + wb = BOARD_MASS * G * (BOARD_D / 2 + GAP) # the board's own weight about the hinge + m.jnt_stiffness[self.jid] = inst["stiffness"] + # spring + catch hold the board level up to a load moment of `preload` (the catch's part fades with the droop) + m.qpos_spring[self.qa] = -(inst["preload"] - LATCH + wb) / inst["stiffness"] + m.dof_damping[self.da] = inst["damping"] + d.qpos[self.qa] = 0.0 + d.qvel[self.da] = 0.0 + d.qfrc_applied[self.da] = -LATCH + for c, j in zip(COLOURS, JARS): + b = self.jbid[j] + M = inst["mass"][c] + m.body_mass[b] = M + m.body_inertia[b] = [M * ((2 * JB) ** 2 + BODY_H ** 2) / 12] * 2 + [M * (2 * JB) ** 2 / 6] + m.geom_friction[self.body_gid[j]] = [inst["mu"][c], 0.005, 0.0001] + m.dof_damping[self.jdof[j] + 3:self.jdof[j] + 6] = JAR_ROT_DAMP + self.env.sim.forward() + for c, j in zip(COLOURS, JARS): + envs.place_upright(self.env, j, inst["start"][c], yaw=inst["yaw0"][c], clearance=0.0005) + + def reset_instance(self, inst, recorder=None): + self.mon = None + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = DroopSkills(self.env, self, recorder=recorder) + self._sub_rob, self._sub_obj, self._sub_board = {}, {}, set() + n = len(JARS) + self.mon = dict(state=[False] * n, raw_since=[0] * n, ever=[False] * n, lost=[False] * n, lost_cause=[None] * n, + events=[], last_robot=[None] * n, last_obj=[None] * n, placed_step=[None] * n, + last_place=None, raw_prev=[False] * n, raw_on=[None] * n, in_sag=False, sag_start=None, sag_fired=False, sag_max=0.0, n_sag=0, + fell_in_sag=[], max_deg=0.0, board_touch=[], n_steps=0, finish_step=None) + return self.sk + + # ------------------------------------------------------------ geometry / predicates + def angle(self): + return float(self.env.sim.data.qpos[self.qa]) + + def board_frame(self): + d = self.env.sim.data + return d.xpos[self.board_bid].copy(), d.xmat[self.board_bid].reshape(3, 3).copy() + + def to_board(self, p): + o, R = self.board_frame() + return R.T @ (np.asarray(p, float) - o) + + def board_point(self, u, r, h=BOARD_T / 2): + """world point at (u along the wall, r from the hinge across the board, h above the hinge axis) in the board + frame""" + o, R = self.board_frame() + return o + R @ np.array([u, r, h]) + + def level_point(self, u, r): + """world xy of board coordinates (u, r) with the board level (planning)""" + s = -1.0 if self.inst["side"] == "right" else 1.0 + return np.array([self.inst["shelf_x"] - s * u, self.inst["wall_y"] - s * r]) + + def board_top_z(self): + return TZ + BOARD_TOP + + def jar_axis(self, j): + return self.env.sim.data.xmat[self.jbid[j]].reshape(3, 3)[:, 2].copy() + + def jar_bottom(self, j): + return envs.obj_pos(self.env, j) - self.jar_axis(j) * JAR_H / 2 + + def knob_xyz(self, j): + return self.env.sim.data.geom_xpos[self.knob_gid[j]].copy() + + def tilt(self, j): + return float(np.arccos(np.clip(self.jar_axis(j)[2], -1.0, 1.0))) + + def held(self, j): + return self.sk is not None and self.sk.holding(j) + + def on_board(self, i, extra=0.0): + """jar i stands on the shelf board: its bottom (centre) on the board's top, within the board's outline, its + axis within 10 deg of the board's normal, not held""" + j = JARS[i] + o, R = self.board_frame() + ax = R.T @ self.jar_axis(j) + if ax[2] < np.cos(TILT_OK + extra * 5): + return False + bc = R.T @ (self.jar_bottom(j) - o) + if not (BOARD_T / 2 - 0.004 <= bc[2] <= BOARD_T / 2 + 0.005 + extra): + return False + if abs(bc[0]) > BOARD_L / 2 + extra or not (GAP - extra <= bc[1] <= GAP + BOARD_D + extra): + return False + return not self.held(j) + + def stages(self): + return [self.on_board(i) for i in range(len(JARS))] + + def lever(self, j): + """horizontal distance (m) of the jar's centre of mass from the hinge line, towards the free edge""" + o, R = self.board_frame() + n = R[:, 1].copy() + n[2] = 0.0 + n /= max(np.linalg.norm(n), 1e-9) + return float((self.env.sim.data.xipos[self.jbid[j]] - o) @ n) + + def moment(self, only_state=True): + """load moment (N m) of the jars standing on the board about the hinge""" + mon = self.mon + tot = 0.0 + for i, j in enumerate(JARS): + on = mon["state"][i] if (only_state and mon is not None) else self.on_board(i) + if on: + tot += self.inst["mass"][COLOURS[i]] * G * self.lever(j) + return float(tot) + + def r_cm(self, i): + """distance of jar i's bottom centre from the wall face (cm), in the board frame""" + return 100 * float(self.to_board(self.jar_bottom(JARS[i]))[1]) + + # ------------------------------------------------------------ monitor + def _t(self): + return int(self.sk.n_steps) if self.sk is not None else 0 + + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + mon["n_steps"] += 1 + t = self._t() + rob, obj, brd = dict(self._sub_rob), dict(self._sub_obj), set(self._sub_board) + self._sub_rob, self._sub_obj, self._sub_board = {}, {}, set() + for i in rob: + if not self.held(JARS[i]): + mon["last_robot"][i] = int(t) + for i, k in obj.items(): + mon["last_obj"][i] = [COLOURS[k], int(t)] + for b in brd: + if b not in mon["board_touch"]: + mon["board_touch"].append(b) + mon["_board_touch_now"] = sorted(brd) + th = self.angle() + mon["max_deg"] = max(mon["max_deg"], float(np.degrees(th))) + if th > np.radians(5.0): + mon["droop_t"] = int(t) # last step with the board drooped > 5 deg (it springs back once the jars are off) + self._sag(th, t) + if mon["n_steps"] % 2: + return + for i in range(len(JARS)): + raw = self.on_board(i, 0.002 if mon["state"][i] else 0.0) + if raw and not mon["raw_prev"][i]: + mon["raw_on"][i] = int(t) # set down on the board (raw; the stage event below is debounced) + mon["raw_prev"][i] = raw + if raw == mon["state"][i]: + mon["raw_since"][i] = 0 + continue + mon["raw_since"][i] += 2 + if mon["raw_since"][i] < DEBOUNCE: + continue + mon["state"][i] = raw + mon["raw_since"][i] = 0 + t0 = int(t - DEBOUNCE + 1) + c = COLOURS[i] + if raw: + restored = mon["lost"][i] + e = dict(stage=c, event="restored" if restored else "achieved", step=t0, + r_cm=round(self.r_cm(i), 1), moment_Nm=round(self.moment(), 3)) + if restored: + e["after"] = mon["lost_cause"][i] + mon["events"].append(e) + mon["ever"][i] = True + mon["placed_step"][i] = t0 + mon["last_place"] = (c, t0) + else: + mon["lost"][i] = True + cause = self._cause(i, t) + mon["lost_cause"][i] = cause + e = dict(stage=c, event="lost", step=t0, cause=cause, board_deg=round(float(np.degrees(th)), 1)) + mon["events"].append(e) + if cause == "slid_off": + ps = mon["placed_step"][i] + ss = mon["sag_start"]["step"] if mon["sag_start"] else None + sc = mon.get("sag_cause") + mon["events"].append(dict(jar=c, event="jar_fell", step=t0, + dt_since_placed_s=None if ps is None else round((t0 - ps) * DT, 2), + dt_since_sag_start_s=None if ss is None else round((t0 - ss) * DT, 2), + after_placing=None if sc is None else sc[0], + dt_since_cause_s=None if sc is None else round((t0 - sc[1]) * DT, 2), + in_final_settle=mon["finish_step"] is not None, + board_deg=round(float(np.degrees(th)), 1))) + mon["fell_in_sag"].append(c) + + def _sag(self, th, t): + mon = self.mon + if not mon["in_sag"]: + if th > SAG0: + mon["in_sag"] = True + mon["sag_fired"] = False + mon["sag_max"] = th + mon["fell_in_sag"] = [] + lp = self._last_set_down(t) + mon["sag_cause"] = lp + e = dict(event="sag_start", step=int(t), board_deg=round(float(np.degrees(th)), 2), + moment_Nm=round(self.moment(only_state=False), 3), + preload_Nm=round(float(self.inst["preload"]), 3), + after_placing=None if lp is None else lp[0], + dt_since_placement_s=None if lp is None else round((t - lp[1]) * DT, 2), + n_on_board=int(sum(self.on_board(i) for i in range(len(JARS))))) + mon["sag_start"] = e + mon["events"].append(e) + return + mon["sag_max"] = max(mon["sag_max"], th) + if not mon["sag_fired"] and th > SAG_DEG: + mon["sag_fired"] = True + mon["n_sag"] += 1 + ss = mon["sag_start"] + lp = self._last_set_down(t) # the placement that drove the board past 8 deg (sag_start may be earlier: + mon["sag_cause"] = lp # two jars in the middle already make it creep a few degrees) + mon["events"].append(dict(event="sag", step=int(t), board_deg=round(float(np.degrees(th)), 2), + moment_Nm=round(self.moment(only_state=False), 3), + after_placing=None if lp is None else lp[0], + sag_start_after=ss["after_placing"], + dt_since_placement_s=None if lp is None else round((t - lp[1]) * DT, 2), + dt_since_sag_start_s=round((t - ss["step"]) * DT, 2), + in_final_settle=mon["finish_step"] is not None)) + mon["below"] = mon.get("below", 0) + 1 if th < SAG_END else 0 + if mon["below"] >= 2 * DEBOUNCE: # back level for 1 s (the jars that slid off have been registered) + mon["in_sag"] = False + mon["below"] = 0 + mon["events"].append(dict(event="sag_end", step=int(t), max_deg=round(float(np.degrees(mon["sag_max"])), 1), + fell=list(mon["fell_in_sag"]), + duration_s=round((t - mon["sag_start"]["step"]) * DT, 2))) + + def _last_set_down(self, t): + """(colour, step) of the jar most recently set down on the board (raw predicate) that still stands on it""" + mon = self.mon + cands = [(mon["raw_on"][i], COLOURS[i]) for i in range(len(JARS)) + if mon["raw_on"][i] is not None and mon["raw_prev"][i] and mon["raw_on"][i] <= t] + if not cands: + return None + st, c = max(cands) + return (c, st) + + def _cause(self, i, t, window=60): + mon = self.mon + if self.held(JARS[i]): + return "picked_up" + if (mon["in_sag"] and mon["sag_max"] > np.radians(5.0)) or (mon.get("droop_t") is not None + and t - mon["droop_t"] <= window): + return "slid_off" + lr, lo = mon["last_robot"][i], mon["last_obj"][i] + if lr is not None and t - lr <= window: + return "robot" + if lo is not None and t - lo[1] <= window: + return "jar:" + lo[0] + return "other" + + def _finalize_monitor(self, raw): + mon = self.mon + t = self._t() + for i in range(len(JARS)): + if raw[i] == mon["state"][i]: + continue + mon["state"][i] = raw[i] + c = COLOURS[i] + if raw[i]: + restored = mon["lost"][i] + e = dict(stage=c, event="restored" if restored else "achieved", step=t, final=True) + if restored: + e["after"] = mon["lost_cause"][i] + mon["events"].append(e) + mon["ever"][i] = True + else: + mon["lost"][i] = True + cause = self._cause(i, t, window=10 ** 6) + mon["lost_cause"][i] = cause + mon["events"].append(dict(stage=c, event="lost", step=t, cause=cause, final=True)) + + # ------------------------------------------------------------ outcome + def _touching(self): + d = self.env.sim.data + jar_touch, board_touch = False, False + for k in range(d.ncon): + c = d.contact[k] + a, b = c.geom1, c.geom2 + if (self.is_robot[a] and self.owner[b] >= 0) or (self.is_robot[b] and self.owner[a] >= 0): + jar_touch = True + if (self.is_robot[a] and self.is_board[b]) or (self.is_robot[b] and self.is_board[a]): + board_touch = True + return jar_touch, board_touch + + def _moving(self): + d = self.env.sim.data + if abs(float(d.qvel[self.da])) > np.radians(0.3): + return True + for j in JARS: + da = self.jdof[j] + if np.linalg.norm(d.qvel[da:da + 3]) > 0.01 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.3: + return True + return False + + def outcome(self, inst): + sk = self.sk + mon = self.mon + mon["finish_step"] = self._t() + # what the agent's last images show (finish returns no image): board angle and the jars already off the board + th_fin = self.angle() + off_fin = [COLOURS[i] for i in range(4) if mon["ever"][i] and not self.on_board(i) and not self.held(JARS[i])] + max_fin = float(mon["max_deg"]) + # settle with the arm holding still: >= 15 s of simulated time, up to 30 s while the board or a jar still moves + # (the droop is slow: finishing right after the last placement must not beat it) + n = 0 + while n < SETTLE_MAX: + sk.hold(10) + n += 10 + if n >= SETTLE_MIN and not self._moving() and not mon["in_sag"]: + break + settle_s = n * DT + p0 = {j: envs.obj_pos(self.env, j) for j in JARS} + th0 = self.angle() + jar_touch = board_touch = False + board_other = set() + for _ in range(20): + sk.hold(1) + jt, bt = self._touching() + jar_touch, board_touch = jar_touch or jt, board_touch or bt + board_other |= {b for b in mon.get("_board_touch_now", []) if b != "robot"} + moved = max(float(np.linalg.norm(envs.obj_pos(self.env, j) - p0[j])) for j in JARS) + static = moved < 0.003 and abs(self.angle() - th0) < np.radians(0.3) + raw = self.stages() + self._finalize_monitor(raw) + th = self.angle() + held = [COLOURS[i] for i, j in enumerate(JARS) if self.held(j)] + level = th <= BOARD_OK + propped = sorted(board_other) + success = bool(all(raw) and level and static and not held and not jar_touch and not board_touch and not propped) + ev = list(mon["events"]) + n_reg = sum(e.get("event") == "lost" and e.get("cause") != "picked_up" for e in ev) + n_lost = sum(e.get("event") == "lost" for e in ev) + n_res = sum(e.get("event") == "restored" and e.get("after") != "picked_up" for e in ev) + fell = [e for e in ev if e.get("event") == "jar_fell"] + sags = [e for e in ev if e.get("event") == "sag"] + sag_vis = [e for e in sags if not e.get("in_final_settle")] + starts = [e for e in ev if e.get("event") == "sag_start"] + ever = mon["ever"] + lost_final = [i for i in range(4) if not raw[i] and ever[i]] + never = [i for i in range(4) if not raw[i] and not ever[i]] + if success: + failure = "none" + elif held: + failure = "held" + elif propped or board_touch: + failure = "propped" + elif jar_touch: + failure = "touching" + elif lost_final: + causes = {mon["lost_cause"][i] for i in lost_final} + failure = ("slid_off" if "slid_off" in causes else "knocked_off" if "robot" in causes else "regressed") + elif never: + failure = "not_on_shelf" + elif not level: + failure = "board_drooped" + else: + failure = "not_static" + # ---- F2 text + parts = [] + if success: + parts.append("All four jars stand upright on the shelf board.") + for i in range(4): + if raw[i]: + continue + c, j = COLOURS[i], JARS[i] + if c in held: + parts.append(f"The {c} jar is still held by the gripper.") + continue + pb = self.to_board(self.jar_bottom(j)) + lying = self.tilt(j) > np.radians(45) + if pb[2] < -0.02: # below the board: on the table + where = "lies on its side on the table" if lying else "stands on the table" + dist = 100 * float(pb[1] - (GAP + BOARD_D)) + txt = f"The {c} jar {where}" + (f", {dist:.0f} cm out from the shelf's front edge." if dist > 0 + else ", under the shelf.") + elif lying: + txt = f"The {c} jar lies on its side on the shelf board." + else: + txt = f"The {c} jar is not standing on the shelf board." + if ever[i]: + why = mon["lost_cause"][i] + txt += {"slid_off": " It had stood on the shelf; it slid off when the shelf board drooped under the load.", + "robot": " It had stood on the shelf; the robot knocked it off.", + }.get(why, " It had stood on the shelf earlier.") + parts.append(txt) + if all(raw) and not success: + if not level: + parts.append(f"The shelf board droops by {np.degrees(th):.0f} degrees.") + if held: + pass + elif jar_touch or board_touch: + parts.append("The gripper is still touching " + ("a jar." if jar_touch else "the shelf board.")) + elif propped: + parts.append("The shelf board rests on something below it.") + elif not static: + parts.append("Something was still moving.") + if sags: + parts.append(f"During the attempt the shelf board drooped {len(sags)} time(s) (down to {mon['max_deg']:.0f} " + f"degrees) and {len(fell)} time(s) a jar slid off; {n_res} time(s) a jar was put back.") + trap = bool(sags) + lp = lambda e: e.get("dt_since_placement_s") # noqa: E731 + return dict(success=success, stages={COLOURS[i]: bool(raw[i]) for i in range(4)}, events=ev, + n_regressions=int(n_reg), n_lost=int(n_lost), n_restored=int(n_res), n_fell=len(fell), + n_sag=len(sags), trap_fired=trap, sag_visible=bool(sag_vis), + recovered_in_attempt=bool(trap and success), + first_sag_dt_s=lp(sags[0]) if sags else None, + first_sag_start_dt_s=lp(starts[0]) if starts else None, + first_sag_after=sags[0].get("after_placing") if sags else None, + first_fall_dt_s=fell[0].get("dt_since_cause_s") if fell else None, + fell_before_finish=bool([e for e in fell if not e.get("in_final_settle")]), + board_deg_at_finish=round(float(np.degrees(th_fin)), 1), off_at_finish=off_fin, + max_droop_before_finish_deg=round(max_fin, 1), + visible_before_finish=bool(sag_vis or off_fin or max_fin > np.degrees(SAG_DEG)), + fell_jars=sorted({e["jar"] for e in fell}), failure=failure, held=held, touching=bool(jar_touch), + board_touched=bool(board_touch), propped=propped, static=bool(static), + board_deg=round(float(np.degrees(th)), 2), max_droop_deg=round(mon["max_deg"], 1), + r_cm={COLOURS[i]: round(self.r_cm(i), 1) for i in range(4)}, + moment_Nm=round(self.moment(only_state=False), 3), preload_Nm=round(float(inst["preload"]), 3), + loose=bool(inst["loose"]), settle_s=settle_s, finish_step=mon["finish_step"], + detail=" ".join(parts)) + + # ------------------------------------------------------------ scripted primitives (move_to + gripper only) + def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300): + return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + + def _lift_to(self, z, speed=0.15): + cur = self.sk.eef_pos() + if cur[2] < TZ + z - 0.005: + self._go([cur[0], cur[1], TZ + z], speed=speed) + + def _settle_jar(self, j, max_checks=30): + d = self.env.sim.data + da = self.jdof[j] + for _ in range(max_checks): + if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2: + return + self.sk.hold(2) + + def wait_board(self, max_steps=200): + """wait (arm still) until the board stops moving""" + for _ in range(max_steps // 5): + if abs(float(self.env.sim.data.qvel[self.da])) < np.radians(0.3) and not self.mon["in_sag"]: + return + self.sk.hold(5) + + def lying(self, j): + return self.tilt(j) > np.radians(45) + + def pick(self, j, z_carry=Z_CARRY, yaw=0.0, v=0.2, err=None, tries=2, v_down=0.10, waits=1.0): + """grasp the jar by its knob and lift it to carry height. Standing jar: from above, wrist yaw `yaw`. Lying jar: + fingers across its axis; lifted, it turns between the fingers and hangs straight down.""" + sk = self.sk + for _ in range(tries): + self._settle_jar(j) + lying = self.lying(j) + k = self.knob_xyz(j) + if lying: + ax = self.jar_axis(j)[:2] + gy = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else sk.yaw + else: + gy = yaw + q = k[:2] + (np.asarray(err, float) if err is not None else 0.0) + sk.set_gripper(False, steps=8) + cur = sk.eef_pos() + self._go([cur[0], cur[1], max(cur[2], TZ + min(z_carry, 0.22))], speed=0.15) + self._go([q[0], q[1], max(k[2] + 0.06, TZ + min(z_carry, 0.22))], yaw=gy, speed=v) + sk.hold(max(1, int(4 * waits))) + k = self.knob_xyz(j) + q = k[:2] + (np.asarray(err, float) if err is not None else 0.0) + self._go([q[0], q[1], k[2] + 0.015], speed=v_down) + self._go([q[0], q[1], k[2]], speed=0.04, tol=0.003, max_steps=150) + sk.set_gripper(True, steps=15) + if lying: # lift slowly until it hangs free, let the swing die down + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + KNOB_Z + 0.04], speed=0.08) + sk.hold(20) + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + z_carry], speed=max(0.12, v_down)) + sk.hold(max(1, int(5 * waits))) + if self.held(j): + return True + sk.set_gripper(False, steps=8) + cur = sk.eef_pos() + self._go([cur[0], cur[1], cur[2] + 0.05], speed=0.1) + return False + + def put(self, j, u, r, z_carry=Z_CARRY, h_rel=0.010, v=0.2, yaw=0.0, v_down=0.10, waits=1.0): + """carry the held jar over board point (u, r) (planned with the board level), straight down until its bottom is + h_rel above the board top, let go, lift back to carry height""" + sk = self.sk + xy = self.level_point(u, r) + rel = self.jar_bottom(j)[:2] - sk.eef_pos()[:2] + q = xy - rel + cur = sk.eef_pos() + self._go([q[0], q[1], max(cur[2], TZ + z_carry)], yaw=yaw, speed=v) + sk.hold(max(1, int(12 * waits))) # let the hanging jar stop swinging + rel = self.jar_bottom(j)[:2] - sk.eef_pos()[:2] + q = xy - rel + dz = sk.eef_pos()[2] - envs.obj_min_z(self.env, j) + zr = self.board_top_z() + dz + h_rel + self._go([q[0], q[1], zr + 0.02], speed=v_down) + self._go([q[0], q[1], zr], speed=0.03, tol=0.003, max_steps=150) + sk.set_gripper(False, steps=12) + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + z_carry], speed=max(0.15, v_down)) + sk.hold(3) + + def place(self, i, u, r, p, rng, rand=0.0): + """one stage: pick jar i from wherever it is and put it on the board at (u, r) +- rand""" + j = JARS[i] + e = rng.uniform(-rand, rand, 2) if rand else np.zeros(2) + gerr = rng.uniform(-0.002, 0.002, 2) if rand else None + kw = dict(z_carry=p.get("z_carry", Z_CARRY), v=p.get("v", 0.2), v_down=p.get("v_down", 0.10), + waits=p.get("waits", 1.0)) + if not self.pick(j, err=gerr, **kw): + return False + self.put(j, u + e[0], r + e[1], h_rel=p.get("h_rel", 0.010), **kw) + self._settle_jar(j) + return True + + def supply_order(self): + """jar indices by their supply position: the one whose slot is farthest from the robot first (Sonnet fills a + row from the far end)""" + return sorted(range(4), key=lambda i: -self.inst["start"][COLOURS[i]][0]) + + def slot_u(self, k): + """board u of slot k (k = 0 farthest from the robot)""" + s = -1.0 if self.inst["side"] == "right" else 1.0 + # u runs along local x = -s * world x -> farthest (largest world x) first + return -s * SLOT_U[3 - k] + + def fallen(self): + return [i for i in range(4) if self.mon["ever"][i] and not self.on_board(i) and not self.held(JARS[i])] + + def repair(self, r_target, rng, p, rand=0.0, used=None): + """move every jar on the board to depth r_target (same slot), then stand up the fallen ones and put them into the + free slots at r_target""" + sk = self.sk + self.wait_board() + slots = dict(used or {}) + for i in range(4): + if self.on_board(i) and abs(self.r_cm(i) / 100 - r_target) > 0.02: + self.place(i, slots.get(i, self.slot_u(0)), r_target, p, rng, rand) + self.wait_board() + for i in self.fallen(): + free = [k for k in range(4) if self.slot_u(k) not in slots.values()] or [0] + u = slots.get(i, self.slot_u(free[0])) + slots[i] = u + self.place(i, u, r_target, p, rng, rand) + self.wait_board() + sk.hold(5) + return slots + + def execute(self, inst, params): + rng = np.random.default_rng(params.get("noise_seed", 0)) + r = float(params["r"]) + rand = float(params.get("rand", 0.0)) + order = params.get("order") or self.supply_order() + used = {} + mode_back = False + for k, i in enumerate(order): + u = self.slot_u(k) + used[i] = u + rr = R_BACK + params.get("back_off", 0.0) if mode_back else r + self.place(i, u, rr, params, rng, rand) + # looks at the jar it just placed (Sonnet): re-places it if it is not standing on the board + if not self.on_board(i) and params.get("self_check", True): + self.place(i, u, rr, params, rng, rand) + if params.get("look_back") and (self.fallen() or self.angle() > np.radians(3.0)): + # the shelf sags / jars fell: from now on load it near the wall, and move what is on it there too + mode_back = True + used = self.repair(R_BACK + params.get("back_off", 0.0), rng, params, rand, used) + if params.get("final_check"): + for _ in range(2): + if all(self.stages()): + break + rr = R_BACK + params.get("back_off", 0.0) if (mode_back or params.get("look_back")) else r + used = self.repair(rr, rng, params, rand, used) + if not params.get("fast_finish"): + self._lift_to(Z_CARRY) + self.sk.hold(5) + + # naive = Sonnet-like (DESIGN_INSIGHTS §3; lh_nudge_row / lh_bystander pilots): careful top-down pick and place, jars + # set down in the visual middle of the shelf's depth, released ~1-4 cm above, wrist yaw 0, looks at the jar it just + # placed, no look back at the others before finishing + def default_params(self, inst): + sd = int(inst["seed"]) + return dict(r=R_MID + float(inst["naive_bias"]), rand=NAIVE_RAND, noise_seed=sd * 13, + h_rel=0.010 + 0.030 * ((sd * 7) % 11) / 10, z_carry=Z_CARRY, look_back=False, final_check=False, + v=NAIVE_V, v_down=NAIVE_V_DOWN, waits=NAIVE_WAITS) + + def oracle_params(self, inst): + return dict(r=R_BACK, rand=0.0, h_rel=0.005, z_carry=Z_CARRY, look_back=True, final_check=True) + + def adapt_params(self, inst, history): + """from attempt 2: load the shelf near the wall (same imprecision), look back after every jar and at the end""" + return dict(self.default_params(inst), r=R_BACK + 0.008, look_back=True, final_check=True) + + def blind_params(self, inst, attempt, rng): + """the naive behaviour with random variation (depth on the board, order, heights), no history, no look back""" + order = [int(x) for x in rng.permutation(4)] + return dict(self.default_params(inst), noise_seed=int(rng.integers(1 << 30)), r=float(rng.uniform(0.06, 0.15)), + order=order, z_carry=float(rng.uniform(0.24, 0.28)), h_rel=float(rng.uniform(0.005, 0.04)), + v=float(rng.uniform(0.12, 0.3))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + single = ("oracle", "naive", "oracle_noise", "naive_front", "naive_back", "naive_check_mid", "naive_fast") + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": # attempt 1: naive + looks back after every jar; repairs near the wall + params = (dict(self.default_params(inst), look_back=True, final_check=True, back_off=0.008) if a == 0 + else self.adapt_params(inst, history)) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": # control: cross-attempt learning only (near the wall from attempt 2), no repair + params = (self.default_params(inst) if a == 0 else + dict(self.default_params(inst), r=R_BACK + 0.008)) + elif kind == "oracle_noise": + params = dict(self.oracle_params(inst), rand=0.005, noise_seed=int(seed) * 7 + a) + elif kind == "naive_front": # control: naive, but jars set down near the free edge + params = dict(self.default_params(inst), r=GAP + BOARD_D - JB - 0.015) + elif kind == "naive_back": # control: naive pace and imprecision, jars against the wall -> no droop + params = dict(self.default_params(inst), r=R_BACK + 0.008) + elif kind == "naive_check_mid": # control: looks back and repairs, but puts the jars back in the middle + params = dict(self.default_params(inst), final_check=True) + elif kind == "naive_fast": # control: naive at the fastest pace, finishing right after the last jar + params = dict(self.default_params(inst), v=0.6, v_down=0.3, waits=0.1, h_rel=0.03, fast_finish=True) + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in single: + break + return history diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/lh_wobbly_table.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/lh_wobbly_table.py new file mode 100644 index 0000000000000000000000000000000000000000..9d7b70f09bae7e0720480903ba087e0a11aed799 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/lh_wobbly_table.py @@ -0,0 +1,1177 @@ +"""LH lh_wobbly_table (2026-10-16): stand four bottles on the four coloured spots of a small side table -- one of its +legs is 1.5 cm short. Set the heavy bottle down on the corner over that leg while other bottles already stand on the +table and the table rocks down onto the short leg with a knock that throws the tall light bottles over. + +Family: long-horizon self-disturbance ("state_restoration"): four plain pick-and-place stages, but a later stage (the heavy +bottle on the wobbly corner) physically undoes the earlier ones without the robot touching them. The agent has to +notice the fallen bottles and stand them up again (the rocked table is stable, so they stay up), or learn across +attempts to put that bottle down first (the table then rocks while nothing stands on it). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a small wooden side table (free body, 1.1 kg): 28 x 28 x 1.6 cm top, 8.5 cm high, four 1.6 cm square legs at + +-12.5 cm; centre 53-57 cm in front of the robot base, +-4 cm left/right; four coloured spots (7.2 x 6.4 cm, + painted, colours permuted) centred 8 cm from the middle on both axes (one per corner); + * four square glass bottles (red / blue / green / yellow; 3.2 x 3.2 x 10 cm body, 2.4 cm flat foot, shoulder, 1.4 cm + square neck, a thin stem and a 1.2 cm white ball stopper; 14.7 cm tall) standing in a row on the main table in + front of the side table or beside it (random). Three are empty and light (75-90 g, centre of mass 7.2-8.0 cm up: + they tip over beyond ~9 deg); the fourth looks the same but is heavy (0.34-0.38 kg, sand in the bottom, centre of + mass 3.0-3.6 cm up). + +Hidden variables: which leg is short (its collision capsule is 14-16 mm shorter; the visual leg is drawn full length, +so all legs look alike and touch the table) and which bottle is heavy. Coupled by construction: the heavy bottle's spot +is the corner over the short leg. Balanced over seeds: in the scripted naive order (spots farthest from the supply +first, then left first) the heavy bottle's spot comes 1st / 2nd / 3rd / 4th for exactly 5 of every 20 consecutive seeds +(1st = benign for that order: the table rocks while it is empty). + +Physics (measured, scratch scripts t2-t24, see the task card and results/lh_wobbly_table/physics.json): + * The legs' collision geoms are capsules (rounded feet). With flat 1.6 cm box feet the rocking axis moved 1.1 cm + towards the loaded corner and the table's own weight stopped the rock half way (0.5 deg, balanced on two legs). + * The empty table rests level on its three long legs: its centre of mass is 5 mm towards the corner opposite the + short leg (1.1 kg x 5 mm). The light bottles on their own spots (the other three corners) never tip it, also let go + 4 cm above the top with a 2.6 cm error towards the short corner (4/4 seeds); the heavy bottle on the short corner + does (0.36 kg x 11.3 cm), also against a light bottle on the opposite corner. (A light bottle put on the short + corner's spot -- a wrong spot -- also tips the empty table: 85 g x 11.3 cm > 1.1 kg x 5 mm.) Rocked onto the short + leg the table tilts 4.5-5.1 deg and stays there with the heavy bottle on it, also when the light ones are added; + lifting the heavy bottle off, or pressing 1.25 N down near the raised corner, rocks it back (measured). + * The knock topples the light bottles standing on the table: 18/18 with teleported (zero-velocity) placements at gaps + 13-18 mm (12 mm: 8-10/18, 10 mm: 0/18); they fall towards the low corner, some off the table edge. The heavy bottle + stays up. The robot does not touch the bottles that fall (logged per rock). + * Bottle and table-top contacts are overdamped (solref 0.01, damping ratio 3): with stiff critically damped contacts + a light bottle let go 1-4 cm above the ROCKED table landed on its uphill edge and fell over (21/27 at 3.4 deg); + damped, 0/54 at every gap 13-18 mm, so the cross-attempt fix (heavy bottle first) works with the agent's usual + release 1-4 cm above the surface. + * A 22 x 22 cm draft table (spots 15.6 cm apart diagonally, 15.7 cm draft bottles) let the bottle on the opposite corner + fall onto the heavy one and lean on it; its stopper could not be grasped without knocking the heavy bottle over + (after which the table rocks back and forth on every repair step). At 28 cm nothing leans on it. + * Grasps: the Panda hand's collision hull starts 3 cm above the grasp point and the finger pads reach 1.2 cm above + it. Everything above the square neck is narrower than the neck: fingers that overlap the neck (grasp point 0.4-0.9 + cm below its top) close on its flat faces and hold the bottle rigidly (the heavy one stayed in the fingers through + three moves at the controller's top speed 12/12, a light one 11/12); fingers on the ball alone (grasp point at or + above the neck's top) touch it at one point each and the bottle pivots (top-speed carries lost it 6/6). Drafts: a + 1.8 cm ball on a 1.3 cm round neck (the fingers always closed on the ball; the heavy bottle swung out in 5/6 fast + carries and once in the first smoke test), a 1.2 x 2.2 cm cylinder stopper (line contacts: a lying bottle lifted by + it stuck at ~26 deg and fell over when set down). The instruction states which grip is rigid and which swings (as + lh_bystander states its cap). + * Restoring (yaw-only top-down gripper): grasp the ball stopper of a lying bottle from above with the fingers across + its axis (torsional friction 0.0005), lift: it swings down and hangs straight (0.1 deg); lower it onto its spot and + let go. A bottle that fell off onto the main table right beside the small table often cannot be reached this way: + the hand (20 cm wide along the finger axis, 3 cm above the grasp point) would hit the table top. Where the hand, + the open fingers or the forearm would touch a standing bottle, the scripted repair first lifts the fallen bottle by + its body and lays it down in free space. + * Reach: the arm stalls 2-3 cm short of low targets beyond ~0.72 m from the base; every scripted grasp point stays + within 0.70 m. + +Success predicates (evaluated every other control step by a monitor, debounced over 0.5 s): each bottle stands upright +(tilt <= 10 deg from vertical; on the rocked table they stand at ~5.5 deg) on the small table's top with the centre of +its bottom inside its spot shrunk by 6 mm (3.0 cm forward-back, 2.6 cm left-right of the spot's centre), not held. +Success = all four at the end, gripper open and not touching a bottle, scene static, and the small table within 3 cm / +10 deg of where it stood and standing on its legs (tilt <= 8 deg; the rocked tilt counts as standing). The monitor logs +achieved / lost / restored per bottle and table_rocked / table_rocked_back events (the bottle released just before, +the bottles standing at that moment, which of them fell, whether the robot touched them before / while they fell) for +the server log only (F1 gives the agent only success / failure). + +Protocol: cross (reset to the same instance before every attempt), k = 3. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +TZ = envs.TABLE_Z +COLOURS = ["red", "blue", "green", "yellow"] +BOTTLES = [f"bottle_{c}_1" for c in COLOURS] +TABLE = "side_table_1" +RGBA = {"red": (0.80, 0.14, 0.12, 1.0), "blue": (0.15, 0.33, 0.80, 1.0), "green": (0.14, 0.58, 0.24, 1.0), + "yellow": (0.90, 0.74, 0.12, 1.0)} +SPOT_RGBA = {"red": (0.62, 0.12, 0.11, 1.0), "blue": (0.12, 0.22, 0.58, 1.0), "green": (0.10, 0.42, 0.17, 1.0), + "yellow": (0.70, 0.56, 0.08, 1.0)} +CAP_RGBA = (0.93, 0.93, 0.91, 1.0) # white round stopper +WOOD = (0.52, 0.36, 0.22, 1.0) +LEG_RGBA = (0.40, 0.27, 0.16, 1.0) + +# ---------------------------------------------------------------- side table (free body) +TOP_HW = 0.140 # 28 x 28 cm top +TOP_T = 0.016 +TABLE_H = 0.085 # top surface above the main table +LEG_HW = 0.008 # 1.6 x 1.6 cm legs (visual); collision: capsules of radius 8 mm (rounded feet) +LEG_O = 0.125 # leg centre offset from the table centre (x and y) +LEG_L = TABLE_H - TOP_T +TBL_MASS = 1.1 +TBL_SOLREF = 'solimp="0.95 0.99 0.001" solref="0.004 1"' # legs: stiff (a sharp knock when the short leg lands) +TOP_SOLREF = 'solimp="0.95 0.99 0.001" solref="0.01 3"' # top: overdamped like the bottles +LEG_MU = 1.0 +TOP_MU = 0.8 +# corners in the table frame (= world axes; +x forward, +y left): index -> (sx, sy); k and k + 2 are diagonal +CORNERS = [(1, 1), (1, -1), (-1, -1), (-1, 1)] +CORNER_NAME = {(1, 1): "far-left", (1, -1): "far-right", (-1, -1): "near-right", (-1, 1): "near-left"} +SPOT_O = 0.080 # spot centre offset from the table centre (x and y) +SPOT_HX, SPOT_HY = 0.036, 0.032 # spot half sizes (forward-back, left-right): 7.2 x 6.4 cm +SHORT_H = (0.014, 0.016) # hidden: one leg this much shorter (collision only; the visual leg reaches the table) +COM_BIAS = 0.005 # table centre of mass this far towards the leg opposite the short one: the empty table rests level + +# ---------------------------------------------------------------- bottles (square glass bottles with a round stopper) +RB, HB = 0.016, 0.100 # body half width, height (3.2 x 3.2 x 10 cm) +RF, HF = 0.012, 0.005 # foot: flat contact 2.4 x 2.4 cm (rounded glass base) +RS, HS = 0.011, 0.010 # shoulder +RN, HN = 0.007, 0.016 # square neck: 1.4 cm wide, 1.6 cm long (11.0-12.6 cm above the bottom) +RT, HT = 0.0035, 0.010 # thin round stem above it: 0.7 cm wide, 1.0 cm long +RK, CAP_SINK = 0.006, 0.001 # ball stopper: 1.2 cm wide, on the stem (top 14.7 cm above the bottom) +# Why this top (measured, t8_hand.py / t19_slip.py / t22_restand.py): the Panda hand's collision hull starts ~3 cm above +# the grasp point and the finger pads reach 1.2 cm above it. Everything above the square neck is narrower than the +# neck, so fingers that overlap the neck close on its flat faces (several contact points: the bottle is held rigidly), +# and fingers on the ball alone touch it at one point each (low torsional friction: a lying bottle swings down and +# hangs straight). Drafts: a 1.8 cm ball on a 1.3 cm round neck -- the fingers always closed on the ball, the heavy +# bottle pivoted and swung out in 5/6 fast carries; a 1.2 x 2.2 cm cylinder stopper -- line contacts, a lifted lying +# bottle stuck at ~26 deg and fell over when set down (in-attempt repair 6/15). +H_TOT = HB + HS + HN + HT + 2 * RK - CAP_SINK # 14.7 cm +CAP_Z = H_TOT - RK # stopper centre above the bottle's bottom +NECK_Z = (HB + HS, HB + HS + HN) # square neck span above the bottom +BOT_MU = 0.7 +CAP_MU_T = 0.0005 # torsional friction of the stopper (condim 4): held by it, a lying bottle swings down and hangs +BOT_DAMP = 0.003 # free-joint damping of the bottles (damps the swing of a bottle hanging from its stopper) +# overdamped contacts (damping ratio 3): with critically damped stiff contacts a light bottle set down 1-4 cm above a +# table top tilted 3.4 deg landed on its uphill edge and fell over (measured 21/27); damped: 0/54 at tilts up to 5 deg +BOT_SOLREF = 'solimp="0.95 0.99 0.001" solref="0.01 3"' +LIGHT_MASS = (0.075, 0.090) +LIGHT_COM = (0.072, 0.080) # above the bottom (empty glass bottle, thick shoulder) +HEAVY_MASS = (0.34, 0.38) +HEAVY_COM = (0.030, 0.036) # sand in the bottom + +# ---------------------------------------------------------------- predicates / monitor +TILT_OK = np.radians(10.0) # a bottle stands upright (world vertical; the rocked table itself tilts ~4.3 deg) +TOL_X = SPOT_HX - 0.006 # bottle centre within the spot shrunk by 6 mm (3.0 cm forward-back, 2.6 cm left-right) +TOL_Y = SPOT_HY - 0.006 +ON_TOP = 0.006 # the bottle's bottom within this of the table top +HYST = 0.003 +DEBOUNCE = 10 # control steps (0.5 s) +ROCK_ON, ROCK_OFF = np.radians(1.5), np.radians(0.8) # table tilt thresholds of the rock detector +FELL_WINDOW = 40 # control steps after a rock in which lost stages are attributed to it (2 s) +TABLE_MOVE_TOL = 0.03 # success: the table centre within 3 cm of where it stood +TABLE_YAW_TOL = np.radians(10.0) +TABLE_TILT_MAX = np.radians(8.0) + +# ---------------------------------------------------------------- scripted motion +Z_CARRY = 0.40 # grasp point above the main table while carrying (bottle bottom ~27 cm up: clears standing bottles) +Z_HANG = 0.42 # ... carrying a bottle that hangs from its stopper (its bottom 27 cm up) +GRASP_NECK = 0.006 # scripted transport grasp point: this far below the neck's top (pads 1.1 cm on the neck, the hand +# 3 mm above the stopper; measured: 4-9 mm below the top hold rigidly, 4 mm above it close on the ball) +NAIVE_GAP = (0.010, 0.040) # Sonnet releases 1-4 cm above the surface +NAIVE_BIAS = (0.008, 0.020) # systematic forward placement error (lh_nudge_row pilot), per instance +NAIVE_RAND = 0.006 +CAREFUL_GAP = 0.004 + + +def bottle_xml(name, rgba): + """square glass bottle: rounded foot (smaller flat contact), body, shoulder, square neck, round stopper. Collision and + visual geoms separate; the inertial (mass, COM) is replaced per instance.""" + h = H_TOT / 2 + zf, zb = -h + HF / 2, -h + HF + (HB - HF) / 2 + zs, zn = -h + HB + HS / 2, -h + HB + HS + HN / 2 + zt = -h + HB + HS + HN + HT / 2 + zk = -h + HB + HS + HN + HT + RK - CAP_SINK + parts = [("foot", "box", (0, 0, zf), (RF, RF, HF / 2), rgba, f'friction="{BOT_MU} 0.005 0.0001"'), + ("body", "box", (0, 0, zb), (RB, RB, (HB - HF) / 2), rgba, f'friction="{BOT_MU} 0.005 0.0001"'), + ("shoulder", "box", (0, 0, zs), (RS, RS, HS / 2), rgba, f'friction="{BOT_MU} 0.005 0.0001"'), + ("neck", "box", (0, 0, zn), (RN, RN, HN / 2), rgba, f'friction="{BOT_MU} 0.005 0.0001"'), + ("stem", "cylinder", (0, 0, zt), (RT, HT / 2), CAP_RGBA, f'friction="{BOT_MU} 0.005 0.0001"'), + ("cap", "sphere", (0, 0, zk), (RK,), CAP_RGBA, f'friction="1 {CAP_MU_T} 0.0001" condim="4" priority="2"')] + s = [f' '] + for nm, typ, pos, size, c, extra in parts: + s.append(f' ') + s.append(f' ') + # a pale label (visual) so the bottles read as bottles + s.append(f' ') + return _wrap(name, "\n".join(s), h, RB * 1.42) + + +def table_xml(name): + """side table, origin at the centre of the footprint at mid height. Leg k sits under corner CORNERS[k].""" + h = TABLE_H / 2 + zt = h - TOP_T / 2 + zl = -h + LEG_L / 2 + s = [f' ', + f' ', + f' '] + for k, (sx, sy) in enumerate(CORNERS): + p = (sx * LEG_O, sy * LEG_O, zl) + # collision: a capsule inscribed in the square leg -> a rounded, point-like foot (a flat 1.6 cm foot moves the + # rocking axis 1.1 cm towards the loaded corner, and the table's own weight then stops the rock; measured) + s.append(f' ') + s.append(f' ') + for k, (sx, sy) in enumerate(CORNERS): # coloured spots (visual); colours are set per instance + s.append(f' ') + return _wrap(name, "\n".join(s), h, TOP_HW * 1.42) + + +def _fb(d): + return f"{100 * abs(d):.1f} cm {'forward' if d > 0 else 'back'}" + + +def _lr(d): + return f"{100 * abs(d):.1f} cm to the {'left' if d > 0 else 'right'}" + + +def _ang(a): + return float((a + np.pi) % (2 * np.pi) - np.pi) + + +class WobblySkills(Skills): + """Skills that feed the task's per-step monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class WobblyTable(LFFTask): + name = "lh_wobbly_table" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Restore", "Plan") + protocol = "cross" + max_attempts = 3 + # careful: 4 bottles x ~7 commands + standing up to three fallen bottles again x ~9 + looking / corrections + agent_max_steps = 120 + instruction = ("Put each of the four bottles on the spot of its own colour on the small wooden table. At the end " + "every bottle must stand upright on its spot, the gripper must be open and clear of the bottles, and " + "the small table must still stand where it is now. (Each bottle has a square neck with a small round " + "white stopper on top. Gripped on the neck, a bottle stays rigid in the fingers; gripped by the " + "stopper alone, it swings freely and hangs straight down.)") + instruction_indirect = ("Set the four coloured bottles out on the little wooden side table, each on the patch that " + "matches its colour. When you finish, all four have to be standing upright on their patches, " + "the gripper open and away from them, and the side table left where it stands. (Gripped " + "on its square neck a bottle stays rigid; gripped by the round white stopper alone it swings " + "freely and hangs straight down.)") + agent_object_names = ["bottles (red, blue, green, yellow; each with a square neck and a small round white stopper)", + "small wooden side table with four coloured spots (red, blue, green, yellow)"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs = [] + for i, (c, b) in enumerate(zip(COLOURS, BOTTLES)): + cat = register_generated(f"LffLhwBottle{c.capitalize()}", bottle_xml(f"lff_lhw_bottle_{c}", RGBA[c])) + objs.append((b, cat, f"bottle{i}_region", (-0.30 + 0.13 * i, 0.30, -0.29 + 0.13 * i, 0.31))) + cat = register_generated("LffLhwSideTable", table_xml("lff_lhw_table")) + objs.append((TABLE, cat, "table_region", (-0.05, -0.30, -0.04, -0.29))) + return write_bddl(self.name, "Stand each bottle on the spot of its colour on the small table", objs, []) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.tbid = envs.body_id(self.env, TABLE) + pre = f"{TABLE}_lff_lhw_table" + self.leg_gid = [m.geom_name2id(f"{pre}_leg{k}") for k in range(4)] + self.top_gid = m.geom_name2id(f"{pre}_top") + self.leg_size0 = [m.geom_size[g].copy() for g in self.leg_gid] + self.leg_pos0 = [m.geom_pos[g].copy() for g in self.leg_gid] + self.tbl_ipos0 = m.body_ipos[self.tbid].copy() + self.spot_gid = [m.geom_name2id(f"{pre}_spot{k}") for k in range(4)] + self.bbid = {b: envs.body_id(self.env, b) for b in BOTTLES} + self.cap_gid = {b: m.geom_name2id(f"{b}_lff_lhw_bottle_{c}_cap") for c, b in zip(COLOURS, BOTTLES)} + self.dof = {b: envs.free_joint_addr(self.env, b)[1] for b in BOTTLES} + self.tbl_dof = envs.free_joint_addr(self.env, TABLE)[1] + self.bgeoms = {b: envs.obj_geom_ids(self.env, b) for b in BOTTLES} + self.finger_geoms, self.hand_geoms, self.arm_geoms = [], [], [] + for g in envs.robot_geom_ids(self.env): + n = m.geom_id2name(g) or "" + (self.finger_geoms if "finger" in n else self.hand_geoms if n.startswith("gripper0_") + else self.arm_geoms).append(g) + # per-geom lookup tables for the substep contact check: bottle index (-1 none), robot part (1 finger, 2 hand, + # 3 arm), table geom + self.owner = np.full(m.ngeom, -1, int) + for i, b in enumerate(BOTTLES): + self.owner[self.bgeoms[b]] = i + self.part = np.zeros(m.ngeom, int) + self.part[self.finger_geoms] = 1 + self.part[self.hand_geoms] = 2 + self.part[self.arm_geoms] = 3 + self.is_table = np.zeros(m.ngeom, bool) + self.is_table[envs.obj_geom_ids(self.env, TABLE)] = True + self._sub_rob, self._sub_obj, self._sub_tbl = {}, {}, 0 + # contacts are collected after every MuJoCo substep (same technique as lh_nudge_row; wrappers chain) + sim = self.env.sim + if not getattr(sim, "_lhw_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lhw_task", None) + if t is not None and t.mon is not None: + t._substep() + sim.step = step + sim._lhw_wrapped = True + sim._lhw_task = self + self.inst = None + self.mon = None + self.sk = None + self._held_prev = None + + def _substep(self): + d = self.env.sim.data + n = d.ncon + if not n: + return + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + o1, o2 = self.owner[g1], self.owner[g2] + for a, b, pa, pb in zip(g1, g2, o1, o2): + if pa < 0 and pb < 0: + if (self.is_table[a] and self.part[b]) or (self.is_table[b] and self.part[a]): + self._sub_tbl = 1 + continue + if pa >= 0 and pb >= 0: + if pa != pb: + self._sub_obj[int(pa)] = int(pb) + self._sub_obj[int(pb)] = int(pa) + continue + p, o = (pa, b) if pa >= 0 else (pb, a) + part = int(self.part[o]) + if part: + self._sub_rob[int(p)] = min(self._sub_rob.get(int(p), 9), part) + + # ------------------------------------------------------------ instances + @staticmethod + def _supply(side, tx, ty, j): + """slot j (0-3) of the row of bottles on the main table: in front of the side table (robot side) or beside it; + every grasp point stays within 0.70 m (horizontal) of the robot base (the arm stalled 2-3 cm short of low + targets beyond ~0.72 m, measured)""" + if side == "front": + return [tx - 0.215, ty + (j - 1.5) * 0.085] + sg = 1.0 if side == "left" else -1.0 + return [tx - 0.05 + (j - 1.5) * 0.075, ty + sg * 0.22] + + @staticmethod + def _far_first(spot_of, side, tx, ty): + """colours in the order of the scripted naive policy: the spots farthest from the supply first (a careful agent + does not reach over bottles it has already put down), ties broken to the left, then far""" + sup = np.mean([WobblyTable._supply(side, tx, ty, j) for j in range(4)], axis=0) + sc = [] + for c, k in spot_of.items(): + sx, sy = CORNERS[k] + p = np.array([tx + sx * SPOT_O, ty + sy * SPOT_O]) + sc.append((-round(float(np.linalg.norm(p - sup)), 3), -sy, -sx, c)) + return [t[-1] for t in sorted(sc)] + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + tx = float(rng.uniform(-0.13, -0.09)) # side table centre: 53-57 cm in front of the robot base + ty = float(rng.uniform(-0.04, 0.04)) + side = str(rng.choice(["left", "right", "front"])) + perm = [int(v) for v in rng.permutation(4)] # perm[corner] = colour index on that corner's spot + spot_of = {COLOURS[perm[k]]: k for k in range(4)} + # the heavy bottle and the short leg under its spot: balanced over seeds against the scripted naive order (far + # spots first): its spot comes 1st / 2nd / 3rd / 4th in that order for exactly 5 of every 20 consecutive seeds + order = self._far_first(spot_of, side, tx, ty) + pos = int((int(seed) * 7) % 20 // 5) + heavy = order[pos] + short = spot_of[heavy] + slots = [int(v) for v in rng.permutation(4)] + start = {} + for i in range(4): + x, y = self._supply(side, tx, ty, slots[i]) + start[COLOURS[i]] = [x + float(rng.uniform(-0.006, 0.006)), y + float(rng.uniform(-0.006, 0.006))] + mass = {c: float(rng.uniform(*LIGHT_MASS)) for c in COLOURS} + com = {c: float(rng.uniform(*LIGHT_COM)) for c in COLOURS} + mass[heavy] = float(rng.uniform(*HEAVY_MASS)) + com[heavy] = float(rng.uniform(*HEAVY_COM)) + return dict(seed=int(seed), table_xy=[tx, ty], short_leg=int(short), short_corner=CORNER_NAME[CORNERS[short]], + heavy=heavy, heavy_rank_naive=pos + 1, spot_of=spot_of, supply_side=side, start=start, mass=mass, + com=com, short_h=float(rng.uniform(*SHORT_H)), com_bias=COM_BIAS, + yaw0={c: float(rng.uniform(-0.3, 0.3)) for c in COLOURS}, + naive_bias_x=float(rng.uniform(*NAIVE_BIAS))) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + k = inst["short_leg"] + h = float(inst["short_h"]) + for j, g in enumerate(self.leg_gid): + m.geom_size[g] = self.leg_size0[j] + m.geom_pos[g] = self.leg_pos0[j] + g = self.leg_gid[k] + m.geom_size[g][1] = self.leg_size0[k][1] - h / 2 # capsule half length + m.geom_pos[g][2] = self.leg_pos0[k][2] + h / 2 + opp = CORNERS[(k + 2) % 4] + b = float(inst.get("com_bias", COM_BIAS)) / np.sqrt(2) + m.body_ipos[self.tbid] = [opp[0] * b, opp[1] * b, self.tbl_ipos0[2]] + envs.refit_bounds(m, self.tbid) + for c in COLOURS: + m.geom_rgba[self.spot_gid[inst["spot_of"][c]]] = SPOT_RGBA[c] + for c, bot in zip(COLOURS, BOTTLES): + bid = self.bbid[bot] + M, zc = inst["mass"][c], inst["com"][c] + m.body_mass[bid] = M + m.body_ipos[bid] = [0.0, 0.0, -H_TOT / 2 + zc] + # glass shell + internal weight, roughly: radius of gyration ~ 0.35 x height about horizontal axes + ixx = M * ((2 * RB) ** 2 / 12 + (0.35 * H_TOT) ** 2) + m.body_inertia[bid] = [ixx, ixx, M * (2 * RB) ** 2 / 6] + envs.refit_bounds(m, bid) + m.dof_damping[self.dof[bot]:self.dof[bot] + 6] = BOT_DAMP + self.env.sim.forward() + tx, ty = inst["table_xy"] + # yaw pi: the canonical quaternion LIBERO gives generated objects is a 180 deg yaw (envs.canonical_quat); with + # it the table frame is the world frame + envs.place_upright(self.env, TABLE, [tx, ty], yaw=np.pi, clearance=0.0003) + for c, bot in zip(COLOURS, BOTTLES): + envs.place_upright(self.env, bot, inst["start"][c], yaw=inst["yaw0"][c], clearance=0.0005) + self.env.sim.data.qvel[self.tbl_dof:self.tbl_dof + 6] = 0.0 + + def reset_instance(self, inst, recorder=None): + self.mon = None + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = WobblySkills(self.env, self, recorder=recorder) + self._sub_rob, self._sub_obj, self._sub_tbl = {}, {}, 0 + self._held_prev = None + self.table0 = dict(pos=self.table_pos().tolist(), yaw=self.table_yaw()) + n = len(BOTTLES) + self.mon = dict(state=[False] * n, raw_since=[0] * n, ever=[False] * n, lost=[False] * n, events=[], + lost_cause=[None] * n, last_robot=[None] * n, last_obj=[None] * n, last_release=None, + last_table_touch=-10 ** 6, rocked=False, rock_since=0, rocks=[], n_steps=0, + max_table_tilt_deg=0.0) + return self.sk + + # ------------------------------------------------------------ geometry / predicates + def table_R(self): + return self.env.sim.data.body_xmat[self.tbid].reshape(3, 3).copy() + + def table_pos(self): + return self.env.sim.data.body_xpos[self.tbid].copy() + + def table_yaw(self): + R = self.table_R() + return float(np.arctan2(R[1, 0], R[0, 0])) + + def table_tilt(self): + return float(np.arccos(np.clip(self.table_R()[2, 2], -1, 1))) + + def top_point(self, local_xy): + """world position of a point on the table's top surface (table frame xy)""" + return self.table_pos() + self.table_R() @ np.array([local_xy[0], local_xy[1], TABLE_H / 2]) + + def spot_local(self, colour): + sx, sy = CORNERS[self.inst["spot_of"][colour]] + return np.array([sx * SPOT_O, sy * SPOT_O]) + + def spot_world(self, colour): + return self.top_point(self.spot_local(colour)) + + def top_z_at(self, xy): + """z of the table's top plane above world point xy""" + R, p = self.table_R(), self.table_pos() + n = R[:, 2] + c = p + n * TABLE_H / 2 + return float(c[2] - (n[0] * (xy[0] - c[0]) + n[1] * (xy[1] - c[1])) / max(n[2], 1e-6)) + + def over_table(self, xy): + loc = self.table_R().T @ (np.array([xy[0], xy[1], self.table_pos()[2]]) - self.table_pos()) + return abs(loc[0]) < TOP_HW and abs(loc[1]) < TOP_HW + + def bR(self, b): + return self.env.sim.data.body_xmat[self.bbid[b]].reshape(3, 3).copy() + + def bpos(self, b): + return self.env.sim.data.body_xpos[self.bbid[b]].copy() + + def foot(self, b): + """world position of the centre of the bottle's bottom face""" + return self.bpos(b) - self.bR(b)[:, 2] * H_TOT / 2 + + def tilt(self, b): + return float(np.arccos(np.clip(self.bR(b)[2, 2], -1.0, 1.0))) + + def cap_xyz(self, b): + return self.env.sim.data.geom_xpos[self.cap_gid[b]].copy() + + def held(self, b): + return self.sk is not None and self.sk.holding(b) + + def offset(self, i): + """bottle i's foot centre relative to its spot centre, in the table frame (x forward-back, y left-right), and + the height of its bottom above the table top""" + b, c = BOTTLES[i], COLOURS[i] + loc = self.table_R().T @ (self.foot(b) - self.table_pos()) + return loc[:2] - self.spot_local(c), float(loc[2] - TABLE_H / 2) + + def on_spot(self, i, extra=0.0): + b = BOTTLES[i] + if self.tilt(b) > TILT_OK + (np.radians(2.0) if extra else 0.0): + return False + off, dz = self.offset(i) + if abs(off[0]) > TOL_X + extra or abs(off[1]) > TOL_Y + extra or abs(dz) > ON_TOP: + return False + return not self.held(b) + + def stages(self): + return [self.on_spot(i) for i in range(len(BOTTLES))] + + def table_ok(self): + p0 = np.asarray(self.table0["pos"]) + moved = float(np.linalg.norm(self.table_pos()[:2] - p0[:2])) + dyaw = abs(_ang(self.table_yaw() - self.table0["yaw"])) + return bool(moved <= TABLE_MOVE_TOL and dyaw <= TABLE_YAW_TOL and self.table_tilt() <= TABLE_TILT_MAX), moved, dyaw + + def low_corner(self): + """robot-centric name of the table corner that is lowest (after a rock: the corner over the short leg)""" + zs = {k: self.top_point([sx * TOP_HW, sy * TOP_HW])[2] for k, (sx, sy) in enumerate(CORNERS)} + return CORNER_NAME[CORNERS[min(zs, key=zs.get)]] + + # ------------------------------------------------------------ monitor + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + mon["n_steps"] += 1 + t = int(self.sk.n_steps) + rob, obj, tbl = dict(self._sub_rob), dict(self._sub_obj), self._sub_tbl + self._sub_rob, self._sub_obj, self._sub_tbl = {}, {}, 0 + gstate = "open" if self.sk.grip < 0 else "closed" + held_now = None + for c, b in zip(COLOURS, BOTTLES): + if gstate == "closed" and self.held(b): + held_now = c + for i, part in rob.items(): + if COLOURS[i] != held_now: + mon["last_robot"][i] = [{1: "finger", 2: "hand", 3: "arm"}[part], t, gstate] + for i, j in obj.items(): + mon["last_obj"][i] = [COLOURS[j], t] + if tbl: + mon["last_table_touch"] = t + if held_now is None and self._held_prev is not None: # the gripper has just let go of a bottle + mon["last_release"] = [self._held_prev, t] + self._held_prev = held_now + tl = self.table_tilt() + mon["max_table_tilt_deg"] = max(mon["max_table_tilt_deg"], round(float(np.degrees(tl)), 2)) + if mon["n_steps"] % 2: + return + # ---- table rock detector (debounced) + want = tl > ROCK_ON if not mon["rocked"] else tl > ROCK_OFF + if want != mon["rocked"]: + mon["rock_since"] += 2 + if mon["rock_since"] >= 4: + mon["rocked"] = want + mon["rock_since"] = 0 + self._rock_event(want, t - 3) + else: + mon["rock_since"] = 0 + for r in mon["rocks"]: + if not r.get("closed") and t - r["step"] > FELL_WINDOW: + self._close_rock(r) + # ---- stage predicates + for i in range(len(BOTTLES)): + b = BOTTLES[i] + raw = self.on_spot(i, HYST if mon["state"][i] else 0.0) + if raw == mon["state"][i]: + mon["raw_since"][i] = 0 + continue + mon["raw_since"][i] += 2 + if mon["raw_since"][i] < DEBOUNCE: + continue + mon["state"][i] = raw + mon["raw_since"][i] = 0 + t0 = int(t - DEBOUNCE + 1) + if raw: + restored = mon["lost"][i] + e = dict(stage=COLOURS[i], event="restored" if restored else "achieved", step=t0) + if restored: + e["after"] = mon["lost_cause"][i] + mon["events"].append(e) + mon["ever"][i] = True + else: + mon["lost"][i] = True + cause = self._cause(i, t0) + mon["lost_cause"][i] = cause + off, dz = self.offset(i) + mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t0, cause=cause, + tilt_deg=round(float(np.degrees(self.tilt(b))), 1), + offset_cm=[round(100 * float(v), 1) for v in off])) + + def _rock_event(self, down, t): + mon = self.mon + rel = mon["last_release"] + e = dict(event="table_rocked" if down else "table_rocked_back", step=int(t), + table_tilt_deg=round(float(np.degrees(self.table_tilt())), 2), low_corner=self.low_corner(), + released=rel[0] if rel is not None and t - rel[1] <= 40 else None, + robot_touched_table=bool(t - mon["last_table_touch"] <= 20), + standing=[COLOURS[i] for i in range(len(BOTTLES)) if mon["state"][i]]) + # the cheap explanation would be "my hand bumped them": which of the standing bottles did the robot touch in + # the 2 s before the rock (should be none) + e["robot_touched_before"] = [COLOURS[i] for i in range(len(BOTTLES)) if mon["state"][i] and + mon["last_robot"][i] is not None and t - mon["last_robot"][i][1] <= 40] + mon["events"].append(e) + mon["rocks"].append(dict(step=int(t), down=bool(down), standing=list(e["standing"]), event=e)) + + def _close_rock(self, r): + """FELL_WINDOW after a rock: which of the bottles that stood on their spots fell, and did the robot touch any + of them after the rock began (a falling bottle hitting the open fingers)""" + r["closed"] = True + mon = self.mon + fell, touched = [], [] + for c in r["standing"]: + i = COLOURS.index(c) + if self.tilt(BOTTLES[i]) > np.radians(30) or not mon["state"][i]: + fell.append(c) + lr = mon["last_robot"][i] + if lr is not None and lr[1] >= r["step"]: + touched.append(c) + r["event"]["fell"] = fell + r["event"]["robot_touched_while_falling"] = touched + r["fell"] = fell + + def _cause(self, i, t, window=60): + if self.held(BOTTLES[i]): + return "picked_up" + mon = self.mon + for r in reversed(mon["rocks"]): + if 0 <= t - r["step"] <= FELL_WINDOW + 10 and COLOURS[i] in r["standing"]: + return "table_rocked" if r["down"] else "table_rocked_back" + lr, lo = mon["last_robot"][i], mon["last_obj"][i] + cands = [] + if lr is not None and t - lr[1] <= window: + cands.append((lr[1], f"robot_{lr[0]}")) + if lo is not None and t - lo[1] <= window: + cands.append((lo[1] - 30, "bottle:" + lo[0])) + return max(cands)[1] if cands else "other" + + def _finalize_monitor(self, raw): + mon = self.mon + if mon is None: + return + for r in mon["rocks"]: + if not r.get("closed"): + self._close_rock(r) + t = int(self.sk.n_steps) + for i in range(len(BOTTLES)): + if raw[i] == mon["state"][i]: + continue + mon["state"][i] = raw[i] + if raw[i]: + restored = mon["lost"][i] + e = dict(stage=COLOURS[i], event="restored" if restored else "achieved", step=t, final=True) + if restored: + e["after"] = mon["lost_cause"][i] + mon["events"].append(e) + mon["ever"][i] = True + else: + mon["lost"][i] = True + cause = self._cause(i, t, window=10 ** 6) + mon["lost_cause"][i] = cause + mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t, cause=cause, final=True)) + + # ------------------------------------------------------------ outcome + def _touching(self): + d = self.env.sim.data + for j in range(d.ncon): + c = d.contact[j] + if (self.owner[c.geom1] >= 0 and self.part[c.geom2]) or (self.owner[c.geom2] >= 0 and self.part[c.geom1]): + return True + return False + + def outcome(self, inst): + sk = self.sk + sk.hold(10) + p0 = {b: self.bpos(b) for b in BOTTLES} + t0 = self.table_pos() + touching = False + for _ in range(20): + sk.hold(1) + touching = touching or self._touching() + moved = max([float(np.linalg.norm(self.bpos(b) - p0[b])) for b in BOTTLES] + + [float(np.linalg.norm(self.table_pos() - t0))]) + static = moved < 0.003 + raw = self.stages() + self._finalize_monitor(raw) + held = [COLOURS[i] for i, b in enumerate(BOTTLES) if self.held(b)] + tok, tmoved, tyaw = self.table_ok() + mon = self.mon + ev = list(mon["events"]) + rocks = [r for r in mon["rocks"] if r["down"]] + damaging = [r for r in mon["rocks"] if r.get("fell")] + n_reg = sum(e.get("event") == "lost" and e.get("cause") != "picked_up" for e in ev) + n_lost = sum(e.get("event") == "lost" for e in ev) + n_res = sum(e.get("event") == "restored" and e.get("after") != "picked_up" for e in ev) + success = bool(all(raw) and static and not held and not touching and tok) + tilted = [i for i in range(len(BOTTLES)) if self.tilt(BOTTLES[i]) > TILT_OK and COLOURS[i] not in held] + ever = mon["ever"] + fell_by_rock = sorted({c for r in damaging for c in r["fell"]}) + if success: + failure = "none" + elif not tok: + failure = "table_moved" + elif held: + failure = "held" + elif tilted: + failure = "toppled_by_rock" if any(COLOURS[i] in fell_by_rock for i in tilted) else "toppled" + elif not all(raw): + failure = "not_on_spot" + elif touching: + failure = "touching" + else: + failure = "not_static" + parts = [] + if success: + parts.append("Every bottle stands upright on the spot of its colour.") + for i in range(len(BOTTLES)): + if raw[i]: + continue + c, b = COLOURS[i], BOTTLES[i] + if c in held: + parts.append(f"The {c} bottle is still held by the gripper.") + continue + off, dz = self.offset(i) + tl = float(np.degrees(self.tilt(b))) + on_small = abs(dz) < 0.05 and max(abs(off + self.spot_local(c))) < TOP_HW + 0.02 + if tl > np.degrees(TILT_OK): + txt = (f"The {c} bottle lies on its side on the {'small' if on_small else 'big'} table" if tl > 45 else + f"The {c} bottle leans {tl:.0f} degrees") + "." + elif abs(dz) > ON_TOP: + txt = f"The {c} bottle is not on the small table." + else: + txt = f"The {c} bottle stands {_fb(off[0])} and {_lr(off[1])} of its spot's centre, not on its spot." + if ever[i] and c in fell_by_rock: + txt += " It had stood on its spot and fell when the small table rocked." + elif ever[i]: + txt += " It had stood on its spot earlier." + parts.append(txt) + if not tok: + parts.append(f"The small table was moved ({100 * tmoved:.1f} cm, {np.degrees(tyaw):.0f} degrees).") + elif not success and all(raw): + if touching: + parts.append("The gripper is still touching a bottle.") + elif not static: + parts.append("Something was still moving.") + if rocks: + r = rocks[0]["event"] + txt = (f"When the {r['released']} bottle was set down, the small table rocked down onto its " + f"{r['low_corner']} leg" if r.get("released") else + f"The small table rocked down onto its {r['low_corner']} leg") + fl = r.get("fell", []) + txt += (" and the " + " and ".join(fl) + f" bottle{'s' if len(fl) > 1 else ''} standing on it fell over." + if fl else ".") + txt += f" That leg is {100 * float(inst['short_h']):.1f} cm shorter than the other three." + parts.append(txt) + trap = bool(damaging) + return dict(success=success, stages={COLOURS[i]: bool(raw[i]) for i in range(len(BOTTLES))}, events=ev, + n_regressions=int(n_reg), n_lost=int(n_lost), n_restored=int(n_res), n_rocks=len(rocks), + rocked=bool(rocks), trap_fired=trap, recovered_in_attempt=bool(trap and success), + fell_by_rock=fell_by_rock, failure=failure, held=held, touching=bool(touching), + static=bool(static), table_ok=bool(tok), table_moved_cm=round(100 * tmoved, 2), + table_tilt_deg=round(float(np.degrees(self.table_tilt())), 2), + max_table_tilt_deg=mon["max_table_tilt_deg"], + offsets_cm={COLOURS[i]: [round(100 * float(v), 2) for v in self.offset(i)[0]] for i in range(4)}, + tilts_deg={COLOURS[i]: round(float(np.degrees(self.tilt(BOTTLES[i]))), 1) for i in range(4)}, + heavy=inst["heavy"], short_corner=inst["short_corner"], detail=" ".join(parts)) + + # ------------------------------------------------------------ scripted primitives (move_to + gripper only) + def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300): + return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + + def _lift_to(self, z, speed=0.2): + cur = self.sk.eef_pos() + if cur[2] < TZ + z - 0.005: + self._go([cur[0], cur[1], TZ + z], speed=speed) + + def _settle(self, b, max_checks=25): + d = self.env.sim.data + da = self.dof[b] + for _ in range(max_checks): + if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2: + return + self.sk.hold(2) + + def upright(self, b): + return self.tilt(b) < np.radians(20) + + def pick_neck(self, b, z_carry=Z_CARRY, yaw=0.0, v=0.2): + """Sonnet-like top-down pick of a standing bottle: open, over it at carry height, straight down to the upper + neck, close, lift to carry height. Returns True if held.""" + sk = self.sk + self._settle(b) + p = self.foot(b) + zg = p[2] + NECK_Z[1] - GRASP_NECK + sk.set_gripper(False, steps=8) + self._lift_to(z_carry) + self._go([p[0], p[1], TZ + z_carry], yaw=yaw, speed=v) + self._go([p[0], p[1], zg + 0.02], speed=0.12) + self._go([p[0], p[1], zg], speed=0.04, tol=0.003, max_steps=150) + sk.set_gripper(True, steps=15) + self._go([p[0], p[1], TZ + z_carry], speed=0.12) + sk.hold(5) + if not self.held(b): + sk.set_gripper(False, steps=8) + return False + return True + + def put_held(self, b, xy, gap, z_carry=Z_CARRY, yaw=None, v=0.2): + """carry the held bottle so that its foot is over world xy, straight down until its bottom is `gap` above the + surface below, let go, lift""" + sk = self.sk + rel = self.foot(b)[:2] - sk.eef_pos()[:2] + q = np.asarray(xy, float) - rel + self._go([q[0], q[1], TZ + z_carry], yaw=yaw, speed=v) + sk.hold(10) + rel = self.foot(b)[:2] - sk.eef_pos()[:2] # a bottle hanging from its stopper swings while carried + q = np.asarray(xy, float) - rel + surf = self.top_z_at(xy) if self.over_table(xy) else TZ + dz = sk.eef_pos()[2] - self.foot(b)[2] + zr = surf + dz + gap + self._go([q[0], q[1], zr + 0.02], speed=0.10) + self._go([q[0], q[1], zr], speed=0.03, tol=0.003, max_steps=150) + sk.hold(4) + sk.set_gripper(False, steps=12) + cur = sk.eef_pos() + self._go([cur[0], cur[1], cur[2] + 0.06], speed=0.10) + self._go([cur[0], cur[1], TZ + z_carry], speed=0.2) + sk.hold(3) + + def surface_z(self, xy): + return self.top_z_at(xy) if self.over_table(xy) else TZ + + def pick_stopper(self, b, v=0.15): + """grasp a lying (or leaning) bottle by its round stopper from above, fingers across the bottle's axis, lift it + until it hangs free. The fingertips stay >= 4 mm above the surface under the stopper: pressing the raised half + of the rocked table rocks it back (measured), and the knock when it comes down again topples standing bottles. + Returns True if held.""" + sk = self.sk + self._settle(b) + for _ in range(2): + k, zg, yaw = self.stopper_grasp(b) # fingers across the bottle's axis + sk.set_gripper(False, steps=8) + self._lift_to(Z_HANG) + self._go([k[0], k[1], TZ + Z_HANG], yaw=yaw, speed=v) + sk.hold(5) + k, zg, _ = self.stopper_grasp(b) + self._go([k[0], k[1], zg + 0.03], speed=0.10) + self._go([k[0], k[1], zg], speed=0.03, tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + if not self.held(b): + sk.set_gripper(False, steps=8) + self._go([k[0], k[1], zg + 0.08], speed=0.1) + continue + self._go([k[0], k[1], zg + 0.05], speed=0.05) + self._go([k[0], k[1], TZ + Z_HANG], speed=0.10) + sk.hold(20) + return True + return False + + # gripper footprint (measured, t8_hand): the hand's collision hull is a slab 20 cm along the finger axis and ~4 cm + # across, from 3 cm above the grasp point up; open fingers 3.9-6.6 cm out along the finger axis, from 1 cm below + # the grasp point to 4.5 cm above it + HAND_U, HAND_V, HAND_Z0 = 0.100, (-0.018, 0.024), 0.03 + FING_U, FING_V, FING_Z = (0.039, 0.066), (-0.009, 0.013), (-0.010, 0.045) + # wrist and forearm (t16_arm, measured at low grasps): lowest point above the grasp point vs the distance from the + # grasp point towards the robot base; they span ~13 cm to either side of that line + ARM_D = (-0.05, 0.05, 0.10, 0.15, 0.20) + ARM_Z = (0.097, 0.100, 0.155, 0.185, 0.31) + ARM_LAT = 0.13 + + def _footprint(self, q, yaw): + """sample points (xy) of the hand slab and of the open fingers for a grasp at q with gripper yaw `yaw`""" + a = np.array([-np.sin(yaw), np.cos(yaw)]) # finger axis + c = np.array([np.cos(yaw), np.sin(yaw)]) + hand = [q + u * a + v * c for u in np.linspace(-self.HAND_U, self.HAND_U, 21) + for v in np.linspace(*self.HAND_V, 5)] + fing = [q + sg * u * a + v * c for sg in (-1, 1) for u in np.linspace(*self.FING_U, 4) + for v in np.linspace(*self.FING_V, 3)] + return np.array(hand), np.array(fing) + + def grasp_clearance(self, q, zg, yaw, ignore=()): + """smallest horizontal clearance (m) between the hand / open fingers of a grasp at (q, zg) and any standing + bottle (other than `ignore`) or the small table; negative = collision""" + q = np.asarray(q, float)[:2] + hand, fing = self._footprint(q, yaw) + best = 1.0 + for b in BOTTLES: + if b in ignore or self.held(b) or self.tilt(b) > np.radians(30): + continue + p = self.foot(b)[:2] + top = self.foot(b)[2] + H_TOT + r = RB * 1.42 + if top > zg + self.HAND_Z0: + best = min(best, float(np.min(np.linalg.norm(hand - p, axis=1))) - r) + best = min(best, float(np.min(np.linalg.norm(fing - p, axis=1))) - r) + # the wrist / forearm sloping back towards the robot base over a tall standing bottle + ub = np.array([-0.66, 0.0]) - q + ub /= max(float(np.linalg.norm(ub)), 1e-6) + along, lat = float((p - q) @ ub), float((p - q) @ np.array([-ub[1], ub[0]])) + if self.ARM_D[0] <= along <= self.ARM_D[-1] and abs(lat) < self.ARM_LAT + r: + if top > zg + float(np.interp(along, self.ARM_D, self.ARM_Z)) - 0.01: + best = min(best, -0.01) + # the small table's top plate (and legs) when the grasp is below its top surface + R, P = self.table_R(), self.table_pos() + ztop = P[2] + TABLE_H / 2 + for pts, z0, z1 in ((hand, zg + self.HAND_Z0, zg + 0.13), (fing, zg + self.FING_Z[0], zg + self.FING_Z[1])): + if z0 > ztop + 0.003: + continue + loc = (pts - P[:2]) @ R[:2, :2] + if z1 > ztop - TOP_T: # the plate's height band + d = np.maximum(np.abs(loc) - TOP_HW, 0.0) + inside = np.all(np.abs(loc) < TOP_HW, axis=1) + dist = np.where(inside, -0.01, np.linalg.norm(d, axis=1)) + best = min(best, float(np.min(dist))) + return best + + def stopper_grasp(self, b): + """(xy, z, yaw) of the stopper grasp of a lying bottle: fingers across its axis, fingertips >= 4 mm above the + surface below""" + k = self.cap_xyz(b) + ax = self.bR(b)[:2, 2] + yaw = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else self.sk.yaw + zg = max(float(k[2]), self.surface_z(k[:2]) + envs.FINGERTIP_BELOW_SITE + 0.004) + return k[:2], zg, yaw + + def body_grasp(self, b, along=None): + """(xy, z, yaw) of a grasp across a lying bottle's body, `along` m from its bottom (default: the middle)""" + R = self.bR(b) + a = HF + (HB - HF) / 2 if along is None else float(along) + c = self.foot(b) + R[:, 2] * a + ax = R[:2, 2] + yaw = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else self.sk.yaw + zg = max(float(c[2]), self.surface_z(c[:2]) + envs.FINGERTIP_BELOW_SITE + 0.004) + return c[:2], zg, yaw + + def staging_spot(self, b): + """a free place on the main table to lay a fallen bottle down: far from the small table and the other bottles, + within the arm's comfortable reach""" + tx, ty = self.table_pos()[:2] + best, bq = -1.0, None + for x in np.arange(tx - 0.30, tx + 0.06, 0.03): + for y in np.arange(ty - 0.30, ty + 0.31, 0.03): + # within reach, and >= 14 cm inside the main table's edges (it spans x, y = +-0.5, +-0.6): a bottle laid + # down too close to the near edge rolled off onto the floor (measured) + if np.hypot(x + 0.66, y) > 0.66 or np.hypot(x + 0.66, y) < 0.33 or x < -0.36 or abs(y) > 0.46: + continue + loc = self.table_R()[:2, :2].T @ (np.array([x, y]) - np.array([tx, ty])) + dt = float(np.linalg.norm(np.maximum(np.abs(loc) - TOP_HW, 0.0))) + if np.all(np.abs(loc) < TOP_HW): + continue + do = min([float(np.linalg.norm(self.foot(o)[:2] - [x, y])) for o in BOTTLES if o != b] + + [float(np.linalg.norm(self.cap_xyz(o)[:2] - [x, y])) for o in BOTTLES if o != b]) + sc = min(dt - 0.10, do - 0.14) # the bottle lies ~16 cm long around the point + if sc > best and min(self.grasp_clearance([x, y], TZ + 0.016, yw, ignore=(b,)) + for yw in (0.0, np.pi / 2)) > 0.01: + best, bq = sc, np.array([x, y]) + return bq + + def stage(self, b, v=0.12): + """the stopper of a fallen bottle cannot be reached: grasp its body at a point where the hand is clear (the + bottle then hangs from the grasp), carry it to free space on the main table, let it down there so that it falls + over away from everything. Returns True if it was moved.""" + sk = self.sk + for along in (0.055, 0.035, 0.075, 0.015, 0.095): + q, zg, yaw = self.body_grasp(b, along) + if self.grasp_clearance(q, zg, yaw, ignore=(b,)) >= 0.004: + break + else: + return False + dst = self.staging_spot(b) + if dst is None: + return False + sk.set_gripper(False, steps=8) + self._lift_to(Z_CARRY) + self._go([q[0], q[1], TZ + Z_CARRY], yaw=yaw, speed=v) + self._go([q[0], q[1], zg + 0.03], speed=0.10) + self._go([q[0], q[1], zg], speed=0.03, tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + if not self.held(b): + sk.set_gripper(False, steps=8) + self._go([q[0], q[1], TZ + Z_CARRY], speed=0.1) + return False + self._go([q[0], q[1], zg + 0.04], speed=0.05) + self._go([q[0], q[1], TZ + Z_HANG], speed=0.10) + sk.hold(15) + self._go([dst[0], dst[1], TZ + Z_HANG], speed=0.10) + sk.hold(15) + drop = envs.obj_min_z(self.env, b) - (TZ + 0.012) + cur = sk.eef_pos() + self._go([cur[0], cur[1], cur[2] - drop], speed=0.08) + sk.set_gripper(False, steps=12) + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + Z_HANG], speed=0.15) + self._settle(b, 40) + return True + + def restand(self, i, gap=CAREFUL_GAP, err=None): + """stand bottle i up again on its spot: if the stopper cannot be grasped without the hand touching a standing + bottle or the small table, first lay the bottle down in free space; grasp the stopper, let the bottle hang, + carry it over the spot, lower it until its bottom is `gap` above the table top, let go""" + b, c = BOTTLES[i], COLOURS[i] + q, zg, yaw = self.stopper_grasp(b) + if self.grasp_clearance(q, zg, yaw, ignore=(b,)) < 0.005: + self.stage(b) + if not self.pick_stopper(b): + return False + tgt = self.spot_world(c)[:2] + (np.asarray(err, float) if err is not None else 0.0) + self.put_held(b, tgt, gap, z_carry=Z_HANG, v=0.10) + self._settle(b) + return self.on_spot(i) + + def place(self, i, gap, err=None, z_carry=Z_CARRY, yaw=0.0, v=0.2): + """one stage: pick bottle i (by the neck if it stands, by the stopper if it lies) and put it on its spot""" + b, c = BOTTLES[i], COLOURS[i] + tgt = self.spot_world(c)[:2] + (np.asarray(err, float) if err is not None else 0.0) + if self.upright(b): + if not self.pick_neck(b, z_carry=z_carry, yaw=yaw, v=v) and not self.pick_neck(b, z_carry=z_carry, + yaw=yaw, v=v): + return False + self.put_held(b, tgt, gap, z_carry=z_carry, yaw=yaw, v=v) + else: + if not self.pick_stopper(b): + return False + self.put_held(b, tgt, gap, z_carry=Z_HANG, v=0.10) + self._settle(b) + return True + + def repair_order(self, idx): + """bottles to fix: one standing upright off its spot first (it may be the heavy one: re-placing it rocks the + table), then lying ones whose stopper is easiest to reach""" + def key(j): + b = BOTTLES[j] + if self.upright(b): + return (0, 0.0) + q, zg, yaw = self.stopper_grasp(b) + return (1, -self.grasp_clearance(q, zg, yaw, ignore=(b,))) + return sorted(idx, key=key) + + def fix(self, i, gap=CAREFUL_GAP): + if self.upright(BOTTLES[i]): + self.place(i, gap) + else: + self.restand(i, gap) + + def check_and_repair(self, rounds=3, gap=CAREFUL_GAP): + """look at every bottle; stand up / re-place every one that is not on its spot""" + for _ in range(rounds): + bad = [i for i in range(4) if not self.on_spot(i)] + if not bad: + return True + for i in self.repair_order(bad): + if not self.on_spot(i): + self.fix(i, gap) + return all(self.stages()) + + def order(self, mode, rng=None, first=None): + o = self._far_first(self.inst["spot_of"], self.inst["supply_side"], *self.inst["table_xy"]) + if mode == "near_first": + o = o[::-1] + elif mode == "random": + o = [o[j] for j in rng.permutation(4)] + if first is not None: + o = [first] + [c for c in o if c != first] + return [COLOURS.index(c) for c in o] + + def execute(self, inst, params): + rng = np.random.default_rng(params.get("noise_seed", 0)) + order = self.order(params.get("order", "far_first"), rng, params.get("first")) + gap = params.get("gap") # None: random in NAIVE_GAP per placement + bias = np.array([float(params.get("bias_x", 0.0)), 0.0]) + rand = float(params.get("rand", 0.0)) + for i in order: + g = float(rng.uniform(*NAIVE_GAP)) if gap is None else float(gap) + e = bias + (rng.uniform(-rand, rand, 2) if rand else 0.0) + self.place(i, g, err=e, z_carry=params.get("z_carry", Z_CARRY), v=params.get("v", 0.2)) + if params.get("repair") == "each": # looks at all bottles after every step and stands fallen ones up + for _ in range(2): + bad = [j for j in range(4) if self.mon["ever"][j] and not self.on_spot(j)] + for j in self.repair_order(bad): + if not self.on_spot(j): + self.fix(j) + if params.get("check"): + self.check_and_repair() + self._lift_to(Z_CARRY) + self.sk.hold(10) + + # naive = Sonnet-like habits (lh_nudge_row / lh_bystander pilots): careful, far spots first, carries high, vertical + # descent, releases 1-4 cm above the surface, places ~1-2 cm too far forward +- 0.6 cm, no special plan for the + # table, does not look back at the bottles it has already put down + def default_params(self, inst): + return dict(order="far_first", gap=None, bias_x=float(inst["naive_bias_x"]), rand=NAIVE_RAND, + noise_seed=int(inst["seed"]) * 13, repair=None, check=False) + + def oracle_params(self, inst): + """knows the short leg: puts the heavy bottle on its corner first (the table rocks while nothing stands on it), + sets the others down gently, checks at the end""" + return dict(order="far_first", first=inst["heavy"], gap=CAREFUL_GAP, bias_x=0.0, rand=0.0, repair="each", + check=True) + + def adapt_params(self, inst, history): + """attempt >= 2: the bottle whose placement rocked the table (from the event of the failed attempt) first; the + same imprecise habits otherwise; stands fallen bottles up and checks at the end""" + first = None + for h in history: + for e in h["outcome"].get("events", []): + if e.get("event") == "table_rocked" and e.get("released"): + first = e["released"] + break + if first: + break + return dict(self.default_params(inst), first=first, repair="each", check=True) + + def blind_params(self, inst, attempt, rng): + """the naive behaviour with a random order and random variation, no history, no look back""" + return dict(self.default_params(inst), order="random", noise_seed=int(rng.integers(1 << 30)), + z_carry=float(rng.uniform(0.40, 0.45)), v=float(rng.uniform(0.12, 0.25)), + bias_x=float(rng.uniform(*NAIVE_BIAS))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """oracle / naive: one attempt. adaptive: attempt 1 = naive + stands fallen bottles up after every step and checks + at the end; attempts >= 2: the rocking bottle first. blind: naive with a random order. + Extra kinds (controls): naive_heavy_first (naive habits, 1-4 cm drops, but the heavy bottle first), + naive_repair (= adaptive's first attempt), naive_near_first, switch (order change only, no repair), + oracle_noise (+-5 mm).""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + single = ("oracle", "naive", "naive_heavy_first", "naive_repair", "oracle_noise", "naive_near_first") + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + params = (dict(self.default_params(inst), repair="each", check=True) if a == 0 else + self.adapt_params(inst, history)) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": + params = (self.default_params(inst) if a == 0 else + dict(self.adapt_params(inst, history), repair=None, check=False)) + elif kind == "naive_heavy_first": + params = dict(self.default_params(inst), first=inst["heavy"]) + elif kind == "naive_repair": + params = dict(self.default_params(inst), repair="each", check=True) + elif kind == "naive_near_first": + params = dict(self.default_params(inst), order="near_first") + elif kind == "oracle_noise": + params = dict(self.oracle_params(inst), rand=0.005, noise_seed=int(seed) * 7 + a) + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in single: + break + return history diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/scripts/agent_compare.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/scripts/agent_compare.py new file mode 100644 index 0000000000000000000000000000000000000000..4f53b5126adc0eadae0498f1de5e8a3fd60f0cdb --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/scripts/agent_compare.py @@ -0,0 +1,40 @@ +"""ΔICL between two agent run directories on the same seeds. + + python scripts/agent_compare.py --with runs/agent// --iid runs/agent// + +ΔICL = succ@k(with history) - pass@k_iid(independent retries), paired by instance seed, with a paired +bootstrap 95% interval. Also prints the analytic i.i.d. reference 1-(1-p1)^k from the 'with' run. +""" +import argparse +import json +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from lffbench.agent.metrics import paired_delta # noqa: E402 + + +def load(d): + with open(os.path.join(d, "summary.json")) as f: + return json.load(f) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--with", dest="with_", required=True) + ap.add_argument("--iid", required=True) + ap.add_argument("--k", type=int, default=None) + a = ap.parse_args() + w, i = load(a.with_), load(a.iid) + k = a.k or min(w["k"], i["k"]) + res = paired_delta(w["runs"], i["runs"], k) + res["k"] = k + res["with"] = dict(memory=w["memory"], feedback=w["feedback"], attempt1=w["aggregate"]["attempt1_success"], + pass_at_k_iid_analytic=w["aggregate"]["pass_at_k_iid_analytic"]) + res["iid"] = dict(memory=i["memory"], feedback=i["feedback"]) + print(json.dumps(res, indent=1)) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/scripts/check_desk_mechanisms.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/scripts/check_desk_mechanisms.py new file mode 100644 index 0000000000000000000000000000000000000000..4143afcf4ced634cd936a7a4007ddebba3af7ba2 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/scripts/check_desk_mechanisms.py @@ -0,0 +1,20 @@ +"""Physical controls for offset, covered access, and loss of support.""" +import argparse,copy,json +from pathlib import Path +from lffbench.tasks.lh_desk_organizer import DeskOrganizer,JARS +from check_compound_remaining import plain +p=argparse.ArgumentParser();p.add_argument('--n',type=int,default=5);p.add_argument('--out',required=True);a=p.parse_args();out=Path(a.out);out.mkdir(parents=True,exist_ok=True);t=DeskOrganizer();rows=[] +for seed in range(1000,1000+a.n): + i=t.sample_instance(seed);r=dict(seed=seed) + t.reset_instance(i);r['biased_grasp']=t.pick(JARS[0],tries=1,v=.15) + z=copy.deepcopy(i);z['bias']=[0,0,0];t.reset_instance(z);r['unbiased_grasp']=t.pick(JARS[0],tries=1,v=.15) + t.reset_instance(i);t.sk.correction=t.sk.bias.copy();r['covered_top_grasp']=t.top_book_probe() + z=copy.deepcopy(i);z['start']['green']=[-.20,.05];t.reset_instance(z);t.sk.correction=t.sk.bias.copy();r['uncovered_top_grasp']=t.top_book_probe() + for remove in (False,True): + t.reset_instance(i);t.sk.correction=t.sk.bias.copy();assert t.pick(JARS[0]);t.put(JARS[0],-.09,.14);assert t.pick(JARS[2]);t.put(JARS[2],.055,.13);t.sk.hold(80);t.top_book_probe();before=t.on_board(2) + if remove:t.move_book_out() + else:t.sk.hold(400) + t.sk.hold(150);r['removed_support' if remove else 'retained_support']=dict(mug_before=before,mug_after=t.on_board(2),tray_degrees=float(__import__('numpy').degrees(t.angle())),cause=t.mon['lost_cause'][2]) + r['pass']=bool(not r['biased_grasp'] and r['unbiased_grasp'] and not r['covered_top_grasp'] and r['uncovered_top_grasp'] and r['retained_support']['mug_before'] and r['retained_support']['mug_after'] and r['removed_support']['mug_before'] and not r['removed_support']['mug_after'] and r['removed_support']['cause']=='slid_off') + rows.append(r);(out/'progress.json').write_text(json.dumps(rows,indent=2,default=plain));print(json.dumps(r,default=plain),flush=True) +(out/'summary.json').write_text(json.dumps(dict(rows=rows,pass_count=sum(x['pass'] for x in rows)),indent=2,default=plain));t.env.close();assert all(x['pass'] for x in rows) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/scripts/check_lh_pantry_relatch.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/scripts/check_lh_pantry_relatch.py new file mode 100644 index 0000000000000000000000000000000000000000..d915b3137d888a2735e6b1b2b1e16fa85da3604a --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/scripts/check_lh_pantry_relatch.py @@ -0,0 +1,138 @@ +"""Physical checks for lh_pantry_relatch: confirm the latch-fatigue mechanism actually behaves as designed before +any acceptance validation. Not the formal n>=20 k=5 headroom run (see scripts/validate.py for that). + +Usage: + cd lffbench && source run_env.sh && OMP_NUM_THREADS=1 python scripts/check_lh_pantry_relatch.py mechanism + OMP_NUM_THREADS=1 python scripts/check_lh_pantry_relatch.py seeds --seeds 1000,1001,1002 --out +""" +import argparse +import copy +import hashlib +import json +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import numpy as np + +from lffbench import envs +from lffbench.tasks.lh_pantry_relatch import PantryRelatch + + +def source_hash(): + path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "lffbench", "tasks", + "lh_pantry_relatch.py") + return hashlib.sha256(open(path, "rb").read()).hexdigest() + + +def mechanism_check(seed=1000, out=None): + """Isolate the latch mechanism: close 1 (quick) should hold; close 2 (quick) should drift open on its own + during the settle window; close 2 (dwell) should hold. No bread/butter picking involved -- just the lid.""" + task = PantryRelatch() + rows = [] + for label, dwell1, dwell2 in [("quick_quick", False, False), ("quick_dwell", False, True)]: + inst = task.sample_instance(seed) + task.reset_instance(inst) + task.open_lid() + task.close_lid(dwell=dwell1) + after_close1 = task.lid_deg() + n = 0 + while n < 300: + task.sk.hold(10) + n += 10 + settled1 = task.lid_deg() + task.open_lid() + task.close_lid(dwell=dwell2) + after_close2 = task.lid_deg() + n = 0 + while n < 500: + task.sk.hold(10) + n += 10 + settled2 = task.lid_deg() + row = dict(label=label, dwell1=dwell1, dwell2=dwell2, after_close1_deg=round(after_close1, 2), + settled1_deg=round(settled1, 2), after_close2_deg=round(after_close2, 2), + settled2_deg=round(settled2, 2), closes_done=task.closes_done, + active_latch_final=round(task.active_latch, 4)) + rows.append(row) + print(row, flush=True) + print("expect: quick_quick settled2_deg clearly > quick_dwell settled2_deg (fatigue visible without dwell)") + if out: + with open(out, "w") as f: + json.dump(dict(rows=rows, source_sha256=source_hash()), f, indent=1) + return rows + + +def ablation_no_decay(seed=1000, out=None): + """Ablation: force DECAY=1.0 (no fatigue). Quick-release close 2 should then also hold.""" + import lffbench.tasks.lh_pantry_relatch as mod + orig = mod.DECAY + mod.DECAY = 1.0 + try: + task = PantryRelatch() + inst = task.sample_instance(seed) + task.reset_instance(inst) + task.open_lid() + task.close_lid(dwell=False) + task.open_lid() + task.close_lid(dwell=False) + n = 0 + while n < 500: + task.sk.hold(10) + n += 10 + settled2 = task.lid_deg() + row = dict(decay_forced=1.0, settled2_deg=round(settled2, 2), closes_done=task.closes_done) + print(row, flush=True) + finally: + mod.DECAY = orig + if out: + with open(out, "w") as f: + json.dump(row, f, indent=1) + return row + + +def full_episode(seed, kind, out_dir=None): + """Full pick-bread / put-butter episode with a given scripted policy kind.""" + task = PantryRelatch() + inst = task.sample_instance(seed) + hist = task.run_scripted(kind, inst, k=task.max_attempts, seed=seed) + for h in hist: + o = h["outcome"] + print(f"seed={seed} kind={kind} attempt={h['attempt']} success={o['success']} failure={o['failure']} " + f"closes_done={o['closes_done']} lid_final={o['lid_final_deg']} detail={o['detail']}", flush=True) + return hist + + +def seeds_check(seeds, out=None): + task_rows = {} + for seed in seeds: + rows = {} + for kind in ("oracle", "naive", "adaptive"): + hist = full_episode(seed, kind) + rows[kind] = [dict(attempt=h["attempt"], success=h["outcome"]["success"], + failure=h["outcome"]["failure"], closes_done=h["outcome"]["closes_done"], + lid_final_deg=h["outcome"]["lid_final_deg"]) for h in hist] + task_rows[seed] = rows + result = dict(seeds=seeds, rows=task_rows, source_sha256=source_hash()) + if out: + with open(out, "w") as f: + json.dump(result, f, indent=1) + return result + + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("mode", choices=["mechanism", "ablation", "seeds", "episode"]) + ap.add_argument("--seed", type=int, default=1000) + ap.add_argument("--seeds", type=str, default="1000,1001,1002") + ap.add_argument("--kind", type=str, default="oracle") + ap.add_argument("--out", type=str, default=None) + args = ap.parse_args() + if args.mode == "mechanism": + mechanism_check(args.seed, args.out) + elif args.mode == "ablation": + ablation_no_decay(args.seed, args.out) + elif args.mode == "episode": + full_episode(args.seed, args.kind) + elif args.mode == "seeds": + seeds_check([int(s) for s in args.seeds.split(",")], args.out) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/scripts/lerobot_replay.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/scripts/lerobot_replay.py new file mode 100644 index 0000000000000000000000000000000000000000..4c43a69bdb066327b27614bc9efda53d4a74e931 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/scripts/lerobot_replay.py @@ -0,0 +1,744 @@ +"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay +against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the +LeRobot export (scripts/lerobot_export.py). + + python scripts/lerobot_replay.py check [ ...] [--json out.json] # replay only, print fidelity + python scripts/lerobot_replay.py record --out [--res 256] + +Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot +commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite +is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly +like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same +outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width, +ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code +hashes equal the current files are expected to match (check_code()). + +Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB, +proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes: +protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode +per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the +fidelity check runs in record mode too. Per episode the recorder writes ///epNN/: + agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes) + frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase + sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel) + final_*.png, final.npz observation after the last control step (the state the outcome was judged in) + annotation.json episode annotation (build_annotation) +and ///replay.json (fidelity) when the whole run is done. +""" +import argparse +import ast +import hashlib +import importlib +import json +import math +import os +import pkgutil +import re +import shutil +import sys +import time +from collections import defaultdict + +import numpy as np + +LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, LFF_ROOT) + +from lffbench import envs # noqa: E402 +from lffbench import tasks as task_pkg # noqa: E402 +from lffbench.agent import camera as C # noqa: E402 +from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402 +from lffbench.task_base import TASKS # noqa: E402 + +for _m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{_m.name}") + +# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the +# task's outcome() check after `finish` (the arm holds still; not an agent action) +PHASES = {"move": 0, "gripper": 1, "judge": 2} +FPS = 20 +SCHEMA = "lff-replay-1" + +# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR" +ERROR_FLAGS = ("trap_fired", "recovered_in_attempt") +ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events", + "n_missed_strikes", "n_open_gripper_pushes") + + +def load_jsonl(p): + out = [] + if not os.path.exists(p): + return out + with open(p) as f: + for line in f: + line = line.strip() + if line: + try: + out.append(json.loads(line)) + except ValueError: + pass + return out + + +def norm_json(o): + return json.loads(json.dumps(o, default=_json_default)) + + +def sha256(p): + with open(p, "rb") as f: + return hashlib.sha256(f.read()).hexdigest() + + +def check_code(run_dir): + """[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract.""" + p = os.path.join(run_dir, "contract.json") + if not os.path.exists(p): + return [("contract.json", None, None)] + files = json.load(open(p))["contract"].get("server_code_files", {}) + bad = [] + for f, h in files.items(): + q = os.path.join(LFF_ROOT, f) + cur = sha256(q) if os.path.exists(q) else None + if cur != h: + bad.append((f, h, cur)) + return bad + + +def diff_json(a, b, path="", tol=0.0, out=None, limit=20): + """Differences between two JSON values (numbers compared with an absolute tolerance).""" + out = [] if out is None else out + if len(out) >= limit: + return out + if isinstance(a, dict) and isinstance(b, dict): + for k in sorted(set(a) | set(b)): + if k not in a or k not in b: + out.append((f"{path}.{k}", a.get(k, ""), b.get(k, ""))) + else: + diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit) + elif isinstance(a, list) and isinstance(b, list): + if len(a) != len(b): + out.append((path, f"len {len(a)}", f"len {len(b)}")) + else: + for i, (x, y) in enumerate(zip(a, b)): + diff_json(x, y, f"{path}[{i}]", tol, out, limit) + elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))): + if a != b: + out.append((path, a, b)) + elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))): + out.append((path, a, b)) + return out + + +def error_event(o): + """True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none.""" + if not isinstance(o, dict): + return None + keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o] + if not keys: + return None + return any(bool(o[k]) for k in ERROR_FLAGS if k in o) or any((o.get(k) or 0) > 0 for k in ERROR_COUNTS if k in o) + + +# ====================================================================================================== logs -> notes + +class RunLog: + """Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's + narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition.""" + + def __init__(self, run_dir, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run = os.path.basename(self.run_dir) + self.batch = os.path.basename(os.path.dirname(self.run_dir)) + self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl")) + self.start = next(e for e in self.ev if e["ev"] == "session_start") + self.calls, self.dones, self.harness_status = {}, [], [] + last = None + for e in self.ev: + if e["ev"] == "call": + self.calls[(int(e["attempt"]), int(e["step"]))] = e + last = e + elif e["ev"] == "done": + self.dones.append(e) + last = e + elif e["ev"] == "http" and last is not None and "think_s" not in last: + ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \ + (last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe")) + if ok: + last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s") + self.manifest = manifest or {} + self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {} + p = os.path.join(self.run_dir, "harness.json") + self.harness = json.load(open(p)) if os.path.exists(p) else {} + self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl")) + self._narration() + + # ---------------------------------------------------------------- agent narration + def _narration(self): + """notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one; + finish_notes[attempt] likewise for the agent's finish call; final_report = its last message.""" + self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", [] + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + attempt = 1 + + def take(): + nonlocal buf + out = {k: v for k, v in buf.items() if v} + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + return out + + last_msg = "" + for t in self.traj: + if t.get("kind") == "header": + self.headers.append(t.get("agent") or {}) + continue + if t.get("kind") != "step": + continue + if (t.get("message") or "").strip(): + buf["messages"].append(t["message"].strip()) + last_msg = t["message"].strip() + if (t.get("reasoning_content") or "").strip(): + buf["reasoning"].append(t["reasoning_content"].strip()) + res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])} + for c in t.get("tool_calls") or []: + fn, args = c.get("function_name"), c.get("arguments") or {} + if fn == "shell": + buf["shell"].append(str(args.get("command", ""))[:2000]) + elif fn == "view_images": + buf["viewed"].extend(args.get("paths") or []) + elif fn == "robot": + cmd = str(args.get("command", "")).strip() + r = res.get(c.get("tool_call_id")) or {} + try: + rep = json.loads(r.get("content") or "{}") + except ValueError: + rep = {} + word = cmd.split()[0] if cmd else "" + m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", ""))) + if word in ("move_eef", "observe") and m: + a, s = int(m.group(1)), int(m.group(2)) + n = take() + n["command"] = cmd + self.notes[(a, s)] = n + attempt = a + elif word in ("finish", "done"): + n = take() + n["command"] = cmd + n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)} + self.finish_notes.setdefault(attempt, n) + if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"): + attempt += 1 + # status / help / errors: their narration stays in the buffer for the next command + self.final_report = last_msg + + # ---------------------------------------------------------------- run-level labels + def attempts(self): + out = [] + for e in self.dones: + o = e.get("outcome") or {} + if isinstance(o, str): + try: + o = ast.literal_eval(o) + except (ValueError, SyntaxError): + o = {} + out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o, + reason=e.get("reason") or "")) + return sorted(out, key=lambda x: x["attempt"]) + + def condition(self): + s, en = self.start, self.entry + mem = s.get("memory", en.get("mem")) + chain = en.get("chain") + if mem == "full": + cond = "with_history" + elif chain: + cond = "memory_free_retry" + else: + cond = "independent_single_attempt" + return cond, chain + + def outcome_class(self): + """CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None.""" + att = self.attempts() + if not att or self.start.get("memory") != "full": + return None, "".join("S" if a["success"] else "F" for a in att) + hist = "".join("S" if a["success"] else "F" for a in att) + if att[0]["success"]: + ev = error_event(att[0]["outcome"]) + cls = "S?" if ev is None else ("IR" if ev else "CS") + else: + cls = "XR" if any(a["success"] for a in att) else "F" + return cls, hist + + def agent_info(self): + h, en = self.harness, self.entry + hdr = self.headers[0] if self.headers else {} + return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"), + harness_version=h.get("version") or hdr.get("version"), + harness_binary_sha256=(h.get("binary") or {}).get("sha256"), + model=h.get("model") or en.get("model") or hdr.get("model_name"), + effort=h.get("effort") or en.get("effort") or hdr.get("effort"), + provider=h.get("provider") or en.get("provider"), + codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"), + jail=en.get("jail")) + + +# ====================================================================================================== recording + +class EpisodeSink: + """Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed.""" + + def __init__(self, path): + self.path = path + os.makedirs(path, exist_ok=True) + self.w = None + self.num = defaultdict(list) + self.n = 0 + + def add(self, st, imgs): + import imageio + if self.w is None: + self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb", + pixelformat="rgb24", macro_block_size=1, + ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error") + for k in ("agentview", "wrist")] + for w, im in zip(self.w, imgs): + w.append_data(im) + for k, v in st.items(): + self.num[k].append(v) + self.n += 1 + + def close(self, final_state, final_imgs): + from PIL import Image + if self.w is not None: + for w in self.w: + w.close() + arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"} + np.savez(os.path.join(self.path, "frames.npz"), **arr) + if self.num.get("sim_state"): + np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64)) + np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()}) + for k, im in zip(("agentview", "wrist"), final_imgs): + Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png")) + + +class Recorder: + """Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink.""" + + def __init__(self, rp, res): + self.rp, self.res = rp, int(res) + self.active = False + self.sink = None + self.cur = dict(attempt=1, command=-1, phase=PHASES["move"]) + env = rp.task.env + self.env, self.rob = env, env.robots[0] + self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist")) + orig = env.step + + def step(a): + if self.active and self.sink is not None: + self.capture(np.asarray(a, np.float64)) + out = orig(a) + if self.active and self.sink is not None: + self.rp.poll_events(self.sink.n - 1) + return out + + env.step = step + + @property + def n(self): + return self.sink.n if self.sink is not None else 0 + + def state(self): + import robosuite.utils.transform_utils as T + env, rob = self.env, self.rob + d = env.sim.data + eef = np.array(d.site_xpos[rob.eef_site_id], np.float64) + q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw") + gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64) + try: + flat = np.asarray(env.sim.get_state().flatten(), np.float64) + except Exception: + flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64) + sk = self.rp.task.sk + return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64), + gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64), + joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64), + gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64), + eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)), + sim_time=np.float64(d.time), sim_state=flat) + + def images(self): + return [envs.render(self.env, c, self.res) for c in self.cams] + + def capture(self, a): + st = self.state() + st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]), + phase=np.int64(self.cur["phase"])) + self.sink.add(st, self.images()) + + +class RunReplay: + def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run_name = os.path.basename(self.run_dir) + self.log = RunLog(self.run_dir, manifest) + self.ev = self.log.ev + self.start = self.log.start + cp = os.path.join(self.run_dir, "contract.json") + self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {} + spec = self.contract.get("image_spec") or {} + self.image_res = int(spec.get("width", 512)) + self.code_diff = check_code(self.run_dir) + s = self.start + self.task = TASKS[s["task"]](cam_res=self.image_res) + inst = self.task.sample_instance(s["seed"]) + logged = s.get("inst") or {} + sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")}) + self.inst_diff = diff_json(sampled, logged, "inst") + if s.get("arm", "none") not in (None, "none") or logged.get("nominal"): + inst.update(logged) # controlled arms / nominal: the server overrode these instance fields + self.inst_diff = [] + self.inst = inst + self.protocol = getattr(self.task, "protocol", "cross") + self.k = int(s.get("k") or self.task.max_attempts) + self.attempt = 1 + self.mismatch = [] # (where, what, logged, replayed) + self.n_checked = 0 + self.max_dev_m = 0.0 + self.unfinished = None + self.rec = Recorder(self, res) if record else None + self.res = int(res) + self.out_root = out_root + self.n_mon = 0 + self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0 + self.episodes = [] # summaries of the written episodes + self.task.reset_instance(self.inst) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + sim = self.task.env.sim + bid = sim.model.body_name2id("robot0_base") + self.base_off = np.array(sim.data.body_xpos[bid], float).copy() + if self.rec: + self._open_episode() + + # ------------------------------------------------------------------ episodes + def _ep_dir(self): + return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}") + + def _open_episode(self): + self.rec.sink = EpisodeSink(self._ep_dir()) + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.rec.active = True + self.events, self.spans, self.ep_attempts = [], [], [] + self.ep_initial = self.rec.state() # state right after the reset (before frame 0) + + def close_episode(self): + if not self.rec: + self.ep_attempts = [] + return + sink = self.rec.sink + st = self.rec.state() + imgs = self.rec.images() + st.pop("sim_state", None) + sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs) + ann = build_annotation(self, sink) + with open(os.path.join(sink.path, "annotation.json"), "w") as f: + json.dump(ann, f, indent=1, default=_json_default) + self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n, + attempts=[a["attempt"] for a in self.ep_attempts])) + self.rec.active = False + self.rec.sink = None + self.ep_index += 1 + + # ------------------------------------------------------------------ monitor events (task-side error events) + def poll_events(self, frame): + mon = getattr(self.task, "mon", None) + evs = mon.get("events") if isinstance(mon, dict) else None + if not isinstance(evs, list): + return + if len(evs) < self.n_mon: # monitor was rebuilt + self.n_mon = 0 + for e in evs[self.n_mon:]: + self.events.append(dict(frame=int(frame), attempt=self.attempt, + event=norm_json(e) if isinstance(e, dict) else str(e))) + self.n_mon = len(evs) + + # ------------------------------------------------------------------ state as the server reports it + def proprio_la(self): + p = self.ex.proprio() + pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off] + return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"]) + + def compare(self, where, rep_logged, rep): + self.n_checked += 1 + for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"): + if k not in rep_logged or k not in rep: + continue + a, b = rep_logged[k], rep[k] + if k == "eef_pos": + dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float)))) + self.max_dev_m = max(self.max_dev_m, dev) + if dev > 1.5e-4: + self.mismatch.append((where, k, a, b)) + elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4): + self.mismatch.append((where, k, a, b)) + if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)): + self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok"))) + + def _span(self, e, f0, kind): + if self.rec: + self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0, + frame_end=self.rec.n)) + + # ------------------------------------------------------------------ commands (robot_server._handle_v2) + def move_eef(self, e): + args = e.get("args") or {} + where = f"a{e['attempt']}s{e['step']}" + logged = e.get("report") or {} + f0 = self.rec.n if self.rec else 0 + p = self.ex.proprio() + if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}: + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + off = self.base_off + try: + cur = np.asarray(p["eef_pos"], float) - off + tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")] + yaw = float(args.get("yaw", p["eef_yaw_deg"])) + speed = None if args.get("speed") in (None, "") else float(args["speed"]) + except (TypeError, ValueError): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + grip = args.get("gripper") + if grip not in (None, "open", "close"): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + moving = any(k in args for k in ("x", "y", "z", "yaw")) + tgt_w = np.asarray(tgt) + off + if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)): + self._span(e, f0, "rejected") + return self.compare(where, logged, dict(ok=False, **self.proprio_la())) + raw = {} + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"]) + if moving: + mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw) + if speed is not None: + mv["speed"] = speed + raw.update(self.ex.call("move_to", mv).report) + if grip is not None: + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"]) + raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report) + rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la()) + self.compare(where, logged, rep) + lr = e.get("raw") or {} + for k in ("holding_object", "touched_object"): + if k in lr and k in raw and bool(lr[k]) != bool(raw[k]): + self.mismatch.append((where, "raw." + k, lr[k], raw[k])) + self._span(e, f0, "move_eef") + + def observe(self, e): + f0 = self.rec.n if self.rec else 0 + self._span(e, f0, "observe") + + def done(self, e): + f0 = self.rec.n if self.rec else 0 + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"]) + out = self.task.outcome(self.inst) + succ = bool(out["success"]) + where = f"a{e['attempt']}done" + if succ != bool(e.get("success") in (True, "True")): + self.mismatch.append((where, "success", e.get("success"), succ)) + lo = e.get("outcome") or {} + ro = norm_json({k: v for k, v in out.items() if k != "feedback"}) + if isinstance(lo, dict): + for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8): + self.mismatch.append((where,) + d) + info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""), + feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")), + think_s=e.get("think_s")) + try: + info["feedback_f2"] = self.task.feedback(self.inst, out, "F2") + except Exception as ex_: + info["feedback_f2"] = f"" + if self.rec: + info["judge_frames"] = [f0, self.rec.n] + self.ep_attempts.append(info) + last = self.attempt >= self.k or succ or bool(out.get("terminal")) + if self.protocol == "cross" or last: + self.close_episode() + if last: + return True + self.attempt += 1 + if self.protocol == "cross": + self.task.reset_instance(self.inst) + self.n_mon = 0 + if self.rec: + self._open_episode() + elif self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + return False + + def run(self): + t0 = time.time() + finished = False + for e in self.ev: + if e["ev"] == "call": + if e.get("cmd") == "move_eef": + self.move_eef(e) + elif e.get("cmd") == "observe": + self.observe(e) + else: + self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None)) + elif e["ev"] == "done": + finished = self.done(e) + if finished: + break + self.unfinished = not finished + if not finished and self.rec and self.rec.sink is not None: + # the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged + if self.rec.n or self.ep_attempts: + self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True, + finish_reason="", feedback_shown="", auto_ended=False)) + self.close_episode() + else: + shutil.rmtree(self.rec.sink.path, ignore_errors=True) + self.rec.sink = None + self.wall_s = time.time() - t0 + return self + + def summary(self): + return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"], + protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff), + n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6), + unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1), + first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]]) + + +# ====================================================================================================== annotation + +def task_info(task, inst): + cls = type(task) + return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable", + category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"), + max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)), + instruction=cls.instruction) + + +def build_annotation(rp, sink): + """Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2 + failure description), run-level outcome class, every robot command with its frame span and the agent's narration, + task-side error events with frame indices.""" + log = rp.log + s = rp.start + cond, chain = log.condition() + cls, hist = log.outcome_class() + att_all = log.attempts() + attempts = [] + for a in rp.ep_attempts: + a = dict(a) + n = a["attempt"] + later = [x for x in att_all if x["attempt"] > n] + a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later)) + a["is_last_attempt_of_run"] = not later + fn = log.finish_notes.get(n) + if fn: + a["agent_finish"] = fn + a["error_event_in_attempt"] = error_event(a.get("outcome")) + attempts.append(a) + # post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command) + for a in attempts: + nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1]) + if a.get("success") is False and nxt: + note = log.notes[nxt[0]] + a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note} + commands = [] + for sp in rp.spans: + e = log.calls.get((sp["attempt"], sp["step"])) or {} + rep = e.get("report") or {} + c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"], + frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]), + args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"), + stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"), + gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"), + touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"), + agent_obs_images=rep.get("images")) + note = log.notes.get((sp["attempt"], sp["step"])) + if note: + c["agent_note"] = {k: v for k, v in note.items() if k != "command"} + commands.append(c) + t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x] + return dict( + schema=SCHEMA, + source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts], + episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain, + memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None), + feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"), + k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"), + contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256") + if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)), + agent=log.agent_info(), + task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"), + instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}), + run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all), + run_success=any(x["success"] for x in att_all) if att_all else None, + agent_final_report=log.final_report[:6000] or None, + mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)), + attempts=attempts, + commands=commands, + task_events=rp.events, + frames=dict(n=sink.n, fps=FPS, image_res=rp.res, + phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"], + joint_pos=rp.ep_initial["joint_pos"], + gripper_qpos=rp.ep_initial["gripper_qpos"])), + ) + + +# ====================================================================================================== CLI + +def load_manifest(run_dir): + p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json") + return json.load(open(p)) if os.path.exists(p) else {} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("mode", choices=["check", "record"]) + ap.add_argument("runs", nargs="+") + ap.add_argument("--json", default="") + ap.add_argument("--out", default="") + ap.add_argument("--res", type=int, default=256) + ap.add_argument("--force", action="store_true", help="record again even if replay.json exists") + a = ap.parse_args() + rows = [] + for r in a.runs: + r = r.rstrip("/") + try: + if a.mode == "check": + s = RunReplay(r, manifest=load_manifest(r)).run().summary() + else: + batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r) + rd = os.path.join(a.out, batch, name) + if os.path.exists(os.path.join(rd, "replay.json")) and not a.force: + print(json.dumps(dict(run=name, skipped="exists")), flush=True) + continue + shutil.rmtree(rd, ignore_errors=True) + rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run() + s = rp.summary() + s["episodes"] = rp.episodes + with open(os.path.join(rd, "replay.json"), "w") as f: + json.dump(s, f, indent=1) + except Exception: + import traceback + s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:]) + rows.append(s) + print(json.dumps(s), flush=True) + if a.json: + with open(a.json, "w") as f: + json.dump(rows, f, indent=1) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/scripts/make_video.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/scripts/make_video.py new file mode 100644 index 0000000000000000000000000000000000000000..f4bd60f3d819d908ea813c25f79acec08b6a3cd7 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/scripts/make_video.py @@ -0,0 +1,132 @@ +"""Record a scripted rollout of a task as an mp4 (agentview | wrist), with title cards between attempts. + +python scripts/make_video.py --task l1_bias_place --kind adaptive --seed 1000 +""" +import argparse +import importlib +import os +import pkgutil +import sys +import textwrap + +import numpy as np + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) + +import imageio # noqa: E402 +from PIL import Image, ImageDraw, ImageFont # noqa: E402 + +import lffbench.tasks as task_pkg # noqa: E402 +from lffbench import envs # noqa: E402 +from lffbench.task_base import TASKS # noqa: E402 + +for m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{m.name}") + +RES = 320 +FPS = 15 + + +def font(size): + try: + return ImageFont.load_default(size=size) + except TypeError: + return ImageFont.load_default() + + +def header(img, lines): + im = Image.fromarray(img) + d = ImageDraw.Draw(im) + d.rectangle([0, 0, im.width, 18 * len(lines) + 6], fill=(0, 0, 0)) + for i, s in enumerate(lines): + d.text((6, 3 + 18 * i), s, fill=(255, 255, 255), font=font(15)) + return np.asarray(im) + + +def card(lines, w, h, color=(20, 20, 20)): + im = Image.new("RGB", (w, h), color) + d = ImageDraw.Draw(im) + y = 20 + for s in lines: + for part in textwrap.wrap(s, 70) or [""]: + d.text((20, y), part, fill=(255, 255, 255), font=font(18)) + y += 24 + y += 6 + return np.asarray(im) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--task", required=True) + ap.add_argument("--kind", default="adaptive") + ap.add_argument("--seed", type=int, default=1000) + ap.add_argument("--k", type=int, default=5) + ap.add_argument("--every", type=int, default=3, help="record one frame every N control steps") + ap.add_argument("--out", default=None) + args = ap.parse_args() + + task = TASKS[args.task]() + env = task.env + inst = task.sample_instance(args.seed) + frames = [] + state = dict(n=0, attempt=1) + W = 2 * RES + + def grab(): + a = envs.render(env, "agentview", RES) + w = envs.render(env, "robot0_eye_in_hand", RES) + img = np.concatenate([a, w], axis=1) + return header(img, [f"{args.task} [{task.level}] policy={args.kind} seed={args.seed}", + f"attempt {state['attempt']} t={state['n'] * 0.05:5.1f}s (sim) left: agentview right: wrist"]) + + orig_step = env.step + + def step(a): + out = orig_step(a) + state["n"] += 1 + if state["n"] % args.every == 0: + frames.append(grab()) + return out + + env.step = step + + def on_attempt(a, params, out): + txt = [f"Attempt {a + 1}: {'SUCCESS' if out['success'] else 'FAILED'}"] + if out.get("detail"): + txt.append("Feedback (F2): " + out["detail"]) + p = {k: (round(v, 3) if isinstance(v, float) else v) for k, v in (params or {}).items() + if not isinstance(v, (list, dict)) or len(str(v)) < 120} + if p: + txt.append(f"params: {p}") + if not out["success"]: + txt.append(f"-> attempt {a + 2}") + frames.extend([card(txt, W, RES, (40, 20, 20) if not out["success"] else (20, 50, 20))] * (FPS * 3)) + state["attempt"] = a + 2 + + intro = card([f"Task: {args.task} (level {task.level}; capabilities: {', '.join(task.capabilities)})", + f"Instruction: {task.instruction}", + f"Policy: {args.kind} (scripted reference)", + "Hidden variables are not visible to the policy."], W, RES) + frames.extend([intro] * (FPS * 3)) + task.reset_instance(inst) + frames.append(grab()) + n_cards_before = len(frames) + hist = task.run_scripted(args.kind, inst, k=args.k, seed=args.seed, on_attempt=on_attempt) + # tasks whose run_scripted does not call on_attempt: summarise at the end + if not any(f is not None and f.shape[0] == RES and (f[5, 5] == np.array([40, 20, 20])).all() for f in frames[n_cards_before:]) \ + and not any((f[5, 5] == np.array([20, 50, 20])).all() for f in frames[n_cards_before:]): + lines = [] + for h in hist: + o = h["outcome"] + lines.append(f"Attempt {h['attempt']}: {'SUCCESS' if o['success'] else 'FAILED'} — {o.get('detail', '')}") + frames.extend([card(lines[-6:], W, RES)] * (FPS * 4)) + out = args.out or os.path.join(ROOT, "videos", f"{args.task}_{args.kind}_s{args.seed}.mp4") + os.makedirs(os.path.dirname(out), exist_ok=True) + imageio.mimwrite(out, frames, fps=FPS, quality=7, macro_block_size=8) + first = next((h["attempt"] for h in hist if h["outcome"]["success"]), None) + print(f"wrote {out} frames={len(frames)} attempts={len(hist)} first_success={first}") + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/scripts/start_robot_session.sh b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/scripts/start_robot_session.sh new file mode 100644 index 0000000000000000000000000000000000000000..998586e07e8eae302b64797e0d4a2d12d7157c7b --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/scripts/start_robot_session.sh @@ -0,0 +1,24 @@ +#!/bin/bash +# Start a robot server + isolated sandbox for one task instance. +# usage: scripts/start_robot_session.sh [instruction direct|indirect] [k] [tag] [perception depth|rgb] [video 0|1] +# The sandbox gets an opaque random name (no task / condition in the path); the readable run name is only in LOG. +set -e +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +TASK=$1; SEED=$2; MEM=$3; FB=$4; PORT=$5; INSTR=${6:-direct}; K=${7:-}; TAG=${8:-}; PERC=${9:-depth}; VID=${10:-0} +RUN=${TAG:+${TAG}_}${TASK}_s${SEED}_${MEM}_${FB}_${INSTR}_k${K:-d}_$(date +%m%d-%H%M%S)_p${PORT} +SANDBOX=${LFF_SANDBOX_ROOT:-/tmp/robotlab}/$(python3 -c 'import secrets;print(secrets.token_hex(6))') +LOG=${LFF_RUNS_DIR:-$ROOT/runs/claude}/$RUN +mkdir -p "$SANDBOX" "$LOG" +cd "$ROOT" && source run_env.sh && export OMP_NUM_THREADS=1 +KARG=""; [ -n "$K" ] && KARG="--k $K" +VARG=""; [ "$VID" = "1" ] && VARG="--video $LOG/rollout.mp4" +nohup python -m lffbench.agent.robot_server --task "$TASK" --seed "$SEED" --memory "$MEM" --feedback "$FB" \ + --instruction "$INSTR" --port "$PORT" --sandbox "$SANDBOX" --log-dir "$LOG" --perception "$PERC" --style "${LFF_STYLE:-v1}" ${LFF_EXTRA_ARGS:-} $KARG $VARG > "$LOG/server.log" 2>&1 & +echo $! > "$LOG/server.pid" +# wait for the scene (long-horizon scenes on a loaded machine took > 2 min, 2026-10-20); on failure stop the server +# so that it does not keep the port +for i in $(seq 1 "${LFF_SERVER_WAIT_S:-600}"); do [ -f "$LOG/READY" ] && break; sleep 1; done +[ -f "$LOG/READY" ] || { echo "server failed"; tail -20 "$LOG/server.log"; kill "$(cat "$LOG/server.pid")" 2>/dev/null; exit 1; } +echo "{\"run\": \"$RUN\", \"sandbox\": \"$SANDBOX\", \"port\": $PORT}" > "$LOG/session.json" +echo "SANDBOX=$SANDBOX" +echo "LOG=$LOG" diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/scripts/summarize.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/scripts/summarize.py new file mode 100644 index 0000000000000000000000000000000000000000..5ceda683353fb938c1e8a219552c088181c197c2 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/scripts/summarize.py @@ -0,0 +1,33 @@ +"""Aggregate results//validate.json into results/SUMMARY.md (headroom table).""" +import glob +import json +import os + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +def main(): + rows = [] + for p in sorted(glob.glob(os.path.join(ROOT, "results", "*", "validate.json"))): + r = json.load(open(p)) + s = r["succ_at_k"] + + def g(kind, j): + v = s.get(kind) + return "—" if v is None else f"{100 * v[j - 1]:.0f}" + + k = r["k"] + rows.append(f"| {r['task']} | {r['level']} | {', '.join(r['capabilities'])} | {r['n']} | " + f"{g('oracle', 1)} | {g('naive', 1)} | {g('adaptive', 1)} / {g('adaptive', 2)} / {g('adaptive', k)} | " + f"{g('blind', k)} | {r.get('seconds', 0) / 60:.0f} min |") + head = ("| task | level | capabilities | n | oracle@1 | naive@1 | adaptive @1/@2/@k | blind@k | wall |\n" + "|---|---|---|---|---|---|---|---|---|") + text = "# LFF-Bench headroom validation (scripted reference policies)\n\n" + head + "\n" + "\n".join(rows) + "\n" + out = os.path.join(ROOT, "results", "SUMMARY.md") + with open(out, "w") as f: + f.write(text) + print(text) + + +if __name__ == "__main__": + main()