Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- leaf/code/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lerobot_export.py +431 -0
- leaf/code/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lerobot_replay.py +744 -0
- leaf/code/compound-lh-20261102-clh_20261102_deepseek/lerobot_export.py +431 -0
- leaf/code/compound-lh-20261102-clh_20261102_deepseek/lerobot_replay.py +744 -0
- leaf/code/compound-lh-20261102-clh_20261102_gpt/lerobot_export.py +431 -0
- leaf/code/compound-lh-20261102-clh_20261102_gpt/lerobot_replay.py +744 -0
- leaf/code/compound-lh-20261102-clh_20261102_sonnet/lerobot_export.py +431 -0
- leaf/code/compound-lh-20261102-clh_20261102_sonnet/lerobot_replay.py +744 -0
- leaf/code/remaining-lh-20261103-remaining_lh_20261103_deepseek/lerobot_export.py +431 -0
- leaf/code/remaining-lh-20261103-remaining_lh_auto_001_opus/lerobot_export.py +431 -0
- leaf/code/remaining-lh-20261103-remaining_lh_auto_001_opus/lerobot_replay.py +744 -0
- leaf/code/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lerobot_export.py +431 -0
- leaf/code/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lerobot_replay.py +744 -0
- leaf/code/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lerobot_export.py +431 -0
- leaf/code/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lerobot_replay.py +744 -0
- leaf/code/supp-20261113-g61_evofull_20261025/lerobot_export.py +431 -0
- leaf/code/supp-20261113-g61_evofull_20261025/lerobot_replay.py +744 -0
- leaf/code/supp-20261113-g61_evosub_2_20261026/lerobot_export.py +431 -0
- leaf/code/supp-20261113-g61_evosub_3_20261026/lerobot_export.py +431 -0
- leaf/code/supp-20261113-rcc_dev09_sonnet_20261111/lerobot_export.py +431 -0
- leaf/code/supp-20261113-rcc_dev09_sonnet_20261111/lerobot_replay.py +744 -0
- leaf/code/v1.5/backfill-20261102-l4i_fx_test/lerobot_export.py +431 -0
- leaf/code/v1.5/backfill-20261102-l4i_fx_test/lerobot_replay.py +744 -0
- leaf/code/v1.5/backfill-20261102-l4i_v_test/lerobot_export.py +431 -0
- leaf/code/v1.5/backfill-20261102-l4i_v_test/lerobot_replay.py +744 -0
- leaf/code/v1.5/backfill-20261102-lf2_sonnet_r2/lerobot_replay.py +744 -0
- leaf/code/v1.5/v1.4/prepare_verified.py +29 -0
- leaf/code/v1.5/v1.4/run.sh +35 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/backends/chat_completions.py +150 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/fakeapi.py +188 -0
- 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 +15 -0
- 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 +27 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/real/executor.py +138 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/client/lffbench_client/__init__.py +139 -0
- 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 +15 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/__init__.py +0 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/l2_restore_layout.py +502 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/l6_count.py +562 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/lh_bystander.py +830 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/agent_viewer/README.md +150 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/agent_viewer/export.py +219 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/tools.py +392 -0
- leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/agent/__init__.py +1 -0
- leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/l5_iterative.py +136 -0
- leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/agent_compare.py +40 -0
- leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/check_breakfast_mechanisms.py +79 -0
- leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/full_report.py +89 -0
- leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/harness_run.py +431 -0
- leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/lerobot_export.py +431 -0
- leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/lerobot_replay.py +744 -0
leaf/code/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lerobot_export.py
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars.
|
| 2 |
+
|
| 3 |
+
Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding
|
| 4 |
+
can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan):
|
| 5 |
+
|
| 6 |
+
python scripts/lerobot_export.py plan --raw <raw_root>[,<raw_root2>] --runs-root <lffbench>/runs/api \
|
| 7 |
+
--paper <paper/latex> --task-set <lffbench>/sets/main_v2_1inst.txt --work <work_dir> [--batches ...] [--limit N]
|
| 8 |
+
python scripts/lerobot_export.py shard --work <work_dir> --shard i --nshards N
|
| 9 |
+
python scripts/lerobot_export.py merge --work <work_dir> --nshards N --out <dataset_root>
|
| 10 |
+
|
| 11 |
+
Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0
|
| 12 |
+
mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped.
|
| 13 |
+
|
| 14 |
+
LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t):
|
| 15 |
+
observation.images.image agentview RGB 256x256 (upright; LIBERO naming)
|
| 16 |
+
observation.images.wrist_image wrist (eye-in-hand) RGB 256x256
|
| 17 |
+
observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout)
|
| 18 |
+
observation.joint_pos / joint_vel 7 arm joints (rad, rad/s)
|
| 19 |
+
observation.eef_quat 4: xyzw; observation.gripper_width 1 (m)
|
| 20 |
+
action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad),
|
| 21 |
+
gripper (-1 open, +1 close)
|
| 22 |
+
annotation.attempt_index attempt (1-based) the frame belongs to
|
| 23 |
+
annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`)
|
| 24 |
+
annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action)
|
| 25 |
+
annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt
|
| 26 |
+
annotation.task_event number of task-monitor events (error / progress events) registered at this step
|
| 27 |
+
Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table),
|
| 28 |
+
runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state
|
| 29 |
+
per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/.
|
| 30 |
+
"""
|
| 31 |
+
import argparse
|
| 32 |
+
import glob
|
| 33 |
+
import json
|
| 34 |
+
import os
|
| 35 |
+
import re
|
| 36 |
+
import shutil
|
| 37 |
+
import time
|
| 38 |
+
|
| 39 |
+
import numpy as np
|
| 40 |
+
|
| 41 |
+
FPS = 20
|
| 42 |
+
RES = 256
|
| 43 |
+
BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke",
|
| 44 |
+
"cc_smoke", "cc_opus_smoke"]
|
| 45 |
+
BATCH_NOTES = {
|
| 46 |
+
"cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog",
|
| 47 |
+
"cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267",
|
| 48 |
+
"cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299",
|
| 49 |
+
"cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances",
|
| 50 |
+
"cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)",
|
| 51 |
+
"cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the "
|
| 52 |
+
"with-history continuation of failed runs is incomplete",
|
| 53 |
+
"cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early",
|
| 54 |
+
"cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt",
|
| 55 |
+
"cc_opus_smoke": "smoke test: single attempt",
|
| 56 |
+
}
|
| 57 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 58 |
+
CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)",
|
| 59 |
+
"L2": "disturbed state to restore (incl. damage the agent causes)",
|
| 60 |
+
"L3": "infeasible manipulation strategy (grasp / contact / tool must change)",
|
| 61 |
+
"L4": "misjudged geometry (size, shape, fit, hidden structure)",
|
| 62 |
+
"L5": "misjudged physics (mass distribution, friction, dynamics)"}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def features():
|
| 66 |
+
vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]}
|
| 67 |
+
f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names}
|
| 68 |
+
i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None}
|
| 69 |
+
return {
|
| 70 |
+
"observation.images.image": vid(),
|
| 71 |
+
"observation.images.wrist_image": vid(),
|
| 72 |
+
"observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z",
|
| 73 |
+
"finger_qpos_left", "finger_qpos_right"]),
|
| 74 |
+
"observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 75 |
+
"observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 76 |
+
"observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]),
|
| 77 |
+
"observation.gripper_width": f32(1, ["width_m"]),
|
| 78 |
+
"action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y",
|
| 79 |
+
"eef_delta_rot_aa_z", "gripper_close"]),
|
| 80 |
+
"annotation.attempt_index": i64(),
|
| 81 |
+
"annotation.command_index": i64(),
|
| 82 |
+
"annotation.phase": i64(),
|
| 83 |
+
"annotation.attempt_success": i64(),
|
| 84 |
+
"annotation.task_event": i64(),
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ------------------------------------------------------------------------------------------------ paper metadata
|
| 89 |
+
|
| 90 |
+
def _clean_tex(s):
|
| 91 |
+
s = re.sub(r"%.*", "", s)
|
| 92 |
+
for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"),
|
| 93 |
+
(r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"),
|
| 94 |
+
(r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"),
|
| 95 |
+
(r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"),
|
| 96 |
+
(r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]:
|
| 97 |
+
s = re.sub(a, b, s)
|
| 98 |
+
s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s)
|
| 99 |
+
s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s)
|
| 100 |
+
for _ in range(3):
|
| 101 |
+
s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s)
|
| 102 |
+
s = re.sub(r"\$([^$]*)\$", r"\1", s)
|
| 103 |
+
s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ")
|
| 104 |
+
s = re.sub(r"\{([^{}]*)\}", r"\1", s)
|
| 105 |
+
s = re.sub(r"\\[a-zA-Z]+\*?", "", s)
|
| 106 |
+
return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def paper_tasks(paper_dir):
|
| 110 |
+
"""{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the
|
| 111 |
+
paper's task table and task appendix (empty if the paper sources are not there)."""
|
| 112 |
+
out = {}
|
| 113 |
+
if not paper_dir:
|
| 114 |
+
return out
|
| 115 |
+
app = os.path.join(paper_dir, "sections", "appendix_tasks.tex")
|
| 116 |
+
tab = os.path.join(paper_dir, "sections", "tab_tasks.tex")
|
| 117 |
+
if os.path.exists(app):
|
| 118 |
+
txt = open(app).read()
|
| 119 |
+
parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt)
|
| 120 |
+
for i in range(1, len(parts) - 1, 2):
|
| 121 |
+
if parts[i] != "\\paragraph{":
|
| 122 |
+
continue
|
| 123 |
+
body = parts[i + 1]
|
| 124 |
+
m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S)
|
| 125 |
+
if not m:
|
| 126 |
+
continue
|
| 127 |
+
name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip()
|
| 128 |
+
desc = _clean_tex(body[m.end():])
|
| 129 |
+
out[code] = dict(name=name, cause=_clean_tex(cause), description=desc)
|
| 130 |
+
if os.path.exists(tab):
|
| 131 |
+
names = {v["name"].lower(): k for k, v in out.items()}
|
| 132 |
+
for line in open(tab):
|
| 133 |
+
cells = [c.strip() for c in line.split("&")]
|
| 134 |
+
if len(cells) != 6 or not cells[-1].endswith("\\\\"):
|
| 135 |
+
continue
|
| 136 |
+
nm = re.sub(r"\\contscene", "", cells[0]).strip().lower()
|
| 137 |
+
code = names.get(nm)
|
| 138 |
+
if not code:
|
| 139 |
+
continue
|
| 140 |
+
out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]),
|
| 141 |
+
repair_within_attempt=_clean_tex(cells[3]) == "yes",
|
| 142 |
+
oracle_first_attempt_pct=_clean_tex(cells[4]),
|
| 143 |
+
naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip()))
|
| 144 |
+
return out
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
# ------------------------------------------------------------------------------------------------ collection
|
| 148 |
+
|
| 149 |
+
def manifest_status(runs_root, batch, run, cache={}):
|
| 150 |
+
if batch not in cache:
|
| 151 |
+
p = os.path.join(runs_root, batch, "manifest.json")
|
| 152 |
+
cache[batch] = json.load(open(p)) if os.path.exists(p) else {}
|
| 153 |
+
m = cache[batch]
|
| 154 |
+
for r in m.get("runs", []):
|
| 155 |
+
if r.get("run") == run:
|
| 156 |
+
return r.get("status", "?"), r
|
| 157 |
+
for r in m.get("superseded", []):
|
| 158 |
+
if r.get("run") == run:
|
| 159 |
+
return "superseded_" + str(r.get("status", "?")), r
|
| 160 |
+
return "not_in_manifest", {}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def collect(raw_roots, runs_root, batches, task_order):
|
| 164 |
+
"""Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root."""
|
| 165 |
+
eps, rejected, seen = [], [], set()
|
| 166 |
+
for root in raw_roots:
|
| 167 |
+
for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))):
|
| 168 |
+
rep = json.load(open(rj))
|
| 169 |
+
batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"]
|
| 170 |
+
if (batches and batch not in batches) or (batch, run) in seen:
|
| 171 |
+
continue
|
| 172 |
+
seen.add((batch, run))
|
| 173 |
+
ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff")
|
| 174 |
+
status, entry = manifest_status(runs_root, batch, run)
|
| 175 |
+
if not ok:
|
| 176 |
+
never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked")
|
| 177 |
+
rejected.append(dict(run=run, batch=batch, run_status=status,
|
| 178 |
+
reason="run never started (no contract, no robot command)" if never else
|
| 179 |
+
"replay does not reproduce the log (the log has gaps or the replay diverged)",
|
| 180 |
+
detail=rep.get("first_mismatches")))
|
| 181 |
+
continue
|
| 182 |
+
for ep in rep.get("episodes", []):
|
| 183 |
+
d = os.path.join(root, ep["dir"])
|
| 184 |
+
ann = json.load(open(os.path.join(d, "annotation.json")))
|
| 185 |
+
judged = [a for a in ann["attempts"] if a.get("success") is not None]
|
| 186 |
+
if not judged or ep["n_frames"] == 0:
|
| 187 |
+
rejected.append(dict(run=run, batch=batch, episode=ep["dir"],
|
| 188 |
+
reason="no judged attempt" if not judged else "no frames"))
|
| 189 |
+
continue
|
| 190 |
+
ann["source"]["run_status"] = status
|
| 191 |
+
ann["source"]["manifest_id"] = entry.get("id")
|
| 192 |
+
ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"],
|
| 193 |
+
max_eef_dev_m=rep["max_eef_dev_m"])
|
| 194 |
+
key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99),
|
| 195 |
+
{"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2),
|
| 196 |
+
ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"])
|
| 197 |
+
eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann))
|
| 198 |
+
eps.sort(key=lambda x: x["key"])
|
| 199 |
+
return eps, rejected
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# ------------------------------------------------------------------------------------------------ writing
|
| 203 |
+
|
| 204 |
+
def frames_of(path):
|
| 205 |
+
import av
|
| 206 |
+
with av.open(path) as c:
|
| 207 |
+
for fr in c.decode(video=0):
|
| 208 |
+
yield fr.to_ndarray(format="rgb24")
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def flat_row(i, ann, n, idx0):
|
| 212 |
+
s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"]
|
| 213 |
+
att = ann["attempts"]
|
| 214 |
+
a0 = att[0]
|
| 215 |
+
return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n,
|
| 216 |
+
batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"],
|
| 217 |
+
memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"),
|
| 218 |
+
episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att],
|
| 219 |
+
harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"),
|
| 220 |
+
effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"),
|
| 221 |
+
task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"),
|
| 222 |
+
category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"],
|
| 223 |
+
success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att],
|
| 224 |
+
feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att],
|
| 225 |
+
auto_ended=[a.get("auto_ended") for a in att],
|
| 226 |
+
corrected_later_in_run=[a.get("corrected_later_in_run") for a in att],
|
| 227 |
+
error_event_in_attempt=[a.get("error_event_in_attempt") for a in att],
|
| 228 |
+
run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"),
|
| 229 |
+
n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]),
|
| 230 |
+
first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def cmd_plan(a):
|
| 234 |
+
task_order = {}
|
| 235 |
+
if a.task_set and os.path.exists(a.task_set):
|
| 236 |
+
for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")):
|
| 237 |
+
task_order[line.split(":")[0].strip()] = i
|
| 238 |
+
batches = [b for b in a.batches.split(",") if b] if a.batches else None
|
| 239 |
+
eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order)
|
| 240 |
+
if a.limit:
|
| 241 |
+
eps = eps[:a.limit]
|
| 242 |
+
paper = paper_tasks(a.paper)
|
| 243 |
+
idx0 = 0
|
| 244 |
+
for i, e in enumerate(eps):
|
| 245 |
+
ann = e["ann"]
|
| 246 |
+
tname = ann["task"]["name"]
|
| 247 |
+
if tname in paper:
|
| 248 |
+
ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"}
|
| 249 |
+
ann["episode_index"] = i
|
| 250 |
+
ann["dataset_index_range"] = [idx0, idx0 + e["n"]]
|
| 251 |
+
e["index"], e["from"] = i, idx0
|
| 252 |
+
idx0 += e["n"]
|
| 253 |
+
del e["key"]
|
| 254 |
+
os.makedirs(a.work, exist_ok=True)
|
| 255 |
+
with open(os.path.join(a.work, "plan.json"), "w") as f:
|
| 256 |
+
json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f,
|
| 257 |
+
ensure_ascii=False)
|
| 258 |
+
print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def shard_range(n_eps, i, k):
|
| 262 |
+
return (n_eps * i) // k, (n_eps * (i + 1)) // k
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def cmd_shard(a):
|
| 266 |
+
from lerobot.datasets.lerobot_dataset import LeRobotDataset
|
| 267 |
+
t0 = time.time()
|
| 268 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 269 |
+
eps = plan["episodes"]
|
| 270 |
+
lo, hi = shard_range(len(eps), a.shard, a.nshards)
|
| 271 |
+
out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}")
|
| 272 |
+
if os.path.exists(os.path.join(out, "DONE")):
|
| 273 |
+
print(f"shard {a.shard}: done already", flush=True)
|
| 274 |
+
return
|
| 275 |
+
shutil.rmtree(out, ignore_errors=True)
|
| 276 |
+
ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out,
|
| 277 |
+
robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads,
|
| 278 |
+
vcodec=a.vcodec)
|
| 279 |
+
nfr = 0
|
| 280 |
+
for e in eps[lo:hi]:
|
| 281 |
+
d, ann, n = e["dir"], e["ann"], e["n"]
|
| 282 |
+
fr = np.load(os.path.join(d, "frames.npz"))
|
| 283 |
+
assert len(fr["action"]) == n, d
|
| 284 |
+
succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]}
|
| 285 |
+
evc = np.zeros(n, np.int64)
|
| 286 |
+
for ev in ann["task_events"]:
|
| 287 |
+
if 0 <= ev["frame"] < n:
|
| 288 |
+
evc[ev["frame"]] += 1
|
| 289 |
+
state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32)
|
| 290 |
+
instr = ann["task"]["instruction"]
|
| 291 |
+
k = 0
|
| 292 |
+
for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))):
|
| 293 |
+
if k >= n:
|
| 294 |
+
break
|
| 295 |
+
ds.add_frame({
|
| 296 |
+
"observation.images.image": img, "observation.images.wrist_image": wr,
|
| 297 |
+
"observation.state": state[k],
|
| 298 |
+
"observation.joint_pos": fr["joint_pos"][k].astype(np.float32),
|
| 299 |
+
"observation.joint_vel": fr["joint_vel"][k].astype(np.float32),
|
| 300 |
+
"observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32),
|
| 301 |
+
"observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32),
|
| 302 |
+
"action": fr["action"][k].astype(np.float32),
|
| 303 |
+
"annotation.attempt_index": np.array([fr["attempt"][k]], np.int64),
|
| 304 |
+
"annotation.command_index": np.array([fr["command"][k]], np.int64),
|
| 305 |
+
"annotation.phase": np.array([fr["phase"][k]], np.int64),
|
| 306 |
+
"annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64),
|
| 307 |
+
"annotation.task_event": np.array([evc[k]], np.int64),
|
| 308 |
+
"task": instr,
|
| 309 |
+
})
|
| 310 |
+
k += 1
|
| 311 |
+
if k != n:
|
| 312 |
+
raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames")
|
| 313 |
+
ds.save_episode()
|
| 314 |
+
nfr += n
|
| 315 |
+
ds.finalize()
|
| 316 |
+
shutil.rmtree(os.path.join(out, "images"), ignore_errors=True)
|
| 317 |
+
open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n")
|
| 318 |
+
print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def cmd_merge(a):
|
| 322 |
+
from pathlib import Path
|
| 323 |
+
from lerobot.datasets.aggregate import aggregate_datasets
|
| 324 |
+
t0 = time.time()
|
| 325 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 326 |
+
eps = plan["episodes"]
|
| 327 |
+
roots, ids = [], []
|
| 328 |
+
for i in range(a.nshards):
|
| 329 |
+
lo, hi = shard_range(len(eps), i, a.nshards)
|
| 330 |
+
if hi <= lo:
|
| 331 |
+
continue
|
| 332 |
+
r = os.path.join(a.work, "shards", f"shard_{i:03d}")
|
| 333 |
+
if not os.path.exists(os.path.join(r, "DONE")):
|
| 334 |
+
raise SystemExit(f"shard {i} is not done")
|
| 335 |
+
roots.append(Path(r))
|
| 336 |
+
ids.append(f"{plan['repo_id']}-shard{i:03d}")
|
| 337 |
+
if os.path.exists(a.out):
|
| 338 |
+
raise SystemExit(f"{a.out} exists; refusing to overwrite")
|
| 339 |
+
aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out))
|
| 340 |
+
print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True)
|
| 341 |
+
write_sidecars(a, plan)
|
| 342 |
+
print(f"merge done in {time.time() - t0:.0f}s", flush=True)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def write_sidecars(a, plan):
|
| 346 |
+
eps, paper = plan["episodes"], plan["paper"]
|
| 347 |
+
lff = os.path.join(a.out, "lff")
|
| 348 |
+
for sub in ("annotations", "sim_state", "final", "code"):
|
| 349 |
+
os.makedirs(os.path.join(lff, sub), exist_ok=True)
|
| 350 |
+
rows, runs, tasks = [], {}, {}
|
| 351 |
+
for e in eps:
|
| 352 |
+
i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"]
|
| 353 |
+
name = f"episode_{i:06d}"
|
| 354 |
+
if os.path.exists(os.path.join(d, "sim_state.npy")):
|
| 355 |
+
shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy"))
|
| 356 |
+
shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz"))
|
| 357 |
+
for cam, key in (("agentview", "image"), ("wrist", "wrist_image")):
|
| 358 |
+
shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png"))
|
| 359 |
+
with open(os.path.join(lff, "annotations", name + ".json"), "w") as f:
|
| 360 |
+
json.dump(ann, f, indent=1, ensure_ascii=False)
|
| 361 |
+
rows.append(flat_row(i, ann, n, e["from"]))
|
| 362 |
+
tname = ann["task"]["name"]
|
| 363 |
+
rk = (ann["source"]["batch"], ann["source"]["run"])
|
| 364 |
+
r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"),
|
| 365 |
+
run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"],
|
| 366 |
+
memory_free_chain_of=ann["source"].get("memory_free_chain_of"),
|
| 367 |
+
memory_free_rep=ann["source"].get("memory_free_rep"), task=tname,
|
| 368 |
+
seed=ann["task"]["seed"], model=ann["agent"].get("model"),
|
| 369 |
+
harness=ann["agent"].get("harness"),
|
| 370 |
+
harness_version=ann["agent"].get("harness_version"),
|
| 371 |
+
codex_catalog=ann["agent"].get("codex_catalog"),
|
| 372 |
+
outcome_class=ann["run_outcome"].get("outcome_class"),
|
| 373 |
+
attempt_history=ann["run_outcome"].get("attempt_history"),
|
| 374 |
+
agent_final_report=ann["run_outcome"].get("agent_final_report"),
|
| 375 |
+
episodes=[]))
|
| 376 |
+
for x in ann["attempts"]:
|
| 377 |
+
r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success")))
|
| 378 |
+
if tname not in tasks:
|
| 379 |
+
tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")}
|
| 380 |
+
if tname in paper:
|
| 381 |
+
tasks[tname]["paper"] = paper[tname]
|
| 382 |
+
tasks[tname]["instances"] = {}
|
| 383 |
+
tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"]
|
| 384 |
+
# memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id)
|
| 385 |
+
by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")}
|
| 386 |
+
for r in runs.values():
|
| 387 |
+
if r.get("memory_free_chain_of"):
|
| 388 |
+
r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"]))
|
| 389 |
+
for (b, rn), r in runs.items():
|
| 390 |
+
r["memory_free_retries"] = sorted((x["run"] for x in runs.values()
|
| 391 |
+
if x["batch"] == b and x.get("memory_free_chain_of_run") == rn),
|
| 392 |
+
key=lambda q: runs[(b, q)].get("memory_free_rep") or 0)
|
| 393 |
+
with open(os.path.join(lff, "episodes.jsonl"), "w") as f:
|
| 394 |
+
for row in rows:
|
| 395 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 396 |
+
with open(os.path.join(lff, "runs.jsonl"), "w") as f:
|
| 397 |
+
for r in runs.values():
|
| 398 |
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 399 |
+
with open(os.path.join(lff, "tasks.json"), "w") as f:
|
| 400 |
+
json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False)
|
| 401 |
+
with open(os.path.join(lff, "batches.json"), "w") as f:
|
| 402 |
+
json.dump(BATCH_NOTES, f, indent=1)
|
| 403 |
+
with open(os.path.join(lff, "rejected.json"), "w") as f:
|
| 404 |
+
json.dump(plan["rejected"], f, indent=1)
|
| 405 |
+
here = os.path.dirname(os.path.abspath(__file__))
|
| 406 |
+
for s in ("lerobot_replay.py", "lerobot_export.py"):
|
| 407 |
+
shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s))
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def main():
|
| 411 |
+
ap = argparse.ArgumentParser()
|
| 412 |
+
ap.add_argument("step", choices=["plan", "shard", "merge"])
|
| 413 |
+
ap.add_argument("--work", required=True)
|
| 414 |
+
ap.add_argument("--raw", default="")
|
| 415 |
+
ap.add_argument("--runs-root", default="")
|
| 416 |
+
ap.add_argument("--out", default="")
|
| 417 |
+
ap.add_argument("--paper", default="")
|
| 418 |
+
ap.add_argument("--task-set", default="")
|
| 419 |
+
ap.add_argument("--repo-id", default="lffbench/agent-replays")
|
| 420 |
+
ap.add_argument("--batches", default="")
|
| 421 |
+
ap.add_argument("--limit", type=int, default=0)
|
| 422 |
+
ap.add_argument("--shard", type=int, default=0)
|
| 423 |
+
ap.add_argument("--nshards", type=int, default=1)
|
| 424 |
+
ap.add_argument("--threads", type=int, default=2)
|
| 425 |
+
ap.add_argument("--vcodec", default="libsvtav1")
|
| 426 |
+
a = ap.parse_args()
|
| 427 |
+
{"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
if __name__ == "__main__":
|
| 431 |
+
main()
|
leaf/code/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lerobot_replay.py
ADDED
|
@@ -0,0 +1,744 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay
|
| 2 |
+
against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the
|
| 3 |
+
LeRobot export (scripts/lerobot_export.py).
|
| 4 |
+
|
| 5 |
+
python scripts/lerobot_replay.py check <run_dir> [<run_dir> ...] [--json out.json] # replay only, print fidelity
|
| 6 |
+
python scripts/lerobot_replay.py record <run_dir> --out <raw_root> [--res 256]
|
| 7 |
+
|
| 8 |
+
Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot
|
| 9 |
+
commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite
|
| 10 |
+
is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly
|
| 11 |
+
like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same
|
| 12 |
+
outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width,
|
| 13 |
+
ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code
|
| 14 |
+
hashes equal the current files are expected to match (check_code()).
|
| 15 |
+
|
| 16 |
+
Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB,
|
| 17 |
+
proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes:
|
| 18 |
+
protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode
|
| 19 |
+
per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the
|
| 20 |
+
fidelity check runs in record mode too. Per episode the recorder writes <raw_root>/<batch>/<run>/epNN/:
|
| 21 |
+
agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes)
|
| 22 |
+
frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase
|
| 23 |
+
sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel)
|
| 24 |
+
final_*.png, final.npz observation after the last control step (the state the outcome was judged in)
|
| 25 |
+
annotation.json episode annotation (build_annotation)
|
| 26 |
+
and <raw_root>/<batch>/<run>/replay.json (fidelity) when the whole run is done.
|
| 27 |
+
"""
|
| 28 |
+
import argparse
|
| 29 |
+
import ast
|
| 30 |
+
import hashlib
|
| 31 |
+
import importlib
|
| 32 |
+
import json
|
| 33 |
+
import math
|
| 34 |
+
import os
|
| 35 |
+
import pkgutil
|
| 36 |
+
import re
|
| 37 |
+
import shutil
|
| 38 |
+
import sys
|
| 39 |
+
import time
|
| 40 |
+
from collections import defaultdict
|
| 41 |
+
|
| 42 |
+
import numpy as np
|
| 43 |
+
|
| 44 |
+
LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 45 |
+
sys.path.insert(0, LFF_ROOT)
|
| 46 |
+
|
| 47 |
+
from lffbench import envs # noqa: E402
|
| 48 |
+
from lffbench import tasks as task_pkg # noqa: E402
|
| 49 |
+
from lffbench.agent import camera as C # noqa: E402
|
| 50 |
+
from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402
|
| 51 |
+
from lffbench.task_base import TASKS # noqa: E402
|
| 52 |
+
|
| 53 |
+
for _m in pkgutil.iter_modules(task_pkg.__path__):
|
| 54 |
+
importlib.import_module(f"lffbench.tasks.{_m.name}")
|
| 55 |
+
|
| 56 |
+
# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the
|
| 57 |
+
# task's outcome() check after `finish` (the arm holds still; not an agent action)
|
| 58 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 59 |
+
FPS = 20
|
| 60 |
+
SCHEMA = "lff-replay-1"
|
| 61 |
+
|
| 62 |
+
# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR"
|
| 63 |
+
ERROR_FLAGS = ("trap_fired", "recovered_in_attempt")
|
| 64 |
+
ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events",
|
| 65 |
+
"n_missed_strikes", "n_open_gripper_pushes")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def load_jsonl(p):
|
| 69 |
+
out = []
|
| 70 |
+
if not os.path.exists(p):
|
| 71 |
+
return out
|
| 72 |
+
with open(p) as f:
|
| 73 |
+
for line in f:
|
| 74 |
+
line = line.strip()
|
| 75 |
+
if line:
|
| 76 |
+
try:
|
| 77 |
+
out.append(json.loads(line))
|
| 78 |
+
except ValueError:
|
| 79 |
+
pass
|
| 80 |
+
return out
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def norm_json(o):
|
| 84 |
+
return json.loads(json.dumps(o, default=_json_default))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def sha256(p):
|
| 88 |
+
with open(p, "rb") as f:
|
| 89 |
+
return hashlib.sha256(f.read()).hexdigest()
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def check_code(run_dir):
|
| 93 |
+
"""[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract."""
|
| 94 |
+
p = os.path.join(run_dir, "contract.json")
|
| 95 |
+
if not os.path.exists(p):
|
| 96 |
+
return [("contract.json", None, None)]
|
| 97 |
+
files = json.load(open(p))["contract"].get("server_code_files", {})
|
| 98 |
+
bad = []
|
| 99 |
+
for f, h in files.items():
|
| 100 |
+
q = os.path.join(LFF_ROOT, f)
|
| 101 |
+
cur = sha256(q) if os.path.exists(q) else None
|
| 102 |
+
if cur != h:
|
| 103 |
+
bad.append((f, h, cur))
|
| 104 |
+
return bad
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def diff_json(a, b, path="", tol=0.0, out=None, limit=20):
|
| 108 |
+
"""Differences between two JSON values (numbers compared with an absolute tolerance)."""
|
| 109 |
+
out = [] if out is None else out
|
| 110 |
+
if len(out) >= limit:
|
| 111 |
+
return out
|
| 112 |
+
if isinstance(a, dict) and isinstance(b, dict):
|
| 113 |
+
for k in sorted(set(a) | set(b)):
|
| 114 |
+
if k not in a or k not in b:
|
| 115 |
+
out.append((f"{path}.{k}", a.get(k, "<missing>"), b.get(k, "<missing>")))
|
| 116 |
+
else:
|
| 117 |
+
diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit)
|
| 118 |
+
elif isinstance(a, list) and isinstance(b, list):
|
| 119 |
+
if len(a) != len(b):
|
| 120 |
+
out.append((path, f"len {len(a)}", f"len {len(b)}"))
|
| 121 |
+
else:
|
| 122 |
+
for i, (x, y) in enumerate(zip(a, b)):
|
| 123 |
+
diff_json(x, y, f"{path}[{i}]", tol, out, limit)
|
| 124 |
+
elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
|
| 125 |
+
if a != b:
|
| 126 |
+
out.append((path, a, b))
|
| 127 |
+
elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))):
|
| 128 |
+
out.append((path, a, b))
|
| 129 |
+
return out
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def error_event(o):
|
| 133 |
+
"""True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none."""
|
| 134 |
+
if not isinstance(o, dict):
|
| 135 |
+
return None
|
| 136 |
+
keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o]
|
| 137 |
+
if not keys:
|
| 138 |
+
return None
|
| 139 |
+
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)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# ====================================================================================================== logs -> notes
|
| 143 |
+
|
| 144 |
+
class RunLog:
|
| 145 |
+
"""Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's
|
| 146 |
+
narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition."""
|
| 147 |
+
|
| 148 |
+
def __init__(self, run_dir, manifest=None):
|
| 149 |
+
self.run_dir = os.path.abspath(run_dir.rstrip("/"))
|
| 150 |
+
self.run = os.path.basename(self.run_dir)
|
| 151 |
+
self.batch = os.path.basename(os.path.dirname(self.run_dir))
|
| 152 |
+
self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl"))
|
| 153 |
+
self.start = next(e for e in self.ev if e["ev"] == "session_start")
|
| 154 |
+
self.calls, self.dones, self.harness_status = {}, [], []
|
| 155 |
+
last = None
|
| 156 |
+
for e in self.ev:
|
| 157 |
+
if e["ev"] == "call":
|
| 158 |
+
self.calls[(int(e["attempt"]), int(e["step"]))] = e
|
| 159 |
+
last = e
|
| 160 |
+
elif e["ev"] == "done":
|
| 161 |
+
self.dones.append(e)
|
| 162 |
+
last = e
|
| 163 |
+
elif e["ev"] == "http" and last is not None and "think_s" not in last:
|
| 164 |
+
ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \
|
| 165 |
+
(last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe"))
|
| 166 |
+
if ok:
|
| 167 |
+
last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s")
|
| 168 |
+
self.manifest = manifest or {}
|
| 169 |
+
self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {}
|
| 170 |
+
p = os.path.join(self.run_dir, "harness.json")
|
| 171 |
+
self.harness = json.load(open(p)) if os.path.exists(p) else {}
|
| 172 |
+
self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl"))
|
| 173 |
+
self._narration()
|
| 174 |
+
|
| 175 |
+
# ---------------------------------------------------------------- agent narration
|
| 176 |
+
def _narration(self):
|
| 177 |
+
"""notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one;
|
| 178 |
+
finish_notes[attempt] likewise for the agent's finish call; final_report = its last message."""
|
| 179 |
+
self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", []
|
| 180 |
+
buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
|
| 181 |
+
attempt = 1
|
| 182 |
+
|
| 183 |
+
def take():
|
| 184 |
+
nonlocal buf
|
| 185 |
+
out = {k: v for k, v in buf.items() if v}
|
| 186 |
+
buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
|
| 187 |
+
return out
|
| 188 |
+
|
| 189 |
+
last_msg = ""
|
| 190 |
+
for t in self.traj:
|
| 191 |
+
if t.get("kind") == "header":
|
| 192 |
+
self.headers.append(t.get("agent") or {})
|
| 193 |
+
continue
|
| 194 |
+
if t.get("kind") != "step":
|
| 195 |
+
continue
|
| 196 |
+
if (t.get("message") or "").strip():
|
| 197 |
+
buf["messages"].append(t["message"].strip())
|
| 198 |
+
last_msg = t["message"].strip()
|
| 199 |
+
if (t.get("reasoning_content") or "").strip():
|
| 200 |
+
buf["reasoning"].append(t["reasoning_content"].strip())
|
| 201 |
+
res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])}
|
| 202 |
+
for c in t.get("tool_calls") or []:
|
| 203 |
+
fn, args = c.get("function_name"), c.get("arguments") or {}
|
| 204 |
+
if fn == "shell":
|
| 205 |
+
buf["shell"].append(str(args.get("command", ""))[:2000])
|
| 206 |
+
elif fn == "view_images":
|
| 207 |
+
buf["viewed"].extend(args.get("paths") or [])
|
| 208 |
+
elif fn == "robot":
|
| 209 |
+
cmd = str(args.get("command", "")).strip()
|
| 210 |
+
r = res.get(c.get("tool_call_id")) or {}
|
| 211 |
+
try:
|
| 212 |
+
rep = json.loads(r.get("content") or "{}")
|
| 213 |
+
except ValueError:
|
| 214 |
+
rep = {}
|
| 215 |
+
word = cmd.split()[0] if cmd else ""
|
| 216 |
+
m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", "")))
|
| 217 |
+
if word in ("move_eef", "observe") and m:
|
| 218 |
+
a, s = int(m.group(1)), int(m.group(2))
|
| 219 |
+
n = take()
|
| 220 |
+
n["command"] = cmd
|
| 221 |
+
self.notes[(a, s)] = n
|
| 222 |
+
attempt = a
|
| 223 |
+
elif word in ("finish", "done"):
|
| 224 |
+
n = take()
|
| 225 |
+
n["command"] = cmd
|
| 226 |
+
n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)}
|
| 227 |
+
self.finish_notes.setdefault(attempt, n)
|
| 228 |
+
if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"):
|
| 229 |
+
attempt += 1
|
| 230 |
+
# status / help / errors: their narration stays in the buffer for the next command
|
| 231 |
+
self.final_report = last_msg
|
| 232 |
+
|
| 233 |
+
# ---------------------------------------------------------------- run-level labels
|
| 234 |
+
def attempts(self):
|
| 235 |
+
out = []
|
| 236 |
+
for e in self.dones:
|
| 237 |
+
o = e.get("outcome") or {}
|
| 238 |
+
if isinstance(o, str):
|
| 239 |
+
try:
|
| 240 |
+
o = ast.literal_eval(o)
|
| 241 |
+
except (ValueError, SyntaxError):
|
| 242 |
+
o = {}
|
| 243 |
+
out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o,
|
| 244 |
+
reason=e.get("reason") or ""))
|
| 245 |
+
return sorted(out, key=lambda x: x["attempt"])
|
| 246 |
+
|
| 247 |
+
def condition(self):
|
| 248 |
+
s, en = self.start, self.entry
|
| 249 |
+
mem = s.get("memory", en.get("mem"))
|
| 250 |
+
chain = en.get("chain")
|
| 251 |
+
if mem == "full":
|
| 252 |
+
cond = "with_history"
|
| 253 |
+
elif chain:
|
| 254 |
+
cond = "memory_free_retry"
|
| 255 |
+
else:
|
| 256 |
+
cond = "independent_single_attempt"
|
| 257 |
+
return cond, chain
|
| 258 |
+
|
| 259 |
+
def outcome_class(self):
|
| 260 |
+
"""CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None."""
|
| 261 |
+
att = self.attempts()
|
| 262 |
+
if not att or self.start.get("memory") != "full":
|
| 263 |
+
return None, "".join("S" if a["success"] else "F" for a in att)
|
| 264 |
+
hist = "".join("S" if a["success"] else "F" for a in att)
|
| 265 |
+
if att[0]["success"]:
|
| 266 |
+
ev = error_event(att[0]["outcome"])
|
| 267 |
+
cls = "S?" if ev is None else ("IR" if ev else "CS")
|
| 268 |
+
else:
|
| 269 |
+
cls = "XR" if any(a["success"] for a in att) else "F"
|
| 270 |
+
return cls, hist
|
| 271 |
+
|
| 272 |
+
def agent_info(self):
|
| 273 |
+
h, en = self.harness, self.entry
|
| 274 |
+
hdr = self.headers[0] if self.headers else {}
|
| 275 |
+
return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"),
|
| 276 |
+
harness_version=h.get("version") or hdr.get("version"),
|
| 277 |
+
harness_binary_sha256=(h.get("binary") or {}).get("sha256"),
|
| 278 |
+
model=h.get("model") or en.get("model") or hdr.get("model_name"),
|
| 279 |
+
effort=h.get("effort") or en.get("effort") or hdr.get("effort"),
|
| 280 |
+
provider=h.get("provider") or en.get("provider"),
|
| 281 |
+
codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"),
|
| 282 |
+
jail=en.get("jail"))
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
# ====================================================================================================== recording
|
| 286 |
+
|
| 287 |
+
class EpisodeSink:
|
| 288 |
+
"""Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed."""
|
| 289 |
+
|
| 290 |
+
def __init__(self, path):
|
| 291 |
+
self.path = path
|
| 292 |
+
os.makedirs(path, exist_ok=True)
|
| 293 |
+
self.w = None
|
| 294 |
+
self.num = defaultdict(list)
|
| 295 |
+
self.n = 0
|
| 296 |
+
|
| 297 |
+
def add(self, st, imgs):
|
| 298 |
+
import imageio
|
| 299 |
+
if self.w is None:
|
| 300 |
+
self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb",
|
| 301 |
+
pixelformat="rgb24", macro_block_size=1,
|
| 302 |
+
ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error")
|
| 303 |
+
for k in ("agentview", "wrist")]
|
| 304 |
+
for w, im in zip(self.w, imgs):
|
| 305 |
+
w.append_data(im)
|
| 306 |
+
for k, v in st.items():
|
| 307 |
+
self.num[k].append(v)
|
| 308 |
+
self.n += 1
|
| 309 |
+
|
| 310 |
+
def close(self, final_state, final_imgs):
|
| 311 |
+
from PIL import Image
|
| 312 |
+
if self.w is not None:
|
| 313 |
+
for w in self.w:
|
| 314 |
+
w.close()
|
| 315 |
+
arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"}
|
| 316 |
+
np.savez(os.path.join(self.path, "frames.npz"), **arr)
|
| 317 |
+
if self.num.get("sim_state"):
|
| 318 |
+
np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64))
|
| 319 |
+
np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()})
|
| 320 |
+
for k, im in zip(("agentview", "wrist"), final_imgs):
|
| 321 |
+
Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png"))
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
class Recorder:
|
| 325 |
+
"""Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink."""
|
| 326 |
+
|
| 327 |
+
def __init__(self, rp, res):
|
| 328 |
+
self.rp, self.res = rp, int(res)
|
| 329 |
+
self.active = False
|
| 330 |
+
self.sink = None
|
| 331 |
+
self.cur = dict(attempt=1, command=-1, phase=PHASES["move"])
|
| 332 |
+
env = rp.task.env
|
| 333 |
+
self.env, self.rob = env, env.robots[0]
|
| 334 |
+
self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist"))
|
| 335 |
+
orig = env.step
|
| 336 |
+
|
| 337 |
+
def step(a):
|
| 338 |
+
if self.active and self.sink is not None:
|
| 339 |
+
self.capture(np.asarray(a, np.float64))
|
| 340 |
+
out = orig(a)
|
| 341 |
+
if self.active and self.sink is not None:
|
| 342 |
+
self.rp.poll_events(self.sink.n - 1)
|
| 343 |
+
return out
|
| 344 |
+
|
| 345 |
+
env.step = step
|
| 346 |
+
|
| 347 |
+
@property
|
| 348 |
+
def n(self):
|
| 349 |
+
return self.sink.n if self.sink is not None else 0
|
| 350 |
+
|
| 351 |
+
def state(self):
|
| 352 |
+
import robosuite.utils.transform_utils as T
|
| 353 |
+
env, rob = self.env, self.rob
|
| 354 |
+
d = env.sim.data
|
| 355 |
+
eef = np.array(d.site_xpos[rob.eef_site_id], np.float64)
|
| 356 |
+
q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw")
|
| 357 |
+
gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64)
|
| 358 |
+
try:
|
| 359 |
+
flat = np.asarray(env.sim.get_state().flatten(), np.float64)
|
| 360 |
+
except Exception:
|
| 361 |
+
flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64)
|
| 362 |
+
sk = self.rp.task.sk
|
| 363 |
+
return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64),
|
| 364 |
+
gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64),
|
| 365 |
+
joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64),
|
| 366 |
+
gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64),
|
| 367 |
+
eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)),
|
| 368 |
+
sim_time=np.float64(d.time), sim_state=flat)
|
| 369 |
+
|
| 370 |
+
def images(self):
|
| 371 |
+
return [envs.render(self.env, c, self.res) for c in self.cams]
|
| 372 |
+
|
| 373 |
+
def capture(self, a):
|
| 374 |
+
st = self.state()
|
| 375 |
+
st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]),
|
| 376 |
+
phase=np.int64(self.cur["phase"]))
|
| 377 |
+
self.sink.add(st, self.images())
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
class RunReplay:
|
| 381 |
+
def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None):
|
| 382 |
+
self.run_dir = os.path.abspath(run_dir.rstrip("/"))
|
| 383 |
+
self.run_name = os.path.basename(self.run_dir)
|
| 384 |
+
self.log = RunLog(self.run_dir, manifest)
|
| 385 |
+
self.ev = self.log.ev
|
| 386 |
+
self.start = self.log.start
|
| 387 |
+
cp = os.path.join(self.run_dir, "contract.json")
|
| 388 |
+
self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {}
|
| 389 |
+
spec = self.contract.get("image_spec") or {}
|
| 390 |
+
self.image_res = int(spec.get("width", 512))
|
| 391 |
+
self.code_diff = check_code(self.run_dir)
|
| 392 |
+
s = self.start
|
| 393 |
+
self.task = TASKS[s["task"]](cam_res=self.image_res)
|
| 394 |
+
inst = self.task.sample_instance(s["seed"])
|
| 395 |
+
logged = s.get("inst") or {}
|
| 396 |
+
sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")})
|
| 397 |
+
self.inst_diff = diff_json(sampled, logged, "inst")
|
| 398 |
+
if s.get("arm", "none") not in (None, "none") or logged.get("nominal"):
|
| 399 |
+
inst.update(logged) # controlled arms / nominal: the server overrode these instance fields
|
| 400 |
+
self.inst_diff = []
|
| 401 |
+
self.inst = inst
|
| 402 |
+
self.protocol = getattr(self.task, "protocol", "cross")
|
| 403 |
+
self.k = int(s.get("k") or self.task.max_attempts)
|
| 404 |
+
self.attempt = 1
|
| 405 |
+
self.mismatch = [] # (where, what, logged, replayed)
|
| 406 |
+
self.n_checked = 0
|
| 407 |
+
self.max_dev_m = 0.0
|
| 408 |
+
self.unfinished = None
|
| 409 |
+
self.rec = Recorder(self, res) if record else None
|
| 410 |
+
self.res = int(res)
|
| 411 |
+
self.out_root = out_root
|
| 412 |
+
self.n_mon = 0
|
| 413 |
+
self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0
|
| 414 |
+
self.episodes = [] # summaries of the written episodes
|
| 415 |
+
self.task.reset_instance(self.inst)
|
| 416 |
+
self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
|
| 417 |
+
sim = self.task.env.sim
|
| 418 |
+
bid = sim.model.body_name2id("robot0_base")
|
| 419 |
+
self.base_off = np.array(sim.data.body_xpos[bid], float).copy()
|
| 420 |
+
if self.rec:
|
| 421 |
+
self._open_episode()
|
| 422 |
+
|
| 423 |
+
# ------------------------------------------------------------------ episodes
|
| 424 |
+
def _ep_dir(self):
|
| 425 |
+
return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}")
|
| 426 |
+
|
| 427 |
+
def _open_episode(self):
|
| 428 |
+
self.rec.sink = EpisodeSink(self._ep_dir())
|
| 429 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
|
| 430 |
+
self.rec.active = True
|
| 431 |
+
self.events, self.spans, self.ep_attempts = [], [], []
|
| 432 |
+
self.ep_initial = self.rec.state() # state right after the reset (before frame 0)
|
| 433 |
+
|
| 434 |
+
def close_episode(self):
|
| 435 |
+
if not self.rec:
|
| 436 |
+
self.ep_attempts = []
|
| 437 |
+
return
|
| 438 |
+
sink = self.rec.sink
|
| 439 |
+
st = self.rec.state()
|
| 440 |
+
imgs = self.rec.images()
|
| 441 |
+
st.pop("sim_state", None)
|
| 442 |
+
sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs)
|
| 443 |
+
ann = build_annotation(self, sink)
|
| 444 |
+
with open(os.path.join(sink.path, "annotation.json"), "w") as f:
|
| 445 |
+
json.dump(ann, f, indent=1, default=_json_default)
|
| 446 |
+
self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n,
|
| 447 |
+
attempts=[a["attempt"] for a in self.ep_attempts]))
|
| 448 |
+
self.rec.active = False
|
| 449 |
+
self.rec.sink = None
|
| 450 |
+
self.ep_index += 1
|
| 451 |
+
|
| 452 |
+
# ------------------------------------------------------------------ monitor events (task-side error events)
|
| 453 |
+
def poll_events(self, frame):
|
| 454 |
+
mon = getattr(self.task, "mon", None)
|
| 455 |
+
evs = mon.get("events") if isinstance(mon, dict) else None
|
| 456 |
+
if not isinstance(evs, list):
|
| 457 |
+
return
|
| 458 |
+
if len(evs) < self.n_mon: # monitor was rebuilt
|
| 459 |
+
self.n_mon = 0
|
| 460 |
+
for e in evs[self.n_mon:]:
|
| 461 |
+
self.events.append(dict(frame=int(frame), attempt=self.attempt,
|
| 462 |
+
event=norm_json(e) if isinstance(e, dict) else str(e)))
|
| 463 |
+
self.n_mon = len(evs)
|
| 464 |
+
|
| 465 |
+
# ------------------------------------------------------------------ state as the server reports it
|
| 466 |
+
def proprio_la(self):
|
| 467 |
+
p = self.ex.proprio()
|
| 468 |
+
pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off]
|
| 469 |
+
return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"])
|
| 470 |
+
|
| 471 |
+
def compare(self, where, rep_logged, rep):
|
| 472 |
+
self.n_checked += 1
|
| 473 |
+
for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"):
|
| 474 |
+
if k not in rep_logged or k not in rep:
|
| 475 |
+
continue
|
| 476 |
+
a, b = rep_logged[k], rep[k]
|
| 477 |
+
if k == "eef_pos":
|
| 478 |
+
dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float))))
|
| 479 |
+
self.max_dev_m = max(self.max_dev_m, dev)
|
| 480 |
+
if dev > 1.5e-4:
|
| 481 |
+
self.mismatch.append((where, k, a, b))
|
| 482 |
+
elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4):
|
| 483 |
+
self.mismatch.append((where, k, a, b))
|
| 484 |
+
if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)):
|
| 485 |
+
self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok")))
|
| 486 |
+
|
| 487 |
+
def _span(self, e, f0, kind):
|
| 488 |
+
if self.rec:
|
| 489 |
+
self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0,
|
| 490 |
+
frame_end=self.rec.n))
|
| 491 |
+
|
| 492 |
+
# ------------------------------------------------------------------ commands (robot_server._handle_v2)
|
| 493 |
+
def move_eef(self, e):
|
| 494 |
+
args = e.get("args") or {}
|
| 495 |
+
where = f"a{e['attempt']}s{e['step']}"
|
| 496 |
+
logged = e.get("report") or {}
|
| 497 |
+
f0 = self.rec.n if self.rec else 0
|
| 498 |
+
p = self.ex.proprio()
|
| 499 |
+
if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}:
|
| 500 |
+
self._span(e, f0, "error")
|
| 501 |
+
return self.compare(where, logged, dict(ok=False))
|
| 502 |
+
off = self.base_off
|
| 503 |
+
try:
|
| 504 |
+
cur = np.asarray(p["eef_pos"], float) - off
|
| 505 |
+
tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
|
| 506 |
+
yaw = float(args.get("yaw", p["eef_yaw_deg"]))
|
| 507 |
+
speed = None if args.get("speed") in (None, "") else float(args["speed"])
|
| 508 |
+
except (TypeError, ValueError):
|
| 509 |
+
self._span(e, f0, "error")
|
| 510 |
+
return self.compare(where, logged, dict(ok=False))
|
| 511 |
+
grip = args.get("gripper")
|
| 512 |
+
if grip not in (None, "open", "close"):
|
| 513 |
+
self._span(e, f0, "error")
|
| 514 |
+
return self.compare(where, logged, dict(ok=False))
|
| 515 |
+
moving = any(k in args for k in ("x", "y", "z", "yaw"))
|
| 516 |
+
tgt_w = np.asarray(tgt) + off
|
| 517 |
+
if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)):
|
| 518 |
+
self._span(e, f0, "rejected")
|
| 519 |
+
return self.compare(where, logged, dict(ok=False, **self.proprio_la()))
|
| 520 |
+
raw = {}
|
| 521 |
+
if self.rec:
|
| 522 |
+
self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"])
|
| 523 |
+
if moving:
|
| 524 |
+
mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw)
|
| 525 |
+
if speed is not None:
|
| 526 |
+
mv["speed"] = speed
|
| 527 |
+
raw.update(self.ex.call("move_to", mv).report)
|
| 528 |
+
if grip is not None:
|
| 529 |
+
if self.rec:
|
| 530 |
+
self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"])
|
| 531 |
+
raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report)
|
| 532 |
+
rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la())
|
| 533 |
+
self.compare(where, logged, rep)
|
| 534 |
+
lr = e.get("raw") or {}
|
| 535 |
+
for k in ("holding_object", "touched_object"):
|
| 536 |
+
if k in lr and k in raw and bool(lr[k]) != bool(raw[k]):
|
| 537 |
+
self.mismatch.append((where, "raw." + k, lr[k], raw[k]))
|
| 538 |
+
self._span(e, f0, "move_eef")
|
| 539 |
+
|
| 540 |
+
def observe(self, e):
|
| 541 |
+
f0 = self.rec.n if self.rec else 0
|
| 542 |
+
self._span(e, f0, "observe")
|
| 543 |
+
|
| 544 |
+
def done(self, e):
|
| 545 |
+
f0 = self.rec.n if self.rec else 0
|
| 546 |
+
if self.rec:
|
| 547 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"])
|
| 548 |
+
out = self.task.outcome(self.inst)
|
| 549 |
+
succ = bool(out["success"])
|
| 550 |
+
where = f"a{e['attempt']}done"
|
| 551 |
+
if succ != bool(e.get("success") in (True, "True")):
|
| 552 |
+
self.mismatch.append((where, "success", e.get("success"), succ))
|
| 553 |
+
lo = e.get("outcome") or {}
|
| 554 |
+
ro = norm_json({k: v for k, v in out.items() if k != "feedback"})
|
| 555 |
+
if isinstance(lo, dict):
|
| 556 |
+
for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8):
|
| 557 |
+
self.mismatch.append((where,) + d)
|
| 558 |
+
info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""),
|
| 559 |
+
feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")),
|
| 560 |
+
think_s=e.get("think_s"))
|
| 561 |
+
try:
|
| 562 |
+
info["feedback_f2"] = self.task.feedback(self.inst, out, "F2")
|
| 563 |
+
except Exception as ex_:
|
| 564 |
+
info["feedback_f2"] = f"<unavailable: {type(ex_).__name__}>"
|
| 565 |
+
if self.rec:
|
| 566 |
+
info["judge_frames"] = [f0, self.rec.n]
|
| 567 |
+
self.ep_attempts.append(info)
|
| 568 |
+
last = self.attempt >= self.k or succ or bool(out.get("terminal"))
|
| 569 |
+
if self.protocol == "cross" or last:
|
| 570 |
+
self.close_episode()
|
| 571 |
+
if last:
|
| 572 |
+
return True
|
| 573 |
+
self.attempt += 1
|
| 574 |
+
if self.protocol == "cross":
|
| 575 |
+
self.task.reset_instance(self.inst)
|
| 576 |
+
self.n_mon = 0
|
| 577 |
+
if self.rec:
|
| 578 |
+
self._open_episode()
|
| 579 |
+
elif self.rec:
|
| 580 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
|
| 581 |
+
self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
|
| 582 |
+
return False
|
| 583 |
+
|
| 584 |
+
def run(self):
|
| 585 |
+
t0 = time.time()
|
| 586 |
+
finished = False
|
| 587 |
+
for e in self.ev:
|
| 588 |
+
if e["ev"] == "call":
|
| 589 |
+
if e.get("cmd") == "move_eef":
|
| 590 |
+
self.move_eef(e)
|
| 591 |
+
elif e.get("cmd") == "observe":
|
| 592 |
+
self.observe(e)
|
| 593 |
+
else:
|
| 594 |
+
self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None))
|
| 595 |
+
elif e["ev"] == "done":
|
| 596 |
+
finished = self.done(e)
|
| 597 |
+
if finished:
|
| 598 |
+
break
|
| 599 |
+
self.unfinished = not finished
|
| 600 |
+
if not finished and self.rec and self.rec.sink is not None:
|
| 601 |
+
# the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged
|
| 602 |
+
if self.rec.n or self.ep_attempts:
|
| 603 |
+
self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True,
|
| 604 |
+
finish_reason="", feedback_shown="", auto_ended=False))
|
| 605 |
+
self.close_episode()
|
| 606 |
+
else:
|
| 607 |
+
shutil.rmtree(self.rec.sink.path, ignore_errors=True)
|
| 608 |
+
self.rec.sink = None
|
| 609 |
+
self.wall_s = time.time() - t0
|
| 610 |
+
return self
|
| 611 |
+
|
| 612 |
+
def summary(self):
|
| 613 |
+
return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"],
|
| 614 |
+
protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff),
|
| 615 |
+
n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6),
|
| 616 |
+
unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1),
|
| 617 |
+
first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]])
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
# ====================================================================================================== annotation
|
| 621 |
+
|
| 622 |
+
def task_info(task, inst):
|
| 623 |
+
cls = type(task)
|
| 624 |
+
return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable",
|
| 625 |
+
category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"),
|
| 626 |
+
max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)),
|
| 627 |
+
instruction=cls.instruction)
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
def build_annotation(rp, sink):
|
| 631 |
+
"""Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2
|
| 632 |
+
failure description), run-level outcome class, every robot command with its frame span and the agent's narration,
|
| 633 |
+
task-side error events with frame indices."""
|
| 634 |
+
log = rp.log
|
| 635 |
+
s = rp.start
|
| 636 |
+
cond, chain = log.condition()
|
| 637 |
+
cls, hist = log.outcome_class()
|
| 638 |
+
att_all = log.attempts()
|
| 639 |
+
attempts = []
|
| 640 |
+
for a in rp.ep_attempts:
|
| 641 |
+
a = dict(a)
|
| 642 |
+
n = a["attempt"]
|
| 643 |
+
later = [x for x in att_all if x["attempt"] > n]
|
| 644 |
+
a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later))
|
| 645 |
+
a["is_last_attempt_of_run"] = not later
|
| 646 |
+
fn = log.finish_notes.get(n)
|
| 647 |
+
if fn:
|
| 648 |
+
a["agent_finish"] = fn
|
| 649 |
+
a["error_event_in_attempt"] = error_event(a.get("outcome"))
|
| 650 |
+
attempts.append(a)
|
| 651 |
+
# post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command)
|
| 652 |
+
for a in attempts:
|
| 653 |
+
nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1])
|
| 654 |
+
if a.get("success") is False and nxt:
|
| 655 |
+
note = log.notes[nxt[0]]
|
| 656 |
+
a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note}
|
| 657 |
+
commands = []
|
| 658 |
+
for sp in rp.spans:
|
| 659 |
+
e = log.calls.get((sp["attempt"], sp["step"])) or {}
|
| 660 |
+
rep = e.get("report") or {}
|
| 661 |
+
c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"],
|
| 662 |
+
frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]),
|
| 663 |
+
args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"),
|
| 664 |
+
stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"),
|
| 665 |
+
gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"),
|
| 666 |
+
touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"),
|
| 667 |
+
agent_obs_images=rep.get("images"))
|
| 668 |
+
note = log.notes.get((sp["attempt"], sp["step"]))
|
| 669 |
+
if note:
|
| 670 |
+
c["agent_note"] = {k: v for k, v in note.items() if k != "command"}
|
| 671 |
+
commands.append(c)
|
| 672 |
+
t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x]
|
| 673 |
+
return dict(
|
| 674 |
+
schema=SCHEMA,
|
| 675 |
+
source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts],
|
| 676 |
+
episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain,
|
| 677 |
+
memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None),
|
| 678 |
+
feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"),
|
| 679 |
+
k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"),
|
| 680 |
+
contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256")
|
| 681 |
+
if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)),
|
| 682 |
+
agent=log.agent_info(),
|
| 683 |
+
task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"),
|
| 684 |
+
instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}),
|
| 685 |
+
run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all),
|
| 686 |
+
run_success=any(x["success"] for x in att_all) if att_all else None,
|
| 687 |
+
agent_final_report=log.final_report[:6000] or None,
|
| 688 |
+
mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)),
|
| 689 |
+
attempts=attempts,
|
| 690 |
+
commands=commands,
|
| 691 |
+
task_events=rp.events,
|
| 692 |
+
frames=dict(n=sink.n, fps=FPS, image_res=rp.res,
|
| 693 |
+
phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"],
|
| 694 |
+
joint_pos=rp.ep_initial["joint_pos"],
|
| 695 |
+
gripper_qpos=rp.ep_initial["gripper_qpos"])),
|
| 696 |
+
)
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
# ====================================================================================================== CLI
|
| 700 |
+
|
| 701 |
+
def load_manifest(run_dir):
|
| 702 |
+
p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json")
|
| 703 |
+
return json.load(open(p)) if os.path.exists(p) else {}
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
def main():
|
| 707 |
+
ap = argparse.ArgumentParser()
|
| 708 |
+
ap.add_argument("mode", choices=["check", "record"])
|
| 709 |
+
ap.add_argument("runs", nargs="+")
|
| 710 |
+
ap.add_argument("--json", default="")
|
| 711 |
+
ap.add_argument("--out", default="")
|
| 712 |
+
ap.add_argument("--res", type=int, default=256)
|
| 713 |
+
ap.add_argument("--force", action="store_true", help="record again even if replay.json exists")
|
| 714 |
+
a = ap.parse_args()
|
| 715 |
+
rows = []
|
| 716 |
+
for r in a.runs:
|
| 717 |
+
r = r.rstrip("/")
|
| 718 |
+
try:
|
| 719 |
+
if a.mode == "check":
|
| 720 |
+
s = RunReplay(r, manifest=load_manifest(r)).run().summary()
|
| 721 |
+
else:
|
| 722 |
+
batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r)
|
| 723 |
+
rd = os.path.join(a.out, batch, name)
|
| 724 |
+
if os.path.exists(os.path.join(rd, "replay.json")) and not a.force:
|
| 725 |
+
print(json.dumps(dict(run=name, skipped="exists")), flush=True)
|
| 726 |
+
continue
|
| 727 |
+
shutil.rmtree(rd, ignore_errors=True)
|
| 728 |
+
rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run()
|
| 729 |
+
s = rp.summary()
|
| 730 |
+
s["episodes"] = rp.episodes
|
| 731 |
+
with open(os.path.join(rd, "replay.json"), "w") as f:
|
| 732 |
+
json.dump(s, f, indent=1)
|
| 733 |
+
except Exception:
|
| 734 |
+
import traceback
|
| 735 |
+
s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:])
|
| 736 |
+
rows.append(s)
|
| 737 |
+
print(json.dumps(s), flush=True)
|
| 738 |
+
if a.json:
|
| 739 |
+
with open(a.json, "w") as f:
|
| 740 |
+
json.dump(rows, f, indent=1)
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
if __name__ == "__main__":
|
| 744 |
+
main()
|
leaf/code/compound-lh-20261102-clh_20261102_deepseek/lerobot_export.py
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars.
|
| 2 |
+
|
| 3 |
+
Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding
|
| 4 |
+
can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan):
|
| 5 |
+
|
| 6 |
+
python scripts/lerobot_export.py plan --raw <raw_root>[,<raw_root2>] --runs-root <lffbench>/runs/api \
|
| 7 |
+
--paper <paper/latex> --task-set <lffbench>/sets/main_v2_1inst.txt --work <work_dir> [--batches ...] [--limit N]
|
| 8 |
+
python scripts/lerobot_export.py shard --work <work_dir> --shard i --nshards N
|
| 9 |
+
python scripts/lerobot_export.py merge --work <work_dir> --nshards N --out <dataset_root>
|
| 10 |
+
|
| 11 |
+
Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0
|
| 12 |
+
mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped.
|
| 13 |
+
|
| 14 |
+
LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t):
|
| 15 |
+
observation.images.image agentview RGB 256x256 (upright; LIBERO naming)
|
| 16 |
+
observation.images.wrist_image wrist (eye-in-hand) RGB 256x256
|
| 17 |
+
observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout)
|
| 18 |
+
observation.joint_pos / joint_vel 7 arm joints (rad, rad/s)
|
| 19 |
+
observation.eef_quat 4: xyzw; observation.gripper_width 1 (m)
|
| 20 |
+
action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad),
|
| 21 |
+
gripper (-1 open, +1 close)
|
| 22 |
+
annotation.attempt_index attempt (1-based) the frame belongs to
|
| 23 |
+
annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`)
|
| 24 |
+
annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action)
|
| 25 |
+
annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt
|
| 26 |
+
annotation.task_event number of task-monitor events (error / progress events) registered at this step
|
| 27 |
+
Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table),
|
| 28 |
+
runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state
|
| 29 |
+
per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/.
|
| 30 |
+
"""
|
| 31 |
+
import argparse
|
| 32 |
+
import glob
|
| 33 |
+
import json
|
| 34 |
+
import os
|
| 35 |
+
import re
|
| 36 |
+
import shutil
|
| 37 |
+
import time
|
| 38 |
+
|
| 39 |
+
import numpy as np
|
| 40 |
+
|
| 41 |
+
FPS = 20
|
| 42 |
+
RES = 256
|
| 43 |
+
BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke",
|
| 44 |
+
"cc_smoke", "cc_opus_smoke"]
|
| 45 |
+
BATCH_NOTES = {
|
| 46 |
+
"cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog",
|
| 47 |
+
"cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267",
|
| 48 |
+
"cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299",
|
| 49 |
+
"cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances",
|
| 50 |
+
"cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)",
|
| 51 |
+
"cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the "
|
| 52 |
+
"with-history continuation of failed runs is incomplete",
|
| 53 |
+
"cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early",
|
| 54 |
+
"cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt",
|
| 55 |
+
"cc_opus_smoke": "smoke test: single attempt",
|
| 56 |
+
}
|
| 57 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 58 |
+
CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)",
|
| 59 |
+
"L2": "disturbed state to restore (incl. damage the agent causes)",
|
| 60 |
+
"L3": "infeasible manipulation strategy (grasp / contact / tool must change)",
|
| 61 |
+
"L4": "misjudged geometry (size, shape, fit, hidden structure)",
|
| 62 |
+
"L5": "misjudged physics (mass distribution, friction, dynamics)"}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def features():
|
| 66 |
+
vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]}
|
| 67 |
+
f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names}
|
| 68 |
+
i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None}
|
| 69 |
+
return {
|
| 70 |
+
"observation.images.image": vid(),
|
| 71 |
+
"observation.images.wrist_image": vid(),
|
| 72 |
+
"observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z",
|
| 73 |
+
"finger_qpos_left", "finger_qpos_right"]),
|
| 74 |
+
"observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 75 |
+
"observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 76 |
+
"observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]),
|
| 77 |
+
"observation.gripper_width": f32(1, ["width_m"]),
|
| 78 |
+
"action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y",
|
| 79 |
+
"eef_delta_rot_aa_z", "gripper_close"]),
|
| 80 |
+
"annotation.attempt_index": i64(),
|
| 81 |
+
"annotation.command_index": i64(),
|
| 82 |
+
"annotation.phase": i64(),
|
| 83 |
+
"annotation.attempt_success": i64(),
|
| 84 |
+
"annotation.task_event": i64(),
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ------------------------------------------------------------------------------------------------ paper metadata
|
| 89 |
+
|
| 90 |
+
def _clean_tex(s):
|
| 91 |
+
s = re.sub(r"%.*", "", s)
|
| 92 |
+
for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"),
|
| 93 |
+
(r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"),
|
| 94 |
+
(r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"),
|
| 95 |
+
(r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"),
|
| 96 |
+
(r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]:
|
| 97 |
+
s = re.sub(a, b, s)
|
| 98 |
+
s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s)
|
| 99 |
+
s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s)
|
| 100 |
+
for _ in range(3):
|
| 101 |
+
s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s)
|
| 102 |
+
s = re.sub(r"\$([^$]*)\$", r"\1", s)
|
| 103 |
+
s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ")
|
| 104 |
+
s = re.sub(r"\{([^{}]*)\}", r"\1", s)
|
| 105 |
+
s = re.sub(r"\\[a-zA-Z]+\*?", "", s)
|
| 106 |
+
return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def paper_tasks(paper_dir):
|
| 110 |
+
"""{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the
|
| 111 |
+
paper's task table and task appendix (empty if the paper sources are not there)."""
|
| 112 |
+
out = {}
|
| 113 |
+
if not paper_dir:
|
| 114 |
+
return out
|
| 115 |
+
app = os.path.join(paper_dir, "sections", "appendix_tasks.tex")
|
| 116 |
+
tab = os.path.join(paper_dir, "sections", "tab_tasks.tex")
|
| 117 |
+
if os.path.exists(app):
|
| 118 |
+
txt = open(app).read()
|
| 119 |
+
parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt)
|
| 120 |
+
for i in range(1, len(parts) - 1, 2):
|
| 121 |
+
if parts[i] != "\\paragraph{":
|
| 122 |
+
continue
|
| 123 |
+
body = parts[i + 1]
|
| 124 |
+
m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S)
|
| 125 |
+
if not m:
|
| 126 |
+
continue
|
| 127 |
+
name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip()
|
| 128 |
+
desc = _clean_tex(body[m.end():])
|
| 129 |
+
out[code] = dict(name=name, cause=_clean_tex(cause), description=desc)
|
| 130 |
+
if os.path.exists(tab):
|
| 131 |
+
names = {v["name"].lower(): k for k, v in out.items()}
|
| 132 |
+
for line in open(tab):
|
| 133 |
+
cells = [c.strip() for c in line.split("&")]
|
| 134 |
+
if len(cells) != 6 or not cells[-1].endswith("\\\\"):
|
| 135 |
+
continue
|
| 136 |
+
nm = re.sub(r"\\contscene", "", cells[0]).strip().lower()
|
| 137 |
+
code = names.get(nm)
|
| 138 |
+
if not code:
|
| 139 |
+
continue
|
| 140 |
+
out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]),
|
| 141 |
+
repair_within_attempt=_clean_tex(cells[3]) == "yes",
|
| 142 |
+
oracle_first_attempt_pct=_clean_tex(cells[4]),
|
| 143 |
+
naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip()))
|
| 144 |
+
return out
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
# ------------------------------------------------------------------------------------------------ collection
|
| 148 |
+
|
| 149 |
+
def manifest_status(runs_root, batch, run, cache={}):
|
| 150 |
+
if batch not in cache:
|
| 151 |
+
p = os.path.join(runs_root, batch, "manifest.json")
|
| 152 |
+
cache[batch] = json.load(open(p)) if os.path.exists(p) else {}
|
| 153 |
+
m = cache[batch]
|
| 154 |
+
for r in m.get("runs", []):
|
| 155 |
+
if r.get("run") == run:
|
| 156 |
+
return r.get("status", "?"), r
|
| 157 |
+
for r in m.get("superseded", []):
|
| 158 |
+
if r.get("run") == run:
|
| 159 |
+
return "superseded_" + str(r.get("status", "?")), r
|
| 160 |
+
return "not_in_manifest", {}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def collect(raw_roots, runs_root, batches, task_order):
|
| 164 |
+
"""Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root."""
|
| 165 |
+
eps, rejected, seen = [], [], set()
|
| 166 |
+
for root in raw_roots:
|
| 167 |
+
for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))):
|
| 168 |
+
rep = json.load(open(rj))
|
| 169 |
+
batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"]
|
| 170 |
+
if (batches and batch not in batches) or (batch, run) in seen:
|
| 171 |
+
continue
|
| 172 |
+
seen.add((batch, run))
|
| 173 |
+
ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff")
|
| 174 |
+
status, entry = manifest_status(runs_root, batch, run)
|
| 175 |
+
if not ok:
|
| 176 |
+
never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked")
|
| 177 |
+
rejected.append(dict(run=run, batch=batch, run_status=status,
|
| 178 |
+
reason="run never started (no contract, no robot command)" if never else
|
| 179 |
+
"replay does not reproduce the log (the log has gaps or the replay diverged)",
|
| 180 |
+
detail=rep.get("first_mismatches")))
|
| 181 |
+
continue
|
| 182 |
+
for ep in rep.get("episodes", []):
|
| 183 |
+
d = os.path.join(root, ep["dir"])
|
| 184 |
+
ann = json.load(open(os.path.join(d, "annotation.json")))
|
| 185 |
+
judged = [a for a in ann["attempts"] if a.get("success") is not None]
|
| 186 |
+
if not judged or ep["n_frames"] == 0:
|
| 187 |
+
rejected.append(dict(run=run, batch=batch, episode=ep["dir"],
|
| 188 |
+
reason="no judged attempt" if not judged else "no frames"))
|
| 189 |
+
continue
|
| 190 |
+
ann["source"]["run_status"] = status
|
| 191 |
+
ann["source"]["manifest_id"] = entry.get("id")
|
| 192 |
+
ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"],
|
| 193 |
+
max_eef_dev_m=rep["max_eef_dev_m"])
|
| 194 |
+
key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99),
|
| 195 |
+
{"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2),
|
| 196 |
+
ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"])
|
| 197 |
+
eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann))
|
| 198 |
+
eps.sort(key=lambda x: x["key"])
|
| 199 |
+
return eps, rejected
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# ------------------------------------------------------------------------------------------------ writing
|
| 203 |
+
|
| 204 |
+
def frames_of(path):
|
| 205 |
+
import av
|
| 206 |
+
with av.open(path) as c:
|
| 207 |
+
for fr in c.decode(video=0):
|
| 208 |
+
yield fr.to_ndarray(format="rgb24")
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def flat_row(i, ann, n, idx0):
|
| 212 |
+
s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"]
|
| 213 |
+
att = ann["attempts"]
|
| 214 |
+
a0 = att[0]
|
| 215 |
+
return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n,
|
| 216 |
+
batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"],
|
| 217 |
+
memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"),
|
| 218 |
+
episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att],
|
| 219 |
+
harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"),
|
| 220 |
+
effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"),
|
| 221 |
+
task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"),
|
| 222 |
+
category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"],
|
| 223 |
+
success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att],
|
| 224 |
+
feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att],
|
| 225 |
+
auto_ended=[a.get("auto_ended") for a in att],
|
| 226 |
+
corrected_later_in_run=[a.get("corrected_later_in_run") for a in att],
|
| 227 |
+
error_event_in_attempt=[a.get("error_event_in_attempt") for a in att],
|
| 228 |
+
run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"),
|
| 229 |
+
n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]),
|
| 230 |
+
first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def cmd_plan(a):
|
| 234 |
+
task_order = {}
|
| 235 |
+
if a.task_set and os.path.exists(a.task_set):
|
| 236 |
+
for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")):
|
| 237 |
+
task_order[line.split(":")[0].strip()] = i
|
| 238 |
+
batches = [b for b in a.batches.split(",") if b] if a.batches else None
|
| 239 |
+
eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order)
|
| 240 |
+
if a.limit:
|
| 241 |
+
eps = eps[:a.limit]
|
| 242 |
+
paper = paper_tasks(a.paper)
|
| 243 |
+
idx0 = 0
|
| 244 |
+
for i, e in enumerate(eps):
|
| 245 |
+
ann = e["ann"]
|
| 246 |
+
tname = ann["task"]["name"]
|
| 247 |
+
if tname in paper:
|
| 248 |
+
ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"}
|
| 249 |
+
ann["episode_index"] = i
|
| 250 |
+
ann["dataset_index_range"] = [idx0, idx0 + e["n"]]
|
| 251 |
+
e["index"], e["from"] = i, idx0
|
| 252 |
+
idx0 += e["n"]
|
| 253 |
+
del e["key"]
|
| 254 |
+
os.makedirs(a.work, exist_ok=True)
|
| 255 |
+
with open(os.path.join(a.work, "plan.json"), "w") as f:
|
| 256 |
+
json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f,
|
| 257 |
+
ensure_ascii=False)
|
| 258 |
+
print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def shard_range(n_eps, i, k):
|
| 262 |
+
return (n_eps * i) // k, (n_eps * (i + 1)) // k
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def cmd_shard(a):
|
| 266 |
+
from lerobot.datasets.lerobot_dataset import LeRobotDataset
|
| 267 |
+
t0 = time.time()
|
| 268 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 269 |
+
eps = plan["episodes"]
|
| 270 |
+
lo, hi = shard_range(len(eps), a.shard, a.nshards)
|
| 271 |
+
out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}")
|
| 272 |
+
if os.path.exists(os.path.join(out, "DONE")):
|
| 273 |
+
print(f"shard {a.shard}: done already", flush=True)
|
| 274 |
+
return
|
| 275 |
+
shutil.rmtree(out, ignore_errors=True)
|
| 276 |
+
ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out,
|
| 277 |
+
robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads,
|
| 278 |
+
vcodec=a.vcodec)
|
| 279 |
+
nfr = 0
|
| 280 |
+
for e in eps[lo:hi]:
|
| 281 |
+
d, ann, n = e["dir"], e["ann"], e["n"]
|
| 282 |
+
fr = np.load(os.path.join(d, "frames.npz"))
|
| 283 |
+
assert len(fr["action"]) == n, d
|
| 284 |
+
succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]}
|
| 285 |
+
evc = np.zeros(n, np.int64)
|
| 286 |
+
for ev in ann["task_events"]:
|
| 287 |
+
if 0 <= ev["frame"] < n:
|
| 288 |
+
evc[ev["frame"]] += 1
|
| 289 |
+
state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32)
|
| 290 |
+
instr = ann["task"]["instruction"]
|
| 291 |
+
k = 0
|
| 292 |
+
for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))):
|
| 293 |
+
if k >= n:
|
| 294 |
+
break
|
| 295 |
+
ds.add_frame({
|
| 296 |
+
"observation.images.image": img, "observation.images.wrist_image": wr,
|
| 297 |
+
"observation.state": state[k],
|
| 298 |
+
"observation.joint_pos": fr["joint_pos"][k].astype(np.float32),
|
| 299 |
+
"observation.joint_vel": fr["joint_vel"][k].astype(np.float32),
|
| 300 |
+
"observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32),
|
| 301 |
+
"observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32),
|
| 302 |
+
"action": fr["action"][k].astype(np.float32),
|
| 303 |
+
"annotation.attempt_index": np.array([fr["attempt"][k]], np.int64),
|
| 304 |
+
"annotation.command_index": np.array([fr["command"][k]], np.int64),
|
| 305 |
+
"annotation.phase": np.array([fr["phase"][k]], np.int64),
|
| 306 |
+
"annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64),
|
| 307 |
+
"annotation.task_event": np.array([evc[k]], np.int64),
|
| 308 |
+
"task": instr,
|
| 309 |
+
})
|
| 310 |
+
k += 1
|
| 311 |
+
if k != n:
|
| 312 |
+
raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames")
|
| 313 |
+
ds.save_episode()
|
| 314 |
+
nfr += n
|
| 315 |
+
ds.finalize()
|
| 316 |
+
shutil.rmtree(os.path.join(out, "images"), ignore_errors=True)
|
| 317 |
+
open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n")
|
| 318 |
+
print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def cmd_merge(a):
|
| 322 |
+
from pathlib import Path
|
| 323 |
+
from lerobot.datasets.aggregate import aggregate_datasets
|
| 324 |
+
t0 = time.time()
|
| 325 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 326 |
+
eps = plan["episodes"]
|
| 327 |
+
roots, ids = [], []
|
| 328 |
+
for i in range(a.nshards):
|
| 329 |
+
lo, hi = shard_range(len(eps), i, a.nshards)
|
| 330 |
+
if hi <= lo:
|
| 331 |
+
continue
|
| 332 |
+
r = os.path.join(a.work, "shards", f"shard_{i:03d}")
|
| 333 |
+
if not os.path.exists(os.path.join(r, "DONE")):
|
| 334 |
+
raise SystemExit(f"shard {i} is not done")
|
| 335 |
+
roots.append(Path(r))
|
| 336 |
+
ids.append(f"{plan['repo_id']}-shard{i:03d}")
|
| 337 |
+
if os.path.exists(a.out):
|
| 338 |
+
raise SystemExit(f"{a.out} exists; refusing to overwrite")
|
| 339 |
+
aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out))
|
| 340 |
+
print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True)
|
| 341 |
+
write_sidecars(a, plan)
|
| 342 |
+
print(f"merge done in {time.time() - t0:.0f}s", flush=True)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def write_sidecars(a, plan):
|
| 346 |
+
eps, paper = plan["episodes"], plan["paper"]
|
| 347 |
+
lff = os.path.join(a.out, "lff")
|
| 348 |
+
for sub in ("annotations", "sim_state", "final", "code"):
|
| 349 |
+
os.makedirs(os.path.join(lff, sub), exist_ok=True)
|
| 350 |
+
rows, runs, tasks = [], {}, {}
|
| 351 |
+
for e in eps:
|
| 352 |
+
i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"]
|
| 353 |
+
name = f"episode_{i:06d}"
|
| 354 |
+
if os.path.exists(os.path.join(d, "sim_state.npy")):
|
| 355 |
+
shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy"))
|
| 356 |
+
shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz"))
|
| 357 |
+
for cam, key in (("agentview", "image"), ("wrist", "wrist_image")):
|
| 358 |
+
shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png"))
|
| 359 |
+
with open(os.path.join(lff, "annotations", name + ".json"), "w") as f:
|
| 360 |
+
json.dump(ann, f, indent=1, ensure_ascii=False)
|
| 361 |
+
rows.append(flat_row(i, ann, n, e["from"]))
|
| 362 |
+
tname = ann["task"]["name"]
|
| 363 |
+
rk = (ann["source"]["batch"], ann["source"]["run"])
|
| 364 |
+
r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"),
|
| 365 |
+
run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"],
|
| 366 |
+
memory_free_chain_of=ann["source"].get("memory_free_chain_of"),
|
| 367 |
+
memory_free_rep=ann["source"].get("memory_free_rep"), task=tname,
|
| 368 |
+
seed=ann["task"]["seed"], model=ann["agent"].get("model"),
|
| 369 |
+
harness=ann["agent"].get("harness"),
|
| 370 |
+
harness_version=ann["agent"].get("harness_version"),
|
| 371 |
+
codex_catalog=ann["agent"].get("codex_catalog"),
|
| 372 |
+
outcome_class=ann["run_outcome"].get("outcome_class"),
|
| 373 |
+
attempt_history=ann["run_outcome"].get("attempt_history"),
|
| 374 |
+
agent_final_report=ann["run_outcome"].get("agent_final_report"),
|
| 375 |
+
episodes=[]))
|
| 376 |
+
for x in ann["attempts"]:
|
| 377 |
+
r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success")))
|
| 378 |
+
if tname not in tasks:
|
| 379 |
+
tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")}
|
| 380 |
+
if tname in paper:
|
| 381 |
+
tasks[tname]["paper"] = paper[tname]
|
| 382 |
+
tasks[tname]["instances"] = {}
|
| 383 |
+
tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"]
|
| 384 |
+
# memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id)
|
| 385 |
+
by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")}
|
| 386 |
+
for r in runs.values():
|
| 387 |
+
if r.get("memory_free_chain_of"):
|
| 388 |
+
r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"]))
|
| 389 |
+
for (b, rn), r in runs.items():
|
| 390 |
+
r["memory_free_retries"] = sorted((x["run"] for x in runs.values()
|
| 391 |
+
if x["batch"] == b and x.get("memory_free_chain_of_run") == rn),
|
| 392 |
+
key=lambda q: runs[(b, q)].get("memory_free_rep") or 0)
|
| 393 |
+
with open(os.path.join(lff, "episodes.jsonl"), "w") as f:
|
| 394 |
+
for row in rows:
|
| 395 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 396 |
+
with open(os.path.join(lff, "runs.jsonl"), "w") as f:
|
| 397 |
+
for r in runs.values():
|
| 398 |
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 399 |
+
with open(os.path.join(lff, "tasks.json"), "w") as f:
|
| 400 |
+
json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False)
|
| 401 |
+
with open(os.path.join(lff, "batches.json"), "w") as f:
|
| 402 |
+
json.dump(BATCH_NOTES, f, indent=1)
|
| 403 |
+
with open(os.path.join(lff, "rejected.json"), "w") as f:
|
| 404 |
+
json.dump(plan["rejected"], f, indent=1)
|
| 405 |
+
here = os.path.dirname(os.path.abspath(__file__))
|
| 406 |
+
for s in ("lerobot_replay.py", "lerobot_export.py"):
|
| 407 |
+
shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s))
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def main():
|
| 411 |
+
ap = argparse.ArgumentParser()
|
| 412 |
+
ap.add_argument("step", choices=["plan", "shard", "merge"])
|
| 413 |
+
ap.add_argument("--work", required=True)
|
| 414 |
+
ap.add_argument("--raw", default="")
|
| 415 |
+
ap.add_argument("--runs-root", default="")
|
| 416 |
+
ap.add_argument("--out", default="")
|
| 417 |
+
ap.add_argument("--paper", default="")
|
| 418 |
+
ap.add_argument("--task-set", default="")
|
| 419 |
+
ap.add_argument("--repo-id", default="lffbench/agent-replays")
|
| 420 |
+
ap.add_argument("--batches", default="")
|
| 421 |
+
ap.add_argument("--limit", type=int, default=0)
|
| 422 |
+
ap.add_argument("--shard", type=int, default=0)
|
| 423 |
+
ap.add_argument("--nshards", type=int, default=1)
|
| 424 |
+
ap.add_argument("--threads", type=int, default=2)
|
| 425 |
+
ap.add_argument("--vcodec", default="libsvtav1")
|
| 426 |
+
a = ap.parse_args()
|
| 427 |
+
{"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
if __name__ == "__main__":
|
| 431 |
+
main()
|
leaf/code/compound-lh-20261102-clh_20261102_deepseek/lerobot_replay.py
ADDED
|
@@ -0,0 +1,744 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay
|
| 2 |
+
against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the
|
| 3 |
+
LeRobot export (scripts/lerobot_export.py).
|
| 4 |
+
|
| 5 |
+
python scripts/lerobot_replay.py check <run_dir> [<run_dir> ...] [--json out.json] # replay only, print fidelity
|
| 6 |
+
python scripts/lerobot_replay.py record <run_dir> --out <raw_root> [--res 256]
|
| 7 |
+
|
| 8 |
+
Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot
|
| 9 |
+
commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite
|
| 10 |
+
is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly
|
| 11 |
+
like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same
|
| 12 |
+
outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width,
|
| 13 |
+
ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code
|
| 14 |
+
hashes equal the current files are expected to match (check_code()).
|
| 15 |
+
|
| 16 |
+
Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB,
|
| 17 |
+
proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes:
|
| 18 |
+
protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode
|
| 19 |
+
per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the
|
| 20 |
+
fidelity check runs in record mode too. Per episode the recorder writes <raw_root>/<batch>/<run>/epNN/:
|
| 21 |
+
agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes)
|
| 22 |
+
frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase
|
| 23 |
+
sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel)
|
| 24 |
+
final_*.png, final.npz observation after the last control step (the state the outcome was judged in)
|
| 25 |
+
annotation.json episode annotation (build_annotation)
|
| 26 |
+
and <raw_root>/<batch>/<run>/replay.json (fidelity) when the whole run is done.
|
| 27 |
+
"""
|
| 28 |
+
import argparse
|
| 29 |
+
import ast
|
| 30 |
+
import hashlib
|
| 31 |
+
import importlib
|
| 32 |
+
import json
|
| 33 |
+
import math
|
| 34 |
+
import os
|
| 35 |
+
import pkgutil
|
| 36 |
+
import re
|
| 37 |
+
import shutil
|
| 38 |
+
import sys
|
| 39 |
+
import time
|
| 40 |
+
from collections import defaultdict
|
| 41 |
+
|
| 42 |
+
import numpy as np
|
| 43 |
+
|
| 44 |
+
LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 45 |
+
sys.path.insert(0, LFF_ROOT)
|
| 46 |
+
|
| 47 |
+
from lffbench import envs # noqa: E402
|
| 48 |
+
from lffbench import tasks as task_pkg # noqa: E402
|
| 49 |
+
from lffbench.agent import camera as C # noqa: E402
|
| 50 |
+
from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402
|
| 51 |
+
from lffbench.task_base import TASKS # noqa: E402
|
| 52 |
+
|
| 53 |
+
for _m in pkgutil.iter_modules(task_pkg.__path__):
|
| 54 |
+
importlib.import_module(f"lffbench.tasks.{_m.name}")
|
| 55 |
+
|
| 56 |
+
# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the
|
| 57 |
+
# task's outcome() check after `finish` (the arm holds still; not an agent action)
|
| 58 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 59 |
+
FPS = 20
|
| 60 |
+
SCHEMA = "lff-replay-1"
|
| 61 |
+
|
| 62 |
+
# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR"
|
| 63 |
+
ERROR_FLAGS = ("trap_fired", "recovered_in_attempt")
|
| 64 |
+
ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events",
|
| 65 |
+
"n_missed_strikes", "n_open_gripper_pushes")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def load_jsonl(p):
|
| 69 |
+
out = []
|
| 70 |
+
if not os.path.exists(p):
|
| 71 |
+
return out
|
| 72 |
+
with open(p) as f:
|
| 73 |
+
for line in f:
|
| 74 |
+
line = line.strip()
|
| 75 |
+
if line:
|
| 76 |
+
try:
|
| 77 |
+
out.append(json.loads(line))
|
| 78 |
+
except ValueError:
|
| 79 |
+
pass
|
| 80 |
+
return out
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def norm_json(o):
|
| 84 |
+
return json.loads(json.dumps(o, default=_json_default))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def sha256(p):
|
| 88 |
+
with open(p, "rb") as f:
|
| 89 |
+
return hashlib.sha256(f.read()).hexdigest()
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def check_code(run_dir):
|
| 93 |
+
"""[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract."""
|
| 94 |
+
p = os.path.join(run_dir, "contract.json")
|
| 95 |
+
if not os.path.exists(p):
|
| 96 |
+
return [("contract.json", None, None)]
|
| 97 |
+
files = json.load(open(p))["contract"].get("server_code_files", {})
|
| 98 |
+
bad = []
|
| 99 |
+
for f, h in files.items():
|
| 100 |
+
q = os.path.join(LFF_ROOT, f)
|
| 101 |
+
cur = sha256(q) if os.path.exists(q) else None
|
| 102 |
+
if cur != h:
|
| 103 |
+
bad.append((f, h, cur))
|
| 104 |
+
return bad
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def diff_json(a, b, path="", tol=0.0, out=None, limit=20):
|
| 108 |
+
"""Differences between two JSON values (numbers compared with an absolute tolerance)."""
|
| 109 |
+
out = [] if out is None else out
|
| 110 |
+
if len(out) >= limit:
|
| 111 |
+
return out
|
| 112 |
+
if isinstance(a, dict) and isinstance(b, dict):
|
| 113 |
+
for k in sorted(set(a) | set(b)):
|
| 114 |
+
if k not in a or k not in b:
|
| 115 |
+
out.append((f"{path}.{k}", a.get(k, "<missing>"), b.get(k, "<missing>")))
|
| 116 |
+
else:
|
| 117 |
+
diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit)
|
| 118 |
+
elif isinstance(a, list) and isinstance(b, list):
|
| 119 |
+
if len(a) != len(b):
|
| 120 |
+
out.append((path, f"len {len(a)}", f"len {len(b)}"))
|
| 121 |
+
else:
|
| 122 |
+
for i, (x, y) in enumerate(zip(a, b)):
|
| 123 |
+
diff_json(x, y, f"{path}[{i}]", tol, out, limit)
|
| 124 |
+
elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
|
| 125 |
+
if a != b:
|
| 126 |
+
out.append((path, a, b))
|
| 127 |
+
elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))):
|
| 128 |
+
out.append((path, a, b))
|
| 129 |
+
return out
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def error_event(o):
|
| 133 |
+
"""True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none."""
|
| 134 |
+
if not isinstance(o, dict):
|
| 135 |
+
return None
|
| 136 |
+
keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o]
|
| 137 |
+
if not keys:
|
| 138 |
+
return None
|
| 139 |
+
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)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# ====================================================================================================== logs -> notes
|
| 143 |
+
|
| 144 |
+
class RunLog:
|
| 145 |
+
"""Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's
|
| 146 |
+
narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition."""
|
| 147 |
+
|
| 148 |
+
def __init__(self, run_dir, manifest=None):
|
| 149 |
+
self.run_dir = os.path.abspath(run_dir.rstrip("/"))
|
| 150 |
+
self.run = os.path.basename(self.run_dir)
|
| 151 |
+
self.batch = os.path.basename(os.path.dirname(self.run_dir))
|
| 152 |
+
self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl"))
|
| 153 |
+
self.start = next(e for e in self.ev if e["ev"] == "session_start")
|
| 154 |
+
self.calls, self.dones, self.harness_status = {}, [], []
|
| 155 |
+
last = None
|
| 156 |
+
for e in self.ev:
|
| 157 |
+
if e["ev"] == "call":
|
| 158 |
+
self.calls[(int(e["attempt"]), int(e["step"]))] = e
|
| 159 |
+
last = e
|
| 160 |
+
elif e["ev"] == "done":
|
| 161 |
+
self.dones.append(e)
|
| 162 |
+
last = e
|
| 163 |
+
elif e["ev"] == "http" and last is not None and "think_s" not in last:
|
| 164 |
+
ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \
|
| 165 |
+
(last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe"))
|
| 166 |
+
if ok:
|
| 167 |
+
last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s")
|
| 168 |
+
self.manifest = manifest or {}
|
| 169 |
+
self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {}
|
| 170 |
+
p = os.path.join(self.run_dir, "harness.json")
|
| 171 |
+
self.harness = json.load(open(p)) if os.path.exists(p) else {}
|
| 172 |
+
self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl"))
|
| 173 |
+
self._narration()
|
| 174 |
+
|
| 175 |
+
# ---------------------------------------------------------------- agent narration
|
| 176 |
+
def _narration(self):
|
| 177 |
+
"""notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one;
|
| 178 |
+
finish_notes[attempt] likewise for the agent's finish call; final_report = its last message."""
|
| 179 |
+
self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", []
|
| 180 |
+
buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
|
| 181 |
+
attempt = 1
|
| 182 |
+
|
| 183 |
+
def take():
|
| 184 |
+
nonlocal buf
|
| 185 |
+
out = {k: v for k, v in buf.items() if v}
|
| 186 |
+
buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
|
| 187 |
+
return out
|
| 188 |
+
|
| 189 |
+
last_msg = ""
|
| 190 |
+
for t in self.traj:
|
| 191 |
+
if t.get("kind") == "header":
|
| 192 |
+
self.headers.append(t.get("agent") or {})
|
| 193 |
+
continue
|
| 194 |
+
if t.get("kind") != "step":
|
| 195 |
+
continue
|
| 196 |
+
if (t.get("message") or "").strip():
|
| 197 |
+
buf["messages"].append(t["message"].strip())
|
| 198 |
+
last_msg = t["message"].strip()
|
| 199 |
+
if (t.get("reasoning_content") or "").strip():
|
| 200 |
+
buf["reasoning"].append(t["reasoning_content"].strip())
|
| 201 |
+
res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])}
|
| 202 |
+
for c in t.get("tool_calls") or []:
|
| 203 |
+
fn, args = c.get("function_name"), c.get("arguments") or {}
|
| 204 |
+
if fn == "shell":
|
| 205 |
+
buf["shell"].append(str(args.get("command", ""))[:2000])
|
| 206 |
+
elif fn == "view_images":
|
| 207 |
+
buf["viewed"].extend(args.get("paths") or [])
|
| 208 |
+
elif fn == "robot":
|
| 209 |
+
cmd = str(args.get("command", "")).strip()
|
| 210 |
+
r = res.get(c.get("tool_call_id")) or {}
|
| 211 |
+
try:
|
| 212 |
+
rep = json.loads(r.get("content") or "{}")
|
| 213 |
+
except ValueError:
|
| 214 |
+
rep = {}
|
| 215 |
+
word = cmd.split()[0] if cmd else ""
|
| 216 |
+
m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", "")))
|
| 217 |
+
if word in ("move_eef", "observe") and m:
|
| 218 |
+
a, s = int(m.group(1)), int(m.group(2))
|
| 219 |
+
n = take()
|
| 220 |
+
n["command"] = cmd
|
| 221 |
+
self.notes[(a, s)] = n
|
| 222 |
+
attempt = a
|
| 223 |
+
elif word in ("finish", "done"):
|
| 224 |
+
n = take()
|
| 225 |
+
n["command"] = cmd
|
| 226 |
+
n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)}
|
| 227 |
+
self.finish_notes.setdefault(attempt, n)
|
| 228 |
+
if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"):
|
| 229 |
+
attempt += 1
|
| 230 |
+
# status / help / errors: their narration stays in the buffer for the next command
|
| 231 |
+
self.final_report = last_msg
|
| 232 |
+
|
| 233 |
+
# ---------------------------------------------------------------- run-level labels
|
| 234 |
+
def attempts(self):
|
| 235 |
+
out = []
|
| 236 |
+
for e in self.dones:
|
| 237 |
+
o = e.get("outcome") or {}
|
| 238 |
+
if isinstance(o, str):
|
| 239 |
+
try:
|
| 240 |
+
o = ast.literal_eval(o)
|
| 241 |
+
except (ValueError, SyntaxError):
|
| 242 |
+
o = {}
|
| 243 |
+
out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o,
|
| 244 |
+
reason=e.get("reason") or ""))
|
| 245 |
+
return sorted(out, key=lambda x: x["attempt"])
|
| 246 |
+
|
| 247 |
+
def condition(self):
|
| 248 |
+
s, en = self.start, self.entry
|
| 249 |
+
mem = s.get("memory", en.get("mem"))
|
| 250 |
+
chain = en.get("chain")
|
| 251 |
+
if mem == "full":
|
| 252 |
+
cond = "with_history"
|
| 253 |
+
elif chain:
|
| 254 |
+
cond = "memory_free_retry"
|
| 255 |
+
else:
|
| 256 |
+
cond = "independent_single_attempt"
|
| 257 |
+
return cond, chain
|
| 258 |
+
|
| 259 |
+
def outcome_class(self):
|
| 260 |
+
"""CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None."""
|
| 261 |
+
att = self.attempts()
|
| 262 |
+
if not att or self.start.get("memory") != "full":
|
| 263 |
+
return None, "".join("S" if a["success"] else "F" for a in att)
|
| 264 |
+
hist = "".join("S" if a["success"] else "F" for a in att)
|
| 265 |
+
if att[0]["success"]:
|
| 266 |
+
ev = error_event(att[0]["outcome"])
|
| 267 |
+
cls = "S?" if ev is None else ("IR" if ev else "CS")
|
| 268 |
+
else:
|
| 269 |
+
cls = "XR" if any(a["success"] for a in att) else "F"
|
| 270 |
+
return cls, hist
|
| 271 |
+
|
| 272 |
+
def agent_info(self):
|
| 273 |
+
h, en = self.harness, self.entry
|
| 274 |
+
hdr = self.headers[0] if self.headers else {}
|
| 275 |
+
return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"),
|
| 276 |
+
harness_version=h.get("version") or hdr.get("version"),
|
| 277 |
+
harness_binary_sha256=(h.get("binary") or {}).get("sha256"),
|
| 278 |
+
model=h.get("model") or en.get("model") or hdr.get("model_name"),
|
| 279 |
+
effort=h.get("effort") or en.get("effort") or hdr.get("effort"),
|
| 280 |
+
provider=h.get("provider") or en.get("provider"),
|
| 281 |
+
codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"),
|
| 282 |
+
jail=en.get("jail"))
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
# ====================================================================================================== recording
|
| 286 |
+
|
| 287 |
+
class EpisodeSink:
|
| 288 |
+
"""Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed."""
|
| 289 |
+
|
| 290 |
+
def __init__(self, path):
|
| 291 |
+
self.path = path
|
| 292 |
+
os.makedirs(path, exist_ok=True)
|
| 293 |
+
self.w = None
|
| 294 |
+
self.num = defaultdict(list)
|
| 295 |
+
self.n = 0
|
| 296 |
+
|
| 297 |
+
def add(self, st, imgs):
|
| 298 |
+
import imageio
|
| 299 |
+
if self.w is None:
|
| 300 |
+
self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb",
|
| 301 |
+
pixelformat="rgb24", macro_block_size=1,
|
| 302 |
+
ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error")
|
| 303 |
+
for k in ("agentview", "wrist")]
|
| 304 |
+
for w, im in zip(self.w, imgs):
|
| 305 |
+
w.append_data(im)
|
| 306 |
+
for k, v in st.items():
|
| 307 |
+
self.num[k].append(v)
|
| 308 |
+
self.n += 1
|
| 309 |
+
|
| 310 |
+
def close(self, final_state, final_imgs):
|
| 311 |
+
from PIL import Image
|
| 312 |
+
if self.w is not None:
|
| 313 |
+
for w in self.w:
|
| 314 |
+
w.close()
|
| 315 |
+
arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"}
|
| 316 |
+
np.savez(os.path.join(self.path, "frames.npz"), **arr)
|
| 317 |
+
if self.num.get("sim_state"):
|
| 318 |
+
np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64))
|
| 319 |
+
np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()})
|
| 320 |
+
for k, im in zip(("agentview", "wrist"), final_imgs):
|
| 321 |
+
Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png"))
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
class Recorder:
|
| 325 |
+
"""Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink."""
|
| 326 |
+
|
| 327 |
+
def __init__(self, rp, res):
|
| 328 |
+
self.rp, self.res = rp, int(res)
|
| 329 |
+
self.active = False
|
| 330 |
+
self.sink = None
|
| 331 |
+
self.cur = dict(attempt=1, command=-1, phase=PHASES["move"])
|
| 332 |
+
env = rp.task.env
|
| 333 |
+
self.env, self.rob = env, env.robots[0]
|
| 334 |
+
self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist"))
|
| 335 |
+
orig = env.step
|
| 336 |
+
|
| 337 |
+
def step(a):
|
| 338 |
+
if self.active and self.sink is not None:
|
| 339 |
+
self.capture(np.asarray(a, np.float64))
|
| 340 |
+
out = orig(a)
|
| 341 |
+
if self.active and self.sink is not None:
|
| 342 |
+
self.rp.poll_events(self.sink.n - 1)
|
| 343 |
+
return out
|
| 344 |
+
|
| 345 |
+
env.step = step
|
| 346 |
+
|
| 347 |
+
@property
|
| 348 |
+
def n(self):
|
| 349 |
+
return self.sink.n if self.sink is not None else 0
|
| 350 |
+
|
| 351 |
+
def state(self):
|
| 352 |
+
import robosuite.utils.transform_utils as T
|
| 353 |
+
env, rob = self.env, self.rob
|
| 354 |
+
d = env.sim.data
|
| 355 |
+
eef = np.array(d.site_xpos[rob.eef_site_id], np.float64)
|
| 356 |
+
q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw")
|
| 357 |
+
gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64)
|
| 358 |
+
try:
|
| 359 |
+
flat = np.asarray(env.sim.get_state().flatten(), np.float64)
|
| 360 |
+
except Exception:
|
| 361 |
+
flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64)
|
| 362 |
+
sk = self.rp.task.sk
|
| 363 |
+
return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64),
|
| 364 |
+
gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64),
|
| 365 |
+
joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64),
|
| 366 |
+
gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64),
|
| 367 |
+
eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)),
|
| 368 |
+
sim_time=np.float64(d.time), sim_state=flat)
|
| 369 |
+
|
| 370 |
+
def images(self):
|
| 371 |
+
return [envs.render(self.env, c, self.res) for c in self.cams]
|
| 372 |
+
|
| 373 |
+
def capture(self, a):
|
| 374 |
+
st = self.state()
|
| 375 |
+
st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]),
|
| 376 |
+
phase=np.int64(self.cur["phase"]))
|
| 377 |
+
self.sink.add(st, self.images())
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
class RunReplay:
|
| 381 |
+
def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None):
|
| 382 |
+
self.run_dir = os.path.abspath(run_dir.rstrip("/"))
|
| 383 |
+
self.run_name = os.path.basename(self.run_dir)
|
| 384 |
+
self.log = RunLog(self.run_dir, manifest)
|
| 385 |
+
self.ev = self.log.ev
|
| 386 |
+
self.start = self.log.start
|
| 387 |
+
cp = os.path.join(self.run_dir, "contract.json")
|
| 388 |
+
self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {}
|
| 389 |
+
spec = self.contract.get("image_spec") or {}
|
| 390 |
+
self.image_res = int(spec.get("width", 512))
|
| 391 |
+
self.code_diff = check_code(self.run_dir)
|
| 392 |
+
s = self.start
|
| 393 |
+
self.task = TASKS[s["task"]](cam_res=self.image_res)
|
| 394 |
+
inst = self.task.sample_instance(s["seed"])
|
| 395 |
+
logged = s.get("inst") or {}
|
| 396 |
+
sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")})
|
| 397 |
+
self.inst_diff = diff_json(sampled, logged, "inst")
|
| 398 |
+
if s.get("arm", "none") not in (None, "none") or logged.get("nominal"):
|
| 399 |
+
inst.update(logged) # controlled arms / nominal: the server overrode these instance fields
|
| 400 |
+
self.inst_diff = []
|
| 401 |
+
self.inst = inst
|
| 402 |
+
self.protocol = getattr(self.task, "protocol", "cross")
|
| 403 |
+
self.k = int(s.get("k") or self.task.max_attempts)
|
| 404 |
+
self.attempt = 1
|
| 405 |
+
self.mismatch = [] # (where, what, logged, replayed)
|
| 406 |
+
self.n_checked = 0
|
| 407 |
+
self.max_dev_m = 0.0
|
| 408 |
+
self.unfinished = None
|
| 409 |
+
self.rec = Recorder(self, res) if record else None
|
| 410 |
+
self.res = int(res)
|
| 411 |
+
self.out_root = out_root
|
| 412 |
+
self.n_mon = 0
|
| 413 |
+
self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0
|
| 414 |
+
self.episodes = [] # summaries of the written episodes
|
| 415 |
+
self.task.reset_instance(self.inst)
|
| 416 |
+
self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
|
| 417 |
+
sim = self.task.env.sim
|
| 418 |
+
bid = sim.model.body_name2id("robot0_base")
|
| 419 |
+
self.base_off = np.array(sim.data.body_xpos[bid], float).copy()
|
| 420 |
+
if self.rec:
|
| 421 |
+
self._open_episode()
|
| 422 |
+
|
| 423 |
+
# ------------------------------------------------------------------ episodes
|
| 424 |
+
def _ep_dir(self):
|
| 425 |
+
return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}")
|
| 426 |
+
|
| 427 |
+
def _open_episode(self):
|
| 428 |
+
self.rec.sink = EpisodeSink(self._ep_dir())
|
| 429 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
|
| 430 |
+
self.rec.active = True
|
| 431 |
+
self.events, self.spans, self.ep_attempts = [], [], []
|
| 432 |
+
self.ep_initial = self.rec.state() # state right after the reset (before frame 0)
|
| 433 |
+
|
| 434 |
+
def close_episode(self):
|
| 435 |
+
if not self.rec:
|
| 436 |
+
self.ep_attempts = []
|
| 437 |
+
return
|
| 438 |
+
sink = self.rec.sink
|
| 439 |
+
st = self.rec.state()
|
| 440 |
+
imgs = self.rec.images()
|
| 441 |
+
st.pop("sim_state", None)
|
| 442 |
+
sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs)
|
| 443 |
+
ann = build_annotation(self, sink)
|
| 444 |
+
with open(os.path.join(sink.path, "annotation.json"), "w") as f:
|
| 445 |
+
json.dump(ann, f, indent=1, default=_json_default)
|
| 446 |
+
self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n,
|
| 447 |
+
attempts=[a["attempt"] for a in self.ep_attempts]))
|
| 448 |
+
self.rec.active = False
|
| 449 |
+
self.rec.sink = None
|
| 450 |
+
self.ep_index += 1
|
| 451 |
+
|
| 452 |
+
# ------------------------------------------------------------------ monitor events (task-side error events)
|
| 453 |
+
def poll_events(self, frame):
|
| 454 |
+
mon = getattr(self.task, "mon", None)
|
| 455 |
+
evs = mon.get("events") if isinstance(mon, dict) else None
|
| 456 |
+
if not isinstance(evs, list):
|
| 457 |
+
return
|
| 458 |
+
if len(evs) < self.n_mon: # monitor was rebuilt
|
| 459 |
+
self.n_mon = 0
|
| 460 |
+
for e in evs[self.n_mon:]:
|
| 461 |
+
self.events.append(dict(frame=int(frame), attempt=self.attempt,
|
| 462 |
+
event=norm_json(e) if isinstance(e, dict) else str(e)))
|
| 463 |
+
self.n_mon = len(evs)
|
| 464 |
+
|
| 465 |
+
# ------------------------------------------------------------------ state as the server reports it
|
| 466 |
+
def proprio_la(self):
|
| 467 |
+
p = self.ex.proprio()
|
| 468 |
+
pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off]
|
| 469 |
+
return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"])
|
| 470 |
+
|
| 471 |
+
def compare(self, where, rep_logged, rep):
|
| 472 |
+
self.n_checked += 1
|
| 473 |
+
for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"):
|
| 474 |
+
if k not in rep_logged or k not in rep:
|
| 475 |
+
continue
|
| 476 |
+
a, b = rep_logged[k], rep[k]
|
| 477 |
+
if k == "eef_pos":
|
| 478 |
+
dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float))))
|
| 479 |
+
self.max_dev_m = max(self.max_dev_m, dev)
|
| 480 |
+
if dev > 1.5e-4:
|
| 481 |
+
self.mismatch.append((where, k, a, b))
|
| 482 |
+
elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4):
|
| 483 |
+
self.mismatch.append((where, k, a, b))
|
| 484 |
+
if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)):
|
| 485 |
+
self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok")))
|
| 486 |
+
|
| 487 |
+
def _span(self, e, f0, kind):
|
| 488 |
+
if self.rec:
|
| 489 |
+
self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0,
|
| 490 |
+
frame_end=self.rec.n))
|
| 491 |
+
|
| 492 |
+
# ------------------------------------------------------------------ commands (robot_server._handle_v2)
|
| 493 |
+
def move_eef(self, e):
|
| 494 |
+
args = e.get("args") or {}
|
| 495 |
+
where = f"a{e['attempt']}s{e['step']}"
|
| 496 |
+
logged = e.get("report") or {}
|
| 497 |
+
f0 = self.rec.n if self.rec else 0
|
| 498 |
+
p = self.ex.proprio()
|
| 499 |
+
if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}:
|
| 500 |
+
self._span(e, f0, "error")
|
| 501 |
+
return self.compare(where, logged, dict(ok=False))
|
| 502 |
+
off = self.base_off
|
| 503 |
+
try:
|
| 504 |
+
cur = np.asarray(p["eef_pos"], float) - off
|
| 505 |
+
tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
|
| 506 |
+
yaw = float(args.get("yaw", p["eef_yaw_deg"]))
|
| 507 |
+
speed = None if args.get("speed") in (None, "") else float(args["speed"])
|
| 508 |
+
except (TypeError, ValueError):
|
| 509 |
+
self._span(e, f0, "error")
|
| 510 |
+
return self.compare(where, logged, dict(ok=False))
|
| 511 |
+
grip = args.get("gripper")
|
| 512 |
+
if grip not in (None, "open", "close"):
|
| 513 |
+
self._span(e, f0, "error")
|
| 514 |
+
return self.compare(where, logged, dict(ok=False))
|
| 515 |
+
moving = any(k in args for k in ("x", "y", "z", "yaw"))
|
| 516 |
+
tgt_w = np.asarray(tgt) + off
|
| 517 |
+
if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)):
|
| 518 |
+
self._span(e, f0, "rejected")
|
| 519 |
+
return self.compare(where, logged, dict(ok=False, **self.proprio_la()))
|
| 520 |
+
raw = {}
|
| 521 |
+
if self.rec:
|
| 522 |
+
self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"])
|
| 523 |
+
if moving:
|
| 524 |
+
mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw)
|
| 525 |
+
if speed is not None:
|
| 526 |
+
mv["speed"] = speed
|
| 527 |
+
raw.update(self.ex.call("move_to", mv).report)
|
| 528 |
+
if grip is not None:
|
| 529 |
+
if self.rec:
|
| 530 |
+
self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"])
|
| 531 |
+
raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report)
|
| 532 |
+
rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la())
|
| 533 |
+
self.compare(where, logged, rep)
|
| 534 |
+
lr = e.get("raw") or {}
|
| 535 |
+
for k in ("holding_object", "touched_object"):
|
| 536 |
+
if k in lr and k in raw and bool(lr[k]) != bool(raw[k]):
|
| 537 |
+
self.mismatch.append((where, "raw." + k, lr[k], raw[k]))
|
| 538 |
+
self._span(e, f0, "move_eef")
|
| 539 |
+
|
| 540 |
+
def observe(self, e):
|
| 541 |
+
f0 = self.rec.n if self.rec else 0
|
| 542 |
+
self._span(e, f0, "observe")
|
| 543 |
+
|
| 544 |
+
def done(self, e):
|
| 545 |
+
f0 = self.rec.n if self.rec else 0
|
| 546 |
+
if self.rec:
|
| 547 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"])
|
| 548 |
+
out = self.task.outcome(self.inst)
|
| 549 |
+
succ = bool(out["success"])
|
| 550 |
+
where = f"a{e['attempt']}done"
|
| 551 |
+
if succ != bool(e.get("success") in (True, "True")):
|
| 552 |
+
self.mismatch.append((where, "success", e.get("success"), succ))
|
| 553 |
+
lo = e.get("outcome") or {}
|
| 554 |
+
ro = norm_json({k: v for k, v in out.items() if k != "feedback"})
|
| 555 |
+
if isinstance(lo, dict):
|
| 556 |
+
for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8):
|
| 557 |
+
self.mismatch.append((where,) + d)
|
| 558 |
+
info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""),
|
| 559 |
+
feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")),
|
| 560 |
+
think_s=e.get("think_s"))
|
| 561 |
+
try:
|
| 562 |
+
info["feedback_f2"] = self.task.feedback(self.inst, out, "F2")
|
| 563 |
+
except Exception as ex_:
|
| 564 |
+
info["feedback_f2"] = f"<unavailable: {type(ex_).__name__}>"
|
| 565 |
+
if self.rec:
|
| 566 |
+
info["judge_frames"] = [f0, self.rec.n]
|
| 567 |
+
self.ep_attempts.append(info)
|
| 568 |
+
last = self.attempt >= self.k or succ or bool(out.get("terminal"))
|
| 569 |
+
if self.protocol == "cross" or last:
|
| 570 |
+
self.close_episode()
|
| 571 |
+
if last:
|
| 572 |
+
return True
|
| 573 |
+
self.attempt += 1
|
| 574 |
+
if self.protocol == "cross":
|
| 575 |
+
self.task.reset_instance(self.inst)
|
| 576 |
+
self.n_mon = 0
|
| 577 |
+
if self.rec:
|
| 578 |
+
self._open_episode()
|
| 579 |
+
elif self.rec:
|
| 580 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
|
| 581 |
+
self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
|
| 582 |
+
return False
|
| 583 |
+
|
| 584 |
+
def run(self):
|
| 585 |
+
t0 = time.time()
|
| 586 |
+
finished = False
|
| 587 |
+
for e in self.ev:
|
| 588 |
+
if e["ev"] == "call":
|
| 589 |
+
if e.get("cmd") == "move_eef":
|
| 590 |
+
self.move_eef(e)
|
| 591 |
+
elif e.get("cmd") == "observe":
|
| 592 |
+
self.observe(e)
|
| 593 |
+
else:
|
| 594 |
+
self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None))
|
| 595 |
+
elif e["ev"] == "done":
|
| 596 |
+
finished = self.done(e)
|
| 597 |
+
if finished:
|
| 598 |
+
break
|
| 599 |
+
self.unfinished = not finished
|
| 600 |
+
if not finished and self.rec and self.rec.sink is not None:
|
| 601 |
+
# the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged
|
| 602 |
+
if self.rec.n or self.ep_attempts:
|
| 603 |
+
self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True,
|
| 604 |
+
finish_reason="", feedback_shown="", auto_ended=False))
|
| 605 |
+
self.close_episode()
|
| 606 |
+
else:
|
| 607 |
+
shutil.rmtree(self.rec.sink.path, ignore_errors=True)
|
| 608 |
+
self.rec.sink = None
|
| 609 |
+
self.wall_s = time.time() - t0
|
| 610 |
+
return self
|
| 611 |
+
|
| 612 |
+
def summary(self):
|
| 613 |
+
return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"],
|
| 614 |
+
protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff),
|
| 615 |
+
n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6),
|
| 616 |
+
unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1),
|
| 617 |
+
first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]])
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
# ====================================================================================================== annotation
|
| 621 |
+
|
| 622 |
+
def task_info(task, inst):
|
| 623 |
+
cls = type(task)
|
| 624 |
+
return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable",
|
| 625 |
+
category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"),
|
| 626 |
+
max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)),
|
| 627 |
+
instruction=cls.instruction)
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
def build_annotation(rp, sink):
|
| 631 |
+
"""Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2
|
| 632 |
+
failure description), run-level outcome class, every robot command with its frame span and the agent's narration,
|
| 633 |
+
task-side error events with frame indices."""
|
| 634 |
+
log = rp.log
|
| 635 |
+
s = rp.start
|
| 636 |
+
cond, chain = log.condition()
|
| 637 |
+
cls, hist = log.outcome_class()
|
| 638 |
+
att_all = log.attempts()
|
| 639 |
+
attempts = []
|
| 640 |
+
for a in rp.ep_attempts:
|
| 641 |
+
a = dict(a)
|
| 642 |
+
n = a["attempt"]
|
| 643 |
+
later = [x for x in att_all if x["attempt"] > n]
|
| 644 |
+
a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later))
|
| 645 |
+
a["is_last_attempt_of_run"] = not later
|
| 646 |
+
fn = log.finish_notes.get(n)
|
| 647 |
+
if fn:
|
| 648 |
+
a["agent_finish"] = fn
|
| 649 |
+
a["error_event_in_attempt"] = error_event(a.get("outcome"))
|
| 650 |
+
attempts.append(a)
|
| 651 |
+
# post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command)
|
| 652 |
+
for a in attempts:
|
| 653 |
+
nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1])
|
| 654 |
+
if a.get("success") is False and nxt:
|
| 655 |
+
note = log.notes[nxt[0]]
|
| 656 |
+
a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note}
|
| 657 |
+
commands = []
|
| 658 |
+
for sp in rp.spans:
|
| 659 |
+
e = log.calls.get((sp["attempt"], sp["step"])) or {}
|
| 660 |
+
rep = e.get("report") or {}
|
| 661 |
+
c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"],
|
| 662 |
+
frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]),
|
| 663 |
+
args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"),
|
| 664 |
+
stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"),
|
| 665 |
+
gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"),
|
| 666 |
+
touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"),
|
| 667 |
+
agent_obs_images=rep.get("images"))
|
| 668 |
+
note = log.notes.get((sp["attempt"], sp["step"]))
|
| 669 |
+
if note:
|
| 670 |
+
c["agent_note"] = {k: v for k, v in note.items() if k != "command"}
|
| 671 |
+
commands.append(c)
|
| 672 |
+
t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x]
|
| 673 |
+
return dict(
|
| 674 |
+
schema=SCHEMA,
|
| 675 |
+
source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts],
|
| 676 |
+
episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain,
|
| 677 |
+
memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None),
|
| 678 |
+
feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"),
|
| 679 |
+
k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"),
|
| 680 |
+
contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256")
|
| 681 |
+
if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)),
|
| 682 |
+
agent=log.agent_info(),
|
| 683 |
+
task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"),
|
| 684 |
+
instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}),
|
| 685 |
+
run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all),
|
| 686 |
+
run_success=any(x["success"] for x in att_all) if att_all else None,
|
| 687 |
+
agent_final_report=log.final_report[:6000] or None,
|
| 688 |
+
mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)),
|
| 689 |
+
attempts=attempts,
|
| 690 |
+
commands=commands,
|
| 691 |
+
task_events=rp.events,
|
| 692 |
+
frames=dict(n=sink.n, fps=FPS, image_res=rp.res,
|
| 693 |
+
phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"],
|
| 694 |
+
joint_pos=rp.ep_initial["joint_pos"],
|
| 695 |
+
gripper_qpos=rp.ep_initial["gripper_qpos"])),
|
| 696 |
+
)
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
# ====================================================================================================== CLI
|
| 700 |
+
|
| 701 |
+
def load_manifest(run_dir):
|
| 702 |
+
p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json")
|
| 703 |
+
return json.load(open(p)) if os.path.exists(p) else {}
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
def main():
|
| 707 |
+
ap = argparse.ArgumentParser()
|
| 708 |
+
ap.add_argument("mode", choices=["check", "record"])
|
| 709 |
+
ap.add_argument("runs", nargs="+")
|
| 710 |
+
ap.add_argument("--json", default="")
|
| 711 |
+
ap.add_argument("--out", default="")
|
| 712 |
+
ap.add_argument("--res", type=int, default=256)
|
| 713 |
+
ap.add_argument("--force", action="store_true", help="record again even if replay.json exists")
|
| 714 |
+
a = ap.parse_args()
|
| 715 |
+
rows = []
|
| 716 |
+
for r in a.runs:
|
| 717 |
+
r = r.rstrip("/")
|
| 718 |
+
try:
|
| 719 |
+
if a.mode == "check":
|
| 720 |
+
s = RunReplay(r, manifest=load_manifest(r)).run().summary()
|
| 721 |
+
else:
|
| 722 |
+
batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r)
|
| 723 |
+
rd = os.path.join(a.out, batch, name)
|
| 724 |
+
if os.path.exists(os.path.join(rd, "replay.json")) and not a.force:
|
| 725 |
+
print(json.dumps(dict(run=name, skipped="exists")), flush=True)
|
| 726 |
+
continue
|
| 727 |
+
shutil.rmtree(rd, ignore_errors=True)
|
| 728 |
+
rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run()
|
| 729 |
+
s = rp.summary()
|
| 730 |
+
s["episodes"] = rp.episodes
|
| 731 |
+
with open(os.path.join(rd, "replay.json"), "w") as f:
|
| 732 |
+
json.dump(s, f, indent=1)
|
| 733 |
+
except Exception:
|
| 734 |
+
import traceback
|
| 735 |
+
s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:])
|
| 736 |
+
rows.append(s)
|
| 737 |
+
print(json.dumps(s), flush=True)
|
| 738 |
+
if a.json:
|
| 739 |
+
with open(a.json, "w") as f:
|
| 740 |
+
json.dump(rows, f, indent=1)
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
if __name__ == "__main__":
|
| 744 |
+
main()
|
leaf/code/compound-lh-20261102-clh_20261102_gpt/lerobot_export.py
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars.
|
| 2 |
+
|
| 3 |
+
Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding
|
| 4 |
+
can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan):
|
| 5 |
+
|
| 6 |
+
python scripts/lerobot_export.py plan --raw <raw_root>[,<raw_root2>] --runs-root <lffbench>/runs/api \
|
| 7 |
+
--paper <paper/latex> --task-set <lffbench>/sets/main_v2_1inst.txt --work <work_dir> [--batches ...] [--limit N]
|
| 8 |
+
python scripts/lerobot_export.py shard --work <work_dir> --shard i --nshards N
|
| 9 |
+
python scripts/lerobot_export.py merge --work <work_dir> --nshards N --out <dataset_root>
|
| 10 |
+
|
| 11 |
+
Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0
|
| 12 |
+
mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped.
|
| 13 |
+
|
| 14 |
+
LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t):
|
| 15 |
+
observation.images.image agentview RGB 256x256 (upright; LIBERO naming)
|
| 16 |
+
observation.images.wrist_image wrist (eye-in-hand) RGB 256x256
|
| 17 |
+
observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout)
|
| 18 |
+
observation.joint_pos / joint_vel 7 arm joints (rad, rad/s)
|
| 19 |
+
observation.eef_quat 4: xyzw; observation.gripper_width 1 (m)
|
| 20 |
+
action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad),
|
| 21 |
+
gripper (-1 open, +1 close)
|
| 22 |
+
annotation.attempt_index attempt (1-based) the frame belongs to
|
| 23 |
+
annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`)
|
| 24 |
+
annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action)
|
| 25 |
+
annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt
|
| 26 |
+
annotation.task_event number of task-monitor events (error / progress events) registered at this step
|
| 27 |
+
Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table),
|
| 28 |
+
runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state
|
| 29 |
+
per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/.
|
| 30 |
+
"""
|
| 31 |
+
import argparse
|
| 32 |
+
import glob
|
| 33 |
+
import json
|
| 34 |
+
import os
|
| 35 |
+
import re
|
| 36 |
+
import shutil
|
| 37 |
+
import time
|
| 38 |
+
|
| 39 |
+
import numpy as np
|
| 40 |
+
|
| 41 |
+
FPS = 20
|
| 42 |
+
RES = 256
|
| 43 |
+
BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke",
|
| 44 |
+
"cc_smoke", "cc_opus_smoke"]
|
| 45 |
+
BATCH_NOTES = {
|
| 46 |
+
"cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog",
|
| 47 |
+
"cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267",
|
| 48 |
+
"cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299",
|
| 49 |
+
"cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances",
|
| 50 |
+
"cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)",
|
| 51 |
+
"cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the "
|
| 52 |
+
"with-history continuation of failed runs is incomplete",
|
| 53 |
+
"cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early",
|
| 54 |
+
"cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt",
|
| 55 |
+
"cc_opus_smoke": "smoke test: single attempt",
|
| 56 |
+
}
|
| 57 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 58 |
+
CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)",
|
| 59 |
+
"L2": "disturbed state to restore (incl. damage the agent causes)",
|
| 60 |
+
"L3": "infeasible manipulation strategy (grasp / contact / tool must change)",
|
| 61 |
+
"L4": "misjudged geometry (size, shape, fit, hidden structure)",
|
| 62 |
+
"L5": "misjudged physics (mass distribution, friction, dynamics)"}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def features():
|
| 66 |
+
vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]}
|
| 67 |
+
f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names}
|
| 68 |
+
i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None}
|
| 69 |
+
return {
|
| 70 |
+
"observation.images.image": vid(),
|
| 71 |
+
"observation.images.wrist_image": vid(),
|
| 72 |
+
"observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z",
|
| 73 |
+
"finger_qpos_left", "finger_qpos_right"]),
|
| 74 |
+
"observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 75 |
+
"observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 76 |
+
"observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]),
|
| 77 |
+
"observation.gripper_width": f32(1, ["width_m"]),
|
| 78 |
+
"action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y",
|
| 79 |
+
"eef_delta_rot_aa_z", "gripper_close"]),
|
| 80 |
+
"annotation.attempt_index": i64(),
|
| 81 |
+
"annotation.command_index": i64(),
|
| 82 |
+
"annotation.phase": i64(),
|
| 83 |
+
"annotation.attempt_success": i64(),
|
| 84 |
+
"annotation.task_event": i64(),
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ------------------------------------------------------------------------------------------------ paper metadata
|
| 89 |
+
|
| 90 |
+
def _clean_tex(s):
|
| 91 |
+
s = re.sub(r"%.*", "", s)
|
| 92 |
+
for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"),
|
| 93 |
+
(r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"),
|
| 94 |
+
(r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"),
|
| 95 |
+
(r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"),
|
| 96 |
+
(r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]:
|
| 97 |
+
s = re.sub(a, b, s)
|
| 98 |
+
s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s)
|
| 99 |
+
s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s)
|
| 100 |
+
for _ in range(3):
|
| 101 |
+
s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s)
|
| 102 |
+
s = re.sub(r"\$([^$]*)\$", r"\1", s)
|
| 103 |
+
s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ")
|
| 104 |
+
s = re.sub(r"\{([^{}]*)\}", r"\1", s)
|
| 105 |
+
s = re.sub(r"\\[a-zA-Z]+\*?", "", s)
|
| 106 |
+
return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def paper_tasks(paper_dir):
|
| 110 |
+
"""{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the
|
| 111 |
+
paper's task table and task appendix (empty if the paper sources are not there)."""
|
| 112 |
+
out = {}
|
| 113 |
+
if not paper_dir:
|
| 114 |
+
return out
|
| 115 |
+
app = os.path.join(paper_dir, "sections", "appendix_tasks.tex")
|
| 116 |
+
tab = os.path.join(paper_dir, "sections", "tab_tasks.tex")
|
| 117 |
+
if os.path.exists(app):
|
| 118 |
+
txt = open(app).read()
|
| 119 |
+
parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt)
|
| 120 |
+
for i in range(1, len(parts) - 1, 2):
|
| 121 |
+
if parts[i] != "\\paragraph{":
|
| 122 |
+
continue
|
| 123 |
+
body = parts[i + 1]
|
| 124 |
+
m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S)
|
| 125 |
+
if not m:
|
| 126 |
+
continue
|
| 127 |
+
name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip()
|
| 128 |
+
desc = _clean_tex(body[m.end():])
|
| 129 |
+
out[code] = dict(name=name, cause=_clean_tex(cause), description=desc)
|
| 130 |
+
if os.path.exists(tab):
|
| 131 |
+
names = {v["name"].lower(): k for k, v in out.items()}
|
| 132 |
+
for line in open(tab):
|
| 133 |
+
cells = [c.strip() for c in line.split("&")]
|
| 134 |
+
if len(cells) != 6 or not cells[-1].endswith("\\\\"):
|
| 135 |
+
continue
|
| 136 |
+
nm = re.sub(r"\\contscene", "", cells[0]).strip().lower()
|
| 137 |
+
code = names.get(nm)
|
| 138 |
+
if not code:
|
| 139 |
+
continue
|
| 140 |
+
out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]),
|
| 141 |
+
repair_within_attempt=_clean_tex(cells[3]) == "yes",
|
| 142 |
+
oracle_first_attempt_pct=_clean_tex(cells[4]),
|
| 143 |
+
naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip()))
|
| 144 |
+
return out
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
# ------------------------------------------------------------------------------------------------ collection
|
| 148 |
+
|
| 149 |
+
def manifest_status(runs_root, batch, run, cache={}):
|
| 150 |
+
if batch not in cache:
|
| 151 |
+
p = os.path.join(runs_root, batch, "manifest.json")
|
| 152 |
+
cache[batch] = json.load(open(p)) if os.path.exists(p) else {}
|
| 153 |
+
m = cache[batch]
|
| 154 |
+
for r in m.get("runs", []):
|
| 155 |
+
if r.get("run") == run:
|
| 156 |
+
return r.get("status", "?"), r
|
| 157 |
+
for r in m.get("superseded", []):
|
| 158 |
+
if r.get("run") == run:
|
| 159 |
+
return "superseded_" + str(r.get("status", "?")), r
|
| 160 |
+
return "not_in_manifest", {}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def collect(raw_roots, runs_root, batches, task_order):
|
| 164 |
+
"""Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root."""
|
| 165 |
+
eps, rejected, seen = [], [], set()
|
| 166 |
+
for root in raw_roots:
|
| 167 |
+
for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))):
|
| 168 |
+
rep = json.load(open(rj))
|
| 169 |
+
batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"]
|
| 170 |
+
if (batches and batch not in batches) or (batch, run) in seen:
|
| 171 |
+
continue
|
| 172 |
+
seen.add((batch, run))
|
| 173 |
+
ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff")
|
| 174 |
+
status, entry = manifest_status(runs_root, batch, run)
|
| 175 |
+
if not ok:
|
| 176 |
+
never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked")
|
| 177 |
+
rejected.append(dict(run=run, batch=batch, run_status=status,
|
| 178 |
+
reason="run never started (no contract, no robot command)" if never else
|
| 179 |
+
"replay does not reproduce the log (the log has gaps or the replay diverged)",
|
| 180 |
+
detail=rep.get("first_mismatches")))
|
| 181 |
+
continue
|
| 182 |
+
for ep in rep.get("episodes", []):
|
| 183 |
+
d = os.path.join(root, ep["dir"])
|
| 184 |
+
ann = json.load(open(os.path.join(d, "annotation.json")))
|
| 185 |
+
judged = [a for a in ann["attempts"] if a.get("success") is not None]
|
| 186 |
+
if not judged or ep["n_frames"] == 0:
|
| 187 |
+
rejected.append(dict(run=run, batch=batch, episode=ep["dir"],
|
| 188 |
+
reason="no judged attempt" if not judged else "no frames"))
|
| 189 |
+
continue
|
| 190 |
+
ann["source"]["run_status"] = status
|
| 191 |
+
ann["source"]["manifest_id"] = entry.get("id")
|
| 192 |
+
ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"],
|
| 193 |
+
max_eef_dev_m=rep["max_eef_dev_m"])
|
| 194 |
+
key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99),
|
| 195 |
+
{"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2),
|
| 196 |
+
ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"])
|
| 197 |
+
eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann))
|
| 198 |
+
eps.sort(key=lambda x: x["key"])
|
| 199 |
+
return eps, rejected
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# ------------------------------------------------------------------------------------------------ writing
|
| 203 |
+
|
| 204 |
+
def frames_of(path):
|
| 205 |
+
import av
|
| 206 |
+
with av.open(path) as c:
|
| 207 |
+
for fr in c.decode(video=0):
|
| 208 |
+
yield fr.to_ndarray(format="rgb24")
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def flat_row(i, ann, n, idx0):
|
| 212 |
+
s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"]
|
| 213 |
+
att = ann["attempts"]
|
| 214 |
+
a0 = att[0]
|
| 215 |
+
return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n,
|
| 216 |
+
batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"],
|
| 217 |
+
memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"),
|
| 218 |
+
episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att],
|
| 219 |
+
harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"),
|
| 220 |
+
effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"),
|
| 221 |
+
task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"),
|
| 222 |
+
category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"],
|
| 223 |
+
success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att],
|
| 224 |
+
feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att],
|
| 225 |
+
auto_ended=[a.get("auto_ended") for a in att],
|
| 226 |
+
corrected_later_in_run=[a.get("corrected_later_in_run") for a in att],
|
| 227 |
+
error_event_in_attempt=[a.get("error_event_in_attempt") for a in att],
|
| 228 |
+
run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"),
|
| 229 |
+
n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]),
|
| 230 |
+
first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def cmd_plan(a):
|
| 234 |
+
task_order = {}
|
| 235 |
+
if a.task_set and os.path.exists(a.task_set):
|
| 236 |
+
for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")):
|
| 237 |
+
task_order[line.split(":")[0].strip()] = i
|
| 238 |
+
batches = [b for b in a.batches.split(",") if b] if a.batches else None
|
| 239 |
+
eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order)
|
| 240 |
+
if a.limit:
|
| 241 |
+
eps = eps[:a.limit]
|
| 242 |
+
paper = paper_tasks(a.paper)
|
| 243 |
+
idx0 = 0
|
| 244 |
+
for i, e in enumerate(eps):
|
| 245 |
+
ann = e["ann"]
|
| 246 |
+
tname = ann["task"]["name"]
|
| 247 |
+
if tname in paper:
|
| 248 |
+
ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"}
|
| 249 |
+
ann["episode_index"] = i
|
| 250 |
+
ann["dataset_index_range"] = [idx0, idx0 + e["n"]]
|
| 251 |
+
e["index"], e["from"] = i, idx0
|
| 252 |
+
idx0 += e["n"]
|
| 253 |
+
del e["key"]
|
| 254 |
+
os.makedirs(a.work, exist_ok=True)
|
| 255 |
+
with open(os.path.join(a.work, "plan.json"), "w") as f:
|
| 256 |
+
json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f,
|
| 257 |
+
ensure_ascii=False)
|
| 258 |
+
print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def shard_range(n_eps, i, k):
|
| 262 |
+
return (n_eps * i) // k, (n_eps * (i + 1)) // k
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def cmd_shard(a):
|
| 266 |
+
from lerobot.datasets.lerobot_dataset import LeRobotDataset
|
| 267 |
+
t0 = time.time()
|
| 268 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 269 |
+
eps = plan["episodes"]
|
| 270 |
+
lo, hi = shard_range(len(eps), a.shard, a.nshards)
|
| 271 |
+
out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}")
|
| 272 |
+
if os.path.exists(os.path.join(out, "DONE")):
|
| 273 |
+
print(f"shard {a.shard}: done already", flush=True)
|
| 274 |
+
return
|
| 275 |
+
shutil.rmtree(out, ignore_errors=True)
|
| 276 |
+
ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out,
|
| 277 |
+
robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads,
|
| 278 |
+
vcodec=a.vcodec)
|
| 279 |
+
nfr = 0
|
| 280 |
+
for e in eps[lo:hi]:
|
| 281 |
+
d, ann, n = e["dir"], e["ann"], e["n"]
|
| 282 |
+
fr = np.load(os.path.join(d, "frames.npz"))
|
| 283 |
+
assert len(fr["action"]) == n, d
|
| 284 |
+
succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]}
|
| 285 |
+
evc = np.zeros(n, np.int64)
|
| 286 |
+
for ev in ann["task_events"]:
|
| 287 |
+
if 0 <= ev["frame"] < n:
|
| 288 |
+
evc[ev["frame"]] += 1
|
| 289 |
+
state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32)
|
| 290 |
+
instr = ann["task"]["instruction"]
|
| 291 |
+
k = 0
|
| 292 |
+
for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))):
|
| 293 |
+
if k >= n:
|
| 294 |
+
break
|
| 295 |
+
ds.add_frame({
|
| 296 |
+
"observation.images.image": img, "observation.images.wrist_image": wr,
|
| 297 |
+
"observation.state": state[k],
|
| 298 |
+
"observation.joint_pos": fr["joint_pos"][k].astype(np.float32),
|
| 299 |
+
"observation.joint_vel": fr["joint_vel"][k].astype(np.float32),
|
| 300 |
+
"observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32),
|
| 301 |
+
"observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32),
|
| 302 |
+
"action": fr["action"][k].astype(np.float32),
|
| 303 |
+
"annotation.attempt_index": np.array([fr["attempt"][k]], np.int64),
|
| 304 |
+
"annotation.command_index": np.array([fr["command"][k]], np.int64),
|
| 305 |
+
"annotation.phase": np.array([fr["phase"][k]], np.int64),
|
| 306 |
+
"annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64),
|
| 307 |
+
"annotation.task_event": np.array([evc[k]], np.int64),
|
| 308 |
+
"task": instr,
|
| 309 |
+
})
|
| 310 |
+
k += 1
|
| 311 |
+
if k != n:
|
| 312 |
+
raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames")
|
| 313 |
+
ds.save_episode()
|
| 314 |
+
nfr += n
|
| 315 |
+
ds.finalize()
|
| 316 |
+
shutil.rmtree(os.path.join(out, "images"), ignore_errors=True)
|
| 317 |
+
open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n")
|
| 318 |
+
print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def cmd_merge(a):
|
| 322 |
+
from pathlib import Path
|
| 323 |
+
from lerobot.datasets.aggregate import aggregate_datasets
|
| 324 |
+
t0 = time.time()
|
| 325 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 326 |
+
eps = plan["episodes"]
|
| 327 |
+
roots, ids = [], []
|
| 328 |
+
for i in range(a.nshards):
|
| 329 |
+
lo, hi = shard_range(len(eps), i, a.nshards)
|
| 330 |
+
if hi <= lo:
|
| 331 |
+
continue
|
| 332 |
+
r = os.path.join(a.work, "shards", f"shard_{i:03d}")
|
| 333 |
+
if not os.path.exists(os.path.join(r, "DONE")):
|
| 334 |
+
raise SystemExit(f"shard {i} is not done")
|
| 335 |
+
roots.append(Path(r))
|
| 336 |
+
ids.append(f"{plan['repo_id']}-shard{i:03d}")
|
| 337 |
+
if os.path.exists(a.out):
|
| 338 |
+
raise SystemExit(f"{a.out} exists; refusing to overwrite")
|
| 339 |
+
aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out))
|
| 340 |
+
print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True)
|
| 341 |
+
write_sidecars(a, plan)
|
| 342 |
+
print(f"merge done in {time.time() - t0:.0f}s", flush=True)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def write_sidecars(a, plan):
|
| 346 |
+
eps, paper = plan["episodes"], plan["paper"]
|
| 347 |
+
lff = os.path.join(a.out, "lff")
|
| 348 |
+
for sub in ("annotations", "sim_state", "final", "code"):
|
| 349 |
+
os.makedirs(os.path.join(lff, sub), exist_ok=True)
|
| 350 |
+
rows, runs, tasks = [], {}, {}
|
| 351 |
+
for e in eps:
|
| 352 |
+
i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"]
|
| 353 |
+
name = f"episode_{i:06d}"
|
| 354 |
+
if os.path.exists(os.path.join(d, "sim_state.npy")):
|
| 355 |
+
shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy"))
|
| 356 |
+
shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz"))
|
| 357 |
+
for cam, key in (("agentview", "image"), ("wrist", "wrist_image")):
|
| 358 |
+
shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png"))
|
| 359 |
+
with open(os.path.join(lff, "annotations", name + ".json"), "w") as f:
|
| 360 |
+
json.dump(ann, f, indent=1, ensure_ascii=False)
|
| 361 |
+
rows.append(flat_row(i, ann, n, e["from"]))
|
| 362 |
+
tname = ann["task"]["name"]
|
| 363 |
+
rk = (ann["source"]["batch"], ann["source"]["run"])
|
| 364 |
+
r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"),
|
| 365 |
+
run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"],
|
| 366 |
+
memory_free_chain_of=ann["source"].get("memory_free_chain_of"),
|
| 367 |
+
memory_free_rep=ann["source"].get("memory_free_rep"), task=tname,
|
| 368 |
+
seed=ann["task"]["seed"], model=ann["agent"].get("model"),
|
| 369 |
+
harness=ann["agent"].get("harness"),
|
| 370 |
+
harness_version=ann["agent"].get("harness_version"),
|
| 371 |
+
codex_catalog=ann["agent"].get("codex_catalog"),
|
| 372 |
+
outcome_class=ann["run_outcome"].get("outcome_class"),
|
| 373 |
+
attempt_history=ann["run_outcome"].get("attempt_history"),
|
| 374 |
+
agent_final_report=ann["run_outcome"].get("agent_final_report"),
|
| 375 |
+
episodes=[]))
|
| 376 |
+
for x in ann["attempts"]:
|
| 377 |
+
r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success")))
|
| 378 |
+
if tname not in tasks:
|
| 379 |
+
tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")}
|
| 380 |
+
if tname in paper:
|
| 381 |
+
tasks[tname]["paper"] = paper[tname]
|
| 382 |
+
tasks[tname]["instances"] = {}
|
| 383 |
+
tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"]
|
| 384 |
+
# memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id)
|
| 385 |
+
by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")}
|
| 386 |
+
for r in runs.values():
|
| 387 |
+
if r.get("memory_free_chain_of"):
|
| 388 |
+
r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"]))
|
| 389 |
+
for (b, rn), r in runs.items():
|
| 390 |
+
r["memory_free_retries"] = sorted((x["run"] for x in runs.values()
|
| 391 |
+
if x["batch"] == b and x.get("memory_free_chain_of_run") == rn),
|
| 392 |
+
key=lambda q: runs[(b, q)].get("memory_free_rep") or 0)
|
| 393 |
+
with open(os.path.join(lff, "episodes.jsonl"), "w") as f:
|
| 394 |
+
for row in rows:
|
| 395 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 396 |
+
with open(os.path.join(lff, "runs.jsonl"), "w") as f:
|
| 397 |
+
for r in runs.values():
|
| 398 |
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 399 |
+
with open(os.path.join(lff, "tasks.json"), "w") as f:
|
| 400 |
+
json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False)
|
| 401 |
+
with open(os.path.join(lff, "batches.json"), "w") as f:
|
| 402 |
+
json.dump(BATCH_NOTES, f, indent=1)
|
| 403 |
+
with open(os.path.join(lff, "rejected.json"), "w") as f:
|
| 404 |
+
json.dump(plan["rejected"], f, indent=1)
|
| 405 |
+
here = os.path.dirname(os.path.abspath(__file__))
|
| 406 |
+
for s in ("lerobot_replay.py", "lerobot_export.py"):
|
| 407 |
+
shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s))
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def main():
|
| 411 |
+
ap = argparse.ArgumentParser()
|
| 412 |
+
ap.add_argument("step", choices=["plan", "shard", "merge"])
|
| 413 |
+
ap.add_argument("--work", required=True)
|
| 414 |
+
ap.add_argument("--raw", default="")
|
| 415 |
+
ap.add_argument("--runs-root", default="")
|
| 416 |
+
ap.add_argument("--out", default="")
|
| 417 |
+
ap.add_argument("--paper", default="")
|
| 418 |
+
ap.add_argument("--task-set", default="")
|
| 419 |
+
ap.add_argument("--repo-id", default="lffbench/agent-replays")
|
| 420 |
+
ap.add_argument("--batches", default="")
|
| 421 |
+
ap.add_argument("--limit", type=int, default=0)
|
| 422 |
+
ap.add_argument("--shard", type=int, default=0)
|
| 423 |
+
ap.add_argument("--nshards", type=int, default=1)
|
| 424 |
+
ap.add_argument("--threads", type=int, default=2)
|
| 425 |
+
ap.add_argument("--vcodec", default="libsvtav1")
|
| 426 |
+
a = ap.parse_args()
|
| 427 |
+
{"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
if __name__ == "__main__":
|
| 431 |
+
main()
|
leaf/code/compound-lh-20261102-clh_20261102_gpt/lerobot_replay.py
ADDED
|
@@ -0,0 +1,744 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay
|
| 2 |
+
against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the
|
| 3 |
+
LeRobot export (scripts/lerobot_export.py).
|
| 4 |
+
|
| 5 |
+
python scripts/lerobot_replay.py check <run_dir> [<run_dir> ...] [--json out.json] # replay only, print fidelity
|
| 6 |
+
python scripts/lerobot_replay.py record <run_dir> --out <raw_root> [--res 256]
|
| 7 |
+
|
| 8 |
+
Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot
|
| 9 |
+
commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite
|
| 10 |
+
is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly
|
| 11 |
+
like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same
|
| 12 |
+
outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width,
|
| 13 |
+
ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code
|
| 14 |
+
hashes equal the current files are expected to match (check_code()).
|
| 15 |
+
|
| 16 |
+
Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB,
|
| 17 |
+
proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes:
|
| 18 |
+
protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode
|
| 19 |
+
per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the
|
| 20 |
+
fidelity check runs in record mode too. Per episode the recorder writes <raw_root>/<batch>/<run>/epNN/:
|
| 21 |
+
agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes)
|
| 22 |
+
frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase
|
| 23 |
+
sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel)
|
| 24 |
+
final_*.png, final.npz observation after the last control step (the state the outcome was judged in)
|
| 25 |
+
annotation.json episode annotation (build_annotation)
|
| 26 |
+
and <raw_root>/<batch>/<run>/replay.json (fidelity) when the whole run is done.
|
| 27 |
+
"""
|
| 28 |
+
import argparse
|
| 29 |
+
import ast
|
| 30 |
+
import hashlib
|
| 31 |
+
import importlib
|
| 32 |
+
import json
|
| 33 |
+
import math
|
| 34 |
+
import os
|
| 35 |
+
import pkgutil
|
| 36 |
+
import re
|
| 37 |
+
import shutil
|
| 38 |
+
import sys
|
| 39 |
+
import time
|
| 40 |
+
from collections import defaultdict
|
| 41 |
+
|
| 42 |
+
import numpy as np
|
| 43 |
+
|
| 44 |
+
LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 45 |
+
sys.path.insert(0, LFF_ROOT)
|
| 46 |
+
|
| 47 |
+
from lffbench import envs # noqa: E402
|
| 48 |
+
from lffbench import tasks as task_pkg # noqa: E402
|
| 49 |
+
from lffbench.agent import camera as C # noqa: E402
|
| 50 |
+
from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402
|
| 51 |
+
from lffbench.task_base import TASKS # noqa: E402
|
| 52 |
+
|
| 53 |
+
for _m in pkgutil.iter_modules(task_pkg.__path__):
|
| 54 |
+
importlib.import_module(f"lffbench.tasks.{_m.name}")
|
| 55 |
+
|
| 56 |
+
# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the
|
| 57 |
+
# task's outcome() check after `finish` (the arm holds still; not an agent action)
|
| 58 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 59 |
+
FPS = 20
|
| 60 |
+
SCHEMA = "lff-replay-1"
|
| 61 |
+
|
| 62 |
+
# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR"
|
| 63 |
+
ERROR_FLAGS = ("trap_fired", "recovered_in_attempt")
|
| 64 |
+
ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events",
|
| 65 |
+
"n_missed_strikes", "n_open_gripper_pushes")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def load_jsonl(p):
|
| 69 |
+
out = []
|
| 70 |
+
if not os.path.exists(p):
|
| 71 |
+
return out
|
| 72 |
+
with open(p) as f:
|
| 73 |
+
for line in f:
|
| 74 |
+
line = line.strip()
|
| 75 |
+
if line:
|
| 76 |
+
try:
|
| 77 |
+
out.append(json.loads(line))
|
| 78 |
+
except ValueError:
|
| 79 |
+
pass
|
| 80 |
+
return out
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def norm_json(o):
|
| 84 |
+
return json.loads(json.dumps(o, default=_json_default))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def sha256(p):
|
| 88 |
+
with open(p, "rb") as f:
|
| 89 |
+
return hashlib.sha256(f.read()).hexdigest()
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def check_code(run_dir):
|
| 93 |
+
"""[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract."""
|
| 94 |
+
p = os.path.join(run_dir, "contract.json")
|
| 95 |
+
if not os.path.exists(p):
|
| 96 |
+
return [("contract.json", None, None)]
|
| 97 |
+
files = json.load(open(p))["contract"].get("server_code_files", {})
|
| 98 |
+
bad = []
|
| 99 |
+
for f, h in files.items():
|
| 100 |
+
q = os.path.join(LFF_ROOT, f)
|
| 101 |
+
cur = sha256(q) if os.path.exists(q) else None
|
| 102 |
+
if cur != h:
|
| 103 |
+
bad.append((f, h, cur))
|
| 104 |
+
return bad
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def diff_json(a, b, path="", tol=0.0, out=None, limit=20):
|
| 108 |
+
"""Differences between two JSON values (numbers compared with an absolute tolerance)."""
|
| 109 |
+
out = [] if out is None else out
|
| 110 |
+
if len(out) >= limit:
|
| 111 |
+
return out
|
| 112 |
+
if isinstance(a, dict) and isinstance(b, dict):
|
| 113 |
+
for k in sorted(set(a) | set(b)):
|
| 114 |
+
if k not in a or k not in b:
|
| 115 |
+
out.append((f"{path}.{k}", a.get(k, "<missing>"), b.get(k, "<missing>")))
|
| 116 |
+
else:
|
| 117 |
+
diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit)
|
| 118 |
+
elif isinstance(a, list) and isinstance(b, list):
|
| 119 |
+
if len(a) != len(b):
|
| 120 |
+
out.append((path, f"len {len(a)}", f"len {len(b)}"))
|
| 121 |
+
else:
|
| 122 |
+
for i, (x, y) in enumerate(zip(a, b)):
|
| 123 |
+
diff_json(x, y, f"{path}[{i}]", tol, out, limit)
|
| 124 |
+
elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
|
| 125 |
+
if a != b:
|
| 126 |
+
out.append((path, a, b))
|
| 127 |
+
elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))):
|
| 128 |
+
out.append((path, a, b))
|
| 129 |
+
return out
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def error_event(o):
|
| 133 |
+
"""True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none."""
|
| 134 |
+
if not isinstance(o, dict):
|
| 135 |
+
return None
|
| 136 |
+
keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o]
|
| 137 |
+
if not keys:
|
| 138 |
+
return None
|
| 139 |
+
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)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# ====================================================================================================== logs -> notes
|
| 143 |
+
|
| 144 |
+
class RunLog:
|
| 145 |
+
"""Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's
|
| 146 |
+
narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition."""
|
| 147 |
+
|
| 148 |
+
def __init__(self, run_dir, manifest=None):
|
| 149 |
+
self.run_dir = os.path.abspath(run_dir.rstrip("/"))
|
| 150 |
+
self.run = os.path.basename(self.run_dir)
|
| 151 |
+
self.batch = os.path.basename(os.path.dirname(self.run_dir))
|
| 152 |
+
self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl"))
|
| 153 |
+
self.start = next(e for e in self.ev if e["ev"] == "session_start")
|
| 154 |
+
self.calls, self.dones, self.harness_status = {}, [], []
|
| 155 |
+
last = None
|
| 156 |
+
for e in self.ev:
|
| 157 |
+
if e["ev"] == "call":
|
| 158 |
+
self.calls[(int(e["attempt"]), int(e["step"]))] = e
|
| 159 |
+
last = e
|
| 160 |
+
elif e["ev"] == "done":
|
| 161 |
+
self.dones.append(e)
|
| 162 |
+
last = e
|
| 163 |
+
elif e["ev"] == "http" and last is not None and "think_s" not in last:
|
| 164 |
+
ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \
|
| 165 |
+
(last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe"))
|
| 166 |
+
if ok:
|
| 167 |
+
last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s")
|
| 168 |
+
self.manifest = manifest or {}
|
| 169 |
+
self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {}
|
| 170 |
+
p = os.path.join(self.run_dir, "harness.json")
|
| 171 |
+
self.harness = json.load(open(p)) if os.path.exists(p) else {}
|
| 172 |
+
self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl"))
|
| 173 |
+
self._narration()
|
| 174 |
+
|
| 175 |
+
# ---------------------------------------------------------------- agent narration
|
| 176 |
+
def _narration(self):
|
| 177 |
+
"""notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one;
|
| 178 |
+
finish_notes[attempt] likewise for the agent's finish call; final_report = its last message."""
|
| 179 |
+
self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", []
|
| 180 |
+
buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
|
| 181 |
+
attempt = 1
|
| 182 |
+
|
| 183 |
+
def take():
|
| 184 |
+
nonlocal buf
|
| 185 |
+
out = {k: v for k, v in buf.items() if v}
|
| 186 |
+
buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
|
| 187 |
+
return out
|
| 188 |
+
|
| 189 |
+
last_msg = ""
|
| 190 |
+
for t in self.traj:
|
| 191 |
+
if t.get("kind") == "header":
|
| 192 |
+
self.headers.append(t.get("agent") or {})
|
| 193 |
+
continue
|
| 194 |
+
if t.get("kind") != "step":
|
| 195 |
+
continue
|
| 196 |
+
if (t.get("message") or "").strip():
|
| 197 |
+
buf["messages"].append(t["message"].strip())
|
| 198 |
+
last_msg = t["message"].strip()
|
| 199 |
+
if (t.get("reasoning_content") or "").strip():
|
| 200 |
+
buf["reasoning"].append(t["reasoning_content"].strip())
|
| 201 |
+
res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])}
|
| 202 |
+
for c in t.get("tool_calls") or []:
|
| 203 |
+
fn, args = c.get("function_name"), c.get("arguments") or {}
|
| 204 |
+
if fn == "shell":
|
| 205 |
+
buf["shell"].append(str(args.get("command", ""))[:2000])
|
| 206 |
+
elif fn == "view_images":
|
| 207 |
+
buf["viewed"].extend(args.get("paths") or [])
|
| 208 |
+
elif fn == "robot":
|
| 209 |
+
cmd = str(args.get("command", "")).strip()
|
| 210 |
+
r = res.get(c.get("tool_call_id")) or {}
|
| 211 |
+
try:
|
| 212 |
+
rep = json.loads(r.get("content") or "{}")
|
| 213 |
+
except ValueError:
|
| 214 |
+
rep = {}
|
| 215 |
+
word = cmd.split()[0] if cmd else ""
|
| 216 |
+
m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", "")))
|
| 217 |
+
if word in ("move_eef", "observe") and m:
|
| 218 |
+
a, s = int(m.group(1)), int(m.group(2))
|
| 219 |
+
n = take()
|
| 220 |
+
n["command"] = cmd
|
| 221 |
+
self.notes[(a, s)] = n
|
| 222 |
+
attempt = a
|
| 223 |
+
elif word in ("finish", "done"):
|
| 224 |
+
n = take()
|
| 225 |
+
n["command"] = cmd
|
| 226 |
+
n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)}
|
| 227 |
+
self.finish_notes.setdefault(attempt, n)
|
| 228 |
+
if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"):
|
| 229 |
+
attempt += 1
|
| 230 |
+
# status / help / errors: their narration stays in the buffer for the next command
|
| 231 |
+
self.final_report = last_msg
|
| 232 |
+
|
| 233 |
+
# ---------------------------------------------------------------- run-level labels
|
| 234 |
+
def attempts(self):
|
| 235 |
+
out = []
|
| 236 |
+
for e in self.dones:
|
| 237 |
+
o = e.get("outcome") or {}
|
| 238 |
+
if isinstance(o, str):
|
| 239 |
+
try:
|
| 240 |
+
o = ast.literal_eval(o)
|
| 241 |
+
except (ValueError, SyntaxError):
|
| 242 |
+
o = {}
|
| 243 |
+
out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o,
|
| 244 |
+
reason=e.get("reason") or ""))
|
| 245 |
+
return sorted(out, key=lambda x: x["attempt"])
|
| 246 |
+
|
| 247 |
+
def condition(self):
|
| 248 |
+
s, en = self.start, self.entry
|
| 249 |
+
mem = s.get("memory", en.get("mem"))
|
| 250 |
+
chain = en.get("chain")
|
| 251 |
+
if mem == "full":
|
| 252 |
+
cond = "with_history"
|
| 253 |
+
elif chain:
|
| 254 |
+
cond = "memory_free_retry"
|
| 255 |
+
else:
|
| 256 |
+
cond = "independent_single_attempt"
|
| 257 |
+
return cond, chain
|
| 258 |
+
|
| 259 |
+
def outcome_class(self):
|
| 260 |
+
"""CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None."""
|
| 261 |
+
att = self.attempts()
|
| 262 |
+
if not att or self.start.get("memory") != "full":
|
| 263 |
+
return None, "".join("S" if a["success"] else "F" for a in att)
|
| 264 |
+
hist = "".join("S" if a["success"] else "F" for a in att)
|
| 265 |
+
if att[0]["success"]:
|
| 266 |
+
ev = error_event(att[0]["outcome"])
|
| 267 |
+
cls = "S?" if ev is None else ("IR" if ev else "CS")
|
| 268 |
+
else:
|
| 269 |
+
cls = "XR" if any(a["success"] for a in att) else "F"
|
| 270 |
+
return cls, hist
|
| 271 |
+
|
| 272 |
+
def agent_info(self):
|
| 273 |
+
h, en = self.harness, self.entry
|
| 274 |
+
hdr = self.headers[0] if self.headers else {}
|
| 275 |
+
return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"),
|
| 276 |
+
harness_version=h.get("version") or hdr.get("version"),
|
| 277 |
+
harness_binary_sha256=(h.get("binary") or {}).get("sha256"),
|
| 278 |
+
model=h.get("model") or en.get("model") or hdr.get("model_name"),
|
| 279 |
+
effort=h.get("effort") or en.get("effort") or hdr.get("effort"),
|
| 280 |
+
provider=h.get("provider") or en.get("provider"),
|
| 281 |
+
codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"),
|
| 282 |
+
jail=en.get("jail"))
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
# ====================================================================================================== recording
|
| 286 |
+
|
| 287 |
+
class EpisodeSink:
|
| 288 |
+
"""Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed."""
|
| 289 |
+
|
| 290 |
+
def __init__(self, path):
|
| 291 |
+
self.path = path
|
| 292 |
+
os.makedirs(path, exist_ok=True)
|
| 293 |
+
self.w = None
|
| 294 |
+
self.num = defaultdict(list)
|
| 295 |
+
self.n = 0
|
| 296 |
+
|
| 297 |
+
def add(self, st, imgs):
|
| 298 |
+
import imageio
|
| 299 |
+
if self.w is None:
|
| 300 |
+
self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb",
|
| 301 |
+
pixelformat="rgb24", macro_block_size=1,
|
| 302 |
+
ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error")
|
| 303 |
+
for k in ("agentview", "wrist")]
|
| 304 |
+
for w, im in zip(self.w, imgs):
|
| 305 |
+
w.append_data(im)
|
| 306 |
+
for k, v in st.items():
|
| 307 |
+
self.num[k].append(v)
|
| 308 |
+
self.n += 1
|
| 309 |
+
|
| 310 |
+
def close(self, final_state, final_imgs):
|
| 311 |
+
from PIL import Image
|
| 312 |
+
if self.w is not None:
|
| 313 |
+
for w in self.w:
|
| 314 |
+
w.close()
|
| 315 |
+
arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"}
|
| 316 |
+
np.savez(os.path.join(self.path, "frames.npz"), **arr)
|
| 317 |
+
if self.num.get("sim_state"):
|
| 318 |
+
np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64))
|
| 319 |
+
np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()})
|
| 320 |
+
for k, im in zip(("agentview", "wrist"), final_imgs):
|
| 321 |
+
Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png"))
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
class Recorder:
|
| 325 |
+
"""Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink."""
|
| 326 |
+
|
| 327 |
+
def __init__(self, rp, res):
|
| 328 |
+
self.rp, self.res = rp, int(res)
|
| 329 |
+
self.active = False
|
| 330 |
+
self.sink = None
|
| 331 |
+
self.cur = dict(attempt=1, command=-1, phase=PHASES["move"])
|
| 332 |
+
env = rp.task.env
|
| 333 |
+
self.env, self.rob = env, env.robots[0]
|
| 334 |
+
self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist"))
|
| 335 |
+
orig = env.step
|
| 336 |
+
|
| 337 |
+
def step(a):
|
| 338 |
+
if self.active and self.sink is not None:
|
| 339 |
+
self.capture(np.asarray(a, np.float64))
|
| 340 |
+
out = orig(a)
|
| 341 |
+
if self.active and self.sink is not None:
|
| 342 |
+
self.rp.poll_events(self.sink.n - 1)
|
| 343 |
+
return out
|
| 344 |
+
|
| 345 |
+
env.step = step
|
| 346 |
+
|
| 347 |
+
@property
|
| 348 |
+
def n(self):
|
| 349 |
+
return self.sink.n if self.sink is not None else 0
|
| 350 |
+
|
| 351 |
+
def state(self):
|
| 352 |
+
import robosuite.utils.transform_utils as T
|
| 353 |
+
env, rob = self.env, self.rob
|
| 354 |
+
d = env.sim.data
|
| 355 |
+
eef = np.array(d.site_xpos[rob.eef_site_id], np.float64)
|
| 356 |
+
q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw")
|
| 357 |
+
gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64)
|
| 358 |
+
try:
|
| 359 |
+
flat = np.asarray(env.sim.get_state().flatten(), np.float64)
|
| 360 |
+
except Exception:
|
| 361 |
+
flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64)
|
| 362 |
+
sk = self.rp.task.sk
|
| 363 |
+
return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64),
|
| 364 |
+
gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64),
|
| 365 |
+
joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64),
|
| 366 |
+
gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64),
|
| 367 |
+
eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)),
|
| 368 |
+
sim_time=np.float64(d.time), sim_state=flat)
|
| 369 |
+
|
| 370 |
+
def images(self):
|
| 371 |
+
return [envs.render(self.env, c, self.res) for c in self.cams]
|
| 372 |
+
|
| 373 |
+
def capture(self, a):
|
| 374 |
+
st = self.state()
|
| 375 |
+
st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]),
|
| 376 |
+
phase=np.int64(self.cur["phase"]))
|
| 377 |
+
self.sink.add(st, self.images())
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
class RunReplay:
|
| 381 |
+
def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None):
|
| 382 |
+
self.run_dir = os.path.abspath(run_dir.rstrip("/"))
|
| 383 |
+
self.run_name = os.path.basename(self.run_dir)
|
| 384 |
+
self.log = RunLog(self.run_dir, manifest)
|
| 385 |
+
self.ev = self.log.ev
|
| 386 |
+
self.start = self.log.start
|
| 387 |
+
cp = os.path.join(self.run_dir, "contract.json")
|
| 388 |
+
self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {}
|
| 389 |
+
spec = self.contract.get("image_spec") or {}
|
| 390 |
+
self.image_res = int(spec.get("width", 512))
|
| 391 |
+
self.code_diff = check_code(self.run_dir)
|
| 392 |
+
s = self.start
|
| 393 |
+
self.task = TASKS[s["task"]](cam_res=self.image_res)
|
| 394 |
+
inst = self.task.sample_instance(s["seed"])
|
| 395 |
+
logged = s.get("inst") or {}
|
| 396 |
+
sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")})
|
| 397 |
+
self.inst_diff = diff_json(sampled, logged, "inst")
|
| 398 |
+
if s.get("arm", "none") not in (None, "none") or logged.get("nominal"):
|
| 399 |
+
inst.update(logged) # controlled arms / nominal: the server overrode these instance fields
|
| 400 |
+
self.inst_diff = []
|
| 401 |
+
self.inst = inst
|
| 402 |
+
self.protocol = getattr(self.task, "protocol", "cross")
|
| 403 |
+
self.k = int(s.get("k") or self.task.max_attempts)
|
| 404 |
+
self.attempt = 1
|
| 405 |
+
self.mismatch = [] # (where, what, logged, replayed)
|
| 406 |
+
self.n_checked = 0
|
| 407 |
+
self.max_dev_m = 0.0
|
| 408 |
+
self.unfinished = None
|
| 409 |
+
self.rec = Recorder(self, res) if record else None
|
| 410 |
+
self.res = int(res)
|
| 411 |
+
self.out_root = out_root
|
| 412 |
+
self.n_mon = 0
|
| 413 |
+
self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0
|
| 414 |
+
self.episodes = [] # summaries of the written episodes
|
| 415 |
+
self.task.reset_instance(self.inst)
|
| 416 |
+
self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
|
| 417 |
+
sim = self.task.env.sim
|
| 418 |
+
bid = sim.model.body_name2id("robot0_base")
|
| 419 |
+
self.base_off = np.array(sim.data.body_xpos[bid], float).copy()
|
| 420 |
+
if self.rec:
|
| 421 |
+
self._open_episode()
|
| 422 |
+
|
| 423 |
+
# ------------------------------------------------------------------ episodes
|
| 424 |
+
def _ep_dir(self):
|
| 425 |
+
return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}")
|
| 426 |
+
|
| 427 |
+
def _open_episode(self):
|
| 428 |
+
self.rec.sink = EpisodeSink(self._ep_dir())
|
| 429 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
|
| 430 |
+
self.rec.active = True
|
| 431 |
+
self.events, self.spans, self.ep_attempts = [], [], []
|
| 432 |
+
self.ep_initial = self.rec.state() # state right after the reset (before frame 0)
|
| 433 |
+
|
| 434 |
+
def close_episode(self):
|
| 435 |
+
if not self.rec:
|
| 436 |
+
self.ep_attempts = []
|
| 437 |
+
return
|
| 438 |
+
sink = self.rec.sink
|
| 439 |
+
st = self.rec.state()
|
| 440 |
+
imgs = self.rec.images()
|
| 441 |
+
st.pop("sim_state", None)
|
| 442 |
+
sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs)
|
| 443 |
+
ann = build_annotation(self, sink)
|
| 444 |
+
with open(os.path.join(sink.path, "annotation.json"), "w") as f:
|
| 445 |
+
json.dump(ann, f, indent=1, default=_json_default)
|
| 446 |
+
self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n,
|
| 447 |
+
attempts=[a["attempt"] for a in self.ep_attempts]))
|
| 448 |
+
self.rec.active = False
|
| 449 |
+
self.rec.sink = None
|
| 450 |
+
self.ep_index += 1
|
| 451 |
+
|
| 452 |
+
# ------------------------------------------------------------------ monitor events (task-side error events)
|
| 453 |
+
def poll_events(self, frame):
|
| 454 |
+
mon = getattr(self.task, "mon", None)
|
| 455 |
+
evs = mon.get("events") if isinstance(mon, dict) else None
|
| 456 |
+
if not isinstance(evs, list):
|
| 457 |
+
return
|
| 458 |
+
if len(evs) < self.n_mon: # monitor was rebuilt
|
| 459 |
+
self.n_mon = 0
|
| 460 |
+
for e in evs[self.n_mon:]:
|
| 461 |
+
self.events.append(dict(frame=int(frame), attempt=self.attempt,
|
| 462 |
+
event=norm_json(e) if isinstance(e, dict) else str(e)))
|
| 463 |
+
self.n_mon = len(evs)
|
| 464 |
+
|
| 465 |
+
# ------------------------------------------------------------------ state as the server reports it
|
| 466 |
+
def proprio_la(self):
|
| 467 |
+
p = self.ex.proprio()
|
| 468 |
+
pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off]
|
| 469 |
+
return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"])
|
| 470 |
+
|
| 471 |
+
def compare(self, where, rep_logged, rep):
|
| 472 |
+
self.n_checked += 1
|
| 473 |
+
for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"):
|
| 474 |
+
if k not in rep_logged or k not in rep:
|
| 475 |
+
continue
|
| 476 |
+
a, b = rep_logged[k], rep[k]
|
| 477 |
+
if k == "eef_pos":
|
| 478 |
+
dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float))))
|
| 479 |
+
self.max_dev_m = max(self.max_dev_m, dev)
|
| 480 |
+
if dev > 1.5e-4:
|
| 481 |
+
self.mismatch.append((where, k, a, b))
|
| 482 |
+
elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4):
|
| 483 |
+
self.mismatch.append((where, k, a, b))
|
| 484 |
+
if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)):
|
| 485 |
+
self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok")))
|
| 486 |
+
|
| 487 |
+
def _span(self, e, f0, kind):
|
| 488 |
+
if self.rec:
|
| 489 |
+
self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0,
|
| 490 |
+
frame_end=self.rec.n))
|
| 491 |
+
|
| 492 |
+
# ------------------------------------------------------------------ commands (robot_server._handle_v2)
|
| 493 |
+
def move_eef(self, e):
|
| 494 |
+
args = e.get("args") or {}
|
| 495 |
+
where = f"a{e['attempt']}s{e['step']}"
|
| 496 |
+
logged = e.get("report") or {}
|
| 497 |
+
f0 = self.rec.n if self.rec else 0
|
| 498 |
+
p = self.ex.proprio()
|
| 499 |
+
if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}:
|
| 500 |
+
self._span(e, f0, "error")
|
| 501 |
+
return self.compare(where, logged, dict(ok=False))
|
| 502 |
+
off = self.base_off
|
| 503 |
+
try:
|
| 504 |
+
cur = np.asarray(p["eef_pos"], float) - off
|
| 505 |
+
tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
|
| 506 |
+
yaw = float(args.get("yaw", p["eef_yaw_deg"]))
|
| 507 |
+
speed = None if args.get("speed") in (None, "") else float(args["speed"])
|
| 508 |
+
except (TypeError, ValueError):
|
| 509 |
+
self._span(e, f0, "error")
|
| 510 |
+
return self.compare(where, logged, dict(ok=False))
|
| 511 |
+
grip = args.get("gripper")
|
| 512 |
+
if grip not in (None, "open", "close"):
|
| 513 |
+
self._span(e, f0, "error")
|
| 514 |
+
return self.compare(where, logged, dict(ok=False))
|
| 515 |
+
moving = any(k in args for k in ("x", "y", "z", "yaw"))
|
| 516 |
+
tgt_w = np.asarray(tgt) + off
|
| 517 |
+
if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)):
|
| 518 |
+
self._span(e, f0, "rejected")
|
| 519 |
+
return self.compare(where, logged, dict(ok=False, **self.proprio_la()))
|
| 520 |
+
raw = {}
|
| 521 |
+
if self.rec:
|
| 522 |
+
self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"])
|
| 523 |
+
if moving:
|
| 524 |
+
mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw)
|
| 525 |
+
if speed is not None:
|
| 526 |
+
mv["speed"] = speed
|
| 527 |
+
raw.update(self.ex.call("move_to", mv).report)
|
| 528 |
+
if grip is not None:
|
| 529 |
+
if self.rec:
|
| 530 |
+
self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"])
|
| 531 |
+
raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report)
|
| 532 |
+
rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la())
|
| 533 |
+
self.compare(where, logged, rep)
|
| 534 |
+
lr = e.get("raw") or {}
|
| 535 |
+
for k in ("holding_object", "touched_object"):
|
| 536 |
+
if k in lr and k in raw and bool(lr[k]) != bool(raw[k]):
|
| 537 |
+
self.mismatch.append((where, "raw." + k, lr[k], raw[k]))
|
| 538 |
+
self._span(e, f0, "move_eef")
|
| 539 |
+
|
| 540 |
+
def observe(self, e):
|
| 541 |
+
f0 = self.rec.n if self.rec else 0
|
| 542 |
+
self._span(e, f0, "observe")
|
| 543 |
+
|
| 544 |
+
def done(self, e):
|
| 545 |
+
f0 = self.rec.n if self.rec else 0
|
| 546 |
+
if self.rec:
|
| 547 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"])
|
| 548 |
+
out = self.task.outcome(self.inst)
|
| 549 |
+
succ = bool(out["success"])
|
| 550 |
+
where = f"a{e['attempt']}done"
|
| 551 |
+
if succ != bool(e.get("success") in (True, "True")):
|
| 552 |
+
self.mismatch.append((where, "success", e.get("success"), succ))
|
| 553 |
+
lo = e.get("outcome") or {}
|
| 554 |
+
ro = norm_json({k: v for k, v in out.items() if k != "feedback"})
|
| 555 |
+
if isinstance(lo, dict):
|
| 556 |
+
for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8):
|
| 557 |
+
self.mismatch.append((where,) + d)
|
| 558 |
+
info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""),
|
| 559 |
+
feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")),
|
| 560 |
+
think_s=e.get("think_s"))
|
| 561 |
+
try:
|
| 562 |
+
info["feedback_f2"] = self.task.feedback(self.inst, out, "F2")
|
| 563 |
+
except Exception as ex_:
|
| 564 |
+
info["feedback_f2"] = f"<unavailable: {type(ex_).__name__}>"
|
| 565 |
+
if self.rec:
|
| 566 |
+
info["judge_frames"] = [f0, self.rec.n]
|
| 567 |
+
self.ep_attempts.append(info)
|
| 568 |
+
last = self.attempt >= self.k or succ or bool(out.get("terminal"))
|
| 569 |
+
if self.protocol == "cross" or last:
|
| 570 |
+
self.close_episode()
|
| 571 |
+
if last:
|
| 572 |
+
return True
|
| 573 |
+
self.attempt += 1
|
| 574 |
+
if self.protocol == "cross":
|
| 575 |
+
self.task.reset_instance(self.inst)
|
| 576 |
+
self.n_mon = 0
|
| 577 |
+
if self.rec:
|
| 578 |
+
self._open_episode()
|
| 579 |
+
elif self.rec:
|
| 580 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
|
| 581 |
+
self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
|
| 582 |
+
return False
|
| 583 |
+
|
| 584 |
+
def run(self):
|
| 585 |
+
t0 = time.time()
|
| 586 |
+
finished = False
|
| 587 |
+
for e in self.ev:
|
| 588 |
+
if e["ev"] == "call":
|
| 589 |
+
if e.get("cmd") == "move_eef":
|
| 590 |
+
self.move_eef(e)
|
| 591 |
+
elif e.get("cmd") == "observe":
|
| 592 |
+
self.observe(e)
|
| 593 |
+
else:
|
| 594 |
+
self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None))
|
| 595 |
+
elif e["ev"] == "done":
|
| 596 |
+
finished = self.done(e)
|
| 597 |
+
if finished:
|
| 598 |
+
break
|
| 599 |
+
self.unfinished = not finished
|
| 600 |
+
if not finished and self.rec and self.rec.sink is not None:
|
| 601 |
+
# the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged
|
| 602 |
+
if self.rec.n or self.ep_attempts:
|
| 603 |
+
self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True,
|
| 604 |
+
finish_reason="", feedback_shown="", auto_ended=False))
|
| 605 |
+
self.close_episode()
|
| 606 |
+
else:
|
| 607 |
+
shutil.rmtree(self.rec.sink.path, ignore_errors=True)
|
| 608 |
+
self.rec.sink = None
|
| 609 |
+
self.wall_s = time.time() - t0
|
| 610 |
+
return self
|
| 611 |
+
|
| 612 |
+
def summary(self):
|
| 613 |
+
return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"],
|
| 614 |
+
protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff),
|
| 615 |
+
n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6),
|
| 616 |
+
unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1),
|
| 617 |
+
first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]])
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
# ====================================================================================================== annotation
|
| 621 |
+
|
| 622 |
+
def task_info(task, inst):
|
| 623 |
+
cls = type(task)
|
| 624 |
+
return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable",
|
| 625 |
+
category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"),
|
| 626 |
+
max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)),
|
| 627 |
+
instruction=cls.instruction)
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
def build_annotation(rp, sink):
|
| 631 |
+
"""Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2
|
| 632 |
+
failure description), run-level outcome class, every robot command with its frame span and the agent's narration,
|
| 633 |
+
task-side error events with frame indices."""
|
| 634 |
+
log = rp.log
|
| 635 |
+
s = rp.start
|
| 636 |
+
cond, chain = log.condition()
|
| 637 |
+
cls, hist = log.outcome_class()
|
| 638 |
+
att_all = log.attempts()
|
| 639 |
+
attempts = []
|
| 640 |
+
for a in rp.ep_attempts:
|
| 641 |
+
a = dict(a)
|
| 642 |
+
n = a["attempt"]
|
| 643 |
+
later = [x for x in att_all if x["attempt"] > n]
|
| 644 |
+
a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later))
|
| 645 |
+
a["is_last_attempt_of_run"] = not later
|
| 646 |
+
fn = log.finish_notes.get(n)
|
| 647 |
+
if fn:
|
| 648 |
+
a["agent_finish"] = fn
|
| 649 |
+
a["error_event_in_attempt"] = error_event(a.get("outcome"))
|
| 650 |
+
attempts.append(a)
|
| 651 |
+
# post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command)
|
| 652 |
+
for a in attempts:
|
| 653 |
+
nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1])
|
| 654 |
+
if a.get("success") is False and nxt:
|
| 655 |
+
note = log.notes[nxt[0]]
|
| 656 |
+
a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note}
|
| 657 |
+
commands = []
|
| 658 |
+
for sp in rp.spans:
|
| 659 |
+
e = log.calls.get((sp["attempt"], sp["step"])) or {}
|
| 660 |
+
rep = e.get("report") or {}
|
| 661 |
+
c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"],
|
| 662 |
+
frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]),
|
| 663 |
+
args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"),
|
| 664 |
+
stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"),
|
| 665 |
+
gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"),
|
| 666 |
+
touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"),
|
| 667 |
+
agent_obs_images=rep.get("images"))
|
| 668 |
+
note = log.notes.get((sp["attempt"], sp["step"]))
|
| 669 |
+
if note:
|
| 670 |
+
c["agent_note"] = {k: v for k, v in note.items() if k != "command"}
|
| 671 |
+
commands.append(c)
|
| 672 |
+
t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x]
|
| 673 |
+
return dict(
|
| 674 |
+
schema=SCHEMA,
|
| 675 |
+
source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts],
|
| 676 |
+
episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain,
|
| 677 |
+
memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None),
|
| 678 |
+
feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"),
|
| 679 |
+
k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"),
|
| 680 |
+
contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256")
|
| 681 |
+
if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)),
|
| 682 |
+
agent=log.agent_info(),
|
| 683 |
+
task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"),
|
| 684 |
+
instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}),
|
| 685 |
+
run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all),
|
| 686 |
+
run_success=any(x["success"] for x in att_all) if att_all else None,
|
| 687 |
+
agent_final_report=log.final_report[:6000] or None,
|
| 688 |
+
mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)),
|
| 689 |
+
attempts=attempts,
|
| 690 |
+
commands=commands,
|
| 691 |
+
task_events=rp.events,
|
| 692 |
+
frames=dict(n=sink.n, fps=FPS, image_res=rp.res,
|
| 693 |
+
phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"],
|
| 694 |
+
joint_pos=rp.ep_initial["joint_pos"],
|
| 695 |
+
gripper_qpos=rp.ep_initial["gripper_qpos"])),
|
| 696 |
+
)
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
# ====================================================================================================== CLI
|
| 700 |
+
|
| 701 |
+
def load_manifest(run_dir):
|
| 702 |
+
p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json")
|
| 703 |
+
return json.load(open(p)) if os.path.exists(p) else {}
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
def main():
|
| 707 |
+
ap = argparse.ArgumentParser()
|
| 708 |
+
ap.add_argument("mode", choices=["check", "record"])
|
| 709 |
+
ap.add_argument("runs", nargs="+")
|
| 710 |
+
ap.add_argument("--json", default="")
|
| 711 |
+
ap.add_argument("--out", default="")
|
| 712 |
+
ap.add_argument("--res", type=int, default=256)
|
| 713 |
+
ap.add_argument("--force", action="store_true", help="record again even if replay.json exists")
|
| 714 |
+
a = ap.parse_args()
|
| 715 |
+
rows = []
|
| 716 |
+
for r in a.runs:
|
| 717 |
+
r = r.rstrip("/")
|
| 718 |
+
try:
|
| 719 |
+
if a.mode == "check":
|
| 720 |
+
s = RunReplay(r, manifest=load_manifest(r)).run().summary()
|
| 721 |
+
else:
|
| 722 |
+
batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r)
|
| 723 |
+
rd = os.path.join(a.out, batch, name)
|
| 724 |
+
if os.path.exists(os.path.join(rd, "replay.json")) and not a.force:
|
| 725 |
+
print(json.dumps(dict(run=name, skipped="exists")), flush=True)
|
| 726 |
+
continue
|
| 727 |
+
shutil.rmtree(rd, ignore_errors=True)
|
| 728 |
+
rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run()
|
| 729 |
+
s = rp.summary()
|
| 730 |
+
s["episodes"] = rp.episodes
|
| 731 |
+
with open(os.path.join(rd, "replay.json"), "w") as f:
|
| 732 |
+
json.dump(s, f, indent=1)
|
| 733 |
+
except Exception:
|
| 734 |
+
import traceback
|
| 735 |
+
s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:])
|
| 736 |
+
rows.append(s)
|
| 737 |
+
print(json.dumps(s), flush=True)
|
| 738 |
+
if a.json:
|
| 739 |
+
with open(a.json, "w") as f:
|
| 740 |
+
json.dump(rows, f, indent=1)
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
if __name__ == "__main__":
|
| 744 |
+
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars.
|
| 2 |
+
|
| 3 |
+
Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding
|
| 4 |
+
can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan):
|
| 5 |
+
|
| 6 |
+
python scripts/lerobot_export.py plan --raw <raw_root>[,<raw_root2>] --runs-root <lffbench>/runs/api \
|
| 7 |
+
--paper <paper/latex> --task-set <lffbench>/sets/main_v2_1inst.txt --work <work_dir> [--batches ...] [--limit N]
|
| 8 |
+
python scripts/lerobot_export.py shard --work <work_dir> --shard i --nshards N
|
| 9 |
+
python scripts/lerobot_export.py merge --work <work_dir> --nshards N --out <dataset_root>
|
| 10 |
+
|
| 11 |
+
Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0
|
| 12 |
+
mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped.
|
| 13 |
+
|
| 14 |
+
LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t):
|
| 15 |
+
observation.images.image agentview RGB 256x256 (upright; LIBERO naming)
|
| 16 |
+
observation.images.wrist_image wrist (eye-in-hand) RGB 256x256
|
| 17 |
+
observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout)
|
| 18 |
+
observation.joint_pos / joint_vel 7 arm joints (rad, rad/s)
|
| 19 |
+
observation.eef_quat 4: xyzw; observation.gripper_width 1 (m)
|
| 20 |
+
action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad),
|
| 21 |
+
gripper (-1 open, +1 close)
|
| 22 |
+
annotation.attempt_index attempt (1-based) the frame belongs to
|
| 23 |
+
annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`)
|
| 24 |
+
annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action)
|
| 25 |
+
annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt
|
| 26 |
+
annotation.task_event number of task-monitor events (error / progress events) registered at this step
|
| 27 |
+
Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table),
|
| 28 |
+
runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state
|
| 29 |
+
per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/.
|
| 30 |
+
"""
|
| 31 |
+
import argparse
|
| 32 |
+
import glob
|
| 33 |
+
import json
|
| 34 |
+
import os
|
| 35 |
+
import re
|
| 36 |
+
import shutil
|
| 37 |
+
import time
|
| 38 |
+
|
| 39 |
+
import numpy as np
|
| 40 |
+
|
| 41 |
+
FPS = 20
|
| 42 |
+
RES = 256
|
| 43 |
+
BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke",
|
| 44 |
+
"cc_smoke", "cc_opus_smoke"]
|
| 45 |
+
BATCH_NOTES = {
|
| 46 |
+
"cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog",
|
| 47 |
+
"cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267",
|
| 48 |
+
"cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299",
|
| 49 |
+
"cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances",
|
| 50 |
+
"cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)",
|
| 51 |
+
"cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the "
|
| 52 |
+
"with-history continuation of failed runs is incomplete",
|
| 53 |
+
"cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early",
|
| 54 |
+
"cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt",
|
| 55 |
+
"cc_opus_smoke": "smoke test: single attempt",
|
| 56 |
+
}
|
| 57 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 58 |
+
CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)",
|
| 59 |
+
"L2": "disturbed state to restore (incl. damage the agent causes)",
|
| 60 |
+
"L3": "infeasible manipulation strategy (grasp / contact / tool must change)",
|
| 61 |
+
"L4": "misjudged geometry (size, shape, fit, hidden structure)",
|
| 62 |
+
"L5": "misjudged physics (mass distribution, friction, dynamics)"}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def features():
|
| 66 |
+
vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]}
|
| 67 |
+
f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names}
|
| 68 |
+
i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None}
|
| 69 |
+
return {
|
| 70 |
+
"observation.images.image": vid(),
|
| 71 |
+
"observation.images.wrist_image": vid(),
|
| 72 |
+
"observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z",
|
| 73 |
+
"finger_qpos_left", "finger_qpos_right"]),
|
| 74 |
+
"observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 75 |
+
"observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 76 |
+
"observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]),
|
| 77 |
+
"observation.gripper_width": f32(1, ["width_m"]),
|
| 78 |
+
"action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y",
|
| 79 |
+
"eef_delta_rot_aa_z", "gripper_close"]),
|
| 80 |
+
"annotation.attempt_index": i64(),
|
| 81 |
+
"annotation.command_index": i64(),
|
| 82 |
+
"annotation.phase": i64(),
|
| 83 |
+
"annotation.attempt_success": i64(),
|
| 84 |
+
"annotation.task_event": i64(),
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ------------------------------------------------------------------------------------------------ paper metadata
|
| 89 |
+
|
| 90 |
+
def _clean_tex(s):
|
| 91 |
+
s = re.sub(r"%.*", "", s)
|
| 92 |
+
for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"),
|
| 93 |
+
(r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"),
|
| 94 |
+
(r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"),
|
| 95 |
+
(r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"),
|
| 96 |
+
(r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]:
|
| 97 |
+
s = re.sub(a, b, s)
|
| 98 |
+
s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s)
|
| 99 |
+
s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s)
|
| 100 |
+
for _ in range(3):
|
| 101 |
+
s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s)
|
| 102 |
+
s = re.sub(r"\$([^$]*)\$", r"\1", s)
|
| 103 |
+
s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ")
|
| 104 |
+
s = re.sub(r"\{([^{}]*)\}", r"\1", s)
|
| 105 |
+
s = re.sub(r"\\[a-zA-Z]+\*?", "", s)
|
| 106 |
+
return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def paper_tasks(paper_dir):
|
| 110 |
+
"""{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the
|
| 111 |
+
paper's task table and task appendix (empty if the paper sources are not there)."""
|
| 112 |
+
out = {}
|
| 113 |
+
if not paper_dir:
|
| 114 |
+
return out
|
| 115 |
+
app = os.path.join(paper_dir, "sections", "appendix_tasks.tex")
|
| 116 |
+
tab = os.path.join(paper_dir, "sections", "tab_tasks.tex")
|
| 117 |
+
if os.path.exists(app):
|
| 118 |
+
txt = open(app).read()
|
| 119 |
+
parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt)
|
| 120 |
+
for i in range(1, len(parts) - 1, 2):
|
| 121 |
+
if parts[i] != "\\paragraph{":
|
| 122 |
+
continue
|
| 123 |
+
body = parts[i + 1]
|
| 124 |
+
m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S)
|
| 125 |
+
if not m:
|
| 126 |
+
continue
|
| 127 |
+
name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip()
|
| 128 |
+
desc = _clean_tex(body[m.end():])
|
| 129 |
+
out[code] = dict(name=name, cause=_clean_tex(cause), description=desc)
|
| 130 |
+
if os.path.exists(tab):
|
| 131 |
+
names = {v["name"].lower(): k for k, v in out.items()}
|
| 132 |
+
for line in open(tab):
|
| 133 |
+
cells = [c.strip() for c in line.split("&")]
|
| 134 |
+
if len(cells) != 6 or not cells[-1].endswith("\\\\"):
|
| 135 |
+
continue
|
| 136 |
+
nm = re.sub(r"\\contscene", "", cells[0]).strip().lower()
|
| 137 |
+
code = names.get(nm)
|
| 138 |
+
if not code:
|
| 139 |
+
continue
|
| 140 |
+
out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]),
|
| 141 |
+
repair_within_attempt=_clean_tex(cells[3]) == "yes",
|
| 142 |
+
oracle_first_attempt_pct=_clean_tex(cells[4]),
|
| 143 |
+
naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip()))
|
| 144 |
+
return out
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
# ------------------------------------------------------------------------------------------------ collection
|
| 148 |
+
|
| 149 |
+
def manifest_status(runs_root, batch, run, cache={}):
|
| 150 |
+
if batch not in cache:
|
| 151 |
+
p = os.path.join(runs_root, batch, "manifest.json")
|
| 152 |
+
cache[batch] = json.load(open(p)) if os.path.exists(p) else {}
|
| 153 |
+
m = cache[batch]
|
| 154 |
+
for r in m.get("runs", []):
|
| 155 |
+
if r.get("run") == run:
|
| 156 |
+
return r.get("status", "?"), r
|
| 157 |
+
for r in m.get("superseded", []):
|
| 158 |
+
if r.get("run") == run:
|
| 159 |
+
return "superseded_" + str(r.get("status", "?")), r
|
| 160 |
+
return "not_in_manifest", {}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def collect(raw_roots, runs_root, batches, task_order):
|
| 164 |
+
"""Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root."""
|
| 165 |
+
eps, rejected, seen = [], [], set()
|
| 166 |
+
for root in raw_roots:
|
| 167 |
+
for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))):
|
| 168 |
+
rep = json.load(open(rj))
|
| 169 |
+
batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"]
|
| 170 |
+
if (batches and batch not in batches) or (batch, run) in seen:
|
| 171 |
+
continue
|
| 172 |
+
seen.add((batch, run))
|
| 173 |
+
ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff")
|
| 174 |
+
status, entry = manifest_status(runs_root, batch, run)
|
| 175 |
+
if not ok:
|
| 176 |
+
never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked")
|
| 177 |
+
rejected.append(dict(run=run, batch=batch, run_status=status,
|
| 178 |
+
reason="run never started (no contract, no robot command)" if never else
|
| 179 |
+
"replay does not reproduce the log (the log has gaps or the replay diverged)",
|
| 180 |
+
detail=rep.get("first_mismatches")))
|
| 181 |
+
continue
|
| 182 |
+
for ep in rep.get("episodes", []):
|
| 183 |
+
d = os.path.join(root, ep["dir"])
|
| 184 |
+
ann = json.load(open(os.path.join(d, "annotation.json")))
|
| 185 |
+
judged = [a for a in ann["attempts"] if a.get("success") is not None]
|
| 186 |
+
if not judged or ep["n_frames"] == 0:
|
| 187 |
+
rejected.append(dict(run=run, batch=batch, episode=ep["dir"],
|
| 188 |
+
reason="no judged attempt" if not judged else "no frames"))
|
| 189 |
+
continue
|
| 190 |
+
ann["source"]["run_status"] = status
|
| 191 |
+
ann["source"]["manifest_id"] = entry.get("id")
|
| 192 |
+
ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"],
|
| 193 |
+
max_eef_dev_m=rep["max_eef_dev_m"])
|
| 194 |
+
key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99),
|
| 195 |
+
{"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2),
|
| 196 |
+
ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"])
|
| 197 |
+
eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann))
|
| 198 |
+
eps.sort(key=lambda x: x["key"])
|
| 199 |
+
return eps, rejected
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# ------------------------------------------------------------------------------------------------ writing
|
| 203 |
+
|
| 204 |
+
def frames_of(path):
|
| 205 |
+
import av
|
| 206 |
+
with av.open(path) as c:
|
| 207 |
+
for fr in c.decode(video=0):
|
| 208 |
+
yield fr.to_ndarray(format="rgb24")
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def flat_row(i, ann, n, idx0):
|
| 212 |
+
s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"]
|
| 213 |
+
att = ann["attempts"]
|
| 214 |
+
a0 = att[0]
|
| 215 |
+
return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n,
|
| 216 |
+
batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"],
|
| 217 |
+
memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"),
|
| 218 |
+
episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att],
|
| 219 |
+
harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"),
|
| 220 |
+
effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"),
|
| 221 |
+
task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"),
|
| 222 |
+
category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"],
|
| 223 |
+
success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att],
|
| 224 |
+
feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att],
|
| 225 |
+
auto_ended=[a.get("auto_ended") for a in att],
|
| 226 |
+
corrected_later_in_run=[a.get("corrected_later_in_run") for a in att],
|
| 227 |
+
error_event_in_attempt=[a.get("error_event_in_attempt") for a in att],
|
| 228 |
+
run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"),
|
| 229 |
+
n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]),
|
| 230 |
+
first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def cmd_plan(a):
|
| 234 |
+
task_order = {}
|
| 235 |
+
if a.task_set and os.path.exists(a.task_set):
|
| 236 |
+
for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")):
|
| 237 |
+
task_order[line.split(":")[0].strip()] = i
|
| 238 |
+
batches = [b for b in a.batches.split(",") if b] if a.batches else None
|
| 239 |
+
eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order)
|
| 240 |
+
if a.limit:
|
| 241 |
+
eps = eps[:a.limit]
|
| 242 |
+
paper = paper_tasks(a.paper)
|
| 243 |
+
idx0 = 0
|
| 244 |
+
for i, e in enumerate(eps):
|
| 245 |
+
ann = e["ann"]
|
| 246 |
+
tname = ann["task"]["name"]
|
| 247 |
+
if tname in paper:
|
| 248 |
+
ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"}
|
| 249 |
+
ann["episode_index"] = i
|
| 250 |
+
ann["dataset_index_range"] = [idx0, idx0 + e["n"]]
|
| 251 |
+
e["index"], e["from"] = i, idx0
|
| 252 |
+
idx0 += e["n"]
|
| 253 |
+
del e["key"]
|
| 254 |
+
os.makedirs(a.work, exist_ok=True)
|
| 255 |
+
with open(os.path.join(a.work, "plan.json"), "w") as f:
|
| 256 |
+
json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f,
|
| 257 |
+
ensure_ascii=False)
|
| 258 |
+
print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def shard_range(n_eps, i, k):
|
| 262 |
+
return (n_eps * i) // k, (n_eps * (i + 1)) // k
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def cmd_shard(a):
|
| 266 |
+
from lerobot.datasets.lerobot_dataset import LeRobotDataset
|
| 267 |
+
t0 = time.time()
|
| 268 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 269 |
+
eps = plan["episodes"]
|
| 270 |
+
lo, hi = shard_range(len(eps), a.shard, a.nshards)
|
| 271 |
+
out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}")
|
| 272 |
+
if os.path.exists(os.path.join(out, "DONE")):
|
| 273 |
+
print(f"shard {a.shard}: done already", flush=True)
|
| 274 |
+
return
|
| 275 |
+
shutil.rmtree(out, ignore_errors=True)
|
| 276 |
+
ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out,
|
| 277 |
+
robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads,
|
| 278 |
+
vcodec=a.vcodec)
|
| 279 |
+
nfr = 0
|
| 280 |
+
for e in eps[lo:hi]:
|
| 281 |
+
d, ann, n = e["dir"], e["ann"], e["n"]
|
| 282 |
+
fr = np.load(os.path.join(d, "frames.npz"))
|
| 283 |
+
assert len(fr["action"]) == n, d
|
| 284 |
+
succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]}
|
| 285 |
+
evc = np.zeros(n, np.int64)
|
| 286 |
+
for ev in ann["task_events"]:
|
| 287 |
+
if 0 <= ev["frame"] < n:
|
| 288 |
+
evc[ev["frame"]] += 1
|
| 289 |
+
state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32)
|
| 290 |
+
instr = ann["task"]["instruction"]
|
| 291 |
+
k = 0
|
| 292 |
+
for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))):
|
| 293 |
+
if k >= n:
|
| 294 |
+
break
|
| 295 |
+
ds.add_frame({
|
| 296 |
+
"observation.images.image": img, "observation.images.wrist_image": wr,
|
| 297 |
+
"observation.state": state[k],
|
| 298 |
+
"observation.joint_pos": fr["joint_pos"][k].astype(np.float32),
|
| 299 |
+
"observation.joint_vel": fr["joint_vel"][k].astype(np.float32),
|
| 300 |
+
"observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32),
|
| 301 |
+
"observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32),
|
| 302 |
+
"action": fr["action"][k].astype(np.float32),
|
| 303 |
+
"annotation.attempt_index": np.array([fr["attempt"][k]], np.int64),
|
| 304 |
+
"annotation.command_index": np.array([fr["command"][k]], np.int64),
|
| 305 |
+
"annotation.phase": np.array([fr["phase"][k]], np.int64),
|
| 306 |
+
"annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64),
|
| 307 |
+
"annotation.task_event": np.array([evc[k]], np.int64),
|
| 308 |
+
"task": instr,
|
| 309 |
+
})
|
| 310 |
+
k += 1
|
| 311 |
+
if k != n:
|
| 312 |
+
raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames")
|
| 313 |
+
ds.save_episode()
|
| 314 |
+
nfr += n
|
| 315 |
+
ds.finalize()
|
| 316 |
+
shutil.rmtree(os.path.join(out, "images"), ignore_errors=True)
|
| 317 |
+
open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n")
|
| 318 |
+
print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def cmd_merge(a):
|
| 322 |
+
from pathlib import Path
|
| 323 |
+
from lerobot.datasets.aggregate import aggregate_datasets
|
| 324 |
+
t0 = time.time()
|
| 325 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 326 |
+
eps = plan["episodes"]
|
| 327 |
+
roots, ids = [], []
|
| 328 |
+
for i in range(a.nshards):
|
| 329 |
+
lo, hi = shard_range(len(eps), i, a.nshards)
|
| 330 |
+
if hi <= lo:
|
| 331 |
+
continue
|
| 332 |
+
r = os.path.join(a.work, "shards", f"shard_{i:03d}")
|
| 333 |
+
if not os.path.exists(os.path.join(r, "DONE")):
|
| 334 |
+
raise SystemExit(f"shard {i} is not done")
|
| 335 |
+
roots.append(Path(r))
|
| 336 |
+
ids.append(f"{plan['repo_id']}-shard{i:03d}")
|
| 337 |
+
if os.path.exists(a.out):
|
| 338 |
+
raise SystemExit(f"{a.out} exists; refusing to overwrite")
|
| 339 |
+
aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out))
|
| 340 |
+
print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True)
|
| 341 |
+
write_sidecars(a, plan)
|
| 342 |
+
print(f"merge done in {time.time() - t0:.0f}s", flush=True)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def write_sidecars(a, plan):
|
| 346 |
+
eps, paper = plan["episodes"], plan["paper"]
|
| 347 |
+
lff = os.path.join(a.out, "lff")
|
| 348 |
+
for sub in ("annotations", "sim_state", "final", "code"):
|
| 349 |
+
os.makedirs(os.path.join(lff, sub), exist_ok=True)
|
| 350 |
+
rows, runs, tasks = [], {}, {}
|
| 351 |
+
for e in eps:
|
| 352 |
+
i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"]
|
| 353 |
+
name = f"episode_{i:06d}"
|
| 354 |
+
if os.path.exists(os.path.join(d, "sim_state.npy")):
|
| 355 |
+
shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy"))
|
| 356 |
+
shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz"))
|
| 357 |
+
for cam, key in (("agentview", "image"), ("wrist", "wrist_image")):
|
| 358 |
+
shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png"))
|
| 359 |
+
with open(os.path.join(lff, "annotations", name + ".json"), "w") as f:
|
| 360 |
+
json.dump(ann, f, indent=1, ensure_ascii=False)
|
| 361 |
+
rows.append(flat_row(i, ann, n, e["from"]))
|
| 362 |
+
tname = ann["task"]["name"]
|
| 363 |
+
rk = (ann["source"]["batch"], ann["source"]["run"])
|
| 364 |
+
r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"),
|
| 365 |
+
run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"],
|
| 366 |
+
memory_free_chain_of=ann["source"].get("memory_free_chain_of"),
|
| 367 |
+
memory_free_rep=ann["source"].get("memory_free_rep"), task=tname,
|
| 368 |
+
seed=ann["task"]["seed"], model=ann["agent"].get("model"),
|
| 369 |
+
harness=ann["agent"].get("harness"),
|
| 370 |
+
harness_version=ann["agent"].get("harness_version"),
|
| 371 |
+
codex_catalog=ann["agent"].get("codex_catalog"),
|
| 372 |
+
outcome_class=ann["run_outcome"].get("outcome_class"),
|
| 373 |
+
attempt_history=ann["run_outcome"].get("attempt_history"),
|
| 374 |
+
agent_final_report=ann["run_outcome"].get("agent_final_report"),
|
| 375 |
+
episodes=[]))
|
| 376 |
+
for x in ann["attempts"]:
|
| 377 |
+
r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success")))
|
| 378 |
+
if tname not in tasks:
|
| 379 |
+
tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")}
|
| 380 |
+
if tname in paper:
|
| 381 |
+
tasks[tname]["paper"] = paper[tname]
|
| 382 |
+
tasks[tname]["instances"] = {}
|
| 383 |
+
tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"]
|
| 384 |
+
# memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id)
|
| 385 |
+
by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")}
|
| 386 |
+
for r in runs.values():
|
| 387 |
+
if r.get("memory_free_chain_of"):
|
| 388 |
+
r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"]))
|
| 389 |
+
for (b, rn), r in runs.items():
|
| 390 |
+
r["memory_free_retries"] = sorted((x["run"] for x in runs.values()
|
| 391 |
+
if x["batch"] == b and x.get("memory_free_chain_of_run") == rn),
|
| 392 |
+
key=lambda q: runs[(b, q)].get("memory_free_rep") or 0)
|
| 393 |
+
with open(os.path.join(lff, "episodes.jsonl"), "w") as f:
|
| 394 |
+
for row in rows:
|
| 395 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 396 |
+
with open(os.path.join(lff, "runs.jsonl"), "w") as f:
|
| 397 |
+
for r in runs.values():
|
| 398 |
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 399 |
+
with open(os.path.join(lff, "tasks.json"), "w") as f:
|
| 400 |
+
json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False)
|
| 401 |
+
with open(os.path.join(lff, "batches.json"), "w") as f:
|
| 402 |
+
json.dump(BATCH_NOTES, f, indent=1)
|
| 403 |
+
with open(os.path.join(lff, "rejected.json"), "w") as f:
|
| 404 |
+
json.dump(plan["rejected"], f, indent=1)
|
| 405 |
+
here = os.path.dirname(os.path.abspath(__file__))
|
| 406 |
+
for s in ("lerobot_replay.py", "lerobot_export.py"):
|
| 407 |
+
shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s))
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def main():
|
| 411 |
+
ap = argparse.ArgumentParser()
|
| 412 |
+
ap.add_argument("step", choices=["plan", "shard", "merge"])
|
| 413 |
+
ap.add_argument("--work", required=True)
|
| 414 |
+
ap.add_argument("--raw", default="")
|
| 415 |
+
ap.add_argument("--runs-root", default="")
|
| 416 |
+
ap.add_argument("--out", default="")
|
| 417 |
+
ap.add_argument("--paper", default="")
|
| 418 |
+
ap.add_argument("--task-set", default="")
|
| 419 |
+
ap.add_argument("--repo-id", default="lffbench/agent-replays")
|
| 420 |
+
ap.add_argument("--batches", default="")
|
| 421 |
+
ap.add_argument("--limit", type=int, default=0)
|
| 422 |
+
ap.add_argument("--shard", type=int, default=0)
|
| 423 |
+
ap.add_argument("--nshards", type=int, default=1)
|
| 424 |
+
ap.add_argument("--threads", type=int, default=2)
|
| 425 |
+
ap.add_argument("--vcodec", default="libsvtav1")
|
| 426 |
+
a = ap.parse_args()
|
| 427 |
+
{"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
if __name__ == "__main__":
|
| 431 |
+
main()
|
leaf/code/compound-lh-20261102-clh_20261102_sonnet/lerobot_replay.py
ADDED
|
@@ -0,0 +1,744 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay
|
| 2 |
+
against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the
|
| 3 |
+
LeRobot export (scripts/lerobot_export.py).
|
| 4 |
+
|
| 5 |
+
python scripts/lerobot_replay.py check <run_dir> [<run_dir> ...] [--json out.json] # replay only, print fidelity
|
| 6 |
+
python scripts/lerobot_replay.py record <run_dir> --out <raw_root> [--res 256]
|
| 7 |
+
|
| 8 |
+
Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot
|
| 9 |
+
commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite
|
| 10 |
+
is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly
|
| 11 |
+
like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same
|
| 12 |
+
outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width,
|
| 13 |
+
ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code
|
| 14 |
+
hashes equal the current files are expected to match (check_code()).
|
| 15 |
+
|
| 16 |
+
Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB,
|
| 17 |
+
proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes:
|
| 18 |
+
protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode
|
| 19 |
+
per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the
|
| 20 |
+
fidelity check runs in record mode too. Per episode the recorder writes <raw_root>/<batch>/<run>/epNN/:
|
| 21 |
+
agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes)
|
| 22 |
+
frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase
|
| 23 |
+
sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel)
|
| 24 |
+
final_*.png, final.npz observation after the last control step (the state the outcome was judged in)
|
| 25 |
+
annotation.json episode annotation (build_annotation)
|
| 26 |
+
and <raw_root>/<batch>/<run>/replay.json (fidelity) when the whole run is done.
|
| 27 |
+
"""
|
| 28 |
+
import argparse
|
| 29 |
+
import ast
|
| 30 |
+
import hashlib
|
| 31 |
+
import importlib
|
| 32 |
+
import json
|
| 33 |
+
import math
|
| 34 |
+
import os
|
| 35 |
+
import pkgutil
|
| 36 |
+
import re
|
| 37 |
+
import shutil
|
| 38 |
+
import sys
|
| 39 |
+
import time
|
| 40 |
+
from collections import defaultdict
|
| 41 |
+
|
| 42 |
+
import numpy as np
|
| 43 |
+
|
| 44 |
+
LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 45 |
+
sys.path.insert(0, LFF_ROOT)
|
| 46 |
+
|
| 47 |
+
from lffbench import envs # noqa: E402
|
| 48 |
+
from lffbench import tasks as task_pkg # noqa: E402
|
| 49 |
+
from lffbench.agent import camera as C # noqa: E402
|
| 50 |
+
from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402
|
| 51 |
+
from lffbench.task_base import TASKS # noqa: E402
|
| 52 |
+
|
| 53 |
+
for _m in pkgutil.iter_modules(task_pkg.__path__):
|
| 54 |
+
importlib.import_module(f"lffbench.tasks.{_m.name}")
|
| 55 |
+
|
| 56 |
+
# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the
|
| 57 |
+
# task's outcome() check after `finish` (the arm holds still; not an agent action)
|
| 58 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 59 |
+
FPS = 20
|
| 60 |
+
SCHEMA = "lff-replay-1"
|
| 61 |
+
|
| 62 |
+
# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR"
|
| 63 |
+
ERROR_FLAGS = ("trap_fired", "recovered_in_attempt")
|
| 64 |
+
ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events",
|
| 65 |
+
"n_missed_strikes", "n_open_gripper_pushes")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def load_jsonl(p):
|
| 69 |
+
out = []
|
| 70 |
+
if not os.path.exists(p):
|
| 71 |
+
return out
|
| 72 |
+
with open(p) as f:
|
| 73 |
+
for line in f:
|
| 74 |
+
line = line.strip()
|
| 75 |
+
if line:
|
| 76 |
+
try:
|
| 77 |
+
out.append(json.loads(line))
|
| 78 |
+
except ValueError:
|
| 79 |
+
pass
|
| 80 |
+
return out
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def norm_json(o):
|
| 84 |
+
return json.loads(json.dumps(o, default=_json_default))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def sha256(p):
|
| 88 |
+
with open(p, "rb") as f:
|
| 89 |
+
return hashlib.sha256(f.read()).hexdigest()
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def check_code(run_dir):
|
| 93 |
+
"""[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract."""
|
| 94 |
+
p = os.path.join(run_dir, "contract.json")
|
| 95 |
+
if not os.path.exists(p):
|
| 96 |
+
return [("contract.json", None, None)]
|
| 97 |
+
files = json.load(open(p))["contract"].get("server_code_files", {})
|
| 98 |
+
bad = []
|
| 99 |
+
for f, h in files.items():
|
| 100 |
+
q = os.path.join(LFF_ROOT, f)
|
| 101 |
+
cur = sha256(q) if os.path.exists(q) else None
|
| 102 |
+
if cur != h:
|
| 103 |
+
bad.append((f, h, cur))
|
| 104 |
+
return bad
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def diff_json(a, b, path="", tol=0.0, out=None, limit=20):
|
| 108 |
+
"""Differences between two JSON values (numbers compared with an absolute tolerance)."""
|
| 109 |
+
out = [] if out is None else out
|
| 110 |
+
if len(out) >= limit:
|
| 111 |
+
return out
|
| 112 |
+
if isinstance(a, dict) and isinstance(b, dict):
|
| 113 |
+
for k in sorted(set(a) | set(b)):
|
| 114 |
+
if k not in a or k not in b:
|
| 115 |
+
out.append((f"{path}.{k}", a.get(k, "<missing>"), b.get(k, "<missing>")))
|
| 116 |
+
else:
|
| 117 |
+
diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit)
|
| 118 |
+
elif isinstance(a, list) and isinstance(b, list):
|
| 119 |
+
if len(a) != len(b):
|
| 120 |
+
out.append((path, f"len {len(a)}", f"len {len(b)}"))
|
| 121 |
+
else:
|
| 122 |
+
for i, (x, y) in enumerate(zip(a, b)):
|
| 123 |
+
diff_json(x, y, f"{path}[{i}]", tol, out, limit)
|
| 124 |
+
elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
|
| 125 |
+
if a != b:
|
| 126 |
+
out.append((path, a, b))
|
| 127 |
+
elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))):
|
| 128 |
+
out.append((path, a, b))
|
| 129 |
+
return out
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def error_event(o):
|
| 133 |
+
"""True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none."""
|
| 134 |
+
if not isinstance(o, dict):
|
| 135 |
+
return None
|
| 136 |
+
keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o]
|
| 137 |
+
if not keys:
|
| 138 |
+
return None
|
| 139 |
+
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)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# ====================================================================================================== logs -> notes
|
| 143 |
+
|
| 144 |
+
class RunLog:
|
| 145 |
+
"""Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's
|
| 146 |
+
narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition."""
|
| 147 |
+
|
| 148 |
+
def __init__(self, run_dir, manifest=None):
|
| 149 |
+
self.run_dir = os.path.abspath(run_dir.rstrip("/"))
|
| 150 |
+
self.run = os.path.basename(self.run_dir)
|
| 151 |
+
self.batch = os.path.basename(os.path.dirname(self.run_dir))
|
| 152 |
+
self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl"))
|
| 153 |
+
self.start = next(e for e in self.ev if e["ev"] == "session_start")
|
| 154 |
+
self.calls, self.dones, self.harness_status = {}, [], []
|
| 155 |
+
last = None
|
| 156 |
+
for e in self.ev:
|
| 157 |
+
if e["ev"] == "call":
|
| 158 |
+
self.calls[(int(e["attempt"]), int(e["step"]))] = e
|
| 159 |
+
last = e
|
| 160 |
+
elif e["ev"] == "done":
|
| 161 |
+
self.dones.append(e)
|
| 162 |
+
last = e
|
| 163 |
+
elif e["ev"] == "http" and last is not None and "think_s" not in last:
|
| 164 |
+
ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \
|
| 165 |
+
(last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe"))
|
| 166 |
+
if ok:
|
| 167 |
+
last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s")
|
| 168 |
+
self.manifest = manifest or {}
|
| 169 |
+
self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {}
|
| 170 |
+
p = os.path.join(self.run_dir, "harness.json")
|
| 171 |
+
self.harness = json.load(open(p)) if os.path.exists(p) else {}
|
| 172 |
+
self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl"))
|
| 173 |
+
self._narration()
|
| 174 |
+
|
| 175 |
+
# ---------------------------------------------------------------- agent narration
|
| 176 |
+
def _narration(self):
|
| 177 |
+
"""notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one;
|
| 178 |
+
finish_notes[attempt] likewise for the agent's finish call; final_report = its last message."""
|
| 179 |
+
self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", []
|
| 180 |
+
buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
|
| 181 |
+
attempt = 1
|
| 182 |
+
|
| 183 |
+
def take():
|
| 184 |
+
nonlocal buf
|
| 185 |
+
out = {k: v for k, v in buf.items() if v}
|
| 186 |
+
buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
|
| 187 |
+
return out
|
| 188 |
+
|
| 189 |
+
last_msg = ""
|
| 190 |
+
for t in self.traj:
|
| 191 |
+
if t.get("kind") == "header":
|
| 192 |
+
self.headers.append(t.get("agent") or {})
|
| 193 |
+
continue
|
| 194 |
+
if t.get("kind") != "step":
|
| 195 |
+
continue
|
| 196 |
+
if (t.get("message") or "").strip():
|
| 197 |
+
buf["messages"].append(t["message"].strip())
|
| 198 |
+
last_msg = t["message"].strip()
|
| 199 |
+
if (t.get("reasoning_content") or "").strip():
|
| 200 |
+
buf["reasoning"].append(t["reasoning_content"].strip())
|
| 201 |
+
res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])}
|
| 202 |
+
for c in t.get("tool_calls") or []:
|
| 203 |
+
fn, args = c.get("function_name"), c.get("arguments") or {}
|
| 204 |
+
if fn == "shell":
|
| 205 |
+
buf["shell"].append(str(args.get("command", ""))[:2000])
|
| 206 |
+
elif fn == "view_images":
|
| 207 |
+
buf["viewed"].extend(args.get("paths") or [])
|
| 208 |
+
elif fn == "robot":
|
| 209 |
+
cmd = str(args.get("command", "")).strip()
|
| 210 |
+
r = res.get(c.get("tool_call_id")) or {}
|
| 211 |
+
try:
|
| 212 |
+
rep = json.loads(r.get("content") or "{}")
|
| 213 |
+
except ValueError:
|
| 214 |
+
rep = {}
|
| 215 |
+
word = cmd.split()[0] if cmd else ""
|
| 216 |
+
m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", "")))
|
| 217 |
+
if word in ("move_eef", "observe") and m:
|
| 218 |
+
a, s = int(m.group(1)), int(m.group(2))
|
| 219 |
+
n = take()
|
| 220 |
+
n["command"] = cmd
|
| 221 |
+
self.notes[(a, s)] = n
|
| 222 |
+
attempt = a
|
| 223 |
+
elif word in ("finish", "done"):
|
| 224 |
+
n = take()
|
| 225 |
+
n["command"] = cmd
|
| 226 |
+
n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)}
|
| 227 |
+
self.finish_notes.setdefault(attempt, n)
|
| 228 |
+
if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"):
|
| 229 |
+
attempt += 1
|
| 230 |
+
# status / help / errors: their narration stays in the buffer for the next command
|
| 231 |
+
self.final_report = last_msg
|
| 232 |
+
|
| 233 |
+
# ---------------------------------------------------------------- run-level labels
|
| 234 |
+
def attempts(self):
|
| 235 |
+
out = []
|
| 236 |
+
for e in self.dones:
|
| 237 |
+
o = e.get("outcome") or {}
|
| 238 |
+
if isinstance(o, str):
|
| 239 |
+
try:
|
| 240 |
+
o = ast.literal_eval(o)
|
| 241 |
+
except (ValueError, SyntaxError):
|
| 242 |
+
o = {}
|
| 243 |
+
out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o,
|
| 244 |
+
reason=e.get("reason") or ""))
|
| 245 |
+
return sorted(out, key=lambda x: x["attempt"])
|
| 246 |
+
|
| 247 |
+
def condition(self):
|
| 248 |
+
s, en = self.start, self.entry
|
| 249 |
+
mem = s.get("memory", en.get("mem"))
|
| 250 |
+
chain = en.get("chain")
|
| 251 |
+
if mem == "full":
|
| 252 |
+
cond = "with_history"
|
| 253 |
+
elif chain:
|
| 254 |
+
cond = "memory_free_retry"
|
| 255 |
+
else:
|
| 256 |
+
cond = "independent_single_attempt"
|
| 257 |
+
return cond, chain
|
| 258 |
+
|
| 259 |
+
def outcome_class(self):
|
| 260 |
+
"""CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None."""
|
| 261 |
+
att = self.attempts()
|
| 262 |
+
if not att or self.start.get("memory") != "full":
|
| 263 |
+
return None, "".join("S" if a["success"] else "F" for a in att)
|
| 264 |
+
hist = "".join("S" if a["success"] else "F" for a in att)
|
| 265 |
+
if att[0]["success"]:
|
| 266 |
+
ev = error_event(att[0]["outcome"])
|
| 267 |
+
cls = "S?" if ev is None else ("IR" if ev else "CS")
|
| 268 |
+
else:
|
| 269 |
+
cls = "XR" if any(a["success"] for a in att) else "F"
|
| 270 |
+
return cls, hist
|
| 271 |
+
|
| 272 |
+
def agent_info(self):
|
| 273 |
+
h, en = self.harness, self.entry
|
| 274 |
+
hdr = self.headers[0] if self.headers else {}
|
| 275 |
+
return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"),
|
| 276 |
+
harness_version=h.get("version") or hdr.get("version"),
|
| 277 |
+
harness_binary_sha256=(h.get("binary") or {}).get("sha256"),
|
| 278 |
+
model=h.get("model") or en.get("model") or hdr.get("model_name"),
|
| 279 |
+
effort=h.get("effort") or en.get("effort") or hdr.get("effort"),
|
| 280 |
+
provider=h.get("provider") or en.get("provider"),
|
| 281 |
+
codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"),
|
| 282 |
+
jail=en.get("jail"))
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
# ====================================================================================================== recording
|
| 286 |
+
|
| 287 |
+
class EpisodeSink:
|
| 288 |
+
"""Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed."""
|
| 289 |
+
|
| 290 |
+
def __init__(self, path):
|
| 291 |
+
self.path = path
|
| 292 |
+
os.makedirs(path, exist_ok=True)
|
| 293 |
+
self.w = None
|
| 294 |
+
self.num = defaultdict(list)
|
| 295 |
+
self.n = 0
|
| 296 |
+
|
| 297 |
+
def add(self, st, imgs):
|
| 298 |
+
import imageio
|
| 299 |
+
if self.w is None:
|
| 300 |
+
self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb",
|
| 301 |
+
pixelformat="rgb24", macro_block_size=1,
|
| 302 |
+
ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error")
|
| 303 |
+
for k in ("agentview", "wrist")]
|
| 304 |
+
for w, im in zip(self.w, imgs):
|
| 305 |
+
w.append_data(im)
|
| 306 |
+
for k, v in st.items():
|
| 307 |
+
self.num[k].append(v)
|
| 308 |
+
self.n += 1
|
| 309 |
+
|
| 310 |
+
def close(self, final_state, final_imgs):
|
| 311 |
+
from PIL import Image
|
| 312 |
+
if self.w is not None:
|
| 313 |
+
for w in self.w:
|
| 314 |
+
w.close()
|
| 315 |
+
arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"}
|
| 316 |
+
np.savez(os.path.join(self.path, "frames.npz"), **arr)
|
| 317 |
+
if self.num.get("sim_state"):
|
| 318 |
+
np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64))
|
| 319 |
+
np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()})
|
| 320 |
+
for k, im in zip(("agentview", "wrist"), final_imgs):
|
| 321 |
+
Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png"))
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
class Recorder:
|
| 325 |
+
"""Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink."""
|
| 326 |
+
|
| 327 |
+
def __init__(self, rp, res):
|
| 328 |
+
self.rp, self.res = rp, int(res)
|
| 329 |
+
self.active = False
|
| 330 |
+
self.sink = None
|
| 331 |
+
self.cur = dict(attempt=1, command=-1, phase=PHASES["move"])
|
| 332 |
+
env = rp.task.env
|
| 333 |
+
self.env, self.rob = env, env.robots[0]
|
| 334 |
+
self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist"))
|
| 335 |
+
orig = env.step
|
| 336 |
+
|
| 337 |
+
def step(a):
|
| 338 |
+
if self.active and self.sink is not None:
|
| 339 |
+
self.capture(np.asarray(a, np.float64))
|
| 340 |
+
out = orig(a)
|
| 341 |
+
if self.active and self.sink is not None:
|
| 342 |
+
self.rp.poll_events(self.sink.n - 1)
|
| 343 |
+
return out
|
| 344 |
+
|
| 345 |
+
env.step = step
|
| 346 |
+
|
| 347 |
+
@property
|
| 348 |
+
def n(self):
|
| 349 |
+
return self.sink.n if self.sink is not None else 0
|
| 350 |
+
|
| 351 |
+
def state(self):
|
| 352 |
+
import robosuite.utils.transform_utils as T
|
| 353 |
+
env, rob = self.env, self.rob
|
| 354 |
+
d = env.sim.data
|
| 355 |
+
eef = np.array(d.site_xpos[rob.eef_site_id], np.float64)
|
| 356 |
+
q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw")
|
| 357 |
+
gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64)
|
| 358 |
+
try:
|
| 359 |
+
flat = np.asarray(env.sim.get_state().flatten(), np.float64)
|
| 360 |
+
except Exception:
|
| 361 |
+
flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64)
|
| 362 |
+
sk = self.rp.task.sk
|
| 363 |
+
return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64),
|
| 364 |
+
gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64),
|
| 365 |
+
joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64),
|
| 366 |
+
gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64),
|
| 367 |
+
eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)),
|
| 368 |
+
sim_time=np.float64(d.time), sim_state=flat)
|
| 369 |
+
|
| 370 |
+
def images(self):
|
| 371 |
+
return [envs.render(self.env, c, self.res) for c in self.cams]
|
| 372 |
+
|
| 373 |
+
def capture(self, a):
|
| 374 |
+
st = self.state()
|
| 375 |
+
st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]),
|
| 376 |
+
phase=np.int64(self.cur["phase"]))
|
| 377 |
+
self.sink.add(st, self.images())
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
class RunReplay:
|
| 381 |
+
def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None):
|
| 382 |
+
self.run_dir = os.path.abspath(run_dir.rstrip("/"))
|
| 383 |
+
self.run_name = os.path.basename(self.run_dir)
|
| 384 |
+
self.log = RunLog(self.run_dir, manifest)
|
| 385 |
+
self.ev = self.log.ev
|
| 386 |
+
self.start = self.log.start
|
| 387 |
+
cp = os.path.join(self.run_dir, "contract.json")
|
| 388 |
+
self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {}
|
| 389 |
+
spec = self.contract.get("image_spec") or {}
|
| 390 |
+
self.image_res = int(spec.get("width", 512))
|
| 391 |
+
self.code_diff = check_code(self.run_dir)
|
| 392 |
+
s = self.start
|
| 393 |
+
self.task = TASKS[s["task"]](cam_res=self.image_res)
|
| 394 |
+
inst = self.task.sample_instance(s["seed"])
|
| 395 |
+
logged = s.get("inst") or {}
|
| 396 |
+
sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")})
|
| 397 |
+
self.inst_diff = diff_json(sampled, logged, "inst")
|
| 398 |
+
if s.get("arm", "none") not in (None, "none") or logged.get("nominal"):
|
| 399 |
+
inst.update(logged) # controlled arms / nominal: the server overrode these instance fields
|
| 400 |
+
self.inst_diff = []
|
| 401 |
+
self.inst = inst
|
| 402 |
+
self.protocol = getattr(self.task, "protocol", "cross")
|
| 403 |
+
self.k = int(s.get("k") or self.task.max_attempts)
|
| 404 |
+
self.attempt = 1
|
| 405 |
+
self.mismatch = [] # (where, what, logged, replayed)
|
| 406 |
+
self.n_checked = 0
|
| 407 |
+
self.max_dev_m = 0.0
|
| 408 |
+
self.unfinished = None
|
| 409 |
+
self.rec = Recorder(self, res) if record else None
|
| 410 |
+
self.res = int(res)
|
| 411 |
+
self.out_root = out_root
|
| 412 |
+
self.n_mon = 0
|
| 413 |
+
self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0
|
| 414 |
+
self.episodes = [] # summaries of the written episodes
|
| 415 |
+
self.task.reset_instance(self.inst)
|
| 416 |
+
self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
|
| 417 |
+
sim = self.task.env.sim
|
| 418 |
+
bid = sim.model.body_name2id("robot0_base")
|
| 419 |
+
self.base_off = np.array(sim.data.body_xpos[bid], float).copy()
|
| 420 |
+
if self.rec:
|
| 421 |
+
self._open_episode()
|
| 422 |
+
|
| 423 |
+
# ------------------------------------------------------------------ episodes
|
| 424 |
+
def _ep_dir(self):
|
| 425 |
+
return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}")
|
| 426 |
+
|
| 427 |
+
def _open_episode(self):
|
| 428 |
+
self.rec.sink = EpisodeSink(self._ep_dir())
|
| 429 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
|
| 430 |
+
self.rec.active = True
|
| 431 |
+
self.events, self.spans, self.ep_attempts = [], [], []
|
| 432 |
+
self.ep_initial = self.rec.state() # state right after the reset (before frame 0)
|
| 433 |
+
|
| 434 |
+
def close_episode(self):
|
| 435 |
+
if not self.rec:
|
| 436 |
+
self.ep_attempts = []
|
| 437 |
+
return
|
| 438 |
+
sink = self.rec.sink
|
| 439 |
+
st = self.rec.state()
|
| 440 |
+
imgs = self.rec.images()
|
| 441 |
+
st.pop("sim_state", None)
|
| 442 |
+
sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs)
|
| 443 |
+
ann = build_annotation(self, sink)
|
| 444 |
+
with open(os.path.join(sink.path, "annotation.json"), "w") as f:
|
| 445 |
+
json.dump(ann, f, indent=1, default=_json_default)
|
| 446 |
+
self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n,
|
| 447 |
+
attempts=[a["attempt"] for a in self.ep_attempts]))
|
| 448 |
+
self.rec.active = False
|
| 449 |
+
self.rec.sink = None
|
| 450 |
+
self.ep_index += 1
|
| 451 |
+
|
| 452 |
+
# ------------------------------------------------------------------ monitor events (task-side error events)
|
| 453 |
+
def poll_events(self, frame):
|
| 454 |
+
mon = getattr(self.task, "mon", None)
|
| 455 |
+
evs = mon.get("events") if isinstance(mon, dict) else None
|
| 456 |
+
if not isinstance(evs, list):
|
| 457 |
+
return
|
| 458 |
+
if len(evs) < self.n_mon: # monitor was rebuilt
|
| 459 |
+
self.n_mon = 0
|
| 460 |
+
for e in evs[self.n_mon:]:
|
| 461 |
+
self.events.append(dict(frame=int(frame), attempt=self.attempt,
|
| 462 |
+
event=norm_json(e) if isinstance(e, dict) else str(e)))
|
| 463 |
+
self.n_mon = len(evs)
|
| 464 |
+
|
| 465 |
+
# ------------------------------------------------------------------ state as the server reports it
|
| 466 |
+
def proprio_la(self):
|
| 467 |
+
p = self.ex.proprio()
|
| 468 |
+
pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off]
|
| 469 |
+
return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"])
|
| 470 |
+
|
| 471 |
+
def compare(self, where, rep_logged, rep):
|
| 472 |
+
self.n_checked += 1
|
| 473 |
+
for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"):
|
| 474 |
+
if k not in rep_logged or k not in rep:
|
| 475 |
+
continue
|
| 476 |
+
a, b = rep_logged[k], rep[k]
|
| 477 |
+
if k == "eef_pos":
|
| 478 |
+
dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float))))
|
| 479 |
+
self.max_dev_m = max(self.max_dev_m, dev)
|
| 480 |
+
if dev > 1.5e-4:
|
| 481 |
+
self.mismatch.append((where, k, a, b))
|
| 482 |
+
elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4):
|
| 483 |
+
self.mismatch.append((where, k, a, b))
|
| 484 |
+
if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)):
|
| 485 |
+
self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok")))
|
| 486 |
+
|
| 487 |
+
def _span(self, e, f0, kind):
|
| 488 |
+
if self.rec:
|
| 489 |
+
self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0,
|
| 490 |
+
frame_end=self.rec.n))
|
| 491 |
+
|
| 492 |
+
# ------------------------------------------------------------------ commands (robot_server._handle_v2)
|
| 493 |
+
def move_eef(self, e):
|
| 494 |
+
args = e.get("args") or {}
|
| 495 |
+
where = f"a{e['attempt']}s{e['step']}"
|
| 496 |
+
logged = e.get("report") or {}
|
| 497 |
+
f0 = self.rec.n if self.rec else 0
|
| 498 |
+
p = self.ex.proprio()
|
| 499 |
+
if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}:
|
| 500 |
+
self._span(e, f0, "error")
|
| 501 |
+
return self.compare(where, logged, dict(ok=False))
|
| 502 |
+
off = self.base_off
|
| 503 |
+
try:
|
| 504 |
+
cur = np.asarray(p["eef_pos"], float) - off
|
| 505 |
+
tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
|
| 506 |
+
yaw = float(args.get("yaw", p["eef_yaw_deg"]))
|
| 507 |
+
speed = None if args.get("speed") in (None, "") else float(args["speed"])
|
| 508 |
+
except (TypeError, ValueError):
|
| 509 |
+
self._span(e, f0, "error")
|
| 510 |
+
return self.compare(where, logged, dict(ok=False))
|
| 511 |
+
grip = args.get("gripper")
|
| 512 |
+
if grip not in (None, "open", "close"):
|
| 513 |
+
self._span(e, f0, "error")
|
| 514 |
+
return self.compare(where, logged, dict(ok=False))
|
| 515 |
+
moving = any(k in args for k in ("x", "y", "z", "yaw"))
|
| 516 |
+
tgt_w = np.asarray(tgt) + off
|
| 517 |
+
if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)):
|
| 518 |
+
self._span(e, f0, "rejected")
|
| 519 |
+
return self.compare(where, logged, dict(ok=False, **self.proprio_la()))
|
| 520 |
+
raw = {}
|
| 521 |
+
if self.rec:
|
| 522 |
+
self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"])
|
| 523 |
+
if moving:
|
| 524 |
+
mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw)
|
| 525 |
+
if speed is not None:
|
| 526 |
+
mv["speed"] = speed
|
| 527 |
+
raw.update(self.ex.call("move_to", mv).report)
|
| 528 |
+
if grip is not None:
|
| 529 |
+
if self.rec:
|
| 530 |
+
self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"])
|
| 531 |
+
raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report)
|
| 532 |
+
rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la())
|
| 533 |
+
self.compare(where, logged, rep)
|
| 534 |
+
lr = e.get("raw") or {}
|
| 535 |
+
for k in ("holding_object", "touched_object"):
|
| 536 |
+
if k in lr and k in raw and bool(lr[k]) != bool(raw[k]):
|
| 537 |
+
self.mismatch.append((where, "raw." + k, lr[k], raw[k]))
|
| 538 |
+
self._span(e, f0, "move_eef")
|
| 539 |
+
|
| 540 |
+
def observe(self, e):
|
| 541 |
+
f0 = self.rec.n if self.rec else 0
|
| 542 |
+
self._span(e, f0, "observe")
|
| 543 |
+
|
| 544 |
+
def done(self, e):
|
| 545 |
+
f0 = self.rec.n if self.rec else 0
|
| 546 |
+
if self.rec:
|
| 547 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"])
|
| 548 |
+
out = self.task.outcome(self.inst)
|
| 549 |
+
succ = bool(out["success"])
|
| 550 |
+
where = f"a{e['attempt']}done"
|
| 551 |
+
if succ != bool(e.get("success") in (True, "True")):
|
| 552 |
+
self.mismatch.append((where, "success", e.get("success"), succ))
|
| 553 |
+
lo = e.get("outcome") or {}
|
| 554 |
+
ro = norm_json({k: v for k, v in out.items() if k != "feedback"})
|
| 555 |
+
if isinstance(lo, dict):
|
| 556 |
+
for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8):
|
| 557 |
+
self.mismatch.append((where,) + d)
|
| 558 |
+
info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""),
|
| 559 |
+
feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")),
|
| 560 |
+
think_s=e.get("think_s"))
|
| 561 |
+
try:
|
| 562 |
+
info["feedback_f2"] = self.task.feedback(self.inst, out, "F2")
|
| 563 |
+
except Exception as ex_:
|
| 564 |
+
info["feedback_f2"] = f"<unavailable: {type(ex_).__name__}>"
|
| 565 |
+
if self.rec:
|
| 566 |
+
info["judge_frames"] = [f0, self.rec.n]
|
| 567 |
+
self.ep_attempts.append(info)
|
| 568 |
+
last = self.attempt >= self.k or succ or bool(out.get("terminal"))
|
| 569 |
+
if self.protocol == "cross" or last:
|
| 570 |
+
self.close_episode()
|
| 571 |
+
if last:
|
| 572 |
+
return True
|
| 573 |
+
self.attempt += 1
|
| 574 |
+
if self.protocol == "cross":
|
| 575 |
+
self.task.reset_instance(self.inst)
|
| 576 |
+
self.n_mon = 0
|
| 577 |
+
if self.rec:
|
| 578 |
+
self._open_episode()
|
| 579 |
+
elif self.rec:
|
| 580 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
|
| 581 |
+
self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
|
| 582 |
+
return False
|
| 583 |
+
|
| 584 |
+
def run(self):
|
| 585 |
+
t0 = time.time()
|
| 586 |
+
finished = False
|
| 587 |
+
for e in self.ev:
|
| 588 |
+
if e["ev"] == "call":
|
| 589 |
+
if e.get("cmd") == "move_eef":
|
| 590 |
+
self.move_eef(e)
|
| 591 |
+
elif e.get("cmd") == "observe":
|
| 592 |
+
self.observe(e)
|
| 593 |
+
else:
|
| 594 |
+
self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None))
|
| 595 |
+
elif e["ev"] == "done":
|
| 596 |
+
finished = self.done(e)
|
| 597 |
+
if finished:
|
| 598 |
+
break
|
| 599 |
+
self.unfinished = not finished
|
| 600 |
+
if not finished and self.rec and self.rec.sink is not None:
|
| 601 |
+
# the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged
|
| 602 |
+
if self.rec.n or self.ep_attempts:
|
| 603 |
+
self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True,
|
| 604 |
+
finish_reason="", feedback_shown="", auto_ended=False))
|
| 605 |
+
self.close_episode()
|
| 606 |
+
else:
|
| 607 |
+
shutil.rmtree(self.rec.sink.path, ignore_errors=True)
|
| 608 |
+
self.rec.sink = None
|
| 609 |
+
self.wall_s = time.time() - t0
|
| 610 |
+
return self
|
| 611 |
+
|
| 612 |
+
def summary(self):
|
| 613 |
+
return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"],
|
| 614 |
+
protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff),
|
| 615 |
+
n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6),
|
| 616 |
+
unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1),
|
| 617 |
+
first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]])
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
# ====================================================================================================== annotation
|
| 621 |
+
|
| 622 |
+
def task_info(task, inst):
|
| 623 |
+
cls = type(task)
|
| 624 |
+
return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable",
|
| 625 |
+
category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"),
|
| 626 |
+
max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)),
|
| 627 |
+
instruction=cls.instruction)
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
def build_annotation(rp, sink):
|
| 631 |
+
"""Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2
|
| 632 |
+
failure description), run-level outcome class, every robot command with its frame span and the agent's narration,
|
| 633 |
+
task-side error events with frame indices."""
|
| 634 |
+
log = rp.log
|
| 635 |
+
s = rp.start
|
| 636 |
+
cond, chain = log.condition()
|
| 637 |
+
cls, hist = log.outcome_class()
|
| 638 |
+
att_all = log.attempts()
|
| 639 |
+
attempts = []
|
| 640 |
+
for a in rp.ep_attempts:
|
| 641 |
+
a = dict(a)
|
| 642 |
+
n = a["attempt"]
|
| 643 |
+
later = [x for x in att_all if x["attempt"] > n]
|
| 644 |
+
a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later))
|
| 645 |
+
a["is_last_attempt_of_run"] = not later
|
| 646 |
+
fn = log.finish_notes.get(n)
|
| 647 |
+
if fn:
|
| 648 |
+
a["agent_finish"] = fn
|
| 649 |
+
a["error_event_in_attempt"] = error_event(a.get("outcome"))
|
| 650 |
+
attempts.append(a)
|
| 651 |
+
# post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command)
|
| 652 |
+
for a in attempts:
|
| 653 |
+
nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1])
|
| 654 |
+
if a.get("success") is False and nxt:
|
| 655 |
+
note = log.notes[nxt[0]]
|
| 656 |
+
a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note}
|
| 657 |
+
commands = []
|
| 658 |
+
for sp in rp.spans:
|
| 659 |
+
e = log.calls.get((sp["attempt"], sp["step"])) or {}
|
| 660 |
+
rep = e.get("report") or {}
|
| 661 |
+
c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"],
|
| 662 |
+
frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]),
|
| 663 |
+
args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"),
|
| 664 |
+
stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"),
|
| 665 |
+
gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"),
|
| 666 |
+
touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"),
|
| 667 |
+
agent_obs_images=rep.get("images"))
|
| 668 |
+
note = log.notes.get((sp["attempt"], sp["step"]))
|
| 669 |
+
if note:
|
| 670 |
+
c["agent_note"] = {k: v for k, v in note.items() if k != "command"}
|
| 671 |
+
commands.append(c)
|
| 672 |
+
t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x]
|
| 673 |
+
return dict(
|
| 674 |
+
schema=SCHEMA,
|
| 675 |
+
source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts],
|
| 676 |
+
episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain,
|
| 677 |
+
memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None),
|
| 678 |
+
feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"),
|
| 679 |
+
k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"),
|
| 680 |
+
contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256")
|
| 681 |
+
if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)),
|
| 682 |
+
agent=log.agent_info(),
|
| 683 |
+
task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"),
|
| 684 |
+
instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}),
|
| 685 |
+
run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all),
|
| 686 |
+
run_success=any(x["success"] for x in att_all) if att_all else None,
|
| 687 |
+
agent_final_report=log.final_report[:6000] or None,
|
| 688 |
+
mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)),
|
| 689 |
+
attempts=attempts,
|
| 690 |
+
commands=commands,
|
| 691 |
+
task_events=rp.events,
|
| 692 |
+
frames=dict(n=sink.n, fps=FPS, image_res=rp.res,
|
| 693 |
+
phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"],
|
| 694 |
+
joint_pos=rp.ep_initial["joint_pos"],
|
| 695 |
+
gripper_qpos=rp.ep_initial["gripper_qpos"])),
|
| 696 |
+
)
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
# ====================================================================================================== CLI
|
| 700 |
+
|
| 701 |
+
def load_manifest(run_dir):
|
| 702 |
+
p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json")
|
| 703 |
+
return json.load(open(p)) if os.path.exists(p) else {}
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
def main():
|
| 707 |
+
ap = argparse.ArgumentParser()
|
| 708 |
+
ap.add_argument("mode", choices=["check", "record"])
|
| 709 |
+
ap.add_argument("runs", nargs="+")
|
| 710 |
+
ap.add_argument("--json", default="")
|
| 711 |
+
ap.add_argument("--out", default="")
|
| 712 |
+
ap.add_argument("--res", type=int, default=256)
|
| 713 |
+
ap.add_argument("--force", action="store_true", help="record again even if replay.json exists")
|
| 714 |
+
a = ap.parse_args()
|
| 715 |
+
rows = []
|
| 716 |
+
for r in a.runs:
|
| 717 |
+
r = r.rstrip("/")
|
| 718 |
+
try:
|
| 719 |
+
if a.mode == "check":
|
| 720 |
+
s = RunReplay(r, manifest=load_manifest(r)).run().summary()
|
| 721 |
+
else:
|
| 722 |
+
batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r)
|
| 723 |
+
rd = os.path.join(a.out, batch, name)
|
| 724 |
+
if os.path.exists(os.path.join(rd, "replay.json")) and not a.force:
|
| 725 |
+
print(json.dumps(dict(run=name, skipped="exists")), flush=True)
|
| 726 |
+
continue
|
| 727 |
+
shutil.rmtree(rd, ignore_errors=True)
|
| 728 |
+
rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run()
|
| 729 |
+
s = rp.summary()
|
| 730 |
+
s["episodes"] = rp.episodes
|
| 731 |
+
with open(os.path.join(rd, "replay.json"), "w") as f:
|
| 732 |
+
json.dump(s, f, indent=1)
|
| 733 |
+
except Exception:
|
| 734 |
+
import traceback
|
| 735 |
+
s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:])
|
| 736 |
+
rows.append(s)
|
| 737 |
+
print(json.dumps(s), flush=True)
|
| 738 |
+
if a.json:
|
| 739 |
+
with open(a.json, "w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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars.
|
| 2 |
+
|
| 3 |
+
Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding
|
| 4 |
+
can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan):
|
| 5 |
+
|
| 6 |
+
python scripts/lerobot_export.py plan --raw <raw_root>[,<raw_root2>] --runs-root <lffbench>/runs/api \
|
| 7 |
+
--paper <paper/latex> --task-set <lffbench>/sets/main_v2_1inst.txt --work <work_dir> [--batches ...] [--limit N]
|
| 8 |
+
python scripts/lerobot_export.py shard --work <work_dir> --shard i --nshards N
|
| 9 |
+
python scripts/lerobot_export.py merge --work <work_dir> --nshards N --out <dataset_root>
|
| 10 |
+
|
| 11 |
+
Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0
|
| 12 |
+
mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped.
|
| 13 |
+
|
| 14 |
+
LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t):
|
| 15 |
+
observation.images.image agentview RGB 256x256 (upright; LIBERO naming)
|
| 16 |
+
observation.images.wrist_image wrist (eye-in-hand) RGB 256x256
|
| 17 |
+
observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout)
|
| 18 |
+
observation.joint_pos / joint_vel 7 arm joints (rad, rad/s)
|
| 19 |
+
observation.eef_quat 4: xyzw; observation.gripper_width 1 (m)
|
| 20 |
+
action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad),
|
| 21 |
+
gripper (-1 open, +1 close)
|
| 22 |
+
annotation.attempt_index attempt (1-based) the frame belongs to
|
| 23 |
+
annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`)
|
| 24 |
+
annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action)
|
| 25 |
+
annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt
|
| 26 |
+
annotation.task_event number of task-monitor events (error / progress events) registered at this step
|
| 27 |
+
Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table),
|
| 28 |
+
runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state
|
| 29 |
+
per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/.
|
| 30 |
+
"""
|
| 31 |
+
import argparse
|
| 32 |
+
import glob
|
| 33 |
+
import json
|
| 34 |
+
import os
|
| 35 |
+
import re
|
| 36 |
+
import shutil
|
| 37 |
+
import time
|
| 38 |
+
|
| 39 |
+
import numpy as np
|
| 40 |
+
|
| 41 |
+
FPS = 20
|
| 42 |
+
RES = 256
|
| 43 |
+
BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke",
|
| 44 |
+
"cc_smoke", "cc_opus_smoke"]
|
| 45 |
+
BATCH_NOTES = {
|
| 46 |
+
"cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog",
|
| 47 |
+
"cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267",
|
| 48 |
+
"cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299",
|
| 49 |
+
"cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances",
|
| 50 |
+
"cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)",
|
| 51 |
+
"cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the "
|
| 52 |
+
"with-history continuation of failed runs is incomplete",
|
| 53 |
+
"cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early",
|
| 54 |
+
"cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt",
|
| 55 |
+
"cc_opus_smoke": "smoke test: single attempt",
|
| 56 |
+
}
|
| 57 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 58 |
+
CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)",
|
| 59 |
+
"L2": "disturbed state to restore (incl. damage the agent causes)",
|
| 60 |
+
"L3": "infeasible manipulation strategy (grasp / contact / tool must change)",
|
| 61 |
+
"L4": "misjudged geometry (size, shape, fit, hidden structure)",
|
| 62 |
+
"L5": "misjudged physics (mass distribution, friction, dynamics)"}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def features():
|
| 66 |
+
vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]}
|
| 67 |
+
f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names}
|
| 68 |
+
i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None}
|
| 69 |
+
return {
|
| 70 |
+
"observation.images.image": vid(),
|
| 71 |
+
"observation.images.wrist_image": vid(),
|
| 72 |
+
"observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z",
|
| 73 |
+
"finger_qpos_left", "finger_qpos_right"]),
|
| 74 |
+
"observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 75 |
+
"observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 76 |
+
"observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]),
|
| 77 |
+
"observation.gripper_width": f32(1, ["width_m"]),
|
| 78 |
+
"action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y",
|
| 79 |
+
"eef_delta_rot_aa_z", "gripper_close"]),
|
| 80 |
+
"annotation.attempt_index": i64(),
|
| 81 |
+
"annotation.command_index": i64(),
|
| 82 |
+
"annotation.phase": i64(),
|
| 83 |
+
"annotation.attempt_success": i64(),
|
| 84 |
+
"annotation.task_event": i64(),
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ------------------------------------------------------------------------------------------------ paper metadata
|
| 89 |
+
|
| 90 |
+
def _clean_tex(s):
|
| 91 |
+
s = re.sub(r"%.*", "", s)
|
| 92 |
+
for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"),
|
| 93 |
+
(r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"),
|
| 94 |
+
(r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"),
|
| 95 |
+
(r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"),
|
| 96 |
+
(r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]:
|
| 97 |
+
s = re.sub(a, b, s)
|
| 98 |
+
s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s)
|
| 99 |
+
s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s)
|
| 100 |
+
for _ in range(3):
|
| 101 |
+
s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s)
|
| 102 |
+
s = re.sub(r"\$([^$]*)\$", r"\1", s)
|
| 103 |
+
s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ")
|
| 104 |
+
s = re.sub(r"\{([^{}]*)\}", r"\1", s)
|
| 105 |
+
s = re.sub(r"\\[a-zA-Z]+\*?", "", s)
|
| 106 |
+
return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def paper_tasks(paper_dir):
|
| 110 |
+
"""{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the
|
| 111 |
+
paper's task table and task appendix (empty if the paper sources are not there)."""
|
| 112 |
+
out = {}
|
| 113 |
+
if not paper_dir:
|
| 114 |
+
return out
|
| 115 |
+
app = os.path.join(paper_dir, "sections", "appendix_tasks.tex")
|
| 116 |
+
tab = os.path.join(paper_dir, "sections", "tab_tasks.tex")
|
| 117 |
+
if os.path.exists(app):
|
| 118 |
+
txt = open(app).read()
|
| 119 |
+
parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt)
|
| 120 |
+
for i in range(1, len(parts) - 1, 2):
|
| 121 |
+
if parts[i] != "\\paragraph{":
|
| 122 |
+
continue
|
| 123 |
+
body = parts[i + 1]
|
| 124 |
+
m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S)
|
| 125 |
+
if not m:
|
| 126 |
+
continue
|
| 127 |
+
name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip()
|
| 128 |
+
desc = _clean_tex(body[m.end():])
|
| 129 |
+
out[code] = dict(name=name, cause=_clean_tex(cause), description=desc)
|
| 130 |
+
if os.path.exists(tab):
|
| 131 |
+
names = {v["name"].lower(): k for k, v in out.items()}
|
| 132 |
+
for line in open(tab):
|
| 133 |
+
cells = [c.strip() for c in line.split("&")]
|
| 134 |
+
if len(cells) != 6 or not cells[-1].endswith("\\\\"):
|
| 135 |
+
continue
|
| 136 |
+
nm = re.sub(r"\\contscene", "", cells[0]).strip().lower()
|
| 137 |
+
code = names.get(nm)
|
| 138 |
+
if not code:
|
| 139 |
+
continue
|
| 140 |
+
out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]),
|
| 141 |
+
repair_within_attempt=_clean_tex(cells[3]) == "yes",
|
| 142 |
+
oracle_first_attempt_pct=_clean_tex(cells[4]),
|
| 143 |
+
naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip()))
|
| 144 |
+
return out
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
# ------------------------------------------------------------------------------------------------ collection
|
| 148 |
+
|
| 149 |
+
def manifest_status(runs_root, batch, run, cache={}):
|
| 150 |
+
if batch not in cache:
|
| 151 |
+
p = os.path.join(runs_root, batch, "manifest.json")
|
| 152 |
+
cache[batch] = json.load(open(p)) if os.path.exists(p) else {}
|
| 153 |
+
m = cache[batch]
|
| 154 |
+
for r in m.get("runs", []):
|
| 155 |
+
if r.get("run") == run:
|
| 156 |
+
return r.get("status", "?"), r
|
| 157 |
+
for r in m.get("superseded", []):
|
| 158 |
+
if r.get("run") == run:
|
| 159 |
+
return "superseded_" + str(r.get("status", "?")), r
|
| 160 |
+
return "not_in_manifest", {}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def collect(raw_roots, runs_root, batches, task_order):
|
| 164 |
+
"""Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root."""
|
| 165 |
+
eps, rejected, seen = [], [], set()
|
| 166 |
+
for root in raw_roots:
|
| 167 |
+
for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))):
|
| 168 |
+
rep = json.load(open(rj))
|
| 169 |
+
batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"]
|
| 170 |
+
if (batches and batch not in batches) or (batch, run) in seen:
|
| 171 |
+
continue
|
| 172 |
+
seen.add((batch, run))
|
| 173 |
+
ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff")
|
| 174 |
+
status, entry = manifest_status(runs_root, batch, run)
|
| 175 |
+
if not ok:
|
| 176 |
+
never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked")
|
| 177 |
+
rejected.append(dict(run=run, batch=batch, run_status=status,
|
| 178 |
+
reason="run never started (no contract, no robot command)" if never else
|
| 179 |
+
"replay does not reproduce the log (the log has gaps or the replay diverged)",
|
| 180 |
+
detail=rep.get("first_mismatches")))
|
| 181 |
+
continue
|
| 182 |
+
for ep in rep.get("episodes", []):
|
| 183 |
+
d = os.path.join(root, ep["dir"])
|
| 184 |
+
ann = json.load(open(os.path.join(d, "annotation.json")))
|
| 185 |
+
judged = [a for a in ann["attempts"] if a.get("success") is not None]
|
| 186 |
+
if not judged or ep["n_frames"] == 0:
|
| 187 |
+
rejected.append(dict(run=run, batch=batch, episode=ep["dir"],
|
| 188 |
+
reason="no judged attempt" if not judged else "no frames"))
|
| 189 |
+
continue
|
| 190 |
+
ann["source"]["run_status"] = status
|
| 191 |
+
ann["source"]["manifest_id"] = entry.get("id")
|
| 192 |
+
ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"],
|
| 193 |
+
max_eef_dev_m=rep["max_eef_dev_m"])
|
| 194 |
+
key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99),
|
| 195 |
+
{"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2),
|
| 196 |
+
ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"])
|
| 197 |
+
eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann))
|
| 198 |
+
eps.sort(key=lambda x: x["key"])
|
| 199 |
+
return eps, rejected
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# ------------------------------------------------------------------------------------------------ writing
|
| 203 |
+
|
| 204 |
+
def frames_of(path):
|
| 205 |
+
import av
|
| 206 |
+
with av.open(path) as c:
|
| 207 |
+
for fr in c.decode(video=0):
|
| 208 |
+
yield fr.to_ndarray(format="rgb24")
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def flat_row(i, ann, n, idx0):
|
| 212 |
+
s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"]
|
| 213 |
+
att = ann["attempts"]
|
| 214 |
+
a0 = att[0]
|
| 215 |
+
return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n,
|
| 216 |
+
batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"],
|
| 217 |
+
memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"),
|
| 218 |
+
episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att],
|
| 219 |
+
harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"),
|
| 220 |
+
effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"),
|
| 221 |
+
task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"),
|
| 222 |
+
category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"],
|
| 223 |
+
success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att],
|
| 224 |
+
feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att],
|
| 225 |
+
auto_ended=[a.get("auto_ended") for a in att],
|
| 226 |
+
corrected_later_in_run=[a.get("corrected_later_in_run") for a in att],
|
| 227 |
+
error_event_in_attempt=[a.get("error_event_in_attempt") for a in att],
|
| 228 |
+
run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"),
|
| 229 |
+
n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]),
|
| 230 |
+
first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def cmd_plan(a):
|
| 234 |
+
task_order = {}
|
| 235 |
+
if a.task_set and os.path.exists(a.task_set):
|
| 236 |
+
for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")):
|
| 237 |
+
task_order[line.split(":")[0].strip()] = i
|
| 238 |
+
batches = [b for b in a.batches.split(",") if b] if a.batches else None
|
| 239 |
+
eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order)
|
| 240 |
+
if a.limit:
|
| 241 |
+
eps = eps[:a.limit]
|
| 242 |
+
paper = paper_tasks(a.paper)
|
| 243 |
+
idx0 = 0
|
| 244 |
+
for i, e in enumerate(eps):
|
| 245 |
+
ann = e["ann"]
|
| 246 |
+
tname = ann["task"]["name"]
|
| 247 |
+
if tname in paper:
|
| 248 |
+
ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"}
|
| 249 |
+
ann["episode_index"] = i
|
| 250 |
+
ann["dataset_index_range"] = [idx0, idx0 + e["n"]]
|
| 251 |
+
e["index"], e["from"] = i, idx0
|
| 252 |
+
idx0 += e["n"]
|
| 253 |
+
del e["key"]
|
| 254 |
+
os.makedirs(a.work, exist_ok=True)
|
| 255 |
+
with open(os.path.join(a.work, "plan.json"), "w") as f:
|
| 256 |
+
json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f,
|
| 257 |
+
ensure_ascii=False)
|
| 258 |
+
print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def shard_range(n_eps, i, k):
|
| 262 |
+
return (n_eps * i) // k, (n_eps * (i + 1)) // k
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def cmd_shard(a):
|
| 266 |
+
from lerobot.datasets.lerobot_dataset import LeRobotDataset
|
| 267 |
+
t0 = time.time()
|
| 268 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 269 |
+
eps = plan["episodes"]
|
| 270 |
+
lo, hi = shard_range(len(eps), a.shard, a.nshards)
|
| 271 |
+
out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}")
|
| 272 |
+
if os.path.exists(os.path.join(out, "DONE")):
|
| 273 |
+
print(f"shard {a.shard}: done already", flush=True)
|
| 274 |
+
return
|
| 275 |
+
shutil.rmtree(out, ignore_errors=True)
|
| 276 |
+
ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out,
|
| 277 |
+
robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads,
|
| 278 |
+
vcodec=a.vcodec)
|
| 279 |
+
nfr = 0
|
| 280 |
+
for e in eps[lo:hi]:
|
| 281 |
+
d, ann, n = e["dir"], e["ann"], e["n"]
|
| 282 |
+
fr = np.load(os.path.join(d, "frames.npz"))
|
| 283 |
+
assert len(fr["action"]) == n, d
|
| 284 |
+
succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]}
|
| 285 |
+
evc = np.zeros(n, np.int64)
|
| 286 |
+
for ev in ann["task_events"]:
|
| 287 |
+
if 0 <= ev["frame"] < n:
|
| 288 |
+
evc[ev["frame"]] += 1
|
| 289 |
+
state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32)
|
| 290 |
+
instr = ann["task"]["instruction"]
|
| 291 |
+
k = 0
|
| 292 |
+
for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))):
|
| 293 |
+
if k >= n:
|
| 294 |
+
break
|
| 295 |
+
ds.add_frame({
|
| 296 |
+
"observation.images.image": img, "observation.images.wrist_image": wr,
|
| 297 |
+
"observation.state": state[k],
|
| 298 |
+
"observation.joint_pos": fr["joint_pos"][k].astype(np.float32),
|
| 299 |
+
"observation.joint_vel": fr["joint_vel"][k].astype(np.float32),
|
| 300 |
+
"observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32),
|
| 301 |
+
"observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32),
|
| 302 |
+
"action": fr["action"][k].astype(np.float32),
|
| 303 |
+
"annotation.attempt_index": np.array([fr["attempt"][k]], np.int64),
|
| 304 |
+
"annotation.command_index": np.array([fr["command"][k]], np.int64),
|
| 305 |
+
"annotation.phase": np.array([fr["phase"][k]], np.int64),
|
| 306 |
+
"annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64),
|
| 307 |
+
"annotation.task_event": np.array([evc[k]], np.int64),
|
| 308 |
+
"task": instr,
|
| 309 |
+
})
|
| 310 |
+
k += 1
|
| 311 |
+
if k != n:
|
| 312 |
+
raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames")
|
| 313 |
+
ds.save_episode()
|
| 314 |
+
nfr += n
|
| 315 |
+
ds.finalize()
|
| 316 |
+
shutil.rmtree(os.path.join(out, "images"), ignore_errors=True)
|
| 317 |
+
open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n")
|
| 318 |
+
print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def cmd_merge(a):
|
| 322 |
+
from pathlib import Path
|
| 323 |
+
from lerobot.datasets.aggregate import aggregate_datasets
|
| 324 |
+
t0 = time.time()
|
| 325 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 326 |
+
eps = plan["episodes"]
|
| 327 |
+
roots, ids = [], []
|
| 328 |
+
for i in range(a.nshards):
|
| 329 |
+
lo, hi = shard_range(len(eps), i, a.nshards)
|
| 330 |
+
if hi <= lo:
|
| 331 |
+
continue
|
| 332 |
+
r = os.path.join(a.work, "shards", f"shard_{i:03d}")
|
| 333 |
+
if not os.path.exists(os.path.join(r, "DONE")):
|
| 334 |
+
raise SystemExit(f"shard {i} is not done")
|
| 335 |
+
roots.append(Path(r))
|
| 336 |
+
ids.append(f"{plan['repo_id']}-shard{i:03d}")
|
| 337 |
+
if os.path.exists(a.out):
|
| 338 |
+
raise SystemExit(f"{a.out} exists; refusing to overwrite")
|
| 339 |
+
aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out))
|
| 340 |
+
print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True)
|
| 341 |
+
write_sidecars(a, plan)
|
| 342 |
+
print(f"merge done in {time.time() - t0:.0f}s", flush=True)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def write_sidecars(a, plan):
|
| 346 |
+
eps, paper = plan["episodes"], plan["paper"]
|
| 347 |
+
lff = os.path.join(a.out, "lff")
|
| 348 |
+
for sub in ("annotations", "sim_state", "final", "code"):
|
| 349 |
+
os.makedirs(os.path.join(lff, sub), exist_ok=True)
|
| 350 |
+
rows, runs, tasks = [], {}, {}
|
| 351 |
+
for e in eps:
|
| 352 |
+
i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"]
|
| 353 |
+
name = f"episode_{i:06d}"
|
| 354 |
+
if os.path.exists(os.path.join(d, "sim_state.npy")):
|
| 355 |
+
shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy"))
|
| 356 |
+
shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz"))
|
| 357 |
+
for cam, key in (("agentview", "image"), ("wrist", "wrist_image")):
|
| 358 |
+
shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png"))
|
| 359 |
+
with open(os.path.join(lff, "annotations", name + ".json"), "w") as f:
|
| 360 |
+
json.dump(ann, f, indent=1, ensure_ascii=False)
|
| 361 |
+
rows.append(flat_row(i, ann, n, e["from"]))
|
| 362 |
+
tname = ann["task"]["name"]
|
| 363 |
+
rk = (ann["source"]["batch"], ann["source"]["run"])
|
| 364 |
+
r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"),
|
| 365 |
+
run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"],
|
| 366 |
+
memory_free_chain_of=ann["source"].get("memory_free_chain_of"),
|
| 367 |
+
memory_free_rep=ann["source"].get("memory_free_rep"), task=tname,
|
| 368 |
+
seed=ann["task"]["seed"], model=ann["agent"].get("model"),
|
| 369 |
+
harness=ann["agent"].get("harness"),
|
| 370 |
+
harness_version=ann["agent"].get("harness_version"),
|
| 371 |
+
codex_catalog=ann["agent"].get("codex_catalog"),
|
| 372 |
+
outcome_class=ann["run_outcome"].get("outcome_class"),
|
| 373 |
+
attempt_history=ann["run_outcome"].get("attempt_history"),
|
| 374 |
+
agent_final_report=ann["run_outcome"].get("agent_final_report"),
|
| 375 |
+
episodes=[]))
|
| 376 |
+
for x in ann["attempts"]:
|
| 377 |
+
r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success")))
|
| 378 |
+
if tname not in tasks:
|
| 379 |
+
tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")}
|
| 380 |
+
if tname in paper:
|
| 381 |
+
tasks[tname]["paper"] = paper[tname]
|
| 382 |
+
tasks[tname]["instances"] = {}
|
| 383 |
+
tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"]
|
| 384 |
+
# memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id)
|
| 385 |
+
by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")}
|
| 386 |
+
for r in runs.values():
|
| 387 |
+
if r.get("memory_free_chain_of"):
|
| 388 |
+
r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"]))
|
| 389 |
+
for (b, rn), r in runs.items():
|
| 390 |
+
r["memory_free_retries"] = sorted((x["run"] for x in runs.values()
|
| 391 |
+
if x["batch"] == b and x.get("memory_free_chain_of_run") == rn),
|
| 392 |
+
key=lambda q: runs[(b, q)].get("memory_free_rep") or 0)
|
| 393 |
+
with open(os.path.join(lff, "episodes.jsonl"), "w") as f:
|
| 394 |
+
for row in rows:
|
| 395 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 396 |
+
with open(os.path.join(lff, "runs.jsonl"), "w") as f:
|
| 397 |
+
for r in runs.values():
|
| 398 |
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 399 |
+
with open(os.path.join(lff, "tasks.json"), "w") as f:
|
| 400 |
+
json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False)
|
| 401 |
+
with open(os.path.join(lff, "batches.json"), "w") as f:
|
| 402 |
+
json.dump(BATCH_NOTES, f, indent=1)
|
| 403 |
+
with open(os.path.join(lff, "rejected.json"), "w") as f:
|
| 404 |
+
json.dump(plan["rejected"], f, indent=1)
|
| 405 |
+
here = os.path.dirname(os.path.abspath(__file__))
|
| 406 |
+
for s in ("lerobot_replay.py", "lerobot_export.py"):
|
| 407 |
+
shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s))
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def main():
|
| 411 |
+
ap = argparse.ArgumentParser()
|
| 412 |
+
ap.add_argument("step", choices=["plan", "shard", "merge"])
|
| 413 |
+
ap.add_argument("--work", required=True)
|
| 414 |
+
ap.add_argument("--raw", default="")
|
| 415 |
+
ap.add_argument("--runs-root", default="")
|
| 416 |
+
ap.add_argument("--out", default="")
|
| 417 |
+
ap.add_argument("--paper", default="")
|
| 418 |
+
ap.add_argument("--task-set", default="")
|
| 419 |
+
ap.add_argument("--repo-id", default="lffbench/agent-replays")
|
| 420 |
+
ap.add_argument("--batches", default="")
|
| 421 |
+
ap.add_argument("--limit", type=int, default=0)
|
| 422 |
+
ap.add_argument("--shard", type=int, default=0)
|
| 423 |
+
ap.add_argument("--nshards", type=int, default=1)
|
| 424 |
+
ap.add_argument("--threads", type=int, default=2)
|
| 425 |
+
ap.add_argument("--vcodec", default="libsvtav1")
|
| 426 |
+
a = ap.parse_args()
|
| 427 |
+
{"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
if __name__ == "__main__":
|
| 431 |
+
main()
|
leaf/code/remaining-lh-20261103-remaining_lh_auto_001_opus/lerobot_export.py
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars.
|
| 2 |
+
|
| 3 |
+
Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding
|
| 4 |
+
can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan):
|
| 5 |
+
|
| 6 |
+
python scripts/lerobot_export.py plan --raw <raw_root>[,<raw_root2>] --runs-root <lffbench>/runs/api \
|
| 7 |
+
--paper <paper/latex> --task-set <lffbench>/sets/main_v2_1inst.txt --work <work_dir> [--batches ...] [--limit N]
|
| 8 |
+
python scripts/lerobot_export.py shard --work <work_dir> --shard i --nshards N
|
| 9 |
+
python scripts/lerobot_export.py merge --work <work_dir> --nshards N --out <dataset_root>
|
| 10 |
+
|
| 11 |
+
Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0
|
| 12 |
+
mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped.
|
| 13 |
+
|
| 14 |
+
LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t):
|
| 15 |
+
observation.images.image agentview RGB 256x256 (upright; LIBERO naming)
|
| 16 |
+
observation.images.wrist_image wrist (eye-in-hand) RGB 256x256
|
| 17 |
+
observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout)
|
| 18 |
+
observation.joint_pos / joint_vel 7 arm joints (rad, rad/s)
|
| 19 |
+
observation.eef_quat 4: xyzw; observation.gripper_width 1 (m)
|
| 20 |
+
action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad),
|
| 21 |
+
gripper (-1 open, +1 close)
|
| 22 |
+
annotation.attempt_index attempt (1-based) the frame belongs to
|
| 23 |
+
annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`)
|
| 24 |
+
annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action)
|
| 25 |
+
annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt
|
| 26 |
+
annotation.task_event number of task-monitor events (error / progress events) registered at this step
|
| 27 |
+
Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table),
|
| 28 |
+
runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state
|
| 29 |
+
per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/.
|
| 30 |
+
"""
|
| 31 |
+
import argparse
|
| 32 |
+
import glob
|
| 33 |
+
import json
|
| 34 |
+
import os
|
| 35 |
+
import re
|
| 36 |
+
import shutil
|
| 37 |
+
import time
|
| 38 |
+
|
| 39 |
+
import numpy as np
|
| 40 |
+
|
| 41 |
+
FPS = 20
|
| 42 |
+
RES = 256
|
| 43 |
+
BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke",
|
| 44 |
+
"cc_smoke", "cc_opus_smoke"]
|
| 45 |
+
BATCH_NOTES = {
|
| 46 |
+
"cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog",
|
| 47 |
+
"cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267",
|
| 48 |
+
"cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299",
|
| 49 |
+
"cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances",
|
| 50 |
+
"cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)",
|
| 51 |
+
"cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the "
|
| 52 |
+
"with-history continuation of failed runs is incomplete",
|
| 53 |
+
"cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early",
|
| 54 |
+
"cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt",
|
| 55 |
+
"cc_opus_smoke": "smoke test: single attempt",
|
| 56 |
+
}
|
| 57 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 58 |
+
CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)",
|
| 59 |
+
"L2": "disturbed state to restore (incl. damage the agent causes)",
|
| 60 |
+
"L3": "infeasible manipulation strategy (grasp / contact / tool must change)",
|
| 61 |
+
"L4": "misjudged geometry (size, shape, fit, hidden structure)",
|
| 62 |
+
"L5": "misjudged physics (mass distribution, friction, dynamics)"}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def features():
|
| 66 |
+
vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]}
|
| 67 |
+
f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names}
|
| 68 |
+
i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None}
|
| 69 |
+
return {
|
| 70 |
+
"observation.images.image": vid(),
|
| 71 |
+
"observation.images.wrist_image": vid(),
|
| 72 |
+
"observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z",
|
| 73 |
+
"finger_qpos_left", "finger_qpos_right"]),
|
| 74 |
+
"observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 75 |
+
"observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 76 |
+
"observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]),
|
| 77 |
+
"observation.gripper_width": f32(1, ["width_m"]),
|
| 78 |
+
"action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y",
|
| 79 |
+
"eef_delta_rot_aa_z", "gripper_close"]),
|
| 80 |
+
"annotation.attempt_index": i64(),
|
| 81 |
+
"annotation.command_index": i64(),
|
| 82 |
+
"annotation.phase": i64(),
|
| 83 |
+
"annotation.attempt_success": i64(),
|
| 84 |
+
"annotation.task_event": i64(),
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ------------------------------------------------------------------------------------------------ paper metadata
|
| 89 |
+
|
| 90 |
+
def _clean_tex(s):
|
| 91 |
+
s = re.sub(r"%.*", "", s)
|
| 92 |
+
for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"),
|
| 93 |
+
(r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"),
|
| 94 |
+
(r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"),
|
| 95 |
+
(r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"),
|
| 96 |
+
(r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]:
|
| 97 |
+
s = re.sub(a, b, s)
|
| 98 |
+
s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s)
|
| 99 |
+
s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s)
|
| 100 |
+
for _ in range(3):
|
| 101 |
+
s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s)
|
| 102 |
+
s = re.sub(r"\$([^$]*)\$", r"\1", s)
|
| 103 |
+
s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ")
|
| 104 |
+
s = re.sub(r"\{([^{}]*)\}", r"\1", s)
|
| 105 |
+
s = re.sub(r"\\[a-zA-Z]+\*?", "", s)
|
| 106 |
+
return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def paper_tasks(paper_dir):
|
| 110 |
+
"""{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the
|
| 111 |
+
paper's task table and task appendix (empty if the paper sources are not there)."""
|
| 112 |
+
out = {}
|
| 113 |
+
if not paper_dir:
|
| 114 |
+
return out
|
| 115 |
+
app = os.path.join(paper_dir, "sections", "appendix_tasks.tex")
|
| 116 |
+
tab = os.path.join(paper_dir, "sections", "tab_tasks.tex")
|
| 117 |
+
if os.path.exists(app):
|
| 118 |
+
txt = open(app).read()
|
| 119 |
+
parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt)
|
| 120 |
+
for i in range(1, len(parts) - 1, 2):
|
| 121 |
+
if parts[i] != "\\paragraph{":
|
| 122 |
+
continue
|
| 123 |
+
body = parts[i + 1]
|
| 124 |
+
m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S)
|
| 125 |
+
if not m:
|
| 126 |
+
continue
|
| 127 |
+
name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip()
|
| 128 |
+
desc = _clean_tex(body[m.end():])
|
| 129 |
+
out[code] = dict(name=name, cause=_clean_tex(cause), description=desc)
|
| 130 |
+
if os.path.exists(tab):
|
| 131 |
+
names = {v["name"].lower(): k for k, v in out.items()}
|
| 132 |
+
for line in open(tab):
|
| 133 |
+
cells = [c.strip() for c in line.split("&")]
|
| 134 |
+
if len(cells) != 6 or not cells[-1].endswith("\\\\"):
|
| 135 |
+
continue
|
| 136 |
+
nm = re.sub(r"\\contscene", "", cells[0]).strip().lower()
|
| 137 |
+
code = names.get(nm)
|
| 138 |
+
if not code:
|
| 139 |
+
continue
|
| 140 |
+
out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]),
|
| 141 |
+
repair_within_attempt=_clean_tex(cells[3]) == "yes",
|
| 142 |
+
oracle_first_attempt_pct=_clean_tex(cells[4]),
|
| 143 |
+
naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip()))
|
| 144 |
+
return out
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
# ------------------------------------------------------------------------------------------------ collection
|
| 148 |
+
|
| 149 |
+
def manifest_status(runs_root, batch, run, cache={}):
|
| 150 |
+
if batch not in cache:
|
| 151 |
+
p = os.path.join(runs_root, batch, "manifest.json")
|
| 152 |
+
cache[batch] = json.load(open(p)) if os.path.exists(p) else {}
|
| 153 |
+
m = cache[batch]
|
| 154 |
+
for r in m.get("runs", []):
|
| 155 |
+
if r.get("run") == run:
|
| 156 |
+
return r.get("status", "?"), r
|
| 157 |
+
for r in m.get("superseded", []):
|
| 158 |
+
if r.get("run") == run:
|
| 159 |
+
return "superseded_" + str(r.get("status", "?")), r
|
| 160 |
+
return "not_in_manifest", {}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def collect(raw_roots, runs_root, batches, task_order):
|
| 164 |
+
"""Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root."""
|
| 165 |
+
eps, rejected, seen = [], [], set()
|
| 166 |
+
for root in raw_roots:
|
| 167 |
+
for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))):
|
| 168 |
+
rep = json.load(open(rj))
|
| 169 |
+
batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"]
|
| 170 |
+
if (batches and batch not in batches) or (batch, run) in seen:
|
| 171 |
+
continue
|
| 172 |
+
seen.add((batch, run))
|
| 173 |
+
ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff")
|
| 174 |
+
status, entry = manifest_status(runs_root, batch, run)
|
| 175 |
+
if not ok:
|
| 176 |
+
never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked")
|
| 177 |
+
rejected.append(dict(run=run, batch=batch, run_status=status,
|
| 178 |
+
reason="run never started (no contract, no robot command)" if never else
|
| 179 |
+
"replay does not reproduce the log (the log has gaps or the replay diverged)",
|
| 180 |
+
detail=rep.get("first_mismatches")))
|
| 181 |
+
continue
|
| 182 |
+
for ep in rep.get("episodes", []):
|
| 183 |
+
d = os.path.join(root, ep["dir"])
|
| 184 |
+
ann = json.load(open(os.path.join(d, "annotation.json")))
|
| 185 |
+
judged = [a for a in ann["attempts"] if a.get("success") is not None]
|
| 186 |
+
if not judged or ep["n_frames"] == 0:
|
| 187 |
+
rejected.append(dict(run=run, batch=batch, episode=ep["dir"],
|
| 188 |
+
reason="no judged attempt" if not judged else "no frames"))
|
| 189 |
+
continue
|
| 190 |
+
ann["source"]["run_status"] = status
|
| 191 |
+
ann["source"]["manifest_id"] = entry.get("id")
|
| 192 |
+
ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"],
|
| 193 |
+
max_eef_dev_m=rep["max_eef_dev_m"])
|
| 194 |
+
key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99),
|
| 195 |
+
{"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2),
|
| 196 |
+
ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"])
|
| 197 |
+
eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann))
|
| 198 |
+
eps.sort(key=lambda x: x["key"])
|
| 199 |
+
return eps, rejected
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# ------------------------------------------------------------------------------------------------ writing
|
| 203 |
+
|
| 204 |
+
def frames_of(path):
|
| 205 |
+
import av
|
| 206 |
+
with av.open(path) as c:
|
| 207 |
+
for fr in c.decode(video=0):
|
| 208 |
+
yield fr.to_ndarray(format="rgb24")
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def flat_row(i, ann, n, idx0):
|
| 212 |
+
s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"]
|
| 213 |
+
att = ann["attempts"]
|
| 214 |
+
a0 = att[0]
|
| 215 |
+
return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n,
|
| 216 |
+
batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"],
|
| 217 |
+
memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"),
|
| 218 |
+
episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att],
|
| 219 |
+
harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"),
|
| 220 |
+
effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"),
|
| 221 |
+
task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"),
|
| 222 |
+
category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"],
|
| 223 |
+
success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att],
|
| 224 |
+
feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att],
|
| 225 |
+
auto_ended=[a.get("auto_ended") for a in att],
|
| 226 |
+
corrected_later_in_run=[a.get("corrected_later_in_run") for a in att],
|
| 227 |
+
error_event_in_attempt=[a.get("error_event_in_attempt") for a in att],
|
| 228 |
+
run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"),
|
| 229 |
+
n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]),
|
| 230 |
+
first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def cmd_plan(a):
|
| 234 |
+
task_order = {}
|
| 235 |
+
if a.task_set and os.path.exists(a.task_set):
|
| 236 |
+
for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")):
|
| 237 |
+
task_order[line.split(":")[0].strip()] = i
|
| 238 |
+
batches = [b for b in a.batches.split(",") if b] if a.batches else None
|
| 239 |
+
eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order)
|
| 240 |
+
if a.limit:
|
| 241 |
+
eps = eps[:a.limit]
|
| 242 |
+
paper = paper_tasks(a.paper)
|
| 243 |
+
idx0 = 0
|
| 244 |
+
for i, e in enumerate(eps):
|
| 245 |
+
ann = e["ann"]
|
| 246 |
+
tname = ann["task"]["name"]
|
| 247 |
+
if tname in paper:
|
| 248 |
+
ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"}
|
| 249 |
+
ann["episode_index"] = i
|
| 250 |
+
ann["dataset_index_range"] = [idx0, idx0 + e["n"]]
|
| 251 |
+
e["index"], e["from"] = i, idx0
|
| 252 |
+
idx0 += e["n"]
|
| 253 |
+
del e["key"]
|
| 254 |
+
os.makedirs(a.work, exist_ok=True)
|
| 255 |
+
with open(os.path.join(a.work, "plan.json"), "w") as f:
|
| 256 |
+
json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f,
|
| 257 |
+
ensure_ascii=False)
|
| 258 |
+
print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def shard_range(n_eps, i, k):
|
| 262 |
+
return (n_eps * i) // k, (n_eps * (i + 1)) // k
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def cmd_shard(a):
|
| 266 |
+
from lerobot.datasets.lerobot_dataset import LeRobotDataset
|
| 267 |
+
t0 = time.time()
|
| 268 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 269 |
+
eps = plan["episodes"]
|
| 270 |
+
lo, hi = shard_range(len(eps), a.shard, a.nshards)
|
| 271 |
+
out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}")
|
| 272 |
+
if os.path.exists(os.path.join(out, "DONE")):
|
| 273 |
+
print(f"shard {a.shard}: done already", flush=True)
|
| 274 |
+
return
|
| 275 |
+
shutil.rmtree(out, ignore_errors=True)
|
| 276 |
+
ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out,
|
| 277 |
+
robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads,
|
| 278 |
+
vcodec=a.vcodec)
|
| 279 |
+
nfr = 0
|
| 280 |
+
for e in eps[lo:hi]:
|
| 281 |
+
d, ann, n = e["dir"], e["ann"], e["n"]
|
| 282 |
+
fr = np.load(os.path.join(d, "frames.npz"))
|
| 283 |
+
assert len(fr["action"]) == n, d
|
| 284 |
+
succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]}
|
| 285 |
+
evc = np.zeros(n, np.int64)
|
| 286 |
+
for ev in ann["task_events"]:
|
| 287 |
+
if 0 <= ev["frame"] < n:
|
| 288 |
+
evc[ev["frame"]] += 1
|
| 289 |
+
state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32)
|
| 290 |
+
instr = ann["task"]["instruction"]
|
| 291 |
+
k = 0
|
| 292 |
+
for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))):
|
| 293 |
+
if k >= n:
|
| 294 |
+
break
|
| 295 |
+
ds.add_frame({
|
| 296 |
+
"observation.images.image": img, "observation.images.wrist_image": wr,
|
| 297 |
+
"observation.state": state[k],
|
| 298 |
+
"observation.joint_pos": fr["joint_pos"][k].astype(np.float32),
|
| 299 |
+
"observation.joint_vel": fr["joint_vel"][k].astype(np.float32),
|
| 300 |
+
"observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32),
|
| 301 |
+
"observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32),
|
| 302 |
+
"action": fr["action"][k].astype(np.float32),
|
| 303 |
+
"annotation.attempt_index": np.array([fr["attempt"][k]], np.int64),
|
| 304 |
+
"annotation.command_index": np.array([fr["command"][k]], np.int64),
|
| 305 |
+
"annotation.phase": np.array([fr["phase"][k]], np.int64),
|
| 306 |
+
"annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64),
|
| 307 |
+
"annotation.task_event": np.array([evc[k]], np.int64),
|
| 308 |
+
"task": instr,
|
| 309 |
+
})
|
| 310 |
+
k += 1
|
| 311 |
+
if k != n:
|
| 312 |
+
raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames")
|
| 313 |
+
ds.save_episode()
|
| 314 |
+
nfr += n
|
| 315 |
+
ds.finalize()
|
| 316 |
+
shutil.rmtree(os.path.join(out, "images"), ignore_errors=True)
|
| 317 |
+
open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n")
|
| 318 |
+
print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def cmd_merge(a):
|
| 322 |
+
from pathlib import Path
|
| 323 |
+
from lerobot.datasets.aggregate import aggregate_datasets
|
| 324 |
+
t0 = time.time()
|
| 325 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 326 |
+
eps = plan["episodes"]
|
| 327 |
+
roots, ids = [], []
|
| 328 |
+
for i in range(a.nshards):
|
| 329 |
+
lo, hi = shard_range(len(eps), i, a.nshards)
|
| 330 |
+
if hi <= lo:
|
| 331 |
+
continue
|
| 332 |
+
r = os.path.join(a.work, "shards", f"shard_{i:03d}")
|
| 333 |
+
if not os.path.exists(os.path.join(r, "DONE")):
|
| 334 |
+
raise SystemExit(f"shard {i} is not done")
|
| 335 |
+
roots.append(Path(r))
|
| 336 |
+
ids.append(f"{plan['repo_id']}-shard{i:03d}")
|
| 337 |
+
if os.path.exists(a.out):
|
| 338 |
+
raise SystemExit(f"{a.out} exists; refusing to overwrite")
|
| 339 |
+
aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out))
|
| 340 |
+
print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True)
|
| 341 |
+
write_sidecars(a, plan)
|
| 342 |
+
print(f"merge done in {time.time() - t0:.0f}s", flush=True)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def write_sidecars(a, plan):
|
| 346 |
+
eps, paper = plan["episodes"], plan["paper"]
|
| 347 |
+
lff = os.path.join(a.out, "lff")
|
| 348 |
+
for sub in ("annotations", "sim_state", "final", "code"):
|
| 349 |
+
os.makedirs(os.path.join(lff, sub), exist_ok=True)
|
| 350 |
+
rows, runs, tasks = [], {}, {}
|
| 351 |
+
for e in eps:
|
| 352 |
+
i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"]
|
| 353 |
+
name = f"episode_{i:06d}"
|
| 354 |
+
if os.path.exists(os.path.join(d, "sim_state.npy")):
|
| 355 |
+
shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy"))
|
| 356 |
+
shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz"))
|
| 357 |
+
for cam, key in (("agentview", "image"), ("wrist", "wrist_image")):
|
| 358 |
+
shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png"))
|
| 359 |
+
with open(os.path.join(lff, "annotations", name + ".json"), "w") as f:
|
| 360 |
+
json.dump(ann, f, indent=1, ensure_ascii=False)
|
| 361 |
+
rows.append(flat_row(i, ann, n, e["from"]))
|
| 362 |
+
tname = ann["task"]["name"]
|
| 363 |
+
rk = (ann["source"]["batch"], ann["source"]["run"])
|
| 364 |
+
r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"),
|
| 365 |
+
run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"],
|
| 366 |
+
memory_free_chain_of=ann["source"].get("memory_free_chain_of"),
|
| 367 |
+
memory_free_rep=ann["source"].get("memory_free_rep"), task=tname,
|
| 368 |
+
seed=ann["task"]["seed"], model=ann["agent"].get("model"),
|
| 369 |
+
harness=ann["agent"].get("harness"),
|
| 370 |
+
harness_version=ann["agent"].get("harness_version"),
|
| 371 |
+
codex_catalog=ann["agent"].get("codex_catalog"),
|
| 372 |
+
outcome_class=ann["run_outcome"].get("outcome_class"),
|
| 373 |
+
attempt_history=ann["run_outcome"].get("attempt_history"),
|
| 374 |
+
agent_final_report=ann["run_outcome"].get("agent_final_report"),
|
| 375 |
+
episodes=[]))
|
| 376 |
+
for x in ann["attempts"]:
|
| 377 |
+
r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success")))
|
| 378 |
+
if tname not in tasks:
|
| 379 |
+
tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")}
|
| 380 |
+
if tname in paper:
|
| 381 |
+
tasks[tname]["paper"] = paper[tname]
|
| 382 |
+
tasks[tname]["instances"] = {}
|
| 383 |
+
tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"]
|
| 384 |
+
# memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id)
|
| 385 |
+
by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")}
|
| 386 |
+
for r in runs.values():
|
| 387 |
+
if r.get("memory_free_chain_of"):
|
| 388 |
+
r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"]))
|
| 389 |
+
for (b, rn), r in runs.items():
|
| 390 |
+
r["memory_free_retries"] = sorted((x["run"] for x in runs.values()
|
| 391 |
+
if x["batch"] == b and x.get("memory_free_chain_of_run") == rn),
|
| 392 |
+
key=lambda q: runs[(b, q)].get("memory_free_rep") or 0)
|
| 393 |
+
with open(os.path.join(lff, "episodes.jsonl"), "w") as f:
|
| 394 |
+
for row in rows:
|
| 395 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 396 |
+
with open(os.path.join(lff, "runs.jsonl"), "w") as f:
|
| 397 |
+
for r in runs.values():
|
| 398 |
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 399 |
+
with open(os.path.join(lff, "tasks.json"), "w") as f:
|
| 400 |
+
json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False)
|
| 401 |
+
with open(os.path.join(lff, "batches.json"), "w") as f:
|
| 402 |
+
json.dump(BATCH_NOTES, f, indent=1)
|
| 403 |
+
with open(os.path.join(lff, "rejected.json"), "w") as f:
|
| 404 |
+
json.dump(plan["rejected"], f, indent=1)
|
| 405 |
+
here = os.path.dirname(os.path.abspath(__file__))
|
| 406 |
+
for s in ("lerobot_replay.py", "lerobot_export.py"):
|
| 407 |
+
shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s))
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def main():
|
| 411 |
+
ap = argparse.ArgumentParser()
|
| 412 |
+
ap.add_argument("step", choices=["plan", "shard", "merge"])
|
| 413 |
+
ap.add_argument("--work", required=True)
|
| 414 |
+
ap.add_argument("--raw", default="")
|
| 415 |
+
ap.add_argument("--runs-root", default="")
|
| 416 |
+
ap.add_argument("--out", default="")
|
| 417 |
+
ap.add_argument("--paper", default="")
|
| 418 |
+
ap.add_argument("--task-set", default="")
|
| 419 |
+
ap.add_argument("--repo-id", default="lffbench/agent-replays")
|
| 420 |
+
ap.add_argument("--batches", default="")
|
| 421 |
+
ap.add_argument("--limit", type=int, default=0)
|
| 422 |
+
ap.add_argument("--shard", type=int, default=0)
|
| 423 |
+
ap.add_argument("--nshards", type=int, default=1)
|
| 424 |
+
ap.add_argument("--threads", type=int, default=2)
|
| 425 |
+
ap.add_argument("--vcodec", default="libsvtav1")
|
| 426 |
+
a = ap.parse_args()
|
| 427 |
+
{"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
if __name__ == "__main__":
|
| 431 |
+
main()
|
leaf/code/remaining-lh-20261103-remaining_lh_auto_001_opus/lerobot_replay.py
ADDED
|
@@ -0,0 +1,744 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay
|
| 2 |
+
against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the
|
| 3 |
+
LeRobot export (scripts/lerobot_export.py).
|
| 4 |
+
|
| 5 |
+
python scripts/lerobot_replay.py check <run_dir> [<run_dir> ...] [--json out.json] # replay only, print fidelity
|
| 6 |
+
python scripts/lerobot_replay.py record <run_dir> --out <raw_root> [--res 256]
|
| 7 |
+
|
| 8 |
+
Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot
|
| 9 |
+
commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite
|
| 10 |
+
is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly
|
| 11 |
+
like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same
|
| 12 |
+
outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width,
|
| 13 |
+
ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code
|
| 14 |
+
hashes equal the current files are expected to match (check_code()).
|
| 15 |
+
|
| 16 |
+
Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB,
|
| 17 |
+
proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes:
|
| 18 |
+
protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode
|
| 19 |
+
per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the
|
| 20 |
+
fidelity check runs in record mode too. Per episode the recorder writes <raw_root>/<batch>/<run>/epNN/:
|
| 21 |
+
agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes)
|
| 22 |
+
frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase
|
| 23 |
+
sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel)
|
| 24 |
+
final_*.png, final.npz observation after the last control step (the state the outcome was judged in)
|
| 25 |
+
annotation.json episode annotation (build_annotation)
|
| 26 |
+
and <raw_root>/<batch>/<run>/replay.json (fidelity) when the whole run is done.
|
| 27 |
+
"""
|
| 28 |
+
import argparse
|
| 29 |
+
import ast
|
| 30 |
+
import hashlib
|
| 31 |
+
import importlib
|
| 32 |
+
import json
|
| 33 |
+
import math
|
| 34 |
+
import os
|
| 35 |
+
import pkgutil
|
| 36 |
+
import re
|
| 37 |
+
import shutil
|
| 38 |
+
import sys
|
| 39 |
+
import time
|
| 40 |
+
from collections import defaultdict
|
| 41 |
+
|
| 42 |
+
import numpy as np
|
| 43 |
+
|
| 44 |
+
LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 45 |
+
sys.path.insert(0, LFF_ROOT)
|
| 46 |
+
|
| 47 |
+
from lffbench import envs # noqa: E402
|
| 48 |
+
from lffbench import tasks as task_pkg # noqa: E402
|
| 49 |
+
from lffbench.agent import camera as C # noqa: E402
|
| 50 |
+
from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402
|
| 51 |
+
from lffbench.task_base import TASKS # noqa: E402
|
| 52 |
+
|
| 53 |
+
for _m in pkgutil.iter_modules(task_pkg.__path__):
|
| 54 |
+
importlib.import_module(f"lffbench.tasks.{_m.name}")
|
| 55 |
+
|
| 56 |
+
# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the
|
| 57 |
+
# task's outcome() check after `finish` (the arm holds still; not an agent action)
|
| 58 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 59 |
+
FPS = 20
|
| 60 |
+
SCHEMA = "lff-replay-1"
|
| 61 |
+
|
| 62 |
+
# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR"
|
| 63 |
+
ERROR_FLAGS = ("trap_fired", "recovered_in_attempt")
|
| 64 |
+
ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events",
|
| 65 |
+
"n_missed_strikes", "n_open_gripper_pushes")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def load_jsonl(p):
|
| 69 |
+
out = []
|
| 70 |
+
if not os.path.exists(p):
|
| 71 |
+
return out
|
| 72 |
+
with open(p) as f:
|
| 73 |
+
for line in f:
|
| 74 |
+
line = line.strip()
|
| 75 |
+
if line:
|
| 76 |
+
try:
|
| 77 |
+
out.append(json.loads(line))
|
| 78 |
+
except ValueError:
|
| 79 |
+
pass
|
| 80 |
+
return out
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def norm_json(o):
|
| 84 |
+
return json.loads(json.dumps(o, default=_json_default))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def sha256(p):
|
| 88 |
+
with open(p, "rb") as f:
|
| 89 |
+
return hashlib.sha256(f.read()).hexdigest()
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def check_code(run_dir):
|
| 93 |
+
"""[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract."""
|
| 94 |
+
p = os.path.join(run_dir, "contract.json")
|
| 95 |
+
if not os.path.exists(p):
|
| 96 |
+
return [("contract.json", None, None)]
|
| 97 |
+
files = json.load(open(p))["contract"].get("server_code_files", {})
|
| 98 |
+
bad = []
|
| 99 |
+
for f, h in files.items():
|
| 100 |
+
q = os.path.join(LFF_ROOT, f)
|
| 101 |
+
cur = sha256(q) if os.path.exists(q) else None
|
| 102 |
+
if cur != h:
|
| 103 |
+
bad.append((f, h, cur))
|
| 104 |
+
return bad
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def diff_json(a, b, path="", tol=0.0, out=None, limit=20):
|
| 108 |
+
"""Differences between two JSON values (numbers compared with an absolute tolerance)."""
|
| 109 |
+
out = [] if out is None else out
|
| 110 |
+
if len(out) >= limit:
|
| 111 |
+
return out
|
| 112 |
+
if isinstance(a, dict) and isinstance(b, dict):
|
| 113 |
+
for k in sorted(set(a) | set(b)):
|
| 114 |
+
if k not in a or k not in b:
|
| 115 |
+
out.append((f"{path}.{k}", a.get(k, "<missing>"), b.get(k, "<missing>")))
|
| 116 |
+
else:
|
| 117 |
+
diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit)
|
| 118 |
+
elif isinstance(a, list) and isinstance(b, list):
|
| 119 |
+
if len(a) != len(b):
|
| 120 |
+
out.append((path, f"len {len(a)}", f"len {len(b)}"))
|
| 121 |
+
else:
|
| 122 |
+
for i, (x, y) in enumerate(zip(a, b)):
|
| 123 |
+
diff_json(x, y, f"{path}[{i}]", tol, out, limit)
|
| 124 |
+
elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
|
| 125 |
+
if a != b:
|
| 126 |
+
out.append((path, a, b))
|
| 127 |
+
elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))):
|
| 128 |
+
out.append((path, a, b))
|
| 129 |
+
return out
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def error_event(o):
|
| 133 |
+
"""True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none."""
|
| 134 |
+
if not isinstance(o, dict):
|
| 135 |
+
return None
|
| 136 |
+
keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o]
|
| 137 |
+
if not keys:
|
| 138 |
+
return None
|
| 139 |
+
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)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# ====================================================================================================== logs -> notes
|
| 143 |
+
|
| 144 |
+
class RunLog:
|
| 145 |
+
"""Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's
|
| 146 |
+
narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition."""
|
| 147 |
+
|
| 148 |
+
def __init__(self, run_dir, manifest=None):
|
| 149 |
+
self.run_dir = os.path.abspath(run_dir.rstrip("/"))
|
| 150 |
+
self.run = os.path.basename(self.run_dir)
|
| 151 |
+
self.batch = os.path.basename(os.path.dirname(self.run_dir))
|
| 152 |
+
self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl"))
|
| 153 |
+
self.start = next(e for e in self.ev if e["ev"] == "session_start")
|
| 154 |
+
self.calls, self.dones, self.harness_status = {}, [], []
|
| 155 |
+
last = None
|
| 156 |
+
for e in self.ev:
|
| 157 |
+
if e["ev"] == "call":
|
| 158 |
+
self.calls[(int(e["attempt"]), int(e["step"]))] = e
|
| 159 |
+
last = e
|
| 160 |
+
elif e["ev"] == "done":
|
| 161 |
+
self.dones.append(e)
|
| 162 |
+
last = e
|
| 163 |
+
elif e["ev"] == "http" and last is not None and "think_s" not in last:
|
| 164 |
+
ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \
|
| 165 |
+
(last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe"))
|
| 166 |
+
if ok:
|
| 167 |
+
last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s")
|
| 168 |
+
self.manifest = manifest or {}
|
| 169 |
+
self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {}
|
| 170 |
+
p = os.path.join(self.run_dir, "harness.json")
|
| 171 |
+
self.harness = json.load(open(p)) if os.path.exists(p) else {}
|
| 172 |
+
self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl"))
|
| 173 |
+
self._narration()
|
| 174 |
+
|
| 175 |
+
# ---------------------------------------------------------------- agent narration
|
| 176 |
+
def _narration(self):
|
| 177 |
+
"""notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one;
|
| 178 |
+
finish_notes[attempt] likewise for the agent's finish call; final_report = its last message."""
|
| 179 |
+
self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", []
|
| 180 |
+
buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
|
| 181 |
+
attempt = 1
|
| 182 |
+
|
| 183 |
+
def take():
|
| 184 |
+
nonlocal buf
|
| 185 |
+
out = {k: v for k, v in buf.items() if v}
|
| 186 |
+
buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
|
| 187 |
+
return out
|
| 188 |
+
|
| 189 |
+
last_msg = ""
|
| 190 |
+
for t in self.traj:
|
| 191 |
+
if t.get("kind") == "header":
|
| 192 |
+
self.headers.append(t.get("agent") or {})
|
| 193 |
+
continue
|
| 194 |
+
if t.get("kind") != "step":
|
| 195 |
+
continue
|
| 196 |
+
if (t.get("message") or "").strip():
|
| 197 |
+
buf["messages"].append(t["message"].strip())
|
| 198 |
+
last_msg = t["message"].strip()
|
| 199 |
+
if (t.get("reasoning_content") or "").strip():
|
| 200 |
+
buf["reasoning"].append(t["reasoning_content"].strip())
|
| 201 |
+
res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])}
|
| 202 |
+
for c in t.get("tool_calls") or []:
|
| 203 |
+
fn, args = c.get("function_name"), c.get("arguments") or {}
|
| 204 |
+
if fn == "shell":
|
| 205 |
+
buf["shell"].append(str(args.get("command", ""))[:2000])
|
| 206 |
+
elif fn == "view_images":
|
| 207 |
+
buf["viewed"].extend(args.get("paths") or [])
|
| 208 |
+
elif fn == "robot":
|
| 209 |
+
cmd = str(args.get("command", "")).strip()
|
| 210 |
+
r = res.get(c.get("tool_call_id")) or {}
|
| 211 |
+
try:
|
| 212 |
+
rep = json.loads(r.get("content") or "{}")
|
| 213 |
+
except ValueError:
|
| 214 |
+
rep = {}
|
| 215 |
+
word = cmd.split()[0] if cmd else ""
|
| 216 |
+
m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", "")))
|
| 217 |
+
if word in ("move_eef", "observe") and m:
|
| 218 |
+
a, s = int(m.group(1)), int(m.group(2))
|
| 219 |
+
n = take()
|
| 220 |
+
n["command"] = cmd
|
| 221 |
+
self.notes[(a, s)] = n
|
| 222 |
+
attempt = a
|
| 223 |
+
elif word in ("finish", "done"):
|
| 224 |
+
n = take()
|
| 225 |
+
n["command"] = cmd
|
| 226 |
+
n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)}
|
| 227 |
+
self.finish_notes.setdefault(attempt, n)
|
| 228 |
+
if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"):
|
| 229 |
+
attempt += 1
|
| 230 |
+
# status / help / errors: their narration stays in the buffer for the next command
|
| 231 |
+
self.final_report = last_msg
|
| 232 |
+
|
| 233 |
+
# ---------------------------------------------------------------- run-level labels
|
| 234 |
+
def attempts(self):
|
| 235 |
+
out = []
|
| 236 |
+
for e in self.dones:
|
| 237 |
+
o = e.get("outcome") or {}
|
| 238 |
+
if isinstance(o, str):
|
| 239 |
+
try:
|
| 240 |
+
o = ast.literal_eval(o)
|
| 241 |
+
except (ValueError, SyntaxError):
|
| 242 |
+
o = {}
|
| 243 |
+
out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o,
|
| 244 |
+
reason=e.get("reason") or ""))
|
| 245 |
+
return sorted(out, key=lambda x: x["attempt"])
|
| 246 |
+
|
| 247 |
+
def condition(self):
|
| 248 |
+
s, en = self.start, self.entry
|
| 249 |
+
mem = s.get("memory", en.get("mem"))
|
| 250 |
+
chain = en.get("chain")
|
| 251 |
+
if mem == "full":
|
| 252 |
+
cond = "with_history"
|
| 253 |
+
elif chain:
|
| 254 |
+
cond = "memory_free_retry"
|
| 255 |
+
else:
|
| 256 |
+
cond = "independent_single_attempt"
|
| 257 |
+
return cond, chain
|
| 258 |
+
|
| 259 |
+
def outcome_class(self):
|
| 260 |
+
"""CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None."""
|
| 261 |
+
att = self.attempts()
|
| 262 |
+
if not att or self.start.get("memory") != "full":
|
| 263 |
+
return None, "".join("S" if a["success"] else "F" for a in att)
|
| 264 |
+
hist = "".join("S" if a["success"] else "F" for a in att)
|
| 265 |
+
if att[0]["success"]:
|
| 266 |
+
ev = error_event(att[0]["outcome"])
|
| 267 |
+
cls = "S?" if ev is None else ("IR" if ev else "CS")
|
| 268 |
+
else:
|
| 269 |
+
cls = "XR" if any(a["success"] for a in att) else "F"
|
| 270 |
+
return cls, hist
|
| 271 |
+
|
| 272 |
+
def agent_info(self):
|
| 273 |
+
h, en = self.harness, self.entry
|
| 274 |
+
hdr = self.headers[0] if self.headers else {}
|
| 275 |
+
return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"),
|
| 276 |
+
harness_version=h.get("version") or hdr.get("version"),
|
| 277 |
+
harness_binary_sha256=(h.get("binary") or {}).get("sha256"),
|
| 278 |
+
model=h.get("model") or en.get("model") or hdr.get("model_name"),
|
| 279 |
+
effort=h.get("effort") or en.get("effort") or hdr.get("effort"),
|
| 280 |
+
provider=h.get("provider") or en.get("provider"),
|
| 281 |
+
codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"),
|
| 282 |
+
jail=en.get("jail"))
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
# ====================================================================================================== recording
|
| 286 |
+
|
| 287 |
+
class EpisodeSink:
|
| 288 |
+
"""Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed."""
|
| 289 |
+
|
| 290 |
+
def __init__(self, path):
|
| 291 |
+
self.path = path
|
| 292 |
+
os.makedirs(path, exist_ok=True)
|
| 293 |
+
self.w = None
|
| 294 |
+
self.num = defaultdict(list)
|
| 295 |
+
self.n = 0
|
| 296 |
+
|
| 297 |
+
def add(self, st, imgs):
|
| 298 |
+
import imageio
|
| 299 |
+
if self.w is None:
|
| 300 |
+
self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb",
|
| 301 |
+
pixelformat="rgb24", macro_block_size=1,
|
| 302 |
+
ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error")
|
| 303 |
+
for k in ("agentview", "wrist")]
|
| 304 |
+
for w, im in zip(self.w, imgs):
|
| 305 |
+
w.append_data(im)
|
| 306 |
+
for k, v in st.items():
|
| 307 |
+
self.num[k].append(v)
|
| 308 |
+
self.n += 1
|
| 309 |
+
|
| 310 |
+
def close(self, final_state, final_imgs):
|
| 311 |
+
from PIL import Image
|
| 312 |
+
if self.w is not None:
|
| 313 |
+
for w in self.w:
|
| 314 |
+
w.close()
|
| 315 |
+
arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"}
|
| 316 |
+
np.savez(os.path.join(self.path, "frames.npz"), **arr)
|
| 317 |
+
if self.num.get("sim_state"):
|
| 318 |
+
np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64))
|
| 319 |
+
np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()})
|
| 320 |
+
for k, im in zip(("agentview", "wrist"), final_imgs):
|
| 321 |
+
Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png"))
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
class Recorder:
|
| 325 |
+
"""Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink."""
|
| 326 |
+
|
| 327 |
+
def __init__(self, rp, res):
|
| 328 |
+
self.rp, self.res = rp, int(res)
|
| 329 |
+
self.active = False
|
| 330 |
+
self.sink = None
|
| 331 |
+
self.cur = dict(attempt=1, command=-1, phase=PHASES["move"])
|
| 332 |
+
env = rp.task.env
|
| 333 |
+
self.env, self.rob = env, env.robots[0]
|
| 334 |
+
self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist"))
|
| 335 |
+
orig = env.step
|
| 336 |
+
|
| 337 |
+
def step(a):
|
| 338 |
+
if self.active and self.sink is not None:
|
| 339 |
+
self.capture(np.asarray(a, np.float64))
|
| 340 |
+
out = orig(a)
|
| 341 |
+
if self.active and self.sink is not None:
|
| 342 |
+
self.rp.poll_events(self.sink.n - 1)
|
| 343 |
+
return out
|
| 344 |
+
|
| 345 |
+
env.step = step
|
| 346 |
+
|
| 347 |
+
@property
|
| 348 |
+
def n(self):
|
| 349 |
+
return self.sink.n if self.sink is not None else 0
|
| 350 |
+
|
| 351 |
+
def state(self):
|
| 352 |
+
import robosuite.utils.transform_utils as T
|
| 353 |
+
env, rob = self.env, self.rob
|
| 354 |
+
d = env.sim.data
|
| 355 |
+
eef = np.array(d.site_xpos[rob.eef_site_id], np.float64)
|
| 356 |
+
q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw")
|
| 357 |
+
gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64)
|
| 358 |
+
try:
|
| 359 |
+
flat = np.asarray(env.sim.get_state().flatten(), np.float64)
|
| 360 |
+
except Exception:
|
| 361 |
+
flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64)
|
| 362 |
+
sk = self.rp.task.sk
|
| 363 |
+
return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64),
|
| 364 |
+
gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64),
|
| 365 |
+
joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64),
|
| 366 |
+
gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64),
|
| 367 |
+
eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)),
|
| 368 |
+
sim_time=np.float64(d.time), sim_state=flat)
|
| 369 |
+
|
| 370 |
+
def images(self):
|
| 371 |
+
return [envs.render(self.env, c, self.res) for c in self.cams]
|
| 372 |
+
|
| 373 |
+
def capture(self, a):
|
| 374 |
+
st = self.state()
|
| 375 |
+
st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]),
|
| 376 |
+
phase=np.int64(self.cur["phase"]))
|
| 377 |
+
self.sink.add(st, self.images())
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
class RunReplay:
|
| 381 |
+
def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None):
|
| 382 |
+
self.run_dir = os.path.abspath(run_dir.rstrip("/"))
|
| 383 |
+
self.run_name = os.path.basename(self.run_dir)
|
| 384 |
+
self.log = RunLog(self.run_dir, manifest)
|
| 385 |
+
self.ev = self.log.ev
|
| 386 |
+
self.start = self.log.start
|
| 387 |
+
cp = os.path.join(self.run_dir, "contract.json")
|
| 388 |
+
self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {}
|
| 389 |
+
spec = self.contract.get("image_spec") or {}
|
| 390 |
+
self.image_res = int(spec.get("width", 512))
|
| 391 |
+
self.code_diff = check_code(self.run_dir)
|
| 392 |
+
s = self.start
|
| 393 |
+
self.task = TASKS[s["task"]](cam_res=self.image_res)
|
| 394 |
+
inst = self.task.sample_instance(s["seed"])
|
| 395 |
+
logged = s.get("inst") or {}
|
| 396 |
+
sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")})
|
| 397 |
+
self.inst_diff = diff_json(sampled, logged, "inst")
|
| 398 |
+
if s.get("arm", "none") not in (None, "none") or logged.get("nominal"):
|
| 399 |
+
inst.update(logged) # controlled arms / nominal: the server overrode these instance fields
|
| 400 |
+
self.inst_diff = []
|
| 401 |
+
self.inst = inst
|
| 402 |
+
self.protocol = getattr(self.task, "protocol", "cross")
|
| 403 |
+
self.k = int(s.get("k") or self.task.max_attempts)
|
| 404 |
+
self.attempt = 1
|
| 405 |
+
self.mismatch = [] # (where, what, logged, replayed)
|
| 406 |
+
self.n_checked = 0
|
| 407 |
+
self.max_dev_m = 0.0
|
| 408 |
+
self.unfinished = None
|
| 409 |
+
self.rec = Recorder(self, res) if record else None
|
| 410 |
+
self.res = int(res)
|
| 411 |
+
self.out_root = out_root
|
| 412 |
+
self.n_mon = 0
|
| 413 |
+
self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0
|
| 414 |
+
self.episodes = [] # summaries of the written episodes
|
| 415 |
+
self.task.reset_instance(self.inst)
|
| 416 |
+
self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
|
| 417 |
+
sim = self.task.env.sim
|
| 418 |
+
bid = sim.model.body_name2id("robot0_base")
|
| 419 |
+
self.base_off = np.array(sim.data.body_xpos[bid], float).copy()
|
| 420 |
+
if self.rec:
|
| 421 |
+
self._open_episode()
|
| 422 |
+
|
| 423 |
+
# ------------------------------------------------------------------ episodes
|
| 424 |
+
def _ep_dir(self):
|
| 425 |
+
return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}")
|
| 426 |
+
|
| 427 |
+
def _open_episode(self):
|
| 428 |
+
self.rec.sink = EpisodeSink(self._ep_dir())
|
| 429 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
|
| 430 |
+
self.rec.active = True
|
| 431 |
+
self.events, self.spans, self.ep_attempts = [], [], []
|
| 432 |
+
self.ep_initial = self.rec.state() # state right after the reset (before frame 0)
|
| 433 |
+
|
| 434 |
+
def close_episode(self):
|
| 435 |
+
if not self.rec:
|
| 436 |
+
self.ep_attempts = []
|
| 437 |
+
return
|
| 438 |
+
sink = self.rec.sink
|
| 439 |
+
st = self.rec.state()
|
| 440 |
+
imgs = self.rec.images()
|
| 441 |
+
st.pop("sim_state", None)
|
| 442 |
+
sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs)
|
| 443 |
+
ann = build_annotation(self, sink)
|
| 444 |
+
with open(os.path.join(sink.path, "annotation.json"), "w") as f:
|
| 445 |
+
json.dump(ann, f, indent=1, default=_json_default)
|
| 446 |
+
self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n,
|
| 447 |
+
attempts=[a["attempt"] for a in self.ep_attempts]))
|
| 448 |
+
self.rec.active = False
|
| 449 |
+
self.rec.sink = None
|
| 450 |
+
self.ep_index += 1
|
| 451 |
+
|
| 452 |
+
# ------------------------------------------------------------------ monitor events (task-side error events)
|
| 453 |
+
def poll_events(self, frame):
|
| 454 |
+
mon = getattr(self.task, "mon", None)
|
| 455 |
+
evs = mon.get("events") if isinstance(mon, dict) else None
|
| 456 |
+
if not isinstance(evs, list):
|
| 457 |
+
return
|
| 458 |
+
if len(evs) < self.n_mon: # monitor was rebuilt
|
| 459 |
+
self.n_mon = 0
|
| 460 |
+
for e in evs[self.n_mon:]:
|
| 461 |
+
self.events.append(dict(frame=int(frame), attempt=self.attempt,
|
| 462 |
+
event=norm_json(e) if isinstance(e, dict) else str(e)))
|
| 463 |
+
self.n_mon = len(evs)
|
| 464 |
+
|
| 465 |
+
# ------------------------------------------------------------------ state as the server reports it
|
| 466 |
+
def proprio_la(self):
|
| 467 |
+
p = self.ex.proprio()
|
| 468 |
+
pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off]
|
| 469 |
+
return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"])
|
| 470 |
+
|
| 471 |
+
def compare(self, where, rep_logged, rep):
|
| 472 |
+
self.n_checked += 1
|
| 473 |
+
for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"):
|
| 474 |
+
if k not in rep_logged or k not in rep:
|
| 475 |
+
continue
|
| 476 |
+
a, b = rep_logged[k], rep[k]
|
| 477 |
+
if k == "eef_pos":
|
| 478 |
+
dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float))))
|
| 479 |
+
self.max_dev_m = max(self.max_dev_m, dev)
|
| 480 |
+
if dev > 1.5e-4:
|
| 481 |
+
self.mismatch.append((where, k, a, b))
|
| 482 |
+
elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4):
|
| 483 |
+
self.mismatch.append((where, k, a, b))
|
| 484 |
+
if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)):
|
| 485 |
+
self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok")))
|
| 486 |
+
|
| 487 |
+
def _span(self, e, f0, kind):
|
| 488 |
+
if self.rec:
|
| 489 |
+
self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0,
|
| 490 |
+
frame_end=self.rec.n))
|
| 491 |
+
|
| 492 |
+
# ------------------------------------------------------------------ commands (robot_server._handle_v2)
|
| 493 |
+
def move_eef(self, e):
|
| 494 |
+
args = e.get("args") or {}
|
| 495 |
+
where = f"a{e['attempt']}s{e['step']}"
|
| 496 |
+
logged = e.get("report") or {}
|
| 497 |
+
f0 = self.rec.n if self.rec else 0
|
| 498 |
+
p = self.ex.proprio()
|
| 499 |
+
if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}:
|
| 500 |
+
self._span(e, f0, "error")
|
| 501 |
+
return self.compare(where, logged, dict(ok=False))
|
| 502 |
+
off = self.base_off
|
| 503 |
+
try:
|
| 504 |
+
cur = np.asarray(p["eef_pos"], float) - off
|
| 505 |
+
tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
|
| 506 |
+
yaw = float(args.get("yaw", p["eef_yaw_deg"]))
|
| 507 |
+
speed = None if args.get("speed") in (None, "") else float(args["speed"])
|
| 508 |
+
except (TypeError, ValueError):
|
| 509 |
+
self._span(e, f0, "error")
|
| 510 |
+
return self.compare(where, logged, dict(ok=False))
|
| 511 |
+
grip = args.get("gripper")
|
| 512 |
+
if grip not in (None, "open", "close"):
|
| 513 |
+
self._span(e, f0, "error")
|
| 514 |
+
return self.compare(where, logged, dict(ok=False))
|
| 515 |
+
moving = any(k in args for k in ("x", "y", "z", "yaw"))
|
| 516 |
+
tgt_w = np.asarray(tgt) + off
|
| 517 |
+
if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)):
|
| 518 |
+
self._span(e, f0, "rejected")
|
| 519 |
+
return self.compare(where, logged, dict(ok=False, **self.proprio_la()))
|
| 520 |
+
raw = {}
|
| 521 |
+
if self.rec:
|
| 522 |
+
self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"])
|
| 523 |
+
if moving:
|
| 524 |
+
mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw)
|
| 525 |
+
if speed is not None:
|
| 526 |
+
mv["speed"] = speed
|
| 527 |
+
raw.update(self.ex.call("move_to", mv).report)
|
| 528 |
+
if grip is not None:
|
| 529 |
+
if self.rec:
|
| 530 |
+
self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"])
|
| 531 |
+
raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report)
|
| 532 |
+
rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la())
|
| 533 |
+
self.compare(where, logged, rep)
|
| 534 |
+
lr = e.get("raw") or {}
|
| 535 |
+
for k in ("holding_object", "touched_object"):
|
| 536 |
+
if k in lr and k in raw and bool(lr[k]) != bool(raw[k]):
|
| 537 |
+
self.mismatch.append((where, "raw." + k, lr[k], raw[k]))
|
| 538 |
+
self._span(e, f0, "move_eef")
|
| 539 |
+
|
| 540 |
+
def observe(self, e):
|
| 541 |
+
f0 = self.rec.n if self.rec else 0
|
| 542 |
+
self._span(e, f0, "observe")
|
| 543 |
+
|
| 544 |
+
def done(self, e):
|
| 545 |
+
f0 = self.rec.n if self.rec else 0
|
| 546 |
+
if self.rec:
|
| 547 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"])
|
| 548 |
+
out = self.task.outcome(self.inst)
|
| 549 |
+
succ = bool(out["success"])
|
| 550 |
+
where = f"a{e['attempt']}done"
|
| 551 |
+
if succ != bool(e.get("success") in (True, "True")):
|
| 552 |
+
self.mismatch.append((where, "success", e.get("success"), succ))
|
| 553 |
+
lo = e.get("outcome") or {}
|
| 554 |
+
ro = norm_json({k: v for k, v in out.items() if k != "feedback"})
|
| 555 |
+
if isinstance(lo, dict):
|
| 556 |
+
for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8):
|
| 557 |
+
self.mismatch.append((where,) + d)
|
| 558 |
+
info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""),
|
| 559 |
+
feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")),
|
| 560 |
+
think_s=e.get("think_s"))
|
| 561 |
+
try:
|
| 562 |
+
info["feedback_f2"] = self.task.feedback(self.inst, out, "F2")
|
| 563 |
+
except Exception as ex_:
|
| 564 |
+
info["feedback_f2"] = f"<unavailable: {type(ex_).__name__}>"
|
| 565 |
+
if self.rec:
|
| 566 |
+
info["judge_frames"] = [f0, self.rec.n]
|
| 567 |
+
self.ep_attempts.append(info)
|
| 568 |
+
last = self.attempt >= self.k or succ or bool(out.get("terminal"))
|
| 569 |
+
if self.protocol == "cross" or last:
|
| 570 |
+
self.close_episode()
|
| 571 |
+
if last:
|
| 572 |
+
return True
|
| 573 |
+
self.attempt += 1
|
| 574 |
+
if self.protocol == "cross":
|
| 575 |
+
self.task.reset_instance(self.inst)
|
| 576 |
+
self.n_mon = 0
|
| 577 |
+
if self.rec:
|
| 578 |
+
self._open_episode()
|
| 579 |
+
elif self.rec:
|
| 580 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
|
| 581 |
+
self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
|
| 582 |
+
return False
|
| 583 |
+
|
| 584 |
+
def run(self):
|
| 585 |
+
t0 = time.time()
|
| 586 |
+
finished = False
|
| 587 |
+
for e in self.ev:
|
| 588 |
+
if e["ev"] == "call":
|
| 589 |
+
if e.get("cmd") == "move_eef":
|
| 590 |
+
self.move_eef(e)
|
| 591 |
+
elif e.get("cmd") == "observe":
|
| 592 |
+
self.observe(e)
|
| 593 |
+
else:
|
| 594 |
+
self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None))
|
| 595 |
+
elif e["ev"] == "done":
|
| 596 |
+
finished = self.done(e)
|
| 597 |
+
if finished:
|
| 598 |
+
break
|
| 599 |
+
self.unfinished = not finished
|
| 600 |
+
if not finished and self.rec and self.rec.sink is not None:
|
| 601 |
+
# the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged
|
| 602 |
+
if self.rec.n or self.ep_attempts:
|
| 603 |
+
self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True,
|
| 604 |
+
finish_reason="", feedback_shown="", auto_ended=False))
|
| 605 |
+
self.close_episode()
|
| 606 |
+
else:
|
| 607 |
+
shutil.rmtree(self.rec.sink.path, ignore_errors=True)
|
| 608 |
+
self.rec.sink = None
|
| 609 |
+
self.wall_s = time.time() - t0
|
| 610 |
+
return self
|
| 611 |
+
|
| 612 |
+
def summary(self):
|
| 613 |
+
return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"],
|
| 614 |
+
protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff),
|
| 615 |
+
n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6),
|
| 616 |
+
unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1),
|
| 617 |
+
first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]])
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
# ====================================================================================================== annotation
|
| 621 |
+
|
| 622 |
+
def task_info(task, inst):
|
| 623 |
+
cls = type(task)
|
| 624 |
+
return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable",
|
| 625 |
+
category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"),
|
| 626 |
+
max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)),
|
| 627 |
+
instruction=cls.instruction)
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
def build_annotation(rp, sink):
|
| 631 |
+
"""Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2
|
| 632 |
+
failure description), run-level outcome class, every robot command with its frame span and the agent's narration,
|
| 633 |
+
task-side error events with frame indices."""
|
| 634 |
+
log = rp.log
|
| 635 |
+
s = rp.start
|
| 636 |
+
cond, chain = log.condition()
|
| 637 |
+
cls, hist = log.outcome_class()
|
| 638 |
+
att_all = log.attempts()
|
| 639 |
+
attempts = []
|
| 640 |
+
for a in rp.ep_attempts:
|
| 641 |
+
a = dict(a)
|
| 642 |
+
n = a["attempt"]
|
| 643 |
+
later = [x for x in att_all if x["attempt"] > n]
|
| 644 |
+
a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later))
|
| 645 |
+
a["is_last_attempt_of_run"] = not later
|
| 646 |
+
fn = log.finish_notes.get(n)
|
| 647 |
+
if fn:
|
| 648 |
+
a["agent_finish"] = fn
|
| 649 |
+
a["error_event_in_attempt"] = error_event(a.get("outcome"))
|
| 650 |
+
attempts.append(a)
|
| 651 |
+
# post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command)
|
| 652 |
+
for a in attempts:
|
| 653 |
+
nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1])
|
| 654 |
+
if a.get("success") is False and nxt:
|
| 655 |
+
note = log.notes[nxt[0]]
|
| 656 |
+
a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note}
|
| 657 |
+
commands = []
|
| 658 |
+
for sp in rp.spans:
|
| 659 |
+
e = log.calls.get((sp["attempt"], sp["step"])) or {}
|
| 660 |
+
rep = e.get("report") or {}
|
| 661 |
+
c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"],
|
| 662 |
+
frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]),
|
| 663 |
+
args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"),
|
| 664 |
+
stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"),
|
| 665 |
+
gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"),
|
| 666 |
+
touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"),
|
| 667 |
+
agent_obs_images=rep.get("images"))
|
| 668 |
+
note = log.notes.get((sp["attempt"], sp["step"]))
|
| 669 |
+
if note:
|
| 670 |
+
c["agent_note"] = {k: v for k, v in note.items() if k != "command"}
|
| 671 |
+
commands.append(c)
|
| 672 |
+
t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x]
|
| 673 |
+
return dict(
|
| 674 |
+
schema=SCHEMA,
|
| 675 |
+
source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts],
|
| 676 |
+
episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain,
|
| 677 |
+
memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None),
|
| 678 |
+
feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"),
|
| 679 |
+
k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"),
|
| 680 |
+
contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256")
|
| 681 |
+
if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)),
|
| 682 |
+
agent=log.agent_info(),
|
| 683 |
+
task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"),
|
| 684 |
+
instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}),
|
| 685 |
+
run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all),
|
| 686 |
+
run_success=any(x["success"] for x in att_all) if att_all else None,
|
| 687 |
+
agent_final_report=log.final_report[:6000] or None,
|
| 688 |
+
mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)),
|
| 689 |
+
attempts=attempts,
|
| 690 |
+
commands=commands,
|
| 691 |
+
task_events=rp.events,
|
| 692 |
+
frames=dict(n=sink.n, fps=FPS, image_res=rp.res,
|
| 693 |
+
phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"],
|
| 694 |
+
joint_pos=rp.ep_initial["joint_pos"],
|
| 695 |
+
gripper_qpos=rp.ep_initial["gripper_qpos"])),
|
| 696 |
+
)
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
# ====================================================================================================== CLI
|
| 700 |
+
|
| 701 |
+
def load_manifest(run_dir):
|
| 702 |
+
p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json")
|
| 703 |
+
return json.load(open(p)) if os.path.exists(p) else {}
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
def main():
|
| 707 |
+
ap = argparse.ArgumentParser()
|
| 708 |
+
ap.add_argument("mode", choices=["check", "record"])
|
| 709 |
+
ap.add_argument("runs", nargs="+")
|
| 710 |
+
ap.add_argument("--json", default="")
|
| 711 |
+
ap.add_argument("--out", default="")
|
| 712 |
+
ap.add_argument("--res", type=int, default=256)
|
| 713 |
+
ap.add_argument("--force", action="store_true", help="record again even if replay.json exists")
|
| 714 |
+
a = ap.parse_args()
|
| 715 |
+
rows = []
|
| 716 |
+
for r in a.runs:
|
| 717 |
+
r = r.rstrip("/")
|
| 718 |
+
try:
|
| 719 |
+
if a.mode == "check":
|
| 720 |
+
s = RunReplay(r, manifest=load_manifest(r)).run().summary()
|
| 721 |
+
else:
|
| 722 |
+
batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r)
|
| 723 |
+
rd = os.path.join(a.out, batch, name)
|
| 724 |
+
if os.path.exists(os.path.join(rd, "replay.json")) and not a.force:
|
| 725 |
+
print(json.dumps(dict(run=name, skipped="exists")), flush=True)
|
| 726 |
+
continue
|
| 727 |
+
shutil.rmtree(rd, ignore_errors=True)
|
| 728 |
+
rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run()
|
| 729 |
+
s = rp.summary()
|
| 730 |
+
s["episodes"] = rp.episodes
|
| 731 |
+
with open(os.path.join(rd, "replay.json"), "w") as f:
|
| 732 |
+
json.dump(s, f, indent=1)
|
| 733 |
+
except Exception:
|
| 734 |
+
import traceback
|
| 735 |
+
s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:])
|
| 736 |
+
rows.append(s)
|
| 737 |
+
print(json.dumps(s), flush=True)
|
| 738 |
+
if a.json:
|
| 739 |
+
with open(a.json, "w") as f:
|
| 740 |
+
json.dump(rows, f, indent=1)
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
if __name__ == "__main__":
|
| 744 |
+
main()
|
leaf/code/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lerobot_export.py
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars.
|
| 2 |
+
|
| 3 |
+
Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding
|
| 4 |
+
can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan):
|
| 5 |
+
|
| 6 |
+
python scripts/lerobot_export.py plan --raw <raw_root>[,<raw_root2>] --runs-root <lffbench>/runs/api \
|
| 7 |
+
--paper <paper/latex> --task-set <lffbench>/sets/main_v2_1inst.txt --work <work_dir> [--batches ...] [--limit N]
|
| 8 |
+
python scripts/lerobot_export.py shard --work <work_dir> --shard i --nshards N
|
| 9 |
+
python scripts/lerobot_export.py merge --work <work_dir> --nshards N --out <dataset_root>
|
| 10 |
+
|
| 11 |
+
Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0
|
| 12 |
+
mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped.
|
| 13 |
+
|
| 14 |
+
LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t):
|
| 15 |
+
observation.images.image agentview RGB 256x256 (upright; LIBERO naming)
|
| 16 |
+
observation.images.wrist_image wrist (eye-in-hand) RGB 256x256
|
| 17 |
+
observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout)
|
| 18 |
+
observation.joint_pos / joint_vel 7 arm joints (rad, rad/s)
|
| 19 |
+
observation.eef_quat 4: xyzw; observation.gripper_width 1 (m)
|
| 20 |
+
action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad),
|
| 21 |
+
gripper (-1 open, +1 close)
|
| 22 |
+
annotation.attempt_index attempt (1-based) the frame belongs to
|
| 23 |
+
annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`)
|
| 24 |
+
annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action)
|
| 25 |
+
annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt
|
| 26 |
+
annotation.task_event number of task-monitor events (error / progress events) registered at this step
|
| 27 |
+
Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table),
|
| 28 |
+
runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state
|
| 29 |
+
per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/.
|
| 30 |
+
"""
|
| 31 |
+
import argparse
|
| 32 |
+
import glob
|
| 33 |
+
import json
|
| 34 |
+
import os
|
| 35 |
+
import re
|
| 36 |
+
import shutil
|
| 37 |
+
import time
|
| 38 |
+
|
| 39 |
+
import numpy as np
|
| 40 |
+
|
| 41 |
+
FPS = 20
|
| 42 |
+
RES = 256
|
| 43 |
+
BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke",
|
| 44 |
+
"cc_smoke", "cc_opus_smoke"]
|
| 45 |
+
BATCH_NOTES = {
|
| 46 |
+
"cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog",
|
| 47 |
+
"cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267",
|
| 48 |
+
"cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299",
|
| 49 |
+
"cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances",
|
| 50 |
+
"cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)",
|
| 51 |
+
"cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the "
|
| 52 |
+
"with-history continuation of failed runs is incomplete",
|
| 53 |
+
"cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early",
|
| 54 |
+
"cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt",
|
| 55 |
+
"cc_opus_smoke": "smoke test: single attempt",
|
| 56 |
+
}
|
| 57 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 58 |
+
CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)",
|
| 59 |
+
"L2": "disturbed state to restore (incl. damage the agent causes)",
|
| 60 |
+
"L3": "infeasible manipulation strategy (grasp / contact / tool must change)",
|
| 61 |
+
"L4": "misjudged geometry (size, shape, fit, hidden structure)",
|
| 62 |
+
"L5": "misjudged physics (mass distribution, friction, dynamics)"}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def features():
|
| 66 |
+
vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]}
|
| 67 |
+
f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names}
|
| 68 |
+
i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None}
|
| 69 |
+
return {
|
| 70 |
+
"observation.images.image": vid(),
|
| 71 |
+
"observation.images.wrist_image": vid(),
|
| 72 |
+
"observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z",
|
| 73 |
+
"finger_qpos_left", "finger_qpos_right"]),
|
| 74 |
+
"observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 75 |
+
"observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 76 |
+
"observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]),
|
| 77 |
+
"observation.gripper_width": f32(1, ["width_m"]),
|
| 78 |
+
"action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y",
|
| 79 |
+
"eef_delta_rot_aa_z", "gripper_close"]),
|
| 80 |
+
"annotation.attempt_index": i64(),
|
| 81 |
+
"annotation.command_index": i64(),
|
| 82 |
+
"annotation.phase": i64(),
|
| 83 |
+
"annotation.attempt_success": i64(),
|
| 84 |
+
"annotation.task_event": i64(),
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ------------------------------------------------------------------------------------------------ paper metadata
|
| 89 |
+
|
| 90 |
+
def _clean_tex(s):
|
| 91 |
+
s = re.sub(r"%.*", "", s)
|
| 92 |
+
for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"),
|
| 93 |
+
(r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"),
|
| 94 |
+
(r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"),
|
| 95 |
+
(r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"),
|
| 96 |
+
(r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]:
|
| 97 |
+
s = re.sub(a, b, s)
|
| 98 |
+
s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s)
|
| 99 |
+
s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s)
|
| 100 |
+
for _ in range(3):
|
| 101 |
+
s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s)
|
| 102 |
+
s = re.sub(r"\$([^$]*)\$", r"\1", s)
|
| 103 |
+
s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ")
|
| 104 |
+
s = re.sub(r"\{([^{}]*)\}", r"\1", s)
|
| 105 |
+
s = re.sub(r"\\[a-zA-Z]+\*?", "", s)
|
| 106 |
+
return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def paper_tasks(paper_dir):
|
| 110 |
+
"""{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the
|
| 111 |
+
paper's task table and task appendix (empty if the paper sources are not there)."""
|
| 112 |
+
out = {}
|
| 113 |
+
if not paper_dir:
|
| 114 |
+
return out
|
| 115 |
+
app = os.path.join(paper_dir, "sections", "appendix_tasks.tex")
|
| 116 |
+
tab = os.path.join(paper_dir, "sections", "tab_tasks.tex")
|
| 117 |
+
if os.path.exists(app):
|
| 118 |
+
txt = open(app).read()
|
| 119 |
+
parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt)
|
| 120 |
+
for i in range(1, len(parts) - 1, 2):
|
| 121 |
+
if parts[i] != "\\paragraph{":
|
| 122 |
+
continue
|
| 123 |
+
body = parts[i + 1]
|
| 124 |
+
m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S)
|
| 125 |
+
if not m:
|
| 126 |
+
continue
|
| 127 |
+
name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip()
|
| 128 |
+
desc = _clean_tex(body[m.end():])
|
| 129 |
+
out[code] = dict(name=name, cause=_clean_tex(cause), description=desc)
|
| 130 |
+
if os.path.exists(tab):
|
| 131 |
+
names = {v["name"].lower(): k for k, v in out.items()}
|
| 132 |
+
for line in open(tab):
|
| 133 |
+
cells = [c.strip() for c in line.split("&")]
|
| 134 |
+
if len(cells) != 6 or not cells[-1].endswith("\\\\"):
|
| 135 |
+
continue
|
| 136 |
+
nm = re.sub(r"\\contscene", "", cells[0]).strip().lower()
|
| 137 |
+
code = names.get(nm)
|
| 138 |
+
if not code:
|
| 139 |
+
continue
|
| 140 |
+
out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]),
|
| 141 |
+
repair_within_attempt=_clean_tex(cells[3]) == "yes",
|
| 142 |
+
oracle_first_attempt_pct=_clean_tex(cells[4]),
|
| 143 |
+
naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip()))
|
| 144 |
+
return out
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
# ------------------------------------------------------------------------------------------------ collection
|
| 148 |
+
|
| 149 |
+
def manifest_status(runs_root, batch, run, cache={}):
|
| 150 |
+
if batch not in cache:
|
| 151 |
+
p = os.path.join(runs_root, batch, "manifest.json")
|
| 152 |
+
cache[batch] = json.load(open(p)) if os.path.exists(p) else {}
|
| 153 |
+
m = cache[batch]
|
| 154 |
+
for r in m.get("runs", []):
|
| 155 |
+
if r.get("run") == run:
|
| 156 |
+
return r.get("status", "?"), r
|
| 157 |
+
for r in m.get("superseded", []):
|
| 158 |
+
if r.get("run") == run:
|
| 159 |
+
return "superseded_" + str(r.get("status", "?")), r
|
| 160 |
+
return "not_in_manifest", {}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def collect(raw_roots, runs_root, batches, task_order):
|
| 164 |
+
"""Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root."""
|
| 165 |
+
eps, rejected, seen = [], [], set()
|
| 166 |
+
for root in raw_roots:
|
| 167 |
+
for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))):
|
| 168 |
+
rep = json.load(open(rj))
|
| 169 |
+
batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"]
|
| 170 |
+
if (batches and batch not in batches) or (batch, run) in seen:
|
| 171 |
+
continue
|
| 172 |
+
seen.add((batch, run))
|
| 173 |
+
ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff")
|
| 174 |
+
status, entry = manifest_status(runs_root, batch, run)
|
| 175 |
+
if not ok:
|
| 176 |
+
never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked")
|
| 177 |
+
rejected.append(dict(run=run, batch=batch, run_status=status,
|
| 178 |
+
reason="run never started (no contract, no robot command)" if never else
|
| 179 |
+
"replay does not reproduce the log (the log has gaps or the replay diverged)",
|
| 180 |
+
detail=rep.get("first_mismatches")))
|
| 181 |
+
continue
|
| 182 |
+
for ep in rep.get("episodes", []):
|
| 183 |
+
d = os.path.join(root, ep["dir"])
|
| 184 |
+
ann = json.load(open(os.path.join(d, "annotation.json")))
|
| 185 |
+
judged = [a for a in ann["attempts"] if a.get("success") is not None]
|
| 186 |
+
if not judged or ep["n_frames"] == 0:
|
| 187 |
+
rejected.append(dict(run=run, batch=batch, episode=ep["dir"],
|
| 188 |
+
reason="no judged attempt" if not judged else "no frames"))
|
| 189 |
+
continue
|
| 190 |
+
ann["source"]["run_status"] = status
|
| 191 |
+
ann["source"]["manifest_id"] = entry.get("id")
|
| 192 |
+
ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"],
|
| 193 |
+
max_eef_dev_m=rep["max_eef_dev_m"])
|
| 194 |
+
key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99),
|
| 195 |
+
{"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2),
|
| 196 |
+
ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"])
|
| 197 |
+
eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann))
|
| 198 |
+
eps.sort(key=lambda x: x["key"])
|
| 199 |
+
return eps, rejected
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# ------------------------------------------------------------------------------------------------ writing
|
| 203 |
+
|
| 204 |
+
def frames_of(path):
|
| 205 |
+
import av
|
| 206 |
+
with av.open(path) as c:
|
| 207 |
+
for fr in c.decode(video=0):
|
| 208 |
+
yield fr.to_ndarray(format="rgb24")
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def flat_row(i, ann, n, idx0):
|
| 212 |
+
s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"]
|
| 213 |
+
att = ann["attempts"]
|
| 214 |
+
a0 = att[0]
|
| 215 |
+
return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n,
|
| 216 |
+
batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"],
|
| 217 |
+
memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"),
|
| 218 |
+
episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att],
|
| 219 |
+
harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"),
|
| 220 |
+
effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"),
|
| 221 |
+
task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"),
|
| 222 |
+
category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"],
|
| 223 |
+
success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att],
|
| 224 |
+
feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att],
|
| 225 |
+
auto_ended=[a.get("auto_ended") for a in att],
|
| 226 |
+
corrected_later_in_run=[a.get("corrected_later_in_run") for a in att],
|
| 227 |
+
error_event_in_attempt=[a.get("error_event_in_attempt") for a in att],
|
| 228 |
+
run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"),
|
| 229 |
+
n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]),
|
| 230 |
+
first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def cmd_plan(a):
|
| 234 |
+
task_order = {}
|
| 235 |
+
if a.task_set and os.path.exists(a.task_set):
|
| 236 |
+
for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")):
|
| 237 |
+
task_order[line.split(":")[0].strip()] = i
|
| 238 |
+
batches = [b for b in a.batches.split(",") if b] if a.batches else None
|
| 239 |
+
eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order)
|
| 240 |
+
if a.limit:
|
| 241 |
+
eps = eps[:a.limit]
|
| 242 |
+
paper = paper_tasks(a.paper)
|
| 243 |
+
idx0 = 0
|
| 244 |
+
for i, e in enumerate(eps):
|
| 245 |
+
ann = e["ann"]
|
| 246 |
+
tname = ann["task"]["name"]
|
| 247 |
+
if tname in paper:
|
| 248 |
+
ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"}
|
| 249 |
+
ann["episode_index"] = i
|
| 250 |
+
ann["dataset_index_range"] = [idx0, idx0 + e["n"]]
|
| 251 |
+
e["index"], e["from"] = i, idx0
|
| 252 |
+
idx0 += e["n"]
|
| 253 |
+
del e["key"]
|
| 254 |
+
os.makedirs(a.work, exist_ok=True)
|
| 255 |
+
with open(os.path.join(a.work, "plan.json"), "w") as f:
|
| 256 |
+
json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f,
|
| 257 |
+
ensure_ascii=False)
|
| 258 |
+
print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def shard_range(n_eps, i, k):
|
| 262 |
+
return (n_eps * i) // k, (n_eps * (i + 1)) // k
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def cmd_shard(a):
|
| 266 |
+
from lerobot.datasets.lerobot_dataset import LeRobotDataset
|
| 267 |
+
t0 = time.time()
|
| 268 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 269 |
+
eps = plan["episodes"]
|
| 270 |
+
lo, hi = shard_range(len(eps), a.shard, a.nshards)
|
| 271 |
+
out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}")
|
| 272 |
+
if os.path.exists(os.path.join(out, "DONE")):
|
| 273 |
+
print(f"shard {a.shard}: done already", flush=True)
|
| 274 |
+
return
|
| 275 |
+
shutil.rmtree(out, ignore_errors=True)
|
| 276 |
+
ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out,
|
| 277 |
+
robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads,
|
| 278 |
+
vcodec=a.vcodec)
|
| 279 |
+
nfr = 0
|
| 280 |
+
for e in eps[lo:hi]:
|
| 281 |
+
d, ann, n = e["dir"], e["ann"], e["n"]
|
| 282 |
+
fr = np.load(os.path.join(d, "frames.npz"))
|
| 283 |
+
assert len(fr["action"]) == n, d
|
| 284 |
+
succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]}
|
| 285 |
+
evc = np.zeros(n, np.int64)
|
| 286 |
+
for ev in ann["task_events"]:
|
| 287 |
+
if 0 <= ev["frame"] < n:
|
| 288 |
+
evc[ev["frame"]] += 1
|
| 289 |
+
state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32)
|
| 290 |
+
instr = ann["task"]["instruction"]
|
| 291 |
+
k = 0
|
| 292 |
+
for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))):
|
| 293 |
+
if k >= n:
|
| 294 |
+
break
|
| 295 |
+
ds.add_frame({
|
| 296 |
+
"observation.images.image": img, "observation.images.wrist_image": wr,
|
| 297 |
+
"observation.state": state[k],
|
| 298 |
+
"observation.joint_pos": fr["joint_pos"][k].astype(np.float32),
|
| 299 |
+
"observation.joint_vel": fr["joint_vel"][k].astype(np.float32),
|
| 300 |
+
"observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32),
|
| 301 |
+
"observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32),
|
| 302 |
+
"action": fr["action"][k].astype(np.float32),
|
| 303 |
+
"annotation.attempt_index": np.array([fr["attempt"][k]], np.int64),
|
| 304 |
+
"annotation.command_index": np.array([fr["command"][k]], np.int64),
|
| 305 |
+
"annotation.phase": np.array([fr["phase"][k]], np.int64),
|
| 306 |
+
"annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64),
|
| 307 |
+
"annotation.task_event": np.array([evc[k]], np.int64),
|
| 308 |
+
"task": instr,
|
| 309 |
+
})
|
| 310 |
+
k += 1
|
| 311 |
+
if k != n:
|
| 312 |
+
raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames")
|
| 313 |
+
ds.save_episode()
|
| 314 |
+
nfr += n
|
| 315 |
+
ds.finalize()
|
| 316 |
+
shutil.rmtree(os.path.join(out, "images"), ignore_errors=True)
|
| 317 |
+
open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n")
|
| 318 |
+
print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def cmd_merge(a):
|
| 322 |
+
from pathlib import Path
|
| 323 |
+
from lerobot.datasets.aggregate import aggregate_datasets
|
| 324 |
+
t0 = time.time()
|
| 325 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 326 |
+
eps = plan["episodes"]
|
| 327 |
+
roots, ids = [], []
|
| 328 |
+
for i in range(a.nshards):
|
| 329 |
+
lo, hi = shard_range(len(eps), i, a.nshards)
|
| 330 |
+
if hi <= lo:
|
| 331 |
+
continue
|
| 332 |
+
r = os.path.join(a.work, "shards", f"shard_{i:03d}")
|
| 333 |
+
if not os.path.exists(os.path.join(r, "DONE")):
|
| 334 |
+
raise SystemExit(f"shard {i} is not done")
|
| 335 |
+
roots.append(Path(r))
|
| 336 |
+
ids.append(f"{plan['repo_id']}-shard{i:03d}")
|
| 337 |
+
if os.path.exists(a.out):
|
| 338 |
+
raise SystemExit(f"{a.out} exists; refusing to overwrite")
|
| 339 |
+
aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out))
|
| 340 |
+
print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True)
|
| 341 |
+
write_sidecars(a, plan)
|
| 342 |
+
print(f"merge done in {time.time() - t0:.0f}s", flush=True)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def write_sidecars(a, plan):
|
| 346 |
+
eps, paper = plan["episodes"], plan["paper"]
|
| 347 |
+
lff = os.path.join(a.out, "lff")
|
| 348 |
+
for sub in ("annotations", "sim_state", "final", "code"):
|
| 349 |
+
os.makedirs(os.path.join(lff, sub), exist_ok=True)
|
| 350 |
+
rows, runs, tasks = [], {}, {}
|
| 351 |
+
for e in eps:
|
| 352 |
+
i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"]
|
| 353 |
+
name = f"episode_{i:06d}"
|
| 354 |
+
if os.path.exists(os.path.join(d, "sim_state.npy")):
|
| 355 |
+
shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy"))
|
| 356 |
+
shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz"))
|
| 357 |
+
for cam, key in (("agentview", "image"), ("wrist", "wrist_image")):
|
| 358 |
+
shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png"))
|
| 359 |
+
with open(os.path.join(lff, "annotations", name + ".json"), "w") as f:
|
| 360 |
+
json.dump(ann, f, indent=1, ensure_ascii=False)
|
| 361 |
+
rows.append(flat_row(i, ann, n, e["from"]))
|
| 362 |
+
tname = ann["task"]["name"]
|
| 363 |
+
rk = (ann["source"]["batch"], ann["source"]["run"])
|
| 364 |
+
r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"),
|
| 365 |
+
run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"],
|
| 366 |
+
memory_free_chain_of=ann["source"].get("memory_free_chain_of"),
|
| 367 |
+
memory_free_rep=ann["source"].get("memory_free_rep"), task=tname,
|
| 368 |
+
seed=ann["task"]["seed"], model=ann["agent"].get("model"),
|
| 369 |
+
harness=ann["agent"].get("harness"),
|
| 370 |
+
harness_version=ann["agent"].get("harness_version"),
|
| 371 |
+
codex_catalog=ann["agent"].get("codex_catalog"),
|
| 372 |
+
outcome_class=ann["run_outcome"].get("outcome_class"),
|
| 373 |
+
attempt_history=ann["run_outcome"].get("attempt_history"),
|
| 374 |
+
agent_final_report=ann["run_outcome"].get("agent_final_report"),
|
| 375 |
+
episodes=[]))
|
| 376 |
+
for x in ann["attempts"]:
|
| 377 |
+
r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success")))
|
| 378 |
+
if tname not in tasks:
|
| 379 |
+
tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")}
|
| 380 |
+
if tname in paper:
|
| 381 |
+
tasks[tname]["paper"] = paper[tname]
|
| 382 |
+
tasks[tname]["instances"] = {}
|
| 383 |
+
tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"]
|
| 384 |
+
# memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id)
|
| 385 |
+
by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")}
|
| 386 |
+
for r in runs.values():
|
| 387 |
+
if r.get("memory_free_chain_of"):
|
| 388 |
+
r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"]))
|
| 389 |
+
for (b, rn), r in runs.items():
|
| 390 |
+
r["memory_free_retries"] = sorted((x["run"] for x in runs.values()
|
| 391 |
+
if x["batch"] == b and x.get("memory_free_chain_of_run") == rn),
|
| 392 |
+
key=lambda q: runs[(b, q)].get("memory_free_rep") or 0)
|
| 393 |
+
with open(os.path.join(lff, "episodes.jsonl"), "w") as f:
|
| 394 |
+
for row in rows:
|
| 395 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 396 |
+
with open(os.path.join(lff, "runs.jsonl"), "w") as f:
|
| 397 |
+
for r in runs.values():
|
| 398 |
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 399 |
+
with open(os.path.join(lff, "tasks.json"), "w") as f:
|
| 400 |
+
json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False)
|
| 401 |
+
with open(os.path.join(lff, "batches.json"), "w") as f:
|
| 402 |
+
json.dump(BATCH_NOTES, f, indent=1)
|
| 403 |
+
with open(os.path.join(lff, "rejected.json"), "w") as f:
|
| 404 |
+
json.dump(plan["rejected"], f, indent=1)
|
| 405 |
+
here = os.path.dirname(os.path.abspath(__file__))
|
| 406 |
+
for s in ("lerobot_replay.py", "lerobot_export.py"):
|
| 407 |
+
shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s))
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def main():
|
| 411 |
+
ap = argparse.ArgumentParser()
|
| 412 |
+
ap.add_argument("step", choices=["plan", "shard", "merge"])
|
| 413 |
+
ap.add_argument("--work", required=True)
|
| 414 |
+
ap.add_argument("--raw", default="")
|
| 415 |
+
ap.add_argument("--runs-root", default="")
|
| 416 |
+
ap.add_argument("--out", default="")
|
| 417 |
+
ap.add_argument("--paper", default="")
|
| 418 |
+
ap.add_argument("--task-set", default="")
|
| 419 |
+
ap.add_argument("--repo-id", default="lffbench/agent-replays")
|
| 420 |
+
ap.add_argument("--batches", default="")
|
| 421 |
+
ap.add_argument("--limit", type=int, default=0)
|
| 422 |
+
ap.add_argument("--shard", type=int, default=0)
|
| 423 |
+
ap.add_argument("--nshards", type=int, default=1)
|
| 424 |
+
ap.add_argument("--threads", type=int, default=2)
|
| 425 |
+
ap.add_argument("--vcodec", default="libsvtav1")
|
| 426 |
+
a = ap.parse_args()
|
| 427 |
+
{"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
if __name__ == "__main__":
|
| 431 |
+
main()
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay
|
| 2 |
+
against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the
|
| 3 |
+
LeRobot export (scripts/lerobot_export.py).
|
| 4 |
+
|
| 5 |
+
python scripts/lerobot_replay.py check <run_dir> [<run_dir> ...] [--json out.json] # replay only, print fidelity
|
| 6 |
+
python scripts/lerobot_replay.py record <run_dir> --out <raw_root> [--res 256]
|
| 7 |
+
|
| 8 |
+
Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot
|
| 9 |
+
commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite
|
| 10 |
+
is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly
|
| 11 |
+
like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same
|
| 12 |
+
outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width,
|
| 13 |
+
ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code
|
| 14 |
+
hashes equal the current files are expected to match (check_code()).
|
| 15 |
+
|
| 16 |
+
Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB,
|
| 17 |
+
proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes:
|
| 18 |
+
protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode
|
| 19 |
+
per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the
|
| 20 |
+
fidelity check runs in record mode too. Per episode the recorder writes <raw_root>/<batch>/<run>/epNN/:
|
| 21 |
+
agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes)
|
| 22 |
+
frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase
|
| 23 |
+
sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel)
|
| 24 |
+
final_*.png, final.npz observation after the last control step (the state the outcome was judged in)
|
| 25 |
+
annotation.json episode annotation (build_annotation)
|
| 26 |
+
and <raw_root>/<batch>/<run>/replay.json (fidelity) when the whole run is done.
|
| 27 |
+
"""
|
| 28 |
+
import argparse
|
| 29 |
+
import ast
|
| 30 |
+
import hashlib
|
| 31 |
+
import importlib
|
| 32 |
+
import json
|
| 33 |
+
import math
|
| 34 |
+
import os
|
| 35 |
+
import pkgutil
|
| 36 |
+
import re
|
| 37 |
+
import shutil
|
| 38 |
+
import sys
|
| 39 |
+
import time
|
| 40 |
+
from collections import defaultdict
|
| 41 |
+
|
| 42 |
+
import numpy as np
|
| 43 |
+
|
| 44 |
+
LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 45 |
+
sys.path.insert(0, LFF_ROOT)
|
| 46 |
+
|
| 47 |
+
from lffbench import envs # noqa: E402
|
| 48 |
+
from lffbench import tasks as task_pkg # noqa: E402
|
| 49 |
+
from lffbench.agent import camera as C # noqa: E402
|
| 50 |
+
from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402
|
| 51 |
+
from lffbench.task_base import TASKS # noqa: E402
|
| 52 |
+
|
| 53 |
+
for _m in pkgutil.iter_modules(task_pkg.__path__):
|
| 54 |
+
importlib.import_module(f"lffbench.tasks.{_m.name}")
|
| 55 |
+
|
| 56 |
+
# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the
|
| 57 |
+
# task's outcome() check after `finish` (the arm holds still; not an agent action)
|
| 58 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 59 |
+
FPS = 20
|
| 60 |
+
SCHEMA = "lff-replay-1"
|
| 61 |
+
|
| 62 |
+
# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR"
|
| 63 |
+
ERROR_FLAGS = ("trap_fired", "recovered_in_attempt")
|
| 64 |
+
ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events",
|
| 65 |
+
"n_missed_strikes", "n_open_gripper_pushes")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def load_jsonl(p):
|
| 69 |
+
out = []
|
| 70 |
+
if not os.path.exists(p):
|
| 71 |
+
return out
|
| 72 |
+
with open(p) as f:
|
| 73 |
+
for line in f:
|
| 74 |
+
line = line.strip()
|
| 75 |
+
if line:
|
| 76 |
+
try:
|
| 77 |
+
out.append(json.loads(line))
|
| 78 |
+
except ValueError:
|
| 79 |
+
pass
|
| 80 |
+
return out
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def norm_json(o):
|
| 84 |
+
return json.loads(json.dumps(o, default=_json_default))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def sha256(p):
|
| 88 |
+
with open(p, "rb") as f:
|
| 89 |
+
return hashlib.sha256(f.read()).hexdigest()
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def check_code(run_dir):
|
| 93 |
+
"""[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract."""
|
| 94 |
+
p = os.path.join(run_dir, "contract.json")
|
| 95 |
+
if not os.path.exists(p):
|
| 96 |
+
return [("contract.json", None, None)]
|
| 97 |
+
files = json.load(open(p))["contract"].get("server_code_files", {})
|
| 98 |
+
bad = []
|
| 99 |
+
for f, h in files.items():
|
| 100 |
+
q = os.path.join(LFF_ROOT, f)
|
| 101 |
+
cur = sha256(q) if os.path.exists(q) else None
|
| 102 |
+
if cur != h:
|
| 103 |
+
bad.append((f, h, cur))
|
| 104 |
+
return bad
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def diff_json(a, b, path="", tol=0.0, out=None, limit=20):
|
| 108 |
+
"""Differences between two JSON values (numbers compared with an absolute tolerance)."""
|
| 109 |
+
out = [] if out is None else out
|
| 110 |
+
if len(out) >= limit:
|
| 111 |
+
return out
|
| 112 |
+
if isinstance(a, dict) and isinstance(b, dict):
|
| 113 |
+
for k in sorted(set(a) | set(b)):
|
| 114 |
+
if k not in a or k not in b:
|
| 115 |
+
out.append((f"{path}.{k}", a.get(k, "<missing>"), b.get(k, "<missing>")))
|
| 116 |
+
else:
|
| 117 |
+
diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit)
|
| 118 |
+
elif isinstance(a, list) and isinstance(b, list):
|
| 119 |
+
if len(a) != len(b):
|
| 120 |
+
out.append((path, f"len {len(a)}", f"len {len(b)}"))
|
| 121 |
+
else:
|
| 122 |
+
for i, (x, y) in enumerate(zip(a, b)):
|
| 123 |
+
diff_json(x, y, f"{path}[{i}]", tol, out, limit)
|
| 124 |
+
elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
|
| 125 |
+
if a != b:
|
| 126 |
+
out.append((path, a, b))
|
| 127 |
+
elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))):
|
| 128 |
+
out.append((path, a, b))
|
| 129 |
+
return out
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def error_event(o):
|
| 133 |
+
"""True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none."""
|
| 134 |
+
if not isinstance(o, dict):
|
| 135 |
+
return None
|
| 136 |
+
keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o]
|
| 137 |
+
if not keys:
|
| 138 |
+
return None
|
| 139 |
+
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)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# ====================================================================================================== logs -> notes
|
| 143 |
+
|
| 144 |
+
class RunLog:
|
| 145 |
+
"""Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's
|
| 146 |
+
narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition."""
|
| 147 |
+
|
| 148 |
+
def __init__(self, run_dir, manifest=None):
|
| 149 |
+
self.run_dir = os.path.abspath(run_dir.rstrip("/"))
|
| 150 |
+
self.run = os.path.basename(self.run_dir)
|
| 151 |
+
self.batch = os.path.basename(os.path.dirname(self.run_dir))
|
| 152 |
+
self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl"))
|
| 153 |
+
self.start = next(e for e in self.ev if e["ev"] == "session_start")
|
| 154 |
+
self.calls, self.dones, self.harness_status = {}, [], []
|
| 155 |
+
last = None
|
| 156 |
+
for e in self.ev:
|
| 157 |
+
if e["ev"] == "call":
|
| 158 |
+
self.calls[(int(e["attempt"]), int(e["step"]))] = e
|
| 159 |
+
last = e
|
| 160 |
+
elif e["ev"] == "done":
|
| 161 |
+
self.dones.append(e)
|
| 162 |
+
last = e
|
| 163 |
+
elif e["ev"] == "http" and last is not None and "think_s" not in last:
|
| 164 |
+
ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \
|
| 165 |
+
(last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe"))
|
| 166 |
+
if ok:
|
| 167 |
+
last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s")
|
| 168 |
+
self.manifest = manifest or {}
|
| 169 |
+
self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {}
|
| 170 |
+
p = os.path.join(self.run_dir, "harness.json")
|
| 171 |
+
self.harness = json.load(open(p)) if os.path.exists(p) else {}
|
| 172 |
+
self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl"))
|
| 173 |
+
self._narration()
|
| 174 |
+
|
| 175 |
+
# ---------------------------------------------------------------- agent narration
|
| 176 |
+
def _narration(self):
|
| 177 |
+
"""notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one;
|
| 178 |
+
finish_notes[attempt] likewise for the agent's finish call; final_report = its last message."""
|
| 179 |
+
self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", []
|
| 180 |
+
buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
|
| 181 |
+
attempt = 1
|
| 182 |
+
|
| 183 |
+
def take():
|
| 184 |
+
nonlocal buf
|
| 185 |
+
out = {k: v for k, v in buf.items() if v}
|
| 186 |
+
buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
|
| 187 |
+
return out
|
| 188 |
+
|
| 189 |
+
last_msg = ""
|
| 190 |
+
for t in self.traj:
|
| 191 |
+
if t.get("kind") == "header":
|
| 192 |
+
self.headers.append(t.get("agent") or {})
|
| 193 |
+
continue
|
| 194 |
+
if t.get("kind") != "step":
|
| 195 |
+
continue
|
| 196 |
+
if (t.get("message") or "").strip():
|
| 197 |
+
buf["messages"].append(t["message"].strip())
|
| 198 |
+
last_msg = t["message"].strip()
|
| 199 |
+
if (t.get("reasoning_content") or "").strip():
|
| 200 |
+
buf["reasoning"].append(t["reasoning_content"].strip())
|
| 201 |
+
res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])}
|
| 202 |
+
for c in t.get("tool_calls") or []:
|
| 203 |
+
fn, args = c.get("function_name"), c.get("arguments") or {}
|
| 204 |
+
if fn == "shell":
|
| 205 |
+
buf["shell"].append(str(args.get("command", ""))[:2000])
|
| 206 |
+
elif fn == "view_images":
|
| 207 |
+
buf["viewed"].extend(args.get("paths") or [])
|
| 208 |
+
elif fn == "robot":
|
| 209 |
+
cmd = str(args.get("command", "")).strip()
|
| 210 |
+
r = res.get(c.get("tool_call_id")) or {}
|
| 211 |
+
try:
|
| 212 |
+
rep = json.loads(r.get("content") or "{}")
|
| 213 |
+
except ValueError:
|
| 214 |
+
rep = {}
|
| 215 |
+
word = cmd.split()[0] if cmd else ""
|
| 216 |
+
m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", "")))
|
| 217 |
+
if word in ("move_eef", "observe") and m:
|
| 218 |
+
a, s = int(m.group(1)), int(m.group(2))
|
| 219 |
+
n = take()
|
| 220 |
+
n["command"] = cmd
|
| 221 |
+
self.notes[(a, s)] = n
|
| 222 |
+
attempt = a
|
| 223 |
+
elif word in ("finish", "done"):
|
| 224 |
+
n = take()
|
| 225 |
+
n["command"] = cmd
|
| 226 |
+
n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)}
|
| 227 |
+
self.finish_notes.setdefault(attempt, n)
|
| 228 |
+
if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"):
|
| 229 |
+
attempt += 1
|
| 230 |
+
# status / help / errors: their narration stays in the buffer for the next command
|
| 231 |
+
self.final_report = last_msg
|
| 232 |
+
|
| 233 |
+
# ---------------------------------------------------------------- run-level labels
|
| 234 |
+
def attempts(self):
|
| 235 |
+
out = []
|
| 236 |
+
for e in self.dones:
|
| 237 |
+
o = e.get("outcome") or {}
|
| 238 |
+
if isinstance(o, str):
|
| 239 |
+
try:
|
| 240 |
+
o = ast.literal_eval(o)
|
| 241 |
+
except (ValueError, SyntaxError):
|
| 242 |
+
o = {}
|
| 243 |
+
out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o,
|
| 244 |
+
reason=e.get("reason") or ""))
|
| 245 |
+
return sorted(out, key=lambda x: x["attempt"])
|
| 246 |
+
|
| 247 |
+
def condition(self):
|
| 248 |
+
s, en = self.start, self.entry
|
| 249 |
+
mem = s.get("memory", en.get("mem"))
|
| 250 |
+
chain = en.get("chain")
|
| 251 |
+
if mem == "full":
|
| 252 |
+
cond = "with_history"
|
| 253 |
+
elif chain:
|
| 254 |
+
cond = "memory_free_retry"
|
| 255 |
+
else:
|
| 256 |
+
cond = "independent_single_attempt"
|
| 257 |
+
return cond, chain
|
| 258 |
+
|
| 259 |
+
def outcome_class(self):
|
| 260 |
+
"""CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None."""
|
| 261 |
+
att = self.attempts()
|
| 262 |
+
if not att or self.start.get("memory") != "full":
|
| 263 |
+
return None, "".join("S" if a["success"] else "F" for a in att)
|
| 264 |
+
hist = "".join("S" if a["success"] else "F" for a in att)
|
| 265 |
+
if att[0]["success"]:
|
| 266 |
+
ev = error_event(att[0]["outcome"])
|
| 267 |
+
cls = "S?" if ev is None else ("IR" if ev else "CS")
|
| 268 |
+
else:
|
| 269 |
+
cls = "XR" if any(a["success"] for a in att) else "F"
|
| 270 |
+
return cls, hist
|
| 271 |
+
|
| 272 |
+
def agent_info(self):
|
| 273 |
+
h, en = self.harness, self.entry
|
| 274 |
+
hdr = self.headers[0] if self.headers else {}
|
| 275 |
+
return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"),
|
| 276 |
+
harness_version=h.get("version") or hdr.get("version"),
|
| 277 |
+
harness_binary_sha256=(h.get("binary") or {}).get("sha256"),
|
| 278 |
+
model=h.get("model") or en.get("model") or hdr.get("model_name"),
|
| 279 |
+
effort=h.get("effort") or en.get("effort") or hdr.get("effort"),
|
| 280 |
+
provider=h.get("provider") or en.get("provider"),
|
| 281 |
+
codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"),
|
| 282 |
+
jail=en.get("jail"))
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
# ====================================================================================================== recording
|
| 286 |
+
|
| 287 |
+
class EpisodeSink:
|
| 288 |
+
"""Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed."""
|
| 289 |
+
|
| 290 |
+
def __init__(self, path):
|
| 291 |
+
self.path = path
|
| 292 |
+
os.makedirs(path, exist_ok=True)
|
| 293 |
+
self.w = None
|
| 294 |
+
self.num = defaultdict(list)
|
| 295 |
+
self.n = 0
|
| 296 |
+
|
| 297 |
+
def add(self, st, imgs):
|
| 298 |
+
import imageio
|
| 299 |
+
if self.w is None:
|
| 300 |
+
self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb",
|
| 301 |
+
pixelformat="rgb24", macro_block_size=1,
|
| 302 |
+
ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error")
|
| 303 |
+
for k in ("agentview", "wrist")]
|
| 304 |
+
for w, im in zip(self.w, imgs):
|
| 305 |
+
w.append_data(im)
|
| 306 |
+
for k, v in st.items():
|
| 307 |
+
self.num[k].append(v)
|
| 308 |
+
self.n += 1
|
| 309 |
+
|
| 310 |
+
def close(self, final_state, final_imgs):
|
| 311 |
+
from PIL import Image
|
| 312 |
+
if self.w is not None:
|
| 313 |
+
for w in self.w:
|
| 314 |
+
w.close()
|
| 315 |
+
arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"}
|
| 316 |
+
np.savez(os.path.join(self.path, "frames.npz"), **arr)
|
| 317 |
+
if self.num.get("sim_state"):
|
| 318 |
+
np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64))
|
| 319 |
+
np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()})
|
| 320 |
+
for k, im in zip(("agentview", "wrist"), final_imgs):
|
| 321 |
+
Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png"))
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
class Recorder:
|
| 325 |
+
"""Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink."""
|
| 326 |
+
|
| 327 |
+
def __init__(self, rp, res):
|
| 328 |
+
self.rp, self.res = rp, int(res)
|
| 329 |
+
self.active = False
|
| 330 |
+
self.sink = None
|
| 331 |
+
self.cur = dict(attempt=1, command=-1, phase=PHASES["move"])
|
| 332 |
+
env = rp.task.env
|
| 333 |
+
self.env, self.rob = env, env.robots[0]
|
| 334 |
+
self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist"))
|
| 335 |
+
orig = env.step
|
| 336 |
+
|
| 337 |
+
def step(a):
|
| 338 |
+
if self.active and self.sink is not None:
|
| 339 |
+
self.capture(np.asarray(a, np.float64))
|
| 340 |
+
out = orig(a)
|
| 341 |
+
if self.active and self.sink is not None:
|
| 342 |
+
self.rp.poll_events(self.sink.n - 1)
|
| 343 |
+
return out
|
| 344 |
+
|
| 345 |
+
env.step = step
|
| 346 |
+
|
| 347 |
+
@property
|
| 348 |
+
def n(self):
|
| 349 |
+
return self.sink.n if self.sink is not None else 0
|
| 350 |
+
|
| 351 |
+
def state(self):
|
| 352 |
+
import robosuite.utils.transform_utils as T
|
| 353 |
+
env, rob = self.env, self.rob
|
| 354 |
+
d = env.sim.data
|
| 355 |
+
eef = np.array(d.site_xpos[rob.eef_site_id], np.float64)
|
| 356 |
+
q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw")
|
| 357 |
+
gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64)
|
| 358 |
+
try:
|
| 359 |
+
flat = np.asarray(env.sim.get_state().flatten(), np.float64)
|
| 360 |
+
except Exception:
|
| 361 |
+
flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64)
|
| 362 |
+
sk = self.rp.task.sk
|
| 363 |
+
return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64),
|
| 364 |
+
gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64),
|
| 365 |
+
joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64),
|
| 366 |
+
gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64),
|
| 367 |
+
eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)),
|
| 368 |
+
sim_time=np.float64(d.time), sim_state=flat)
|
| 369 |
+
|
| 370 |
+
def images(self):
|
| 371 |
+
return [envs.render(self.env, c, self.res) for c in self.cams]
|
| 372 |
+
|
| 373 |
+
def capture(self, a):
|
| 374 |
+
st = self.state()
|
| 375 |
+
st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]),
|
| 376 |
+
phase=np.int64(self.cur["phase"]))
|
| 377 |
+
self.sink.add(st, self.images())
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
class RunReplay:
|
| 381 |
+
def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None):
|
| 382 |
+
self.run_dir = os.path.abspath(run_dir.rstrip("/"))
|
| 383 |
+
self.run_name = os.path.basename(self.run_dir)
|
| 384 |
+
self.log = RunLog(self.run_dir, manifest)
|
| 385 |
+
self.ev = self.log.ev
|
| 386 |
+
self.start = self.log.start
|
| 387 |
+
cp = os.path.join(self.run_dir, "contract.json")
|
| 388 |
+
self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {}
|
| 389 |
+
spec = self.contract.get("image_spec") or {}
|
| 390 |
+
self.image_res = int(spec.get("width", 512))
|
| 391 |
+
self.code_diff = check_code(self.run_dir)
|
| 392 |
+
s = self.start
|
| 393 |
+
self.task = TASKS[s["task"]](cam_res=self.image_res)
|
| 394 |
+
inst = self.task.sample_instance(s["seed"])
|
| 395 |
+
logged = s.get("inst") or {}
|
| 396 |
+
sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")})
|
| 397 |
+
self.inst_diff = diff_json(sampled, logged, "inst")
|
| 398 |
+
if s.get("arm", "none") not in (None, "none") or logged.get("nominal"):
|
| 399 |
+
inst.update(logged) # controlled arms / nominal: the server overrode these instance fields
|
| 400 |
+
self.inst_diff = []
|
| 401 |
+
self.inst = inst
|
| 402 |
+
self.protocol = getattr(self.task, "protocol", "cross")
|
| 403 |
+
self.k = int(s.get("k") or self.task.max_attempts)
|
| 404 |
+
self.attempt = 1
|
| 405 |
+
self.mismatch = [] # (where, what, logged, replayed)
|
| 406 |
+
self.n_checked = 0
|
| 407 |
+
self.max_dev_m = 0.0
|
| 408 |
+
self.unfinished = None
|
| 409 |
+
self.rec = Recorder(self, res) if record else None
|
| 410 |
+
self.res = int(res)
|
| 411 |
+
self.out_root = out_root
|
| 412 |
+
self.n_mon = 0
|
| 413 |
+
self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0
|
| 414 |
+
self.episodes = [] # summaries of the written episodes
|
| 415 |
+
self.task.reset_instance(self.inst)
|
| 416 |
+
self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
|
| 417 |
+
sim = self.task.env.sim
|
| 418 |
+
bid = sim.model.body_name2id("robot0_base")
|
| 419 |
+
self.base_off = np.array(sim.data.body_xpos[bid], float).copy()
|
| 420 |
+
if self.rec:
|
| 421 |
+
self._open_episode()
|
| 422 |
+
|
| 423 |
+
# ------------------------------------------------------------------ episodes
|
| 424 |
+
def _ep_dir(self):
|
| 425 |
+
return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}")
|
| 426 |
+
|
| 427 |
+
def _open_episode(self):
|
| 428 |
+
self.rec.sink = EpisodeSink(self._ep_dir())
|
| 429 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
|
| 430 |
+
self.rec.active = True
|
| 431 |
+
self.events, self.spans, self.ep_attempts = [], [], []
|
| 432 |
+
self.ep_initial = self.rec.state() # state right after the reset (before frame 0)
|
| 433 |
+
|
| 434 |
+
def close_episode(self):
|
| 435 |
+
if not self.rec:
|
| 436 |
+
self.ep_attempts = []
|
| 437 |
+
return
|
| 438 |
+
sink = self.rec.sink
|
| 439 |
+
st = self.rec.state()
|
| 440 |
+
imgs = self.rec.images()
|
| 441 |
+
st.pop("sim_state", None)
|
| 442 |
+
sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs)
|
| 443 |
+
ann = build_annotation(self, sink)
|
| 444 |
+
with open(os.path.join(sink.path, "annotation.json"), "w") as f:
|
| 445 |
+
json.dump(ann, f, indent=1, default=_json_default)
|
| 446 |
+
self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n,
|
| 447 |
+
attempts=[a["attempt"] for a in self.ep_attempts]))
|
| 448 |
+
self.rec.active = False
|
| 449 |
+
self.rec.sink = None
|
| 450 |
+
self.ep_index += 1
|
| 451 |
+
|
| 452 |
+
# ------------------------------------------------------------------ monitor events (task-side error events)
|
| 453 |
+
def poll_events(self, frame):
|
| 454 |
+
mon = getattr(self.task, "mon", None)
|
| 455 |
+
evs = mon.get("events") if isinstance(mon, dict) else None
|
| 456 |
+
if not isinstance(evs, list):
|
| 457 |
+
return
|
| 458 |
+
if len(evs) < self.n_mon: # monitor was rebuilt
|
| 459 |
+
self.n_mon = 0
|
| 460 |
+
for e in evs[self.n_mon:]:
|
| 461 |
+
self.events.append(dict(frame=int(frame), attempt=self.attempt,
|
| 462 |
+
event=norm_json(e) if isinstance(e, dict) else str(e)))
|
| 463 |
+
self.n_mon = len(evs)
|
| 464 |
+
|
| 465 |
+
# ------------------------------------------------------------------ state as the server reports it
|
| 466 |
+
def proprio_la(self):
|
| 467 |
+
p = self.ex.proprio()
|
| 468 |
+
pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off]
|
| 469 |
+
return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"])
|
| 470 |
+
|
| 471 |
+
def compare(self, where, rep_logged, rep):
|
| 472 |
+
self.n_checked += 1
|
| 473 |
+
for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"):
|
| 474 |
+
if k not in rep_logged or k not in rep:
|
| 475 |
+
continue
|
| 476 |
+
a, b = rep_logged[k], rep[k]
|
| 477 |
+
if k == "eef_pos":
|
| 478 |
+
dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float))))
|
| 479 |
+
self.max_dev_m = max(self.max_dev_m, dev)
|
| 480 |
+
if dev > 1.5e-4:
|
| 481 |
+
self.mismatch.append((where, k, a, b))
|
| 482 |
+
elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4):
|
| 483 |
+
self.mismatch.append((where, k, a, b))
|
| 484 |
+
if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)):
|
| 485 |
+
self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok")))
|
| 486 |
+
|
| 487 |
+
def _span(self, e, f0, kind):
|
| 488 |
+
if self.rec:
|
| 489 |
+
self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0,
|
| 490 |
+
frame_end=self.rec.n))
|
| 491 |
+
|
| 492 |
+
# ------------------------------------------------------------------ commands (robot_server._handle_v2)
|
| 493 |
+
def move_eef(self, e):
|
| 494 |
+
args = e.get("args") or {}
|
| 495 |
+
where = f"a{e['attempt']}s{e['step']}"
|
| 496 |
+
logged = e.get("report") or {}
|
| 497 |
+
f0 = self.rec.n if self.rec else 0
|
| 498 |
+
p = self.ex.proprio()
|
| 499 |
+
if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}:
|
| 500 |
+
self._span(e, f0, "error")
|
| 501 |
+
return self.compare(where, logged, dict(ok=False))
|
| 502 |
+
off = self.base_off
|
| 503 |
+
try:
|
| 504 |
+
cur = np.asarray(p["eef_pos"], float) - off
|
| 505 |
+
tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
|
| 506 |
+
yaw = float(args.get("yaw", p["eef_yaw_deg"]))
|
| 507 |
+
speed = None if args.get("speed") in (None, "") else float(args["speed"])
|
| 508 |
+
except (TypeError, ValueError):
|
| 509 |
+
self._span(e, f0, "error")
|
| 510 |
+
return self.compare(where, logged, dict(ok=False))
|
| 511 |
+
grip = args.get("gripper")
|
| 512 |
+
if grip not in (None, "open", "close"):
|
| 513 |
+
self._span(e, f0, "error")
|
| 514 |
+
return self.compare(where, logged, dict(ok=False))
|
| 515 |
+
moving = any(k in args for k in ("x", "y", "z", "yaw"))
|
| 516 |
+
tgt_w = np.asarray(tgt) + off
|
| 517 |
+
if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)):
|
| 518 |
+
self._span(e, f0, "rejected")
|
| 519 |
+
return self.compare(where, logged, dict(ok=False, **self.proprio_la()))
|
| 520 |
+
raw = {}
|
| 521 |
+
if self.rec:
|
| 522 |
+
self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"])
|
| 523 |
+
if moving:
|
| 524 |
+
mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw)
|
| 525 |
+
if speed is not None:
|
| 526 |
+
mv["speed"] = speed
|
| 527 |
+
raw.update(self.ex.call("move_to", mv).report)
|
| 528 |
+
if grip is not None:
|
| 529 |
+
if self.rec:
|
| 530 |
+
self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"])
|
| 531 |
+
raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report)
|
| 532 |
+
rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la())
|
| 533 |
+
self.compare(where, logged, rep)
|
| 534 |
+
lr = e.get("raw") or {}
|
| 535 |
+
for k in ("holding_object", "touched_object"):
|
| 536 |
+
if k in lr and k in raw and bool(lr[k]) != bool(raw[k]):
|
| 537 |
+
self.mismatch.append((where, "raw." + k, lr[k], raw[k]))
|
| 538 |
+
self._span(e, f0, "move_eef")
|
| 539 |
+
|
| 540 |
+
def observe(self, e):
|
| 541 |
+
f0 = self.rec.n if self.rec else 0
|
| 542 |
+
self._span(e, f0, "observe")
|
| 543 |
+
|
| 544 |
+
def done(self, e):
|
| 545 |
+
f0 = self.rec.n if self.rec else 0
|
| 546 |
+
if self.rec:
|
| 547 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"])
|
| 548 |
+
out = self.task.outcome(self.inst)
|
| 549 |
+
succ = bool(out["success"])
|
| 550 |
+
where = f"a{e['attempt']}done"
|
| 551 |
+
if succ != bool(e.get("success") in (True, "True")):
|
| 552 |
+
self.mismatch.append((where, "success", e.get("success"), succ))
|
| 553 |
+
lo = e.get("outcome") or {}
|
| 554 |
+
ro = norm_json({k: v for k, v in out.items() if k != "feedback"})
|
| 555 |
+
if isinstance(lo, dict):
|
| 556 |
+
for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8):
|
| 557 |
+
self.mismatch.append((where,) + d)
|
| 558 |
+
info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""),
|
| 559 |
+
feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")),
|
| 560 |
+
think_s=e.get("think_s"))
|
| 561 |
+
try:
|
| 562 |
+
info["feedback_f2"] = self.task.feedback(self.inst, out, "F2")
|
| 563 |
+
except Exception as ex_:
|
| 564 |
+
info["feedback_f2"] = f"<unavailable: {type(ex_).__name__}>"
|
| 565 |
+
if self.rec:
|
| 566 |
+
info["judge_frames"] = [f0, self.rec.n]
|
| 567 |
+
self.ep_attempts.append(info)
|
| 568 |
+
last = self.attempt >= self.k or succ or bool(out.get("terminal"))
|
| 569 |
+
if self.protocol == "cross" or last:
|
| 570 |
+
self.close_episode()
|
| 571 |
+
if last:
|
| 572 |
+
return True
|
| 573 |
+
self.attempt += 1
|
| 574 |
+
if self.protocol == "cross":
|
| 575 |
+
self.task.reset_instance(self.inst)
|
| 576 |
+
self.n_mon = 0
|
| 577 |
+
if self.rec:
|
| 578 |
+
self._open_episode()
|
| 579 |
+
elif self.rec:
|
| 580 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
|
| 581 |
+
self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
|
| 582 |
+
return False
|
| 583 |
+
|
| 584 |
+
def run(self):
|
| 585 |
+
t0 = time.time()
|
| 586 |
+
finished = False
|
| 587 |
+
for e in self.ev:
|
| 588 |
+
if e["ev"] == "call":
|
| 589 |
+
if e.get("cmd") == "move_eef":
|
| 590 |
+
self.move_eef(e)
|
| 591 |
+
elif e.get("cmd") == "observe":
|
| 592 |
+
self.observe(e)
|
| 593 |
+
else:
|
| 594 |
+
self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None))
|
| 595 |
+
elif e["ev"] == "done":
|
| 596 |
+
finished = self.done(e)
|
| 597 |
+
if finished:
|
| 598 |
+
break
|
| 599 |
+
self.unfinished = not finished
|
| 600 |
+
if not finished and self.rec and self.rec.sink is not None:
|
| 601 |
+
# the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged
|
| 602 |
+
if self.rec.n or self.ep_attempts:
|
| 603 |
+
self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True,
|
| 604 |
+
finish_reason="", feedback_shown="", auto_ended=False))
|
| 605 |
+
self.close_episode()
|
| 606 |
+
else:
|
| 607 |
+
shutil.rmtree(self.rec.sink.path, ignore_errors=True)
|
| 608 |
+
self.rec.sink = None
|
| 609 |
+
self.wall_s = time.time() - t0
|
| 610 |
+
return self
|
| 611 |
+
|
| 612 |
+
def summary(self):
|
| 613 |
+
return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"],
|
| 614 |
+
protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff),
|
| 615 |
+
n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6),
|
| 616 |
+
unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1),
|
| 617 |
+
first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]])
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
# ====================================================================================================== annotation
|
| 621 |
+
|
| 622 |
+
def task_info(task, inst):
|
| 623 |
+
cls = type(task)
|
| 624 |
+
return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable",
|
| 625 |
+
category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"),
|
| 626 |
+
max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)),
|
| 627 |
+
instruction=cls.instruction)
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
def build_annotation(rp, sink):
|
| 631 |
+
"""Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2
|
| 632 |
+
failure description), run-level outcome class, every robot command with its frame span and the agent's narration,
|
| 633 |
+
task-side error events with frame indices."""
|
| 634 |
+
log = rp.log
|
| 635 |
+
s = rp.start
|
| 636 |
+
cond, chain = log.condition()
|
| 637 |
+
cls, hist = log.outcome_class()
|
| 638 |
+
att_all = log.attempts()
|
| 639 |
+
attempts = []
|
| 640 |
+
for a in rp.ep_attempts:
|
| 641 |
+
a = dict(a)
|
| 642 |
+
n = a["attempt"]
|
| 643 |
+
later = [x for x in att_all if x["attempt"] > n]
|
| 644 |
+
a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later))
|
| 645 |
+
a["is_last_attempt_of_run"] = not later
|
| 646 |
+
fn = log.finish_notes.get(n)
|
| 647 |
+
if fn:
|
| 648 |
+
a["agent_finish"] = fn
|
| 649 |
+
a["error_event_in_attempt"] = error_event(a.get("outcome"))
|
| 650 |
+
attempts.append(a)
|
| 651 |
+
# post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command)
|
| 652 |
+
for a in attempts:
|
| 653 |
+
nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1])
|
| 654 |
+
if a.get("success") is False and nxt:
|
| 655 |
+
note = log.notes[nxt[0]]
|
| 656 |
+
a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note}
|
| 657 |
+
commands = []
|
| 658 |
+
for sp in rp.spans:
|
| 659 |
+
e = log.calls.get((sp["attempt"], sp["step"])) or {}
|
| 660 |
+
rep = e.get("report") or {}
|
| 661 |
+
c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"],
|
| 662 |
+
frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]),
|
| 663 |
+
args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"),
|
| 664 |
+
stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"),
|
| 665 |
+
gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"),
|
| 666 |
+
touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"),
|
| 667 |
+
agent_obs_images=rep.get("images"))
|
| 668 |
+
note = log.notes.get((sp["attempt"], sp["step"]))
|
| 669 |
+
if note:
|
| 670 |
+
c["agent_note"] = {k: v for k, v in note.items() if k != "command"}
|
| 671 |
+
commands.append(c)
|
| 672 |
+
t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x]
|
| 673 |
+
return dict(
|
| 674 |
+
schema=SCHEMA,
|
| 675 |
+
source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts],
|
| 676 |
+
episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain,
|
| 677 |
+
memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None),
|
| 678 |
+
feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"),
|
| 679 |
+
k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"),
|
| 680 |
+
contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256")
|
| 681 |
+
if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)),
|
| 682 |
+
agent=log.agent_info(),
|
| 683 |
+
task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"),
|
| 684 |
+
instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}),
|
| 685 |
+
run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all),
|
| 686 |
+
run_success=any(x["success"] for x in att_all) if att_all else None,
|
| 687 |
+
agent_final_report=log.final_report[:6000] or None,
|
| 688 |
+
mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)),
|
| 689 |
+
attempts=attempts,
|
| 690 |
+
commands=commands,
|
| 691 |
+
task_events=rp.events,
|
| 692 |
+
frames=dict(n=sink.n, fps=FPS, image_res=rp.res,
|
| 693 |
+
phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"],
|
| 694 |
+
joint_pos=rp.ep_initial["joint_pos"],
|
| 695 |
+
gripper_qpos=rp.ep_initial["gripper_qpos"])),
|
| 696 |
+
)
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
# ====================================================================================================== CLI
|
| 700 |
+
|
| 701 |
+
def load_manifest(run_dir):
|
| 702 |
+
p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json")
|
| 703 |
+
return json.load(open(p)) if os.path.exists(p) else {}
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
def main():
|
| 707 |
+
ap = argparse.ArgumentParser()
|
| 708 |
+
ap.add_argument("mode", choices=["check", "record"])
|
| 709 |
+
ap.add_argument("runs", nargs="+")
|
| 710 |
+
ap.add_argument("--json", default="")
|
| 711 |
+
ap.add_argument("--out", default="")
|
| 712 |
+
ap.add_argument("--res", type=int, default=256)
|
| 713 |
+
ap.add_argument("--force", action="store_true", help="record again even if replay.json exists")
|
| 714 |
+
a = ap.parse_args()
|
| 715 |
+
rows = []
|
| 716 |
+
for r in a.runs:
|
| 717 |
+
r = r.rstrip("/")
|
| 718 |
+
try:
|
| 719 |
+
if a.mode == "check":
|
| 720 |
+
s = RunReplay(r, manifest=load_manifest(r)).run().summary()
|
| 721 |
+
else:
|
| 722 |
+
batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r)
|
| 723 |
+
rd = os.path.join(a.out, batch, name)
|
| 724 |
+
if os.path.exists(os.path.join(rd, "replay.json")) and not a.force:
|
| 725 |
+
print(json.dumps(dict(run=name, skipped="exists")), flush=True)
|
| 726 |
+
continue
|
| 727 |
+
shutil.rmtree(rd, ignore_errors=True)
|
| 728 |
+
rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run()
|
| 729 |
+
s = rp.summary()
|
| 730 |
+
s["episodes"] = rp.episodes
|
| 731 |
+
with open(os.path.join(rd, "replay.json"), "w") as f:
|
| 732 |
+
json.dump(s, f, indent=1)
|
| 733 |
+
except Exception:
|
| 734 |
+
import traceback
|
| 735 |
+
s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:])
|
| 736 |
+
rows.append(s)
|
| 737 |
+
print(json.dumps(s), flush=True)
|
| 738 |
+
if a.json:
|
| 739 |
+
with open(a.json, "w") as f:
|
| 740 |
+
json.dump(rows, f, indent=1)
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
if __name__ == "__main__":
|
| 744 |
+
main()
|
leaf/code/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lerobot_export.py
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars.
|
| 2 |
+
|
| 3 |
+
Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding
|
| 4 |
+
can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan):
|
| 5 |
+
|
| 6 |
+
python scripts/lerobot_export.py plan --raw <raw_root>[,<raw_root2>] --runs-root <lffbench>/runs/api \
|
| 7 |
+
--paper <paper/latex> --task-set <lffbench>/sets/main_v2_1inst.txt --work <work_dir> [--batches ...] [--limit N]
|
| 8 |
+
python scripts/lerobot_export.py shard --work <work_dir> --shard i --nshards N
|
| 9 |
+
python scripts/lerobot_export.py merge --work <work_dir> --nshards N --out <dataset_root>
|
| 10 |
+
|
| 11 |
+
Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0
|
| 12 |
+
mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped.
|
| 13 |
+
|
| 14 |
+
LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t):
|
| 15 |
+
observation.images.image agentview RGB 256x256 (upright; LIBERO naming)
|
| 16 |
+
observation.images.wrist_image wrist (eye-in-hand) RGB 256x256
|
| 17 |
+
observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout)
|
| 18 |
+
observation.joint_pos / joint_vel 7 arm joints (rad, rad/s)
|
| 19 |
+
observation.eef_quat 4: xyzw; observation.gripper_width 1 (m)
|
| 20 |
+
action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad),
|
| 21 |
+
gripper (-1 open, +1 close)
|
| 22 |
+
annotation.attempt_index attempt (1-based) the frame belongs to
|
| 23 |
+
annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`)
|
| 24 |
+
annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action)
|
| 25 |
+
annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt
|
| 26 |
+
annotation.task_event number of task-monitor events (error / progress events) registered at this step
|
| 27 |
+
Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table),
|
| 28 |
+
runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state
|
| 29 |
+
per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/.
|
| 30 |
+
"""
|
| 31 |
+
import argparse
|
| 32 |
+
import glob
|
| 33 |
+
import json
|
| 34 |
+
import os
|
| 35 |
+
import re
|
| 36 |
+
import shutil
|
| 37 |
+
import time
|
| 38 |
+
|
| 39 |
+
import numpy as np
|
| 40 |
+
|
| 41 |
+
FPS = 20
|
| 42 |
+
RES = 256
|
| 43 |
+
BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke",
|
| 44 |
+
"cc_smoke", "cc_opus_smoke"]
|
| 45 |
+
BATCH_NOTES = {
|
| 46 |
+
"cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog",
|
| 47 |
+
"cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267",
|
| 48 |
+
"cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299",
|
| 49 |
+
"cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances",
|
| 50 |
+
"cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)",
|
| 51 |
+
"cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the "
|
| 52 |
+
"with-history continuation of failed runs is incomplete",
|
| 53 |
+
"cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early",
|
| 54 |
+
"cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt",
|
| 55 |
+
"cc_opus_smoke": "smoke test: single attempt",
|
| 56 |
+
}
|
| 57 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 58 |
+
CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)",
|
| 59 |
+
"L2": "disturbed state to restore (incl. damage the agent causes)",
|
| 60 |
+
"L3": "infeasible manipulation strategy (grasp / contact / tool must change)",
|
| 61 |
+
"L4": "misjudged geometry (size, shape, fit, hidden structure)",
|
| 62 |
+
"L5": "misjudged physics (mass distribution, friction, dynamics)"}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def features():
|
| 66 |
+
vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]}
|
| 67 |
+
f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names}
|
| 68 |
+
i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None}
|
| 69 |
+
return {
|
| 70 |
+
"observation.images.image": vid(),
|
| 71 |
+
"observation.images.wrist_image": vid(),
|
| 72 |
+
"observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z",
|
| 73 |
+
"finger_qpos_left", "finger_qpos_right"]),
|
| 74 |
+
"observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 75 |
+
"observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 76 |
+
"observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]),
|
| 77 |
+
"observation.gripper_width": f32(1, ["width_m"]),
|
| 78 |
+
"action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y",
|
| 79 |
+
"eef_delta_rot_aa_z", "gripper_close"]),
|
| 80 |
+
"annotation.attempt_index": i64(),
|
| 81 |
+
"annotation.command_index": i64(),
|
| 82 |
+
"annotation.phase": i64(),
|
| 83 |
+
"annotation.attempt_success": i64(),
|
| 84 |
+
"annotation.task_event": i64(),
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ------------------------------------------------------------------------------------------------ paper metadata
|
| 89 |
+
|
| 90 |
+
def _clean_tex(s):
|
| 91 |
+
s = re.sub(r"%.*", "", s)
|
| 92 |
+
for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"),
|
| 93 |
+
(r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"),
|
| 94 |
+
(r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"),
|
| 95 |
+
(r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"),
|
| 96 |
+
(r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]:
|
| 97 |
+
s = re.sub(a, b, s)
|
| 98 |
+
s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s)
|
| 99 |
+
s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s)
|
| 100 |
+
for _ in range(3):
|
| 101 |
+
s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s)
|
| 102 |
+
s = re.sub(r"\$([^$]*)\$", r"\1", s)
|
| 103 |
+
s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ")
|
| 104 |
+
s = re.sub(r"\{([^{}]*)\}", r"\1", s)
|
| 105 |
+
s = re.sub(r"\\[a-zA-Z]+\*?", "", s)
|
| 106 |
+
return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def paper_tasks(paper_dir):
|
| 110 |
+
"""{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the
|
| 111 |
+
paper's task table and task appendix (empty if the paper sources are not there)."""
|
| 112 |
+
out = {}
|
| 113 |
+
if not paper_dir:
|
| 114 |
+
return out
|
| 115 |
+
app = os.path.join(paper_dir, "sections", "appendix_tasks.tex")
|
| 116 |
+
tab = os.path.join(paper_dir, "sections", "tab_tasks.tex")
|
| 117 |
+
if os.path.exists(app):
|
| 118 |
+
txt = open(app).read()
|
| 119 |
+
parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt)
|
| 120 |
+
for i in range(1, len(parts) - 1, 2):
|
| 121 |
+
if parts[i] != "\\paragraph{":
|
| 122 |
+
continue
|
| 123 |
+
body = parts[i + 1]
|
| 124 |
+
m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S)
|
| 125 |
+
if not m:
|
| 126 |
+
continue
|
| 127 |
+
name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip()
|
| 128 |
+
desc = _clean_tex(body[m.end():])
|
| 129 |
+
out[code] = dict(name=name, cause=_clean_tex(cause), description=desc)
|
| 130 |
+
if os.path.exists(tab):
|
| 131 |
+
names = {v["name"].lower(): k for k, v in out.items()}
|
| 132 |
+
for line in open(tab):
|
| 133 |
+
cells = [c.strip() for c in line.split("&")]
|
| 134 |
+
if len(cells) != 6 or not cells[-1].endswith("\\\\"):
|
| 135 |
+
continue
|
| 136 |
+
nm = re.sub(r"\\contscene", "", cells[0]).strip().lower()
|
| 137 |
+
code = names.get(nm)
|
| 138 |
+
if not code:
|
| 139 |
+
continue
|
| 140 |
+
out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]),
|
| 141 |
+
repair_within_attempt=_clean_tex(cells[3]) == "yes",
|
| 142 |
+
oracle_first_attempt_pct=_clean_tex(cells[4]),
|
| 143 |
+
naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip()))
|
| 144 |
+
return out
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
# ------------------------------------------------------------------------------------------------ collection
|
| 148 |
+
|
| 149 |
+
def manifest_status(runs_root, batch, run, cache={}):
|
| 150 |
+
if batch not in cache:
|
| 151 |
+
p = os.path.join(runs_root, batch, "manifest.json")
|
| 152 |
+
cache[batch] = json.load(open(p)) if os.path.exists(p) else {}
|
| 153 |
+
m = cache[batch]
|
| 154 |
+
for r in m.get("runs", []):
|
| 155 |
+
if r.get("run") == run:
|
| 156 |
+
return r.get("status", "?"), r
|
| 157 |
+
for r in m.get("superseded", []):
|
| 158 |
+
if r.get("run") == run:
|
| 159 |
+
return "superseded_" + str(r.get("status", "?")), r
|
| 160 |
+
return "not_in_manifest", {}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def collect(raw_roots, runs_root, batches, task_order):
|
| 164 |
+
"""Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root."""
|
| 165 |
+
eps, rejected, seen = [], [], set()
|
| 166 |
+
for root in raw_roots:
|
| 167 |
+
for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))):
|
| 168 |
+
rep = json.load(open(rj))
|
| 169 |
+
batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"]
|
| 170 |
+
if (batches and batch not in batches) or (batch, run) in seen:
|
| 171 |
+
continue
|
| 172 |
+
seen.add((batch, run))
|
| 173 |
+
ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff")
|
| 174 |
+
status, entry = manifest_status(runs_root, batch, run)
|
| 175 |
+
if not ok:
|
| 176 |
+
never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked")
|
| 177 |
+
rejected.append(dict(run=run, batch=batch, run_status=status,
|
| 178 |
+
reason="run never started (no contract, no robot command)" if never else
|
| 179 |
+
"replay does not reproduce the log (the log has gaps or the replay diverged)",
|
| 180 |
+
detail=rep.get("first_mismatches")))
|
| 181 |
+
continue
|
| 182 |
+
for ep in rep.get("episodes", []):
|
| 183 |
+
d = os.path.join(root, ep["dir"])
|
| 184 |
+
ann = json.load(open(os.path.join(d, "annotation.json")))
|
| 185 |
+
judged = [a for a in ann["attempts"] if a.get("success") is not None]
|
| 186 |
+
if not judged or ep["n_frames"] == 0:
|
| 187 |
+
rejected.append(dict(run=run, batch=batch, episode=ep["dir"],
|
| 188 |
+
reason="no judged attempt" if not judged else "no frames"))
|
| 189 |
+
continue
|
| 190 |
+
ann["source"]["run_status"] = status
|
| 191 |
+
ann["source"]["manifest_id"] = entry.get("id")
|
| 192 |
+
ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"],
|
| 193 |
+
max_eef_dev_m=rep["max_eef_dev_m"])
|
| 194 |
+
key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99),
|
| 195 |
+
{"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2),
|
| 196 |
+
ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"])
|
| 197 |
+
eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann))
|
| 198 |
+
eps.sort(key=lambda x: x["key"])
|
| 199 |
+
return eps, rejected
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# ------------------------------------------------------------------------------------------------ writing
|
| 203 |
+
|
| 204 |
+
def frames_of(path):
|
| 205 |
+
import av
|
| 206 |
+
with av.open(path) as c:
|
| 207 |
+
for fr in c.decode(video=0):
|
| 208 |
+
yield fr.to_ndarray(format="rgb24")
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def flat_row(i, ann, n, idx0):
|
| 212 |
+
s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"]
|
| 213 |
+
att = ann["attempts"]
|
| 214 |
+
a0 = att[0]
|
| 215 |
+
return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n,
|
| 216 |
+
batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"],
|
| 217 |
+
memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"),
|
| 218 |
+
episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att],
|
| 219 |
+
harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"),
|
| 220 |
+
effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"),
|
| 221 |
+
task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"),
|
| 222 |
+
category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"],
|
| 223 |
+
success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att],
|
| 224 |
+
feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att],
|
| 225 |
+
auto_ended=[a.get("auto_ended") for a in att],
|
| 226 |
+
corrected_later_in_run=[a.get("corrected_later_in_run") for a in att],
|
| 227 |
+
error_event_in_attempt=[a.get("error_event_in_attempt") for a in att],
|
| 228 |
+
run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"),
|
| 229 |
+
n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]),
|
| 230 |
+
first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def cmd_plan(a):
|
| 234 |
+
task_order = {}
|
| 235 |
+
if a.task_set and os.path.exists(a.task_set):
|
| 236 |
+
for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")):
|
| 237 |
+
task_order[line.split(":")[0].strip()] = i
|
| 238 |
+
batches = [b for b in a.batches.split(",") if b] if a.batches else None
|
| 239 |
+
eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order)
|
| 240 |
+
if a.limit:
|
| 241 |
+
eps = eps[:a.limit]
|
| 242 |
+
paper = paper_tasks(a.paper)
|
| 243 |
+
idx0 = 0
|
| 244 |
+
for i, e in enumerate(eps):
|
| 245 |
+
ann = e["ann"]
|
| 246 |
+
tname = ann["task"]["name"]
|
| 247 |
+
if tname in paper:
|
| 248 |
+
ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"}
|
| 249 |
+
ann["episode_index"] = i
|
| 250 |
+
ann["dataset_index_range"] = [idx0, idx0 + e["n"]]
|
| 251 |
+
e["index"], e["from"] = i, idx0
|
| 252 |
+
idx0 += e["n"]
|
| 253 |
+
del e["key"]
|
| 254 |
+
os.makedirs(a.work, exist_ok=True)
|
| 255 |
+
with open(os.path.join(a.work, "plan.json"), "w") as f:
|
| 256 |
+
json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f,
|
| 257 |
+
ensure_ascii=False)
|
| 258 |
+
print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def shard_range(n_eps, i, k):
|
| 262 |
+
return (n_eps * i) // k, (n_eps * (i + 1)) // k
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def cmd_shard(a):
|
| 266 |
+
from lerobot.datasets.lerobot_dataset import LeRobotDataset
|
| 267 |
+
t0 = time.time()
|
| 268 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 269 |
+
eps = plan["episodes"]
|
| 270 |
+
lo, hi = shard_range(len(eps), a.shard, a.nshards)
|
| 271 |
+
out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}")
|
| 272 |
+
if os.path.exists(os.path.join(out, "DONE")):
|
| 273 |
+
print(f"shard {a.shard}: done already", flush=True)
|
| 274 |
+
return
|
| 275 |
+
shutil.rmtree(out, ignore_errors=True)
|
| 276 |
+
ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out,
|
| 277 |
+
robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads,
|
| 278 |
+
vcodec=a.vcodec)
|
| 279 |
+
nfr = 0
|
| 280 |
+
for e in eps[lo:hi]:
|
| 281 |
+
d, ann, n = e["dir"], e["ann"], e["n"]
|
| 282 |
+
fr = np.load(os.path.join(d, "frames.npz"))
|
| 283 |
+
assert len(fr["action"]) == n, d
|
| 284 |
+
succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]}
|
| 285 |
+
evc = np.zeros(n, np.int64)
|
| 286 |
+
for ev in ann["task_events"]:
|
| 287 |
+
if 0 <= ev["frame"] < n:
|
| 288 |
+
evc[ev["frame"]] += 1
|
| 289 |
+
state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32)
|
| 290 |
+
instr = ann["task"]["instruction"]
|
| 291 |
+
k = 0
|
| 292 |
+
for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))):
|
| 293 |
+
if k >= n:
|
| 294 |
+
break
|
| 295 |
+
ds.add_frame({
|
| 296 |
+
"observation.images.image": img, "observation.images.wrist_image": wr,
|
| 297 |
+
"observation.state": state[k],
|
| 298 |
+
"observation.joint_pos": fr["joint_pos"][k].astype(np.float32),
|
| 299 |
+
"observation.joint_vel": fr["joint_vel"][k].astype(np.float32),
|
| 300 |
+
"observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32),
|
| 301 |
+
"observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32),
|
| 302 |
+
"action": fr["action"][k].astype(np.float32),
|
| 303 |
+
"annotation.attempt_index": np.array([fr["attempt"][k]], np.int64),
|
| 304 |
+
"annotation.command_index": np.array([fr["command"][k]], np.int64),
|
| 305 |
+
"annotation.phase": np.array([fr["phase"][k]], np.int64),
|
| 306 |
+
"annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64),
|
| 307 |
+
"annotation.task_event": np.array([evc[k]], np.int64),
|
| 308 |
+
"task": instr,
|
| 309 |
+
})
|
| 310 |
+
k += 1
|
| 311 |
+
if k != n:
|
| 312 |
+
raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames")
|
| 313 |
+
ds.save_episode()
|
| 314 |
+
nfr += n
|
| 315 |
+
ds.finalize()
|
| 316 |
+
shutil.rmtree(os.path.join(out, "images"), ignore_errors=True)
|
| 317 |
+
open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n")
|
| 318 |
+
print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def cmd_merge(a):
|
| 322 |
+
from pathlib import Path
|
| 323 |
+
from lerobot.datasets.aggregate import aggregate_datasets
|
| 324 |
+
t0 = time.time()
|
| 325 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 326 |
+
eps = plan["episodes"]
|
| 327 |
+
roots, ids = [], []
|
| 328 |
+
for i in range(a.nshards):
|
| 329 |
+
lo, hi = shard_range(len(eps), i, a.nshards)
|
| 330 |
+
if hi <= lo:
|
| 331 |
+
continue
|
| 332 |
+
r = os.path.join(a.work, "shards", f"shard_{i:03d}")
|
| 333 |
+
if not os.path.exists(os.path.join(r, "DONE")):
|
| 334 |
+
raise SystemExit(f"shard {i} is not done")
|
| 335 |
+
roots.append(Path(r))
|
| 336 |
+
ids.append(f"{plan['repo_id']}-shard{i:03d}")
|
| 337 |
+
if os.path.exists(a.out):
|
| 338 |
+
raise SystemExit(f"{a.out} exists; refusing to overwrite")
|
| 339 |
+
aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out))
|
| 340 |
+
print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True)
|
| 341 |
+
write_sidecars(a, plan)
|
| 342 |
+
print(f"merge done in {time.time() - t0:.0f}s", flush=True)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def write_sidecars(a, plan):
|
| 346 |
+
eps, paper = plan["episodes"], plan["paper"]
|
| 347 |
+
lff = os.path.join(a.out, "lff")
|
| 348 |
+
for sub in ("annotations", "sim_state", "final", "code"):
|
| 349 |
+
os.makedirs(os.path.join(lff, sub), exist_ok=True)
|
| 350 |
+
rows, runs, tasks = [], {}, {}
|
| 351 |
+
for e in eps:
|
| 352 |
+
i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"]
|
| 353 |
+
name = f"episode_{i:06d}"
|
| 354 |
+
if os.path.exists(os.path.join(d, "sim_state.npy")):
|
| 355 |
+
shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy"))
|
| 356 |
+
shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz"))
|
| 357 |
+
for cam, key in (("agentview", "image"), ("wrist", "wrist_image")):
|
| 358 |
+
shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png"))
|
| 359 |
+
with open(os.path.join(lff, "annotations", name + ".json"), "w") as f:
|
| 360 |
+
json.dump(ann, f, indent=1, ensure_ascii=False)
|
| 361 |
+
rows.append(flat_row(i, ann, n, e["from"]))
|
| 362 |
+
tname = ann["task"]["name"]
|
| 363 |
+
rk = (ann["source"]["batch"], ann["source"]["run"])
|
| 364 |
+
r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"),
|
| 365 |
+
run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"],
|
| 366 |
+
memory_free_chain_of=ann["source"].get("memory_free_chain_of"),
|
| 367 |
+
memory_free_rep=ann["source"].get("memory_free_rep"), task=tname,
|
| 368 |
+
seed=ann["task"]["seed"], model=ann["agent"].get("model"),
|
| 369 |
+
harness=ann["agent"].get("harness"),
|
| 370 |
+
harness_version=ann["agent"].get("harness_version"),
|
| 371 |
+
codex_catalog=ann["agent"].get("codex_catalog"),
|
| 372 |
+
outcome_class=ann["run_outcome"].get("outcome_class"),
|
| 373 |
+
attempt_history=ann["run_outcome"].get("attempt_history"),
|
| 374 |
+
agent_final_report=ann["run_outcome"].get("agent_final_report"),
|
| 375 |
+
episodes=[]))
|
| 376 |
+
for x in ann["attempts"]:
|
| 377 |
+
r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success")))
|
| 378 |
+
if tname not in tasks:
|
| 379 |
+
tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")}
|
| 380 |
+
if tname in paper:
|
| 381 |
+
tasks[tname]["paper"] = paper[tname]
|
| 382 |
+
tasks[tname]["instances"] = {}
|
| 383 |
+
tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"]
|
| 384 |
+
# memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id)
|
| 385 |
+
by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")}
|
| 386 |
+
for r in runs.values():
|
| 387 |
+
if r.get("memory_free_chain_of"):
|
| 388 |
+
r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"]))
|
| 389 |
+
for (b, rn), r in runs.items():
|
| 390 |
+
r["memory_free_retries"] = sorted((x["run"] for x in runs.values()
|
| 391 |
+
if x["batch"] == b and x.get("memory_free_chain_of_run") == rn),
|
| 392 |
+
key=lambda q: runs[(b, q)].get("memory_free_rep") or 0)
|
| 393 |
+
with open(os.path.join(lff, "episodes.jsonl"), "w") as f:
|
| 394 |
+
for row in rows:
|
| 395 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 396 |
+
with open(os.path.join(lff, "runs.jsonl"), "w") as f:
|
| 397 |
+
for r in runs.values():
|
| 398 |
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 399 |
+
with open(os.path.join(lff, "tasks.json"), "w") as f:
|
| 400 |
+
json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False)
|
| 401 |
+
with open(os.path.join(lff, "batches.json"), "w") as f:
|
| 402 |
+
json.dump(BATCH_NOTES, f, indent=1)
|
| 403 |
+
with open(os.path.join(lff, "rejected.json"), "w") as f:
|
| 404 |
+
json.dump(plan["rejected"], f, indent=1)
|
| 405 |
+
here = os.path.dirname(os.path.abspath(__file__))
|
| 406 |
+
for s in ("lerobot_replay.py", "lerobot_export.py"):
|
| 407 |
+
shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s))
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def main():
|
| 411 |
+
ap = argparse.ArgumentParser()
|
| 412 |
+
ap.add_argument("step", choices=["plan", "shard", "merge"])
|
| 413 |
+
ap.add_argument("--work", required=True)
|
| 414 |
+
ap.add_argument("--raw", default="")
|
| 415 |
+
ap.add_argument("--runs-root", default="")
|
| 416 |
+
ap.add_argument("--out", default="")
|
| 417 |
+
ap.add_argument("--paper", default="")
|
| 418 |
+
ap.add_argument("--task-set", default="")
|
| 419 |
+
ap.add_argument("--repo-id", default="lffbench/agent-replays")
|
| 420 |
+
ap.add_argument("--batches", default="")
|
| 421 |
+
ap.add_argument("--limit", type=int, default=0)
|
| 422 |
+
ap.add_argument("--shard", type=int, default=0)
|
| 423 |
+
ap.add_argument("--nshards", type=int, default=1)
|
| 424 |
+
ap.add_argument("--threads", type=int, default=2)
|
| 425 |
+
ap.add_argument("--vcodec", default="libsvtav1")
|
| 426 |
+
a = ap.parse_args()
|
| 427 |
+
{"plan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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay
|
| 2 |
+
against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the
|
| 3 |
+
LeRobot export (scripts/lerobot_export.py).
|
| 4 |
+
|
| 5 |
+
python scripts/lerobot_replay.py check <run_dir> [<run_dir> ...] [--json out.json] # replay only, print fidelity
|
| 6 |
+
python scripts/lerobot_replay.py record <run_dir> --out <raw_root> [--res 256]
|
| 7 |
+
|
| 8 |
+
Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot
|
| 9 |
+
commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite
|
| 10 |
+
is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly
|
| 11 |
+
like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same
|
| 12 |
+
outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width,
|
| 13 |
+
ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code
|
| 14 |
+
hashes equal the current files are expected to match (check_code()).
|
| 15 |
+
|
| 16 |
+
Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB,
|
| 17 |
+
proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes:
|
| 18 |
+
protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode
|
| 19 |
+
per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the
|
| 20 |
+
fidelity check runs in record mode too. Per episode the recorder writes <raw_root>/<batch>/<run>/epNN/:
|
| 21 |
+
agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes)
|
| 22 |
+
frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase
|
| 23 |
+
sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel)
|
| 24 |
+
final_*.png, final.npz observation after the last control step (the state the outcome was judged in)
|
| 25 |
+
annotation.json episode annotation (build_annotation)
|
| 26 |
+
and <raw_root>/<batch>/<run>/replay.json (fidelity) when the whole run is done.
|
| 27 |
+
"""
|
| 28 |
+
import argparse
|
| 29 |
+
import ast
|
| 30 |
+
import hashlib
|
| 31 |
+
import importlib
|
| 32 |
+
import json
|
| 33 |
+
import math
|
| 34 |
+
import os
|
| 35 |
+
import pkgutil
|
| 36 |
+
import re
|
| 37 |
+
import shutil
|
| 38 |
+
import sys
|
| 39 |
+
import time
|
| 40 |
+
from collections import defaultdict
|
| 41 |
+
|
| 42 |
+
import numpy as np
|
| 43 |
+
|
| 44 |
+
LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 45 |
+
sys.path.insert(0, LFF_ROOT)
|
| 46 |
+
|
| 47 |
+
from lffbench import envs # noqa: E402
|
| 48 |
+
from lffbench import tasks as task_pkg # noqa: E402
|
| 49 |
+
from lffbench.agent import camera as C # noqa: E402
|
| 50 |
+
from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402
|
| 51 |
+
from lffbench.task_base import TASKS # noqa: E402
|
| 52 |
+
|
| 53 |
+
for _m in pkgutil.iter_modules(task_pkg.__path__):
|
| 54 |
+
importlib.import_module(f"lffbench.tasks.{_m.name}")
|
| 55 |
+
|
| 56 |
+
# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the
|
| 57 |
+
# task's outcome() check after `finish` (the arm holds still; not an agent action)
|
| 58 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 59 |
+
FPS = 20
|
| 60 |
+
SCHEMA = "lff-replay-1"
|
| 61 |
+
|
| 62 |
+
# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR"
|
| 63 |
+
ERROR_FLAGS = ("trap_fired", "recovered_in_attempt")
|
| 64 |
+
ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events",
|
| 65 |
+
"n_missed_strikes", "n_open_gripper_pushes")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def load_jsonl(p):
|
| 69 |
+
out = []
|
| 70 |
+
if not os.path.exists(p):
|
| 71 |
+
return out
|
| 72 |
+
with open(p) as f:
|
| 73 |
+
for line in f:
|
| 74 |
+
line = line.strip()
|
| 75 |
+
if line:
|
| 76 |
+
try:
|
| 77 |
+
out.append(json.loads(line))
|
| 78 |
+
except ValueError:
|
| 79 |
+
pass
|
| 80 |
+
return out
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def norm_json(o):
|
| 84 |
+
return json.loads(json.dumps(o, default=_json_default))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def sha256(p):
|
| 88 |
+
with open(p, "rb") as f:
|
| 89 |
+
return hashlib.sha256(f.read()).hexdigest()
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def check_code(run_dir):
|
| 93 |
+
"""[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract."""
|
| 94 |
+
p = os.path.join(run_dir, "contract.json")
|
| 95 |
+
if not os.path.exists(p):
|
| 96 |
+
return [("contract.json", None, None)]
|
| 97 |
+
files = json.load(open(p))["contract"].get("server_code_files", {})
|
| 98 |
+
bad = []
|
| 99 |
+
for f, h in files.items():
|
| 100 |
+
q = os.path.join(LFF_ROOT, f)
|
| 101 |
+
cur = sha256(q) if os.path.exists(q) else None
|
| 102 |
+
if cur != h:
|
| 103 |
+
bad.append((f, h, cur))
|
| 104 |
+
return bad
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def diff_json(a, b, path="", tol=0.0, out=None, limit=20):
|
| 108 |
+
"""Differences between two JSON values (numbers compared with an absolute tolerance)."""
|
| 109 |
+
out = [] if out is None else out
|
| 110 |
+
if len(out) >= limit:
|
| 111 |
+
return out
|
| 112 |
+
if isinstance(a, dict) and isinstance(b, dict):
|
| 113 |
+
for k in sorted(set(a) | set(b)):
|
| 114 |
+
if k not in a or k not in b:
|
| 115 |
+
out.append((f"{path}.{k}", a.get(k, "<missing>"), b.get(k, "<missing>")))
|
| 116 |
+
else:
|
| 117 |
+
diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit)
|
| 118 |
+
elif isinstance(a, list) and isinstance(b, list):
|
| 119 |
+
if len(a) != len(b):
|
| 120 |
+
out.append((path, f"len {len(a)}", f"len {len(b)}"))
|
| 121 |
+
else:
|
| 122 |
+
for i, (x, y) in enumerate(zip(a, b)):
|
| 123 |
+
diff_json(x, y, f"{path}[{i}]", tol, out, limit)
|
| 124 |
+
elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
|
| 125 |
+
if a != b:
|
| 126 |
+
out.append((path, a, b))
|
| 127 |
+
elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))):
|
| 128 |
+
out.append((path, a, b))
|
| 129 |
+
return out
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def error_event(o):
|
| 133 |
+
"""True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none."""
|
| 134 |
+
if not isinstance(o, dict):
|
| 135 |
+
return None
|
| 136 |
+
keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o]
|
| 137 |
+
if not keys:
|
| 138 |
+
return None
|
| 139 |
+
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)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# ====================================================================================================== logs -> notes
|
| 143 |
+
|
| 144 |
+
class RunLog:
|
| 145 |
+
"""Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's
|
| 146 |
+
narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition."""
|
| 147 |
+
|
| 148 |
+
def __init__(self, run_dir, manifest=None):
|
| 149 |
+
self.run_dir = os.path.abspath(run_dir.rstrip("/"))
|
| 150 |
+
self.run = os.path.basename(self.run_dir)
|
| 151 |
+
self.batch = os.path.basename(os.path.dirname(self.run_dir))
|
| 152 |
+
self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl"))
|
| 153 |
+
self.start = next(e for e in self.ev if e["ev"] == "session_start")
|
| 154 |
+
self.calls, self.dones, self.harness_status = {}, [], []
|
| 155 |
+
last = None
|
| 156 |
+
for e in self.ev:
|
| 157 |
+
if e["ev"] == "call":
|
| 158 |
+
self.calls[(int(e["attempt"]), int(e["step"]))] = e
|
| 159 |
+
last = e
|
| 160 |
+
elif e["ev"] == "done":
|
| 161 |
+
self.dones.append(e)
|
| 162 |
+
last = e
|
| 163 |
+
elif e["ev"] == "http" and last is not None and "think_s" not in last:
|
| 164 |
+
ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \
|
| 165 |
+
(last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe"))
|
| 166 |
+
if ok:
|
| 167 |
+
last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s")
|
| 168 |
+
self.manifest = manifest or {}
|
| 169 |
+
self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {}
|
| 170 |
+
p = os.path.join(self.run_dir, "harness.json")
|
| 171 |
+
self.harness = json.load(open(p)) if os.path.exists(p) else {}
|
| 172 |
+
self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl"))
|
| 173 |
+
self._narration()
|
| 174 |
+
|
| 175 |
+
# ---------------------------------------------------------------- agent narration
|
| 176 |
+
def _narration(self):
|
| 177 |
+
"""notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one;
|
| 178 |
+
finish_notes[attempt] likewise for the agent's finish call; final_report = its last message."""
|
| 179 |
+
self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", []
|
| 180 |
+
buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
|
| 181 |
+
attempt = 1
|
| 182 |
+
|
| 183 |
+
def take():
|
| 184 |
+
nonlocal buf
|
| 185 |
+
out = {k: v for k, v in buf.items() if v}
|
| 186 |
+
buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
|
| 187 |
+
return out
|
| 188 |
+
|
| 189 |
+
last_msg = ""
|
| 190 |
+
for t in self.traj:
|
| 191 |
+
if t.get("kind") == "header":
|
| 192 |
+
self.headers.append(t.get("agent") or {})
|
| 193 |
+
continue
|
| 194 |
+
if t.get("kind") != "step":
|
| 195 |
+
continue
|
| 196 |
+
if (t.get("message") or "").strip():
|
| 197 |
+
buf["messages"].append(t["message"].strip())
|
| 198 |
+
last_msg = t["message"].strip()
|
| 199 |
+
if (t.get("reasoning_content") or "").strip():
|
| 200 |
+
buf["reasoning"].append(t["reasoning_content"].strip())
|
| 201 |
+
res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])}
|
| 202 |
+
for c in t.get("tool_calls") or []:
|
| 203 |
+
fn, args = c.get("function_name"), c.get("arguments") or {}
|
| 204 |
+
if fn == "shell":
|
| 205 |
+
buf["shell"].append(str(args.get("command", ""))[:2000])
|
| 206 |
+
elif fn == "view_images":
|
| 207 |
+
buf["viewed"].extend(args.get("paths") or [])
|
| 208 |
+
elif fn == "robot":
|
| 209 |
+
cmd = str(args.get("command", "")).strip()
|
| 210 |
+
r = res.get(c.get("tool_call_id")) or {}
|
| 211 |
+
try:
|
| 212 |
+
rep = json.loads(r.get("content") or "{}")
|
| 213 |
+
except ValueError:
|
| 214 |
+
rep = {}
|
| 215 |
+
word = cmd.split()[0] if cmd else ""
|
| 216 |
+
m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", "")))
|
| 217 |
+
if word in ("move_eef", "observe") and m:
|
| 218 |
+
a, s = int(m.group(1)), int(m.group(2))
|
| 219 |
+
n = take()
|
| 220 |
+
n["command"] = cmd
|
| 221 |
+
self.notes[(a, s)] = n
|
| 222 |
+
attempt = a
|
| 223 |
+
elif word in ("finish", "done"):
|
| 224 |
+
n = take()
|
| 225 |
+
n["command"] = cmd
|
| 226 |
+
n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)}
|
| 227 |
+
self.finish_notes.setdefault(attempt, n)
|
| 228 |
+
if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"):
|
| 229 |
+
attempt += 1
|
| 230 |
+
# status / help / errors: their narration stays in the buffer for the next command
|
| 231 |
+
self.final_report = last_msg
|
| 232 |
+
|
| 233 |
+
# ---------------------------------------------------------------- run-level labels
|
| 234 |
+
def attempts(self):
|
| 235 |
+
out = []
|
| 236 |
+
for e in self.dones:
|
| 237 |
+
o = e.get("outcome") or {}
|
| 238 |
+
if isinstance(o, str):
|
| 239 |
+
try:
|
| 240 |
+
o = ast.literal_eval(o)
|
| 241 |
+
except (ValueError, SyntaxError):
|
| 242 |
+
o = {}
|
| 243 |
+
out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o,
|
| 244 |
+
reason=e.get("reason") or ""))
|
| 245 |
+
return sorted(out, key=lambda x: x["attempt"])
|
| 246 |
+
|
| 247 |
+
def condition(self):
|
| 248 |
+
s, en = self.start, self.entry
|
| 249 |
+
mem = s.get("memory", en.get("mem"))
|
| 250 |
+
chain = en.get("chain")
|
| 251 |
+
if mem == "full":
|
| 252 |
+
cond = "with_history"
|
| 253 |
+
elif chain:
|
| 254 |
+
cond = "memory_free_retry"
|
| 255 |
+
else:
|
| 256 |
+
cond = "independent_single_attempt"
|
| 257 |
+
return cond, chain
|
| 258 |
+
|
| 259 |
+
def outcome_class(self):
|
| 260 |
+
"""CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None."""
|
| 261 |
+
att = self.attempts()
|
| 262 |
+
if not att or self.start.get("memory") != "full":
|
| 263 |
+
return None, "".join("S" if a["success"] else "F" for a in att)
|
| 264 |
+
hist = "".join("S" if a["success"] else "F" for a in att)
|
| 265 |
+
if att[0]["success"]:
|
| 266 |
+
ev = error_event(att[0]["outcome"])
|
| 267 |
+
cls = "S?" if ev is None else ("IR" if ev else "CS")
|
| 268 |
+
else:
|
| 269 |
+
cls = "XR" if any(a["success"] for a in att) else "F"
|
| 270 |
+
return cls, hist
|
| 271 |
+
|
| 272 |
+
def agent_info(self):
|
| 273 |
+
h, en = self.harness, self.entry
|
| 274 |
+
hdr = self.headers[0] if self.headers else {}
|
| 275 |
+
return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"),
|
| 276 |
+
harness_version=h.get("version") or hdr.get("version"),
|
| 277 |
+
harness_binary_sha256=(h.get("binary") or {}).get("sha256"),
|
| 278 |
+
model=h.get("model") or en.get("model") or hdr.get("model_name"),
|
| 279 |
+
effort=h.get("effort") or en.get("effort") or hdr.get("effort"),
|
| 280 |
+
provider=h.get("provider") or en.get("provider"),
|
| 281 |
+
codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"),
|
| 282 |
+
jail=en.get("jail"))
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
# ====================================================================================================== recording
|
| 286 |
+
|
| 287 |
+
class EpisodeSink:
|
| 288 |
+
"""Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed."""
|
| 289 |
+
|
| 290 |
+
def __init__(self, path):
|
| 291 |
+
self.path = path
|
| 292 |
+
os.makedirs(path, exist_ok=True)
|
| 293 |
+
self.w = None
|
| 294 |
+
self.num = defaultdict(list)
|
| 295 |
+
self.n = 0
|
| 296 |
+
|
| 297 |
+
def add(self, st, imgs):
|
| 298 |
+
import imageio
|
| 299 |
+
if self.w is None:
|
| 300 |
+
self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb",
|
| 301 |
+
pixelformat="rgb24", macro_block_size=1,
|
| 302 |
+
ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error")
|
| 303 |
+
for k in ("agentview", "wrist")]
|
| 304 |
+
for w, im in zip(self.w, imgs):
|
| 305 |
+
w.append_data(im)
|
| 306 |
+
for k, v in st.items():
|
| 307 |
+
self.num[k].append(v)
|
| 308 |
+
self.n += 1
|
| 309 |
+
|
| 310 |
+
def close(self, final_state, final_imgs):
|
| 311 |
+
from PIL import Image
|
| 312 |
+
if self.w is not None:
|
| 313 |
+
for w in self.w:
|
| 314 |
+
w.close()
|
| 315 |
+
arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"}
|
| 316 |
+
np.savez(os.path.join(self.path, "frames.npz"), **arr)
|
| 317 |
+
if self.num.get("sim_state"):
|
| 318 |
+
np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64))
|
| 319 |
+
np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()})
|
| 320 |
+
for k, im in zip(("agentview", "wrist"), final_imgs):
|
| 321 |
+
Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png"))
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
class Recorder:
|
| 325 |
+
"""Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink."""
|
| 326 |
+
|
| 327 |
+
def __init__(self, rp, res):
|
| 328 |
+
self.rp, self.res = rp, int(res)
|
| 329 |
+
self.active = False
|
| 330 |
+
self.sink = None
|
| 331 |
+
self.cur = dict(attempt=1, command=-1, phase=PHASES["move"])
|
| 332 |
+
env = rp.task.env
|
| 333 |
+
self.env, self.rob = env, env.robots[0]
|
| 334 |
+
self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist"))
|
| 335 |
+
orig = env.step
|
| 336 |
+
|
| 337 |
+
def step(a):
|
| 338 |
+
if self.active and self.sink is not None:
|
| 339 |
+
self.capture(np.asarray(a, np.float64))
|
| 340 |
+
out = orig(a)
|
| 341 |
+
if self.active and self.sink is not None:
|
| 342 |
+
self.rp.poll_events(self.sink.n - 1)
|
| 343 |
+
return out
|
| 344 |
+
|
| 345 |
+
env.step = step
|
| 346 |
+
|
| 347 |
+
@property
|
| 348 |
+
def n(self):
|
| 349 |
+
return self.sink.n if self.sink is not None else 0
|
| 350 |
+
|
| 351 |
+
def state(self):
|
| 352 |
+
import robosuite.utils.transform_utils as T
|
| 353 |
+
env, rob = self.env, self.rob
|
| 354 |
+
d = env.sim.data
|
| 355 |
+
eef = np.array(d.site_xpos[rob.eef_site_id], np.float64)
|
| 356 |
+
q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw")
|
| 357 |
+
gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64)
|
| 358 |
+
try:
|
| 359 |
+
flat = np.asarray(env.sim.get_state().flatten(), np.float64)
|
| 360 |
+
except Exception:
|
| 361 |
+
flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64)
|
| 362 |
+
sk = self.rp.task.sk
|
| 363 |
+
return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64),
|
| 364 |
+
gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64),
|
| 365 |
+
joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64),
|
| 366 |
+
gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64),
|
| 367 |
+
eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)),
|
| 368 |
+
sim_time=np.float64(d.time), sim_state=flat)
|
| 369 |
+
|
| 370 |
+
def images(self):
|
| 371 |
+
return [envs.render(self.env, c, self.res) for c in self.cams]
|
| 372 |
+
|
| 373 |
+
def capture(self, a):
|
| 374 |
+
st = self.state()
|
| 375 |
+
st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]),
|
| 376 |
+
phase=np.int64(self.cur["phase"]))
|
| 377 |
+
self.sink.add(st, self.images())
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
class RunReplay:
|
| 381 |
+
def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None):
|
| 382 |
+
self.run_dir = os.path.abspath(run_dir.rstrip("/"))
|
| 383 |
+
self.run_name = os.path.basename(self.run_dir)
|
| 384 |
+
self.log = RunLog(self.run_dir, manifest)
|
| 385 |
+
self.ev = self.log.ev
|
| 386 |
+
self.start = self.log.start
|
| 387 |
+
cp = os.path.join(self.run_dir, "contract.json")
|
| 388 |
+
self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {}
|
| 389 |
+
spec = self.contract.get("image_spec") or {}
|
| 390 |
+
self.image_res = int(spec.get("width", 512))
|
| 391 |
+
self.code_diff = check_code(self.run_dir)
|
| 392 |
+
s = self.start
|
| 393 |
+
self.task = TASKS[s["task"]](cam_res=self.image_res)
|
| 394 |
+
inst = self.task.sample_instance(s["seed"])
|
| 395 |
+
logged = s.get("inst") or {}
|
| 396 |
+
sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")})
|
| 397 |
+
self.inst_diff = diff_json(sampled, logged, "inst")
|
| 398 |
+
if s.get("arm", "none") not in (None, "none") or logged.get("nominal"):
|
| 399 |
+
inst.update(logged) # controlled arms / nominal: the server overrode these instance fields
|
| 400 |
+
self.inst_diff = []
|
| 401 |
+
self.inst = inst
|
| 402 |
+
self.protocol = getattr(self.task, "protocol", "cross")
|
| 403 |
+
self.k = int(s.get("k") or self.task.max_attempts)
|
| 404 |
+
self.attempt = 1
|
| 405 |
+
self.mismatch = [] # (where, what, logged, replayed)
|
| 406 |
+
self.n_checked = 0
|
| 407 |
+
self.max_dev_m = 0.0
|
| 408 |
+
self.unfinished = None
|
| 409 |
+
self.rec = Recorder(self, res) if record else None
|
| 410 |
+
self.res = int(res)
|
| 411 |
+
self.out_root = out_root
|
| 412 |
+
self.n_mon = 0
|
| 413 |
+
self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0
|
| 414 |
+
self.episodes = [] # summaries of the written episodes
|
| 415 |
+
self.task.reset_instance(self.inst)
|
| 416 |
+
self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
|
| 417 |
+
sim = self.task.env.sim
|
| 418 |
+
bid = sim.model.body_name2id("robot0_base")
|
| 419 |
+
self.base_off = np.array(sim.data.body_xpos[bid], float).copy()
|
| 420 |
+
if self.rec:
|
| 421 |
+
self._open_episode()
|
| 422 |
+
|
| 423 |
+
# ------------------------------------------------------------------ episodes
|
| 424 |
+
def _ep_dir(self):
|
| 425 |
+
return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}")
|
| 426 |
+
|
| 427 |
+
def _open_episode(self):
|
| 428 |
+
self.rec.sink = EpisodeSink(self._ep_dir())
|
| 429 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
|
| 430 |
+
self.rec.active = True
|
| 431 |
+
self.events, self.spans, self.ep_attempts = [], [], []
|
| 432 |
+
self.ep_initial = self.rec.state() # state right after the reset (before frame 0)
|
| 433 |
+
|
| 434 |
+
def close_episode(self):
|
| 435 |
+
if not self.rec:
|
| 436 |
+
self.ep_attempts = []
|
| 437 |
+
return
|
| 438 |
+
sink = self.rec.sink
|
| 439 |
+
st = self.rec.state()
|
| 440 |
+
imgs = self.rec.images()
|
| 441 |
+
st.pop("sim_state", None)
|
| 442 |
+
sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs)
|
| 443 |
+
ann = build_annotation(self, sink)
|
| 444 |
+
with open(os.path.join(sink.path, "annotation.json"), "w") as f:
|
| 445 |
+
json.dump(ann, f, indent=1, default=_json_default)
|
| 446 |
+
self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n,
|
| 447 |
+
attempts=[a["attempt"] for a in self.ep_attempts]))
|
| 448 |
+
self.rec.active = False
|
| 449 |
+
self.rec.sink = None
|
| 450 |
+
self.ep_index += 1
|
| 451 |
+
|
| 452 |
+
# ------------------------------------------------------------------ monitor events (task-side error events)
|
| 453 |
+
def poll_events(self, frame):
|
| 454 |
+
mon = getattr(self.task, "mon", None)
|
| 455 |
+
evs = mon.get("events") if isinstance(mon, dict) else None
|
| 456 |
+
if not isinstance(evs, list):
|
| 457 |
+
return
|
| 458 |
+
if len(evs) < self.n_mon: # monitor was rebuilt
|
| 459 |
+
self.n_mon = 0
|
| 460 |
+
for e in evs[self.n_mon:]:
|
| 461 |
+
self.events.append(dict(frame=int(frame), attempt=self.attempt,
|
| 462 |
+
event=norm_json(e) if isinstance(e, dict) else str(e)))
|
| 463 |
+
self.n_mon = len(evs)
|
| 464 |
+
|
| 465 |
+
# ------------------------------------------------------------------ state as the server reports it
|
| 466 |
+
def proprio_la(self):
|
| 467 |
+
p = self.ex.proprio()
|
| 468 |
+
pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off]
|
| 469 |
+
return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"])
|
| 470 |
+
|
| 471 |
+
def compare(self, where, rep_logged, rep):
|
| 472 |
+
self.n_checked += 1
|
| 473 |
+
for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"):
|
| 474 |
+
if k not in rep_logged or k not in rep:
|
| 475 |
+
continue
|
| 476 |
+
a, b = rep_logged[k], rep[k]
|
| 477 |
+
if k == "eef_pos":
|
| 478 |
+
dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float))))
|
| 479 |
+
self.max_dev_m = max(self.max_dev_m, dev)
|
| 480 |
+
if dev > 1.5e-4:
|
| 481 |
+
self.mismatch.append((where, k, a, b))
|
| 482 |
+
elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4):
|
| 483 |
+
self.mismatch.append((where, k, a, b))
|
| 484 |
+
if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)):
|
| 485 |
+
self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok")))
|
| 486 |
+
|
| 487 |
+
def _span(self, e, f0, kind):
|
| 488 |
+
if self.rec:
|
| 489 |
+
self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0,
|
| 490 |
+
frame_end=self.rec.n))
|
| 491 |
+
|
| 492 |
+
# ------------------------------------------------------------------ commands (robot_server._handle_v2)
|
| 493 |
+
def move_eef(self, e):
|
| 494 |
+
args = e.get("args") or {}
|
| 495 |
+
where = f"a{e['attempt']}s{e['step']}"
|
| 496 |
+
logged = e.get("report") or {}
|
| 497 |
+
f0 = self.rec.n if self.rec else 0
|
| 498 |
+
p = self.ex.proprio()
|
| 499 |
+
if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}:
|
| 500 |
+
self._span(e, f0, "error")
|
| 501 |
+
return self.compare(where, logged, dict(ok=False))
|
| 502 |
+
off = self.base_off
|
| 503 |
+
try:
|
| 504 |
+
cur = np.asarray(p["eef_pos"], float) - off
|
| 505 |
+
tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
|
| 506 |
+
yaw = float(args.get("yaw", p["eef_yaw_deg"]))
|
| 507 |
+
speed = None if args.get("speed") in (None, "") else float(args["speed"])
|
| 508 |
+
except (TypeError, ValueError):
|
| 509 |
+
self._span(e, f0, "error")
|
| 510 |
+
return self.compare(where, logged, dict(ok=False))
|
| 511 |
+
grip = args.get("gripper")
|
| 512 |
+
if grip not in (None, "open", "close"):
|
| 513 |
+
self._span(e, f0, "error")
|
| 514 |
+
return self.compare(where, logged, dict(ok=False))
|
| 515 |
+
moving = any(k in args for k in ("x", "y", "z", "yaw"))
|
| 516 |
+
tgt_w = np.asarray(tgt) + off
|
| 517 |
+
if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)):
|
| 518 |
+
self._span(e, f0, "rejected")
|
| 519 |
+
return self.compare(where, logged, dict(ok=False, **self.proprio_la()))
|
| 520 |
+
raw = {}
|
| 521 |
+
if self.rec:
|
| 522 |
+
self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"])
|
| 523 |
+
if moving:
|
| 524 |
+
mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw)
|
| 525 |
+
if speed is not None:
|
| 526 |
+
mv["speed"] = speed
|
| 527 |
+
raw.update(self.ex.call("move_to", mv).report)
|
| 528 |
+
if grip is not None:
|
| 529 |
+
if self.rec:
|
| 530 |
+
self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"])
|
| 531 |
+
raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report)
|
| 532 |
+
rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la())
|
| 533 |
+
self.compare(where, logged, rep)
|
| 534 |
+
lr = e.get("raw") or {}
|
| 535 |
+
for k in ("holding_object", "touched_object"):
|
| 536 |
+
if k in lr and k in raw and bool(lr[k]) != bool(raw[k]):
|
| 537 |
+
self.mismatch.append((where, "raw." + k, lr[k], raw[k]))
|
| 538 |
+
self._span(e, f0, "move_eef")
|
| 539 |
+
|
| 540 |
+
def observe(self, e):
|
| 541 |
+
f0 = self.rec.n if self.rec else 0
|
| 542 |
+
self._span(e, f0, "observe")
|
| 543 |
+
|
| 544 |
+
def done(self, e):
|
| 545 |
+
f0 = self.rec.n if self.rec else 0
|
| 546 |
+
if self.rec:
|
| 547 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"])
|
| 548 |
+
out = self.task.outcome(self.inst)
|
| 549 |
+
succ = bool(out["success"])
|
| 550 |
+
where = f"a{e['attempt']}done"
|
| 551 |
+
if succ != bool(e.get("success") in (True, "True")):
|
| 552 |
+
self.mismatch.append((where, "success", e.get("success"), succ))
|
| 553 |
+
lo = e.get("outcome") or {}
|
| 554 |
+
ro = norm_json({k: v for k, v in out.items() if k != "feedback"})
|
| 555 |
+
if isinstance(lo, dict):
|
| 556 |
+
for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8):
|
| 557 |
+
self.mismatch.append((where,) + d)
|
| 558 |
+
info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""),
|
| 559 |
+
feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")),
|
| 560 |
+
think_s=e.get("think_s"))
|
| 561 |
+
try:
|
| 562 |
+
info["feedback_f2"] = self.task.feedback(self.inst, out, "F2")
|
| 563 |
+
except Exception as ex_:
|
| 564 |
+
info["feedback_f2"] = f"<unavailable: {type(ex_).__name__}>"
|
| 565 |
+
if self.rec:
|
| 566 |
+
info["judge_frames"] = [f0, self.rec.n]
|
| 567 |
+
self.ep_attempts.append(info)
|
| 568 |
+
last = self.attempt >= self.k or succ or bool(out.get("terminal"))
|
| 569 |
+
if self.protocol == "cross" or last:
|
| 570 |
+
self.close_episode()
|
| 571 |
+
if last:
|
| 572 |
+
return True
|
| 573 |
+
self.attempt += 1
|
| 574 |
+
if self.protocol == "cross":
|
| 575 |
+
self.task.reset_instance(self.inst)
|
| 576 |
+
self.n_mon = 0
|
| 577 |
+
if self.rec:
|
| 578 |
+
self._open_episode()
|
| 579 |
+
elif self.rec:
|
| 580 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
|
| 581 |
+
self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
|
| 582 |
+
return False
|
| 583 |
+
|
| 584 |
+
def run(self):
|
| 585 |
+
t0 = time.time()
|
| 586 |
+
finished = False
|
| 587 |
+
for e in self.ev:
|
| 588 |
+
if e["ev"] == "call":
|
| 589 |
+
if e.get("cmd") == "move_eef":
|
| 590 |
+
self.move_eef(e)
|
| 591 |
+
elif e.get("cmd") == "observe":
|
| 592 |
+
self.observe(e)
|
| 593 |
+
else:
|
| 594 |
+
self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None))
|
| 595 |
+
elif e["ev"] == "done":
|
| 596 |
+
finished = self.done(e)
|
| 597 |
+
if finished:
|
| 598 |
+
break
|
| 599 |
+
self.unfinished = not finished
|
| 600 |
+
if not finished and self.rec and self.rec.sink is not None:
|
| 601 |
+
# the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged
|
| 602 |
+
if self.rec.n or self.ep_attempts:
|
| 603 |
+
self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True,
|
| 604 |
+
finish_reason="", feedback_shown="", auto_ended=False))
|
| 605 |
+
self.close_episode()
|
| 606 |
+
else:
|
| 607 |
+
shutil.rmtree(self.rec.sink.path, ignore_errors=True)
|
| 608 |
+
self.rec.sink = None
|
| 609 |
+
self.wall_s = time.time() - t0
|
| 610 |
+
return self
|
| 611 |
+
|
| 612 |
+
def summary(self):
|
| 613 |
+
return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"],
|
| 614 |
+
protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff),
|
| 615 |
+
n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6),
|
| 616 |
+
unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1),
|
| 617 |
+
first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]])
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
# ====================================================================================================== annotation
|
| 621 |
+
|
| 622 |
+
def task_info(task, inst):
|
| 623 |
+
cls = type(task)
|
| 624 |
+
return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable",
|
| 625 |
+
category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"),
|
| 626 |
+
max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)),
|
| 627 |
+
instruction=cls.instruction)
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
def build_annotation(rp, sink):
|
| 631 |
+
"""Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2
|
| 632 |
+
failure description), run-level outcome class, every robot command with its frame span and the agent's narration,
|
| 633 |
+
task-side error events with frame indices."""
|
| 634 |
+
log = rp.log
|
| 635 |
+
s = rp.start
|
| 636 |
+
cond, chain = log.condition()
|
| 637 |
+
cls, hist = log.outcome_class()
|
| 638 |
+
att_all = log.attempts()
|
| 639 |
+
attempts = []
|
| 640 |
+
for a in rp.ep_attempts:
|
| 641 |
+
a = dict(a)
|
| 642 |
+
n = a["attempt"]
|
| 643 |
+
later = [x for x in att_all if x["attempt"] > n]
|
| 644 |
+
a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later))
|
| 645 |
+
a["is_last_attempt_of_run"] = not later
|
| 646 |
+
fn = log.finish_notes.get(n)
|
| 647 |
+
if fn:
|
| 648 |
+
a["agent_finish"] = fn
|
| 649 |
+
a["error_event_in_attempt"] = error_event(a.get("outcome"))
|
| 650 |
+
attempts.append(a)
|
| 651 |
+
# post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command)
|
| 652 |
+
for a in attempts:
|
| 653 |
+
nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1])
|
| 654 |
+
if a.get("success") is False and nxt:
|
| 655 |
+
note = log.notes[nxt[0]]
|
| 656 |
+
a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note}
|
| 657 |
+
commands = []
|
| 658 |
+
for sp in rp.spans:
|
| 659 |
+
e = log.calls.get((sp["attempt"], sp["step"])) or {}
|
| 660 |
+
rep = e.get("report") or {}
|
| 661 |
+
c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"],
|
| 662 |
+
frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]),
|
| 663 |
+
args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"),
|
| 664 |
+
stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"),
|
| 665 |
+
gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"),
|
| 666 |
+
touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"),
|
| 667 |
+
agent_obs_images=rep.get("images"))
|
| 668 |
+
note = log.notes.get((sp["attempt"], sp["step"]))
|
| 669 |
+
if note:
|
| 670 |
+
c["agent_note"] = {k: v for k, v in note.items() if k != "command"}
|
| 671 |
+
commands.append(c)
|
| 672 |
+
t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x]
|
| 673 |
+
return dict(
|
| 674 |
+
schema=SCHEMA,
|
| 675 |
+
source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts],
|
| 676 |
+
episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain,
|
| 677 |
+
memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None),
|
| 678 |
+
feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"),
|
| 679 |
+
k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"),
|
| 680 |
+
contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256")
|
| 681 |
+
if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)),
|
| 682 |
+
agent=log.agent_info(),
|
| 683 |
+
task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"),
|
| 684 |
+
instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}),
|
| 685 |
+
run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all),
|
| 686 |
+
run_success=any(x["success"] for x in att_all) if att_all else None,
|
| 687 |
+
agent_final_report=log.final_report[:6000] or None,
|
| 688 |
+
mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)),
|
| 689 |
+
attempts=attempts,
|
| 690 |
+
commands=commands,
|
| 691 |
+
task_events=rp.events,
|
| 692 |
+
frames=dict(n=sink.n, fps=FPS, image_res=rp.res,
|
| 693 |
+
phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"],
|
| 694 |
+
joint_pos=rp.ep_initial["joint_pos"],
|
| 695 |
+
gripper_qpos=rp.ep_initial["gripper_qpos"])),
|
| 696 |
+
)
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
# ====================================================================================================== CLI
|
| 700 |
+
|
| 701 |
+
def load_manifest(run_dir):
|
| 702 |
+
p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json")
|
| 703 |
+
return json.load(open(p)) if os.path.exists(p) else {}
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
def main():
|
| 707 |
+
ap = argparse.ArgumentParser()
|
| 708 |
+
ap.add_argument("mode", choices=["check", "record"])
|
| 709 |
+
ap.add_argument("runs", nargs="+")
|
| 710 |
+
ap.add_argument("--json", default="")
|
| 711 |
+
ap.add_argument("--out", default="")
|
| 712 |
+
ap.add_argument("--res", type=int, default=256)
|
| 713 |
+
ap.add_argument("--force", action="store_true", help="record again even if replay.json exists")
|
| 714 |
+
a = ap.parse_args()
|
| 715 |
+
rows = []
|
| 716 |
+
for r in a.runs:
|
| 717 |
+
r = r.rstrip("/")
|
| 718 |
+
try:
|
| 719 |
+
if a.mode == "check":
|
| 720 |
+
s = RunReplay(r, manifest=load_manifest(r)).run().summary()
|
| 721 |
+
else:
|
| 722 |
+
batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r)
|
| 723 |
+
rd = os.path.join(a.out, batch, name)
|
| 724 |
+
if os.path.exists(os.path.join(rd, "replay.json")) and not a.force:
|
| 725 |
+
print(json.dumps(dict(run=name, skipped="exists")), flush=True)
|
| 726 |
+
continue
|
| 727 |
+
shutil.rmtree(rd, ignore_errors=True)
|
| 728 |
+
rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run()
|
| 729 |
+
s = rp.summary()
|
| 730 |
+
s["episodes"] = rp.episodes
|
| 731 |
+
with open(os.path.join(rd, "replay.json"), "w") as f:
|
| 732 |
+
json.dump(s, f, indent=1)
|
| 733 |
+
except Exception:
|
| 734 |
+
import traceback
|
| 735 |
+
s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:])
|
| 736 |
+
rows.append(s)
|
| 737 |
+
print(json.dumps(s), flush=True)
|
| 738 |
+
if a.json:
|
| 739 |
+
with open(a.json, "w") as f:
|
| 740 |
+
json.dump(rows, f, indent=1)
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
if __name__ == "__main__":
|
| 744 |
+
main()
|
leaf/code/supp-20261113-g61_evofull_20261025/lerobot_export.py
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars.
|
| 2 |
+
|
| 3 |
+
Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding
|
| 4 |
+
can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan):
|
| 5 |
+
|
| 6 |
+
python scripts/lerobot_export.py plan --raw <raw_root>[,<raw_root2>] --runs-root <lffbench>/runs/api \
|
| 7 |
+
--paper <paper/latex> --task-set <lffbench>/sets/main_v2_1inst.txt --work <work_dir> [--batches ...] [--limit N]
|
| 8 |
+
python scripts/lerobot_export.py shard --work <work_dir> --shard i --nshards N
|
| 9 |
+
python scripts/lerobot_export.py merge --work <work_dir> --nshards N --out <dataset_root>
|
| 10 |
+
|
| 11 |
+
Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0
|
| 12 |
+
mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped.
|
| 13 |
+
|
| 14 |
+
LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t):
|
| 15 |
+
observation.images.image agentview RGB 256x256 (upright; LIBERO naming)
|
| 16 |
+
observation.images.wrist_image wrist (eye-in-hand) RGB 256x256
|
| 17 |
+
observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout)
|
| 18 |
+
observation.joint_pos / joint_vel 7 arm joints (rad, rad/s)
|
| 19 |
+
observation.eef_quat 4: xyzw; observation.gripper_width 1 (m)
|
| 20 |
+
action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad),
|
| 21 |
+
gripper (-1 open, +1 close)
|
| 22 |
+
annotation.attempt_index attempt (1-based) the frame belongs to
|
| 23 |
+
annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`)
|
| 24 |
+
annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action)
|
| 25 |
+
annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt
|
| 26 |
+
annotation.task_event number of task-monitor events (error / progress events) registered at this step
|
| 27 |
+
Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table),
|
| 28 |
+
runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state
|
| 29 |
+
per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/.
|
| 30 |
+
"""
|
| 31 |
+
import argparse
|
| 32 |
+
import glob
|
| 33 |
+
import json
|
| 34 |
+
import os
|
| 35 |
+
import re
|
| 36 |
+
import shutil
|
| 37 |
+
import time
|
| 38 |
+
|
| 39 |
+
import numpy as np
|
| 40 |
+
|
| 41 |
+
FPS = 20
|
| 42 |
+
RES = 256
|
| 43 |
+
BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke",
|
| 44 |
+
"cc_smoke", "cc_opus_smoke"]
|
| 45 |
+
BATCH_NOTES = {
|
| 46 |
+
"cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog",
|
| 47 |
+
"cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267",
|
| 48 |
+
"cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299",
|
| 49 |
+
"cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances",
|
| 50 |
+
"cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)",
|
| 51 |
+
"cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the "
|
| 52 |
+
"with-history continuation of failed runs is incomplete",
|
| 53 |
+
"cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early",
|
| 54 |
+
"cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt",
|
| 55 |
+
"cc_opus_smoke": "smoke test: single attempt",
|
| 56 |
+
}
|
| 57 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 58 |
+
CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)",
|
| 59 |
+
"L2": "disturbed state to restore (incl. damage the agent causes)",
|
| 60 |
+
"L3": "infeasible manipulation strategy (grasp / contact / tool must change)",
|
| 61 |
+
"L4": "misjudged geometry (size, shape, fit, hidden structure)",
|
| 62 |
+
"L5": "misjudged physics (mass distribution, friction, dynamics)"}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def features():
|
| 66 |
+
vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]}
|
| 67 |
+
f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names}
|
| 68 |
+
i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None}
|
| 69 |
+
return {
|
| 70 |
+
"observation.images.image": vid(),
|
| 71 |
+
"observation.images.wrist_image": vid(),
|
| 72 |
+
"observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z",
|
| 73 |
+
"finger_qpos_left", "finger_qpos_right"]),
|
| 74 |
+
"observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 75 |
+
"observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 76 |
+
"observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]),
|
| 77 |
+
"observation.gripper_width": f32(1, ["width_m"]),
|
| 78 |
+
"action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y",
|
| 79 |
+
"eef_delta_rot_aa_z", "gripper_close"]),
|
| 80 |
+
"annotation.attempt_index": i64(),
|
| 81 |
+
"annotation.command_index": i64(),
|
| 82 |
+
"annotation.phase": i64(),
|
| 83 |
+
"annotation.attempt_success": i64(),
|
| 84 |
+
"annotation.task_event": i64(),
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ------------------------------------------------------------------------------------------------ paper metadata
|
| 89 |
+
|
| 90 |
+
def _clean_tex(s):
|
| 91 |
+
s = re.sub(r"%.*", "", s)
|
| 92 |
+
for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"),
|
| 93 |
+
(r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"),
|
| 94 |
+
(r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"),
|
| 95 |
+
(r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"),
|
| 96 |
+
(r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]:
|
| 97 |
+
s = re.sub(a, b, s)
|
| 98 |
+
s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s)
|
| 99 |
+
s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s)
|
| 100 |
+
for _ in range(3):
|
| 101 |
+
s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s)
|
| 102 |
+
s = re.sub(r"\$([^$]*)\$", r"\1", s)
|
| 103 |
+
s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ")
|
| 104 |
+
s = re.sub(r"\{([^{}]*)\}", r"\1", s)
|
| 105 |
+
s = re.sub(r"\\[a-zA-Z]+\*?", "", s)
|
| 106 |
+
return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def paper_tasks(paper_dir):
|
| 110 |
+
"""{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the
|
| 111 |
+
paper's task table and task appendix (empty if the paper sources are not there)."""
|
| 112 |
+
out = {}
|
| 113 |
+
if not paper_dir:
|
| 114 |
+
return out
|
| 115 |
+
app = os.path.join(paper_dir, "sections", "appendix_tasks.tex")
|
| 116 |
+
tab = os.path.join(paper_dir, "sections", "tab_tasks.tex")
|
| 117 |
+
if os.path.exists(app):
|
| 118 |
+
txt = open(app).read()
|
| 119 |
+
parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt)
|
| 120 |
+
for i in range(1, len(parts) - 1, 2):
|
| 121 |
+
if parts[i] != "\\paragraph{":
|
| 122 |
+
continue
|
| 123 |
+
body = parts[i + 1]
|
| 124 |
+
m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S)
|
| 125 |
+
if not m:
|
| 126 |
+
continue
|
| 127 |
+
name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip()
|
| 128 |
+
desc = _clean_tex(body[m.end():])
|
| 129 |
+
out[code] = dict(name=name, cause=_clean_tex(cause), description=desc)
|
| 130 |
+
if os.path.exists(tab):
|
| 131 |
+
names = {v["name"].lower(): k for k, v in out.items()}
|
| 132 |
+
for line in open(tab):
|
| 133 |
+
cells = [c.strip() for c in line.split("&")]
|
| 134 |
+
if len(cells) != 6 or not cells[-1].endswith("\\\\"):
|
| 135 |
+
continue
|
| 136 |
+
nm = re.sub(r"\\contscene", "", cells[0]).strip().lower()
|
| 137 |
+
code = names.get(nm)
|
| 138 |
+
if not code:
|
| 139 |
+
continue
|
| 140 |
+
out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]),
|
| 141 |
+
repair_within_attempt=_clean_tex(cells[3]) == "yes",
|
| 142 |
+
oracle_first_attempt_pct=_clean_tex(cells[4]),
|
| 143 |
+
naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip()))
|
| 144 |
+
return out
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
# ------------------------------------------------------------------------------------------------ collection
|
| 148 |
+
|
| 149 |
+
def manifest_status(runs_root, batch, run, cache={}):
|
| 150 |
+
if batch not in cache:
|
| 151 |
+
p = os.path.join(runs_root, batch, "manifest.json")
|
| 152 |
+
cache[batch] = json.load(open(p)) if os.path.exists(p) else {}
|
| 153 |
+
m = cache[batch]
|
| 154 |
+
for r in m.get("runs", []):
|
| 155 |
+
if r.get("run") == run:
|
| 156 |
+
return r.get("status", "?"), r
|
| 157 |
+
for r in m.get("superseded", []):
|
| 158 |
+
if r.get("run") == run:
|
| 159 |
+
return "superseded_" + str(r.get("status", "?")), r
|
| 160 |
+
return "not_in_manifest", {}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def collect(raw_roots, runs_root, batches, task_order):
|
| 164 |
+
"""Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root."""
|
| 165 |
+
eps, rejected, seen = [], [], set()
|
| 166 |
+
for root in raw_roots:
|
| 167 |
+
for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))):
|
| 168 |
+
rep = json.load(open(rj))
|
| 169 |
+
batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"]
|
| 170 |
+
if (batches and batch not in batches) or (batch, run) in seen:
|
| 171 |
+
continue
|
| 172 |
+
seen.add((batch, run))
|
| 173 |
+
ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff")
|
| 174 |
+
status, entry = manifest_status(runs_root, batch, run)
|
| 175 |
+
if not ok:
|
| 176 |
+
never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked")
|
| 177 |
+
rejected.append(dict(run=run, batch=batch, run_status=status,
|
| 178 |
+
reason="run never started (no contract, no robot command)" if never else
|
| 179 |
+
"replay does not reproduce the log (the log has gaps or the replay diverged)",
|
| 180 |
+
detail=rep.get("first_mismatches")))
|
| 181 |
+
continue
|
| 182 |
+
for ep in rep.get("episodes", []):
|
| 183 |
+
d = os.path.join(root, ep["dir"])
|
| 184 |
+
ann = json.load(open(os.path.join(d, "annotation.json")))
|
| 185 |
+
judged = [a for a in ann["attempts"] if a.get("success") is not None]
|
| 186 |
+
if not judged or ep["n_frames"] == 0:
|
| 187 |
+
rejected.append(dict(run=run, batch=batch, episode=ep["dir"],
|
| 188 |
+
reason="no judged attempt" if not judged else "no frames"))
|
| 189 |
+
continue
|
| 190 |
+
ann["source"]["run_status"] = status
|
| 191 |
+
ann["source"]["manifest_id"] = entry.get("id")
|
| 192 |
+
ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"],
|
| 193 |
+
max_eef_dev_m=rep["max_eef_dev_m"])
|
| 194 |
+
key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99),
|
| 195 |
+
{"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2),
|
| 196 |
+
ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"])
|
| 197 |
+
eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann))
|
| 198 |
+
eps.sort(key=lambda x: x["key"])
|
| 199 |
+
return eps, rejected
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# ------------------------------------------------------------------------------------------------ writing
|
| 203 |
+
|
| 204 |
+
def frames_of(path):
|
| 205 |
+
import av
|
| 206 |
+
with av.open(path) as c:
|
| 207 |
+
for fr in c.decode(video=0):
|
| 208 |
+
yield fr.to_ndarray(format="rgb24")
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def flat_row(i, ann, n, idx0):
|
| 212 |
+
s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"]
|
| 213 |
+
att = ann["attempts"]
|
| 214 |
+
a0 = att[0]
|
| 215 |
+
return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n,
|
| 216 |
+
batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"],
|
| 217 |
+
memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"),
|
| 218 |
+
episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att],
|
| 219 |
+
harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"),
|
| 220 |
+
effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"),
|
| 221 |
+
task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"),
|
| 222 |
+
category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"],
|
| 223 |
+
success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att],
|
| 224 |
+
feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att],
|
| 225 |
+
auto_ended=[a.get("auto_ended") for a in att],
|
| 226 |
+
corrected_later_in_run=[a.get("corrected_later_in_run") for a in att],
|
| 227 |
+
error_event_in_attempt=[a.get("error_event_in_attempt") for a in att],
|
| 228 |
+
run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"),
|
| 229 |
+
n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]),
|
| 230 |
+
first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def cmd_plan(a):
|
| 234 |
+
task_order = {}
|
| 235 |
+
if a.task_set and os.path.exists(a.task_set):
|
| 236 |
+
for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")):
|
| 237 |
+
task_order[line.split(":")[0].strip()] = i
|
| 238 |
+
batches = [b for b in a.batches.split(",") if b] if a.batches else None
|
| 239 |
+
eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order)
|
| 240 |
+
if a.limit:
|
| 241 |
+
eps = eps[:a.limit]
|
| 242 |
+
paper = paper_tasks(a.paper)
|
| 243 |
+
idx0 = 0
|
| 244 |
+
for i, e in enumerate(eps):
|
| 245 |
+
ann = e["ann"]
|
| 246 |
+
tname = ann["task"]["name"]
|
| 247 |
+
if tname in paper:
|
| 248 |
+
ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"}
|
| 249 |
+
ann["episode_index"] = i
|
| 250 |
+
ann["dataset_index_range"] = [idx0, idx0 + e["n"]]
|
| 251 |
+
e["index"], e["from"] = i, idx0
|
| 252 |
+
idx0 += e["n"]
|
| 253 |
+
del e["key"]
|
| 254 |
+
os.makedirs(a.work, exist_ok=True)
|
| 255 |
+
with open(os.path.join(a.work, "plan.json"), "w") as f:
|
| 256 |
+
json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f,
|
| 257 |
+
ensure_ascii=False)
|
| 258 |
+
print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def shard_range(n_eps, i, k):
|
| 262 |
+
return (n_eps * i) // k, (n_eps * (i + 1)) // k
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def cmd_shard(a):
|
| 266 |
+
from lerobot.datasets.lerobot_dataset import LeRobotDataset
|
| 267 |
+
t0 = time.time()
|
| 268 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 269 |
+
eps = plan["episodes"]
|
| 270 |
+
lo, hi = shard_range(len(eps), a.shard, a.nshards)
|
| 271 |
+
out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}")
|
| 272 |
+
if os.path.exists(os.path.join(out, "DONE")):
|
| 273 |
+
print(f"shard {a.shard}: done already", flush=True)
|
| 274 |
+
return
|
| 275 |
+
shutil.rmtree(out, ignore_errors=True)
|
| 276 |
+
ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out,
|
| 277 |
+
robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads,
|
| 278 |
+
vcodec=a.vcodec)
|
| 279 |
+
nfr = 0
|
| 280 |
+
for e in eps[lo:hi]:
|
| 281 |
+
d, ann, n = e["dir"], e["ann"], e["n"]
|
| 282 |
+
fr = np.load(os.path.join(d, "frames.npz"))
|
| 283 |
+
assert len(fr["action"]) == n, d
|
| 284 |
+
succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]}
|
| 285 |
+
evc = np.zeros(n, np.int64)
|
| 286 |
+
for ev in ann["task_events"]:
|
| 287 |
+
if 0 <= ev["frame"] < n:
|
| 288 |
+
evc[ev["frame"]] += 1
|
| 289 |
+
state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32)
|
| 290 |
+
instr = ann["task"]["instruction"]
|
| 291 |
+
k = 0
|
| 292 |
+
for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))):
|
| 293 |
+
if k >= n:
|
| 294 |
+
break
|
| 295 |
+
ds.add_frame({
|
| 296 |
+
"observation.images.image": img, "observation.images.wrist_image": wr,
|
| 297 |
+
"observation.state": state[k],
|
| 298 |
+
"observation.joint_pos": fr["joint_pos"][k].astype(np.float32),
|
| 299 |
+
"observation.joint_vel": fr["joint_vel"][k].astype(np.float32),
|
| 300 |
+
"observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32),
|
| 301 |
+
"observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32),
|
| 302 |
+
"action": fr["action"][k].astype(np.float32),
|
| 303 |
+
"annotation.attempt_index": np.array([fr["attempt"][k]], np.int64),
|
| 304 |
+
"annotation.command_index": np.array([fr["command"][k]], np.int64),
|
| 305 |
+
"annotation.phase": np.array([fr["phase"][k]], np.int64),
|
| 306 |
+
"annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64),
|
| 307 |
+
"annotation.task_event": np.array([evc[k]], np.int64),
|
| 308 |
+
"task": instr,
|
| 309 |
+
})
|
| 310 |
+
k += 1
|
| 311 |
+
if k != n:
|
| 312 |
+
raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames")
|
| 313 |
+
ds.save_episode()
|
| 314 |
+
nfr += n
|
| 315 |
+
ds.finalize()
|
| 316 |
+
shutil.rmtree(os.path.join(out, "images"), ignore_errors=True)
|
| 317 |
+
open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n")
|
| 318 |
+
print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def cmd_merge(a):
|
| 322 |
+
from pathlib import Path
|
| 323 |
+
from lerobot.datasets.aggregate import aggregate_datasets
|
| 324 |
+
t0 = time.time()
|
| 325 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 326 |
+
eps = plan["episodes"]
|
| 327 |
+
roots, ids = [], []
|
| 328 |
+
for i in range(a.nshards):
|
| 329 |
+
lo, hi = shard_range(len(eps), i, a.nshards)
|
| 330 |
+
if hi <= lo:
|
| 331 |
+
continue
|
| 332 |
+
r = os.path.join(a.work, "shards", f"shard_{i:03d}")
|
| 333 |
+
if not os.path.exists(os.path.join(r, "DONE")):
|
| 334 |
+
raise SystemExit(f"shard {i} is not done")
|
| 335 |
+
roots.append(Path(r))
|
| 336 |
+
ids.append(f"{plan['repo_id']}-shard{i:03d}")
|
| 337 |
+
if os.path.exists(a.out):
|
| 338 |
+
raise SystemExit(f"{a.out} exists; refusing to overwrite")
|
| 339 |
+
aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out))
|
| 340 |
+
print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True)
|
| 341 |
+
write_sidecars(a, plan)
|
| 342 |
+
print(f"merge done in {time.time() - t0:.0f}s", flush=True)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def write_sidecars(a, plan):
|
| 346 |
+
eps, paper = plan["episodes"], plan["paper"]
|
| 347 |
+
lff = os.path.join(a.out, "lff")
|
| 348 |
+
for sub in ("annotations", "sim_state", "final", "code"):
|
| 349 |
+
os.makedirs(os.path.join(lff, sub), exist_ok=True)
|
| 350 |
+
rows, runs, tasks = [], {}, {}
|
| 351 |
+
for e in eps:
|
| 352 |
+
i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"]
|
| 353 |
+
name = f"episode_{i:06d}"
|
| 354 |
+
if os.path.exists(os.path.join(d, "sim_state.npy")):
|
| 355 |
+
shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy"))
|
| 356 |
+
shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz"))
|
| 357 |
+
for cam, key in (("agentview", "image"), ("wrist", "wrist_image")):
|
| 358 |
+
shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png"))
|
| 359 |
+
with open(os.path.join(lff, "annotations", name + ".json"), "w") as f:
|
| 360 |
+
json.dump(ann, f, indent=1, ensure_ascii=False)
|
| 361 |
+
rows.append(flat_row(i, ann, n, e["from"]))
|
| 362 |
+
tname = ann["task"]["name"]
|
| 363 |
+
rk = (ann["source"]["batch"], ann["source"]["run"])
|
| 364 |
+
r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"),
|
| 365 |
+
run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"],
|
| 366 |
+
memory_free_chain_of=ann["source"].get("memory_free_chain_of"),
|
| 367 |
+
memory_free_rep=ann["source"].get("memory_free_rep"), task=tname,
|
| 368 |
+
seed=ann["task"]["seed"], model=ann["agent"].get("model"),
|
| 369 |
+
harness=ann["agent"].get("harness"),
|
| 370 |
+
harness_version=ann["agent"].get("harness_version"),
|
| 371 |
+
codex_catalog=ann["agent"].get("codex_catalog"),
|
| 372 |
+
outcome_class=ann["run_outcome"].get("outcome_class"),
|
| 373 |
+
attempt_history=ann["run_outcome"].get("attempt_history"),
|
| 374 |
+
agent_final_report=ann["run_outcome"].get("agent_final_report"),
|
| 375 |
+
episodes=[]))
|
| 376 |
+
for x in ann["attempts"]:
|
| 377 |
+
r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success")))
|
| 378 |
+
if tname not in tasks:
|
| 379 |
+
tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")}
|
| 380 |
+
if tname in paper:
|
| 381 |
+
tasks[tname]["paper"] = paper[tname]
|
| 382 |
+
tasks[tname]["instances"] = {}
|
| 383 |
+
tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"]
|
| 384 |
+
# memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id)
|
| 385 |
+
by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")}
|
| 386 |
+
for r in runs.values():
|
| 387 |
+
if r.get("memory_free_chain_of"):
|
| 388 |
+
r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"]))
|
| 389 |
+
for (b, rn), r in runs.items():
|
| 390 |
+
r["memory_free_retries"] = sorted((x["run"] for x in runs.values()
|
| 391 |
+
if x["batch"] == b and x.get("memory_free_chain_of_run") == rn),
|
| 392 |
+
key=lambda q: runs[(b, q)].get("memory_free_rep") or 0)
|
| 393 |
+
with open(os.path.join(lff, "episodes.jsonl"), "w") as f:
|
| 394 |
+
for row in rows:
|
| 395 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 396 |
+
with open(os.path.join(lff, "runs.jsonl"), "w") as f:
|
| 397 |
+
for r in runs.values():
|
| 398 |
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 399 |
+
with open(os.path.join(lff, "tasks.json"), "w") as f:
|
| 400 |
+
json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False)
|
| 401 |
+
with open(os.path.join(lff, "batches.json"), "w") as f:
|
| 402 |
+
json.dump(BATCH_NOTES, f, indent=1)
|
| 403 |
+
with open(os.path.join(lff, "rejected.json"), "w") as f:
|
| 404 |
+
json.dump(plan["rejected"], f, indent=1)
|
| 405 |
+
here = os.path.dirname(os.path.abspath(__file__))
|
| 406 |
+
for s in ("lerobot_replay.py", "lerobot_export.py"):
|
| 407 |
+
shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s))
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def main():
|
| 411 |
+
ap = argparse.ArgumentParser()
|
| 412 |
+
ap.add_argument("step", choices=["plan", "shard", "merge"])
|
| 413 |
+
ap.add_argument("--work", required=True)
|
| 414 |
+
ap.add_argument("--raw", default="")
|
| 415 |
+
ap.add_argument("--runs-root", default="")
|
| 416 |
+
ap.add_argument("--out", default="")
|
| 417 |
+
ap.add_argument("--paper", default="")
|
| 418 |
+
ap.add_argument("--task-set", default="")
|
| 419 |
+
ap.add_argument("--repo-id", default="lffbench/agent-replays")
|
| 420 |
+
ap.add_argument("--batches", default="")
|
| 421 |
+
ap.add_argument("--limit", type=int, default=0)
|
| 422 |
+
ap.add_argument("--shard", type=int, default=0)
|
| 423 |
+
ap.add_argument("--nshards", type=int, default=1)
|
| 424 |
+
ap.add_argument("--threads", type=int, default=2)
|
| 425 |
+
ap.add_argument("--vcodec", default="libsvtav1")
|
| 426 |
+
a = ap.parse_args()
|
| 427 |
+
{"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
if __name__ == "__main__":
|
| 431 |
+
main()
|
leaf/code/supp-20261113-g61_evofull_20261025/lerobot_replay.py
ADDED
|
@@ -0,0 +1,744 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay
|
| 2 |
+
against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the
|
| 3 |
+
LeRobot export (scripts/lerobot_export.py).
|
| 4 |
+
|
| 5 |
+
python scripts/lerobot_replay.py check <run_dir> [<run_dir> ...] [--json out.json] # replay only, print fidelity
|
| 6 |
+
python scripts/lerobot_replay.py record <run_dir> --out <raw_root> [--res 256]
|
| 7 |
+
|
| 8 |
+
Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot
|
| 9 |
+
commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite
|
| 10 |
+
is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly
|
| 11 |
+
like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same
|
| 12 |
+
outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width,
|
| 13 |
+
ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code
|
| 14 |
+
hashes equal the current files are expected to match (check_code()).
|
| 15 |
+
|
| 16 |
+
Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB,
|
| 17 |
+
proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes:
|
| 18 |
+
protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode
|
| 19 |
+
per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the
|
| 20 |
+
fidelity check runs in record mode too. Per episode the recorder writes <raw_root>/<batch>/<run>/epNN/:
|
| 21 |
+
agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes)
|
| 22 |
+
frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase
|
| 23 |
+
sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel)
|
| 24 |
+
final_*.png, final.npz observation after the last control step (the state the outcome was judged in)
|
| 25 |
+
annotation.json episode annotation (build_annotation)
|
| 26 |
+
and <raw_root>/<batch>/<run>/replay.json (fidelity) when the whole run is done.
|
| 27 |
+
"""
|
| 28 |
+
import argparse
|
| 29 |
+
import ast
|
| 30 |
+
import hashlib
|
| 31 |
+
import importlib
|
| 32 |
+
import json
|
| 33 |
+
import math
|
| 34 |
+
import os
|
| 35 |
+
import pkgutil
|
| 36 |
+
import re
|
| 37 |
+
import shutil
|
| 38 |
+
import sys
|
| 39 |
+
import time
|
| 40 |
+
from collections import defaultdict
|
| 41 |
+
|
| 42 |
+
import numpy as np
|
| 43 |
+
|
| 44 |
+
LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 45 |
+
sys.path.insert(0, LFF_ROOT)
|
| 46 |
+
|
| 47 |
+
from lffbench import envs # noqa: E402
|
| 48 |
+
from lffbench import tasks as task_pkg # noqa: E402
|
| 49 |
+
from lffbench.agent import camera as C # noqa: E402
|
| 50 |
+
from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402
|
| 51 |
+
from lffbench.task_base import TASKS # noqa: E402
|
| 52 |
+
|
| 53 |
+
for _m in pkgutil.iter_modules(task_pkg.__path__):
|
| 54 |
+
importlib.import_module(f"lffbench.tasks.{_m.name}")
|
| 55 |
+
|
| 56 |
+
# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the
|
| 57 |
+
# task's outcome() check after `finish` (the arm holds still; not an agent action)
|
| 58 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 59 |
+
FPS = 20
|
| 60 |
+
SCHEMA = "lff-replay-1"
|
| 61 |
+
|
| 62 |
+
# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR"
|
| 63 |
+
ERROR_FLAGS = ("trap_fired", "recovered_in_attempt")
|
| 64 |
+
ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events",
|
| 65 |
+
"n_missed_strikes", "n_open_gripper_pushes")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def load_jsonl(p):
|
| 69 |
+
out = []
|
| 70 |
+
if not os.path.exists(p):
|
| 71 |
+
return out
|
| 72 |
+
with open(p) as f:
|
| 73 |
+
for line in f:
|
| 74 |
+
line = line.strip()
|
| 75 |
+
if line:
|
| 76 |
+
try:
|
| 77 |
+
out.append(json.loads(line))
|
| 78 |
+
except ValueError:
|
| 79 |
+
pass
|
| 80 |
+
return out
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def norm_json(o):
|
| 84 |
+
return json.loads(json.dumps(o, default=_json_default))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def sha256(p):
|
| 88 |
+
with open(p, "rb") as f:
|
| 89 |
+
return hashlib.sha256(f.read()).hexdigest()
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def check_code(run_dir):
|
| 93 |
+
"""[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract."""
|
| 94 |
+
p = os.path.join(run_dir, "contract.json")
|
| 95 |
+
if not os.path.exists(p):
|
| 96 |
+
return [("contract.json", None, None)]
|
| 97 |
+
files = json.load(open(p))["contract"].get("server_code_files", {})
|
| 98 |
+
bad = []
|
| 99 |
+
for f, h in files.items():
|
| 100 |
+
q = os.path.join(LFF_ROOT, f)
|
| 101 |
+
cur = sha256(q) if os.path.exists(q) else None
|
| 102 |
+
if cur != h:
|
| 103 |
+
bad.append((f, h, cur))
|
| 104 |
+
return bad
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def diff_json(a, b, path="", tol=0.0, out=None, limit=20):
|
| 108 |
+
"""Differences between two JSON values (numbers compared with an absolute tolerance)."""
|
| 109 |
+
out = [] if out is None else out
|
| 110 |
+
if len(out) >= limit:
|
| 111 |
+
return out
|
| 112 |
+
if isinstance(a, dict) and isinstance(b, dict):
|
| 113 |
+
for k in sorted(set(a) | set(b)):
|
| 114 |
+
if k not in a or k not in b:
|
| 115 |
+
out.append((f"{path}.{k}", a.get(k, "<missing>"), b.get(k, "<missing>")))
|
| 116 |
+
else:
|
| 117 |
+
diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit)
|
| 118 |
+
elif isinstance(a, list) and isinstance(b, list):
|
| 119 |
+
if len(a) != len(b):
|
| 120 |
+
out.append((path, f"len {len(a)}", f"len {len(b)}"))
|
| 121 |
+
else:
|
| 122 |
+
for i, (x, y) in enumerate(zip(a, b)):
|
| 123 |
+
diff_json(x, y, f"{path}[{i}]", tol, out, limit)
|
| 124 |
+
elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
|
| 125 |
+
if a != b:
|
| 126 |
+
out.append((path, a, b))
|
| 127 |
+
elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))):
|
| 128 |
+
out.append((path, a, b))
|
| 129 |
+
return out
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def error_event(o):
|
| 133 |
+
"""True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none."""
|
| 134 |
+
if not isinstance(o, dict):
|
| 135 |
+
return None
|
| 136 |
+
keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o]
|
| 137 |
+
if not keys:
|
| 138 |
+
return None
|
| 139 |
+
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)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# ====================================================================================================== logs -> notes
|
| 143 |
+
|
| 144 |
+
class RunLog:
|
| 145 |
+
"""Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's
|
| 146 |
+
narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition."""
|
| 147 |
+
|
| 148 |
+
def __init__(self, run_dir, manifest=None):
|
| 149 |
+
self.run_dir = os.path.abspath(run_dir.rstrip("/"))
|
| 150 |
+
self.run = os.path.basename(self.run_dir)
|
| 151 |
+
self.batch = os.path.basename(os.path.dirname(self.run_dir))
|
| 152 |
+
self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl"))
|
| 153 |
+
self.start = next(e for e in self.ev if e["ev"] == "session_start")
|
| 154 |
+
self.calls, self.dones, self.harness_status = {}, [], []
|
| 155 |
+
last = None
|
| 156 |
+
for e in self.ev:
|
| 157 |
+
if e["ev"] == "call":
|
| 158 |
+
self.calls[(int(e["attempt"]), int(e["step"]))] = e
|
| 159 |
+
last = e
|
| 160 |
+
elif e["ev"] == "done":
|
| 161 |
+
self.dones.append(e)
|
| 162 |
+
last = e
|
| 163 |
+
elif e["ev"] == "http" and last is not None and "think_s" not in last:
|
| 164 |
+
ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \
|
| 165 |
+
(last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe"))
|
| 166 |
+
if ok:
|
| 167 |
+
last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s")
|
| 168 |
+
self.manifest = manifest or {}
|
| 169 |
+
self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {}
|
| 170 |
+
p = os.path.join(self.run_dir, "harness.json")
|
| 171 |
+
self.harness = json.load(open(p)) if os.path.exists(p) else {}
|
| 172 |
+
self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl"))
|
| 173 |
+
self._narration()
|
| 174 |
+
|
| 175 |
+
# ---------------------------------------------------------------- agent narration
|
| 176 |
+
def _narration(self):
|
| 177 |
+
"""notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one;
|
| 178 |
+
finish_notes[attempt] likewise for the agent's finish call; final_report = its last message."""
|
| 179 |
+
self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", []
|
| 180 |
+
buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
|
| 181 |
+
attempt = 1
|
| 182 |
+
|
| 183 |
+
def take():
|
| 184 |
+
nonlocal buf
|
| 185 |
+
out = {k: v for k, v in buf.items() if v}
|
| 186 |
+
buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
|
| 187 |
+
return out
|
| 188 |
+
|
| 189 |
+
last_msg = ""
|
| 190 |
+
for t in self.traj:
|
| 191 |
+
if t.get("kind") == "header":
|
| 192 |
+
self.headers.append(t.get("agent") or {})
|
| 193 |
+
continue
|
| 194 |
+
if t.get("kind") != "step":
|
| 195 |
+
continue
|
| 196 |
+
if (t.get("message") or "").strip():
|
| 197 |
+
buf["messages"].append(t["message"].strip())
|
| 198 |
+
last_msg = t["message"].strip()
|
| 199 |
+
if (t.get("reasoning_content") or "").strip():
|
| 200 |
+
buf["reasoning"].append(t["reasoning_content"].strip())
|
| 201 |
+
res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])}
|
| 202 |
+
for c in t.get("tool_calls") or []:
|
| 203 |
+
fn, args = c.get("function_name"), c.get("arguments") or {}
|
| 204 |
+
if fn == "shell":
|
| 205 |
+
buf["shell"].append(str(args.get("command", ""))[:2000])
|
| 206 |
+
elif fn == "view_images":
|
| 207 |
+
buf["viewed"].extend(args.get("paths") or [])
|
| 208 |
+
elif fn == "robot":
|
| 209 |
+
cmd = str(args.get("command", "")).strip()
|
| 210 |
+
r = res.get(c.get("tool_call_id")) or {}
|
| 211 |
+
try:
|
| 212 |
+
rep = json.loads(r.get("content") or "{}")
|
| 213 |
+
except ValueError:
|
| 214 |
+
rep = {}
|
| 215 |
+
word = cmd.split()[0] if cmd else ""
|
| 216 |
+
m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", "")))
|
| 217 |
+
if word in ("move_eef", "observe") and m:
|
| 218 |
+
a, s = int(m.group(1)), int(m.group(2))
|
| 219 |
+
n = take()
|
| 220 |
+
n["command"] = cmd
|
| 221 |
+
self.notes[(a, s)] = n
|
| 222 |
+
attempt = a
|
| 223 |
+
elif word in ("finish", "done"):
|
| 224 |
+
n = take()
|
| 225 |
+
n["command"] = cmd
|
| 226 |
+
n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)}
|
| 227 |
+
self.finish_notes.setdefault(attempt, n)
|
| 228 |
+
if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"):
|
| 229 |
+
attempt += 1
|
| 230 |
+
# status / help / errors: their narration stays in the buffer for the next command
|
| 231 |
+
self.final_report = last_msg
|
| 232 |
+
|
| 233 |
+
# ---------------------------------------------------------------- run-level labels
|
| 234 |
+
def attempts(self):
|
| 235 |
+
out = []
|
| 236 |
+
for e in self.dones:
|
| 237 |
+
o = e.get("outcome") or {}
|
| 238 |
+
if isinstance(o, str):
|
| 239 |
+
try:
|
| 240 |
+
o = ast.literal_eval(o)
|
| 241 |
+
except (ValueError, SyntaxError):
|
| 242 |
+
o = {}
|
| 243 |
+
out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o,
|
| 244 |
+
reason=e.get("reason") or ""))
|
| 245 |
+
return sorted(out, key=lambda x: x["attempt"])
|
| 246 |
+
|
| 247 |
+
def condition(self):
|
| 248 |
+
s, en = self.start, self.entry
|
| 249 |
+
mem = s.get("memory", en.get("mem"))
|
| 250 |
+
chain = en.get("chain")
|
| 251 |
+
if mem == "full":
|
| 252 |
+
cond = "with_history"
|
| 253 |
+
elif chain:
|
| 254 |
+
cond = "memory_free_retry"
|
| 255 |
+
else:
|
| 256 |
+
cond = "independent_single_attempt"
|
| 257 |
+
return cond, chain
|
| 258 |
+
|
| 259 |
+
def outcome_class(self):
|
| 260 |
+
"""CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None."""
|
| 261 |
+
att = self.attempts()
|
| 262 |
+
if not att or self.start.get("memory") != "full":
|
| 263 |
+
return None, "".join("S" if a["success"] else "F" for a in att)
|
| 264 |
+
hist = "".join("S" if a["success"] else "F" for a in att)
|
| 265 |
+
if att[0]["success"]:
|
| 266 |
+
ev = error_event(att[0]["outcome"])
|
| 267 |
+
cls = "S?" if ev is None else ("IR" if ev else "CS")
|
| 268 |
+
else:
|
| 269 |
+
cls = "XR" if any(a["success"] for a in att) else "F"
|
| 270 |
+
return cls, hist
|
| 271 |
+
|
| 272 |
+
def agent_info(self):
|
| 273 |
+
h, en = self.harness, self.entry
|
| 274 |
+
hdr = self.headers[0] if self.headers else {}
|
| 275 |
+
return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"),
|
| 276 |
+
harness_version=h.get("version") or hdr.get("version"),
|
| 277 |
+
harness_binary_sha256=(h.get("binary") or {}).get("sha256"),
|
| 278 |
+
model=h.get("model") or en.get("model") or hdr.get("model_name"),
|
| 279 |
+
effort=h.get("effort") or en.get("effort") or hdr.get("effort"),
|
| 280 |
+
provider=h.get("provider") or en.get("provider"),
|
| 281 |
+
codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"),
|
| 282 |
+
jail=en.get("jail"))
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
# ====================================================================================================== recording
|
| 286 |
+
|
| 287 |
+
class EpisodeSink:
|
| 288 |
+
"""Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed."""
|
| 289 |
+
|
| 290 |
+
def __init__(self, path):
|
| 291 |
+
self.path = path
|
| 292 |
+
os.makedirs(path, exist_ok=True)
|
| 293 |
+
self.w = None
|
| 294 |
+
self.num = defaultdict(list)
|
| 295 |
+
self.n = 0
|
| 296 |
+
|
| 297 |
+
def add(self, st, imgs):
|
| 298 |
+
import imageio
|
| 299 |
+
if self.w is None:
|
| 300 |
+
self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb",
|
| 301 |
+
pixelformat="rgb24", macro_block_size=1,
|
| 302 |
+
ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error")
|
| 303 |
+
for k in ("agentview", "wrist")]
|
| 304 |
+
for w, im in zip(self.w, imgs):
|
| 305 |
+
w.append_data(im)
|
| 306 |
+
for k, v in st.items():
|
| 307 |
+
self.num[k].append(v)
|
| 308 |
+
self.n += 1
|
| 309 |
+
|
| 310 |
+
def close(self, final_state, final_imgs):
|
| 311 |
+
from PIL import Image
|
| 312 |
+
if self.w is not None:
|
| 313 |
+
for w in self.w:
|
| 314 |
+
w.close()
|
| 315 |
+
arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"}
|
| 316 |
+
np.savez(os.path.join(self.path, "frames.npz"), **arr)
|
| 317 |
+
if self.num.get("sim_state"):
|
| 318 |
+
np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64))
|
| 319 |
+
np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()})
|
| 320 |
+
for k, im in zip(("agentview", "wrist"), final_imgs):
|
| 321 |
+
Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png"))
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
class Recorder:
|
| 325 |
+
"""Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink."""
|
| 326 |
+
|
| 327 |
+
def __init__(self, rp, res):
|
| 328 |
+
self.rp, self.res = rp, int(res)
|
| 329 |
+
self.active = False
|
| 330 |
+
self.sink = None
|
| 331 |
+
self.cur = dict(attempt=1, command=-1, phase=PHASES["move"])
|
| 332 |
+
env = rp.task.env
|
| 333 |
+
self.env, self.rob = env, env.robots[0]
|
| 334 |
+
self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist"))
|
| 335 |
+
orig = env.step
|
| 336 |
+
|
| 337 |
+
def step(a):
|
| 338 |
+
if self.active and self.sink is not None:
|
| 339 |
+
self.capture(np.asarray(a, np.float64))
|
| 340 |
+
out = orig(a)
|
| 341 |
+
if self.active and self.sink is not None:
|
| 342 |
+
self.rp.poll_events(self.sink.n - 1)
|
| 343 |
+
return out
|
| 344 |
+
|
| 345 |
+
env.step = step
|
| 346 |
+
|
| 347 |
+
@property
|
| 348 |
+
def n(self):
|
| 349 |
+
return self.sink.n if self.sink is not None else 0
|
| 350 |
+
|
| 351 |
+
def state(self):
|
| 352 |
+
import robosuite.utils.transform_utils as T
|
| 353 |
+
env, rob = self.env, self.rob
|
| 354 |
+
d = env.sim.data
|
| 355 |
+
eef = np.array(d.site_xpos[rob.eef_site_id], np.float64)
|
| 356 |
+
q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw")
|
| 357 |
+
gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64)
|
| 358 |
+
try:
|
| 359 |
+
flat = np.asarray(env.sim.get_state().flatten(), np.float64)
|
| 360 |
+
except Exception:
|
| 361 |
+
flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64)
|
| 362 |
+
sk = self.rp.task.sk
|
| 363 |
+
return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64),
|
| 364 |
+
gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64),
|
| 365 |
+
joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64),
|
| 366 |
+
gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64),
|
| 367 |
+
eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)),
|
| 368 |
+
sim_time=np.float64(d.time), sim_state=flat)
|
| 369 |
+
|
| 370 |
+
def images(self):
|
| 371 |
+
return [envs.render(self.env, c, self.res) for c in self.cams]
|
| 372 |
+
|
| 373 |
+
def capture(self, a):
|
| 374 |
+
st = self.state()
|
| 375 |
+
st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]),
|
| 376 |
+
phase=np.int64(self.cur["phase"]))
|
| 377 |
+
self.sink.add(st, self.images())
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
class RunReplay:
|
| 381 |
+
def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None):
|
| 382 |
+
self.run_dir = os.path.abspath(run_dir.rstrip("/"))
|
| 383 |
+
self.run_name = os.path.basename(self.run_dir)
|
| 384 |
+
self.log = RunLog(self.run_dir, manifest)
|
| 385 |
+
self.ev = self.log.ev
|
| 386 |
+
self.start = self.log.start
|
| 387 |
+
cp = os.path.join(self.run_dir, "contract.json")
|
| 388 |
+
self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {}
|
| 389 |
+
spec = self.contract.get("image_spec") or {}
|
| 390 |
+
self.image_res = int(spec.get("width", 512))
|
| 391 |
+
self.code_diff = check_code(self.run_dir)
|
| 392 |
+
s = self.start
|
| 393 |
+
self.task = TASKS[s["task"]](cam_res=self.image_res)
|
| 394 |
+
inst = self.task.sample_instance(s["seed"])
|
| 395 |
+
logged = s.get("inst") or {}
|
| 396 |
+
sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")})
|
| 397 |
+
self.inst_diff = diff_json(sampled, logged, "inst")
|
| 398 |
+
if s.get("arm", "none") not in (None, "none") or logged.get("nominal"):
|
| 399 |
+
inst.update(logged) # controlled arms / nominal: the server overrode these instance fields
|
| 400 |
+
self.inst_diff = []
|
| 401 |
+
self.inst = inst
|
| 402 |
+
self.protocol = getattr(self.task, "protocol", "cross")
|
| 403 |
+
self.k = int(s.get("k") or self.task.max_attempts)
|
| 404 |
+
self.attempt = 1
|
| 405 |
+
self.mismatch = [] # (where, what, logged, replayed)
|
| 406 |
+
self.n_checked = 0
|
| 407 |
+
self.max_dev_m = 0.0
|
| 408 |
+
self.unfinished = None
|
| 409 |
+
self.rec = Recorder(self, res) if record else None
|
| 410 |
+
self.res = int(res)
|
| 411 |
+
self.out_root = out_root
|
| 412 |
+
self.n_mon = 0
|
| 413 |
+
self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0
|
| 414 |
+
self.episodes = [] # summaries of the written episodes
|
| 415 |
+
self.task.reset_instance(self.inst)
|
| 416 |
+
self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
|
| 417 |
+
sim = self.task.env.sim
|
| 418 |
+
bid = sim.model.body_name2id("robot0_base")
|
| 419 |
+
self.base_off = np.array(sim.data.body_xpos[bid], float).copy()
|
| 420 |
+
if self.rec:
|
| 421 |
+
self._open_episode()
|
| 422 |
+
|
| 423 |
+
# ------------------------------------------------------------------ episodes
|
| 424 |
+
def _ep_dir(self):
|
| 425 |
+
return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}")
|
| 426 |
+
|
| 427 |
+
def _open_episode(self):
|
| 428 |
+
self.rec.sink = EpisodeSink(self._ep_dir())
|
| 429 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
|
| 430 |
+
self.rec.active = True
|
| 431 |
+
self.events, self.spans, self.ep_attempts = [], [], []
|
| 432 |
+
self.ep_initial = self.rec.state() # state right after the reset (before frame 0)
|
| 433 |
+
|
| 434 |
+
def close_episode(self):
|
| 435 |
+
if not self.rec:
|
| 436 |
+
self.ep_attempts = []
|
| 437 |
+
return
|
| 438 |
+
sink = self.rec.sink
|
| 439 |
+
st = self.rec.state()
|
| 440 |
+
imgs = self.rec.images()
|
| 441 |
+
st.pop("sim_state", None)
|
| 442 |
+
sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs)
|
| 443 |
+
ann = build_annotation(self, sink)
|
| 444 |
+
with open(os.path.join(sink.path, "annotation.json"), "w") as f:
|
| 445 |
+
json.dump(ann, f, indent=1, default=_json_default)
|
| 446 |
+
self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n,
|
| 447 |
+
attempts=[a["attempt"] for a in self.ep_attempts]))
|
| 448 |
+
self.rec.active = False
|
| 449 |
+
self.rec.sink = None
|
| 450 |
+
self.ep_index += 1
|
| 451 |
+
|
| 452 |
+
# ------------------------------------------------------------------ monitor events (task-side error events)
|
| 453 |
+
def poll_events(self, frame):
|
| 454 |
+
mon = getattr(self.task, "mon", None)
|
| 455 |
+
evs = mon.get("events") if isinstance(mon, dict) else None
|
| 456 |
+
if not isinstance(evs, list):
|
| 457 |
+
return
|
| 458 |
+
if len(evs) < self.n_mon: # monitor was rebuilt
|
| 459 |
+
self.n_mon = 0
|
| 460 |
+
for e in evs[self.n_mon:]:
|
| 461 |
+
self.events.append(dict(frame=int(frame), attempt=self.attempt,
|
| 462 |
+
event=norm_json(e) if isinstance(e, dict) else str(e)))
|
| 463 |
+
self.n_mon = len(evs)
|
| 464 |
+
|
| 465 |
+
# ------------------------------------------------------------------ state as the server reports it
|
| 466 |
+
def proprio_la(self):
|
| 467 |
+
p = self.ex.proprio()
|
| 468 |
+
pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off]
|
| 469 |
+
return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"])
|
| 470 |
+
|
| 471 |
+
def compare(self, where, rep_logged, rep):
|
| 472 |
+
self.n_checked += 1
|
| 473 |
+
for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"):
|
| 474 |
+
if k not in rep_logged or k not in rep:
|
| 475 |
+
continue
|
| 476 |
+
a, b = rep_logged[k], rep[k]
|
| 477 |
+
if k == "eef_pos":
|
| 478 |
+
dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float))))
|
| 479 |
+
self.max_dev_m = max(self.max_dev_m, dev)
|
| 480 |
+
if dev > 1.5e-4:
|
| 481 |
+
self.mismatch.append((where, k, a, b))
|
| 482 |
+
elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4):
|
| 483 |
+
self.mismatch.append((where, k, a, b))
|
| 484 |
+
if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)):
|
| 485 |
+
self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok")))
|
| 486 |
+
|
| 487 |
+
def _span(self, e, f0, kind):
|
| 488 |
+
if self.rec:
|
| 489 |
+
self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0,
|
| 490 |
+
frame_end=self.rec.n))
|
| 491 |
+
|
| 492 |
+
# ------------------------------------------------------------------ commands (robot_server._handle_v2)
|
| 493 |
+
def move_eef(self, e):
|
| 494 |
+
args = e.get("args") or {}
|
| 495 |
+
where = f"a{e['attempt']}s{e['step']}"
|
| 496 |
+
logged = e.get("report") or {}
|
| 497 |
+
f0 = self.rec.n if self.rec else 0
|
| 498 |
+
p = self.ex.proprio()
|
| 499 |
+
if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}:
|
| 500 |
+
self._span(e, f0, "error")
|
| 501 |
+
return self.compare(where, logged, dict(ok=False))
|
| 502 |
+
off = self.base_off
|
| 503 |
+
try:
|
| 504 |
+
cur = np.asarray(p["eef_pos"], float) - off
|
| 505 |
+
tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
|
| 506 |
+
yaw = float(args.get("yaw", p["eef_yaw_deg"]))
|
| 507 |
+
speed = None if args.get("speed") in (None, "") else float(args["speed"])
|
| 508 |
+
except (TypeError, ValueError):
|
| 509 |
+
self._span(e, f0, "error")
|
| 510 |
+
return self.compare(where, logged, dict(ok=False))
|
| 511 |
+
grip = args.get("gripper")
|
| 512 |
+
if grip not in (None, "open", "close"):
|
| 513 |
+
self._span(e, f0, "error")
|
| 514 |
+
return self.compare(where, logged, dict(ok=False))
|
| 515 |
+
moving = any(k in args for k in ("x", "y", "z", "yaw"))
|
| 516 |
+
tgt_w = np.asarray(tgt) + off
|
| 517 |
+
if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)):
|
| 518 |
+
self._span(e, f0, "rejected")
|
| 519 |
+
return self.compare(where, logged, dict(ok=False, **self.proprio_la()))
|
| 520 |
+
raw = {}
|
| 521 |
+
if self.rec:
|
| 522 |
+
self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"])
|
| 523 |
+
if moving:
|
| 524 |
+
mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw)
|
| 525 |
+
if speed is not None:
|
| 526 |
+
mv["speed"] = speed
|
| 527 |
+
raw.update(self.ex.call("move_to", mv).report)
|
| 528 |
+
if grip is not None:
|
| 529 |
+
if self.rec:
|
| 530 |
+
self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"])
|
| 531 |
+
raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report)
|
| 532 |
+
rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la())
|
| 533 |
+
self.compare(where, logged, rep)
|
| 534 |
+
lr = e.get("raw") or {}
|
| 535 |
+
for k in ("holding_object", "touched_object"):
|
| 536 |
+
if k in lr and k in raw and bool(lr[k]) != bool(raw[k]):
|
| 537 |
+
self.mismatch.append((where, "raw." + k, lr[k], raw[k]))
|
| 538 |
+
self._span(e, f0, "move_eef")
|
| 539 |
+
|
| 540 |
+
def observe(self, e):
|
| 541 |
+
f0 = self.rec.n if self.rec else 0
|
| 542 |
+
self._span(e, f0, "observe")
|
| 543 |
+
|
| 544 |
+
def done(self, e):
|
| 545 |
+
f0 = self.rec.n if self.rec else 0
|
| 546 |
+
if self.rec:
|
| 547 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"])
|
| 548 |
+
out = self.task.outcome(self.inst)
|
| 549 |
+
succ = bool(out["success"])
|
| 550 |
+
where = f"a{e['attempt']}done"
|
| 551 |
+
if succ != bool(e.get("success") in (True, "True")):
|
| 552 |
+
self.mismatch.append((where, "success", e.get("success"), succ))
|
| 553 |
+
lo = e.get("outcome") or {}
|
| 554 |
+
ro = norm_json({k: v for k, v in out.items() if k != "feedback"})
|
| 555 |
+
if isinstance(lo, dict):
|
| 556 |
+
for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8):
|
| 557 |
+
self.mismatch.append((where,) + d)
|
| 558 |
+
info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""),
|
| 559 |
+
feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")),
|
| 560 |
+
think_s=e.get("think_s"))
|
| 561 |
+
try:
|
| 562 |
+
info["feedback_f2"] = self.task.feedback(self.inst, out, "F2")
|
| 563 |
+
except Exception as ex_:
|
| 564 |
+
info["feedback_f2"] = f"<unavailable: {type(ex_).__name__}>"
|
| 565 |
+
if self.rec:
|
| 566 |
+
info["judge_frames"] = [f0, self.rec.n]
|
| 567 |
+
self.ep_attempts.append(info)
|
| 568 |
+
last = self.attempt >= self.k or succ or bool(out.get("terminal"))
|
| 569 |
+
if self.protocol == "cross" or last:
|
| 570 |
+
self.close_episode()
|
| 571 |
+
if last:
|
| 572 |
+
return True
|
| 573 |
+
self.attempt += 1
|
| 574 |
+
if self.protocol == "cross":
|
| 575 |
+
self.task.reset_instance(self.inst)
|
| 576 |
+
self.n_mon = 0
|
| 577 |
+
if self.rec:
|
| 578 |
+
self._open_episode()
|
| 579 |
+
elif self.rec:
|
| 580 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
|
| 581 |
+
self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
|
| 582 |
+
return False
|
| 583 |
+
|
| 584 |
+
def run(self):
|
| 585 |
+
t0 = time.time()
|
| 586 |
+
finished = False
|
| 587 |
+
for e in self.ev:
|
| 588 |
+
if e["ev"] == "call":
|
| 589 |
+
if e.get("cmd") == "move_eef":
|
| 590 |
+
self.move_eef(e)
|
| 591 |
+
elif e.get("cmd") == "observe":
|
| 592 |
+
self.observe(e)
|
| 593 |
+
else:
|
| 594 |
+
self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None))
|
| 595 |
+
elif e["ev"] == "done":
|
| 596 |
+
finished = self.done(e)
|
| 597 |
+
if finished:
|
| 598 |
+
break
|
| 599 |
+
self.unfinished = not finished
|
| 600 |
+
if not finished and self.rec and self.rec.sink is not None:
|
| 601 |
+
# the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged
|
| 602 |
+
if self.rec.n or self.ep_attempts:
|
| 603 |
+
self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True,
|
| 604 |
+
finish_reason="", feedback_shown="", auto_ended=False))
|
| 605 |
+
self.close_episode()
|
| 606 |
+
else:
|
| 607 |
+
shutil.rmtree(self.rec.sink.path, ignore_errors=True)
|
| 608 |
+
self.rec.sink = None
|
| 609 |
+
self.wall_s = time.time() - t0
|
| 610 |
+
return self
|
| 611 |
+
|
| 612 |
+
def summary(self):
|
| 613 |
+
return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"],
|
| 614 |
+
protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff),
|
| 615 |
+
n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6),
|
| 616 |
+
unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1),
|
| 617 |
+
first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]])
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
# ====================================================================================================== annotation
|
| 621 |
+
|
| 622 |
+
def task_info(task, inst):
|
| 623 |
+
cls = type(task)
|
| 624 |
+
return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable",
|
| 625 |
+
category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"),
|
| 626 |
+
max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)),
|
| 627 |
+
instruction=cls.instruction)
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
def build_annotation(rp, sink):
|
| 631 |
+
"""Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2
|
| 632 |
+
failure description), run-level outcome class, every robot command with its frame span and the agent's narration,
|
| 633 |
+
task-side error events with frame indices."""
|
| 634 |
+
log = rp.log
|
| 635 |
+
s = rp.start
|
| 636 |
+
cond, chain = log.condition()
|
| 637 |
+
cls, hist = log.outcome_class()
|
| 638 |
+
att_all = log.attempts()
|
| 639 |
+
attempts = []
|
| 640 |
+
for a in rp.ep_attempts:
|
| 641 |
+
a = dict(a)
|
| 642 |
+
n = a["attempt"]
|
| 643 |
+
later = [x for x in att_all if x["attempt"] > n]
|
| 644 |
+
a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later))
|
| 645 |
+
a["is_last_attempt_of_run"] = not later
|
| 646 |
+
fn = log.finish_notes.get(n)
|
| 647 |
+
if fn:
|
| 648 |
+
a["agent_finish"] = fn
|
| 649 |
+
a["error_event_in_attempt"] = error_event(a.get("outcome"))
|
| 650 |
+
attempts.append(a)
|
| 651 |
+
# post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command)
|
| 652 |
+
for a in attempts:
|
| 653 |
+
nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1])
|
| 654 |
+
if a.get("success") is False and nxt:
|
| 655 |
+
note = log.notes[nxt[0]]
|
| 656 |
+
a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note}
|
| 657 |
+
commands = []
|
| 658 |
+
for sp in rp.spans:
|
| 659 |
+
e = log.calls.get((sp["attempt"], sp["step"])) or {}
|
| 660 |
+
rep = e.get("report") or {}
|
| 661 |
+
c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"],
|
| 662 |
+
frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]),
|
| 663 |
+
args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"),
|
| 664 |
+
stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"),
|
| 665 |
+
gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"),
|
| 666 |
+
touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"),
|
| 667 |
+
agent_obs_images=rep.get("images"))
|
| 668 |
+
note = log.notes.get((sp["attempt"], sp["step"]))
|
| 669 |
+
if note:
|
| 670 |
+
c["agent_note"] = {k: v for k, v in note.items() if k != "command"}
|
| 671 |
+
commands.append(c)
|
| 672 |
+
t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x]
|
| 673 |
+
return dict(
|
| 674 |
+
schema=SCHEMA,
|
| 675 |
+
source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts],
|
| 676 |
+
episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain,
|
| 677 |
+
memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None),
|
| 678 |
+
feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"),
|
| 679 |
+
k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"),
|
| 680 |
+
contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256")
|
| 681 |
+
if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)),
|
| 682 |
+
agent=log.agent_info(),
|
| 683 |
+
task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"),
|
| 684 |
+
instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}),
|
| 685 |
+
run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all),
|
| 686 |
+
run_success=any(x["success"] for x in att_all) if att_all else None,
|
| 687 |
+
agent_final_report=log.final_report[:6000] or None,
|
| 688 |
+
mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)),
|
| 689 |
+
attempts=attempts,
|
| 690 |
+
commands=commands,
|
| 691 |
+
task_events=rp.events,
|
| 692 |
+
frames=dict(n=sink.n, fps=FPS, image_res=rp.res,
|
| 693 |
+
phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"],
|
| 694 |
+
joint_pos=rp.ep_initial["joint_pos"],
|
| 695 |
+
gripper_qpos=rp.ep_initial["gripper_qpos"])),
|
| 696 |
+
)
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
# ====================================================================================================== CLI
|
| 700 |
+
|
| 701 |
+
def load_manifest(run_dir):
|
| 702 |
+
p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json")
|
| 703 |
+
return json.load(open(p)) if os.path.exists(p) else {}
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
def main():
|
| 707 |
+
ap = argparse.ArgumentParser()
|
| 708 |
+
ap.add_argument("mode", choices=["check", "record"])
|
| 709 |
+
ap.add_argument("runs", nargs="+")
|
| 710 |
+
ap.add_argument("--json", default="")
|
| 711 |
+
ap.add_argument("--out", default="")
|
| 712 |
+
ap.add_argument("--res", type=int, default=256)
|
| 713 |
+
ap.add_argument("--force", action="store_true", help="record again even if replay.json exists")
|
| 714 |
+
a = ap.parse_args()
|
| 715 |
+
rows = []
|
| 716 |
+
for r in a.runs:
|
| 717 |
+
r = r.rstrip("/")
|
| 718 |
+
try:
|
| 719 |
+
if a.mode == "check":
|
| 720 |
+
s = RunReplay(r, manifest=load_manifest(r)).run().summary()
|
| 721 |
+
else:
|
| 722 |
+
batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r)
|
| 723 |
+
rd = os.path.join(a.out, batch, name)
|
| 724 |
+
if os.path.exists(os.path.join(rd, "replay.json")) and not a.force:
|
| 725 |
+
print(json.dumps(dict(run=name, skipped="exists")), flush=True)
|
| 726 |
+
continue
|
| 727 |
+
shutil.rmtree(rd, ignore_errors=True)
|
| 728 |
+
rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run()
|
| 729 |
+
s = rp.summary()
|
| 730 |
+
s["episodes"] = rp.episodes
|
| 731 |
+
with open(os.path.join(rd, "replay.json"), "w") as f:
|
| 732 |
+
json.dump(s, f, indent=1)
|
| 733 |
+
except Exception:
|
| 734 |
+
import traceback
|
| 735 |
+
s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:])
|
| 736 |
+
rows.append(s)
|
| 737 |
+
print(json.dumps(s), flush=True)
|
| 738 |
+
if a.json:
|
| 739 |
+
with open(a.json, "w") as f:
|
| 740 |
+
json.dump(rows, f, indent=1)
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
if __name__ == "__main__":
|
| 744 |
+
main()
|
leaf/code/supp-20261113-g61_evosub_2_20261026/lerobot_export.py
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars.
|
| 2 |
+
|
| 3 |
+
Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding
|
| 4 |
+
can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan):
|
| 5 |
+
|
| 6 |
+
python scripts/lerobot_export.py plan --raw <raw_root>[,<raw_root2>] --runs-root <lffbench>/runs/api \
|
| 7 |
+
--paper <paper/latex> --task-set <lffbench>/sets/main_v2_1inst.txt --work <work_dir> [--batches ...] [--limit N]
|
| 8 |
+
python scripts/lerobot_export.py shard --work <work_dir> --shard i --nshards N
|
| 9 |
+
python scripts/lerobot_export.py merge --work <work_dir> --nshards N --out <dataset_root>
|
| 10 |
+
|
| 11 |
+
Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0
|
| 12 |
+
mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped.
|
| 13 |
+
|
| 14 |
+
LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t):
|
| 15 |
+
observation.images.image agentview RGB 256x256 (upright; LIBERO naming)
|
| 16 |
+
observation.images.wrist_image wrist (eye-in-hand) RGB 256x256
|
| 17 |
+
observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout)
|
| 18 |
+
observation.joint_pos / joint_vel 7 arm joints (rad, rad/s)
|
| 19 |
+
observation.eef_quat 4: xyzw; observation.gripper_width 1 (m)
|
| 20 |
+
action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad),
|
| 21 |
+
gripper (-1 open, +1 close)
|
| 22 |
+
annotation.attempt_index attempt (1-based) the frame belongs to
|
| 23 |
+
annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`)
|
| 24 |
+
annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action)
|
| 25 |
+
annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt
|
| 26 |
+
annotation.task_event number of task-monitor events (error / progress events) registered at this step
|
| 27 |
+
Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table),
|
| 28 |
+
runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state
|
| 29 |
+
per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/.
|
| 30 |
+
"""
|
| 31 |
+
import argparse
|
| 32 |
+
import glob
|
| 33 |
+
import json
|
| 34 |
+
import os
|
| 35 |
+
import re
|
| 36 |
+
import shutil
|
| 37 |
+
import time
|
| 38 |
+
|
| 39 |
+
import numpy as np
|
| 40 |
+
|
| 41 |
+
FPS = 20
|
| 42 |
+
RES = 256
|
| 43 |
+
BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke",
|
| 44 |
+
"cc_smoke", "cc_opus_smoke"]
|
| 45 |
+
BATCH_NOTES = {
|
| 46 |
+
"cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog",
|
| 47 |
+
"cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267",
|
| 48 |
+
"cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299",
|
| 49 |
+
"cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances",
|
| 50 |
+
"cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)",
|
| 51 |
+
"cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the "
|
| 52 |
+
"with-history continuation of failed runs is incomplete",
|
| 53 |
+
"cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early",
|
| 54 |
+
"cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt",
|
| 55 |
+
"cc_opus_smoke": "smoke test: single attempt",
|
| 56 |
+
}
|
| 57 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 58 |
+
CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)",
|
| 59 |
+
"L2": "disturbed state to restore (incl. damage the agent causes)",
|
| 60 |
+
"L3": "infeasible manipulation strategy (grasp / contact / tool must change)",
|
| 61 |
+
"L4": "misjudged geometry (size, shape, fit, hidden structure)",
|
| 62 |
+
"L5": "misjudged physics (mass distribution, friction, dynamics)"}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def features():
|
| 66 |
+
vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]}
|
| 67 |
+
f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names}
|
| 68 |
+
i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None}
|
| 69 |
+
return {
|
| 70 |
+
"observation.images.image": vid(),
|
| 71 |
+
"observation.images.wrist_image": vid(),
|
| 72 |
+
"observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z",
|
| 73 |
+
"finger_qpos_left", "finger_qpos_right"]),
|
| 74 |
+
"observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 75 |
+
"observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 76 |
+
"observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]),
|
| 77 |
+
"observation.gripper_width": f32(1, ["width_m"]),
|
| 78 |
+
"action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y",
|
| 79 |
+
"eef_delta_rot_aa_z", "gripper_close"]),
|
| 80 |
+
"annotation.attempt_index": i64(),
|
| 81 |
+
"annotation.command_index": i64(),
|
| 82 |
+
"annotation.phase": i64(),
|
| 83 |
+
"annotation.attempt_success": i64(),
|
| 84 |
+
"annotation.task_event": i64(),
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ------------------------------------------------------------------------------------------------ paper metadata
|
| 89 |
+
|
| 90 |
+
def _clean_tex(s):
|
| 91 |
+
s = re.sub(r"%.*", "", s)
|
| 92 |
+
for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"),
|
| 93 |
+
(r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"),
|
| 94 |
+
(r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"),
|
| 95 |
+
(r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"),
|
| 96 |
+
(r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]:
|
| 97 |
+
s = re.sub(a, b, s)
|
| 98 |
+
s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s)
|
| 99 |
+
s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s)
|
| 100 |
+
for _ in range(3):
|
| 101 |
+
s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s)
|
| 102 |
+
s = re.sub(r"\$([^$]*)\$", r"\1", s)
|
| 103 |
+
s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ")
|
| 104 |
+
s = re.sub(r"\{([^{}]*)\}", r"\1", s)
|
| 105 |
+
s = re.sub(r"\\[a-zA-Z]+\*?", "", s)
|
| 106 |
+
return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def paper_tasks(paper_dir):
|
| 110 |
+
"""{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the
|
| 111 |
+
paper's task table and task appendix (empty if the paper sources are not there)."""
|
| 112 |
+
out = {}
|
| 113 |
+
if not paper_dir:
|
| 114 |
+
return out
|
| 115 |
+
app = os.path.join(paper_dir, "sections", "appendix_tasks.tex")
|
| 116 |
+
tab = os.path.join(paper_dir, "sections", "tab_tasks.tex")
|
| 117 |
+
if os.path.exists(app):
|
| 118 |
+
txt = open(app).read()
|
| 119 |
+
parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt)
|
| 120 |
+
for i in range(1, len(parts) - 1, 2):
|
| 121 |
+
if parts[i] != "\\paragraph{":
|
| 122 |
+
continue
|
| 123 |
+
body = parts[i + 1]
|
| 124 |
+
m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S)
|
| 125 |
+
if not m:
|
| 126 |
+
continue
|
| 127 |
+
name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip()
|
| 128 |
+
desc = _clean_tex(body[m.end():])
|
| 129 |
+
out[code] = dict(name=name, cause=_clean_tex(cause), description=desc)
|
| 130 |
+
if os.path.exists(tab):
|
| 131 |
+
names = {v["name"].lower(): k for k, v in out.items()}
|
| 132 |
+
for line in open(tab):
|
| 133 |
+
cells = [c.strip() for c in line.split("&")]
|
| 134 |
+
if len(cells) != 6 or not cells[-1].endswith("\\\\"):
|
| 135 |
+
continue
|
| 136 |
+
nm = re.sub(r"\\contscene", "", cells[0]).strip().lower()
|
| 137 |
+
code = names.get(nm)
|
| 138 |
+
if not code:
|
| 139 |
+
continue
|
| 140 |
+
out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]),
|
| 141 |
+
repair_within_attempt=_clean_tex(cells[3]) == "yes",
|
| 142 |
+
oracle_first_attempt_pct=_clean_tex(cells[4]),
|
| 143 |
+
naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip()))
|
| 144 |
+
return out
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
# ------------------------------------------------------------------------------------------------ collection
|
| 148 |
+
|
| 149 |
+
def manifest_status(runs_root, batch, run, cache={}):
|
| 150 |
+
if batch not in cache:
|
| 151 |
+
p = os.path.join(runs_root, batch, "manifest.json")
|
| 152 |
+
cache[batch] = json.load(open(p)) if os.path.exists(p) else {}
|
| 153 |
+
m = cache[batch]
|
| 154 |
+
for r in m.get("runs", []):
|
| 155 |
+
if r.get("run") == run:
|
| 156 |
+
return r.get("status", "?"), r
|
| 157 |
+
for r in m.get("superseded", []):
|
| 158 |
+
if r.get("run") == run:
|
| 159 |
+
return "superseded_" + str(r.get("status", "?")), r
|
| 160 |
+
return "not_in_manifest", {}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def collect(raw_roots, runs_root, batches, task_order):
|
| 164 |
+
"""Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root."""
|
| 165 |
+
eps, rejected, seen = [], [], set()
|
| 166 |
+
for root in raw_roots:
|
| 167 |
+
for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))):
|
| 168 |
+
rep = json.load(open(rj))
|
| 169 |
+
batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"]
|
| 170 |
+
if (batches and batch not in batches) or (batch, run) in seen:
|
| 171 |
+
continue
|
| 172 |
+
seen.add((batch, run))
|
| 173 |
+
ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff")
|
| 174 |
+
status, entry = manifest_status(runs_root, batch, run)
|
| 175 |
+
if not ok:
|
| 176 |
+
never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked")
|
| 177 |
+
rejected.append(dict(run=run, batch=batch, run_status=status,
|
| 178 |
+
reason="run never started (no contract, no robot command)" if never else
|
| 179 |
+
"replay does not reproduce the log (the log has gaps or the replay diverged)",
|
| 180 |
+
detail=rep.get("first_mismatches")))
|
| 181 |
+
continue
|
| 182 |
+
for ep in rep.get("episodes", []):
|
| 183 |
+
d = os.path.join(root, ep["dir"])
|
| 184 |
+
ann = json.load(open(os.path.join(d, "annotation.json")))
|
| 185 |
+
judged = [a for a in ann["attempts"] if a.get("success") is not None]
|
| 186 |
+
if not judged or ep["n_frames"] == 0:
|
| 187 |
+
rejected.append(dict(run=run, batch=batch, episode=ep["dir"],
|
| 188 |
+
reason="no judged attempt" if not judged else "no frames"))
|
| 189 |
+
continue
|
| 190 |
+
ann["source"]["run_status"] = status
|
| 191 |
+
ann["source"]["manifest_id"] = entry.get("id")
|
| 192 |
+
ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"],
|
| 193 |
+
max_eef_dev_m=rep["max_eef_dev_m"])
|
| 194 |
+
key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99),
|
| 195 |
+
{"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2),
|
| 196 |
+
ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"])
|
| 197 |
+
eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann))
|
| 198 |
+
eps.sort(key=lambda x: x["key"])
|
| 199 |
+
return eps, rejected
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# ------------------------------------------------------------------------------------------------ writing
|
| 203 |
+
|
| 204 |
+
def frames_of(path):
|
| 205 |
+
import av
|
| 206 |
+
with av.open(path) as c:
|
| 207 |
+
for fr in c.decode(video=0):
|
| 208 |
+
yield fr.to_ndarray(format="rgb24")
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def flat_row(i, ann, n, idx0):
|
| 212 |
+
s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"]
|
| 213 |
+
att = ann["attempts"]
|
| 214 |
+
a0 = att[0]
|
| 215 |
+
return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n,
|
| 216 |
+
batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"],
|
| 217 |
+
memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"),
|
| 218 |
+
episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att],
|
| 219 |
+
harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"),
|
| 220 |
+
effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"),
|
| 221 |
+
task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"),
|
| 222 |
+
category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"],
|
| 223 |
+
success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att],
|
| 224 |
+
feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att],
|
| 225 |
+
auto_ended=[a.get("auto_ended") for a in att],
|
| 226 |
+
corrected_later_in_run=[a.get("corrected_later_in_run") for a in att],
|
| 227 |
+
error_event_in_attempt=[a.get("error_event_in_attempt") for a in att],
|
| 228 |
+
run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"),
|
| 229 |
+
n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]),
|
| 230 |
+
first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def cmd_plan(a):
|
| 234 |
+
task_order = {}
|
| 235 |
+
if a.task_set and os.path.exists(a.task_set):
|
| 236 |
+
for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")):
|
| 237 |
+
task_order[line.split(":")[0].strip()] = i
|
| 238 |
+
batches = [b for b in a.batches.split(",") if b] if a.batches else None
|
| 239 |
+
eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order)
|
| 240 |
+
if a.limit:
|
| 241 |
+
eps = eps[:a.limit]
|
| 242 |
+
paper = paper_tasks(a.paper)
|
| 243 |
+
idx0 = 0
|
| 244 |
+
for i, e in enumerate(eps):
|
| 245 |
+
ann = e["ann"]
|
| 246 |
+
tname = ann["task"]["name"]
|
| 247 |
+
if tname in paper:
|
| 248 |
+
ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"}
|
| 249 |
+
ann["episode_index"] = i
|
| 250 |
+
ann["dataset_index_range"] = [idx0, idx0 + e["n"]]
|
| 251 |
+
e["index"], e["from"] = i, idx0
|
| 252 |
+
idx0 += e["n"]
|
| 253 |
+
del e["key"]
|
| 254 |
+
os.makedirs(a.work, exist_ok=True)
|
| 255 |
+
with open(os.path.join(a.work, "plan.json"), "w") as f:
|
| 256 |
+
json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f,
|
| 257 |
+
ensure_ascii=False)
|
| 258 |
+
print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def shard_range(n_eps, i, k):
|
| 262 |
+
return (n_eps * i) // k, (n_eps * (i + 1)) // k
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def cmd_shard(a):
|
| 266 |
+
from lerobot.datasets.lerobot_dataset import LeRobotDataset
|
| 267 |
+
t0 = time.time()
|
| 268 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 269 |
+
eps = plan["episodes"]
|
| 270 |
+
lo, hi = shard_range(len(eps), a.shard, a.nshards)
|
| 271 |
+
out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}")
|
| 272 |
+
if os.path.exists(os.path.join(out, "DONE")):
|
| 273 |
+
print(f"shard {a.shard}: done already", flush=True)
|
| 274 |
+
return
|
| 275 |
+
shutil.rmtree(out, ignore_errors=True)
|
| 276 |
+
ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out,
|
| 277 |
+
robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads,
|
| 278 |
+
vcodec=a.vcodec)
|
| 279 |
+
nfr = 0
|
| 280 |
+
for e in eps[lo:hi]:
|
| 281 |
+
d, ann, n = e["dir"], e["ann"], e["n"]
|
| 282 |
+
fr = np.load(os.path.join(d, "frames.npz"))
|
| 283 |
+
assert len(fr["action"]) == n, d
|
| 284 |
+
succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]}
|
| 285 |
+
evc = np.zeros(n, np.int64)
|
| 286 |
+
for ev in ann["task_events"]:
|
| 287 |
+
if 0 <= ev["frame"] < n:
|
| 288 |
+
evc[ev["frame"]] += 1
|
| 289 |
+
state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32)
|
| 290 |
+
instr = ann["task"]["instruction"]
|
| 291 |
+
k = 0
|
| 292 |
+
for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))):
|
| 293 |
+
if k >= n:
|
| 294 |
+
break
|
| 295 |
+
ds.add_frame({
|
| 296 |
+
"observation.images.image": img, "observation.images.wrist_image": wr,
|
| 297 |
+
"observation.state": state[k],
|
| 298 |
+
"observation.joint_pos": fr["joint_pos"][k].astype(np.float32),
|
| 299 |
+
"observation.joint_vel": fr["joint_vel"][k].astype(np.float32),
|
| 300 |
+
"observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32),
|
| 301 |
+
"observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32),
|
| 302 |
+
"action": fr["action"][k].astype(np.float32),
|
| 303 |
+
"annotation.attempt_index": np.array([fr["attempt"][k]], np.int64),
|
| 304 |
+
"annotation.command_index": np.array([fr["command"][k]], np.int64),
|
| 305 |
+
"annotation.phase": np.array([fr["phase"][k]], np.int64),
|
| 306 |
+
"annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64),
|
| 307 |
+
"annotation.task_event": np.array([evc[k]], np.int64),
|
| 308 |
+
"task": instr,
|
| 309 |
+
})
|
| 310 |
+
k += 1
|
| 311 |
+
if k != n:
|
| 312 |
+
raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames")
|
| 313 |
+
ds.save_episode()
|
| 314 |
+
nfr += n
|
| 315 |
+
ds.finalize()
|
| 316 |
+
shutil.rmtree(os.path.join(out, "images"), ignore_errors=True)
|
| 317 |
+
open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n")
|
| 318 |
+
print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def cmd_merge(a):
|
| 322 |
+
from pathlib import Path
|
| 323 |
+
from lerobot.datasets.aggregate import aggregate_datasets
|
| 324 |
+
t0 = time.time()
|
| 325 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 326 |
+
eps = plan["episodes"]
|
| 327 |
+
roots, ids = [], []
|
| 328 |
+
for i in range(a.nshards):
|
| 329 |
+
lo, hi = shard_range(len(eps), i, a.nshards)
|
| 330 |
+
if hi <= lo:
|
| 331 |
+
continue
|
| 332 |
+
r = os.path.join(a.work, "shards", f"shard_{i:03d}")
|
| 333 |
+
if not os.path.exists(os.path.join(r, "DONE")):
|
| 334 |
+
raise SystemExit(f"shard {i} is not done")
|
| 335 |
+
roots.append(Path(r))
|
| 336 |
+
ids.append(f"{plan['repo_id']}-shard{i:03d}")
|
| 337 |
+
if os.path.exists(a.out):
|
| 338 |
+
raise SystemExit(f"{a.out} exists; refusing to overwrite")
|
| 339 |
+
aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out))
|
| 340 |
+
print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True)
|
| 341 |
+
write_sidecars(a, plan)
|
| 342 |
+
print(f"merge done in {time.time() - t0:.0f}s", flush=True)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def write_sidecars(a, plan):
|
| 346 |
+
eps, paper = plan["episodes"], plan["paper"]
|
| 347 |
+
lff = os.path.join(a.out, "lff")
|
| 348 |
+
for sub in ("annotations", "sim_state", "final", "code"):
|
| 349 |
+
os.makedirs(os.path.join(lff, sub), exist_ok=True)
|
| 350 |
+
rows, runs, tasks = [], {}, {}
|
| 351 |
+
for e in eps:
|
| 352 |
+
i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"]
|
| 353 |
+
name = f"episode_{i:06d}"
|
| 354 |
+
if os.path.exists(os.path.join(d, "sim_state.npy")):
|
| 355 |
+
shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy"))
|
| 356 |
+
shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz"))
|
| 357 |
+
for cam, key in (("agentview", "image"), ("wrist", "wrist_image")):
|
| 358 |
+
shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png"))
|
| 359 |
+
with open(os.path.join(lff, "annotations", name + ".json"), "w") as f:
|
| 360 |
+
json.dump(ann, f, indent=1, ensure_ascii=False)
|
| 361 |
+
rows.append(flat_row(i, ann, n, e["from"]))
|
| 362 |
+
tname = ann["task"]["name"]
|
| 363 |
+
rk = (ann["source"]["batch"], ann["source"]["run"])
|
| 364 |
+
r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"),
|
| 365 |
+
run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"],
|
| 366 |
+
memory_free_chain_of=ann["source"].get("memory_free_chain_of"),
|
| 367 |
+
memory_free_rep=ann["source"].get("memory_free_rep"), task=tname,
|
| 368 |
+
seed=ann["task"]["seed"], model=ann["agent"].get("model"),
|
| 369 |
+
harness=ann["agent"].get("harness"),
|
| 370 |
+
harness_version=ann["agent"].get("harness_version"),
|
| 371 |
+
codex_catalog=ann["agent"].get("codex_catalog"),
|
| 372 |
+
outcome_class=ann["run_outcome"].get("outcome_class"),
|
| 373 |
+
attempt_history=ann["run_outcome"].get("attempt_history"),
|
| 374 |
+
agent_final_report=ann["run_outcome"].get("agent_final_report"),
|
| 375 |
+
episodes=[]))
|
| 376 |
+
for x in ann["attempts"]:
|
| 377 |
+
r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success")))
|
| 378 |
+
if tname not in tasks:
|
| 379 |
+
tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")}
|
| 380 |
+
if tname in paper:
|
| 381 |
+
tasks[tname]["paper"] = paper[tname]
|
| 382 |
+
tasks[tname]["instances"] = {}
|
| 383 |
+
tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"]
|
| 384 |
+
# memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id)
|
| 385 |
+
by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")}
|
| 386 |
+
for r in runs.values():
|
| 387 |
+
if r.get("memory_free_chain_of"):
|
| 388 |
+
r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"]))
|
| 389 |
+
for (b, rn), r in runs.items():
|
| 390 |
+
r["memory_free_retries"] = sorted((x["run"] for x in runs.values()
|
| 391 |
+
if x["batch"] == b and x.get("memory_free_chain_of_run") == rn),
|
| 392 |
+
key=lambda q: runs[(b, q)].get("memory_free_rep") or 0)
|
| 393 |
+
with open(os.path.join(lff, "episodes.jsonl"), "w") as f:
|
| 394 |
+
for row in rows:
|
| 395 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 396 |
+
with open(os.path.join(lff, "runs.jsonl"), "w") as f:
|
| 397 |
+
for r in runs.values():
|
| 398 |
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 399 |
+
with open(os.path.join(lff, "tasks.json"), "w") as f:
|
| 400 |
+
json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False)
|
| 401 |
+
with open(os.path.join(lff, "batches.json"), "w") as f:
|
| 402 |
+
json.dump(BATCH_NOTES, f, indent=1)
|
| 403 |
+
with open(os.path.join(lff, "rejected.json"), "w") as f:
|
| 404 |
+
json.dump(plan["rejected"], f, indent=1)
|
| 405 |
+
here = os.path.dirname(os.path.abspath(__file__))
|
| 406 |
+
for s in ("lerobot_replay.py", "lerobot_export.py"):
|
| 407 |
+
shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s))
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def main():
|
| 411 |
+
ap = argparse.ArgumentParser()
|
| 412 |
+
ap.add_argument("step", choices=["plan", "shard", "merge"])
|
| 413 |
+
ap.add_argument("--work", required=True)
|
| 414 |
+
ap.add_argument("--raw", default="")
|
| 415 |
+
ap.add_argument("--runs-root", default="")
|
| 416 |
+
ap.add_argument("--out", default="")
|
| 417 |
+
ap.add_argument("--paper", default="")
|
| 418 |
+
ap.add_argument("--task-set", default="")
|
| 419 |
+
ap.add_argument("--repo-id", default="lffbench/agent-replays")
|
| 420 |
+
ap.add_argument("--batches", default="")
|
| 421 |
+
ap.add_argument("--limit", type=int, default=0)
|
| 422 |
+
ap.add_argument("--shard", type=int, default=0)
|
| 423 |
+
ap.add_argument("--nshards", type=int, default=1)
|
| 424 |
+
ap.add_argument("--threads", type=int, default=2)
|
| 425 |
+
ap.add_argument("--vcodec", default="libsvtav1")
|
| 426 |
+
a = ap.parse_args()
|
| 427 |
+
{"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
if __name__ == "__main__":
|
| 431 |
+
main()
|
leaf/code/supp-20261113-g61_evosub_3_20261026/lerobot_export.py
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars.
|
| 2 |
+
|
| 3 |
+
Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding
|
| 4 |
+
can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan):
|
| 5 |
+
|
| 6 |
+
python scripts/lerobot_export.py plan --raw <raw_root>[,<raw_root2>] --runs-root <lffbench>/runs/api \
|
| 7 |
+
--paper <paper/latex> --task-set <lffbench>/sets/main_v2_1inst.txt --work <work_dir> [--batches ...] [--limit N]
|
| 8 |
+
python scripts/lerobot_export.py shard --work <work_dir> --shard i --nshards N
|
| 9 |
+
python scripts/lerobot_export.py merge --work <work_dir> --nshards N --out <dataset_root>
|
| 10 |
+
|
| 11 |
+
Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0
|
| 12 |
+
mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped.
|
| 13 |
+
|
| 14 |
+
LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t):
|
| 15 |
+
observation.images.image agentview RGB 256x256 (upright; LIBERO naming)
|
| 16 |
+
observation.images.wrist_image wrist (eye-in-hand) RGB 256x256
|
| 17 |
+
observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout)
|
| 18 |
+
observation.joint_pos / joint_vel 7 arm joints (rad, rad/s)
|
| 19 |
+
observation.eef_quat 4: xyzw; observation.gripper_width 1 (m)
|
| 20 |
+
action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad),
|
| 21 |
+
gripper (-1 open, +1 close)
|
| 22 |
+
annotation.attempt_index attempt (1-based) the frame belongs to
|
| 23 |
+
annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`)
|
| 24 |
+
annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action)
|
| 25 |
+
annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt
|
| 26 |
+
annotation.task_event number of task-monitor events (error / progress events) registered at this step
|
| 27 |
+
Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table),
|
| 28 |
+
runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state
|
| 29 |
+
per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/.
|
| 30 |
+
"""
|
| 31 |
+
import argparse
|
| 32 |
+
import glob
|
| 33 |
+
import json
|
| 34 |
+
import os
|
| 35 |
+
import re
|
| 36 |
+
import shutil
|
| 37 |
+
import time
|
| 38 |
+
|
| 39 |
+
import numpy as np
|
| 40 |
+
|
| 41 |
+
FPS = 20
|
| 42 |
+
RES = 256
|
| 43 |
+
BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke",
|
| 44 |
+
"cc_smoke", "cc_opus_smoke"]
|
| 45 |
+
BATCH_NOTES = {
|
| 46 |
+
"cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog",
|
| 47 |
+
"cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267",
|
| 48 |
+
"cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299",
|
| 49 |
+
"cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances",
|
| 50 |
+
"cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)",
|
| 51 |
+
"cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the "
|
| 52 |
+
"with-history continuation of failed runs is incomplete",
|
| 53 |
+
"cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early",
|
| 54 |
+
"cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt",
|
| 55 |
+
"cc_opus_smoke": "smoke test: single attempt",
|
| 56 |
+
}
|
| 57 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 58 |
+
CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)",
|
| 59 |
+
"L2": "disturbed state to restore (incl. damage the agent causes)",
|
| 60 |
+
"L3": "infeasible manipulation strategy (grasp / contact / tool must change)",
|
| 61 |
+
"L4": "misjudged geometry (size, shape, fit, hidden structure)",
|
| 62 |
+
"L5": "misjudged physics (mass distribution, friction, dynamics)"}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def features():
|
| 66 |
+
vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]}
|
| 67 |
+
f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names}
|
| 68 |
+
i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None}
|
| 69 |
+
return {
|
| 70 |
+
"observation.images.image": vid(),
|
| 71 |
+
"observation.images.wrist_image": vid(),
|
| 72 |
+
"observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z",
|
| 73 |
+
"finger_qpos_left", "finger_qpos_right"]),
|
| 74 |
+
"observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 75 |
+
"observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 76 |
+
"observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]),
|
| 77 |
+
"observation.gripper_width": f32(1, ["width_m"]),
|
| 78 |
+
"action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y",
|
| 79 |
+
"eef_delta_rot_aa_z", "gripper_close"]),
|
| 80 |
+
"annotation.attempt_index": i64(),
|
| 81 |
+
"annotation.command_index": i64(),
|
| 82 |
+
"annotation.phase": i64(),
|
| 83 |
+
"annotation.attempt_success": i64(),
|
| 84 |
+
"annotation.task_event": i64(),
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ------------------------------------------------------------------------------------------------ paper metadata
|
| 89 |
+
|
| 90 |
+
def _clean_tex(s):
|
| 91 |
+
s = re.sub(r"%.*", "", s)
|
| 92 |
+
for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"),
|
| 93 |
+
(r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"),
|
| 94 |
+
(r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"),
|
| 95 |
+
(r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"),
|
| 96 |
+
(r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]:
|
| 97 |
+
s = re.sub(a, b, s)
|
| 98 |
+
s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s)
|
| 99 |
+
s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s)
|
| 100 |
+
for _ in range(3):
|
| 101 |
+
s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s)
|
| 102 |
+
s = re.sub(r"\$([^$]*)\$", r"\1", s)
|
| 103 |
+
s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ")
|
| 104 |
+
s = re.sub(r"\{([^{}]*)\}", r"\1", s)
|
| 105 |
+
s = re.sub(r"\\[a-zA-Z]+\*?", "", s)
|
| 106 |
+
return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def paper_tasks(paper_dir):
|
| 110 |
+
"""{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the
|
| 111 |
+
paper's task table and task appendix (empty if the paper sources are not there)."""
|
| 112 |
+
out = {}
|
| 113 |
+
if not paper_dir:
|
| 114 |
+
return out
|
| 115 |
+
app = os.path.join(paper_dir, "sections", "appendix_tasks.tex")
|
| 116 |
+
tab = os.path.join(paper_dir, "sections", "tab_tasks.tex")
|
| 117 |
+
if os.path.exists(app):
|
| 118 |
+
txt = open(app).read()
|
| 119 |
+
parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt)
|
| 120 |
+
for i in range(1, len(parts) - 1, 2):
|
| 121 |
+
if parts[i] != "\\paragraph{":
|
| 122 |
+
continue
|
| 123 |
+
body = parts[i + 1]
|
| 124 |
+
m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S)
|
| 125 |
+
if not m:
|
| 126 |
+
continue
|
| 127 |
+
name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip()
|
| 128 |
+
desc = _clean_tex(body[m.end():])
|
| 129 |
+
out[code] = dict(name=name, cause=_clean_tex(cause), description=desc)
|
| 130 |
+
if os.path.exists(tab):
|
| 131 |
+
names = {v["name"].lower(): k for k, v in out.items()}
|
| 132 |
+
for line in open(tab):
|
| 133 |
+
cells = [c.strip() for c in line.split("&")]
|
| 134 |
+
if len(cells) != 6 or not cells[-1].endswith("\\\\"):
|
| 135 |
+
continue
|
| 136 |
+
nm = re.sub(r"\\contscene", "", cells[0]).strip().lower()
|
| 137 |
+
code = names.get(nm)
|
| 138 |
+
if not code:
|
| 139 |
+
continue
|
| 140 |
+
out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]),
|
| 141 |
+
repair_within_attempt=_clean_tex(cells[3]) == "yes",
|
| 142 |
+
oracle_first_attempt_pct=_clean_tex(cells[4]),
|
| 143 |
+
naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip()))
|
| 144 |
+
return out
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
# ------------------------------------------------------------------------------------------------ collection
|
| 148 |
+
|
| 149 |
+
def manifest_status(runs_root, batch, run, cache={}):
|
| 150 |
+
if batch not in cache:
|
| 151 |
+
p = os.path.join(runs_root, batch, "manifest.json")
|
| 152 |
+
cache[batch] = json.load(open(p)) if os.path.exists(p) else {}
|
| 153 |
+
m = cache[batch]
|
| 154 |
+
for r in m.get("runs", []):
|
| 155 |
+
if r.get("run") == run:
|
| 156 |
+
return r.get("status", "?"), r
|
| 157 |
+
for r in m.get("superseded", []):
|
| 158 |
+
if r.get("run") == run:
|
| 159 |
+
return "superseded_" + str(r.get("status", "?")), r
|
| 160 |
+
return "not_in_manifest", {}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def collect(raw_roots, runs_root, batches, task_order):
|
| 164 |
+
"""Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root."""
|
| 165 |
+
eps, rejected, seen = [], [], set()
|
| 166 |
+
for root in raw_roots:
|
| 167 |
+
for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))):
|
| 168 |
+
rep = json.load(open(rj))
|
| 169 |
+
batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"]
|
| 170 |
+
if (batches and batch not in batches) or (batch, run) in seen:
|
| 171 |
+
continue
|
| 172 |
+
seen.add((batch, run))
|
| 173 |
+
ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff")
|
| 174 |
+
status, entry = manifest_status(runs_root, batch, run)
|
| 175 |
+
if not ok:
|
| 176 |
+
never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked")
|
| 177 |
+
rejected.append(dict(run=run, batch=batch, run_status=status,
|
| 178 |
+
reason="run never started (no contract, no robot command)" if never else
|
| 179 |
+
"replay does not reproduce the log (the log has gaps or the replay diverged)",
|
| 180 |
+
detail=rep.get("first_mismatches")))
|
| 181 |
+
continue
|
| 182 |
+
for ep in rep.get("episodes", []):
|
| 183 |
+
d = os.path.join(root, ep["dir"])
|
| 184 |
+
ann = json.load(open(os.path.join(d, "annotation.json")))
|
| 185 |
+
judged = [a for a in ann["attempts"] if a.get("success") is not None]
|
| 186 |
+
if not judged or ep["n_frames"] == 0:
|
| 187 |
+
rejected.append(dict(run=run, batch=batch, episode=ep["dir"],
|
| 188 |
+
reason="no judged attempt" if not judged else "no frames"))
|
| 189 |
+
continue
|
| 190 |
+
ann["source"]["run_status"] = status
|
| 191 |
+
ann["source"]["manifest_id"] = entry.get("id")
|
| 192 |
+
ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"],
|
| 193 |
+
max_eef_dev_m=rep["max_eef_dev_m"])
|
| 194 |
+
key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99),
|
| 195 |
+
{"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2),
|
| 196 |
+
ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"])
|
| 197 |
+
eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann))
|
| 198 |
+
eps.sort(key=lambda x: x["key"])
|
| 199 |
+
return eps, rejected
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# ------------------------------------------------------------------------------------------------ writing
|
| 203 |
+
|
| 204 |
+
def frames_of(path):
|
| 205 |
+
import av
|
| 206 |
+
with av.open(path) as c:
|
| 207 |
+
for fr in c.decode(video=0):
|
| 208 |
+
yield fr.to_ndarray(format="rgb24")
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def flat_row(i, ann, n, idx0):
|
| 212 |
+
s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"]
|
| 213 |
+
att = ann["attempts"]
|
| 214 |
+
a0 = att[0]
|
| 215 |
+
return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n,
|
| 216 |
+
batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"],
|
| 217 |
+
memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"),
|
| 218 |
+
episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att],
|
| 219 |
+
harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"),
|
| 220 |
+
effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"),
|
| 221 |
+
task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"),
|
| 222 |
+
category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"],
|
| 223 |
+
success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att],
|
| 224 |
+
feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att],
|
| 225 |
+
auto_ended=[a.get("auto_ended") for a in att],
|
| 226 |
+
corrected_later_in_run=[a.get("corrected_later_in_run") for a in att],
|
| 227 |
+
error_event_in_attempt=[a.get("error_event_in_attempt") for a in att],
|
| 228 |
+
run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"),
|
| 229 |
+
n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]),
|
| 230 |
+
first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def cmd_plan(a):
|
| 234 |
+
task_order = {}
|
| 235 |
+
if a.task_set and os.path.exists(a.task_set):
|
| 236 |
+
for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")):
|
| 237 |
+
task_order[line.split(":")[0].strip()] = i
|
| 238 |
+
batches = [b for b in a.batches.split(",") if b] if a.batches else None
|
| 239 |
+
eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order)
|
| 240 |
+
if a.limit:
|
| 241 |
+
eps = eps[:a.limit]
|
| 242 |
+
paper = paper_tasks(a.paper)
|
| 243 |
+
idx0 = 0
|
| 244 |
+
for i, e in enumerate(eps):
|
| 245 |
+
ann = e["ann"]
|
| 246 |
+
tname = ann["task"]["name"]
|
| 247 |
+
if tname in paper:
|
| 248 |
+
ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"}
|
| 249 |
+
ann["episode_index"] = i
|
| 250 |
+
ann["dataset_index_range"] = [idx0, idx0 + e["n"]]
|
| 251 |
+
e["index"], e["from"] = i, idx0
|
| 252 |
+
idx0 += e["n"]
|
| 253 |
+
del e["key"]
|
| 254 |
+
os.makedirs(a.work, exist_ok=True)
|
| 255 |
+
with open(os.path.join(a.work, "plan.json"), "w") as f:
|
| 256 |
+
json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f,
|
| 257 |
+
ensure_ascii=False)
|
| 258 |
+
print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def shard_range(n_eps, i, k):
|
| 262 |
+
return (n_eps * i) // k, (n_eps * (i + 1)) // k
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def cmd_shard(a):
|
| 266 |
+
from lerobot.datasets.lerobot_dataset import LeRobotDataset
|
| 267 |
+
t0 = time.time()
|
| 268 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 269 |
+
eps = plan["episodes"]
|
| 270 |
+
lo, hi = shard_range(len(eps), a.shard, a.nshards)
|
| 271 |
+
out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}")
|
| 272 |
+
if os.path.exists(os.path.join(out, "DONE")):
|
| 273 |
+
print(f"shard {a.shard}: done already", flush=True)
|
| 274 |
+
return
|
| 275 |
+
shutil.rmtree(out, ignore_errors=True)
|
| 276 |
+
ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out,
|
| 277 |
+
robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads,
|
| 278 |
+
vcodec=a.vcodec)
|
| 279 |
+
nfr = 0
|
| 280 |
+
for e in eps[lo:hi]:
|
| 281 |
+
d, ann, n = e["dir"], e["ann"], e["n"]
|
| 282 |
+
fr = np.load(os.path.join(d, "frames.npz"))
|
| 283 |
+
assert len(fr["action"]) == n, d
|
| 284 |
+
succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]}
|
| 285 |
+
evc = np.zeros(n, np.int64)
|
| 286 |
+
for ev in ann["task_events"]:
|
| 287 |
+
if 0 <= ev["frame"] < n:
|
| 288 |
+
evc[ev["frame"]] += 1
|
| 289 |
+
state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32)
|
| 290 |
+
instr = ann["task"]["instruction"]
|
| 291 |
+
k = 0
|
| 292 |
+
for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))):
|
| 293 |
+
if k >= n:
|
| 294 |
+
break
|
| 295 |
+
ds.add_frame({
|
| 296 |
+
"observation.images.image": img, "observation.images.wrist_image": wr,
|
| 297 |
+
"observation.state": state[k],
|
| 298 |
+
"observation.joint_pos": fr["joint_pos"][k].astype(np.float32),
|
| 299 |
+
"observation.joint_vel": fr["joint_vel"][k].astype(np.float32),
|
| 300 |
+
"observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32),
|
| 301 |
+
"observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32),
|
| 302 |
+
"action": fr["action"][k].astype(np.float32),
|
| 303 |
+
"annotation.attempt_index": np.array([fr["attempt"][k]], np.int64),
|
| 304 |
+
"annotation.command_index": np.array([fr["command"][k]], np.int64),
|
| 305 |
+
"annotation.phase": np.array([fr["phase"][k]], np.int64),
|
| 306 |
+
"annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64),
|
| 307 |
+
"annotation.task_event": np.array([evc[k]], np.int64),
|
| 308 |
+
"task": instr,
|
| 309 |
+
})
|
| 310 |
+
k += 1
|
| 311 |
+
if k != n:
|
| 312 |
+
raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames")
|
| 313 |
+
ds.save_episode()
|
| 314 |
+
nfr += n
|
| 315 |
+
ds.finalize()
|
| 316 |
+
shutil.rmtree(os.path.join(out, "images"), ignore_errors=True)
|
| 317 |
+
open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n")
|
| 318 |
+
print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def cmd_merge(a):
|
| 322 |
+
from pathlib import Path
|
| 323 |
+
from lerobot.datasets.aggregate import aggregate_datasets
|
| 324 |
+
t0 = time.time()
|
| 325 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 326 |
+
eps = plan["episodes"]
|
| 327 |
+
roots, ids = [], []
|
| 328 |
+
for i in range(a.nshards):
|
| 329 |
+
lo, hi = shard_range(len(eps), i, a.nshards)
|
| 330 |
+
if hi <= lo:
|
| 331 |
+
continue
|
| 332 |
+
r = os.path.join(a.work, "shards", f"shard_{i:03d}")
|
| 333 |
+
if not os.path.exists(os.path.join(r, "DONE")):
|
| 334 |
+
raise SystemExit(f"shard {i} is not done")
|
| 335 |
+
roots.append(Path(r))
|
| 336 |
+
ids.append(f"{plan['repo_id']}-shard{i:03d}")
|
| 337 |
+
if os.path.exists(a.out):
|
| 338 |
+
raise SystemExit(f"{a.out} exists; refusing to overwrite")
|
| 339 |
+
aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out))
|
| 340 |
+
print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True)
|
| 341 |
+
write_sidecars(a, plan)
|
| 342 |
+
print(f"merge done in {time.time() - t0:.0f}s", flush=True)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def write_sidecars(a, plan):
|
| 346 |
+
eps, paper = plan["episodes"], plan["paper"]
|
| 347 |
+
lff = os.path.join(a.out, "lff")
|
| 348 |
+
for sub in ("annotations", "sim_state", "final", "code"):
|
| 349 |
+
os.makedirs(os.path.join(lff, sub), exist_ok=True)
|
| 350 |
+
rows, runs, tasks = [], {}, {}
|
| 351 |
+
for e in eps:
|
| 352 |
+
i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"]
|
| 353 |
+
name = f"episode_{i:06d}"
|
| 354 |
+
if os.path.exists(os.path.join(d, "sim_state.npy")):
|
| 355 |
+
shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy"))
|
| 356 |
+
shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz"))
|
| 357 |
+
for cam, key in (("agentview", "image"), ("wrist", "wrist_image")):
|
| 358 |
+
shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png"))
|
| 359 |
+
with open(os.path.join(lff, "annotations", name + ".json"), "w") as f:
|
| 360 |
+
json.dump(ann, f, indent=1, ensure_ascii=False)
|
| 361 |
+
rows.append(flat_row(i, ann, n, e["from"]))
|
| 362 |
+
tname = ann["task"]["name"]
|
| 363 |
+
rk = (ann["source"]["batch"], ann["source"]["run"])
|
| 364 |
+
r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"),
|
| 365 |
+
run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"],
|
| 366 |
+
memory_free_chain_of=ann["source"].get("memory_free_chain_of"),
|
| 367 |
+
memory_free_rep=ann["source"].get("memory_free_rep"), task=tname,
|
| 368 |
+
seed=ann["task"]["seed"], model=ann["agent"].get("model"),
|
| 369 |
+
harness=ann["agent"].get("harness"),
|
| 370 |
+
harness_version=ann["agent"].get("harness_version"),
|
| 371 |
+
codex_catalog=ann["agent"].get("codex_catalog"),
|
| 372 |
+
outcome_class=ann["run_outcome"].get("outcome_class"),
|
| 373 |
+
attempt_history=ann["run_outcome"].get("attempt_history"),
|
| 374 |
+
agent_final_report=ann["run_outcome"].get("agent_final_report"),
|
| 375 |
+
episodes=[]))
|
| 376 |
+
for x in ann["attempts"]:
|
| 377 |
+
r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success")))
|
| 378 |
+
if tname not in tasks:
|
| 379 |
+
tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")}
|
| 380 |
+
if tname in paper:
|
| 381 |
+
tasks[tname]["paper"] = paper[tname]
|
| 382 |
+
tasks[tname]["instances"] = {}
|
| 383 |
+
tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"]
|
| 384 |
+
# memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id)
|
| 385 |
+
by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")}
|
| 386 |
+
for r in runs.values():
|
| 387 |
+
if r.get("memory_free_chain_of"):
|
| 388 |
+
r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"]))
|
| 389 |
+
for (b, rn), r in runs.items():
|
| 390 |
+
r["memory_free_retries"] = sorted((x["run"] for x in runs.values()
|
| 391 |
+
if x["batch"] == b and x.get("memory_free_chain_of_run") == rn),
|
| 392 |
+
key=lambda q: runs[(b, q)].get("memory_free_rep") or 0)
|
| 393 |
+
with open(os.path.join(lff, "episodes.jsonl"), "w") as f:
|
| 394 |
+
for row in rows:
|
| 395 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 396 |
+
with open(os.path.join(lff, "runs.jsonl"), "w") as f:
|
| 397 |
+
for r in runs.values():
|
| 398 |
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 399 |
+
with open(os.path.join(lff, "tasks.json"), "w") as f:
|
| 400 |
+
json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False)
|
| 401 |
+
with open(os.path.join(lff, "batches.json"), "w") as f:
|
| 402 |
+
json.dump(BATCH_NOTES, f, indent=1)
|
| 403 |
+
with open(os.path.join(lff, "rejected.json"), "w") as f:
|
| 404 |
+
json.dump(plan["rejected"], f, indent=1)
|
| 405 |
+
here = os.path.dirname(os.path.abspath(__file__))
|
| 406 |
+
for s in ("lerobot_replay.py", "lerobot_export.py"):
|
| 407 |
+
shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s))
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def main():
|
| 411 |
+
ap = argparse.ArgumentParser()
|
| 412 |
+
ap.add_argument("step", choices=["plan", "shard", "merge"])
|
| 413 |
+
ap.add_argument("--work", required=True)
|
| 414 |
+
ap.add_argument("--raw", default="")
|
| 415 |
+
ap.add_argument("--runs-root", default="")
|
| 416 |
+
ap.add_argument("--out", default="")
|
| 417 |
+
ap.add_argument("--paper", default="")
|
| 418 |
+
ap.add_argument("--task-set", default="")
|
| 419 |
+
ap.add_argument("--repo-id", default="lffbench/agent-replays")
|
| 420 |
+
ap.add_argument("--batches", default="")
|
| 421 |
+
ap.add_argument("--limit", type=int, default=0)
|
| 422 |
+
ap.add_argument("--shard", type=int, default=0)
|
| 423 |
+
ap.add_argument("--nshards", type=int, default=1)
|
| 424 |
+
ap.add_argument("--threads", type=int, default=2)
|
| 425 |
+
ap.add_argument("--vcodec", default="libsvtav1")
|
| 426 |
+
a = ap.parse_args()
|
| 427 |
+
{"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
if __name__ == "__main__":
|
| 431 |
+
main()
|
leaf/code/supp-20261113-rcc_dev09_sonnet_20261111/lerobot_export.py
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars.
|
| 2 |
+
|
| 3 |
+
Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding
|
| 4 |
+
can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan):
|
| 5 |
+
|
| 6 |
+
python scripts/lerobot_export.py plan --raw <raw_root>[,<raw_root2>] --runs-root <lffbench>/runs/api \
|
| 7 |
+
--paper <paper/latex> --task-set <lffbench>/sets/main_v2_1inst.txt --work <work_dir> [--batches ...] [--limit N]
|
| 8 |
+
python scripts/lerobot_export.py shard --work <work_dir> --shard i --nshards N
|
| 9 |
+
python scripts/lerobot_export.py merge --work <work_dir> --nshards N --out <dataset_root>
|
| 10 |
+
|
| 11 |
+
Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0
|
| 12 |
+
mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped.
|
| 13 |
+
|
| 14 |
+
LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t):
|
| 15 |
+
observation.images.image agentview RGB 256x256 (upright; LIBERO naming)
|
| 16 |
+
observation.images.wrist_image wrist (eye-in-hand) RGB 256x256
|
| 17 |
+
observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout)
|
| 18 |
+
observation.joint_pos / joint_vel 7 arm joints (rad, rad/s)
|
| 19 |
+
observation.eef_quat 4: xyzw; observation.gripper_width 1 (m)
|
| 20 |
+
action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad),
|
| 21 |
+
gripper (-1 open, +1 close)
|
| 22 |
+
annotation.attempt_index attempt (1-based) the frame belongs to
|
| 23 |
+
annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`)
|
| 24 |
+
annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action)
|
| 25 |
+
annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt
|
| 26 |
+
annotation.task_event number of task-monitor events (error / progress events) registered at this step
|
| 27 |
+
Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table),
|
| 28 |
+
runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state
|
| 29 |
+
per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/.
|
| 30 |
+
"""
|
| 31 |
+
import argparse
|
| 32 |
+
import glob
|
| 33 |
+
import json
|
| 34 |
+
import os
|
| 35 |
+
import re
|
| 36 |
+
import shutil
|
| 37 |
+
import time
|
| 38 |
+
|
| 39 |
+
import numpy as np
|
| 40 |
+
|
| 41 |
+
FPS = 20
|
| 42 |
+
RES = 256
|
| 43 |
+
BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke",
|
| 44 |
+
"cc_smoke", "cc_opus_smoke"]
|
| 45 |
+
BATCH_NOTES = {
|
| 46 |
+
"cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog",
|
| 47 |
+
"cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267",
|
| 48 |
+
"cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299",
|
| 49 |
+
"cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances",
|
| 50 |
+
"cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)",
|
| 51 |
+
"cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the "
|
| 52 |
+
"with-history continuation of failed runs is incomplete",
|
| 53 |
+
"cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early",
|
| 54 |
+
"cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt",
|
| 55 |
+
"cc_opus_smoke": "smoke test: single attempt",
|
| 56 |
+
}
|
| 57 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 58 |
+
CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)",
|
| 59 |
+
"L2": "disturbed state to restore (incl. damage the agent causes)",
|
| 60 |
+
"L3": "infeasible manipulation strategy (grasp / contact / tool must change)",
|
| 61 |
+
"L4": "misjudged geometry (size, shape, fit, hidden structure)",
|
| 62 |
+
"L5": "misjudged physics (mass distribution, friction, dynamics)"}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def features():
|
| 66 |
+
vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]}
|
| 67 |
+
f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names}
|
| 68 |
+
i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None}
|
| 69 |
+
return {
|
| 70 |
+
"observation.images.image": vid(),
|
| 71 |
+
"observation.images.wrist_image": vid(),
|
| 72 |
+
"observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z",
|
| 73 |
+
"finger_qpos_left", "finger_qpos_right"]),
|
| 74 |
+
"observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 75 |
+
"observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 76 |
+
"observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]),
|
| 77 |
+
"observation.gripper_width": f32(1, ["width_m"]),
|
| 78 |
+
"action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y",
|
| 79 |
+
"eef_delta_rot_aa_z", "gripper_close"]),
|
| 80 |
+
"annotation.attempt_index": i64(),
|
| 81 |
+
"annotation.command_index": i64(),
|
| 82 |
+
"annotation.phase": i64(),
|
| 83 |
+
"annotation.attempt_success": i64(),
|
| 84 |
+
"annotation.task_event": i64(),
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ------------------------------------------------------------------------------------------------ paper metadata
|
| 89 |
+
|
| 90 |
+
def _clean_tex(s):
|
| 91 |
+
s = re.sub(r"%.*", "", s)
|
| 92 |
+
for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"),
|
| 93 |
+
(r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"),
|
| 94 |
+
(r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"),
|
| 95 |
+
(r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"),
|
| 96 |
+
(r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]:
|
| 97 |
+
s = re.sub(a, b, s)
|
| 98 |
+
s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s)
|
| 99 |
+
s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s)
|
| 100 |
+
for _ in range(3):
|
| 101 |
+
s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s)
|
| 102 |
+
s = re.sub(r"\$([^$]*)\$", r"\1", s)
|
| 103 |
+
s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ")
|
| 104 |
+
s = re.sub(r"\{([^{}]*)\}", r"\1", s)
|
| 105 |
+
s = re.sub(r"\\[a-zA-Z]+\*?", "", s)
|
| 106 |
+
return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def paper_tasks(paper_dir):
|
| 110 |
+
"""{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the
|
| 111 |
+
paper's task table and task appendix (empty if the paper sources are not there)."""
|
| 112 |
+
out = {}
|
| 113 |
+
if not paper_dir:
|
| 114 |
+
return out
|
| 115 |
+
app = os.path.join(paper_dir, "sections", "appendix_tasks.tex")
|
| 116 |
+
tab = os.path.join(paper_dir, "sections", "tab_tasks.tex")
|
| 117 |
+
if os.path.exists(app):
|
| 118 |
+
txt = open(app).read()
|
| 119 |
+
parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt)
|
| 120 |
+
for i in range(1, len(parts) - 1, 2):
|
| 121 |
+
if parts[i] != "\\paragraph{":
|
| 122 |
+
continue
|
| 123 |
+
body = parts[i + 1]
|
| 124 |
+
m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S)
|
| 125 |
+
if not m:
|
| 126 |
+
continue
|
| 127 |
+
name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip()
|
| 128 |
+
desc = _clean_tex(body[m.end():])
|
| 129 |
+
out[code] = dict(name=name, cause=_clean_tex(cause), description=desc)
|
| 130 |
+
if os.path.exists(tab):
|
| 131 |
+
names = {v["name"].lower(): k for k, v in out.items()}
|
| 132 |
+
for line in open(tab):
|
| 133 |
+
cells = [c.strip() for c in line.split("&")]
|
| 134 |
+
if len(cells) != 6 or not cells[-1].endswith("\\\\"):
|
| 135 |
+
continue
|
| 136 |
+
nm = re.sub(r"\\contscene", "", cells[0]).strip().lower()
|
| 137 |
+
code = names.get(nm)
|
| 138 |
+
if not code:
|
| 139 |
+
continue
|
| 140 |
+
out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]),
|
| 141 |
+
repair_within_attempt=_clean_tex(cells[3]) == "yes",
|
| 142 |
+
oracle_first_attempt_pct=_clean_tex(cells[4]),
|
| 143 |
+
naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip()))
|
| 144 |
+
return out
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
# ------------------------------------------------------------------------------------------------ collection
|
| 148 |
+
|
| 149 |
+
def manifest_status(runs_root, batch, run, cache={}):
|
| 150 |
+
if batch not in cache:
|
| 151 |
+
p = os.path.join(runs_root, batch, "manifest.json")
|
| 152 |
+
cache[batch] = json.load(open(p)) if os.path.exists(p) else {}
|
| 153 |
+
m = cache[batch]
|
| 154 |
+
for r in m.get("runs", []):
|
| 155 |
+
if r.get("run") == run:
|
| 156 |
+
return r.get("status", "?"), r
|
| 157 |
+
for r in m.get("superseded", []):
|
| 158 |
+
if r.get("run") == run:
|
| 159 |
+
return "superseded_" + str(r.get("status", "?")), r
|
| 160 |
+
return "not_in_manifest", {}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def collect(raw_roots, runs_root, batches, task_order):
|
| 164 |
+
"""Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root."""
|
| 165 |
+
eps, rejected, seen = [], [], set()
|
| 166 |
+
for root in raw_roots:
|
| 167 |
+
for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))):
|
| 168 |
+
rep = json.load(open(rj))
|
| 169 |
+
batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"]
|
| 170 |
+
if (batches and batch not in batches) or (batch, run) in seen:
|
| 171 |
+
continue
|
| 172 |
+
seen.add((batch, run))
|
| 173 |
+
ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff")
|
| 174 |
+
status, entry = manifest_status(runs_root, batch, run)
|
| 175 |
+
if not ok:
|
| 176 |
+
never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked")
|
| 177 |
+
rejected.append(dict(run=run, batch=batch, run_status=status,
|
| 178 |
+
reason="run never started (no contract, no robot command)" if never else
|
| 179 |
+
"replay does not reproduce the log (the log has gaps or the replay diverged)",
|
| 180 |
+
detail=rep.get("first_mismatches")))
|
| 181 |
+
continue
|
| 182 |
+
for ep in rep.get("episodes", []):
|
| 183 |
+
d = os.path.join(root, ep["dir"])
|
| 184 |
+
ann = json.load(open(os.path.join(d, "annotation.json")))
|
| 185 |
+
judged = [a for a in ann["attempts"] if a.get("success") is not None]
|
| 186 |
+
if not judged or ep["n_frames"] == 0:
|
| 187 |
+
rejected.append(dict(run=run, batch=batch, episode=ep["dir"],
|
| 188 |
+
reason="no judged attempt" if not judged else "no frames"))
|
| 189 |
+
continue
|
| 190 |
+
ann["source"]["run_status"] = status
|
| 191 |
+
ann["source"]["manifest_id"] = entry.get("id")
|
| 192 |
+
ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"],
|
| 193 |
+
max_eef_dev_m=rep["max_eef_dev_m"])
|
| 194 |
+
key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99),
|
| 195 |
+
{"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2),
|
| 196 |
+
ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"])
|
| 197 |
+
eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann))
|
| 198 |
+
eps.sort(key=lambda x: x["key"])
|
| 199 |
+
return eps, rejected
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# ------------------------------------------------------------------------------------------------ writing
|
| 203 |
+
|
| 204 |
+
def frames_of(path):
|
| 205 |
+
import av
|
| 206 |
+
with av.open(path) as c:
|
| 207 |
+
for fr in c.decode(video=0):
|
| 208 |
+
yield fr.to_ndarray(format="rgb24")
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def flat_row(i, ann, n, idx0):
|
| 212 |
+
s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"]
|
| 213 |
+
att = ann["attempts"]
|
| 214 |
+
a0 = att[0]
|
| 215 |
+
return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n,
|
| 216 |
+
batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"],
|
| 217 |
+
memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"),
|
| 218 |
+
episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att],
|
| 219 |
+
harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"),
|
| 220 |
+
effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"),
|
| 221 |
+
task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"),
|
| 222 |
+
category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"],
|
| 223 |
+
success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att],
|
| 224 |
+
feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att],
|
| 225 |
+
auto_ended=[a.get("auto_ended") for a in att],
|
| 226 |
+
corrected_later_in_run=[a.get("corrected_later_in_run") for a in att],
|
| 227 |
+
error_event_in_attempt=[a.get("error_event_in_attempt") for a in att],
|
| 228 |
+
run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"),
|
| 229 |
+
n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]),
|
| 230 |
+
first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def cmd_plan(a):
|
| 234 |
+
task_order = {}
|
| 235 |
+
if a.task_set and os.path.exists(a.task_set):
|
| 236 |
+
for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")):
|
| 237 |
+
task_order[line.split(":")[0].strip()] = i
|
| 238 |
+
batches = [b for b in a.batches.split(",") if b] if a.batches else None
|
| 239 |
+
eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order)
|
| 240 |
+
if a.limit:
|
| 241 |
+
eps = eps[:a.limit]
|
| 242 |
+
paper = paper_tasks(a.paper)
|
| 243 |
+
idx0 = 0
|
| 244 |
+
for i, e in enumerate(eps):
|
| 245 |
+
ann = e["ann"]
|
| 246 |
+
tname = ann["task"]["name"]
|
| 247 |
+
if tname in paper:
|
| 248 |
+
ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"}
|
| 249 |
+
ann["episode_index"] = i
|
| 250 |
+
ann["dataset_index_range"] = [idx0, idx0 + e["n"]]
|
| 251 |
+
e["index"], e["from"] = i, idx0
|
| 252 |
+
idx0 += e["n"]
|
| 253 |
+
del e["key"]
|
| 254 |
+
os.makedirs(a.work, exist_ok=True)
|
| 255 |
+
with open(os.path.join(a.work, "plan.json"), "w") as f:
|
| 256 |
+
json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f,
|
| 257 |
+
ensure_ascii=False)
|
| 258 |
+
print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def shard_range(n_eps, i, k):
|
| 262 |
+
return (n_eps * i) // k, (n_eps * (i + 1)) // k
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def cmd_shard(a):
|
| 266 |
+
from lerobot.datasets.lerobot_dataset import LeRobotDataset
|
| 267 |
+
t0 = time.time()
|
| 268 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 269 |
+
eps = plan["episodes"]
|
| 270 |
+
lo, hi = shard_range(len(eps), a.shard, a.nshards)
|
| 271 |
+
out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}")
|
| 272 |
+
if os.path.exists(os.path.join(out, "DONE")):
|
| 273 |
+
print(f"shard {a.shard}: done already", flush=True)
|
| 274 |
+
return
|
| 275 |
+
shutil.rmtree(out, ignore_errors=True)
|
| 276 |
+
ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out,
|
| 277 |
+
robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads,
|
| 278 |
+
vcodec=a.vcodec)
|
| 279 |
+
nfr = 0
|
| 280 |
+
for e in eps[lo:hi]:
|
| 281 |
+
d, ann, n = e["dir"], e["ann"], e["n"]
|
| 282 |
+
fr = np.load(os.path.join(d, "frames.npz"))
|
| 283 |
+
assert len(fr["action"]) == n, d
|
| 284 |
+
succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]}
|
| 285 |
+
evc = np.zeros(n, np.int64)
|
| 286 |
+
for ev in ann["task_events"]:
|
| 287 |
+
if 0 <= ev["frame"] < n:
|
| 288 |
+
evc[ev["frame"]] += 1
|
| 289 |
+
state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32)
|
| 290 |
+
instr = ann["task"]["instruction"]
|
| 291 |
+
k = 0
|
| 292 |
+
for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))):
|
| 293 |
+
if k >= n:
|
| 294 |
+
break
|
| 295 |
+
ds.add_frame({
|
| 296 |
+
"observation.images.image": img, "observation.images.wrist_image": wr,
|
| 297 |
+
"observation.state": state[k],
|
| 298 |
+
"observation.joint_pos": fr["joint_pos"][k].astype(np.float32),
|
| 299 |
+
"observation.joint_vel": fr["joint_vel"][k].astype(np.float32),
|
| 300 |
+
"observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32),
|
| 301 |
+
"observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32),
|
| 302 |
+
"action": fr["action"][k].astype(np.float32),
|
| 303 |
+
"annotation.attempt_index": np.array([fr["attempt"][k]], np.int64),
|
| 304 |
+
"annotation.command_index": np.array([fr["command"][k]], np.int64),
|
| 305 |
+
"annotation.phase": np.array([fr["phase"][k]], np.int64),
|
| 306 |
+
"annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64),
|
| 307 |
+
"annotation.task_event": np.array([evc[k]], np.int64),
|
| 308 |
+
"task": instr,
|
| 309 |
+
})
|
| 310 |
+
k += 1
|
| 311 |
+
if k != n:
|
| 312 |
+
raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames")
|
| 313 |
+
ds.save_episode()
|
| 314 |
+
nfr += n
|
| 315 |
+
ds.finalize()
|
| 316 |
+
shutil.rmtree(os.path.join(out, "images"), ignore_errors=True)
|
| 317 |
+
open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n")
|
| 318 |
+
print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def cmd_merge(a):
|
| 322 |
+
from pathlib import Path
|
| 323 |
+
from lerobot.datasets.aggregate import aggregate_datasets
|
| 324 |
+
t0 = time.time()
|
| 325 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 326 |
+
eps = plan["episodes"]
|
| 327 |
+
roots, ids = [], []
|
| 328 |
+
for i in range(a.nshards):
|
| 329 |
+
lo, hi = shard_range(len(eps), i, a.nshards)
|
| 330 |
+
if hi <= lo:
|
| 331 |
+
continue
|
| 332 |
+
r = os.path.join(a.work, "shards", f"shard_{i:03d}")
|
| 333 |
+
if not os.path.exists(os.path.join(r, "DONE")):
|
| 334 |
+
raise SystemExit(f"shard {i} is not done")
|
| 335 |
+
roots.append(Path(r))
|
| 336 |
+
ids.append(f"{plan['repo_id']}-shard{i:03d}")
|
| 337 |
+
if os.path.exists(a.out):
|
| 338 |
+
raise SystemExit(f"{a.out} exists; refusing to overwrite")
|
| 339 |
+
aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out))
|
| 340 |
+
print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True)
|
| 341 |
+
write_sidecars(a, plan)
|
| 342 |
+
print(f"merge done in {time.time() - t0:.0f}s", flush=True)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def write_sidecars(a, plan):
|
| 346 |
+
eps, paper = plan["episodes"], plan["paper"]
|
| 347 |
+
lff = os.path.join(a.out, "lff")
|
| 348 |
+
for sub in ("annotations", "sim_state", "final", "code"):
|
| 349 |
+
os.makedirs(os.path.join(lff, sub), exist_ok=True)
|
| 350 |
+
rows, runs, tasks = [], {}, {}
|
| 351 |
+
for e in eps:
|
| 352 |
+
i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"]
|
| 353 |
+
name = f"episode_{i:06d}"
|
| 354 |
+
if os.path.exists(os.path.join(d, "sim_state.npy")):
|
| 355 |
+
shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy"))
|
| 356 |
+
shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz"))
|
| 357 |
+
for cam, key in (("agentview", "image"), ("wrist", "wrist_image")):
|
| 358 |
+
shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png"))
|
| 359 |
+
with open(os.path.join(lff, "annotations", name + ".json"), "w") as f:
|
| 360 |
+
json.dump(ann, f, indent=1, ensure_ascii=False)
|
| 361 |
+
rows.append(flat_row(i, ann, n, e["from"]))
|
| 362 |
+
tname = ann["task"]["name"]
|
| 363 |
+
rk = (ann["source"]["batch"], ann["source"]["run"])
|
| 364 |
+
r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"),
|
| 365 |
+
run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"],
|
| 366 |
+
memory_free_chain_of=ann["source"].get("memory_free_chain_of"),
|
| 367 |
+
memory_free_rep=ann["source"].get("memory_free_rep"), task=tname,
|
| 368 |
+
seed=ann["task"]["seed"], model=ann["agent"].get("model"),
|
| 369 |
+
harness=ann["agent"].get("harness"),
|
| 370 |
+
harness_version=ann["agent"].get("harness_version"),
|
| 371 |
+
codex_catalog=ann["agent"].get("codex_catalog"),
|
| 372 |
+
outcome_class=ann["run_outcome"].get("outcome_class"),
|
| 373 |
+
attempt_history=ann["run_outcome"].get("attempt_history"),
|
| 374 |
+
agent_final_report=ann["run_outcome"].get("agent_final_report"),
|
| 375 |
+
episodes=[]))
|
| 376 |
+
for x in ann["attempts"]:
|
| 377 |
+
r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success")))
|
| 378 |
+
if tname not in tasks:
|
| 379 |
+
tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")}
|
| 380 |
+
if tname in paper:
|
| 381 |
+
tasks[tname]["paper"] = paper[tname]
|
| 382 |
+
tasks[tname]["instances"] = {}
|
| 383 |
+
tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"]
|
| 384 |
+
# memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id)
|
| 385 |
+
by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")}
|
| 386 |
+
for r in runs.values():
|
| 387 |
+
if r.get("memory_free_chain_of"):
|
| 388 |
+
r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"]))
|
| 389 |
+
for (b, rn), r in runs.items():
|
| 390 |
+
r["memory_free_retries"] = sorted((x["run"] for x in runs.values()
|
| 391 |
+
if x["batch"] == b and x.get("memory_free_chain_of_run") == rn),
|
| 392 |
+
key=lambda q: runs[(b, q)].get("memory_free_rep") or 0)
|
| 393 |
+
with open(os.path.join(lff, "episodes.jsonl"), "w") as f:
|
| 394 |
+
for row in rows:
|
| 395 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 396 |
+
with open(os.path.join(lff, "runs.jsonl"), "w") as f:
|
| 397 |
+
for r in runs.values():
|
| 398 |
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 399 |
+
with open(os.path.join(lff, "tasks.json"), "w") as f:
|
| 400 |
+
json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False)
|
| 401 |
+
with open(os.path.join(lff, "batches.json"), "w") as f:
|
| 402 |
+
json.dump(BATCH_NOTES, f, indent=1)
|
| 403 |
+
with open(os.path.join(lff, "rejected.json"), "w") as f:
|
| 404 |
+
json.dump(plan["rejected"], f, indent=1)
|
| 405 |
+
here = os.path.dirname(os.path.abspath(__file__))
|
| 406 |
+
for s in ("lerobot_replay.py", "lerobot_export.py"):
|
| 407 |
+
shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s))
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def main():
|
| 411 |
+
ap = argparse.ArgumentParser()
|
| 412 |
+
ap.add_argument("step", choices=["plan", "shard", "merge"])
|
| 413 |
+
ap.add_argument("--work", required=True)
|
| 414 |
+
ap.add_argument("--raw", default="")
|
| 415 |
+
ap.add_argument("--runs-root", default="")
|
| 416 |
+
ap.add_argument("--out", default="")
|
| 417 |
+
ap.add_argument("--paper", default="")
|
| 418 |
+
ap.add_argument("--task-set", default="")
|
| 419 |
+
ap.add_argument("--repo-id", default="lffbench/agent-replays")
|
| 420 |
+
ap.add_argument("--batches", default="")
|
| 421 |
+
ap.add_argument("--limit", type=int, default=0)
|
| 422 |
+
ap.add_argument("--shard", type=int, default=0)
|
| 423 |
+
ap.add_argument("--nshards", type=int, default=1)
|
| 424 |
+
ap.add_argument("--threads", type=int, default=2)
|
| 425 |
+
ap.add_argument("--vcodec", default="libsvtav1")
|
| 426 |
+
a = ap.parse_args()
|
| 427 |
+
{"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_mer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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay
|
| 2 |
+
against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the
|
| 3 |
+
LeRobot export (scripts/lerobot_export.py).
|
| 4 |
+
|
| 5 |
+
python scripts/lerobot_replay.py check <run_dir> [<run_dir> ...] [--json out.json] # replay only, print fidelity
|
| 6 |
+
python scripts/lerobot_replay.py record <run_dir> --out <raw_root> [--res 256]
|
| 7 |
+
|
| 8 |
+
Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot
|
| 9 |
+
commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite
|
| 10 |
+
is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly
|
| 11 |
+
like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same
|
| 12 |
+
outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width,
|
| 13 |
+
ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code
|
| 14 |
+
hashes equal the current files are expected to match (check_code()).
|
| 15 |
+
|
| 16 |
+
Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB,
|
| 17 |
+
proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes:
|
| 18 |
+
protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode
|
| 19 |
+
per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the
|
| 20 |
+
fidelity check runs in record mode too. Per episode the recorder writes <raw_root>/<batch>/<run>/epNN/:
|
| 21 |
+
agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes)
|
| 22 |
+
frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase
|
| 23 |
+
sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel)
|
| 24 |
+
final_*.png, final.npz observation after the last control step (the state the outcome was judged in)
|
| 25 |
+
annotation.json episode annotation (build_annotation)
|
| 26 |
+
and <raw_root>/<batch>/<run>/replay.json (fidelity) when the whole run is done.
|
| 27 |
+
"""
|
| 28 |
+
import argparse
|
| 29 |
+
import ast
|
| 30 |
+
import hashlib
|
| 31 |
+
import importlib
|
| 32 |
+
import json
|
| 33 |
+
import math
|
| 34 |
+
import os
|
| 35 |
+
import pkgutil
|
| 36 |
+
import re
|
| 37 |
+
import shutil
|
| 38 |
+
import sys
|
| 39 |
+
import time
|
| 40 |
+
from collections import defaultdict
|
| 41 |
+
|
| 42 |
+
import numpy as np
|
| 43 |
+
|
| 44 |
+
LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 45 |
+
sys.path.insert(0, LFF_ROOT)
|
| 46 |
+
|
| 47 |
+
from lffbench import envs # noqa: E402
|
| 48 |
+
from lffbench import tasks as task_pkg # noqa: E402
|
| 49 |
+
from lffbench.agent import camera as C # noqa: E402
|
| 50 |
+
from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402
|
| 51 |
+
from lffbench.task_base import TASKS # noqa: E402
|
| 52 |
+
|
| 53 |
+
for _m in pkgutil.iter_modules(task_pkg.__path__):
|
| 54 |
+
importlib.import_module(f"lffbench.tasks.{_m.name}")
|
| 55 |
+
|
| 56 |
+
# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the
|
| 57 |
+
# task's outcome() check after `finish` (the arm holds still; not an agent action)
|
| 58 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 59 |
+
FPS = 20
|
| 60 |
+
SCHEMA = "lff-replay-1"
|
| 61 |
+
|
| 62 |
+
# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR"
|
| 63 |
+
ERROR_FLAGS = ("trap_fired", "recovered_in_attempt")
|
| 64 |
+
ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events",
|
| 65 |
+
"n_missed_strikes", "n_open_gripper_pushes")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def load_jsonl(p):
|
| 69 |
+
out = []
|
| 70 |
+
if not os.path.exists(p):
|
| 71 |
+
return out
|
| 72 |
+
with open(p) as f:
|
| 73 |
+
for line in f:
|
| 74 |
+
line = line.strip()
|
| 75 |
+
if line:
|
| 76 |
+
try:
|
| 77 |
+
out.append(json.loads(line))
|
| 78 |
+
except ValueError:
|
| 79 |
+
pass
|
| 80 |
+
return out
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def norm_json(o):
|
| 84 |
+
return json.loads(json.dumps(o, default=_json_default))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def sha256(p):
|
| 88 |
+
with open(p, "rb") as f:
|
| 89 |
+
return hashlib.sha256(f.read()).hexdigest()
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def check_code(run_dir):
|
| 93 |
+
"""[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract."""
|
| 94 |
+
p = os.path.join(run_dir, "contract.json")
|
| 95 |
+
if not os.path.exists(p):
|
| 96 |
+
return [("contract.json", None, None)]
|
| 97 |
+
files = json.load(open(p))["contract"].get("server_code_files", {})
|
| 98 |
+
bad = []
|
| 99 |
+
for f, h in files.items():
|
| 100 |
+
q = os.path.join(LFF_ROOT, f)
|
| 101 |
+
cur = sha256(q) if os.path.exists(q) else None
|
| 102 |
+
if cur != h:
|
| 103 |
+
bad.append((f, h, cur))
|
| 104 |
+
return bad
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def diff_json(a, b, path="", tol=0.0, out=None, limit=20):
|
| 108 |
+
"""Differences between two JSON values (numbers compared with an absolute tolerance)."""
|
| 109 |
+
out = [] if out is None else out
|
| 110 |
+
if len(out) >= limit:
|
| 111 |
+
return out
|
| 112 |
+
if isinstance(a, dict) and isinstance(b, dict):
|
| 113 |
+
for k in sorted(set(a) | set(b)):
|
| 114 |
+
if k not in a or k not in b:
|
| 115 |
+
out.append((f"{path}.{k}", a.get(k, "<missing>"), b.get(k, "<missing>")))
|
| 116 |
+
else:
|
| 117 |
+
diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit)
|
| 118 |
+
elif isinstance(a, list) and isinstance(b, list):
|
| 119 |
+
if len(a) != len(b):
|
| 120 |
+
out.append((path, f"len {len(a)}", f"len {len(b)}"))
|
| 121 |
+
else:
|
| 122 |
+
for i, (x, y) in enumerate(zip(a, b)):
|
| 123 |
+
diff_json(x, y, f"{path}[{i}]", tol, out, limit)
|
| 124 |
+
elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
|
| 125 |
+
if a != b:
|
| 126 |
+
out.append((path, a, b))
|
| 127 |
+
elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))):
|
| 128 |
+
out.append((path, a, b))
|
| 129 |
+
return out
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def error_event(o):
|
| 133 |
+
"""True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none."""
|
| 134 |
+
if not isinstance(o, dict):
|
| 135 |
+
return None
|
| 136 |
+
keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o]
|
| 137 |
+
if not keys:
|
| 138 |
+
return None
|
| 139 |
+
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)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# ====================================================================================================== logs -> notes
|
| 143 |
+
|
| 144 |
+
class RunLog:
|
| 145 |
+
"""Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's
|
| 146 |
+
narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition."""
|
| 147 |
+
|
| 148 |
+
def __init__(self, run_dir, manifest=None):
|
| 149 |
+
self.run_dir = os.path.abspath(run_dir.rstrip("/"))
|
| 150 |
+
self.run = os.path.basename(self.run_dir)
|
| 151 |
+
self.batch = os.path.basename(os.path.dirname(self.run_dir))
|
| 152 |
+
self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl"))
|
| 153 |
+
self.start = next(e for e in self.ev if e["ev"] == "session_start")
|
| 154 |
+
self.calls, self.dones, self.harness_status = {}, [], []
|
| 155 |
+
last = None
|
| 156 |
+
for e in self.ev:
|
| 157 |
+
if e["ev"] == "call":
|
| 158 |
+
self.calls[(int(e["attempt"]), int(e["step"]))] = e
|
| 159 |
+
last = e
|
| 160 |
+
elif e["ev"] == "done":
|
| 161 |
+
self.dones.append(e)
|
| 162 |
+
last = e
|
| 163 |
+
elif e["ev"] == "http" and last is not None and "think_s" not in last:
|
| 164 |
+
ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \
|
| 165 |
+
(last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe"))
|
| 166 |
+
if ok:
|
| 167 |
+
last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s")
|
| 168 |
+
self.manifest = manifest or {}
|
| 169 |
+
self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {}
|
| 170 |
+
p = os.path.join(self.run_dir, "harness.json")
|
| 171 |
+
self.harness = json.load(open(p)) if os.path.exists(p) else {}
|
| 172 |
+
self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl"))
|
| 173 |
+
self._narration()
|
| 174 |
+
|
| 175 |
+
# ---------------------------------------------------------------- agent narration
|
| 176 |
+
def _narration(self):
|
| 177 |
+
"""notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one;
|
| 178 |
+
finish_notes[attempt] likewise for the agent's finish call; final_report = its last message."""
|
| 179 |
+
self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", []
|
| 180 |
+
buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
|
| 181 |
+
attempt = 1
|
| 182 |
+
|
| 183 |
+
def take():
|
| 184 |
+
nonlocal buf
|
| 185 |
+
out = {k: v for k, v in buf.items() if v}
|
| 186 |
+
buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
|
| 187 |
+
return out
|
| 188 |
+
|
| 189 |
+
last_msg = ""
|
| 190 |
+
for t in self.traj:
|
| 191 |
+
if t.get("kind") == "header":
|
| 192 |
+
self.headers.append(t.get("agent") or {})
|
| 193 |
+
continue
|
| 194 |
+
if t.get("kind") != "step":
|
| 195 |
+
continue
|
| 196 |
+
if (t.get("message") or "").strip():
|
| 197 |
+
buf["messages"].append(t["message"].strip())
|
| 198 |
+
last_msg = t["message"].strip()
|
| 199 |
+
if (t.get("reasoning_content") or "").strip():
|
| 200 |
+
buf["reasoning"].append(t["reasoning_content"].strip())
|
| 201 |
+
res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])}
|
| 202 |
+
for c in t.get("tool_calls") or []:
|
| 203 |
+
fn, args = c.get("function_name"), c.get("arguments") or {}
|
| 204 |
+
if fn == "shell":
|
| 205 |
+
buf["shell"].append(str(args.get("command", ""))[:2000])
|
| 206 |
+
elif fn == "view_images":
|
| 207 |
+
buf["viewed"].extend(args.get("paths") or [])
|
| 208 |
+
elif fn == "robot":
|
| 209 |
+
cmd = str(args.get("command", "")).strip()
|
| 210 |
+
r = res.get(c.get("tool_call_id")) or {}
|
| 211 |
+
try:
|
| 212 |
+
rep = json.loads(r.get("content") or "{}")
|
| 213 |
+
except ValueError:
|
| 214 |
+
rep = {}
|
| 215 |
+
word = cmd.split()[0] if cmd else ""
|
| 216 |
+
m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", "")))
|
| 217 |
+
if word in ("move_eef", "observe") and m:
|
| 218 |
+
a, s = int(m.group(1)), int(m.group(2))
|
| 219 |
+
n = take()
|
| 220 |
+
n["command"] = cmd
|
| 221 |
+
self.notes[(a, s)] = n
|
| 222 |
+
attempt = a
|
| 223 |
+
elif word in ("finish", "done"):
|
| 224 |
+
n = take()
|
| 225 |
+
n["command"] = cmd
|
| 226 |
+
n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)}
|
| 227 |
+
self.finish_notes.setdefault(attempt, n)
|
| 228 |
+
if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"):
|
| 229 |
+
attempt += 1
|
| 230 |
+
# status / help / errors: their narration stays in the buffer for the next command
|
| 231 |
+
self.final_report = last_msg
|
| 232 |
+
|
| 233 |
+
# ---------------------------------------------------------------- run-level labels
|
| 234 |
+
def attempts(self):
|
| 235 |
+
out = []
|
| 236 |
+
for e in self.dones:
|
| 237 |
+
o = e.get("outcome") or {}
|
| 238 |
+
if isinstance(o, str):
|
| 239 |
+
try:
|
| 240 |
+
o = ast.literal_eval(o)
|
| 241 |
+
except (ValueError, SyntaxError):
|
| 242 |
+
o = {}
|
| 243 |
+
out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o,
|
| 244 |
+
reason=e.get("reason") or ""))
|
| 245 |
+
return sorted(out, key=lambda x: x["attempt"])
|
| 246 |
+
|
| 247 |
+
def condition(self):
|
| 248 |
+
s, en = self.start, self.entry
|
| 249 |
+
mem = s.get("memory", en.get("mem"))
|
| 250 |
+
chain = en.get("chain")
|
| 251 |
+
if mem == "full":
|
| 252 |
+
cond = "with_history"
|
| 253 |
+
elif chain:
|
| 254 |
+
cond = "memory_free_retry"
|
| 255 |
+
else:
|
| 256 |
+
cond = "independent_single_attempt"
|
| 257 |
+
return cond, chain
|
| 258 |
+
|
| 259 |
+
def outcome_class(self):
|
| 260 |
+
"""CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None."""
|
| 261 |
+
att = self.attempts()
|
| 262 |
+
if not att or self.start.get("memory") != "full":
|
| 263 |
+
return None, "".join("S" if a["success"] else "F" for a in att)
|
| 264 |
+
hist = "".join("S" if a["success"] else "F" for a in att)
|
| 265 |
+
if att[0]["success"]:
|
| 266 |
+
ev = error_event(att[0]["outcome"])
|
| 267 |
+
cls = "S?" if ev is None else ("IR" if ev else "CS")
|
| 268 |
+
else:
|
| 269 |
+
cls = "XR" if any(a["success"] for a in att) else "F"
|
| 270 |
+
return cls, hist
|
| 271 |
+
|
| 272 |
+
def agent_info(self):
|
| 273 |
+
h, en = self.harness, self.entry
|
| 274 |
+
hdr = self.headers[0] if self.headers else {}
|
| 275 |
+
return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"),
|
| 276 |
+
harness_version=h.get("version") or hdr.get("version"),
|
| 277 |
+
harness_binary_sha256=(h.get("binary") or {}).get("sha256"),
|
| 278 |
+
model=h.get("model") or en.get("model") or hdr.get("model_name"),
|
| 279 |
+
effort=h.get("effort") or en.get("effort") or hdr.get("effort"),
|
| 280 |
+
provider=h.get("provider") or en.get("provider"),
|
| 281 |
+
codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"),
|
| 282 |
+
jail=en.get("jail"))
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
# ====================================================================================================== recording
|
| 286 |
+
|
| 287 |
+
class EpisodeSink:
|
| 288 |
+
"""Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed."""
|
| 289 |
+
|
| 290 |
+
def __init__(self, path):
|
| 291 |
+
self.path = path
|
| 292 |
+
os.makedirs(path, exist_ok=True)
|
| 293 |
+
self.w = None
|
| 294 |
+
self.num = defaultdict(list)
|
| 295 |
+
self.n = 0
|
| 296 |
+
|
| 297 |
+
def add(self, st, imgs):
|
| 298 |
+
import imageio
|
| 299 |
+
if self.w is None:
|
| 300 |
+
self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb",
|
| 301 |
+
pixelformat="rgb24", macro_block_size=1,
|
| 302 |
+
ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error")
|
| 303 |
+
for k in ("agentview", "wrist")]
|
| 304 |
+
for w, im in zip(self.w, imgs):
|
| 305 |
+
w.append_data(im)
|
| 306 |
+
for k, v in st.items():
|
| 307 |
+
self.num[k].append(v)
|
| 308 |
+
self.n += 1
|
| 309 |
+
|
| 310 |
+
def close(self, final_state, final_imgs):
|
| 311 |
+
from PIL import Image
|
| 312 |
+
if self.w is not None:
|
| 313 |
+
for w in self.w:
|
| 314 |
+
w.close()
|
| 315 |
+
arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"}
|
| 316 |
+
np.savez(os.path.join(self.path, "frames.npz"), **arr)
|
| 317 |
+
if self.num.get("sim_state"):
|
| 318 |
+
np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64))
|
| 319 |
+
np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()})
|
| 320 |
+
for k, im in zip(("agentview", "wrist"), final_imgs):
|
| 321 |
+
Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png"))
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
class Recorder:
|
| 325 |
+
"""Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink."""
|
| 326 |
+
|
| 327 |
+
def __init__(self, rp, res):
|
| 328 |
+
self.rp, self.res = rp, int(res)
|
| 329 |
+
self.active = False
|
| 330 |
+
self.sink = None
|
| 331 |
+
self.cur = dict(attempt=1, command=-1, phase=PHASES["move"])
|
| 332 |
+
env = rp.task.env
|
| 333 |
+
self.env, self.rob = env, env.robots[0]
|
| 334 |
+
self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist"))
|
| 335 |
+
orig = env.step
|
| 336 |
+
|
| 337 |
+
def step(a):
|
| 338 |
+
if self.active and self.sink is not None:
|
| 339 |
+
self.capture(np.asarray(a, np.float64))
|
| 340 |
+
out = orig(a)
|
| 341 |
+
if self.active and self.sink is not None:
|
| 342 |
+
self.rp.poll_events(self.sink.n - 1)
|
| 343 |
+
return out
|
| 344 |
+
|
| 345 |
+
env.step = step
|
| 346 |
+
|
| 347 |
+
@property
|
| 348 |
+
def n(self):
|
| 349 |
+
return self.sink.n if self.sink is not None else 0
|
| 350 |
+
|
| 351 |
+
def state(self):
|
| 352 |
+
import robosuite.utils.transform_utils as T
|
| 353 |
+
env, rob = self.env, self.rob
|
| 354 |
+
d = env.sim.data
|
| 355 |
+
eef = np.array(d.site_xpos[rob.eef_site_id], np.float64)
|
| 356 |
+
q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw")
|
| 357 |
+
gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64)
|
| 358 |
+
try:
|
| 359 |
+
flat = np.asarray(env.sim.get_state().flatten(), np.float64)
|
| 360 |
+
except Exception:
|
| 361 |
+
flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64)
|
| 362 |
+
sk = self.rp.task.sk
|
| 363 |
+
return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64),
|
| 364 |
+
gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64),
|
| 365 |
+
joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64),
|
| 366 |
+
gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64),
|
| 367 |
+
eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)),
|
| 368 |
+
sim_time=np.float64(d.time), sim_state=flat)
|
| 369 |
+
|
| 370 |
+
def images(self):
|
| 371 |
+
return [envs.render(self.env, c, self.res) for c in self.cams]
|
| 372 |
+
|
| 373 |
+
def capture(self, a):
|
| 374 |
+
st = self.state()
|
| 375 |
+
st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]),
|
| 376 |
+
phase=np.int64(self.cur["phase"]))
|
| 377 |
+
self.sink.add(st, self.images())
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
class RunReplay:
|
| 381 |
+
def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None):
|
| 382 |
+
self.run_dir = os.path.abspath(run_dir.rstrip("/"))
|
| 383 |
+
self.run_name = os.path.basename(self.run_dir)
|
| 384 |
+
self.log = RunLog(self.run_dir, manifest)
|
| 385 |
+
self.ev = self.log.ev
|
| 386 |
+
self.start = self.log.start
|
| 387 |
+
cp = os.path.join(self.run_dir, "contract.json")
|
| 388 |
+
self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {}
|
| 389 |
+
spec = self.contract.get("image_spec") or {}
|
| 390 |
+
self.image_res = int(spec.get("width", 512))
|
| 391 |
+
self.code_diff = check_code(self.run_dir)
|
| 392 |
+
s = self.start
|
| 393 |
+
self.task = TASKS[s["task"]](cam_res=self.image_res)
|
| 394 |
+
inst = self.task.sample_instance(s["seed"])
|
| 395 |
+
logged = s.get("inst") or {}
|
| 396 |
+
sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")})
|
| 397 |
+
self.inst_diff = diff_json(sampled, logged, "inst")
|
| 398 |
+
if s.get("arm", "none") not in (None, "none") or logged.get("nominal"):
|
| 399 |
+
inst.update(logged) # controlled arms / nominal: the server overrode these instance fields
|
| 400 |
+
self.inst_diff = []
|
| 401 |
+
self.inst = inst
|
| 402 |
+
self.protocol = getattr(self.task, "protocol", "cross")
|
| 403 |
+
self.k = int(s.get("k") or self.task.max_attempts)
|
| 404 |
+
self.attempt = 1
|
| 405 |
+
self.mismatch = [] # (where, what, logged, replayed)
|
| 406 |
+
self.n_checked = 0
|
| 407 |
+
self.max_dev_m = 0.0
|
| 408 |
+
self.unfinished = None
|
| 409 |
+
self.rec = Recorder(self, res) if record else None
|
| 410 |
+
self.res = int(res)
|
| 411 |
+
self.out_root = out_root
|
| 412 |
+
self.n_mon = 0
|
| 413 |
+
self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0
|
| 414 |
+
self.episodes = [] # summaries of the written episodes
|
| 415 |
+
self.task.reset_instance(self.inst)
|
| 416 |
+
self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
|
| 417 |
+
sim = self.task.env.sim
|
| 418 |
+
bid = sim.model.body_name2id("robot0_base")
|
| 419 |
+
self.base_off = np.array(sim.data.body_xpos[bid], float).copy()
|
| 420 |
+
if self.rec:
|
| 421 |
+
self._open_episode()
|
| 422 |
+
|
| 423 |
+
# ------------------------------------------------------------------ episodes
|
| 424 |
+
def _ep_dir(self):
|
| 425 |
+
return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}")
|
| 426 |
+
|
| 427 |
+
def _open_episode(self):
|
| 428 |
+
self.rec.sink = EpisodeSink(self._ep_dir())
|
| 429 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
|
| 430 |
+
self.rec.active = True
|
| 431 |
+
self.events, self.spans, self.ep_attempts = [], [], []
|
| 432 |
+
self.ep_initial = self.rec.state() # state right after the reset (before frame 0)
|
| 433 |
+
|
| 434 |
+
def close_episode(self):
|
| 435 |
+
if not self.rec:
|
| 436 |
+
self.ep_attempts = []
|
| 437 |
+
return
|
| 438 |
+
sink = self.rec.sink
|
| 439 |
+
st = self.rec.state()
|
| 440 |
+
imgs = self.rec.images()
|
| 441 |
+
st.pop("sim_state", None)
|
| 442 |
+
sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs)
|
| 443 |
+
ann = build_annotation(self, sink)
|
| 444 |
+
with open(os.path.join(sink.path, "annotation.json"), "w") as f:
|
| 445 |
+
json.dump(ann, f, indent=1, default=_json_default)
|
| 446 |
+
self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n,
|
| 447 |
+
attempts=[a["attempt"] for a in self.ep_attempts]))
|
| 448 |
+
self.rec.active = False
|
| 449 |
+
self.rec.sink = None
|
| 450 |
+
self.ep_index += 1
|
| 451 |
+
|
| 452 |
+
# ------------------------------------------------------------------ monitor events (task-side error events)
|
| 453 |
+
def poll_events(self, frame):
|
| 454 |
+
mon = getattr(self.task, "mon", None)
|
| 455 |
+
evs = mon.get("events") if isinstance(mon, dict) else None
|
| 456 |
+
if not isinstance(evs, list):
|
| 457 |
+
return
|
| 458 |
+
if len(evs) < self.n_mon: # monitor was rebuilt
|
| 459 |
+
self.n_mon = 0
|
| 460 |
+
for e in evs[self.n_mon:]:
|
| 461 |
+
self.events.append(dict(frame=int(frame), attempt=self.attempt,
|
| 462 |
+
event=norm_json(e) if isinstance(e, dict) else str(e)))
|
| 463 |
+
self.n_mon = len(evs)
|
| 464 |
+
|
| 465 |
+
# ------------------------------------------------------------------ state as the server reports it
|
| 466 |
+
def proprio_la(self):
|
| 467 |
+
p = self.ex.proprio()
|
| 468 |
+
pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off]
|
| 469 |
+
return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"])
|
| 470 |
+
|
| 471 |
+
def compare(self, where, rep_logged, rep):
|
| 472 |
+
self.n_checked += 1
|
| 473 |
+
for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"):
|
| 474 |
+
if k not in rep_logged or k not in rep:
|
| 475 |
+
continue
|
| 476 |
+
a, b = rep_logged[k], rep[k]
|
| 477 |
+
if k == "eef_pos":
|
| 478 |
+
dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float))))
|
| 479 |
+
self.max_dev_m = max(self.max_dev_m, dev)
|
| 480 |
+
if dev > 1.5e-4:
|
| 481 |
+
self.mismatch.append((where, k, a, b))
|
| 482 |
+
elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4):
|
| 483 |
+
self.mismatch.append((where, k, a, b))
|
| 484 |
+
if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)):
|
| 485 |
+
self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok")))
|
| 486 |
+
|
| 487 |
+
def _span(self, e, f0, kind):
|
| 488 |
+
if self.rec:
|
| 489 |
+
self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0,
|
| 490 |
+
frame_end=self.rec.n))
|
| 491 |
+
|
| 492 |
+
# ------------------------------------------------------------------ commands (robot_server._handle_v2)
|
| 493 |
+
def move_eef(self, e):
|
| 494 |
+
args = e.get("args") or {}
|
| 495 |
+
where = f"a{e['attempt']}s{e['step']}"
|
| 496 |
+
logged = e.get("report") or {}
|
| 497 |
+
f0 = self.rec.n if self.rec else 0
|
| 498 |
+
p = self.ex.proprio()
|
| 499 |
+
if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}:
|
| 500 |
+
self._span(e, f0, "error")
|
| 501 |
+
return self.compare(where, logged, dict(ok=False))
|
| 502 |
+
off = self.base_off
|
| 503 |
+
try:
|
| 504 |
+
cur = np.asarray(p["eef_pos"], float) - off
|
| 505 |
+
tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
|
| 506 |
+
yaw = float(args.get("yaw", p["eef_yaw_deg"]))
|
| 507 |
+
speed = None if args.get("speed") in (None, "") else float(args["speed"])
|
| 508 |
+
except (TypeError, ValueError):
|
| 509 |
+
self._span(e, f0, "error")
|
| 510 |
+
return self.compare(where, logged, dict(ok=False))
|
| 511 |
+
grip = args.get("gripper")
|
| 512 |
+
if grip not in (None, "open", "close"):
|
| 513 |
+
self._span(e, f0, "error")
|
| 514 |
+
return self.compare(where, logged, dict(ok=False))
|
| 515 |
+
moving = any(k in args for k in ("x", "y", "z", "yaw"))
|
| 516 |
+
tgt_w = np.asarray(tgt) + off
|
| 517 |
+
if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)):
|
| 518 |
+
self._span(e, f0, "rejected")
|
| 519 |
+
return self.compare(where, logged, dict(ok=False, **self.proprio_la()))
|
| 520 |
+
raw = {}
|
| 521 |
+
if self.rec:
|
| 522 |
+
self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"])
|
| 523 |
+
if moving:
|
| 524 |
+
mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw)
|
| 525 |
+
if speed is not None:
|
| 526 |
+
mv["speed"] = speed
|
| 527 |
+
raw.update(self.ex.call("move_to", mv).report)
|
| 528 |
+
if grip is not None:
|
| 529 |
+
if self.rec:
|
| 530 |
+
self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"])
|
| 531 |
+
raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report)
|
| 532 |
+
rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la())
|
| 533 |
+
self.compare(where, logged, rep)
|
| 534 |
+
lr = e.get("raw") or {}
|
| 535 |
+
for k in ("holding_object", "touched_object"):
|
| 536 |
+
if k in lr and k in raw and bool(lr[k]) != bool(raw[k]):
|
| 537 |
+
self.mismatch.append((where, "raw." + k, lr[k], raw[k]))
|
| 538 |
+
self._span(e, f0, "move_eef")
|
| 539 |
+
|
| 540 |
+
def observe(self, e):
|
| 541 |
+
f0 = self.rec.n if self.rec else 0
|
| 542 |
+
self._span(e, f0, "observe")
|
| 543 |
+
|
| 544 |
+
def done(self, e):
|
| 545 |
+
f0 = self.rec.n if self.rec else 0
|
| 546 |
+
if self.rec:
|
| 547 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"])
|
| 548 |
+
out = self.task.outcome(self.inst)
|
| 549 |
+
succ = bool(out["success"])
|
| 550 |
+
where = f"a{e['attempt']}done"
|
| 551 |
+
if succ != bool(e.get("success") in (True, "True")):
|
| 552 |
+
self.mismatch.append((where, "success", e.get("success"), succ))
|
| 553 |
+
lo = e.get("outcome") or {}
|
| 554 |
+
ro = norm_json({k: v for k, v in out.items() if k != "feedback"})
|
| 555 |
+
if isinstance(lo, dict):
|
| 556 |
+
for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8):
|
| 557 |
+
self.mismatch.append((where,) + d)
|
| 558 |
+
info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""),
|
| 559 |
+
feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")),
|
| 560 |
+
think_s=e.get("think_s"))
|
| 561 |
+
try:
|
| 562 |
+
info["feedback_f2"] = self.task.feedback(self.inst, out, "F2")
|
| 563 |
+
except Exception as ex_:
|
| 564 |
+
info["feedback_f2"] = f"<unavailable: {type(ex_).__name__}>"
|
| 565 |
+
if self.rec:
|
| 566 |
+
info["judge_frames"] = [f0, self.rec.n]
|
| 567 |
+
self.ep_attempts.append(info)
|
| 568 |
+
last = self.attempt >= self.k or succ or bool(out.get("terminal"))
|
| 569 |
+
if self.protocol == "cross" or last:
|
| 570 |
+
self.close_episode()
|
| 571 |
+
if last:
|
| 572 |
+
return True
|
| 573 |
+
self.attempt += 1
|
| 574 |
+
if self.protocol == "cross":
|
| 575 |
+
self.task.reset_instance(self.inst)
|
| 576 |
+
self.n_mon = 0
|
| 577 |
+
if self.rec:
|
| 578 |
+
self._open_episode()
|
| 579 |
+
elif self.rec:
|
| 580 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
|
| 581 |
+
self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
|
| 582 |
+
return False
|
| 583 |
+
|
| 584 |
+
def run(self):
|
| 585 |
+
t0 = time.time()
|
| 586 |
+
finished = False
|
| 587 |
+
for e in self.ev:
|
| 588 |
+
if e["ev"] == "call":
|
| 589 |
+
if e.get("cmd") == "move_eef":
|
| 590 |
+
self.move_eef(e)
|
| 591 |
+
elif e.get("cmd") == "observe":
|
| 592 |
+
self.observe(e)
|
| 593 |
+
else:
|
| 594 |
+
self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None))
|
| 595 |
+
elif e["ev"] == "done":
|
| 596 |
+
finished = self.done(e)
|
| 597 |
+
if finished:
|
| 598 |
+
break
|
| 599 |
+
self.unfinished = not finished
|
| 600 |
+
if not finished and self.rec and self.rec.sink is not None:
|
| 601 |
+
# the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged
|
| 602 |
+
if self.rec.n or self.ep_attempts:
|
| 603 |
+
self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True,
|
| 604 |
+
finish_reason="", feedback_shown="", auto_ended=False))
|
| 605 |
+
self.close_episode()
|
| 606 |
+
else:
|
| 607 |
+
shutil.rmtree(self.rec.sink.path, ignore_errors=True)
|
| 608 |
+
self.rec.sink = None
|
| 609 |
+
self.wall_s = time.time() - t0
|
| 610 |
+
return self
|
| 611 |
+
|
| 612 |
+
def summary(self):
|
| 613 |
+
return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"],
|
| 614 |
+
protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff),
|
| 615 |
+
n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6),
|
| 616 |
+
unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1),
|
| 617 |
+
first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]])
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
# ====================================================================================================== annotation
|
| 621 |
+
|
| 622 |
+
def task_info(task, inst):
|
| 623 |
+
cls = type(task)
|
| 624 |
+
return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable",
|
| 625 |
+
category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"),
|
| 626 |
+
max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)),
|
| 627 |
+
instruction=cls.instruction)
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
def build_annotation(rp, sink):
|
| 631 |
+
"""Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2
|
| 632 |
+
failure description), run-level outcome class, every robot command with its frame span and the agent's narration,
|
| 633 |
+
task-side error events with frame indices."""
|
| 634 |
+
log = rp.log
|
| 635 |
+
s = rp.start
|
| 636 |
+
cond, chain = log.condition()
|
| 637 |
+
cls, hist = log.outcome_class()
|
| 638 |
+
att_all = log.attempts()
|
| 639 |
+
attempts = []
|
| 640 |
+
for a in rp.ep_attempts:
|
| 641 |
+
a = dict(a)
|
| 642 |
+
n = a["attempt"]
|
| 643 |
+
later = [x for x in att_all if x["attempt"] > n]
|
| 644 |
+
a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later))
|
| 645 |
+
a["is_last_attempt_of_run"] = not later
|
| 646 |
+
fn = log.finish_notes.get(n)
|
| 647 |
+
if fn:
|
| 648 |
+
a["agent_finish"] = fn
|
| 649 |
+
a["error_event_in_attempt"] = error_event(a.get("outcome"))
|
| 650 |
+
attempts.append(a)
|
| 651 |
+
# post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command)
|
| 652 |
+
for a in attempts:
|
| 653 |
+
nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1])
|
| 654 |
+
if a.get("success") is False and nxt:
|
| 655 |
+
note = log.notes[nxt[0]]
|
| 656 |
+
a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note}
|
| 657 |
+
commands = []
|
| 658 |
+
for sp in rp.spans:
|
| 659 |
+
e = log.calls.get((sp["attempt"], sp["step"])) or {}
|
| 660 |
+
rep = e.get("report") or {}
|
| 661 |
+
c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"],
|
| 662 |
+
frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]),
|
| 663 |
+
args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"),
|
| 664 |
+
stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"),
|
| 665 |
+
gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"),
|
| 666 |
+
touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"),
|
| 667 |
+
agent_obs_images=rep.get("images"))
|
| 668 |
+
note = log.notes.get((sp["attempt"], sp["step"]))
|
| 669 |
+
if note:
|
| 670 |
+
c["agent_note"] = {k: v for k, v in note.items() if k != "command"}
|
| 671 |
+
commands.append(c)
|
| 672 |
+
t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x]
|
| 673 |
+
return dict(
|
| 674 |
+
schema=SCHEMA,
|
| 675 |
+
source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts],
|
| 676 |
+
episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain,
|
| 677 |
+
memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None),
|
| 678 |
+
feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"),
|
| 679 |
+
k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"),
|
| 680 |
+
contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256")
|
| 681 |
+
if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)),
|
| 682 |
+
agent=log.agent_info(),
|
| 683 |
+
task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"),
|
| 684 |
+
instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}),
|
| 685 |
+
run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all),
|
| 686 |
+
run_success=any(x["success"] for x in att_all) if att_all else None,
|
| 687 |
+
agent_final_report=log.final_report[:6000] or None,
|
| 688 |
+
mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)),
|
| 689 |
+
attempts=attempts,
|
| 690 |
+
commands=commands,
|
| 691 |
+
task_events=rp.events,
|
| 692 |
+
frames=dict(n=sink.n, fps=FPS, image_res=rp.res,
|
| 693 |
+
phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"],
|
| 694 |
+
joint_pos=rp.ep_initial["joint_pos"],
|
| 695 |
+
gripper_qpos=rp.ep_initial["gripper_qpos"])),
|
| 696 |
+
)
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
# ====================================================================================================== CLI
|
| 700 |
+
|
| 701 |
+
def load_manifest(run_dir):
|
| 702 |
+
p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json")
|
| 703 |
+
return json.load(open(p)) if os.path.exists(p) else {}
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
def main():
|
| 707 |
+
ap = argparse.ArgumentParser()
|
| 708 |
+
ap.add_argument("mode", choices=["check", "record"])
|
| 709 |
+
ap.add_argument("runs", nargs="+")
|
| 710 |
+
ap.add_argument("--json", default="")
|
| 711 |
+
ap.add_argument("--out", default="")
|
| 712 |
+
ap.add_argument("--res", type=int, default=256)
|
| 713 |
+
ap.add_argument("--force", action="store_true", help="record again even if replay.json exists")
|
| 714 |
+
a = ap.parse_args()
|
| 715 |
+
rows = []
|
| 716 |
+
for r in a.runs:
|
| 717 |
+
r = r.rstrip("/")
|
| 718 |
+
try:
|
| 719 |
+
if a.mode == "check":
|
| 720 |
+
s = RunReplay(r, manifest=load_manifest(r)).run().summary()
|
| 721 |
+
else:
|
| 722 |
+
batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r)
|
| 723 |
+
rd = os.path.join(a.out, batch, name)
|
| 724 |
+
if os.path.exists(os.path.join(rd, "replay.json")) and not a.force:
|
| 725 |
+
print(json.dumps(dict(run=name, skipped="exists")), flush=True)
|
| 726 |
+
continue
|
| 727 |
+
shutil.rmtree(rd, ignore_errors=True)
|
| 728 |
+
rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run()
|
| 729 |
+
s = rp.summary()
|
| 730 |
+
s["episodes"] = rp.episodes
|
| 731 |
+
with open(os.path.join(rd, "replay.json"), "w") as f:
|
| 732 |
+
json.dump(s, f, indent=1)
|
| 733 |
+
except Exception:
|
| 734 |
+
import traceback
|
| 735 |
+
s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:])
|
| 736 |
+
rows.append(s)
|
| 737 |
+
print(json.dumps(s), flush=True)
|
| 738 |
+
if a.json:
|
| 739 |
+
with open(a.json, "w") as f:
|
| 740 |
+
json.dump(rows, f, indent=1)
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
if __name__ == "__main__":
|
| 744 |
+
main()
|
leaf/code/v1.5/backfill-20261102-l4i_fx_test/lerobot_export.py
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars.
|
| 2 |
+
|
| 3 |
+
Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding
|
| 4 |
+
can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan):
|
| 5 |
+
|
| 6 |
+
python scripts/lerobot_export.py plan --raw <raw_root>[,<raw_root2>] --runs-root <lffbench>/runs/api \
|
| 7 |
+
--paper <paper/latex> --task-set <lffbench>/sets/main_v2_1inst.txt --work <work_dir> [--batches ...] [--limit N]
|
| 8 |
+
python scripts/lerobot_export.py shard --work <work_dir> --shard i --nshards N
|
| 9 |
+
python scripts/lerobot_export.py merge --work <work_dir> --nshards N --out <dataset_root>
|
| 10 |
+
|
| 11 |
+
Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0
|
| 12 |
+
mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped.
|
| 13 |
+
|
| 14 |
+
LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t):
|
| 15 |
+
observation.images.image agentview RGB 256x256 (upright; LIBERO naming)
|
| 16 |
+
observation.images.wrist_image wrist (eye-in-hand) RGB 256x256
|
| 17 |
+
observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout)
|
| 18 |
+
observation.joint_pos / joint_vel 7 arm joints (rad, rad/s)
|
| 19 |
+
observation.eef_quat 4: xyzw; observation.gripper_width 1 (m)
|
| 20 |
+
action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad),
|
| 21 |
+
gripper (-1 open, +1 close)
|
| 22 |
+
annotation.attempt_index attempt (1-based) the frame belongs to
|
| 23 |
+
annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`)
|
| 24 |
+
annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action)
|
| 25 |
+
annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt
|
| 26 |
+
annotation.task_event number of task-monitor events (error / progress events) registered at this step
|
| 27 |
+
Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table),
|
| 28 |
+
runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state
|
| 29 |
+
per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/.
|
| 30 |
+
"""
|
| 31 |
+
import argparse
|
| 32 |
+
import glob
|
| 33 |
+
import json
|
| 34 |
+
import os
|
| 35 |
+
import re
|
| 36 |
+
import shutil
|
| 37 |
+
import time
|
| 38 |
+
|
| 39 |
+
import numpy as np
|
| 40 |
+
|
| 41 |
+
FPS = 20
|
| 42 |
+
RES = 256
|
| 43 |
+
BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke",
|
| 44 |
+
"cc_smoke", "cc_opus_smoke"]
|
| 45 |
+
BATCH_NOTES = {
|
| 46 |
+
"cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog",
|
| 47 |
+
"cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267",
|
| 48 |
+
"cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299",
|
| 49 |
+
"cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances",
|
| 50 |
+
"cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)",
|
| 51 |
+
"cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the "
|
| 52 |
+
"with-history continuation of failed runs is incomplete",
|
| 53 |
+
"cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early",
|
| 54 |
+
"cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt",
|
| 55 |
+
"cc_opus_smoke": "smoke test: single attempt",
|
| 56 |
+
}
|
| 57 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 58 |
+
CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)",
|
| 59 |
+
"L2": "disturbed state to restore (incl. damage the agent causes)",
|
| 60 |
+
"L3": "infeasible manipulation strategy (grasp / contact / tool must change)",
|
| 61 |
+
"L4": "misjudged geometry (size, shape, fit, hidden structure)",
|
| 62 |
+
"L5": "misjudged physics (mass distribution, friction, dynamics)"}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def features():
|
| 66 |
+
vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]}
|
| 67 |
+
f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names}
|
| 68 |
+
i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None}
|
| 69 |
+
return {
|
| 70 |
+
"observation.images.image": vid(),
|
| 71 |
+
"observation.images.wrist_image": vid(),
|
| 72 |
+
"observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z",
|
| 73 |
+
"finger_qpos_left", "finger_qpos_right"]),
|
| 74 |
+
"observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 75 |
+
"observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 76 |
+
"observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]),
|
| 77 |
+
"observation.gripper_width": f32(1, ["width_m"]),
|
| 78 |
+
"action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y",
|
| 79 |
+
"eef_delta_rot_aa_z", "gripper_close"]),
|
| 80 |
+
"annotation.attempt_index": i64(),
|
| 81 |
+
"annotation.command_index": i64(),
|
| 82 |
+
"annotation.phase": i64(),
|
| 83 |
+
"annotation.attempt_success": i64(),
|
| 84 |
+
"annotation.task_event": i64(),
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ------------------------------------------------------------------------------------------------ paper metadata
|
| 89 |
+
|
| 90 |
+
def _clean_tex(s):
|
| 91 |
+
s = re.sub(r"%.*", "", s)
|
| 92 |
+
for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"),
|
| 93 |
+
(r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"),
|
| 94 |
+
(r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"),
|
| 95 |
+
(r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"),
|
| 96 |
+
(r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]:
|
| 97 |
+
s = re.sub(a, b, s)
|
| 98 |
+
s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s)
|
| 99 |
+
s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s)
|
| 100 |
+
for _ in range(3):
|
| 101 |
+
s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s)
|
| 102 |
+
s = re.sub(r"\$([^$]*)\$", r"\1", s)
|
| 103 |
+
s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ")
|
| 104 |
+
s = re.sub(r"\{([^{}]*)\}", r"\1", s)
|
| 105 |
+
s = re.sub(r"\\[a-zA-Z]+\*?", "", s)
|
| 106 |
+
return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def paper_tasks(paper_dir):
|
| 110 |
+
"""{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the
|
| 111 |
+
paper's task table and task appendix (empty if the paper sources are not there)."""
|
| 112 |
+
out = {}
|
| 113 |
+
if not paper_dir:
|
| 114 |
+
return out
|
| 115 |
+
app = os.path.join(paper_dir, "sections", "appendix_tasks.tex")
|
| 116 |
+
tab = os.path.join(paper_dir, "sections", "tab_tasks.tex")
|
| 117 |
+
if os.path.exists(app):
|
| 118 |
+
txt = open(app).read()
|
| 119 |
+
parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt)
|
| 120 |
+
for i in range(1, len(parts) - 1, 2):
|
| 121 |
+
if parts[i] != "\\paragraph{":
|
| 122 |
+
continue
|
| 123 |
+
body = parts[i + 1]
|
| 124 |
+
m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S)
|
| 125 |
+
if not m:
|
| 126 |
+
continue
|
| 127 |
+
name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip()
|
| 128 |
+
desc = _clean_tex(body[m.end():])
|
| 129 |
+
out[code] = dict(name=name, cause=_clean_tex(cause), description=desc)
|
| 130 |
+
if os.path.exists(tab):
|
| 131 |
+
names = {v["name"].lower(): k for k, v in out.items()}
|
| 132 |
+
for line in open(tab):
|
| 133 |
+
cells = [c.strip() for c in line.split("&")]
|
| 134 |
+
if len(cells) != 6 or not cells[-1].endswith("\\\\"):
|
| 135 |
+
continue
|
| 136 |
+
nm = re.sub(r"\\contscene", "", cells[0]).strip().lower()
|
| 137 |
+
code = names.get(nm)
|
| 138 |
+
if not code:
|
| 139 |
+
continue
|
| 140 |
+
out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]),
|
| 141 |
+
repair_within_attempt=_clean_tex(cells[3]) == "yes",
|
| 142 |
+
oracle_first_attempt_pct=_clean_tex(cells[4]),
|
| 143 |
+
naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip()))
|
| 144 |
+
return out
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
# ------------------------------------------------------------------------------------------------ collection
|
| 148 |
+
|
| 149 |
+
def manifest_status(runs_root, batch, run, cache={}):
|
| 150 |
+
if batch not in cache:
|
| 151 |
+
p = os.path.join(runs_root, batch, "manifest.json")
|
| 152 |
+
cache[batch] = json.load(open(p)) if os.path.exists(p) else {}
|
| 153 |
+
m = cache[batch]
|
| 154 |
+
for r in m.get("runs", []):
|
| 155 |
+
if r.get("run") == run:
|
| 156 |
+
return r.get("status", "?"), r
|
| 157 |
+
for r in m.get("superseded", []):
|
| 158 |
+
if r.get("run") == run:
|
| 159 |
+
return "superseded_" + str(r.get("status", "?")), r
|
| 160 |
+
return "not_in_manifest", {}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def collect(raw_roots, runs_root, batches, task_order):
|
| 164 |
+
"""Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root."""
|
| 165 |
+
eps, rejected, seen = [], [], set()
|
| 166 |
+
for root in raw_roots:
|
| 167 |
+
for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))):
|
| 168 |
+
rep = json.load(open(rj))
|
| 169 |
+
batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"]
|
| 170 |
+
if (batches and batch not in batches) or (batch, run) in seen:
|
| 171 |
+
continue
|
| 172 |
+
seen.add((batch, run))
|
| 173 |
+
ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff")
|
| 174 |
+
status, entry = manifest_status(runs_root, batch, run)
|
| 175 |
+
if not ok:
|
| 176 |
+
never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked")
|
| 177 |
+
rejected.append(dict(run=run, batch=batch, run_status=status,
|
| 178 |
+
reason="run never started (no contract, no robot command)" if never else
|
| 179 |
+
"replay does not reproduce the log (the log has gaps or the replay diverged)",
|
| 180 |
+
detail=rep.get("first_mismatches")))
|
| 181 |
+
continue
|
| 182 |
+
for ep in rep.get("episodes", []):
|
| 183 |
+
d = os.path.join(root, ep["dir"])
|
| 184 |
+
ann = json.load(open(os.path.join(d, "annotation.json")))
|
| 185 |
+
judged = [a for a in ann["attempts"] if a.get("success") is not None]
|
| 186 |
+
if not judged or ep["n_frames"] == 0:
|
| 187 |
+
rejected.append(dict(run=run, batch=batch, episode=ep["dir"],
|
| 188 |
+
reason="no judged attempt" if not judged else "no frames"))
|
| 189 |
+
continue
|
| 190 |
+
ann["source"]["run_status"] = status
|
| 191 |
+
ann["source"]["manifest_id"] = entry.get("id")
|
| 192 |
+
ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"],
|
| 193 |
+
max_eef_dev_m=rep["max_eef_dev_m"])
|
| 194 |
+
key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99),
|
| 195 |
+
{"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2),
|
| 196 |
+
ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"])
|
| 197 |
+
eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann))
|
| 198 |
+
eps.sort(key=lambda x: x["key"])
|
| 199 |
+
return eps, rejected
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# ------------------------------------------------------------------------------------------------ writing
|
| 203 |
+
|
| 204 |
+
def frames_of(path):
|
| 205 |
+
import av
|
| 206 |
+
with av.open(path) as c:
|
| 207 |
+
for fr in c.decode(video=0):
|
| 208 |
+
yield fr.to_ndarray(format="rgb24")
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def flat_row(i, ann, n, idx0):
|
| 212 |
+
s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"]
|
| 213 |
+
att = ann["attempts"]
|
| 214 |
+
a0 = att[0]
|
| 215 |
+
return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n,
|
| 216 |
+
batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"],
|
| 217 |
+
memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"),
|
| 218 |
+
episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att],
|
| 219 |
+
harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"),
|
| 220 |
+
effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"),
|
| 221 |
+
task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"),
|
| 222 |
+
category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"],
|
| 223 |
+
success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att],
|
| 224 |
+
feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att],
|
| 225 |
+
auto_ended=[a.get("auto_ended") for a in att],
|
| 226 |
+
corrected_later_in_run=[a.get("corrected_later_in_run") for a in att],
|
| 227 |
+
error_event_in_attempt=[a.get("error_event_in_attempt") for a in att],
|
| 228 |
+
run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"),
|
| 229 |
+
n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]),
|
| 230 |
+
first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def cmd_plan(a):
|
| 234 |
+
task_order = {}
|
| 235 |
+
if a.task_set and os.path.exists(a.task_set):
|
| 236 |
+
for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")):
|
| 237 |
+
task_order[line.split(":")[0].strip()] = i
|
| 238 |
+
batches = [b for b in a.batches.split(",") if b] if a.batches else None
|
| 239 |
+
eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order)
|
| 240 |
+
if a.limit:
|
| 241 |
+
eps = eps[:a.limit]
|
| 242 |
+
paper = paper_tasks(a.paper)
|
| 243 |
+
idx0 = 0
|
| 244 |
+
for i, e in enumerate(eps):
|
| 245 |
+
ann = e["ann"]
|
| 246 |
+
tname = ann["task"]["name"]
|
| 247 |
+
if tname in paper:
|
| 248 |
+
ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"}
|
| 249 |
+
ann["episode_index"] = i
|
| 250 |
+
ann["dataset_index_range"] = [idx0, idx0 + e["n"]]
|
| 251 |
+
e["index"], e["from"] = i, idx0
|
| 252 |
+
idx0 += e["n"]
|
| 253 |
+
del e["key"]
|
| 254 |
+
os.makedirs(a.work, exist_ok=True)
|
| 255 |
+
with open(os.path.join(a.work, "plan.json"), "w") as f:
|
| 256 |
+
json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f,
|
| 257 |
+
ensure_ascii=False)
|
| 258 |
+
print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def shard_range(n_eps, i, k):
|
| 262 |
+
return (n_eps * i) // k, (n_eps * (i + 1)) // k
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def cmd_shard(a):
|
| 266 |
+
from lerobot.datasets.lerobot_dataset import LeRobotDataset
|
| 267 |
+
t0 = time.time()
|
| 268 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 269 |
+
eps = plan["episodes"]
|
| 270 |
+
lo, hi = shard_range(len(eps), a.shard, a.nshards)
|
| 271 |
+
out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}")
|
| 272 |
+
if os.path.exists(os.path.join(out, "DONE")):
|
| 273 |
+
print(f"shard {a.shard}: done already", flush=True)
|
| 274 |
+
return
|
| 275 |
+
shutil.rmtree(out, ignore_errors=True)
|
| 276 |
+
ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out,
|
| 277 |
+
robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads,
|
| 278 |
+
vcodec=a.vcodec)
|
| 279 |
+
nfr = 0
|
| 280 |
+
for e in eps[lo:hi]:
|
| 281 |
+
d, ann, n = e["dir"], e["ann"], e["n"]
|
| 282 |
+
fr = np.load(os.path.join(d, "frames.npz"))
|
| 283 |
+
assert len(fr["action"]) == n, d
|
| 284 |
+
succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]}
|
| 285 |
+
evc = np.zeros(n, np.int64)
|
| 286 |
+
for ev in ann["task_events"]:
|
| 287 |
+
if 0 <= ev["frame"] < n:
|
| 288 |
+
evc[ev["frame"]] += 1
|
| 289 |
+
state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32)
|
| 290 |
+
instr = ann["task"]["instruction"]
|
| 291 |
+
k = 0
|
| 292 |
+
for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))):
|
| 293 |
+
if k >= n:
|
| 294 |
+
break
|
| 295 |
+
ds.add_frame({
|
| 296 |
+
"observation.images.image": img, "observation.images.wrist_image": wr,
|
| 297 |
+
"observation.state": state[k],
|
| 298 |
+
"observation.joint_pos": fr["joint_pos"][k].astype(np.float32),
|
| 299 |
+
"observation.joint_vel": fr["joint_vel"][k].astype(np.float32),
|
| 300 |
+
"observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32),
|
| 301 |
+
"observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32),
|
| 302 |
+
"action": fr["action"][k].astype(np.float32),
|
| 303 |
+
"annotation.attempt_index": np.array([fr["attempt"][k]], np.int64),
|
| 304 |
+
"annotation.command_index": np.array([fr["command"][k]], np.int64),
|
| 305 |
+
"annotation.phase": np.array([fr["phase"][k]], np.int64),
|
| 306 |
+
"annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64),
|
| 307 |
+
"annotation.task_event": np.array([evc[k]], np.int64),
|
| 308 |
+
"task": instr,
|
| 309 |
+
})
|
| 310 |
+
k += 1
|
| 311 |
+
if k != n:
|
| 312 |
+
raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames")
|
| 313 |
+
ds.save_episode()
|
| 314 |
+
nfr += n
|
| 315 |
+
ds.finalize()
|
| 316 |
+
shutil.rmtree(os.path.join(out, "images"), ignore_errors=True)
|
| 317 |
+
open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n")
|
| 318 |
+
print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def cmd_merge(a):
|
| 322 |
+
from pathlib import Path
|
| 323 |
+
from lerobot.datasets.aggregate import aggregate_datasets
|
| 324 |
+
t0 = time.time()
|
| 325 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 326 |
+
eps = plan["episodes"]
|
| 327 |
+
roots, ids = [], []
|
| 328 |
+
for i in range(a.nshards):
|
| 329 |
+
lo, hi = shard_range(len(eps), i, a.nshards)
|
| 330 |
+
if hi <= lo:
|
| 331 |
+
continue
|
| 332 |
+
r = os.path.join(a.work, "shards", f"shard_{i:03d}")
|
| 333 |
+
if not os.path.exists(os.path.join(r, "DONE")):
|
| 334 |
+
raise SystemExit(f"shard {i} is not done")
|
| 335 |
+
roots.append(Path(r))
|
| 336 |
+
ids.append(f"{plan['repo_id']}-shard{i:03d}")
|
| 337 |
+
if os.path.exists(a.out):
|
| 338 |
+
raise SystemExit(f"{a.out} exists; refusing to overwrite")
|
| 339 |
+
aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out))
|
| 340 |
+
print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True)
|
| 341 |
+
write_sidecars(a, plan)
|
| 342 |
+
print(f"merge done in {time.time() - t0:.0f}s", flush=True)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def write_sidecars(a, plan):
|
| 346 |
+
eps, paper = plan["episodes"], plan["paper"]
|
| 347 |
+
lff = os.path.join(a.out, "lff")
|
| 348 |
+
for sub in ("annotations", "sim_state", "final", "code"):
|
| 349 |
+
os.makedirs(os.path.join(lff, sub), exist_ok=True)
|
| 350 |
+
rows, runs, tasks = [], {}, {}
|
| 351 |
+
for e in eps:
|
| 352 |
+
i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"]
|
| 353 |
+
name = f"episode_{i:06d}"
|
| 354 |
+
if os.path.exists(os.path.join(d, "sim_state.npy")):
|
| 355 |
+
shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy"))
|
| 356 |
+
shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz"))
|
| 357 |
+
for cam, key in (("agentview", "image"), ("wrist", "wrist_image")):
|
| 358 |
+
shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png"))
|
| 359 |
+
with open(os.path.join(lff, "annotations", name + ".json"), "w") as f:
|
| 360 |
+
json.dump(ann, f, indent=1, ensure_ascii=False)
|
| 361 |
+
rows.append(flat_row(i, ann, n, e["from"]))
|
| 362 |
+
tname = ann["task"]["name"]
|
| 363 |
+
rk = (ann["source"]["batch"], ann["source"]["run"])
|
| 364 |
+
r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"),
|
| 365 |
+
run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"],
|
| 366 |
+
memory_free_chain_of=ann["source"].get("memory_free_chain_of"),
|
| 367 |
+
memory_free_rep=ann["source"].get("memory_free_rep"), task=tname,
|
| 368 |
+
seed=ann["task"]["seed"], model=ann["agent"].get("model"),
|
| 369 |
+
harness=ann["agent"].get("harness"),
|
| 370 |
+
harness_version=ann["agent"].get("harness_version"),
|
| 371 |
+
codex_catalog=ann["agent"].get("codex_catalog"),
|
| 372 |
+
outcome_class=ann["run_outcome"].get("outcome_class"),
|
| 373 |
+
attempt_history=ann["run_outcome"].get("attempt_history"),
|
| 374 |
+
agent_final_report=ann["run_outcome"].get("agent_final_report"),
|
| 375 |
+
episodes=[]))
|
| 376 |
+
for x in ann["attempts"]:
|
| 377 |
+
r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success")))
|
| 378 |
+
if tname not in tasks:
|
| 379 |
+
tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")}
|
| 380 |
+
if tname in paper:
|
| 381 |
+
tasks[tname]["paper"] = paper[tname]
|
| 382 |
+
tasks[tname]["instances"] = {}
|
| 383 |
+
tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"]
|
| 384 |
+
# memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id)
|
| 385 |
+
by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")}
|
| 386 |
+
for r in runs.values():
|
| 387 |
+
if r.get("memory_free_chain_of"):
|
| 388 |
+
r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"]))
|
| 389 |
+
for (b, rn), r in runs.items():
|
| 390 |
+
r["memory_free_retries"] = sorted((x["run"] for x in runs.values()
|
| 391 |
+
if x["batch"] == b and x.get("memory_free_chain_of_run") == rn),
|
| 392 |
+
key=lambda q: runs[(b, q)].get("memory_free_rep") or 0)
|
| 393 |
+
with open(os.path.join(lff, "episodes.jsonl"), "w") as f:
|
| 394 |
+
for row in rows:
|
| 395 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 396 |
+
with open(os.path.join(lff, "runs.jsonl"), "w") as f:
|
| 397 |
+
for r in runs.values():
|
| 398 |
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 399 |
+
with open(os.path.join(lff, "tasks.json"), "w") as f:
|
| 400 |
+
json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False)
|
| 401 |
+
with open(os.path.join(lff, "batches.json"), "w") as f:
|
| 402 |
+
json.dump(BATCH_NOTES, f, indent=1)
|
| 403 |
+
with open(os.path.join(lff, "rejected.json"), "w") as f:
|
| 404 |
+
json.dump(plan["rejected"], f, indent=1)
|
| 405 |
+
here = os.path.dirname(os.path.abspath(__file__))
|
| 406 |
+
for s in ("lerobot_replay.py", "lerobot_export.py"):
|
| 407 |
+
shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s))
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def main():
|
| 411 |
+
ap = argparse.ArgumentParser()
|
| 412 |
+
ap.add_argument("step", choices=["plan", "shard", "merge"])
|
| 413 |
+
ap.add_argument("--work", required=True)
|
| 414 |
+
ap.add_argument("--raw", default="")
|
| 415 |
+
ap.add_argument("--runs-root", default="")
|
| 416 |
+
ap.add_argument("--out", default="")
|
| 417 |
+
ap.add_argument("--paper", default="")
|
| 418 |
+
ap.add_argument("--task-set", default="")
|
| 419 |
+
ap.add_argument("--repo-id", default="lffbench/agent-replays")
|
| 420 |
+
ap.add_argument("--batches", default="")
|
| 421 |
+
ap.add_argument("--limit", type=int, default=0)
|
| 422 |
+
ap.add_argument("--shard", type=int, default=0)
|
| 423 |
+
ap.add_argument("--nshards", type=int, default=1)
|
| 424 |
+
ap.add_argument("--threads", type=int, default=2)
|
| 425 |
+
ap.add_argument("--vcodec", default="libsvtav1")
|
| 426 |
+
a = ap.parse_args()
|
| 427 |
+
{"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
if __name__ == "__main__":
|
| 431 |
+
main()
|
leaf/code/v1.5/backfill-20261102-l4i_fx_test/lerobot_replay.py
ADDED
|
@@ -0,0 +1,744 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay
|
| 2 |
+
against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the
|
| 3 |
+
LeRobot export (scripts/lerobot_export.py).
|
| 4 |
+
|
| 5 |
+
python scripts/lerobot_replay.py check <run_dir> [<run_dir> ...] [--json out.json] # replay only, print fidelity
|
| 6 |
+
python scripts/lerobot_replay.py record <run_dir> --out <raw_root> [--res 256]
|
| 7 |
+
|
| 8 |
+
Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot
|
| 9 |
+
commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite
|
| 10 |
+
is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly
|
| 11 |
+
like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same
|
| 12 |
+
outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width,
|
| 13 |
+
ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code
|
| 14 |
+
hashes equal the current files are expected to match (check_code()).
|
| 15 |
+
|
| 16 |
+
Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB,
|
| 17 |
+
proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes:
|
| 18 |
+
protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode
|
| 19 |
+
per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the
|
| 20 |
+
fidelity check runs in record mode too. Per episode the recorder writes <raw_root>/<batch>/<run>/epNN/:
|
| 21 |
+
agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes)
|
| 22 |
+
frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase
|
| 23 |
+
sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel)
|
| 24 |
+
final_*.png, final.npz observation after the last control step (the state the outcome was judged in)
|
| 25 |
+
annotation.json episode annotation (build_annotation)
|
| 26 |
+
and <raw_root>/<batch>/<run>/replay.json (fidelity) when the whole run is done.
|
| 27 |
+
"""
|
| 28 |
+
import argparse
|
| 29 |
+
import ast
|
| 30 |
+
import hashlib
|
| 31 |
+
import importlib
|
| 32 |
+
import json
|
| 33 |
+
import math
|
| 34 |
+
import os
|
| 35 |
+
import pkgutil
|
| 36 |
+
import re
|
| 37 |
+
import shutil
|
| 38 |
+
import sys
|
| 39 |
+
import time
|
| 40 |
+
from collections import defaultdict
|
| 41 |
+
|
| 42 |
+
import numpy as np
|
| 43 |
+
|
| 44 |
+
LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 45 |
+
sys.path.insert(0, LFF_ROOT)
|
| 46 |
+
|
| 47 |
+
from lffbench import envs # noqa: E402
|
| 48 |
+
from lffbench import tasks as task_pkg # noqa: E402
|
| 49 |
+
from lffbench.agent import camera as C # noqa: E402
|
| 50 |
+
from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402
|
| 51 |
+
from lffbench.task_base import TASKS # noqa: E402
|
| 52 |
+
|
| 53 |
+
for _m in pkgutil.iter_modules(task_pkg.__path__):
|
| 54 |
+
importlib.import_module(f"lffbench.tasks.{_m.name}")
|
| 55 |
+
|
| 56 |
+
# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the
|
| 57 |
+
# task's outcome() check after `finish` (the arm holds still; not an agent action)
|
| 58 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 59 |
+
FPS = 20
|
| 60 |
+
SCHEMA = "lff-replay-1"
|
| 61 |
+
|
| 62 |
+
# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR"
|
| 63 |
+
ERROR_FLAGS = ("trap_fired", "recovered_in_attempt")
|
| 64 |
+
ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events",
|
| 65 |
+
"n_missed_strikes", "n_open_gripper_pushes")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def load_jsonl(p):
|
| 69 |
+
out = []
|
| 70 |
+
if not os.path.exists(p):
|
| 71 |
+
return out
|
| 72 |
+
with open(p) as f:
|
| 73 |
+
for line in f:
|
| 74 |
+
line = line.strip()
|
| 75 |
+
if line:
|
| 76 |
+
try:
|
| 77 |
+
out.append(json.loads(line))
|
| 78 |
+
except ValueError:
|
| 79 |
+
pass
|
| 80 |
+
return out
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def norm_json(o):
|
| 84 |
+
return json.loads(json.dumps(o, default=_json_default))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def sha256(p):
|
| 88 |
+
with open(p, "rb") as f:
|
| 89 |
+
return hashlib.sha256(f.read()).hexdigest()
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def check_code(run_dir):
|
| 93 |
+
"""[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract."""
|
| 94 |
+
p = os.path.join(run_dir, "contract.json")
|
| 95 |
+
if not os.path.exists(p):
|
| 96 |
+
return [("contract.json", None, None)]
|
| 97 |
+
files = json.load(open(p))["contract"].get("server_code_files", {})
|
| 98 |
+
bad = []
|
| 99 |
+
for f, h in files.items():
|
| 100 |
+
q = os.path.join(LFF_ROOT, f)
|
| 101 |
+
cur = sha256(q) if os.path.exists(q) else None
|
| 102 |
+
if cur != h:
|
| 103 |
+
bad.append((f, h, cur))
|
| 104 |
+
return bad
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def diff_json(a, b, path="", tol=0.0, out=None, limit=20):
|
| 108 |
+
"""Differences between two JSON values (numbers compared with an absolute tolerance)."""
|
| 109 |
+
out = [] if out is None else out
|
| 110 |
+
if len(out) >= limit:
|
| 111 |
+
return out
|
| 112 |
+
if isinstance(a, dict) and isinstance(b, dict):
|
| 113 |
+
for k in sorted(set(a) | set(b)):
|
| 114 |
+
if k not in a or k not in b:
|
| 115 |
+
out.append((f"{path}.{k}", a.get(k, "<missing>"), b.get(k, "<missing>")))
|
| 116 |
+
else:
|
| 117 |
+
diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit)
|
| 118 |
+
elif isinstance(a, list) and isinstance(b, list):
|
| 119 |
+
if len(a) != len(b):
|
| 120 |
+
out.append((path, f"len {len(a)}", f"len {len(b)}"))
|
| 121 |
+
else:
|
| 122 |
+
for i, (x, y) in enumerate(zip(a, b)):
|
| 123 |
+
diff_json(x, y, f"{path}[{i}]", tol, out, limit)
|
| 124 |
+
elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
|
| 125 |
+
if a != b:
|
| 126 |
+
out.append((path, a, b))
|
| 127 |
+
elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))):
|
| 128 |
+
out.append((path, a, b))
|
| 129 |
+
return out
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def error_event(o):
|
| 133 |
+
"""True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none."""
|
| 134 |
+
if not isinstance(o, dict):
|
| 135 |
+
return None
|
| 136 |
+
keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o]
|
| 137 |
+
if not keys:
|
| 138 |
+
return None
|
| 139 |
+
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)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# ====================================================================================================== logs -> notes
|
| 143 |
+
|
| 144 |
+
class RunLog:
|
| 145 |
+
"""Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's
|
| 146 |
+
narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition."""
|
| 147 |
+
|
| 148 |
+
def __init__(self, run_dir, manifest=None):
|
| 149 |
+
self.run_dir = os.path.abspath(run_dir.rstrip("/"))
|
| 150 |
+
self.run = os.path.basename(self.run_dir)
|
| 151 |
+
self.batch = os.path.basename(os.path.dirname(self.run_dir))
|
| 152 |
+
self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl"))
|
| 153 |
+
self.start = next(e for e in self.ev if e["ev"] == "session_start")
|
| 154 |
+
self.calls, self.dones, self.harness_status = {}, [], []
|
| 155 |
+
last = None
|
| 156 |
+
for e in self.ev:
|
| 157 |
+
if e["ev"] == "call":
|
| 158 |
+
self.calls[(int(e["attempt"]), int(e["step"]))] = e
|
| 159 |
+
last = e
|
| 160 |
+
elif e["ev"] == "done":
|
| 161 |
+
self.dones.append(e)
|
| 162 |
+
last = e
|
| 163 |
+
elif e["ev"] == "http" and last is not None and "think_s" not in last:
|
| 164 |
+
ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \
|
| 165 |
+
(last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe"))
|
| 166 |
+
if ok:
|
| 167 |
+
last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s")
|
| 168 |
+
self.manifest = manifest or {}
|
| 169 |
+
self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {}
|
| 170 |
+
p = os.path.join(self.run_dir, "harness.json")
|
| 171 |
+
self.harness = json.load(open(p)) if os.path.exists(p) else {}
|
| 172 |
+
self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl"))
|
| 173 |
+
self._narration()
|
| 174 |
+
|
| 175 |
+
# ---------------------------------------------------------------- agent narration
|
| 176 |
+
def _narration(self):
|
| 177 |
+
"""notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one;
|
| 178 |
+
finish_notes[attempt] likewise for the agent's finish call; final_report = its last message."""
|
| 179 |
+
self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", []
|
| 180 |
+
buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
|
| 181 |
+
attempt = 1
|
| 182 |
+
|
| 183 |
+
def take():
|
| 184 |
+
nonlocal buf
|
| 185 |
+
out = {k: v for k, v in buf.items() if v}
|
| 186 |
+
buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
|
| 187 |
+
return out
|
| 188 |
+
|
| 189 |
+
last_msg = ""
|
| 190 |
+
for t in self.traj:
|
| 191 |
+
if t.get("kind") == "header":
|
| 192 |
+
self.headers.append(t.get("agent") or {})
|
| 193 |
+
continue
|
| 194 |
+
if t.get("kind") != "step":
|
| 195 |
+
continue
|
| 196 |
+
if (t.get("message") or "").strip():
|
| 197 |
+
buf["messages"].append(t["message"].strip())
|
| 198 |
+
last_msg = t["message"].strip()
|
| 199 |
+
if (t.get("reasoning_content") or "").strip():
|
| 200 |
+
buf["reasoning"].append(t["reasoning_content"].strip())
|
| 201 |
+
res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])}
|
| 202 |
+
for c in t.get("tool_calls") or []:
|
| 203 |
+
fn, args = c.get("function_name"), c.get("arguments") or {}
|
| 204 |
+
if fn == "shell":
|
| 205 |
+
buf["shell"].append(str(args.get("command", ""))[:2000])
|
| 206 |
+
elif fn == "view_images":
|
| 207 |
+
buf["viewed"].extend(args.get("paths") or [])
|
| 208 |
+
elif fn == "robot":
|
| 209 |
+
cmd = str(args.get("command", "")).strip()
|
| 210 |
+
r = res.get(c.get("tool_call_id")) or {}
|
| 211 |
+
try:
|
| 212 |
+
rep = json.loads(r.get("content") or "{}")
|
| 213 |
+
except ValueError:
|
| 214 |
+
rep = {}
|
| 215 |
+
word = cmd.split()[0] if cmd else ""
|
| 216 |
+
m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", "")))
|
| 217 |
+
if word in ("move_eef", "observe") and m:
|
| 218 |
+
a, s = int(m.group(1)), int(m.group(2))
|
| 219 |
+
n = take()
|
| 220 |
+
n["command"] = cmd
|
| 221 |
+
self.notes[(a, s)] = n
|
| 222 |
+
attempt = a
|
| 223 |
+
elif word in ("finish", "done"):
|
| 224 |
+
n = take()
|
| 225 |
+
n["command"] = cmd
|
| 226 |
+
n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)}
|
| 227 |
+
self.finish_notes.setdefault(attempt, n)
|
| 228 |
+
if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"):
|
| 229 |
+
attempt += 1
|
| 230 |
+
# status / help / errors: their narration stays in the buffer for the next command
|
| 231 |
+
self.final_report = last_msg
|
| 232 |
+
|
| 233 |
+
# ---------------------------------------------------------------- run-level labels
|
| 234 |
+
def attempts(self):
|
| 235 |
+
out = []
|
| 236 |
+
for e in self.dones:
|
| 237 |
+
o = e.get("outcome") or {}
|
| 238 |
+
if isinstance(o, str):
|
| 239 |
+
try:
|
| 240 |
+
o = ast.literal_eval(o)
|
| 241 |
+
except (ValueError, SyntaxError):
|
| 242 |
+
o = {}
|
| 243 |
+
out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o,
|
| 244 |
+
reason=e.get("reason") or ""))
|
| 245 |
+
return sorted(out, key=lambda x: x["attempt"])
|
| 246 |
+
|
| 247 |
+
def condition(self):
|
| 248 |
+
s, en = self.start, self.entry
|
| 249 |
+
mem = s.get("memory", en.get("mem"))
|
| 250 |
+
chain = en.get("chain")
|
| 251 |
+
if mem == "full":
|
| 252 |
+
cond = "with_history"
|
| 253 |
+
elif chain:
|
| 254 |
+
cond = "memory_free_retry"
|
| 255 |
+
else:
|
| 256 |
+
cond = "independent_single_attempt"
|
| 257 |
+
return cond, chain
|
| 258 |
+
|
| 259 |
+
def outcome_class(self):
|
| 260 |
+
"""CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None."""
|
| 261 |
+
att = self.attempts()
|
| 262 |
+
if not att or self.start.get("memory") != "full":
|
| 263 |
+
return None, "".join("S" if a["success"] else "F" for a in att)
|
| 264 |
+
hist = "".join("S" if a["success"] else "F" for a in att)
|
| 265 |
+
if att[0]["success"]:
|
| 266 |
+
ev = error_event(att[0]["outcome"])
|
| 267 |
+
cls = "S?" if ev is None else ("IR" if ev else "CS")
|
| 268 |
+
else:
|
| 269 |
+
cls = "XR" if any(a["success"] for a in att) else "F"
|
| 270 |
+
return cls, hist
|
| 271 |
+
|
| 272 |
+
def agent_info(self):
|
| 273 |
+
h, en = self.harness, self.entry
|
| 274 |
+
hdr = self.headers[0] if self.headers else {}
|
| 275 |
+
return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"),
|
| 276 |
+
harness_version=h.get("version") or hdr.get("version"),
|
| 277 |
+
harness_binary_sha256=(h.get("binary") or {}).get("sha256"),
|
| 278 |
+
model=h.get("model") or en.get("model") or hdr.get("model_name"),
|
| 279 |
+
effort=h.get("effort") or en.get("effort") or hdr.get("effort"),
|
| 280 |
+
provider=h.get("provider") or en.get("provider"),
|
| 281 |
+
codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"),
|
| 282 |
+
jail=en.get("jail"))
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
# ====================================================================================================== recording
|
| 286 |
+
|
| 287 |
+
class EpisodeSink:
|
| 288 |
+
"""Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed."""
|
| 289 |
+
|
| 290 |
+
def __init__(self, path):
|
| 291 |
+
self.path = path
|
| 292 |
+
os.makedirs(path, exist_ok=True)
|
| 293 |
+
self.w = None
|
| 294 |
+
self.num = defaultdict(list)
|
| 295 |
+
self.n = 0
|
| 296 |
+
|
| 297 |
+
def add(self, st, imgs):
|
| 298 |
+
import imageio
|
| 299 |
+
if self.w is None:
|
| 300 |
+
self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb",
|
| 301 |
+
pixelformat="rgb24", macro_block_size=1,
|
| 302 |
+
ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error")
|
| 303 |
+
for k in ("agentview", "wrist")]
|
| 304 |
+
for w, im in zip(self.w, imgs):
|
| 305 |
+
w.append_data(im)
|
| 306 |
+
for k, v in st.items():
|
| 307 |
+
self.num[k].append(v)
|
| 308 |
+
self.n += 1
|
| 309 |
+
|
| 310 |
+
def close(self, final_state, final_imgs):
|
| 311 |
+
from PIL import Image
|
| 312 |
+
if self.w is not None:
|
| 313 |
+
for w in self.w:
|
| 314 |
+
w.close()
|
| 315 |
+
arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"}
|
| 316 |
+
np.savez(os.path.join(self.path, "frames.npz"), **arr)
|
| 317 |
+
if self.num.get("sim_state"):
|
| 318 |
+
np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64))
|
| 319 |
+
np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()})
|
| 320 |
+
for k, im in zip(("agentview", "wrist"), final_imgs):
|
| 321 |
+
Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png"))
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
class Recorder:
|
| 325 |
+
"""Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink."""
|
| 326 |
+
|
| 327 |
+
def __init__(self, rp, res):
|
| 328 |
+
self.rp, self.res = rp, int(res)
|
| 329 |
+
self.active = False
|
| 330 |
+
self.sink = None
|
| 331 |
+
self.cur = dict(attempt=1, command=-1, phase=PHASES["move"])
|
| 332 |
+
env = rp.task.env
|
| 333 |
+
self.env, self.rob = env, env.robots[0]
|
| 334 |
+
self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist"))
|
| 335 |
+
orig = env.step
|
| 336 |
+
|
| 337 |
+
def step(a):
|
| 338 |
+
if self.active and self.sink is not None:
|
| 339 |
+
self.capture(np.asarray(a, np.float64))
|
| 340 |
+
out = orig(a)
|
| 341 |
+
if self.active and self.sink is not None:
|
| 342 |
+
self.rp.poll_events(self.sink.n - 1)
|
| 343 |
+
return out
|
| 344 |
+
|
| 345 |
+
env.step = step
|
| 346 |
+
|
| 347 |
+
@property
|
| 348 |
+
def n(self):
|
| 349 |
+
return self.sink.n if self.sink is not None else 0
|
| 350 |
+
|
| 351 |
+
def state(self):
|
| 352 |
+
import robosuite.utils.transform_utils as T
|
| 353 |
+
env, rob = self.env, self.rob
|
| 354 |
+
d = env.sim.data
|
| 355 |
+
eef = np.array(d.site_xpos[rob.eef_site_id], np.float64)
|
| 356 |
+
q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw")
|
| 357 |
+
gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64)
|
| 358 |
+
try:
|
| 359 |
+
flat = np.asarray(env.sim.get_state().flatten(), np.float64)
|
| 360 |
+
except Exception:
|
| 361 |
+
flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64)
|
| 362 |
+
sk = self.rp.task.sk
|
| 363 |
+
return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64),
|
| 364 |
+
gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64),
|
| 365 |
+
joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64),
|
| 366 |
+
gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64),
|
| 367 |
+
eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)),
|
| 368 |
+
sim_time=np.float64(d.time), sim_state=flat)
|
| 369 |
+
|
| 370 |
+
def images(self):
|
| 371 |
+
return [envs.render(self.env, c, self.res) for c in self.cams]
|
| 372 |
+
|
| 373 |
+
def capture(self, a):
|
| 374 |
+
st = self.state()
|
| 375 |
+
st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]),
|
| 376 |
+
phase=np.int64(self.cur["phase"]))
|
| 377 |
+
self.sink.add(st, self.images())
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
class RunReplay:
|
| 381 |
+
def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None):
|
| 382 |
+
self.run_dir = os.path.abspath(run_dir.rstrip("/"))
|
| 383 |
+
self.run_name = os.path.basename(self.run_dir)
|
| 384 |
+
self.log = RunLog(self.run_dir, manifest)
|
| 385 |
+
self.ev = self.log.ev
|
| 386 |
+
self.start = self.log.start
|
| 387 |
+
cp = os.path.join(self.run_dir, "contract.json")
|
| 388 |
+
self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {}
|
| 389 |
+
spec = self.contract.get("image_spec") or {}
|
| 390 |
+
self.image_res = int(spec.get("width", 512))
|
| 391 |
+
self.code_diff = check_code(self.run_dir)
|
| 392 |
+
s = self.start
|
| 393 |
+
self.task = TASKS[s["task"]](cam_res=self.image_res)
|
| 394 |
+
inst = self.task.sample_instance(s["seed"])
|
| 395 |
+
logged = s.get("inst") or {}
|
| 396 |
+
sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")})
|
| 397 |
+
self.inst_diff = diff_json(sampled, logged, "inst")
|
| 398 |
+
if s.get("arm", "none") not in (None, "none") or logged.get("nominal"):
|
| 399 |
+
inst.update(logged) # controlled arms / nominal: the server overrode these instance fields
|
| 400 |
+
self.inst_diff = []
|
| 401 |
+
self.inst = inst
|
| 402 |
+
self.protocol = getattr(self.task, "protocol", "cross")
|
| 403 |
+
self.k = int(s.get("k") or self.task.max_attempts)
|
| 404 |
+
self.attempt = 1
|
| 405 |
+
self.mismatch = [] # (where, what, logged, replayed)
|
| 406 |
+
self.n_checked = 0
|
| 407 |
+
self.max_dev_m = 0.0
|
| 408 |
+
self.unfinished = None
|
| 409 |
+
self.rec = Recorder(self, res) if record else None
|
| 410 |
+
self.res = int(res)
|
| 411 |
+
self.out_root = out_root
|
| 412 |
+
self.n_mon = 0
|
| 413 |
+
self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0
|
| 414 |
+
self.episodes = [] # summaries of the written episodes
|
| 415 |
+
self.task.reset_instance(self.inst)
|
| 416 |
+
self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
|
| 417 |
+
sim = self.task.env.sim
|
| 418 |
+
bid = sim.model.body_name2id("robot0_base")
|
| 419 |
+
self.base_off = np.array(sim.data.body_xpos[bid], float).copy()
|
| 420 |
+
if self.rec:
|
| 421 |
+
self._open_episode()
|
| 422 |
+
|
| 423 |
+
# ------------------------------------------------------------------ episodes
|
| 424 |
+
def _ep_dir(self):
|
| 425 |
+
return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}")
|
| 426 |
+
|
| 427 |
+
def _open_episode(self):
|
| 428 |
+
self.rec.sink = EpisodeSink(self._ep_dir())
|
| 429 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
|
| 430 |
+
self.rec.active = True
|
| 431 |
+
self.events, self.spans, self.ep_attempts = [], [], []
|
| 432 |
+
self.ep_initial = self.rec.state() # state right after the reset (before frame 0)
|
| 433 |
+
|
| 434 |
+
def close_episode(self):
|
| 435 |
+
if not self.rec:
|
| 436 |
+
self.ep_attempts = []
|
| 437 |
+
return
|
| 438 |
+
sink = self.rec.sink
|
| 439 |
+
st = self.rec.state()
|
| 440 |
+
imgs = self.rec.images()
|
| 441 |
+
st.pop("sim_state", None)
|
| 442 |
+
sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs)
|
| 443 |
+
ann = build_annotation(self, sink)
|
| 444 |
+
with open(os.path.join(sink.path, "annotation.json"), "w") as f:
|
| 445 |
+
json.dump(ann, f, indent=1, default=_json_default)
|
| 446 |
+
self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n,
|
| 447 |
+
attempts=[a["attempt"] for a in self.ep_attempts]))
|
| 448 |
+
self.rec.active = False
|
| 449 |
+
self.rec.sink = None
|
| 450 |
+
self.ep_index += 1
|
| 451 |
+
|
| 452 |
+
# ------------------------------------------------------------------ monitor events (task-side error events)
|
| 453 |
+
def poll_events(self, frame):
|
| 454 |
+
mon = getattr(self.task, "mon", None)
|
| 455 |
+
evs = mon.get("events") if isinstance(mon, dict) else None
|
| 456 |
+
if not isinstance(evs, list):
|
| 457 |
+
return
|
| 458 |
+
if len(evs) < self.n_mon: # monitor was rebuilt
|
| 459 |
+
self.n_mon = 0
|
| 460 |
+
for e in evs[self.n_mon:]:
|
| 461 |
+
self.events.append(dict(frame=int(frame), attempt=self.attempt,
|
| 462 |
+
event=norm_json(e) if isinstance(e, dict) else str(e)))
|
| 463 |
+
self.n_mon = len(evs)
|
| 464 |
+
|
| 465 |
+
# ------------------------------------------------------------------ state as the server reports it
|
| 466 |
+
def proprio_la(self):
|
| 467 |
+
p = self.ex.proprio()
|
| 468 |
+
pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off]
|
| 469 |
+
return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"])
|
| 470 |
+
|
| 471 |
+
def compare(self, where, rep_logged, rep):
|
| 472 |
+
self.n_checked += 1
|
| 473 |
+
for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"):
|
| 474 |
+
if k not in rep_logged or k not in rep:
|
| 475 |
+
continue
|
| 476 |
+
a, b = rep_logged[k], rep[k]
|
| 477 |
+
if k == "eef_pos":
|
| 478 |
+
dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float))))
|
| 479 |
+
self.max_dev_m = max(self.max_dev_m, dev)
|
| 480 |
+
if dev > 1.5e-4:
|
| 481 |
+
self.mismatch.append((where, k, a, b))
|
| 482 |
+
elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4):
|
| 483 |
+
self.mismatch.append((where, k, a, b))
|
| 484 |
+
if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)):
|
| 485 |
+
self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok")))
|
| 486 |
+
|
| 487 |
+
def _span(self, e, f0, kind):
|
| 488 |
+
if self.rec:
|
| 489 |
+
self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0,
|
| 490 |
+
frame_end=self.rec.n))
|
| 491 |
+
|
| 492 |
+
# ------------------------------------------------------------------ commands (robot_server._handle_v2)
|
| 493 |
+
def move_eef(self, e):
|
| 494 |
+
args = e.get("args") or {}
|
| 495 |
+
where = f"a{e['attempt']}s{e['step']}"
|
| 496 |
+
logged = e.get("report") or {}
|
| 497 |
+
f0 = self.rec.n if self.rec else 0
|
| 498 |
+
p = self.ex.proprio()
|
| 499 |
+
if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}:
|
| 500 |
+
self._span(e, f0, "error")
|
| 501 |
+
return self.compare(where, logged, dict(ok=False))
|
| 502 |
+
off = self.base_off
|
| 503 |
+
try:
|
| 504 |
+
cur = np.asarray(p["eef_pos"], float) - off
|
| 505 |
+
tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
|
| 506 |
+
yaw = float(args.get("yaw", p["eef_yaw_deg"]))
|
| 507 |
+
speed = None if args.get("speed") in (None, "") else float(args["speed"])
|
| 508 |
+
except (TypeError, ValueError):
|
| 509 |
+
self._span(e, f0, "error")
|
| 510 |
+
return self.compare(where, logged, dict(ok=False))
|
| 511 |
+
grip = args.get("gripper")
|
| 512 |
+
if grip not in (None, "open", "close"):
|
| 513 |
+
self._span(e, f0, "error")
|
| 514 |
+
return self.compare(where, logged, dict(ok=False))
|
| 515 |
+
moving = any(k in args for k in ("x", "y", "z", "yaw"))
|
| 516 |
+
tgt_w = np.asarray(tgt) + off
|
| 517 |
+
if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)):
|
| 518 |
+
self._span(e, f0, "rejected")
|
| 519 |
+
return self.compare(where, logged, dict(ok=False, **self.proprio_la()))
|
| 520 |
+
raw = {}
|
| 521 |
+
if self.rec:
|
| 522 |
+
self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"])
|
| 523 |
+
if moving:
|
| 524 |
+
mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw)
|
| 525 |
+
if speed is not None:
|
| 526 |
+
mv["speed"] = speed
|
| 527 |
+
raw.update(self.ex.call("move_to", mv).report)
|
| 528 |
+
if grip is not None:
|
| 529 |
+
if self.rec:
|
| 530 |
+
self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"])
|
| 531 |
+
raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report)
|
| 532 |
+
rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la())
|
| 533 |
+
self.compare(where, logged, rep)
|
| 534 |
+
lr = e.get("raw") or {}
|
| 535 |
+
for k in ("holding_object", "touched_object"):
|
| 536 |
+
if k in lr and k in raw and bool(lr[k]) != bool(raw[k]):
|
| 537 |
+
self.mismatch.append((where, "raw." + k, lr[k], raw[k]))
|
| 538 |
+
self._span(e, f0, "move_eef")
|
| 539 |
+
|
| 540 |
+
def observe(self, e):
|
| 541 |
+
f0 = self.rec.n if self.rec else 0
|
| 542 |
+
self._span(e, f0, "observe")
|
| 543 |
+
|
| 544 |
+
def done(self, e):
|
| 545 |
+
f0 = self.rec.n if self.rec else 0
|
| 546 |
+
if self.rec:
|
| 547 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"])
|
| 548 |
+
out = self.task.outcome(self.inst)
|
| 549 |
+
succ = bool(out["success"])
|
| 550 |
+
where = f"a{e['attempt']}done"
|
| 551 |
+
if succ != bool(e.get("success") in (True, "True")):
|
| 552 |
+
self.mismatch.append((where, "success", e.get("success"), succ))
|
| 553 |
+
lo = e.get("outcome") or {}
|
| 554 |
+
ro = norm_json({k: v for k, v in out.items() if k != "feedback"})
|
| 555 |
+
if isinstance(lo, dict):
|
| 556 |
+
for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8):
|
| 557 |
+
self.mismatch.append((where,) + d)
|
| 558 |
+
info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""),
|
| 559 |
+
feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")),
|
| 560 |
+
think_s=e.get("think_s"))
|
| 561 |
+
try:
|
| 562 |
+
info["feedback_f2"] = self.task.feedback(self.inst, out, "F2")
|
| 563 |
+
except Exception as ex_:
|
| 564 |
+
info["feedback_f2"] = f"<unavailable: {type(ex_).__name__}>"
|
| 565 |
+
if self.rec:
|
| 566 |
+
info["judge_frames"] = [f0, self.rec.n]
|
| 567 |
+
self.ep_attempts.append(info)
|
| 568 |
+
last = self.attempt >= self.k or succ or bool(out.get("terminal"))
|
| 569 |
+
if self.protocol == "cross" or last:
|
| 570 |
+
self.close_episode()
|
| 571 |
+
if last:
|
| 572 |
+
return True
|
| 573 |
+
self.attempt += 1
|
| 574 |
+
if self.protocol == "cross":
|
| 575 |
+
self.task.reset_instance(self.inst)
|
| 576 |
+
self.n_mon = 0
|
| 577 |
+
if self.rec:
|
| 578 |
+
self._open_episode()
|
| 579 |
+
elif self.rec:
|
| 580 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
|
| 581 |
+
self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
|
| 582 |
+
return False
|
| 583 |
+
|
| 584 |
+
def run(self):
|
| 585 |
+
t0 = time.time()
|
| 586 |
+
finished = False
|
| 587 |
+
for e in self.ev:
|
| 588 |
+
if e["ev"] == "call":
|
| 589 |
+
if e.get("cmd") == "move_eef":
|
| 590 |
+
self.move_eef(e)
|
| 591 |
+
elif e.get("cmd") == "observe":
|
| 592 |
+
self.observe(e)
|
| 593 |
+
else:
|
| 594 |
+
self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None))
|
| 595 |
+
elif e["ev"] == "done":
|
| 596 |
+
finished = self.done(e)
|
| 597 |
+
if finished:
|
| 598 |
+
break
|
| 599 |
+
self.unfinished = not finished
|
| 600 |
+
if not finished and self.rec and self.rec.sink is not None:
|
| 601 |
+
# the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged
|
| 602 |
+
if self.rec.n or self.ep_attempts:
|
| 603 |
+
self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True,
|
| 604 |
+
finish_reason="", feedback_shown="", auto_ended=False))
|
| 605 |
+
self.close_episode()
|
| 606 |
+
else:
|
| 607 |
+
shutil.rmtree(self.rec.sink.path, ignore_errors=True)
|
| 608 |
+
self.rec.sink = None
|
| 609 |
+
self.wall_s = time.time() - t0
|
| 610 |
+
return self
|
| 611 |
+
|
| 612 |
+
def summary(self):
|
| 613 |
+
return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"],
|
| 614 |
+
protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff),
|
| 615 |
+
n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6),
|
| 616 |
+
unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1),
|
| 617 |
+
first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]])
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
# ====================================================================================================== annotation
|
| 621 |
+
|
| 622 |
+
def task_info(task, inst):
|
| 623 |
+
cls = type(task)
|
| 624 |
+
return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable",
|
| 625 |
+
category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"),
|
| 626 |
+
max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)),
|
| 627 |
+
instruction=cls.instruction)
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
def build_annotation(rp, sink):
|
| 631 |
+
"""Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2
|
| 632 |
+
failure description), run-level outcome class, every robot command with its frame span and the agent's narration,
|
| 633 |
+
task-side error events with frame indices."""
|
| 634 |
+
log = rp.log
|
| 635 |
+
s = rp.start
|
| 636 |
+
cond, chain = log.condition()
|
| 637 |
+
cls, hist = log.outcome_class()
|
| 638 |
+
att_all = log.attempts()
|
| 639 |
+
attempts = []
|
| 640 |
+
for a in rp.ep_attempts:
|
| 641 |
+
a = dict(a)
|
| 642 |
+
n = a["attempt"]
|
| 643 |
+
later = [x for x in att_all if x["attempt"] > n]
|
| 644 |
+
a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later))
|
| 645 |
+
a["is_last_attempt_of_run"] = not later
|
| 646 |
+
fn = log.finish_notes.get(n)
|
| 647 |
+
if fn:
|
| 648 |
+
a["agent_finish"] = fn
|
| 649 |
+
a["error_event_in_attempt"] = error_event(a.get("outcome"))
|
| 650 |
+
attempts.append(a)
|
| 651 |
+
# post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command)
|
| 652 |
+
for a in attempts:
|
| 653 |
+
nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1])
|
| 654 |
+
if a.get("success") is False and nxt:
|
| 655 |
+
note = log.notes[nxt[0]]
|
| 656 |
+
a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note}
|
| 657 |
+
commands = []
|
| 658 |
+
for sp in rp.spans:
|
| 659 |
+
e = log.calls.get((sp["attempt"], sp["step"])) or {}
|
| 660 |
+
rep = e.get("report") or {}
|
| 661 |
+
c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"],
|
| 662 |
+
frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]),
|
| 663 |
+
args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"),
|
| 664 |
+
stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"),
|
| 665 |
+
gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"),
|
| 666 |
+
touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"),
|
| 667 |
+
agent_obs_images=rep.get("images"))
|
| 668 |
+
note = log.notes.get((sp["attempt"], sp["step"]))
|
| 669 |
+
if note:
|
| 670 |
+
c["agent_note"] = {k: v for k, v in note.items() if k != "command"}
|
| 671 |
+
commands.append(c)
|
| 672 |
+
t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x]
|
| 673 |
+
return dict(
|
| 674 |
+
schema=SCHEMA,
|
| 675 |
+
source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts],
|
| 676 |
+
episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain,
|
| 677 |
+
memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None),
|
| 678 |
+
feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"),
|
| 679 |
+
k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"),
|
| 680 |
+
contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256")
|
| 681 |
+
if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)),
|
| 682 |
+
agent=log.agent_info(),
|
| 683 |
+
task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"),
|
| 684 |
+
instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}),
|
| 685 |
+
run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all),
|
| 686 |
+
run_success=any(x["success"] for x in att_all) if att_all else None,
|
| 687 |
+
agent_final_report=log.final_report[:6000] or None,
|
| 688 |
+
mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)),
|
| 689 |
+
attempts=attempts,
|
| 690 |
+
commands=commands,
|
| 691 |
+
task_events=rp.events,
|
| 692 |
+
frames=dict(n=sink.n, fps=FPS, image_res=rp.res,
|
| 693 |
+
phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"],
|
| 694 |
+
joint_pos=rp.ep_initial["joint_pos"],
|
| 695 |
+
gripper_qpos=rp.ep_initial["gripper_qpos"])),
|
| 696 |
+
)
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
# ====================================================================================================== CLI
|
| 700 |
+
|
| 701 |
+
def load_manifest(run_dir):
|
| 702 |
+
p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json")
|
| 703 |
+
return json.load(open(p)) if os.path.exists(p) else {}
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
def main():
|
| 707 |
+
ap = argparse.ArgumentParser()
|
| 708 |
+
ap.add_argument("mode", choices=["check", "record"])
|
| 709 |
+
ap.add_argument("runs", nargs="+")
|
| 710 |
+
ap.add_argument("--json", default="")
|
| 711 |
+
ap.add_argument("--out", default="")
|
| 712 |
+
ap.add_argument("--res", type=int, default=256)
|
| 713 |
+
ap.add_argument("--force", action="store_true", help="record again even if replay.json exists")
|
| 714 |
+
a = ap.parse_args()
|
| 715 |
+
rows = []
|
| 716 |
+
for r in a.runs:
|
| 717 |
+
r = r.rstrip("/")
|
| 718 |
+
try:
|
| 719 |
+
if a.mode == "check":
|
| 720 |
+
s = RunReplay(r, manifest=load_manifest(r)).run().summary()
|
| 721 |
+
else:
|
| 722 |
+
batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r)
|
| 723 |
+
rd = os.path.join(a.out, batch, name)
|
| 724 |
+
if os.path.exists(os.path.join(rd, "replay.json")) and not a.force:
|
| 725 |
+
print(json.dumps(dict(run=name, skipped="exists")), flush=True)
|
| 726 |
+
continue
|
| 727 |
+
shutil.rmtree(rd, ignore_errors=True)
|
| 728 |
+
rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run()
|
| 729 |
+
s = rp.summary()
|
| 730 |
+
s["episodes"] = rp.episodes
|
| 731 |
+
with open(os.path.join(rd, "replay.json"), "w") as f:
|
| 732 |
+
json.dump(s, f, indent=1)
|
| 733 |
+
except Exception:
|
| 734 |
+
import traceback
|
| 735 |
+
s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:])
|
| 736 |
+
rows.append(s)
|
| 737 |
+
print(json.dumps(s), flush=True)
|
| 738 |
+
if a.json:
|
| 739 |
+
with open(a.json, "w") as f:
|
| 740 |
+
json.dump(rows, f, indent=1)
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
if __name__ == "__main__":
|
| 744 |
+
main()
|
leaf/code/v1.5/backfill-20261102-l4i_v_test/lerobot_export.py
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars.
|
| 2 |
+
|
| 3 |
+
Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding
|
| 4 |
+
can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan):
|
| 5 |
+
|
| 6 |
+
python scripts/lerobot_export.py plan --raw <raw_root>[,<raw_root2>] --runs-root <lffbench>/runs/api \
|
| 7 |
+
--paper <paper/latex> --task-set <lffbench>/sets/main_v2_1inst.txt --work <work_dir> [--batches ...] [--limit N]
|
| 8 |
+
python scripts/lerobot_export.py shard --work <work_dir> --shard i --nshards N
|
| 9 |
+
python scripts/lerobot_export.py merge --work <work_dir> --nshards N --out <dataset_root>
|
| 10 |
+
|
| 11 |
+
Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0
|
| 12 |
+
mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped.
|
| 13 |
+
|
| 14 |
+
LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t):
|
| 15 |
+
observation.images.image agentview RGB 256x256 (upright; LIBERO naming)
|
| 16 |
+
observation.images.wrist_image wrist (eye-in-hand) RGB 256x256
|
| 17 |
+
observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout)
|
| 18 |
+
observation.joint_pos / joint_vel 7 arm joints (rad, rad/s)
|
| 19 |
+
observation.eef_quat 4: xyzw; observation.gripper_width 1 (m)
|
| 20 |
+
action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad),
|
| 21 |
+
gripper (-1 open, +1 close)
|
| 22 |
+
annotation.attempt_index attempt (1-based) the frame belongs to
|
| 23 |
+
annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`)
|
| 24 |
+
annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action)
|
| 25 |
+
annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt
|
| 26 |
+
annotation.task_event number of task-monitor events (error / progress events) registered at this step
|
| 27 |
+
Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table),
|
| 28 |
+
runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state
|
| 29 |
+
per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/.
|
| 30 |
+
"""
|
| 31 |
+
import argparse
|
| 32 |
+
import glob
|
| 33 |
+
import json
|
| 34 |
+
import os
|
| 35 |
+
import re
|
| 36 |
+
import shutil
|
| 37 |
+
import time
|
| 38 |
+
|
| 39 |
+
import numpy as np
|
| 40 |
+
|
| 41 |
+
FPS = 20
|
| 42 |
+
RES = 256
|
| 43 |
+
BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke",
|
| 44 |
+
"cc_smoke", "cc_opus_smoke"]
|
| 45 |
+
BATCH_NOTES = {
|
| 46 |
+
"cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog",
|
| 47 |
+
"cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267",
|
| 48 |
+
"cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299",
|
| 49 |
+
"cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances",
|
| 50 |
+
"cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)",
|
| 51 |
+
"cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the "
|
| 52 |
+
"with-history continuation of failed runs is incomplete",
|
| 53 |
+
"cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early",
|
| 54 |
+
"cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt",
|
| 55 |
+
"cc_opus_smoke": "smoke test: single attempt",
|
| 56 |
+
}
|
| 57 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 58 |
+
CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)",
|
| 59 |
+
"L2": "disturbed state to restore (incl. damage the agent causes)",
|
| 60 |
+
"L3": "infeasible manipulation strategy (grasp / contact / tool must change)",
|
| 61 |
+
"L4": "misjudged geometry (size, shape, fit, hidden structure)",
|
| 62 |
+
"L5": "misjudged physics (mass distribution, friction, dynamics)"}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def features():
|
| 66 |
+
vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]}
|
| 67 |
+
f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names}
|
| 68 |
+
i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None}
|
| 69 |
+
return {
|
| 70 |
+
"observation.images.image": vid(),
|
| 71 |
+
"observation.images.wrist_image": vid(),
|
| 72 |
+
"observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z",
|
| 73 |
+
"finger_qpos_left", "finger_qpos_right"]),
|
| 74 |
+
"observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 75 |
+
"observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 76 |
+
"observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]),
|
| 77 |
+
"observation.gripper_width": f32(1, ["width_m"]),
|
| 78 |
+
"action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y",
|
| 79 |
+
"eef_delta_rot_aa_z", "gripper_close"]),
|
| 80 |
+
"annotation.attempt_index": i64(),
|
| 81 |
+
"annotation.command_index": i64(),
|
| 82 |
+
"annotation.phase": i64(),
|
| 83 |
+
"annotation.attempt_success": i64(),
|
| 84 |
+
"annotation.task_event": i64(),
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ------------------------------------------------------------------------------------------------ paper metadata
|
| 89 |
+
|
| 90 |
+
def _clean_tex(s):
|
| 91 |
+
s = re.sub(r"%.*", "", s)
|
| 92 |
+
for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"),
|
| 93 |
+
(r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"),
|
| 94 |
+
(r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"),
|
| 95 |
+
(r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"),
|
| 96 |
+
(r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]:
|
| 97 |
+
s = re.sub(a, b, s)
|
| 98 |
+
s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s)
|
| 99 |
+
s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s)
|
| 100 |
+
for _ in range(3):
|
| 101 |
+
s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s)
|
| 102 |
+
s = re.sub(r"\$([^$]*)\$", r"\1", s)
|
| 103 |
+
s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ")
|
| 104 |
+
s = re.sub(r"\{([^{}]*)\}", r"\1", s)
|
| 105 |
+
s = re.sub(r"\\[a-zA-Z]+\*?", "", s)
|
| 106 |
+
return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def paper_tasks(paper_dir):
|
| 110 |
+
"""{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the
|
| 111 |
+
paper's task table and task appendix (empty if the paper sources are not there)."""
|
| 112 |
+
out = {}
|
| 113 |
+
if not paper_dir:
|
| 114 |
+
return out
|
| 115 |
+
app = os.path.join(paper_dir, "sections", "appendix_tasks.tex")
|
| 116 |
+
tab = os.path.join(paper_dir, "sections", "tab_tasks.tex")
|
| 117 |
+
if os.path.exists(app):
|
| 118 |
+
txt = open(app).read()
|
| 119 |
+
parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt)
|
| 120 |
+
for i in range(1, len(parts) - 1, 2):
|
| 121 |
+
if parts[i] != "\\paragraph{":
|
| 122 |
+
continue
|
| 123 |
+
body = parts[i + 1]
|
| 124 |
+
m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S)
|
| 125 |
+
if not m:
|
| 126 |
+
continue
|
| 127 |
+
name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip()
|
| 128 |
+
desc = _clean_tex(body[m.end():])
|
| 129 |
+
out[code] = dict(name=name, cause=_clean_tex(cause), description=desc)
|
| 130 |
+
if os.path.exists(tab):
|
| 131 |
+
names = {v["name"].lower(): k for k, v in out.items()}
|
| 132 |
+
for line in open(tab):
|
| 133 |
+
cells = [c.strip() for c in line.split("&")]
|
| 134 |
+
if len(cells) != 6 or not cells[-1].endswith("\\\\"):
|
| 135 |
+
continue
|
| 136 |
+
nm = re.sub(r"\\contscene", "", cells[0]).strip().lower()
|
| 137 |
+
code = names.get(nm)
|
| 138 |
+
if not code:
|
| 139 |
+
continue
|
| 140 |
+
out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]),
|
| 141 |
+
repair_within_attempt=_clean_tex(cells[3]) == "yes",
|
| 142 |
+
oracle_first_attempt_pct=_clean_tex(cells[4]),
|
| 143 |
+
naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip()))
|
| 144 |
+
return out
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
# ------------------------------------------------------------------------------------------------ collection
|
| 148 |
+
|
| 149 |
+
def manifest_status(runs_root, batch, run, cache={}):
|
| 150 |
+
if batch not in cache:
|
| 151 |
+
p = os.path.join(runs_root, batch, "manifest.json")
|
| 152 |
+
cache[batch] = json.load(open(p)) if os.path.exists(p) else {}
|
| 153 |
+
m = cache[batch]
|
| 154 |
+
for r in m.get("runs", []):
|
| 155 |
+
if r.get("run") == run:
|
| 156 |
+
return r.get("status", "?"), r
|
| 157 |
+
for r in m.get("superseded", []):
|
| 158 |
+
if r.get("run") == run:
|
| 159 |
+
return "superseded_" + str(r.get("status", "?")), r
|
| 160 |
+
return "not_in_manifest", {}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def collect(raw_roots, runs_root, batches, task_order):
|
| 164 |
+
"""Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root."""
|
| 165 |
+
eps, rejected, seen = [], [], set()
|
| 166 |
+
for root in raw_roots:
|
| 167 |
+
for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))):
|
| 168 |
+
rep = json.load(open(rj))
|
| 169 |
+
batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"]
|
| 170 |
+
if (batches and batch not in batches) or (batch, run) in seen:
|
| 171 |
+
continue
|
| 172 |
+
seen.add((batch, run))
|
| 173 |
+
ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff")
|
| 174 |
+
status, entry = manifest_status(runs_root, batch, run)
|
| 175 |
+
if not ok:
|
| 176 |
+
never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked")
|
| 177 |
+
rejected.append(dict(run=run, batch=batch, run_status=status,
|
| 178 |
+
reason="run never started (no contract, no robot command)" if never else
|
| 179 |
+
"replay does not reproduce the log (the log has gaps or the replay diverged)",
|
| 180 |
+
detail=rep.get("first_mismatches")))
|
| 181 |
+
continue
|
| 182 |
+
for ep in rep.get("episodes", []):
|
| 183 |
+
d = os.path.join(root, ep["dir"])
|
| 184 |
+
ann = json.load(open(os.path.join(d, "annotation.json")))
|
| 185 |
+
judged = [a for a in ann["attempts"] if a.get("success") is not None]
|
| 186 |
+
if not judged or ep["n_frames"] == 0:
|
| 187 |
+
rejected.append(dict(run=run, batch=batch, episode=ep["dir"],
|
| 188 |
+
reason="no judged attempt" if not judged else "no frames"))
|
| 189 |
+
continue
|
| 190 |
+
ann["source"]["run_status"] = status
|
| 191 |
+
ann["source"]["manifest_id"] = entry.get("id")
|
| 192 |
+
ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"],
|
| 193 |
+
max_eef_dev_m=rep["max_eef_dev_m"])
|
| 194 |
+
key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99),
|
| 195 |
+
{"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2),
|
| 196 |
+
ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"])
|
| 197 |
+
eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann))
|
| 198 |
+
eps.sort(key=lambda x: x["key"])
|
| 199 |
+
return eps, rejected
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# ------------------------------------------------------------------------------------------------ writing
|
| 203 |
+
|
| 204 |
+
def frames_of(path):
|
| 205 |
+
import av
|
| 206 |
+
with av.open(path) as c:
|
| 207 |
+
for fr in c.decode(video=0):
|
| 208 |
+
yield fr.to_ndarray(format="rgb24")
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def flat_row(i, ann, n, idx0):
|
| 212 |
+
s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"]
|
| 213 |
+
att = ann["attempts"]
|
| 214 |
+
a0 = att[0]
|
| 215 |
+
return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n,
|
| 216 |
+
batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"],
|
| 217 |
+
memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"),
|
| 218 |
+
episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att],
|
| 219 |
+
harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"),
|
| 220 |
+
effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"),
|
| 221 |
+
task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"),
|
| 222 |
+
category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"],
|
| 223 |
+
success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att],
|
| 224 |
+
feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att],
|
| 225 |
+
auto_ended=[a.get("auto_ended") for a in att],
|
| 226 |
+
corrected_later_in_run=[a.get("corrected_later_in_run") for a in att],
|
| 227 |
+
error_event_in_attempt=[a.get("error_event_in_attempt") for a in att],
|
| 228 |
+
run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"),
|
| 229 |
+
n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]),
|
| 230 |
+
first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def cmd_plan(a):
|
| 234 |
+
task_order = {}
|
| 235 |
+
if a.task_set and os.path.exists(a.task_set):
|
| 236 |
+
for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")):
|
| 237 |
+
task_order[line.split(":")[0].strip()] = i
|
| 238 |
+
batches = [b for b in a.batches.split(",") if b] if a.batches else None
|
| 239 |
+
eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order)
|
| 240 |
+
if a.limit:
|
| 241 |
+
eps = eps[:a.limit]
|
| 242 |
+
paper = paper_tasks(a.paper)
|
| 243 |
+
idx0 = 0
|
| 244 |
+
for i, e in enumerate(eps):
|
| 245 |
+
ann = e["ann"]
|
| 246 |
+
tname = ann["task"]["name"]
|
| 247 |
+
if tname in paper:
|
| 248 |
+
ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"}
|
| 249 |
+
ann["episode_index"] = i
|
| 250 |
+
ann["dataset_index_range"] = [idx0, idx0 + e["n"]]
|
| 251 |
+
e["index"], e["from"] = i, idx0
|
| 252 |
+
idx0 += e["n"]
|
| 253 |
+
del e["key"]
|
| 254 |
+
os.makedirs(a.work, exist_ok=True)
|
| 255 |
+
with open(os.path.join(a.work, "plan.json"), "w") as f:
|
| 256 |
+
json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f,
|
| 257 |
+
ensure_ascii=False)
|
| 258 |
+
print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def shard_range(n_eps, i, k):
|
| 262 |
+
return (n_eps * i) // k, (n_eps * (i + 1)) // k
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def cmd_shard(a):
|
| 266 |
+
from lerobot.datasets.lerobot_dataset import LeRobotDataset
|
| 267 |
+
t0 = time.time()
|
| 268 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 269 |
+
eps = plan["episodes"]
|
| 270 |
+
lo, hi = shard_range(len(eps), a.shard, a.nshards)
|
| 271 |
+
out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}")
|
| 272 |
+
if os.path.exists(os.path.join(out, "DONE")):
|
| 273 |
+
print(f"shard {a.shard}: done already", flush=True)
|
| 274 |
+
return
|
| 275 |
+
shutil.rmtree(out, ignore_errors=True)
|
| 276 |
+
ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out,
|
| 277 |
+
robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads,
|
| 278 |
+
vcodec=a.vcodec)
|
| 279 |
+
nfr = 0
|
| 280 |
+
for e in eps[lo:hi]:
|
| 281 |
+
d, ann, n = e["dir"], e["ann"], e["n"]
|
| 282 |
+
fr = np.load(os.path.join(d, "frames.npz"))
|
| 283 |
+
assert len(fr["action"]) == n, d
|
| 284 |
+
succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]}
|
| 285 |
+
evc = np.zeros(n, np.int64)
|
| 286 |
+
for ev in ann["task_events"]:
|
| 287 |
+
if 0 <= ev["frame"] < n:
|
| 288 |
+
evc[ev["frame"]] += 1
|
| 289 |
+
state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32)
|
| 290 |
+
instr = ann["task"]["instruction"]
|
| 291 |
+
k = 0
|
| 292 |
+
for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))):
|
| 293 |
+
if k >= n:
|
| 294 |
+
break
|
| 295 |
+
ds.add_frame({
|
| 296 |
+
"observation.images.image": img, "observation.images.wrist_image": wr,
|
| 297 |
+
"observation.state": state[k],
|
| 298 |
+
"observation.joint_pos": fr["joint_pos"][k].astype(np.float32),
|
| 299 |
+
"observation.joint_vel": fr["joint_vel"][k].astype(np.float32),
|
| 300 |
+
"observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32),
|
| 301 |
+
"observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32),
|
| 302 |
+
"action": fr["action"][k].astype(np.float32),
|
| 303 |
+
"annotation.attempt_index": np.array([fr["attempt"][k]], np.int64),
|
| 304 |
+
"annotation.command_index": np.array([fr["command"][k]], np.int64),
|
| 305 |
+
"annotation.phase": np.array([fr["phase"][k]], np.int64),
|
| 306 |
+
"annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64),
|
| 307 |
+
"annotation.task_event": np.array([evc[k]], np.int64),
|
| 308 |
+
"task": instr,
|
| 309 |
+
})
|
| 310 |
+
k += 1
|
| 311 |
+
if k != n:
|
| 312 |
+
raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames")
|
| 313 |
+
ds.save_episode()
|
| 314 |
+
nfr += n
|
| 315 |
+
ds.finalize()
|
| 316 |
+
shutil.rmtree(os.path.join(out, "images"), ignore_errors=True)
|
| 317 |
+
open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n")
|
| 318 |
+
print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def cmd_merge(a):
|
| 322 |
+
from pathlib import Path
|
| 323 |
+
from lerobot.datasets.aggregate import aggregate_datasets
|
| 324 |
+
t0 = time.time()
|
| 325 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 326 |
+
eps = plan["episodes"]
|
| 327 |
+
roots, ids = [], []
|
| 328 |
+
for i in range(a.nshards):
|
| 329 |
+
lo, hi = shard_range(len(eps), i, a.nshards)
|
| 330 |
+
if hi <= lo:
|
| 331 |
+
continue
|
| 332 |
+
r = os.path.join(a.work, "shards", f"shard_{i:03d}")
|
| 333 |
+
if not os.path.exists(os.path.join(r, "DONE")):
|
| 334 |
+
raise SystemExit(f"shard {i} is not done")
|
| 335 |
+
roots.append(Path(r))
|
| 336 |
+
ids.append(f"{plan['repo_id']}-shard{i:03d}")
|
| 337 |
+
if os.path.exists(a.out):
|
| 338 |
+
raise SystemExit(f"{a.out} exists; refusing to overwrite")
|
| 339 |
+
aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out))
|
| 340 |
+
print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True)
|
| 341 |
+
write_sidecars(a, plan)
|
| 342 |
+
print(f"merge done in {time.time() - t0:.0f}s", flush=True)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def write_sidecars(a, plan):
|
| 346 |
+
eps, paper = plan["episodes"], plan["paper"]
|
| 347 |
+
lff = os.path.join(a.out, "lff")
|
| 348 |
+
for sub in ("annotations", "sim_state", "final", "code"):
|
| 349 |
+
os.makedirs(os.path.join(lff, sub), exist_ok=True)
|
| 350 |
+
rows, runs, tasks = [], {}, {}
|
| 351 |
+
for e in eps:
|
| 352 |
+
i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"]
|
| 353 |
+
name = f"episode_{i:06d}"
|
| 354 |
+
if os.path.exists(os.path.join(d, "sim_state.npy")):
|
| 355 |
+
shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy"))
|
| 356 |
+
shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz"))
|
| 357 |
+
for cam, key in (("agentview", "image"), ("wrist", "wrist_image")):
|
| 358 |
+
shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png"))
|
| 359 |
+
with open(os.path.join(lff, "annotations", name + ".json"), "w") as f:
|
| 360 |
+
json.dump(ann, f, indent=1, ensure_ascii=False)
|
| 361 |
+
rows.append(flat_row(i, ann, n, e["from"]))
|
| 362 |
+
tname = ann["task"]["name"]
|
| 363 |
+
rk = (ann["source"]["batch"], ann["source"]["run"])
|
| 364 |
+
r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"),
|
| 365 |
+
run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"],
|
| 366 |
+
memory_free_chain_of=ann["source"].get("memory_free_chain_of"),
|
| 367 |
+
memory_free_rep=ann["source"].get("memory_free_rep"), task=tname,
|
| 368 |
+
seed=ann["task"]["seed"], model=ann["agent"].get("model"),
|
| 369 |
+
harness=ann["agent"].get("harness"),
|
| 370 |
+
harness_version=ann["agent"].get("harness_version"),
|
| 371 |
+
codex_catalog=ann["agent"].get("codex_catalog"),
|
| 372 |
+
outcome_class=ann["run_outcome"].get("outcome_class"),
|
| 373 |
+
attempt_history=ann["run_outcome"].get("attempt_history"),
|
| 374 |
+
agent_final_report=ann["run_outcome"].get("agent_final_report"),
|
| 375 |
+
episodes=[]))
|
| 376 |
+
for x in ann["attempts"]:
|
| 377 |
+
r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success")))
|
| 378 |
+
if tname not in tasks:
|
| 379 |
+
tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")}
|
| 380 |
+
if tname in paper:
|
| 381 |
+
tasks[tname]["paper"] = paper[tname]
|
| 382 |
+
tasks[tname]["instances"] = {}
|
| 383 |
+
tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"]
|
| 384 |
+
# memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id)
|
| 385 |
+
by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")}
|
| 386 |
+
for r in runs.values():
|
| 387 |
+
if r.get("memory_free_chain_of"):
|
| 388 |
+
r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"]))
|
| 389 |
+
for (b, rn), r in runs.items():
|
| 390 |
+
r["memory_free_retries"] = sorted((x["run"] for x in runs.values()
|
| 391 |
+
if x["batch"] == b and x.get("memory_free_chain_of_run") == rn),
|
| 392 |
+
key=lambda q: runs[(b, q)].get("memory_free_rep") or 0)
|
| 393 |
+
with open(os.path.join(lff, "episodes.jsonl"), "w") as f:
|
| 394 |
+
for row in rows:
|
| 395 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 396 |
+
with open(os.path.join(lff, "runs.jsonl"), "w") as f:
|
| 397 |
+
for r in runs.values():
|
| 398 |
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 399 |
+
with open(os.path.join(lff, "tasks.json"), "w") as f:
|
| 400 |
+
json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False)
|
| 401 |
+
with open(os.path.join(lff, "batches.json"), "w") as f:
|
| 402 |
+
json.dump(BATCH_NOTES, f, indent=1)
|
| 403 |
+
with open(os.path.join(lff, "rejected.json"), "w") as f:
|
| 404 |
+
json.dump(plan["rejected"], f, indent=1)
|
| 405 |
+
here = os.path.dirname(os.path.abspath(__file__))
|
| 406 |
+
for s in ("lerobot_replay.py", "lerobot_export.py"):
|
| 407 |
+
shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s))
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def main():
|
| 411 |
+
ap = argparse.ArgumentParser()
|
| 412 |
+
ap.add_argument("step", choices=["plan", "shard", "merge"])
|
| 413 |
+
ap.add_argument("--work", required=True)
|
| 414 |
+
ap.add_argument("--raw", default="")
|
| 415 |
+
ap.add_argument("--runs-root", default="")
|
| 416 |
+
ap.add_argument("--out", default="")
|
| 417 |
+
ap.add_argument("--paper", default="")
|
| 418 |
+
ap.add_argument("--task-set", default="")
|
| 419 |
+
ap.add_argument("--repo-id", default="lffbench/agent-replays")
|
| 420 |
+
ap.add_argument("--batches", default="")
|
| 421 |
+
ap.add_argument("--limit", type=int, default=0)
|
| 422 |
+
ap.add_argument("--shard", type=int, default=0)
|
| 423 |
+
ap.add_argument("--nshards", type=int, default=1)
|
| 424 |
+
ap.add_argument("--threads", type=int, default=2)
|
| 425 |
+
ap.add_argument("--vcodec", default="libsvtav1")
|
| 426 |
+
a = ap.parse_args()
|
| 427 |
+
{"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
if __name__ == "__main__":
|
| 431 |
+
main()
|
leaf/code/v1.5/backfill-20261102-l4i_v_test/lerobot_replay.py
ADDED
|
@@ -0,0 +1,744 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay
|
| 2 |
+
against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the
|
| 3 |
+
LeRobot export (scripts/lerobot_export.py).
|
| 4 |
+
|
| 5 |
+
python scripts/lerobot_replay.py check <run_dir> [<run_dir> ...] [--json out.json] # replay only, print fidelity
|
| 6 |
+
python scripts/lerobot_replay.py record <run_dir> --out <raw_root> [--res 256]
|
| 7 |
+
|
| 8 |
+
Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot
|
| 9 |
+
commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite
|
| 10 |
+
is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly
|
| 11 |
+
like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same
|
| 12 |
+
outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width,
|
| 13 |
+
ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code
|
| 14 |
+
hashes equal the current files are expected to match (check_code()).
|
| 15 |
+
|
| 16 |
+
Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB,
|
| 17 |
+
proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes:
|
| 18 |
+
protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode
|
| 19 |
+
per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the
|
| 20 |
+
fidelity check runs in record mode too. Per episode the recorder writes <raw_root>/<batch>/<run>/epNN/:
|
| 21 |
+
agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes)
|
| 22 |
+
frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase
|
| 23 |
+
sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel)
|
| 24 |
+
final_*.png, final.npz observation after the last control step (the state the outcome was judged in)
|
| 25 |
+
annotation.json episode annotation (build_annotation)
|
| 26 |
+
and <raw_root>/<batch>/<run>/replay.json (fidelity) when the whole run is done.
|
| 27 |
+
"""
|
| 28 |
+
import argparse
|
| 29 |
+
import ast
|
| 30 |
+
import hashlib
|
| 31 |
+
import importlib
|
| 32 |
+
import json
|
| 33 |
+
import math
|
| 34 |
+
import os
|
| 35 |
+
import pkgutil
|
| 36 |
+
import re
|
| 37 |
+
import shutil
|
| 38 |
+
import sys
|
| 39 |
+
import time
|
| 40 |
+
from collections import defaultdict
|
| 41 |
+
|
| 42 |
+
import numpy as np
|
| 43 |
+
|
| 44 |
+
LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 45 |
+
sys.path.insert(0, LFF_ROOT)
|
| 46 |
+
|
| 47 |
+
from lffbench import envs # noqa: E402
|
| 48 |
+
from lffbench import tasks as task_pkg # noqa: E402
|
| 49 |
+
from lffbench.agent import camera as C # noqa: E402
|
| 50 |
+
from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402
|
| 51 |
+
from lffbench.task_base import TASKS # noqa: E402
|
| 52 |
+
|
| 53 |
+
for _m in pkgutil.iter_modules(task_pkg.__path__):
|
| 54 |
+
importlib.import_module(f"lffbench.tasks.{_m.name}")
|
| 55 |
+
|
| 56 |
+
# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the
|
| 57 |
+
# task's outcome() check after `finish` (the arm holds still; not an agent action)
|
| 58 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 59 |
+
FPS = 20
|
| 60 |
+
SCHEMA = "lff-replay-1"
|
| 61 |
+
|
| 62 |
+
# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR"
|
| 63 |
+
ERROR_FLAGS = ("trap_fired", "recovered_in_attempt")
|
| 64 |
+
ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events",
|
| 65 |
+
"n_missed_strikes", "n_open_gripper_pushes")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def load_jsonl(p):
|
| 69 |
+
out = []
|
| 70 |
+
if not os.path.exists(p):
|
| 71 |
+
return out
|
| 72 |
+
with open(p) as f:
|
| 73 |
+
for line in f:
|
| 74 |
+
line = line.strip()
|
| 75 |
+
if line:
|
| 76 |
+
try:
|
| 77 |
+
out.append(json.loads(line))
|
| 78 |
+
except ValueError:
|
| 79 |
+
pass
|
| 80 |
+
return out
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def norm_json(o):
|
| 84 |
+
return json.loads(json.dumps(o, default=_json_default))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def sha256(p):
|
| 88 |
+
with open(p, "rb") as f:
|
| 89 |
+
return hashlib.sha256(f.read()).hexdigest()
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def check_code(run_dir):
|
| 93 |
+
"""[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract."""
|
| 94 |
+
p = os.path.join(run_dir, "contract.json")
|
| 95 |
+
if not os.path.exists(p):
|
| 96 |
+
return [("contract.json", None, None)]
|
| 97 |
+
files = json.load(open(p))["contract"].get("server_code_files", {})
|
| 98 |
+
bad = []
|
| 99 |
+
for f, h in files.items():
|
| 100 |
+
q = os.path.join(LFF_ROOT, f)
|
| 101 |
+
cur = sha256(q) if os.path.exists(q) else None
|
| 102 |
+
if cur != h:
|
| 103 |
+
bad.append((f, h, cur))
|
| 104 |
+
return bad
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def diff_json(a, b, path="", tol=0.0, out=None, limit=20):
|
| 108 |
+
"""Differences between two JSON values (numbers compared with an absolute tolerance)."""
|
| 109 |
+
out = [] if out is None else out
|
| 110 |
+
if len(out) >= limit:
|
| 111 |
+
return out
|
| 112 |
+
if isinstance(a, dict) and isinstance(b, dict):
|
| 113 |
+
for k in sorted(set(a) | set(b)):
|
| 114 |
+
if k not in a or k not in b:
|
| 115 |
+
out.append((f"{path}.{k}", a.get(k, "<missing>"), b.get(k, "<missing>")))
|
| 116 |
+
else:
|
| 117 |
+
diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit)
|
| 118 |
+
elif isinstance(a, list) and isinstance(b, list):
|
| 119 |
+
if len(a) != len(b):
|
| 120 |
+
out.append((path, f"len {len(a)}", f"len {len(b)}"))
|
| 121 |
+
else:
|
| 122 |
+
for i, (x, y) in enumerate(zip(a, b)):
|
| 123 |
+
diff_json(x, y, f"{path}[{i}]", tol, out, limit)
|
| 124 |
+
elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
|
| 125 |
+
if a != b:
|
| 126 |
+
out.append((path, a, b))
|
| 127 |
+
elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))):
|
| 128 |
+
out.append((path, a, b))
|
| 129 |
+
return out
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def error_event(o):
|
| 133 |
+
"""True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none."""
|
| 134 |
+
if not isinstance(o, dict):
|
| 135 |
+
return None
|
| 136 |
+
keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o]
|
| 137 |
+
if not keys:
|
| 138 |
+
return None
|
| 139 |
+
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)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# ====================================================================================================== logs -> notes
|
| 143 |
+
|
| 144 |
+
class RunLog:
|
| 145 |
+
"""Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's
|
| 146 |
+
narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition."""
|
| 147 |
+
|
| 148 |
+
def __init__(self, run_dir, manifest=None):
|
| 149 |
+
self.run_dir = os.path.abspath(run_dir.rstrip("/"))
|
| 150 |
+
self.run = os.path.basename(self.run_dir)
|
| 151 |
+
self.batch = os.path.basename(os.path.dirname(self.run_dir))
|
| 152 |
+
self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl"))
|
| 153 |
+
self.start = next(e for e in self.ev if e["ev"] == "session_start")
|
| 154 |
+
self.calls, self.dones, self.harness_status = {}, [], []
|
| 155 |
+
last = None
|
| 156 |
+
for e in self.ev:
|
| 157 |
+
if e["ev"] == "call":
|
| 158 |
+
self.calls[(int(e["attempt"]), int(e["step"]))] = e
|
| 159 |
+
last = e
|
| 160 |
+
elif e["ev"] == "done":
|
| 161 |
+
self.dones.append(e)
|
| 162 |
+
last = e
|
| 163 |
+
elif e["ev"] == "http" and last is not None and "think_s" not in last:
|
| 164 |
+
ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \
|
| 165 |
+
(last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe"))
|
| 166 |
+
if ok:
|
| 167 |
+
last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s")
|
| 168 |
+
self.manifest = manifest or {}
|
| 169 |
+
self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {}
|
| 170 |
+
p = os.path.join(self.run_dir, "harness.json")
|
| 171 |
+
self.harness = json.load(open(p)) if os.path.exists(p) else {}
|
| 172 |
+
self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl"))
|
| 173 |
+
self._narration()
|
| 174 |
+
|
| 175 |
+
# ---------------------------------------------------------------- agent narration
|
| 176 |
+
def _narration(self):
|
| 177 |
+
"""notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one;
|
| 178 |
+
finish_notes[attempt] likewise for the agent's finish call; final_report = its last message."""
|
| 179 |
+
self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", []
|
| 180 |
+
buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
|
| 181 |
+
attempt = 1
|
| 182 |
+
|
| 183 |
+
def take():
|
| 184 |
+
nonlocal buf
|
| 185 |
+
out = {k: v for k, v in buf.items() if v}
|
| 186 |
+
buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
|
| 187 |
+
return out
|
| 188 |
+
|
| 189 |
+
last_msg = ""
|
| 190 |
+
for t in self.traj:
|
| 191 |
+
if t.get("kind") == "header":
|
| 192 |
+
self.headers.append(t.get("agent") or {})
|
| 193 |
+
continue
|
| 194 |
+
if t.get("kind") != "step":
|
| 195 |
+
continue
|
| 196 |
+
if (t.get("message") or "").strip():
|
| 197 |
+
buf["messages"].append(t["message"].strip())
|
| 198 |
+
last_msg = t["message"].strip()
|
| 199 |
+
if (t.get("reasoning_content") or "").strip():
|
| 200 |
+
buf["reasoning"].append(t["reasoning_content"].strip())
|
| 201 |
+
res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])}
|
| 202 |
+
for c in t.get("tool_calls") or []:
|
| 203 |
+
fn, args = c.get("function_name"), c.get("arguments") or {}
|
| 204 |
+
if fn == "shell":
|
| 205 |
+
buf["shell"].append(str(args.get("command", ""))[:2000])
|
| 206 |
+
elif fn == "view_images":
|
| 207 |
+
buf["viewed"].extend(args.get("paths") or [])
|
| 208 |
+
elif fn == "robot":
|
| 209 |
+
cmd = str(args.get("command", "")).strip()
|
| 210 |
+
r = res.get(c.get("tool_call_id")) or {}
|
| 211 |
+
try:
|
| 212 |
+
rep = json.loads(r.get("content") or "{}")
|
| 213 |
+
except ValueError:
|
| 214 |
+
rep = {}
|
| 215 |
+
word = cmd.split()[0] if cmd else ""
|
| 216 |
+
m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", "")))
|
| 217 |
+
if word in ("move_eef", "observe") and m:
|
| 218 |
+
a, s = int(m.group(1)), int(m.group(2))
|
| 219 |
+
n = take()
|
| 220 |
+
n["command"] = cmd
|
| 221 |
+
self.notes[(a, s)] = n
|
| 222 |
+
attempt = a
|
| 223 |
+
elif word in ("finish", "done"):
|
| 224 |
+
n = take()
|
| 225 |
+
n["command"] = cmd
|
| 226 |
+
n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)}
|
| 227 |
+
self.finish_notes.setdefault(attempt, n)
|
| 228 |
+
if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"):
|
| 229 |
+
attempt += 1
|
| 230 |
+
# status / help / errors: their narration stays in the buffer for the next command
|
| 231 |
+
self.final_report = last_msg
|
| 232 |
+
|
| 233 |
+
# ---------------------------------------------------------------- run-level labels
|
| 234 |
+
def attempts(self):
|
| 235 |
+
out = []
|
| 236 |
+
for e in self.dones:
|
| 237 |
+
o = e.get("outcome") or {}
|
| 238 |
+
if isinstance(o, str):
|
| 239 |
+
try:
|
| 240 |
+
o = ast.literal_eval(o)
|
| 241 |
+
except (ValueError, SyntaxError):
|
| 242 |
+
o = {}
|
| 243 |
+
out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o,
|
| 244 |
+
reason=e.get("reason") or ""))
|
| 245 |
+
return sorted(out, key=lambda x: x["attempt"])
|
| 246 |
+
|
| 247 |
+
def condition(self):
|
| 248 |
+
s, en = self.start, self.entry
|
| 249 |
+
mem = s.get("memory", en.get("mem"))
|
| 250 |
+
chain = en.get("chain")
|
| 251 |
+
if mem == "full":
|
| 252 |
+
cond = "with_history"
|
| 253 |
+
elif chain:
|
| 254 |
+
cond = "memory_free_retry"
|
| 255 |
+
else:
|
| 256 |
+
cond = "independent_single_attempt"
|
| 257 |
+
return cond, chain
|
| 258 |
+
|
| 259 |
+
def outcome_class(self):
|
| 260 |
+
"""CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None."""
|
| 261 |
+
att = self.attempts()
|
| 262 |
+
if not att or self.start.get("memory") != "full":
|
| 263 |
+
return None, "".join("S" if a["success"] else "F" for a in att)
|
| 264 |
+
hist = "".join("S" if a["success"] else "F" for a in att)
|
| 265 |
+
if att[0]["success"]:
|
| 266 |
+
ev = error_event(att[0]["outcome"])
|
| 267 |
+
cls = "S?" if ev is None else ("IR" if ev else "CS")
|
| 268 |
+
else:
|
| 269 |
+
cls = "XR" if any(a["success"] for a in att) else "F"
|
| 270 |
+
return cls, hist
|
| 271 |
+
|
| 272 |
+
def agent_info(self):
|
| 273 |
+
h, en = self.harness, self.entry
|
| 274 |
+
hdr = self.headers[0] if self.headers else {}
|
| 275 |
+
return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"),
|
| 276 |
+
harness_version=h.get("version") or hdr.get("version"),
|
| 277 |
+
harness_binary_sha256=(h.get("binary") or {}).get("sha256"),
|
| 278 |
+
model=h.get("model") or en.get("model") or hdr.get("model_name"),
|
| 279 |
+
effort=h.get("effort") or en.get("effort") or hdr.get("effort"),
|
| 280 |
+
provider=h.get("provider") or en.get("provider"),
|
| 281 |
+
codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"),
|
| 282 |
+
jail=en.get("jail"))
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
# ====================================================================================================== recording
|
| 286 |
+
|
| 287 |
+
class EpisodeSink:
|
| 288 |
+
"""Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed."""
|
| 289 |
+
|
| 290 |
+
def __init__(self, path):
|
| 291 |
+
self.path = path
|
| 292 |
+
os.makedirs(path, exist_ok=True)
|
| 293 |
+
self.w = None
|
| 294 |
+
self.num = defaultdict(list)
|
| 295 |
+
self.n = 0
|
| 296 |
+
|
| 297 |
+
def add(self, st, imgs):
|
| 298 |
+
import imageio
|
| 299 |
+
if self.w is None:
|
| 300 |
+
self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb",
|
| 301 |
+
pixelformat="rgb24", macro_block_size=1,
|
| 302 |
+
ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error")
|
| 303 |
+
for k in ("agentview", "wrist")]
|
| 304 |
+
for w, im in zip(self.w, imgs):
|
| 305 |
+
w.append_data(im)
|
| 306 |
+
for k, v in st.items():
|
| 307 |
+
self.num[k].append(v)
|
| 308 |
+
self.n += 1
|
| 309 |
+
|
| 310 |
+
def close(self, final_state, final_imgs):
|
| 311 |
+
from PIL import Image
|
| 312 |
+
if self.w is not None:
|
| 313 |
+
for w in self.w:
|
| 314 |
+
w.close()
|
| 315 |
+
arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"}
|
| 316 |
+
np.savez(os.path.join(self.path, "frames.npz"), **arr)
|
| 317 |
+
if self.num.get("sim_state"):
|
| 318 |
+
np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64))
|
| 319 |
+
np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()})
|
| 320 |
+
for k, im in zip(("agentview", "wrist"), final_imgs):
|
| 321 |
+
Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png"))
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
class Recorder:
|
| 325 |
+
"""Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink."""
|
| 326 |
+
|
| 327 |
+
def __init__(self, rp, res):
|
| 328 |
+
self.rp, self.res = rp, int(res)
|
| 329 |
+
self.active = False
|
| 330 |
+
self.sink = None
|
| 331 |
+
self.cur = dict(attempt=1, command=-1, phase=PHASES["move"])
|
| 332 |
+
env = rp.task.env
|
| 333 |
+
self.env, self.rob = env, env.robots[0]
|
| 334 |
+
self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist"))
|
| 335 |
+
orig = env.step
|
| 336 |
+
|
| 337 |
+
def step(a):
|
| 338 |
+
if self.active and self.sink is not None:
|
| 339 |
+
self.capture(np.asarray(a, np.float64))
|
| 340 |
+
out = orig(a)
|
| 341 |
+
if self.active and self.sink is not None:
|
| 342 |
+
self.rp.poll_events(self.sink.n - 1)
|
| 343 |
+
return out
|
| 344 |
+
|
| 345 |
+
env.step = step
|
| 346 |
+
|
| 347 |
+
@property
|
| 348 |
+
def n(self):
|
| 349 |
+
return self.sink.n if self.sink is not None else 0
|
| 350 |
+
|
| 351 |
+
def state(self):
|
| 352 |
+
import robosuite.utils.transform_utils as T
|
| 353 |
+
env, rob = self.env, self.rob
|
| 354 |
+
d = env.sim.data
|
| 355 |
+
eef = np.array(d.site_xpos[rob.eef_site_id], np.float64)
|
| 356 |
+
q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw")
|
| 357 |
+
gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64)
|
| 358 |
+
try:
|
| 359 |
+
flat = np.asarray(env.sim.get_state().flatten(), np.float64)
|
| 360 |
+
except Exception:
|
| 361 |
+
flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64)
|
| 362 |
+
sk = self.rp.task.sk
|
| 363 |
+
return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64),
|
| 364 |
+
gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64),
|
| 365 |
+
joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64),
|
| 366 |
+
gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64),
|
| 367 |
+
eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)),
|
| 368 |
+
sim_time=np.float64(d.time), sim_state=flat)
|
| 369 |
+
|
| 370 |
+
def images(self):
|
| 371 |
+
return [envs.render(self.env, c, self.res) for c in self.cams]
|
| 372 |
+
|
| 373 |
+
def capture(self, a):
|
| 374 |
+
st = self.state()
|
| 375 |
+
st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]),
|
| 376 |
+
phase=np.int64(self.cur["phase"]))
|
| 377 |
+
self.sink.add(st, self.images())
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
class RunReplay:
|
| 381 |
+
def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None):
|
| 382 |
+
self.run_dir = os.path.abspath(run_dir.rstrip("/"))
|
| 383 |
+
self.run_name = os.path.basename(self.run_dir)
|
| 384 |
+
self.log = RunLog(self.run_dir, manifest)
|
| 385 |
+
self.ev = self.log.ev
|
| 386 |
+
self.start = self.log.start
|
| 387 |
+
cp = os.path.join(self.run_dir, "contract.json")
|
| 388 |
+
self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {}
|
| 389 |
+
spec = self.contract.get("image_spec") or {}
|
| 390 |
+
self.image_res = int(spec.get("width", 512))
|
| 391 |
+
self.code_diff = check_code(self.run_dir)
|
| 392 |
+
s = self.start
|
| 393 |
+
self.task = TASKS[s["task"]](cam_res=self.image_res)
|
| 394 |
+
inst = self.task.sample_instance(s["seed"])
|
| 395 |
+
logged = s.get("inst") or {}
|
| 396 |
+
sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")})
|
| 397 |
+
self.inst_diff = diff_json(sampled, logged, "inst")
|
| 398 |
+
if s.get("arm", "none") not in (None, "none") or logged.get("nominal"):
|
| 399 |
+
inst.update(logged) # controlled arms / nominal: the server overrode these instance fields
|
| 400 |
+
self.inst_diff = []
|
| 401 |
+
self.inst = inst
|
| 402 |
+
self.protocol = getattr(self.task, "protocol", "cross")
|
| 403 |
+
self.k = int(s.get("k") or self.task.max_attempts)
|
| 404 |
+
self.attempt = 1
|
| 405 |
+
self.mismatch = [] # (where, what, logged, replayed)
|
| 406 |
+
self.n_checked = 0
|
| 407 |
+
self.max_dev_m = 0.0
|
| 408 |
+
self.unfinished = None
|
| 409 |
+
self.rec = Recorder(self, res) if record else None
|
| 410 |
+
self.res = int(res)
|
| 411 |
+
self.out_root = out_root
|
| 412 |
+
self.n_mon = 0
|
| 413 |
+
self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0
|
| 414 |
+
self.episodes = [] # summaries of the written episodes
|
| 415 |
+
self.task.reset_instance(self.inst)
|
| 416 |
+
self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
|
| 417 |
+
sim = self.task.env.sim
|
| 418 |
+
bid = sim.model.body_name2id("robot0_base")
|
| 419 |
+
self.base_off = np.array(sim.data.body_xpos[bid], float).copy()
|
| 420 |
+
if self.rec:
|
| 421 |
+
self._open_episode()
|
| 422 |
+
|
| 423 |
+
# ------------------------------------------------------------------ episodes
|
| 424 |
+
def _ep_dir(self):
|
| 425 |
+
return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}")
|
| 426 |
+
|
| 427 |
+
def _open_episode(self):
|
| 428 |
+
self.rec.sink = EpisodeSink(self._ep_dir())
|
| 429 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
|
| 430 |
+
self.rec.active = True
|
| 431 |
+
self.events, self.spans, self.ep_attempts = [], [], []
|
| 432 |
+
self.ep_initial = self.rec.state() # state right after the reset (before frame 0)
|
| 433 |
+
|
| 434 |
+
def close_episode(self):
|
| 435 |
+
if not self.rec:
|
| 436 |
+
self.ep_attempts = []
|
| 437 |
+
return
|
| 438 |
+
sink = self.rec.sink
|
| 439 |
+
st = self.rec.state()
|
| 440 |
+
imgs = self.rec.images()
|
| 441 |
+
st.pop("sim_state", None)
|
| 442 |
+
sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs)
|
| 443 |
+
ann = build_annotation(self, sink)
|
| 444 |
+
with open(os.path.join(sink.path, "annotation.json"), "w") as f:
|
| 445 |
+
json.dump(ann, f, indent=1, default=_json_default)
|
| 446 |
+
self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n,
|
| 447 |
+
attempts=[a["attempt"] for a in self.ep_attempts]))
|
| 448 |
+
self.rec.active = False
|
| 449 |
+
self.rec.sink = None
|
| 450 |
+
self.ep_index += 1
|
| 451 |
+
|
| 452 |
+
# ------------------------------------------------------------------ monitor events (task-side error events)
|
| 453 |
+
def poll_events(self, frame):
|
| 454 |
+
mon = getattr(self.task, "mon", None)
|
| 455 |
+
evs = mon.get("events") if isinstance(mon, dict) else None
|
| 456 |
+
if not isinstance(evs, list):
|
| 457 |
+
return
|
| 458 |
+
if len(evs) < self.n_mon: # monitor was rebuilt
|
| 459 |
+
self.n_mon = 0
|
| 460 |
+
for e in evs[self.n_mon:]:
|
| 461 |
+
self.events.append(dict(frame=int(frame), attempt=self.attempt,
|
| 462 |
+
event=norm_json(e) if isinstance(e, dict) else str(e)))
|
| 463 |
+
self.n_mon = len(evs)
|
| 464 |
+
|
| 465 |
+
# ------------------------------------------------------------------ state as the server reports it
|
| 466 |
+
def proprio_la(self):
|
| 467 |
+
p = self.ex.proprio()
|
| 468 |
+
pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off]
|
| 469 |
+
return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"])
|
| 470 |
+
|
| 471 |
+
def compare(self, where, rep_logged, rep):
|
| 472 |
+
self.n_checked += 1
|
| 473 |
+
for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"):
|
| 474 |
+
if k not in rep_logged or k not in rep:
|
| 475 |
+
continue
|
| 476 |
+
a, b = rep_logged[k], rep[k]
|
| 477 |
+
if k == "eef_pos":
|
| 478 |
+
dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float))))
|
| 479 |
+
self.max_dev_m = max(self.max_dev_m, dev)
|
| 480 |
+
if dev > 1.5e-4:
|
| 481 |
+
self.mismatch.append((where, k, a, b))
|
| 482 |
+
elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4):
|
| 483 |
+
self.mismatch.append((where, k, a, b))
|
| 484 |
+
if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)):
|
| 485 |
+
self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok")))
|
| 486 |
+
|
| 487 |
+
def _span(self, e, f0, kind):
|
| 488 |
+
if self.rec:
|
| 489 |
+
self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0,
|
| 490 |
+
frame_end=self.rec.n))
|
| 491 |
+
|
| 492 |
+
# ------------------------------------------------------------------ commands (robot_server._handle_v2)
|
| 493 |
+
def move_eef(self, e):
|
| 494 |
+
args = e.get("args") or {}
|
| 495 |
+
where = f"a{e['attempt']}s{e['step']}"
|
| 496 |
+
logged = e.get("report") or {}
|
| 497 |
+
f0 = self.rec.n if self.rec else 0
|
| 498 |
+
p = self.ex.proprio()
|
| 499 |
+
if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}:
|
| 500 |
+
self._span(e, f0, "error")
|
| 501 |
+
return self.compare(where, logged, dict(ok=False))
|
| 502 |
+
off = self.base_off
|
| 503 |
+
try:
|
| 504 |
+
cur = np.asarray(p["eef_pos"], float) - off
|
| 505 |
+
tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
|
| 506 |
+
yaw = float(args.get("yaw", p["eef_yaw_deg"]))
|
| 507 |
+
speed = None if args.get("speed") in (None, "") else float(args["speed"])
|
| 508 |
+
except (TypeError, ValueError):
|
| 509 |
+
self._span(e, f0, "error")
|
| 510 |
+
return self.compare(where, logged, dict(ok=False))
|
| 511 |
+
grip = args.get("gripper")
|
| 512 |
+
if grip not in (None, "open", "close"):
|
| 513 |
+
self._span(e, f0, "error")
|
| 514 |
+
return self.compare(where, logged, dict(ok=False))
|
| 515 |
+
moving = any(k in args for k in ("x", "y", "z", "yaw"))
|
| 516 |
+
tgt_w = np.asarray(tgt) + off
|
| 517 |
+
if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)):
|
| 518 |
+
self._span(e, f0, "rejected")
|
| 519 |
+
return self.compare(where, logged, dict(ok=False, **self.proprio_la()))
|
| 520 |
+
raw = {}
|
| 521 |
+
if self.rec:
|
| 522 |
+
self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"])
|
| 523 |
+
if moving:
|
| 524 |
+
mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw)
|
| 525 |
+
if speed is not None:
|
| 526 |
+
mv["speed"] = speed
|
| 527 |
+
raw.update(self.ex.call("move_to", mv).report)
|
| 528 |
+
if grip is not None:
|
| 529 |
+
if self.rec:
|
| 530 |
+
self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"])
|
| 531 |
+
raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report)
|
| 532 |
+
rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la())
|
| 533 |
+
self.compare(where, logged, rep)
|
| 534 |
+
lr = e.get("raw") or {}
|
| 535 |
+
for k in ("holding_object", "touched_object"):
|
| 536 |
+
if k in lr and k in raw and bool(lr[k]) != bool(raw[k]):
|
| 537 |
+
self.mismatch.append((where, "raw." + k, lr[k], raw[k]))
|
| 538 |
+
self._span(e, f0, "move_eef")
|
| 539 |
+
|
| 540 |
+
def observe(self, e):
|
| 541 |
+
f0 = self.rec.n if self.rec else 0
|
| 542 |
+
self._span(e, f0, "observe")
|
| 543 |
+
|
| 544 |
+
def done(self, e):
|
| 545 |
+
f0 = self.rec.n if self.rec else 0
|
| 546 |
+
if self.rec:
|
| 547 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"])
|
| 548 |
+
out = self.task.outcome(self.inst)
|
| 549 |
+
succ = bool(out["success"])
|
| 550 |
+
where = f"a{e['attempt']}done"
|
| 551 |
+
if succ != bool(e.get("success") in (True, "True")):
|
| 552 |
+
self.mismatch.append((where, "success", e.get("success"), succ))
|
| 553 |
+
lo = e.get("outcome") or {}
|
| 554 |
+
ro = norm_json({k: v for k, v in out.items() if k != "feedback"})
|
| 555 |
+
if isinstance(lo, dict):
|
| 556 |
+
for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8):
|
| 557 |
+
self.mismatch.append((where,) + d)
|
| 558 |
+
info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""),
|
| 559 |
+
feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")),
|
| 560 |
+
think_s=e.get("think_s"))
|
| 561 |
+
try:
|
| 562 |
+
info["feedback_f2"] = self.task.feedback(self.inst, out, "F2")
|
| 563 |
+
except Exception as ex_:
|
| 564 |
+
info["feedback_f2"] = f"<unavailable: {type(ex_).__name__}>"
|
| 565 |
+
if self.rec:
|
| 566 |
+
info["judge_frames"] = [f0, self.rec.n]
|
| 567 |
+
self.ep_attempts.append(info)
|
| 568 |
+
last = self.attempt >= self.k or succ or bool(out.get("terminal"))
|
| 569 |
+
if self.protocol == "cross" or last:
|
| 570 |
+
self.close_episode()
|
| 571 |
+
if last:
|
| 572 |
+
return True
|
| 573 |
+
self.attempt += 1
|
| 574 |
+
if self.protocol == "cross":
|
| 575 |
+
self.task.reset_instance(self.inst)
|
| 576 |
+
self.n_mon = 0
|
| 577 |
+
if self.rec:
|
| 578 |
+
self._open_episode()
|
| 579 |
+
elif self.rec:
|
| 580 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
|
| 581 |
+
self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
|
| 582 |
+
return False
|
| 583 |
+
|
| 584 |
+
def run(self):
|
| 585 |
+
t0 = time.time()
|
| 586 |
+
finished = False
|
| 587 |
+
for e in self.ev:
|
| 588 |
+
if e["ev"] == "call":
|
| 589 |
+
if e.get("cmd") == "move_eef":
|
| 590 |
+
self.move_eef(e)
|
| 591 |
+
elif e.get("cmd") == "observe":
|
| 592 |
+
self.observe(e)
|
| 593 |
+
else:
|
| 594 |
+
self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None))
|
| 595 |
+
elif e["ev"] == "done":
|
| 596 |
+
finished = self.done(e)
|
| 597 |
+
if finished:
|
| 598 |
+
break
|
| 599 |
+
self.unfinished = not finished
|
| 600 |
+
if not finished and self.rec and self.rec.sink is not None:
|
| 601 |
+
# the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged
|
| 602 |
+
if self.rec.n or self.ep_attempts:
|
| 603 |
+
self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True,
|
| 604 |
+
finish_reason="", feedback_shown="", auto_ended=False))
|
| 605 |
+
self.close_episode()
|
| 606 |
+
else:
|
| 607 |
+
shutil.rmtree(self.rec.sink.path, ignore_errors=True)
|
| 608 |
+
self.rec.sink = None
|
| 609 |
+
self.wall_s = time.time() - t0
|
| 610 |
+
return self
|
| 611 |
+
|
| 612 |
+
def summary(self):
|
| 613 |
+
return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"],
|
| 614 |
+
protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff),
|
| 615 |
+
n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6),
|
| 616 |
+
unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1),
|
| 617 |
+
first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]])
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
# ====================================================================================================== annotation
|
| 621 |
+
|
| 622 |
+
def task_info(task, inst):
|
| 623 |
+
cls = type(task)
|
| 624 |
+
return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable",
|
| 625 |
+
category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"),
|
| 626 |
+
max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)),
|
| 627 |
+
instruction=cls.instruction)
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
def build_annotation(rp, sink):
|
| 631 |
+
"""Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2
|
| 632 |
+
failure description), run-level outcome class, every robot command with its frame span and the agent's narration,
|
| 633 |
+
task-side error events with frame indices."""
|
| 634 |
+
log = rp.log
|
| 635 |
+
s = rp.start
|
| 636 |
+
cond, chain = log.condition()
|
| 637 |
+
cls, hist = log.outcome_class()
|
| 638 |
+
att_all = log.attempts()
|
| 639 |
+
attempts = []
|
| 640 |
+
for a in rp.ep_attempts:
|
| 641 |
+
a = dict(a)
|
| 642 |
+
n = a["attempt"]
|
| 643 |
+
later = [x for x in att_all if x["attempt"] > n]
|
| 644 |
+
a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later))
|
| 645 |
+
a["is_last_attempt_of_run"] = not later
|
| 646 |
+
fn = log.finish_notes.get(n)
|
| 647 |
+
if fn:
|
| 648 |
+
a["agent_finish"] = fn
|
| 649 |
+
a["error_event_in_attempt"] = error_event(a.get("outcome"))
|
| 650 |
+
attempts.append(a)
|
| 651 |
+
# post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command)
|
| 652 |
+
for a in attempts:
|
| 653 |
+
nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1])
|
| 654 |
+
if a.get("success") is False and nxt:
|
| 655 |
+
note = log.notes[nxt[0]]
|
| 656 |
+
a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note}
|
| 657 |
+
commands = []
|
| 658 |
+
for sp in rp.spans:
|
| 659 |
+
e = log.calls.get((sp["attempt"], sp["step"])) or {}
|
| 660 |
+
rep = e.get("report") or {}
|
| 661 |
+
c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"],
|
| 662 |
+
frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]),
|
| 663 |
+
args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"),
|
| 664 |
+
stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"),
|
| 665 |
+
gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"),
|
| 666 |
+
touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"),
|
| 667 |
+
agent_obs_images=rep.get("images"))
|
| 668 |
+
note = log.notes.get((sp["attempt"], sp["step"]))
|
| 669 |
+
if note:
|
| 670 |
+
c["agent_note"] = {k: v for k, v in note.items() if k != "command"}
|
| 671 |
+
commands.append(c)
|
| 672 |
+
t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x]
|
| 673 |
+
return dict(
|
| 674 |
+
schema=SCHEMA,
|
| 675 |
+
source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts],
|
| 676 |
+
episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain,
|
| 677 |
+
memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None),
|
| 678 |
+
feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"),
|
| 679 |
+
k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"),
|
| 680 |
+
contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256")
|
| 681 |
+
if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)),
|
| 682 |
+
agent=log.agent_info(),
|
| 683 |
+
task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"),
|
| 684 |
+
instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}),
|
| 685 |
+
run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all),
|
| 686 |
+
run_success=any(x["success"] for x in att_all) if att_all else None,
|
| 687 |
+
agent_final_report=log.final_report[:6000] or None,
|
| 688 |
+
mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)),
|
| 689 |
+
attempts=attempts,
|
| 690 |
+
commands=commands,
|
| 691 |
+
task_events=rp.events,
|
| 692 |
+
frames=dict(n=sink.n, fps=FPS, image_res=rp.res,
|
| 693 |
+
phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"],
|
| 694 |
+
joint_pos=rp.ep_initial["joint_pos"],
|
| 695 |
+
gripper_qpos=rp.ep_initial["gripper_qpos"])),
|
| 696 |
+
)
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
# ====================================================================================================== CLI
|
| 700 |
+
|
| 701 |
+
def load_manifest(run_dir):
|
| 702 |
+
p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json")
|
| 703 |
+
return json.load(open(p)) if os.path.exists(p) else {}
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
def main():
|
| 707 |
+
ap = argparse.ArgumentParser()
|
| 708 |
+
ap.add_argument("mode", choices=["check", "record"])
|
| 709 |
+
ap.add_argument("runs", nargs="+")
|
| 710 |
+
ap.add_argument("--json", default="")
|
| 711 |
+
ap.add_argument("--out", default="")
|
| 712 |
+
ap.add_argument("--res", type=int, default=256)
|
| 713 |
+
ap.add_argument("--force", action="store_true", help="record again even if replay.json exists")
|
| 714 |
+
a = ap.parse_args()
|
| 715 |
+
rows = []
|
| 716 |
+
for r in a.runs:
|
| 717 |
+
r = r.rstrip("/")
|
| 718 |
+
try:
|
| 719 |
+
if a.mode == "check":
|
| 720 |
+
s = RunReplay(r, manifest=load_manifest(r)).run().summary()
|
| 721 |
+
else:
|
| 722 |
+
batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r)
|
| 723 |
+
rd = os.path.join(a.out, batch, name)
|
| 724 |
+
if os.path.exists(os.path.join(rd, "replay.json")) and not a.force:
|
| 725 |
+
print(json.dumps(dict(run=name, skipped="exists")), flush=True)
|
| 726 |
+
continue
|
| 727 |
+
shutil.rmtree(rd, ignore_errors=True)
|
| 728 |
+
rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run()
|
| 729 |
+
s = rp.summary()
|
| 730 |
+
s["episodes"] = rp.episodes
|
| 731 |
+
with open(os.path.join(rd, "replay.json"), "w") as f:
|
| 732 |
+
json.dump(s, f, indent=1)
|
| 733 |
+
except Exception:
|
| 734 |
+
import traceback
|
| 735 |
+
s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:])
|
| 736 |
+
rows.append(s)
|
| 737 |
+
print(json.dumps(s), flush=True)
|
| 738 |
+
if a.json:
|
| 739 |
+
with open(a.json, "w") as f:
|
| 740 |
+
json.dump(rows, f, indent=1)
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
if __name__ == "__main__":
|
| 744 |
+
main()
|
leaf/code/v1.5/backfill-20261102-lf2_sonnet_r2/lerobot_replay.py
ADDED
|
@@ -0,0 +1,744 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay
|
| 2 |
+
against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the
|
| 3 |
+
LeRobot export (scripts/lerobot_export.py).
|
| 4 |
+
|
| 5 |
+
python scripts/lerobot_replay.py check <run_dir> [<run_dir> ...] [--json out.json] # replay only, print fidelity
|
| 6 |
+
python scripts/lerobot_replay.py record <run_dir> --out <raw_root> [--res 256]
|
| 7 |
+
|
| 8 |
+
Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot
|
| 9 |
+
commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite
|
| 10 |
+
is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly
|
| 11 |
+
like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same
|
| 12 |
+
outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width,
|
| 13 |
+
ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code
|
| 14 |
+
hashes equal the current files are expected to match (check_code()).
|
| 15 |
+
|
| 16 |
+
Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB,
|
| 17 |
+
proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes:
|
| 18 |
+
protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode
|
| 19 |
+
per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the
|
| 20 |
+
fidelity check runs in record mode too. Per episode the recorder writes <raw_root>/<batch>/<run>/epNN/:
|
| 21 |
+
agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes)
|
| 22 |
+
frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase
|
| 23 |
+
sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel)
|
| 24 |
+
final_*.png, final.npz observation after the last control step (the state the outcome was judged in)
|
| 25 |
+
annotation.json episode annotation (build_annotation)
|
| 26 |
+
and <raw_root>/<batch>/<run>/replay.json (fidelity) when the whole run is done.
|
| 27 |
+
"""
|
| 28 |
+
import argparse
|
| 29 |
+
import ast
|
| 30 |
+
import hashlib
|
| 31 |
+
import importlib
|
| 32 |
+
import json
|
| 33 |
+
import math
|
| 34 |
+
import os
|
| 35 |
+
import pkgutil
|
| 36 |
+
import re
|
| 37 |
+
import shutil
|
| 38 |
+
import sys
|
| 39 |
+
import time
|
| 40 |
+
from collections import defaultdict
|
| 41 |
+
|
| 42 |
+
import numpy as np
|
| 43 |
+
|
| 44 |
+
LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 45 |
+
sys.path.insert(0, LFF_ROOT)
|
| 46 |
+
|
| 47 |
+
from lffbench import envs # noqa: E402
|
| 48 |
+
from lffbench import tasks as task_pkg # noqa: E402
|
| 49 |
+
from lffbench.agent import camera as C # noqa: E402
|
| 50 |
+
from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402
|
| 51 |
+
from lffbench.task_base import TASKS # noqa: E402
|
| 52 |
+
|
| 53 |
+
for _m in pkgutil.iter_modules(task_pkg.__path__):
|
| 54 |
+
importlib.import_module(f"lffbench.tasks.{_m.name}")
|
| 55 |
+
|
| 56 |
+
# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the
|
| 57 |
+
# task's outcome() check after `finish` (the arm holds still; not an agent action)
|
| 58 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 59 |
+
FPS = 20
|
| 60 |
+
SCHEMA = "lff-replay-1"
|
| 61 |
+
|
| 62 |
+
# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR"
|
| 63 |
+
ERROR_FLAGS = ("trap_fired", "recovered_in_attempt")
|
| 64 |
+
ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events",
|
| 65 |
+
"n_missed_strikes", "n_open_gripper_pushes")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def load_jsonl(p):
|
| 69 |
+
out = []
|
| 70 |
+
if not os.path.exists(p):
|
| 71 |
+
return out
|
| 72 |
+
with open(p) as f:
|
| 73 |
+
for line in f:
|
| 74 |
+
line = line.strip()
|
| 75 |
+
if line:
|
| 76 |
+
try:
|
| 77 |
+
out.append(json.loads(line))
|
| 78 |
+
except ValueError:
|
| 79 |
+
pass
|
| 80 |
+
return out
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def norm_json(o):
|
| 84 |
+
return json.loads(json.dumps(o, default=_json_default))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def sha256(p):
|
| 88 |
+
with open(p, "rb") as f:
|
| 89 |
+
return hashlib.sha256(f.read()).hexdigest()
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def check_code(run_dir):
|
| 93 |
+
"""[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract."""
|
| 94 |
+
p = os.path.join(run_dir, "contract.json")
|
| 95 |
+
if not os.path.exists(p):
|
| 96 |
+
return [("contract.json", None, None)]
|
| 97 |
+
files = json.load(open(p))["contract"].get("server_code_files", {})
|
| 98 |
+
bad = []
|
| 99 |
+
for f, h in files.items():
|
| 100 |
+
q = os.path.join(LFF_ROOT, f)
|
| 101 |
+
cur = sha256(q) if os.path.exists(q) else None
|
| 102 |
+
if cur != h:
|
| 103 |
+
bad.append((f, h, cur))
|
| 104 |
+
return bad
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def diff_json(a, b, path="", tol=0.0, out=None, limit=20):
|
| 108 |
+
"""Differences between two JSON values (numbers compared with an absolute tolerance)."""
|
| 109 |
+
out = [] if out is None else out
|
| 110 |
+
if len(out) >= limit:
|
| 111 |
+
return out
|
| 112 |
+
if isinstance(a, dict) and isinstance(b, dict):
|
| 113 |
+
for k in sorted(set(a) | set(b)):
|
| 114 |
+
if k not in a or k not in b:
|
| 115 |
+
out.append((f"{path}.{k}", a.get(k, "<missing>"), b.get(k, "<missing>")))
|
| 116 |
+
else:
|
| 117 |
+
diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit)
|
| 118 |
+
elif isinstance(a, list) and isinstance(b, list):
|
| 119 |
+
if len(a) != len(b):
|
| 120 |
+
out.append((path, f"len {len(a)}", f"len {len(b)}"))
|
| 121 |
+
else:
|
| 122 |
+
for i, (x, y) in enumerate(zip(a, b)):
|
| 123 |
+
diff_json(x, y, f"{path}[{i}]", tol, out, limit)
|
| 124 |
+
elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
|
| 125 |
+
if a != b:
|
| 126 |
+
out.append((path, a, b))
|
| 127 |
+
elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))):
|
| 128 |
+
out.append((path, a, b))
|
| 129 |
+
return out
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def error_event(o):
|
| 133 |
+
"""True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none."""
|
| 134 |
+
if not isinstance(o, dict):
|
| 135 |
+
return None
|
| 136 |
+
keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o]
|
| 137 |
+
if not keys:
|
| 138 |
+
return None
|
| 139 |
+
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)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# ====================================================================================================== logs -> notes
|
| 143 |
+
|
| 144 |
+
class RunLog:
|
| 145 |
+
"""Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's
|
| 146 |
+
narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition."""
|
| 147 |
+
|
| 148 |
+
def __init__(self, run_dir, manifest=None):
|
| 149 |
+
self.run_dir = os.path.abspath(run_dir.rstrip("/"))
|
| 150 |
+
self.run = os.path.basename(self.run_dir)
|
| 151 |
+
self.batch = os.path.basename(os.path.dirname(self.run_dir))
|
| 152 |
+
self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl"))
|
| 153 |
+
self.start = next(e for e in self.ev if e["ev"] == "session_start")
|
| 154 |
+
self.calls, self.dones, self.harness_status = {}, [], []
|
| 155 |
+
last = None
|
| 156 |
+
for e in self.ev:
|
| 157 |
+
if e["ev"] == "call":
|
| 158 |
+
self.calls[(int(e["attempt"]), int(e["step"]))] = e
|
| 159 |
+
last = e
|
| 160 |
+
elif e["ev"] == "done":
|
| 161 |
+
self.dones.append(e)
|
| 162 |
+
last = e
|
| 163 |
+
elif e["ev"] == "http" and last is not None and "think_s" not in last:
|
| 164 |
+
ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \
|
| 165 |
+
(last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe"))
|
| 166 |
+
if ok:
|
| 167 |
+
last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s")
|
| 168 |
+
self.manifest = manifest or {}
|
| 169 |
+
self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {}
|
| 170 |
+
p = os.path.join(self.run_dir, "harness.json")
|
| 171 |
+
self.harness = json.load(open(p)) if os.path.exists(p) else {}
|
| 172 |
+
self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl"))
|
| 173 |
+
self._narration()
|
| 174 |
+
|
| 175 |
+
# ---------------------------------------------------------------- agent narration
|
| 176 |
+
def _narration(self):
|
| 177 |
+
"""notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one;
|
| 178 |
+
finish_notes[attempt] likewise for the agent's finish call; final_report = its last message."""
|
| 179 |
+
self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", []
|
| 180 |
+
buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
|
| 181 |
+
attempt = 1
|
| 182 |
+
|
| 183 |
+
def take():
|
| 184 |
+
nonlocal buf
|
| 185 |
+
out = {k: v for k, v in buf.items() if v}
|
| 186 |
+
buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
|
| 187 |
+
return out
|
| 188 |
+
|
| 189 |
+
last_msg = ""
|
| 190 |
+
for t in self.traj:
|
| 191 |
+
if t.get("kind") == "header":
|
| 192 |
+
self.headers.append(t.get("agent") or {})
|
| 193 |
+
continue
|
| 194 |
+
if t.get("kind") != "step":
|
| 195 |
+
continue
|
| 196 |
+
if (t.get("message") or "").strip():
|
| 197 |
+
buf["messages"].append(t["message"].strip())
|
| 198 |
+
last_msg = t["message"].strip()
|
| 199 |
+
if (t.get("reasoning_content") or "").strip():
|
| 200 |
+
buf["reasoning"].append(t["reasoning_content"].strip())
|
| 201 |
+
res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])}
|
| 202 |
+
for c in t.get("tool_calls") or []:
|
| 203 |
+
fn, args = c.get("function_name"), c.get("arguments") or {}
|
| 204 |
+
if fn == "shell":
|
| 205 |
+
buf["shell"].append(str(args.get("command", ""))[:2000])
|
| 206 |
+
elif fn == "view_images":
|
| 207 |
+
buf["viewed"].extend(args.get("paths") or [])
|
| 208 |
+
elif fn == "robot":
|
| 209 |
+
cmd = str(args.get("command", "")).strip()
|
| 210 |
+
r = res.get(c.get("tool_call_id")) or {}
|
| 211 |
+
try:
|
| 212 |
+
rep = json.loads(r.get("content") or "{}")
|
| 213 |
+
except ValueError:
|
| 214 |
+
rep = {}
|
| 215 |
+
word = cmd.split()[0] if cmd else ""
|
| 216 |
+
m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", "")))
|
| 217 |
+
if word in ("move_eef", "observe") and m:
|
| 218 |
+
a, s = int(m.group(1)), int(m.group(2))
|
| 219 |
+
n = take()
|
| 220 |
+
n["command"] = cmd
|
| 221 |
+
self.notes[(a, s)] = n
|
| 222 |
+
attempt = a
|
| 223 |
+
elif word in ("finish", "done"):
|
| 224 |
+
n = take()
|
| 225 |
+
n["command"] = cmd
|
| 226 |
+
n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)}
|
| 227 |
+
self.finish_notes.setdefault(attempt, n)
|
| 228 |
+
if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"):
|
| 229 |
+
attempt += 1
|
| 230 |
+
# status / help / errors: their narration stays in the buffer for the next command
|
| 231 |
+
self.final_report = last_msg
|
| 232 |
+
|
| 233 |
+
# ---------------------------------------------------------------- run-level labels
|
| 234 |
+
def attempts(self):
|
| 235 |
+
out = []
|
| 236 |
+
for e in self.dones:
|
| 237 |
+
o = e.get("outcome") or {}
|
| 238 |
+
if isinstance(o, str):
|
| 239 |
+
try:
|
| 240 |
+
o = ast.literal_eval(o)
|
| 241 |
+
except (ValueError, SyntaxError):
|
| 242 |
+
o = {}
|
| 243 |
+
out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o,
|
| 244 |
+
reason=e.get("reason") or ""))
|
| 245 |
+
return sorted(out, key=lambda x: x["attempt"])
|
| 246 |
+
|
| 247 |
+
def condition(self):
|
| 248 |
+
s, en = self.start, self.entry
|
| 249 |
+
mem = s.get("memory", en.get("mem"))
|
| 250 |
+
chain = en.get("chain")
|
| 251 |
+
if mem == "full":
|
| 252 |
+
cond = "with_history"
|
| 253 |
+
elif chain:
|
| 254 |
+
cond = "memory_free_retry"
|
| 255 |
+
else:
|
| 256 |
+
cond = "independent_single_attempt"
|
| 257 |
+
return cond, chain
|
| 258 |
+
|
| 259 |
+
def outcome_class(self):
|
| 260 |
+
"""CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None."""
|
| 261 |
+
att = self.attempts()
|
| 262 |
+
if not att or self.start.get("memory") != "full":
|
| 263 |
+
return None, "".join("S" if a["success"] else "F" for a in att)
|
| 264 |
+
hist = "".join("S" if a["success"] else "F" for a in att)
|
| 265 |
+
if att[0]["success"]:
|
| 266 |
+
ev = error_event(att[0]["outcome"])
|
| 267 |
+
cls = "S?" if ev is None else ("IR" if ev else "CS")
|
| 268 |
+
else:
|
| 269 |
+
cls = "XR" if any(a["success"] for a in att) else "F"
|
| 270 |
+
return cls, hist
|
| 271 |
+
|
| 272 |
+
def agent_info(self):
|
| 273 |
+
h, en = self.harness, self.entry
|
| 274 |
+
hdr = self.headers[0] if self.headers else {}
|
| 275 |
+
return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"),
|
| 276 |
+
harness_version=h.get("version") or hdr.get("version"),
|
| 277 |
+
harness_binary_sha256=(h.get("binary") or {}).get("sha256"),
|
| 278 |
+
model=h.get("model") or en.get("model") or hdr.get("model_name"),
|
| 279 |
+
effort=h.get("effort") or en.get("effort") or hdr.get("effort"),
|
| 280 |
+
provider=h.get("provider") or en.get("provider"),
|
| 281 |
+
codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"),
|
| 282 |
+
jail=en.get("jail"))
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
# ====================================================================================================== recording
|
| 286 |
+
|
| 287 |
+
class EpisodeSink:
|
| 288 |
+
"""Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed."""
|
| 289 |
+
|
| 290 |
+
def __init__(self, path):
|
| 291 |
+
self.path = path
|
| 292 |
+
os.makedirs(path, exist_ok=True)
|
| 293 |
+
self.w = None
|
| 294 |
+
self.num = defaultdict(list)
|
| 295 |
+
self.n = 0
|
| 296 |
+
|
| 297 |
+
def add(self, st, imgs):
|
| 298 |
+
import imageio
|
| 299 |
+
if self.w is None:
|
| 300 |
+
self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb",
|
| 301 |
+
pixelformat="rgb24", macro_block_size=1,
|
| 302 |
+
ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error")
|
| 303 |
+
for k in ("agentview", "wrist")]
|
| 304 |
+
for w, im in zip(self.w, imgs):
|
| 305 |
+
w.append_data(im)
|
| 306 |
+
for k, v in st.items():
|
| 307 |
+
self.num[k].append(v)
|
| 308 |
+
self.n += 1
|
| 309 |
+
|
| 310 |
+
def close(self, final_state, final_imgs):
|
| 311 |
+
from PIL import Image
|
| 312 |
+
if self.w is not None:
|
| 313 |
+
for w in self.w:
|
| 314 |
+
w.close()
|
| 315 |
+
arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"}
|
| 316 |
+
np.savez(os.path.join(self.path, "frames.npz"), **arr)
|
| 317 |
+
if self.num.get("sim_state"):
|
| 318 |
+
np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64))
|
| 319 |
+
np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()})
|
| 320 |
+
for k, im in zip(("agentview", "wrist"), final_imgs):
|
| 321 |
+
Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png"))
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
class Recorder:
|
| 325 |
+
"""Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink."""
|
| 326 |
+
|
| 327 |
+
def __init__(self, rp, res):
|
| 328 |
+
self.rp, self.res = rp, int(res)
|
| 329 |
+
self.active = False
|
| 330 |
+
self.sink = None
|
| 331 |
+
self.cur = dict(attempt=1, command=-1, phase=PHASES["move"])
|
| 332 |
+
env = rp.task.env
|
| 333 |
+
self.env, self.rob = env, env.robots[0]
|
| 334 |
+
self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist"))
|
| 335 |
+
orig = env.step
|
| 336 |
+
|
| 337 |
+
def step(a):
|
| 338 |
+
if self.active and self.sink is not None:
|
| 339 |
+
self.capture(np.asarray(a, np.float64))
|
| 340 |
+
out = orig(a)
|
| 341 |
+
if self.active and self.sink is not None:
|
| 342 |
+
self.rp.poll_events(self.sink.n - 1)
|
| 343 |
+
return out
|
| 344 |
+
|
| 345 |
+
env.step = step
|
| 346 |
+
|
| 347 |
+
@property
|
| 348 |
+
def n(self):
|
| 349 |
+
return self.sink.n if self.sink is not None else 0
|
| 350 |
+
|
| 351 |
+
def state(self):
|
| 352 |
+
import robosuite.utils.transform_utils as T
|
| 353 |
+
env, rob = self.env, self.rob
|
| 354 |
+
d = env.sim.data
|
| 355 |
+
eef = np.array(d.site_xpos[rob.eef_site_id], np.float64)
|
| 356 |
+
q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw")
|
| 357 |
+
gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64)
|
| 358 |
+
try:
|
| 359 |
+
flat = np.asarray(env.sim.get_state().flatten(), np.float64)
|
| 360 |
+
except Exception:
|
| 361 |
+
flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64)
|
| 362 |
+
sk = self.rp.task.sk
|
| 363 |
+
return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64),
|
| 364 |
+
gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64),
|
| 365 |
+
joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64),
|
| 366 |
+
gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64),
|
| 367 |
+
eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)),
|
| 368 |
+
sim_time=np.float64(d.time), sim_state=flat)
|
| 369 |
+
|
| 370 |
+
def images(self):
|
| 371 |
+
return [envs.render(self.env, c, self.res) for c in self.cams]
|
| 372 |
+
|
| 373 |
+
def capture(self, a):
|
| 374 |
+
st = self.state()
|
| 375 |
+
st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]),
|
| 376 |
+
phase=np.int64(self.cur["phase"]))
|
| 377 |
+
self.sink.add(st, self.images())
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
class RunReplay:
|
| 381 |
+
def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None):
|
| 382 |
+
self.run_dir = os.path.abspath(run_dir.rstrip("/"))
|
| 383 |
+
self.run_name = os.path.basename(self.run_dir)
|
| 384 |
+
self.log = RunLog(self.run_dir, manifest)
|
| 385 |
+
self.ev = self.log.ev
|
| 386 |
+
self.start = self.log.start
|
| 387 |
+
cp = os.path.join(self.run_dir, "contract.json")
|
| 388 |
+
self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {}
|
| 389 |
+
spec = self.contract.get("image_spec") or {}
|
| 390 |
+
self.image_res = int(spec.get("width", 512))
|
| 391 |
+
self.code_diff = check_code(self.run_dir)
|
| 392 |
+
s = self.start
|
| 393 |
+
self.task = TASKS[s["task"]](cam_res=self.image_res)
|
| 394 |
+
inst = self.task.sample_instance(s["seed"])
|
| 395 |
+
logged = s.get("inst") or {}
|
| 396 |
+
sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")})
|
| 397 |
+
self.inst_diff = diff_json(sampled, logged, "inst")
|
| 398 |
+
if s.get("arm", "none") not in (None, "none") or logged.get("nominal"):
|
| 399 |
+
inst.update(logged) # controlled arms / nominal: the server overrode these instance fields
|
| 400 |
+
self.inst_diff = []
|
| 401 |
+
self.inst = inst
|
| 402 |
+
self.protocol = getattr(self.task, "protocol", "cross")
|
| 403 |
+
self.k = int(s.get("k") or self.task.max_attempts)
|
| 404 |
+
self.attempt = 1
|
| 405 |
+
self.mismatch = [] # (where, what, logged, replayed)
|
| 406 |
+
self.n_checked = 0
|
| 407 |
+
self.max_dev_m = 0.0
|
| 408 |
+
self.unfinished = None
|
| 409 |
+
self.rec = Recorder(self, res) if record else None
|
| 410 |
+
self.res = int(res)
|
| 411 |
+
self.out_root = out_root
|
| 412 |
+
self.n_mon = 0
|
| 413 |
+
self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0
|
| 414 |
+
self.episodes = [] # summaries of the written episodes
|
| 415 |
+
self.task.reset_instance(self.inst)
|
| 416 |
+
self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
|
| 417 |
+
sim = self.task.env.sim
|
| 418 |
+
bid = sim.model.body_name2id("robot0_base")
|
| 419 |
+
self.base_off = np.array(sim.data.body_xpos[bid], float).copy()
|
| 420 |
+
if self.rec:
|
| 421 |
+
self._open_episode()
|
| 422 |
+
|
| 423 |
+
# ------------------------------------------------------------------ episodes
|
| 424 |
+
def _ep_dir(self):
|
| 425 |
+
return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}")
|
| 426 |
+
|
| 427 |
+
def _open_episode(self):
|
| 428 |
+
self.rec.sink = EpisodeSink(self._ep_dir())
|
| 429 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
|
| 430 |
+
self.rec.active = True
|
| 431 |
+
self.events, self.spans, self.ep_attempts = [], [], []
|
| 432 |
+
self.ep_initial = self.rec.state() # state right after the reset (before frame 0)
|
| 433 |
+
|
| 434 |
+
def close_episode(self):
|
| 435 |
+
if not self.rec:
|
| 436 |
+
self.ep_attempts = []
|
| 437 |
+
return
|
| 438 |
+
sink = self.rec.sink
|
| 439 |
+
st = self.rec.state()
|
| 440 |
+
imgs = self.rec.images()
|
| 441 |
+
st.pop("sim_state", None)
|
| 442 |
+
sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs)
|
| 443 |
+
ann = build_annotation(self, sink)
|
| 444 |
+
with open(os.path.join(sink.path, "annotation.json"), "w") as f:
|
| 445 |
+
json.dump(ann, f, indent=1, default=_json_default)
|
| 446 |
+
self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n,
|
| 447 |
+
attempts=[a["attempt"] for a in self.ep_attempts]))
|
| 448 |
+
self.rec.active = False
|
| 449 |
+
self.rec.sink = None
|
| 450 |
+
self.ep_index += 1
|
| 451 |
+
|
| 452 |
+
# ------------------------------------------------------------------ monitor events (task-side error events)
|
| 453 |
+
def poll_events(self, frame):
|
| 454 |
+
mon = getattr(self.task, "mon", None)
|
| 455 |
+
evs = mon.get("events") if isinstance(mon, dict) else None
|
| 456 |
+
if not isinstance(evs, list):
|
| 457 |
+
return
|
| 458 |
+
if len(evs) < self.n_mon: # monitor was rebuilt
|
| 459 |
+
self.n_mon = 0
|
| 460 |
+
for e in evs[self.n_mon:]:
|
| 461 |
+
self.events.append(dict(frame=int(frame), attempt=self.attempt,
|
| 462 |
+
event=norm_json(e) if isinstance(e, dict) else str(e)))
|
| 463 |
+
self.n_mon = len(evs)
|
| 464 |
+
|
| 465 |
+
# ------------------------------------------------------------------ state as the server reports it
|
| 466 |
+
def proprio_la(self):
|
| 467 |
+
p = self.ex.proprio()
|
| 468 |
+
pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off]
|
| 469 |
+
return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"])
|
| 470 |
+
|
| 471 |
+
def compare(self, where, rep_logged, rep):
|
| 472 |
+
self.n_checked += 1
|
| 473 |
+
for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"):
|
| 474 |
+
if k not in rep_logged or k not in rep:
|
| 475 |
+
continue
|
| 476 |
+
a, b = rep_logged[k], rep[k]
|
| 477 |
+
if k == "eef_pos":
|
| 478 |
+
dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float))))
|
| 479 |
+
self.max_dev_m = max(self.max_dev_m, dev)
|
| 480 |
+
if dev > 1.5e-4:
|
| 481 |
+
self.mismatch.append((where, k, a, b))
|
| 482 |
+
elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4):
|
| 483 |
+
self.mismatch.append((where, k, a, b))
|
| 484 |
+
if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)):
|
| 485 |
+
self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok")))
|
| 486 |
+
|
| 487 |
+
def _span(self, e, f0, kind):
|
| 488 |
+
if self.rec:
|
| 489 |
+
self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0,
|
| 490 |
+
frame_end=self.rec.n))
|
| 491 |
+
|
| 492 |
+
# ------------------------------------------------------------------ commands (robot_server._handle_v2)
|
| 493 |
+
def move_eef(self, e):
|
| 494 |
+
args = e.get("args") or {}
|
| 495 |
+
where = f"a{e['attempt']}s{e['step']}"
|
| 496 |
+
logged = e.get("report") or {}
|
| 497 |
+
f0 = self.rec.n if self.rec else 0
|
| 498 |
+
p = self.ex.proprio()
|
| 499 |
+
if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}:
|
| 500 |
+
self._span(e, f0, "error")
|
| 501 |
+
return self.compare(where, logged, dict(ok=False))
|
| 502 |
+
off = self.base_off
|
| 503 |
+
try:
|
| 504 |
+
cur = np.asarray(p["eef_pos"], float) - off
|
| 505 |
+
tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
|
| 506 |
+
yaw = float(args.get("yaw", p["eef_yaw_deg"]))
|
| 507 |
+
speed = None if args.get("speed") in (None, "") else float(args["speed"])
|
| 508 |
+
except (TypeError, ValueError):
|
| 509 |
+
self._span(e, f0, "error")
|
| 510 |
+
return self.compare(where, logged, dict(ok=False))
|
| 511 |
+
grip = args.get("gripper")
|
| 512 |
+
if grip not in (None, "open", "close"):
|
| 513 |
+
self._span(e, f0, "error")
|
| 514 |
+
return self.compare(where, logged, dict(ok=False))
|
| 515 |
+
moving = any(k in args for k in ("x", "y", "z", "yaw"))
|
| 516 |
+
tgt_w = np.asarray(tgt) + off
|
| 517 |
+
if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)):
|
| 518 |
+
self._span(e, f0, "rejected")
|
| 519 |
+
return self.compare(where, logged, dict(ok=False, **self.proprio_la()))
|
| 520 |
+
raw = {}
|
| 521 |
+
if self.rec:
|
| 522 |
+
self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"])
|
| 523 |
+
if moving:
|
| 524 |
+
mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw)
|
| 525 |
+
if speed is not None:
|
| 526 |
+
mv["speed"] = speed
|
| 527 |
+
raw.update(self.ex.call("move_to", mv).report)
|
| 528 |
+
if grip is not None:
|
| 529 |
+
if self.rec:
|
| 530 |
+
self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"])
|
| 531 |
+
raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report)
|
| 532 |
+
rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la())
|
| 533 |
+
self.compare(where, logged, rep)
|
| 534 |
+
lr = e.get("raw") or {}
|
| 535 |
+
for k in ("holding_object", "touched_object"):
|
| 536 |
+
if k in lr and k in raw and bool(lr[k]) != bool(raw[k]):
|
| 537 |
+
self.mismatch.append((where, "raw." + k, lr[k], raw[k]))
|
| 538 |
+
self._span(e, f0, "move_eef")
|
| 539 |
+
|
| 540 |
+
def observe(self, e):
|
| 541 |
+
f0 = self.rec.n if self.rec else 0
|
| 542 |
+
self._span(e, f0, "observe")
|
| 543 |
+
|
| 544 |
+
def done(self, e):
|
| 545 |
+
f0 = self.rec.n if self.rec else 0
|
| 546 |
+
if self.rec:
|
| 547 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"])
|
| 548 |
+
out = self.task.outcome(self.inst)
|
| 549 |
+
succ = bool(out["success"])
|
| 550 |
+
where = f"a{e['attempt']}done"
|
| 551 |
+
if succ != bool(e.get("success") in (True, "True")):
|
| 552 |
+
self.mismatch.append((where, "success", e.get("success"), succ))
|
| 553 |
+
lo = e.get("outcome") or {}
|
| 554 |
+
ro = norm_json({k: v for k, v in out.items() if k != "feedback"})
|
| 555 |
+
if isinstance(lo, dict):
|
| 556 |
+
for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8):
|
| 557 |
+
self.mismatch.append((where,) + d)
|
| 558 |
+
info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""),
|
| 559 |
+
feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")),
|
| 560 |
+
think_s=e.get("think_s"))
|
| 561 |
+
try:
|
| 562 |
+
info["feedback_f2"] = self.task.feedback(self.inst, out, "F2")
|
| 563 |
+
except Exception as ex_:
|
| 564 |
+
info["feedback_f2"] = f"<unavailable: {type(ex_).__name__}>"
|
| 565 |
+
if self.rec:
|
| 566 |
+
info["judge_frames"] = [f0, self.rec.n]
|
| 567 |
+
self.ep_attempts.append(info)
|
| 568 |
+
last = self.attempt >= self.k or succ or bool(out.get("terminal"))
|
| 569 |
+
if self.protocol == "cross" or last:
|
| 570 |
+
self.close_episode()
|
| 571 |
+
if last:
|
| 572 |
+
return True
|
| 573 |
+
self.attempt += 1
|
| 574 |
+
if self.protocol == "cross":
|
| 575 |
+
self.task.reset_instance(self.inst)
|
| 576 |
+
self.n_mon = 0
|
| 577 |
+
if self.rec:
|
| 578 |
+
self._open_episode()
|
| 579 |
+
elif self.rec:
|
| 580 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
|
| 581 |
+
self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
|
| 582 |
+
return False
|
| 583 |
+
|
| 584 |
+
def run(self):
|
| 585 |
+
t0 = time.time()
|
| 586 |
+
finished = False
|
| 587 |
+
for e in self.ev:
|
| 588 |
+
if e["ev"] == "call":
|
| 589 |
+
if e.get("cmd") == "move_eef":
|
| 590 |
+
self.move_eef(e)
|
| 591 |
+
elif e.get("cmd") == "observe":
|
| 592 |
+
self.observe(e)
|
| 593 |
+
else:
|
| 594 |
+
self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None))
|
| 595 |
+
elif e["ev"] == "done":
|
| 596 |
+
finished = self.done(e)
|
| 597 |
+
if finished:
|
| 598 |
+
break
|
| 599 |
+
self.unfinished = not finished
|
| 600 |
+
if not finished and self.rec and self.rec.sink is not None:
|
| 601 |
+
# the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged
|
| 602 |
+
if self.rec.n or self.ep_attempts:
|
| 603 |
+
self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True,
|
| 604 |
+
finish_reason="", feedback_shown="", auto_ended=False))
|
| 605 |
+
self.close_episode()
|
| 606 |
+
else:
|
| 607 |
+
shutil.rmtree(self.rec.sink.path, ignore_errors=True)
|
| 608 |
+
self.rec.sink = None
|
| 609 |
+
self.wall_s = time.time() - t0
|
| 610 |
+
return self
|
| 611 |
+
|
| 612 |
+
def summary(self):
|
| 613 |
+
return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"],
|
| 614 |
+
protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff),
|
| 615 |
+
n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6),
|
| 616 |
+
unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1),
|
| 617 |
+
first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]])
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
# ====================================================================================================== annotation
|
| 621 |
+
|
| 622 |
+
def task_info(task, inst):
|
| 623 |
+
cls = type(task)
|
| 624 |
+
return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable",
|
| 625 |
+
category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"),
|
| 626 |
+
max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)),
|
| 627 |
+
instruction=cls.instruction)
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
def build_annotation(rp, sink):
|
| 631 |
+
"""Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2
|
| 632 |
+
failure description), run-level outcome class, every robot command with its frame span and the agent's narration,
|
| 633 |
+
task-side error events with frame indices."""
|
| 634 |
+
log = rp.log
|
| 635 |
+
s = rp.start
|
| 636 |
+
cond, chain = log.condition()
|
| 637 |
+
cls, hist = log.outcome_class()
|
| 638 |
+
att_all = log.attempts()
|
| 639 |
+
attempts = []
|
| 640 |
+
for a in rp.ep_attempts:
|
| 641 |
+
a = dict(a)
|
| 642 |
+
n = a["attempt"]
|
| 643 |
+
later = [x for x in att_all if x["attempt"] > n]
|
| 644 |
+
a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later))
|
| 645 |
+
a["is_last_attempt_of_run"] = not later
|
| 646 |
+
fn = log.finish_notes.get(n)
|
| 647 |
+
if fn:
|
| 648 |
+
a["agent_finish"] = fn
|
| 649 |
+
a["error_event_in_attempt"] = error_event(a.get("outcome"))
|
| 650 |
+
attempts.append(a)
|
| 651 |
+
# post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command)
|
| 652 |
+
for a in attempts:
|
| 653 |
+
nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1])
|
| 654 |
+
if a.get("success") is False and nxt:
|
| 655 |
+
note = log.notes[nxt[0]]
|
| 656 |
+
a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note}
|
| 657 |
+
commands = []
|
| 658 |
+
for sp in rp.spans:
|
| 659 |
+
e = log.calls.get((sp["attempt"], sp["step"])) or {}
|
| 660 |
+
rep = e.get("report") or {}
|
| 661 |
+
c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"],
|
| 662 |
+
frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]),
|
| 663 |
+
args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"),
|
| 664 |
+
stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"),
|
| 665 |
+
gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"),
|
| 666 |
+
touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"),
|
| 667 |
+
agent_obs_images=rep.get("images"))
|
| 668 |
+
note = log.notes.get((sp["attempt"], sp["step"]))
|
| 669 |
+
if note:
|
| 670 |
+
c["agent_note"] = {k: v for k, v in note.items() if k != "command"}
|
| 671 |
+
commands.append(c)
|
| 672 |
+
t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x]
|
| 673 |
+
return dict(
|
| 674 |
+
schema=SCHEMA,
|
| 675 |
+
source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts],
|
| 676 |
+
episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain,
|
| 677 |
+
memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None),
|
| 678 |
+
feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"),
|
| 679 |
+
k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"),
|
| 680 |
+
contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256")
|
| 681 |
+
if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)),
|
| 682 |
+
agent=log.agent_info(),
|
| 683 |
+
task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"),
|
| 684 |
+
instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}),
|
| 685 |
+
run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all),
|
| 686 |
+
run_success=any(x["success"] for x in att_all) if att_all else None,
|
| 687 |
+
agent_final_report=log.final_report[:6000] or None,
|
| 688 |
+
mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)),
|
| 689 |
+
attempts=attempts,
|
| 690 |
+
commands=commands,
|
| 691 |
+
task_events=rp.events,
|
| 692 |
+
frames=dict(n=sink.n, fps=FPS, image_res=rp.res,
|
| 693 |
+
phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"],
|
| 694 |
+
joint_pos=rp.ep_initial["joint_pos"],
|
| 695 |
+
gripper_qpos=rp.ep_initial["gripper_qpos"])),
|
| 696 |
+
)
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
# ====================================================================================================== CLI
|
| 700 |
+
|
| 701 |
+
def load_manifest(run_dir):
|
| 702 |
+
p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json")
|
| 703 |
+
return json.load(open(p)) if os.path.exists(p) else {}
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
def main():
|
| 707 |
+
ap = argparse.ArgumentParser()
|
| 708 |
+
ap.add_argument("mode", choices=["check", "record"])
|
| 709 |
+
ap.add_argument("runs", nargs="+")
|
| 710 |
+
ap.add_argument("--json", default="")
|
| 711 |
+
ap.add_argument("--out", default="")
|
| 712 |
+
ap.add_argument("--res", type=int, default=256)
|
| 713 |
+
ap.add_argument("--force", action="store_true", help="record again even if replay.json exists")
|
| 714 |
+
a = ap.parse_args()
|
| 715 |
+
rows = []
|
| 716 |
+
for r in a.runs:
|
| 717 |
+
r = r.rstrip("/")
|
| 718 |
+
try:
|
| 719 |
+
if a.mode == "check":
|
| 720 |
+
s = RunReplay(r, manifest=load_manifest(r)).run().summary()
|
| 721 |
+
else:
|
| 722 |
+
batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r)
|
| 723 |
+
rd = os.path.join(a.out, batch, name)
|
| 724 |
+
if os.path.exists(os.path.join(rd, "replay.json")) and not a.force:
|
| 725 |
+
print(json.dumps(dict(run=name, skipped="exists")), flush=True)
|
| 726 |
+
continue
|
| 727 |
+
shutil.rmtree(rd, ignore_errors=True)
|
| 728 |
+
rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run()
|
| 729 |
+
s = rp.summary()
|
| 730 |
+
s["episodes"] = rp.episodes
|
| 731 |
+
with open(os.path.join(rd, "replay.json"), "w") as f:
|
| 732 |
+
json.dump(s, f, indent=1)
|
| 733 |
+
except Exception:
|
| 734 |
+
import traceback
|
| 735 |
+
s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:])
|
| 736 |
+
rows.append(s)
|
| 737 |
+
print(json.dumps(s), flush=True)
|
| 738 |
+
if a.json:
|
| 739 |
+
with open(a.json, "w") as f:
|
| 740 |
+
json.dump(rows, f, indent=1)
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
if __name__ == "__main__":
|
| 744 |
+
main()
|
leaf/code/v1.5/v1.4/prepare_verified.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Select only exact replay candidates, preserving rejected fidelity reports."""
|
| 2 |
+
import json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
J=Path(__file__).resolve().parent
|
| 6 |
+
B=J.parent
|
| 7 |
+
selected=json.loads((J/'selected.json').read_text())
|
| 8 |
+
accepted=[];rejected=[];missing=[]
|
| 9 |
+
for row in selected:
|
| 10 |
+
prefix='legacy_raw' if row['cohort']=='legacy' else 'raw'
|
| 11 |
+
rel=Path(row['batch'])/row['run']
|
| 12 |
+
candidates=[]
|
| 13 |
+
for root in [prefix+'_local',prefix]:
|
| 14 |
+
p=B/root/rel/'replay.json'
|
| 15 |
+
if p.exists():candidates.append((p,json.loads(p.read_text())))
|
| 16 |
+
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')]
|
| 17 |
+
if passing:
|
| 18 |
+
p,r=passing[0]
|
| 19 |
+
target=B/('legacy_verified_raw' if row['cohort']=='legacy' else 'verified_raw')/rel
|
| 20 |
+
target.parent.mkdir(parents=True,exist_ok=True)
|
| 21 |
+
if not target.exists():target.symlink_to(p.parent,target_is_directory=True)
|
| 22 |
+
accepted.append(dict(row,replay_path=str(p),reports_checked=r['n_checked'],frames=sum(e['n_frames'] for e in r['episodes'])))
|
| 23 |
+
elif candidates:
|
| 24 |
+
rejected.append(dict(row,reason='no exact replay candidate',candidates=[dict(path=str(p),report=r) for p,r in candidates]))
|
| 25 |
+
else:missing.append(row)
|
| 26 |
+
assert not missing, [r['run'] for r in missing]
|
| 27 |
+
report=dict(accepted=accepted,rejected=rejected,missing=missing)
|
| 28 |
+
(J/'verified_selection.json').write_text(json.dumps(report,indent=2))
|
| 29 |
+
print(json.dumps(dict(accepted=len(accepted),rejected=len(rejected),missing=len(missing))))
|
leaf/code/v1.5/v1.4/run.sh
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
BASE=/mnt/cpfs/shared/outputs/peter/lffbench/20261025-0615-v1.4-backfill
|
| 4 |
+
J=$BASE/job
|
| 5 |
+
L=$J/source
|
| 6 |
+
LPY=/mnt/cpfs/workspace/env/libero-cpu/bin/python
|
| 7 |
+
EPY=/mnt/cpfs/workspace/env/zeva-cosmos-cu128/bin/python
|
| 8 |
+
export OMP_NUM_THREADS=1 LP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 PYTHONUNBUFFERED=1
|
| 9 |
+
export MUJOCO_GL=osmesa PYOPENGL_PLATFORM=osmesa
|
| 10 |
+
export LIBERO_CONFIG_PATH=/mnt/cpfs/workspace/env/libero-cpu/.libero
|
| 11 |
+
export PYTHONPATH=$L:/mnt/cpfs/workspace/RSS/LIBERO-Recovery/LIBERO
|
| 12 |
+
export LD_LIBRARY_PATH=$J/osmesa_libs
|
| 13 |
+
cd "$L"
|
| 14 |
+
if [ "${EXPORT_ONLY:-0}" != 1 ]; then
|
| 15 |
+
REF=$(find /mnt/cpfs/workspace/agentic-robotics/lerobot_job/preflight_ref/cx_main1 -mindepth 1 -maxdepth 1 -type d | head -1)
|
| 16 |
+
"$LPY" "$J/osmesa_run.py" "$L/scripts/lerobot_replay.py" record \
|
| 17 |
+
"/mnt/cpfs/workspace/agentic-robotics/lffbench/runs/api/cx_main1/$(basename "$REF")" --out "$J/preflight" > "$J/logs/preflight.log" 2>&1
|
| 18 |
+
"$LPY" "$J/preflight_check.py" "$J/preflight/cx_main1/$(basename "$REF")" "$REF"
|
| 19 |
+
xargs -P 64 -n 1 "$LPY" "$J/record_one.py" < "$J/runlist.txt" > "$J/logs/record.jsonl" 2> "$J/logs/record.err"
|
| 20 |
+
fi
|
| 21 |
+
"$LPY" "$J/audit_replays.py"
|
| 22 |
+
for prefix in delta legacy; do
|
| 23 |
+
if [ "$prefix" = delta ]; then
|
| 24 |
+
RAW=$BASE/raw_local,$BASE/raw
|
| 25 |
+
else
|
| 26 |
+
RAW=$BASE/legacy_raw_local,$BASE/legacy_raw
|
| 27 |
+
fi
|
| 28 |
+
"$EPY" "$L/scripts/lerobot_export.py" plan --work "$BASE/${prefix}_work" \
|
| 29 |
+
--raw "$RAW" --runs-root "$J/runs_index" --paper "$J/paper" \
|
| 30 |
+
--task-set "$L/sets/main_v2_1inst.txt" --repo-id "lffbench/${prefix}-backfill"
|
| 31 |
+
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"
|
| 32 |
+
"$EPY" "$L/scripts/lerobot_export.py" merge --work "$BASE/${prefix}_work" --nshards 24 --out "$BASE/${prefix}_dataset" > "$J/logs/merge_${prefix}.log" 2>&1
|
| 33 |
+
done
|
| 34 |
+
"$EPY" "$J/merge_cumulative.py" > "$J/logs/merge_cumulative.log" 2>&1
|
| 35 |
+
echo 'EXPORT COMPLETE; validation and publication pending'
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/backends/chat_completions.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""OpenAI-compatible Chat Completions backend (function calling), e.g. for a local open-source VLM served
|
| 2 |
+
by scripts/qwen_vl_server.py or any vLLM / SGLang endpoint. Same conversation, different wire format.
|
| 3 |
+
|
| 4 |
+
Reasoning models on this API (Kimi, DeepSeek, vLLM reasoning parsers) return their thinking as the non-standard
|
| 5 |
+
message field `reasoning_content`. It is logged as the reasoning summary and, with replay_reasoning (default), sent
|
| 6 |
+
back unchanged on that assistant message, so the model keeps its reasoning across tool calls like the Anthropic and
|
| 7 |
+
Responses backends do (Kimi's docs ask for this in multi-step tool use)."""
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
import time
|
| 11 |
+
|
| 12 |
+
from ..context import ToolCall, prune_live_images
|
| 13 |
+
from .base import Backend, BackendResponse, import_openai
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def chat_tools(specs):
|
| 17 |
+
return [dict(type="function", function=dict(name=s["name"], description=s["description"],
|
| 18 |
+
parameters=s["parameters"])) for s in specs]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class ChatCompletionsBackend(Backend):
|
| 22 |
+
name = "chat"
|
| 23 |
+
|
| 24 |
+
def __init__(self, model="qwen3-vl-8b", base_url=None, api_key=None, temperature=0.0, max_tokens=1024,
|
| 25 |
+
max_live_images=4, jpeg_quality=90, timeout=600.0, client=None, extra_body=None,
|
| 26 |
+
replay_reasoning=True):
|
| 27 |
+
self.model = model
|
| 28 |
+
self.base_url = base_url or os.environ.get("LFF_CHAT_BASE_URL", "http://127.0.0.1:8765/v1")
|
| 29 |
+
self.api_key = api_key or os.environ.get("LFF_CHAT_API_KEY", "EMPTY")
|
| 30 |
+
self.temperature = temperature
|
| 31 |
+
self.max_tokens = max_tokens
|
| 32 |
+
self.max_live_images = max_live_images
|
| 33 |
+
self.jpeg_quality = jpeg_quality
|
| 34 |
+
self.timeout = timeout
|
| 35 |
+
self.extra_body = extra_body
|
| 36 |
+
self.replay_reasoning = replay_reasoning
|
| 37 |
+
self._client = client
|
| 38 |
+
|
| 39 |
+
def config(self):
|
| 40 |
+
return dict(name=self.name, model=self.model, base_url=self.base_url, temperature=self.temperature,
|
| 41 |
+
max_tokens=self.max_tokens, max_live_images=self.max_live_images,
|
| 42 |
+
replay_reasoning=self.replay_reasoning)
|
| 43 |
+
|
| 44 |
+
def client(self):
|
| 45 |
+
if self._client is None:
|
| 46 |
+
openai = import_openai()
|
| 47 |
+
kw = dict(api_key=self.api_key, base_url=self.base_url, timeout=self.timeout, max_retries=1)
|
| 48 |
+
if any(h in self.base_url for h in ("://127.0.0.1", "://localhost")):
|
| 49 |
+
# local server: ignore the machine's proxy variables (ALL_PROXY=socks5h://... is set here)
|
| 50 |
+
kw["http_client"] = openai.DefaultHttpxClient(trust_env=False, timeout=self.timeout)
|
| 51 |
+
self._client = openai.OpenAI(**kw)
|
| 52 |
+
return self._client
|
| 53 |
+
|
| 54 |
+
def build_request(self, conv, tools):
|
| 55 |
+
msgs = [dict(role="system", content=conv.system)]
|
| 56 |
+
for it in prune_live_images(conv.items, self.max_live_images):
|
| 57 |
+
if it["kind"] == "user":
|
| 58 |
+
content = []
|
| 59 |
+
for p in it["parts"]:
|
| 60 |
+
if p["type"] == "text":
|
| 61 |
+
content.append(dict(type="text", text=p["text"]))
|
| 62 |
+
else:
|
| 63 |
+
content.append(dict(type="image_url", image_url=dict(url=p["image"].data_url(self.jpeg_quality))))
|
| 64 |
+
msgs.append(dict(role="user", content=content))
|
| 65 |
+
elif it["kind"] == "assistant":
|
| 66 |
+
if not it.get("text") and not it["tool_calls"]:
|
| 67 |
+
# a reasoning-only turn (no text, no tool call; seen with DeepSeek at effort=max): the player still
|
| 68 |
+
# counts it and nudges, but OpenAI-compatible APIs reject an assistant message with neither content
|
| 69 |
+
# nor tool_calls (DeepSeek: 400 "content or tool_calls must be set"), so it is left out of the request
|
| 70 |
+
continue
|
| 71 |
+
m = dict(role="assistant", content=it.get("text") or None)
|
| 72 |
+
rc = (it.get("raw") or [{}])[0].get("reasoning_content") if it.get("backend") == self.name else None
|
| 73 |
+
if rc and self.replay_reasoning:
|
| 74 |
+
m["reasoning_content"] = rc
|
| 75 |
+
if it["tool_calls"]:
|
| 76 |
+
m["tool_calls"] = [dict(id=tc.id, type="function",
|
| 77 |
+
function=dict(name=tc.name,
|
| 78 |
+
arguments=tc.raw_arguments or json.dumps(tc.arguments)))
|
| 79 |
+
for tc in it["tool_calls"]]
|
| 80 |
+
msgs.append(m)
|
| 81 |
+
elif it["kind"] == "tool_output":
|
| 82 |
+
msgs.append(dict(role="tool", tool_call_id=it["call_id"], content=it["text"]))
|
| 83 |
+
req = dict(model=self.model, messages=tool_results_first(msgs), tools=chat_tools(tools), tool_choice="auto",
|
| 84 |
+
max_tokens=self.max_tokens)
|
| 85 |
+
if self.temperature is not None: # None: the endpoint's default (reasoning models may reject a temperature)
|
| 86 |
+
req["temperature"] = self.temperature
|
| 87 |
+
if self.extra_body:
|
| 88 |
+
req["extra_body"] = dict(self.extra_body)
|
| 89 |
+
return req
|
| 90 |
+
|
| 91 |
+
def act(self, conv, tools):
|
| 92 |
+
req = self.build_request(conv, tools)
|
| 93 |
+
n_img = sum(1 for m in req["messages"] if isinstance(m.get("content"), list)
|
| 94 |
+
for c in m["content"] if c.get("type") == "image_url")
|
| 95 |
+
t0 = time.time()
|
| 96 |
+
resp = self.client().chat.completions.create(**req)
|
| 97 |
+
lat = time.time() - t0
|
| 98 |
+
stats = dict(n_images=n_img, n_messages=len(req["messages"]))
|
| 99 |
+
if not getattr(resp, "choices", None): # gateway hiccup: nothing to append, the player asks again
|
| 100 |
+
return BackendResponse(latency_s=lat, request_stats=stats, status="incomplete",
|
| 101 |
+
error="empty response (no choices)")
|
| 102 |
+
msg = resp.choices[0].message
|
| 103 |
+
rc = getattr(msg, "reasoning_content", None) or (getattr(msg, "model_extra", None) or {}).get("reasoning_content")
|
| 104 |
+
calls = []
|
| 105 |
+
for i, tc in enumerate(msg.tool_calls or []):
|
| 106 |
+
raw = tc.function.arguments or ""
|
| 107 |
+
try:
|
| 108 |
+
args = json.loads(raw) if raw else {}
|
| 109 |
+
except json.JSONDecodeError:
|
| 110 |
+
args = {}
|
| 111 |
+
calls.append(ToolCall(id=tc.id or f"call_{i}", name=tc.function.name, arguments=args, raw_arguments=raw))
|
| 112 |
+
u = resp.usage
|
| 113 |
+
ctd = getattr(u, "completion_tokens_details", None) if u else None
|
| 114 |
+
usage = dict(input_tokens=getattr(u, "prompt_tokens", 0) or 0, cached_tokens=0,
|
| 115 |
+
output_tokens=getattr(u, "completion_tokens", 0) or 0,
|
| 116 |
+
reasoning_tokens=(getattr(ctd, "reasoning_tokens", 0) or 0) if ctd else 0) if u else {}
|
| 117 |
+
if not calls and not msg.content and not rc and not u:
|
| 118 |
+
return BackendResponse(latency_s=lat, request_stats=stats, status="incomplete",
|
| 119 |
+
error="empty response (no output, no usage)")
|
| 120 |
+
return BackendResponse(tool_calls=calls, text=msg.content or None, reasoning_summary=rc or None, usage=usage,
|
| 121 |
+
latency_s=lat, raw=[dict(reasoning_content=rc)] if rc else None, request_stats=stats)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def tool_results_first(msgs):
|
| 125 |
+
"""OpenAI-compatible APIs require every tool_call of an assistant message to be answered by tool messages directly
|
| 126 |
+
after it. The player adds the images a tool returned (view_images, robot) as a user message right after that tool's
|
| 127 |
+
output, so a turn with several tool calls (e.g. view_images then shell) would put a user message between the tool
|
| 128 |
+
messages (DeepSeek: 400 "insufficient tool messages following tool_calls message"). Move such user messages after
|
| 129 |
+
the last tool message of the turn; nothing else changes order."""
|
| 130 |
+
out, i = [], 0
|
| 131 |
+
while i < len(msgs):
|
| 132 |
+
m = msgs[i]
|
| 133 |
+
out.append(m)
|
| 134 |
+
i += 1
|
| 135 |
+
if m["role"] != "assistant" or not m.get("tool_calls"):
|
| 136 |
+
continue
|
| 137 |
+
need = {tc["id"] for tc in m["tool_calls"]}
|
| 138 |
+
held = []
|
| 139 |
+
while i < len(msgs) and need:
|
| 140 |
+
n = msgs[i]
|
| 141 |
+
if n["role"] == "tool" and n.get("tool_call_id") in need:
|
| 142 |
+
out.append(n)
|
| 143 |
+
need.discard(n["tool_call_id"])
|
| 144 |
+
elif n["role"] == "user":
|
| 145 |
+
held.append(n)
|
| 146 |
+
else:
|
| 147 |
+
break
|
| 148 |
+
i += 1
|
| 149 |
+
out.extend(held)
|
| 150 |
+
return out
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/fakeapi.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Local fake model APIs for offline harness checks (no real model, no cost).
|
| 2 |
+
|
| 3 |
+
Both servers listen on 127.0.0.1, record every request body (auth headers dropped) and answer from a script, so a
|
| 4 |
+
native harness can be driven turn by turn without a model:
|
| 5 |
+
FakeAnthropic Anthropic Messages API (streaming SSE), used by Claude Code and by api_player --provider anthropic
|
| 6 |
+
FakeResponses OpenAI Responses API (streaming SSE), used by Codex through a custom model provider
|
| 7 |
+
|
| 8 |
+
A script is a list of turns; turn i is answered to the request that already holds i assistant turns, so retries get
|
| 9 |
+
the same answer. Past the end of the script the server answers with a final text. A turn is a list of steps:
|
| 10 |
+
("tool", name, args) Anthropic: tool_use block (name as given, e.g. "mcp__lff__robot" or "Read")
|
| 11 |
+
("text", s) a text block / assistant message
|
| 12 |
+
("exec", js) Responses: one `exec` custom tool call (Codex code mode) with this JavaScript
|
| 13 |
+
("fcall", name, args) Responses: a plain function call
|
| 14 |
+
("nscall", ns, name, args) Responses: a function call into a tool namespace (Codex without code mode calls our MCP
|
| 15 |
+
tools this way: name "robot", namespace "mcp__lff"; measured with 0.163)
|
| 16 |
+
|
| 17 |
+
srv = FakeAnthropic(script, record_dir).start(); ... srv.base_url ...; srv.stop()
|
| 18 |
+
"""
|
| 19 |
+
import itertools
|
| 20 |
+
import json
|
| 21 |
+
import os
|
| 22 |
+
import threading
|
| 23 |
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
| 24 |
+
|
| 25 |
+
DROP_HEADERS = ("x-api-key", "authorization", "cookie", "chatgpt-account-id")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class _Base:
|
| 29 |
+
final_text = "done"
|
| 30 |
+
|
| 31 |
+
def __init__(self, script=None, record_dir=None, port=0):
|
| 32 |
+
self.script = list(script or [])
|
| 33 |
+
self.record_dir = record_dir
|
| 34 |
+
self.port = port
|
| 35 |
+
self.lock = threading.Lock()
|
| 36 |
+
self.counter = itertools.count(1)
|
| 37 |
+
self.requests = [] # (n, path, body)
|
| 38 |
+
if record_dir:
|
| 39 |
+
os.makedirs(record_dir, exist_ok=True)
|
| 40 |
+
|
| 41 |
+
# ------------------------------------------------------------------ plumbing
|
| 42 |
+
def start(self):
|
| 43 |
+
outer = self
|
| 44 |
+
|
| 45 |
+
class H(BaseHTTPRequestHandler):
|
| 46 |
+
protocol_version = "HTTP/1.1"
|
| 47 |
+
|
| 48 |
+
def log_message(self, *a):
|
| 49 |
+
pass
|
| 50 |
+
|
| 51 |
+
def _record(self, body):
|
| 52 |
+
with outer.lock:
|
| 53 |
+
n = next(outer.counter)
|
| 54 |
+
outer.requests.append((n, self.path, body))
|
| 55 |
+
if outer.record_dir:
|
| 56 |
+
with open(os.path.join(outer.record_dir, f"req_{n:03d}.json"), "w") as f:
|
| 57 |
+
json.dump(dict(method=self.command, path=self.path, body=body,
|
| 58 |
+
headers={k: v for k, v in self.headers.items() if k.lower() not in DROP_HEADERS}),
|
| 59 |
+
f, indent=1, ensure_ascii=False)
|
| 60 |
+
return n
|
| 61 |
+
|
| 62 |
+
def do_GET(self):
|
| 63 |
+
self._record(None)
|
| 64 |
+
self._send(404, b"{}", "application/json")
|
| 65 |
+
|
| 66 |
+
def do_HEAD(self):
|
| 67 |
+
self._send(404, b"", "application/json")
|
| 68 |
+
|
| 69 |
+
def do_POST(self):
|
| 70 |
+
raw = self.rfile.read(int(self.headers.get("content-length", 0) or 0))
|
| 71 |
+
try:
|
| 72 |
+
body = json.loads(raw)
|
| 73 |
+
except ValueError:
|
| 74 |
+
body = raw[:4000].decode("utf-8", "replace")
|
| 75 |
+
n = self._record(body)
|
| 76 |
+
outer.handle(self, n, body)
|
| 77 |
+
|
| 78 |
+
def _send(self, code, data, ctype):
|
| 79 |
+
self.send_response(code)
|
| 80 |
+
self.send_header("content-type", ctype)
|
| 81 |
+
self.send_header("content-length", str(len(data)))
|
| 82 |
+
self.end_headers()
|
| 83 |
+
self.wfile.write(data)
|
| 84 |
+
|
| 85 |
+
self.httpd = ThreadingHTTPServer(("127.0.0.1", self.port), H)
|
| 86 |
+
self.httpd.daemon_threads = True
|
| 87 |
+
self.port = self.httpd.server_address[1]
|
| 88 |
+
threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
|
| 89 |
+
return self
|
| 90 |
+
|
| 91 |
+
def stop(self):
|
| 92 |
+
self.httpd.shutdown()
|
| 93 |
+
self.httpd.server_close()
|
| 94 |
+
|
| 95 |
+
def turn(self, i):
|
| 96 |
+
return self.script[i] if i < len(self.script) else [("text", self.final_text)]
|
| 97 |
+
|
| 98 |
+
@staticmethod
|
| 99 |
+
def send_sse(h, events):
|
| 100 |
+
data = b"".join(f"event: {ev}\ndata: {json.dumps(d)}\n\n".encode() for ev, d in events)
|
| 101 |
+
h._send(200, data, "text/event-stream")
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class FakeAnthropic(_Base):
|
| 105 |
+
@property
|
| 106 |
+
def base_url(self):
|
| 107 |
+
return f"http://127.0.0.1:{self.port}"
|
| 108 |
+
|
| 109 |
+
def handle(self, h, n, body):
|
| 110 |
+
if not h.path.startswith("/v1/messages") or "count_tokens" in h.path or not isinstance(body, dict):
|
| 111 |
+
h._send(200, json.dumps({"input_tokens": 10}).encode(), "application/json")
|
| 112 |
+
return
|
| 113 |
+
msgs = body.get("messages", [])
|
| 114 |
+
i = sum(1 for m in msgs if m.get("role") == "assistant")
|
| 115 |
+
steps = self.turn(i)
|
| 116 |
+
blocks = []
|
| 117 |
+
for j, st in enumerate(steps):
|
| 118 |
+
if st[0] == "tool":
|
| 119 |
+
blocks.append(dict(type="tool_use", id=f"toolu_fake_{i:03d}_{j}", name=st[1], input=st[2]))
|
| 120 |
+
else:
|
| 121 |
+
blocks.append(dict(type="text", text=st[1]))
|
| 122 |
+
stop = "tool_use" if any(b["type"] == "tool_use" for b in blocks) else "end_turn"
|
| 123 |
+
model = body.get("model", "fake")
|
| 124 |
+
evs = [("message_start", dict(type="message_start", message=dict(
|
| 125 |
+
id=f"msg_fake_{n}", type="message", role="assistant", model=model, content=[], stop_reason=None,
|
| 126 |
+
stop_sequence=None, usage=dict(input_tokens=100, output_tokens=1))))]
|
| 127 |
+
for k, b in enumerate(blocks):
|
| 128 |
+
if b["type"] == "tool_use":
|
| 129 |
+
evs.append(("content_block_start", dict(type="content_block_start", index=k, content_block=dict(
|
| 130 |
+
type="tool_use", id=b["id"], name=b["name"], input={}))))
|
| 131 |
+
evs.append(("content_block_delta", dict(type="content_block_delta", index=k, delta=dict(
|
| 132 |
+
type="input_json_delta", partial_json=json.dumps(b["input"])))))
|
| 133 |
+
else:
|
| 134 |
+
evs.append(("content_block_start", dict(type="content_block_start", index=k,
|
| 135 |
+
content_block=dict(type="text", text=""))))
|
| 136 |
+
evs.append(("content_block_delta", dict(type="content_block_delta", index=k,
|
| 137 |
+
delta=dict(type="text_delta", text=b["text"]))))
|
| 138 |
+
evs.append(("content_block_stop", dict(type="content_block_stop", index=k)))
|
| 139 |
+
evs.append(("message_delta", dict(type="message_delta", delta=dict(stop_reason=stop, stop_sequence=None),
|
| 140 |
+
usage=dict(output_tokens=5))))
|
| 141 |
+
evs.append(("message_stop", dict(type="message_stop")))
|
| 142 |
+
self.send_sse(h, evs)
|
| 143 |
+
|
| 144 |
+
def message_requests(self):
|
| 145 |
+
return [(n, b) for n, p, b in self.requests if isinstance(b, dict) and p.startswith("/v1/messages")
|
| 146 |
+
and "count_tokens" not in p]
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class FakeResponses(_Base):
|
| 150 |
+
@property
|
| 151 |
+
def base_url(self):
|
| 152 |
+
return f"http://127.0.0.1:{self.port}/v1"
|
| 153 |
+
|
| 154 |
+
def handle(self, h, n, body):
|
| 155 |
+
if not isinstance(body, dict) or "input" not in body:
|
| 156 |
+
h._send(404, b"{}", "application/json")
|
| 157 |
+
return
|
| 158 |
+
items = body.get("input") or []
|
| 159 |
+
i = sum(1 for it in items if isinstance(it, dict) and it.get("type") in
|
| 160 |
+
("custom_tool_call", "function_call") or (isinstance(it, dict) and it.get("type") == "message"
|
| 161 |
+
and it.get("role") == "assistant"))
|
| 162 |
+
steps = self.turn(i)
|
| 163 |
+
out = []
|
| 164 |
+
for j, st in enumerate(steps):
|
| 165 |
+
if st[0] == "exec":
|
| 166 |
+
out.append(dict(type="custom_tool_call", id=f"ctc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}",
|
| 167 |
+
name="exec", status="completed", input=st[1]))
|
| 168 |
+
elif st[0] == "fcall":
|
| 169 |
+
out.append(dict(type="function_call", id=f"fc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}",
|
| 170 |
+
name=st[1], arguments=json.dumps(st[2]), status="completed"))
|
| 171 |
+
elif st[0] == "nscall":
|
| 172 |
+
out.append(dict(type="function_call", id=f"fc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}",
|
| 173 |
+
namespace=st[1], name=st[2], arguments=json.dumps(st[3]), status="completed"))
|
| 174 |
+
else:
|
| 175 |
+
out.append(dict(type="message", id=f"msg_fake_{n}_{j}", role="assistant", status="completed",
|
| 176 |
+
content=[dict(type="output_text", text=st[1], annotations=[])]))
|
| 177 |
+
rid = f"resp_fake_{n}"
|
| 178 |
+
evs = [("response.created", dict(type="response.created", response=dict(id=rid, status="in_progress")))]
|
| 179 |
+
for k, it in enumerate(out):
|
| 180 |
+
evs.append(("response.output_item.done", dict(type="response.output_item.done", output_index=k, item=it)))
|
| 181 |
+
evs.append(("response.completed", dict(type="response.completed", response=dict(
|
| 182 |
+
id=rid, status="completed", output=out, usage=dict(
|
| 183 |
+
input_tokens=100, input_tokens_details=dict(cached_tokens=0), output_tokens=3,
|
| 184 |
+
output_tokens_details=dict(reasoning_tokens=0), total_tokens=103)))))
|
| 185 |
+
self.send_sse(h, evs)
|
| 186 |
+
|
| 187 |
+
def model_requests(self):
|
| 188 |
+
return [(n, b) for n, p, b in self.requests if isinstance(b, dict) and "input" in 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
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "dsh|0.2.1-rc.5|aa65546cc1f51674|deepseek-flash|high",
|
| 3 |
+
"fingerprint_sha256": "18044f5deb7b4d0d662d620fce120e85e3f94103fa2699346221fa46d093fc8f",
|
| 4 |
+
"written": "2026-10-31 06:05:50",
|
| 5 |
+
"summary": {
|
| 6 |
+
"system_chars": 109,
|
| 7 |
+
"tools": [
|
| 8 |
+
"mcp__lff__robot",
|
| 9 |
+
"mcp__lff__shell",
|
| 10 |
+
"mcp__lff__view_images"
|
| 11 |
+
],
|
| 12 |
+
"effort_in_request": "high",
|
| 13 |
+
"model_in_request": "deepseek-flash"
|
| 14 |
+
}
|
| 15 |
+
}
|
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
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "rpent_codex-generic-9f0e3aafc10c|0.163.0|399ff69c431c066e|gpt-6.1-sol|high",
|
| 3 |
+
"fingerprint_sha256": "6e63c24ad13895ebfbb0bc76a17ebbdc9765414a3f4351fe442480afa50b5ce9",
|
| 4 |
+
"written": "2026-10-24 07:27:13",
|
| 5 |
+
"summary": {
|
| 6 |
+
"developer_chars": 16979,
|
| 7 |
+
"top_tools": [
|
| 8 |
+
"list_mcp_resource_templates",
|
| 9 |
+
"list_mcp_resources",
|
| 10 |
+
"mcp__lff.robot",
|
| 11 |
+
"mcp__lff.shell",
|
| 12 |
+
"mcp__lff.view_images",
|
| 13 |
+
"read_mcp_resource",
|
| 14 |
+
"request_user_input"
|
| 15 |
+
],
|
| 16 |
+
"effort_in_request": "high",
|
| 17 |
+
"model_in_request": "gpt-6.1-sol",
|
| 18 |
+
"sandbox": {
|
| 19 |
+
"sandbox": "seccomp",
|
| 20 |
+
"sandbox_mode": "read-only"
|
| 21 |
+
},
|
| 22 |
+
"middle_fingerprint_sha256": "3dc06d7d7d7c5fb03c550905ba2d16faecefde695afc17f1f9f77da16c376e8c",
|
| 23 |
+
"rpent_prefix_sha256": "f0d0e0a62990cb7028bfb3889e49423b12635347aaddbda40e4d2fc4cb408e25",
|
| 24 |
+
"rpent_prefix_chars": 2789,
|
| 25 |
+
"anchor_status": "match"
|
| 26 |
+
}
|
| 27 |
+
}
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/real/executor.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""RealToolExecutor: the real-robot counterpart of lffbench.agent.tools.ToolExecutor.
|
| 2 |
+
|
| 3 |
+
robot_server's LA interface needs only this from its executor: observe(label) -> [ImageRef], proprio() -> dict, and
|
| 4 |
+
call("move_to" | "open_gripper" | "close_gripper", args) -> ToolResult. Here every call goes to a robot driver
|
| 5 |
+
(lffbench/real/protocol.py) instead of the simulator.
|
| 6 |
+
|
| 7 |
+
Calibration bias (L1 tasks), as Skills / ToolExecutor do it in simulation: the driver is sent commanded + bias and
|
| 8 |
+
reports the true pose; the agent is told true - bias (what a miscalibrated robot believes). Joint angles are then the
|
| 9 |
+
ones that put the grasp point at the believed pose (driver /ik), as robot_server._believed_joints does in simulation.
|
| 10 |
+
"""
|
| 11 |
+
import math
|
| 12 |
+
import time
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
|
| 16 |
+
from ..agent.images import ImageRef
|
| 17 |
+
from ..agent.tools import ToolResult, parse_args
|
| 18 |
+
from .protocol import CAMERAS, DriverError, square_resize, state_problems
|
| 19 |
+
|
| 20 |
+
SPEED_MIN = 0.01 # m/s; below this a straight-line move takes too long to be useful
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _r(v, nd=4):
|
| 24 |
+
return [round(float(x), nd) for x in v]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class RealToolExecutor:
|
| 28 |
+
def __init__(self, driver, info, bias=None, image_res=512, cams=CAMERAS):
|
| 29 |
+
self.driver, self.info = driver, info
|
| 30 |
+
self.bias = np.zeros(3) if bias is None else np.asarray(bias, float)
|
| 31 |
+
self.image_res = int(image_res)
|
| 32 |
+
self.cams = tuple(cams)
|
| 33 |
+
self.n_joints = int(info["n_joints"])
|
| 34 |
+
self.yaw_lo, self.yaw_hi = (float(v) for v in info["yaw_range_deg"])
|
| 35 |
+
self.max_speed = float(info["max_speed"])
|
| 36 |
+
self.motion_s = 0.0 # robot motion time of this executor (= this attempt), as reported by the driver
|
| 37 |
+
self.n_calls = 0
|
| 38 |
+
self._state = None
|
| 39 |
+
self.grip_closed = False # last gripper command of this attempt (the driver's home pose has it open)
|
| 40 |
+
self.yaw_cmd = None # last commanded yaw (degrees), for choosing among the gripper-symmetric equivalents
|
| 41 |
+
self.refresh()
|
| 42 |
+
self.yaw_cmd = float(self._state["eef_yaw_deg"])
|
| 43 |
+
|
| 44 |
+
# ------------------------------------------------------------------ state
|
| 45 |
+
def _set_state(self, st):
|
| 46 |
+
prob = state_problems(st, self.n_joints)
|
| 47 |
+
if prob:
|
| 48 |
+
raise DriverError("driver state: " + "; ".join(prob))
|
| 49 |
+
self._state = st
|
| 50 |
+
|
| 51 |
+
def refresh(self):
|
| 52 |
+
self._set_state(self.driver.state())
|
| 53 |
+
|
| 54 |
+
def true_eef(self):
|
| 55 |
+
return np.asarray(self._state["eef_pos"], float)
|
| 56 |
+
|
| 57 |
+
def believed_eef(self):
|
| 58 |
+
return self.true_eef() - self.bias
|
| 59 |
+
|
| 60 |
+
def proprio(self):
|
| 61 |
+
st = self._state
|
| 62 |
+
return dict(eef_pos=_r(self.believed_eef()), eef_yaw_deg=round(float(st["eef_yaw_deg"]), 1),
|
| 63 |
+
gripper="closed" if self.grip_closed else "open",
|
| 64 |
+
gripper_width_m=round(float(st["gripper_width_m"]), 4))
|
| 65 |
+
|
| 66 |
+
def joints(self):
|
| 67 |
+
"""Joint angles as the robot's encoders would report them under the hidden calibration error."""
|
| 68 |
+
if not np.any(self.bias):
|
| 69 |
+
return [float(v) for v in self._state["joint_pos_rad"]]
|
| 70 |
+
key = (tuple(self._state["eef_pos"]), float(self._state["eef_yaw_deg"]))
|
| 71 |
+
if getattr(self, "_ik_key", None) != key: # one /ik per new state (the server asks several times per command)
|
| 72 |
+
self._ik_key = key
|
| 73 |
+
self._ik_val = [float(v) for v in self.driver.ik(self.believed_eef(), key[1])]
|
| 74 |
+
return list(self._ik_val)
|
| 75 |
+
|
| 76 |
+
def observe(self, label=""):
|
| 77 |
+
frames, st = self.driver.observe()
|
| 78 |
+
self._set_state(st)
|
| 79 |
+
return [ImageRef(camera=c, array=square_resize(frames[c], self.image_res), label=f"{label} {c}".strip())
|
| 80 |
+
for c in self.cams]
|
| 81 |
+
|
| 82 |
+
# ------------------------------------------------------------------ helpers
|
| 83 |
+
def wrap_yaw(self, yaw):
|
| 84 |
+
"""The two-finger gripper is symmetric: among yaw + k*180 inside the driver's yaw range, use the one closest to
|
| 85 |
+
the last commanded yaw (Skills.wrap_yaw does the same with its +-113 deg limit)."""
|
| 86 |
+
cands = [yaw + 180.0 * k for k in range(-3, 4)]
|
| 87 |
+
ok = [c for c in cands if self.yaw_lo <= c <= self.yaw_hi] or cands
|
| 88 |
+
return float(min(ok, key=lambda c: abs(c - self.yaw_cmd)))
|
| 89 |
+
|
| 90 |
+
# ------------------------------------------------------------------ dispatch (same signature as ToolExecutor.call)
|
| 91 |
+
def call(self, name, raw_args):
|
| 92 |
+
t0 = time.time()
|
| 93 |
+
self.n_calls += 1
|
| 94 |
+
args = parse_args(raw_args)
|
| 95 |
+
fn = getattr(self, f"_t_{name}", None)
|
| 96 |
+
if fn is None:
|
| 97 |
+
return ToolResult(name, args, False, dict(ok=False, error=f"unknown tool {name!r}"), wall_s=time.time() - t0)
|
| 98 |
+
res = fn(**args)
|
| 99 |
+
res.args, res.wall_s = args, time.time() - t0
|
| 100 |
+
return res
|
| 101 |
+
|
| 102 |
+
def _report(self, name, extra=None):
|
| 103 |
+
rep = dict(ok=True, tool=name)
|
| 104 |
+
rep.update(extra or {})
|
| 105 |
+
rep.update(self.proprio())
|
| 106 |
+
return rep
|
| 107 |
+
|
| 108 |
+
def _t_move_to(self, x, y, z, yaw, speed=None):
|
| 109 |
+
tgt = np.array([x, y, z], float)
|
| 110 |
+
if not np.all(np.isfinite(tgt)):
|
| 111 |
+
return ToolResult("move_to", {}, False, dict(ok=False, error="non-finite coordinates"))
|
| 112 |
+
spd = None if speed is None else float(np.clip(float(speed), SPEED_MIN, self.max_speed))
|
| 113 |
+
yaw_used = self.wrap_yaw(float(yaw))
|
| 114 |
+
cmd = tgt + self.bias # the hidden calibration error acts on every commanded position
|
| 115 |
+
rep = self.driver.move(cmd[0], cmd[1], cmd[2], yaw_used, spd)
|
| 116 |
+
self.motion_s += float(rep.get("motion_s") or 0.0)
|
| 117 |
+
self._set_state(rep["state"])
|
| 118 |
+
if not rep["ok"]: # rejected before moving (driver hard limits / no IK solution)
|
| 119 |
+
return ToolResult("move_to", {}, False, dict(ok=False, error="target rejected: the arm cannot reach it; "
|
| 120 |
+
"the arm did not move", driver_error=rep.get("error", "")))
|
| 121 |
+
self.yaw_cmd = yaw_used
|
| 122 |
+
reached = bool(np.linalg.norm(cmd - self.true_eef()) < 0.02)
|
| 123 |
+
return ToolResult("move_to", {}, True, self._report("move_to", dict(reached=reached,
|
| 124 |
+
yaw_used_deg=round(yaw_used, 1))))
|
| 125 |
+
|
| 126 |
+
def _gripper(self, close):
|
| 127 |
+
rep = self.driver.gripper(close)
|
| 128 |
+
self.grip_closed = bool(close)
|
| 129 |
+
self.motion_s += float(rep.get("motion_s") or 0.0)
|
| 130 |
+
self._set_state(rep["state"])
|
| 131 |
+
name = "close_gripper" if close else "open_gripper"
|
| 132 |
+
return ToolResult(name, {}, True, self._report(name))
|
| 133 |
+
|
| 134 |
+
def _t_open_gripper(self):
|
| 135 |
+
return self._gripper(False)
|
| 136 |
+
|
| 137 |
+
def _t_close_gripper(self):
|
| 138 |
+
return self._gripper(True)
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/client/lffbench_client/__init__.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LFF-Bench Python client: the three agent tools of one episode, for any robot harness framework (docs/18 §6.3).
|
| 2 |
+
|
| 3 |
+
Only the standard library; it never imports the simulator. It talks to the episode's tool gateway
|
| 4 |
+
(scripts/tool_gateway.py), which runs next to the robot server and owns the per-attempt tool-call budget, the jailed
|
| 5 |
+
shell and the workspace images. A framework registers the three tools with the schemas from tool_specs() and calls
|
| 6 |
+
them through a Session:
|
| 7 |
+
|
| 8 |
+
from lffbench_client import Session
|
| 9 |
+
s = Session.from_env() # LFF_GATEWAY_URL, LFF_GATEWAY_TOKEN (set by the launcher)
|
| 10 |
+
first = s.first_message() # README + first status, as every harness gets it
|
| 11 |
+
tools = s.tool_specs("openai_responses") # or raw / mcp / anthropic / openai_chat
|
| 12 |
+
r = s.robot("move_eef x=0.5 y=0.0 z=0.2") # -> ToolResult
|
| 13 |
+
r.json() # the robot server's reply as a dict
|
| 14 |
+
s.view_images(["obs/s001_agentview.jpg"]).images # [(mime, bytes)]
|
| 15 |
+
|
| 16 |
+
A ToolResult's content is the list a model should see, in MCP form (text items and base64 image items); finished
|
| 17 |
+
says that the episode is over (stop calling tools). Nothing here can reset the scene or read the verdict: the only
|
| 18 |
+
feedback is what the robot server writes into the tool results.
|
| 19 |
+
"""
|
| 20 |
+
import base64
|
| 21 |
+
import dataclasses
|
| 22 |
+
import json
|
| 23 |
+
import os
|
| 24 |
+
import urllib.error
|
| 25 |
+
import urllib.parse
|
| 26 |
+
import urllib.request
|
| 27 |
+
|
| 28 |
+
__all__ = ["Session", "ToolResult", "GatewayError", "STYLES"]
|
| 29 |
+
__version__ = "0.1.0"
|
| 30 |
+
|
| 31 |
+
STYLES = ("raw", "mcp", "anthropic", "openai_responses", "openai_chat")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class GatewayError(RuntimeError):
|
| 35 |
+
pass
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@dataclasses.dataclass
|
| 39 |
+
class ToolResult:
|
| 40 |
+
content: list # [{"type": "text", "text"} | {"type": "image", "mimeType", "data" (base64)}]
|
| 41 |
+
is_error: bool
|
| 42 |
+
finished: bool # the episode is over: stop calling tools and report
|
| 43 |
+
calls_in_attempt: int # tool calls used in the current attempt (after an automatic finish: 0)
|
| 44 |
+
|
| 45 |
+
@property
|
| 46 |
+
def text(self):
|
| 47 |
+
"""All text items, joined by newlines."""
|
| 48 |
+
return "\n".join(c["text"] for c in self.content if c.get("type") == "text")
|
| 49 |
+
|
| 50 |
+
def json(self):
|
| 51 |
+
"""The first text item parsed as JSON (robot / shell / view_images replies are JSON objects)."""
|
| 52 |
+
for c in self.content:
|
| 53 |
+
if c.get("type") == "text":
|
| 54 |
+
return json.loads(c["text"])
|
| 55 |
+
raise ValueError("no text item")
|
| 56 |
+
|
| 57 |
+
@property
|
| 58 |
+
def images(self):
|
| 59 |
+
"""[(mime type, bytes)] of the image items."""
|
| 60 |
+
return [(c["mimeType"], base64.b64decode(c["data"])) for c in self.content if c.get("type") == "image"]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class Session:
|
| 64 |
+
"""One episode's tools through its gateway. face labels this access path in the gateway transcript."""
|
| 65 |
+
|
| 66 |
+
def __init__(self, url, token, face="sdk", timeout_s=900.0):
|
| 67 |
+
self.url, self.token, self.face, self.timeout_s = url.rstrip("/"), token, face, timeout_s
|
| 68 |
+
self._opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) # loopback: never via a proxy
|
| 69 |
+
|
| 70 |
+
@classmethod
|
| 71 |
+
def from_env(cls, face="sdk", **kw):
|
| 72 |
+
url, token = os.environ.get("LFF_GATEWAY_URL"), os.environ.get("LFF_GATEWAY_TOKEN")
|
| 73 |
+
if not url or not token:
|
| 74 |
+
raise GatewayError("LFF_GATEWAY_URL / LFF_GATEWAY_TOKEN are not set")
|
| 75 |
+
return cls(url, token, face=face, **kw)
|
| 76 |
+
|
| 77 |
+
@classmethod
|
| 78 |
+
def from_gateway_file(cls, path, face="sdk", **kw):
|
| 79 |
+
"""gateway.json written by the gateway in the run's log dir (launchers only; harness processes get env vars)."""
|
| 80 |
+
d = json.load(open(path))
|
| 81 |
+
return cls(d["url"], d["token"], face=face, **kw)
|
| 82 |
+
|
| 83 |
+
# ------------------------------------------------------------------------------------------------ http
|
| 84 |
+
def _request(self, method, path, body=None):
|
| 85 |
+
req = urllib.request.Request(self.url + path, method=method,
|
| 86 |
+
data=None if body is None else json.dumps(body).encode(),
|
| 87 |
+
headers={"Authorization": f"Bearer {self.token}", "X-LFF-Face": self.face,
|
| 88 |
+
"Content-Type": "application/json"})
|
| 89 |
+
try:
|
| 90 |
+
with self._opener.open(req, timeout=self.timeout_s) as r:
|
| 91 |
+
return r.read(), r.headers.get("Content-Type", "")
|
| 92 |
+
except urllib.error.HTTPError as e:
|
| 93 |
+
raise GatewayError(f"{method} {path}: HTTP {e.code}: {e.read()[:500].decode('utf-8', 'replace')}") from None
|
| 94 |
+
except urllib.error.URLError as e:
|
| 95 |
+
raise GatewayError(f"{method} {path}: {e.reason}") from None
|
| 96 |
+
|
| 97 |
+
def _get_json(self, path):
|
| 98 |
+
return json.loads(self._request("GET", path)[0])
|
| 99 |
+
|
| 100 |
+
# ------------------------------------------------------------------------------------------------ tools
|
| 101 |
+
def call(self, name, arguments=None):
|
| 102 |
+
raw, _ = self._request("POST", "/tool", dict(name=name, arguments=arguments or {}))
|
| 103 |
+
d = json.loads(raw)
|
| 104 |
+
return ToolResult(content=d["content"], is_error=bool(d["is_error"]), finished=bool(d["finished"]),
|
| 105 |
+
calls_in_attempt=d.get("calls_in_attempt"))
|
| 106 |
+
|
| 107 |
+
def robot(self, command):
|
| 108 |
+
"""One robot command, exactly as in the instructions (e.g. 'status', 'move_eef x=0.5 z=0.2', 'finish ...')."""
|
| 109 |
+
return self.call("robot", dict(command=command))
|
| 110 |
+
|
| 111 |
+
def shell(self, command):
|
| 112 |
+
"""A bash command in the episode workspace (jailed: no network, nothing outside the workspace)."""
|
| 113 |
+
return self.call("shell", dict(command=command))
|
| 114 |
+
|
| 115 |
+
def view_images(self, paths):
|
| 116 |
+
"""Image files of the workspace (e.g. obs/s001_agentview.jpg); the images come back as image items."""
|
| 117 |
+
return self.call("view_images", dict(paths=list(paths)))
|
| 118 |
+
|
| 119 |
+
# ------------------------------------------------------------------------------------------------ instructions
|
| 120 |
+
def tool_specs(self, style="raw"):
|
| 121 |
+
"""The three tool schemas with the reference descriptions, in one of STYLES."""
|
| 122 |
+
if style not in STYLES:
|
| 123 |
+
raise ValueError(f"style must be one of {STYLES}")
|
| 124 |
+
return self._get_json("/tool_specs?style=" + urllib.parse.quote(style))["tools"]
|
| 125 |
+
|
| 126 |
+
def readme(self):
|
| 127 |
+
return self._request("GET", "/readme")[0].decode("utf-8")
|
| 128 |
+
|
| 129 |
+
def first_message(self):
|
| 130 |
+
"""Preamble + README + first status report: the first user message every harness gets."""
|
| 131 |
+
return self._request("GET", "/first_message")[0].decode("utf-8")
|
| 132 |
+
|
| 133 |
+
def health(self):
|
| 134 |
+
return self._get_json("/health")
|
| 135 |
+
|
| 136 |
+
def status(self):
|
| 137 |
+
"""robot_server's `status` for the framework's own loop (e.g. a "continue" nudge that names the attempt): not
|
| 138 |
+
a tool call of the model, not counted in the per-attempt budget. Never show it to the model as a tool result."""
|
| 139 |
+
return self._get_json("/status")
|
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
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "claude_code_full-oauth|2.1.267|0399c793ff571d59|claude-opus-5-5|high",
|
| 3 |
+
"fingerprint_sha256": "06d6245468d20e3550a7ea4b8b4e7d9eda296ae16915dffa1b5bd7d12066efa6",
|
| 4 |
+
"written": "2026-10-20 02:16:17",
|
| 5 |
+
"summary": {
|
| 6 |
+
"system_chars": 6048,
|
| 7 |
+
"tools": [
|
| 8 |
+
"mcp__lff__robot",
|
| 9 |
+
"mcp__lff__shell",
|
| 10 |
+
"mcp__lff__view_images"
|
| 11 |
+
],
|
| 12 |
+
"effort_in_request": "high",
|
| 13 |
+
"model_in_request": "claude-opus-5-5"
|
| 14 |
+
}
|
| 15 |
+
}
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/__init__.py
ADDED
|
File without changes
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/l2_restore_layout.py
ADDED
|
@@ -0,0 +1,502 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L2-B restore_layout: put the ketchup into the basket; every other item must stay exactly where it was.
|
| 2 |
+
|
| 3 |
+
Scene: the ketchup (upright) and three flat boxes (cream cheese, butter, chocolate pudding) stand on the bare
|
| 4 |
+
table in an irregular layout (random positions and yaws, no tray, no markers, no grid), the basket on the
|
| 5 |
+
robot's left. Nothing in the scene marks where an item "belongs": its original pose exists only in the
|
| 6 |
+
first frame.
|
| 7 |
+
|
| 8 |
+
Constructed L2 event (physical, continuous): the first time the ketchup is grasped and lifted 3 cm, the
|
| 9 |
+
neighbouring box (the "victim", a hidden variable) is knocked: it receives a velocity impulse away from the
|
| 10 |
+
ketchup (+-35 deg) and a spin, slides 9-14 cm over the table and comes to rest turned by 45-80 deg. It is
|
| 11 |
+
real MuJoCo motion over ~0.2 s (no teleport), so a video shows it sliding away. The main task itself still
|
| 12 |
+
succeeds; an agent that stops after it fails. To repair the side effect the agent has to put the victim
|
| 13 |
+
back where it was -- within 3 cm and 25 deg (mod 180, the boxes are symmetric) -- and that pose is only in
|
| 14 |
+
its memory of the start of the episode (the F2 text says *which* item is out of place, never where it was).
|
| 15 |
+
|
| 16 |
+
Protocol: within (one episode, no reset). Attempt 1 = the main task, every later attempt = one corrective
|
| 17 |
+
round chosen by the policy; the outcome (success + F2 text) is computed after each round.
|
| 18 |
+
|
| 19 |
+
Scripted references
|
| 20 |
+
oracle knows the victim: right after the main task it puts the victim back at its saved start pose.
|
| 21 |
+
naive main task, then done.
|
| 22 |
+
adaptive saves the start layout from the first frame (Save); after a failure reads from F2 which items are
|
| 23 |
+
out of place (Retrieve their saved poses) and puts them back (Utilize).
|
| 24 |
+
blind no history, no feedback: every later round redoes the main task (lifts the ketchup out of the
|
| 25 |
+
basket and puts it back, grasp jittered by 5 mm), like l2_knock_restore's blind.
|
| 26 |
+
nomem (extra control, not in the acceptance table) gets the F2 text but has no start frame: it knows
|
| 27 |
+
which box is out of place and guesses where to put it (random free spot within 15 cm, random yaw).
|
| 28 |
+
"""
|
| 29 |
+
import numpy as np
|
| 30 |
+
|
| 31 |
+
from .. import envs
|
| 32 |
+
from ..bddl import write_bddl
|
| 33 |
+
from ..task_base import LFFTask, register_task
|
| 34 |
+
|
| 35 |
+
TARGET = "ketchup_1"
|
| 36 |
+
BOXES = ("cream_cheese_1", "butter_1", "chocolate_pudding_1")
|
| 37 |
+
BASKET = "basket_1"
|
| 38 |
+
ITEMS = (TARGET,) + BOXES
|
| 39 |
+
|
| 40 |
+
# LIBERO basket (body frame = world frame at yaw 0), measured by the l2_knock_restore developer
|
| 41 |
+
BASKET_IN = 0.060 # half size of the inner floor
|
| 42 |
+
BASKET_RIM = 0.150 # rim height above the basket's lowest point
|
| 43 |
+
BASKET_FLOOR = 0.017 # floor top above the basket's lowest point
|
| 44 |
+
BASKET_OUT = 0.11 # conservative half size of the outer footprint (keep-out radius for the layout)
|
| 45 |
+
|
| 46 |
+
POS_TOL = 0.03 # success: box centre within 3 cm of its start
|
| 47 |
+
YAW_TOL = np.radians(25.0) # ... and long axis within 25 deg of its start (mod 180)
|
| 48 |
+
STILL_TOL = 0.02 # the knock only fires if the victim is still within 2 cm of its start
|
| 49 |
+
|
| 50 |
+
REGION = (-0.26, 0.06, -0.27, 0.10) # x0, x1, y0, y1 (world) for item centres
|
| 51 |
+
KNOCK_REGION = (-0.28, 0.08, -0.29, 0.12) # where the victim may come to rest
|
| 52 |
+
MAX_REACH = 0.70 # max horizontal distance of an item centre from the robot base
|
| 53 |
+
BASE_X = -0.66
|
| 54 |
+
R_BOX, R_KETCHUP = 0.046, 0.034 # footprint circumradii (boxes 8 x 4.3 cm; ketchup 5.7 x 3.7 cm)
|
| 55 |
+
GAP = 0.03 # free space between footprints (finger room)
|
| 56 |
+
SLIDE_K = 0.0522 # measured: slide distance [m] = SLIDE_K * v0^2 [m/s] for these boxes on the table
|
| 57 |
+
SPIN_W = 40.0 # rad/s, applied each control step until the target turn is reached
|
| 58 |
+
|
| 59 |
+
NAMES = {"ketchup_1": "ketchup", "cream_cheese_1": "cream cheese", "butter_1": "butter",
|
| 60 |
+
"chocolate_pudding_1": "chocolate pudding", BASKET: "basket"}
|
| 61 |
+
DESCR = {"ketchup_1": "red bottle", "cream_cheese_1": "blue box", "butter_1": "small orange box",
|
| 62 |
+
"chocolate_pudding_1": "brown box", BASKET: "wicker basket"}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _qz(a):
|
| 66 |
+
return np.array([np.cos(a / 2), 0.0, 0.0, np.sin(a / 2)])
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _wrap_half(a):
|
| 70 |
+
"""wrap an angle to [-pi/2, pi/2) (boxes and parallel grippers are symmetric under 180 deg)"""
|
| 71 |
+
return float((a + np.pi / 2) % np.pi - np.pi / 2)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _seg_dist(p, a, b):
|
| 75 |
+
"""distance from point p to segment a-b (2D)"""
|
| 76 |
+
p, a, b = (np.asarray(v, float) for v in (p, a, b))
|
| 77 |
+
ab = b - a
|
| 78 |
+
t = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0.0, 1.0)
|
| 79 |
+
return float(np.linalg.norm(p - (a + t * ab)))
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _in_rect(xy, r):
|
| 83 |
+
return r[0] <= xy[0] <= r[1] and r[2] <= xy[1] <= r[3]
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _reach_ok(xy):
|
| 87 |
+
return np.hypot(xy[0] - BASE_X, xy[1]) <= MAX_REACH
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
@register_task
|
| 91 |
+
class RestoreLayout(LFFTask):
|
| 92 |
+
name = "l2_restore_layout"
|
| 93 |
+
level = "L2"
|
| 94 |
+
category = "state_restoration"
|
| 95 |
+
capabilities = ("Perceive", "Save", "Retrieve", "Utilize")
|
| 96 |
+
protocol = "within"
|
| 97 |
+
max_attempts = 5
|
| 98 |
+
instruction = ("Put the ketchup into the basket. Every other item on the table must stay exactly where it "
|
| 99 |
+
"is now, in the same position and orientation.")
|
| 100 |
+
instruction_indirect = ("Put the red bottle into the wicker basket. Every other item on the table must stay "
|
| 101 |
+
"exactly where it is now, in the same position and orientation.")
|
| 102 |
+
knock_lift = 0.03 # trigger: ketchup grasped and lifted this far above its resting height
|
| 103 |
+
|
| 104 |
+
def __init__(self, cam_res=None):
|
| 105 |
+
super().__init__(cam_res)
|
| 106 |
+
# upright orientations (wxyz), fixed like in l2_knock_restore: the ketchup mesh is modelled lying down;
|
| 107 |
+
# basket and boxes are upright in their mesh frame
|
| 108 |
+
self.q_up = {n: np.array([1.0, 0.0, 0.0, 0.0]) for n in self.env.objects_dict}
|
| 109 |
+
self.q_up[TARGET] = np.array([0.5, 0.5, 0.5, 0.5])
|
| 110 |
+
self._inj = None
|
| 111 |
+
self.start = {}
|
| 112 |
+
self._home = None
|
| 113 |
+
# per-control-step monitor on env.step: also sees attempts driven by the agent harness
|
| 114 |
+
orig_step = self.env.step
|
| 115 |
+
|
| 116 |
+
def step(action):
|
| 117 |
+
ret = orig_step(action)
|
| 118 |
+
if self._inj is not None:
|
| 119 |
+
self._knock_step()
|
| 120 |
+
return ret
|
| 121 |
+
|
| 122 |
+
self.env.step = step
|
| 123 |
+
|
| 124 |
+
# ------------------------------------------------------------ scene
|
| 125 |
+
def make_bddl(self):
|
| 126 |
+
names = [*ITEMS, BASKET]
|
| 127 |
+
objs = []
|
| 128 |
+
for i, n in enumerate(names): # layout is overridden in apply_instance; regions only need to be valid
|
| 129 |
+
x0 = -0.30 + 0.13 * (i % 3)
|
| 130 |
+
y0 = -0.25 + 0.25 * (i // 3)
|
| 131 |
+
objs.append((n, n[:-2], f"r_{i}", (x0, y0, x0 + 0.02, y0 + 0.02)))
|
| 132 |
+
return write_bddl(self.name, self.instruction, objs)
|
| 133 |
+
|
| 134 |
+
def sample_instance(self, seed):
|
| 135 |
+
rng = np.random.default_rng(seed)
|
| 136 |
+
for _ in range(5000):
|
| 137 |
+
basket = np.array([rng.uniform(-0.08, 0.0), rng.uniform(0.25, 0.27)])
|
| 138 |
+
k = np.array([rng.uniform(-0.17, -0.03), rng.uniform(-0.14, -0.02)])
|
| 139 |
+
victim = str(rng.choice(BOXES))
|
| 140 |
+
others = [b for b in BOXES if b != victim]
|
| 141 |
+
a_v = rng.uniform(0, 2 * np.pi)
|
| 142 |
+
r_v = rng.uniform(R_BOX + R_KETCHUP + GAP, R_BOX + R_KETCHUP + GAP + 0.02)
|
| 143 |
+
pos = {TARGET: k, victim: k + r_v * np.array([np.cos(a_v), np.sin(a_v)])}
|
| 144 |
+
ok = _in_rect(pos[victim], REGION) and _reach_ok(pos[victim])
|
| 145 |
+
for o in others:
|
| 146 |
+
if not ok:
|
| 147 |
+
break
|
| 148 |
+
for _ in range(200):
|
| 149 |
+
p = np.array([rng.uniform(*REGION[:2]), rng.uniform(*REGION[2:])])
|
| 150 |
+
if not _reach_ok(p):
|
| 151 |
+
continue
|
| 152 |
+
if np.linalg.norm(p - k) < R_BOX + R_KETCHUP + GAP:
|
| 153 |
+
continue
|
| 154 |
+
if any(np.linalg.norm(p - pos[q]) < 2 * R_BOX + GAP for q in pos if q != TARGET):
|
| 155 |
+
continue
|
| 156 |
+
pos[o] = p
|
| 157 |
+
break
|
| 158 |
+
else:
|
| 159 |
+
ok = False
|
| 160 |
+
if not ok:
|
| 161 |
+
continue
|
| 162 |
+
if any(np.linalg.norm(pos[n] - basket) < BASKET_OUT + R_BOX + 0.02 for n in ITEMS):
|
| 163 |
+
continue
|
| 164 |
+
# the knock: away from the ketchup +-35 deg, 9-14 cm, turn 45-80 deg (random sign)
|
| 165 |
+
ang = a_v + rng.uniform(-np.radians(35), np.radians(35))
|
| 166 |
+
dist = rng.uniform(0.09, 0.14)
|
| 167 |
+
u = np.array([np.cos(ang), np.sin(ang)])
|
| 168 |
+
end = pos[victim] + dist * u
|
| 169 |
+
if not (_in_rect(end, KNOCK_REGION) and _reach_ok(end)):
|
| 170 |
+
continue
|
| 171 |
+
if np.linalg.norm(end - basket) < BASKET_OUT + R_BOX + 0.03:
|
| 172 |
+
continue
|
| 173 |
+
# the path and the resting spot keep clear of the other boxes (finger room around the victim too)
|
| 174 |
+
if any(_seg_dist(pos[o], pos[victim], end) < 2 * R_BOX + 0.01 for o in others):
|
| 175 |
+
continue
|
| 176 |
+
if any(np.linalg.norm(end - pos[o]) < 2 * R_BOX + GAP for o in others):
|
| 177 |
+
continue
|
| 178 |
+
if np.linalg.norm(end - k) < R_BOX + R_KETCHUP + GAP:
|
| 179 |
+
continue
|
| 180 |
+
turn = float(rng.choice([-1, 1]) * rng.uniform(np.radians(45), np.radians(80)))
|
| 181 |
+
return dict(seed=int(seed),
|
| 182 |
+
basket_xy=basket.round(4).tolist(),
|
| 183 |
+
xy={n: pos[n].round(4).tolist() for n in ITEMS},
|
| 184 |
+
yaw={**{b: float(rng.uniform(-np.pi / 2, np.pi / 2)) for b in BOXES},
|
| 185 |
+
TARGET: float(np.pi / 2 + rng.uniform(-0.3, 0.3))},
|
| 186 |
+
# hidden variables of the injected failure
|
| 187 |
+
victim=victim, knock_dir=float(ang), knock_dist=float(dist), knock_turn=turn,
|
| 188 |
+
knock_end=end.round(4).tolist())
|
| 189 |
+
raise RuntimeError("could not sample a layout")
|
| 190 |
+
|
| 191 |
+
def place(self, name, xy, yaw, surface_z=envs.TABLE_Z):
|
| 192 |
+
"""Teleport an object upright (yaw about world z) with its lowest point 2 mm above surface_z (reset only)."""
|
| 193 |
+
q = envs._quat_mul(_qz(yaw), self.q_up[name])
|
| 194 |
+
envs.set_obj_pose(self.env, name, [xy[0], xy[1], surface_z + 0.3], quat_wxyz=q)
|
| 195 |
+
self.env.sim.forward()
|
| 196 |
+
dz = envs.obj_min_z(self.env, name) - (surface_z + 0.002)
|
| 197 |
+
qa, _ = envs.free_joint_addr(self.env, name)
|
| 198 |
+
self.env.sim.data.qpos[qa + 2] -= dz
|
| 199 |
+
self.env.sim.forward()
|
| 200 |
+
|
| 201 |
+
def apply_instance(self, inst):
|
| 202 |
+
envs.scale_mass(self.env, BASKET, 2.0) # heavy enough not to be dragged by the gripper (as in l2_knock)
|
| 203 |
+
self.place(BASKET, inst["basket_xy"], 0.0)
|
| 204 |
+
for n in ITEMS:
|
| 205 |
+
self.place(n, inst["xy"][n], inst["yaw"][n])
|
| 206 |
+
self.env.sim.forward()
|
| 207 |
+
|
| 208 |
+
def reset_instance(self, inst, recorder=None):
|
| 209 |
+
self._inj = None
|
| 210 |
+
sk = super().reset_instance(inst, recorder)
|
| 211 |
+
self.start = {n: self.footprint(n) for n in ITEMS}
|
| 212 |
+
self._inj = dict(inst=inst, done=False, knocked=False, step=None, spin_left=0.0, spin_steps=0)
|
| 213 |
+
self._home = sk.eef_pos()
|
| 214 |
+
return sk
|
| 215 |
+
|
| 216 |
+
# ------------------------------------------------------------ measurements
|
| 217 |
+
def footprint(self, name):
|
| 218 |
+
"""Measured pose summary: AABB centre, yaw of the long horizontal axis, half sizes, z range.
|
| 219 |
+
Scripted policies use it as a stand-in for perception."""
|
| 220 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 221 |
+
lo, hi = np.full(3, np.inf), np.full(3, -np.inf)
|
| 222 |
+
best = None
|
| 223 |
+
for g in envs.obj_geom_ids(self.env, name):
|
| 224 |
+
R = d.geom_xmat[g].reshape(3, 3)
|
| 225 |
+
c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3]
|
| 226 |
+
e = np.abs(R) @ m.geom_aabb[g, 3:]
|
| 227 |
+
lo, hi = np.minimum(lo, c - e), np.maximum(hi, c + e)
|
| 228 |
+
vol = float(np.prod(m.geom_aabb[g, 3:]))
|
| 229 |
+
if best is None or vol > best[0]:
|
| 230 |
+
best = (vol, R, m.geom_aabb[g, 3:])
|
| 231 |
+
_, R, half = best
|
| 232 |
+
horiz = sorted([(half[k], R[:, k]) for k in range(3) if abs(R[2, k]) < 0.5], key=lambda t: -t[0])
|
| 233 |
+
ax = horiz[0][1] if horiz else np.array([1.0, 0.0, 0.0])
|
| 234 |
+
return dict(center=[float(v) for v in (lo + hi) / 2], yaw=float(np.arctan2(ax[1], ax[0])),
|
| 235 |
+
half_xy=[float(v) for v in ((hi - lo) / 2)[:2]], zmin=float(lo[2]), zmax=float(hi[2]))
|
| 236 |
+
|
| 237 |
+
def body_yaw(self, name):
|
| 238 |
+
R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3)
|
| 239 |
+
return float(np.arctan2(R[1, 0], R[0, 0]))
|
| 240 |
+
|
| 241 |
+
# ------------------------------------------------------------ failure injection (physical knock)
|
| 242 |
+
def _knock_step(self):
|
| 243 |
+
st = self._inj
|
| 244 |
+
if st["done"]:
|
| 245 |
+
if st["spin_steps"] > 0: # keep spinning until the target turn is reached (<= 6 control steps)
|
| 246 |
+
self._spin(st)
|
| 247 |
+
return
|
| 248 |
+
if self.sk is None:
|
| 249 |
+
return
|
| 250 |
+
if envs.obj_min_z(self.env, TARGET) < self.start[TARGET]["zmin"] + self.knock_lift:
|
| 251 |
+
return
|
| 252 |
+
if not self.sk.holding(TARGET):
|
| 253 |
+
return
|
| 254 |
+
st["done"] = True
|
| 255 |
+
inst = st["inst"]
|
| 256 |
+
v = inst["victim"]
|
| 257 |
+
if np.linalg.norm(np.array(self.footprint(v)["center"][:2]) - np.array(self.start[v]["center"][:2])) > STILL_TOL:
|
| 258 |
+
return # the victim was moved beforehand: nothing happens
|
| 259 |
+
qa, da = envs.free_joint_addr(self.env, v)
|
| 260 |
+
v0 = np.sqrt(inst["knock_dist"] / SLIDE_K)
|
| 261 |
+
dvec = np.array([np.cos(inst["knock_dir"]), np.sin(inst["knock_dir"])])
|
| 262 |
+
d = self.env.sim.data
|
| 263 |
+
d.qvel[da:da + 3] = [v0 * dvec[0], v0 * dvec[1], 0.0]
|
| 264 |
+
st.update(knocked=True, step=int(self.sk.n_steps), yaw0=self.body_yaw(v), spin_left=inst["knock_turn"],
|
| 265 |
+
spin_steps=6)
|
| 266 |
+
self._spin(st)
|
| 267 |
+
|
| 268 |
+
def _spin(self, st):
|
| 269 |
+
v = st["inst"]["victim"]
|
| 270 |
+
_, da = envs.free_joint_addr(self.env, v)
|
| 271 |
+
turned = _wrap_half(self.body_yaw(v) - st["yaw0"]) if abs(st["spin_left"]) < np.pi / 2 else 0.0
|
| 272 |
+
rest = st["spin_left"] - turned
|
| 273 |
+
st["spin_steps"] -= 1
|
| 274 |
+
if abs(rest) < np.radians(4) or np.sign(rest) != np.sign(st["spin_left"]):
|
| 275 |
+
st["spin_steps"] = 0
|
| 276 |
+
return
|
| 277 |
+
# measured: one control step at w rad/s turns these boxes by ~0.35-0.8 deg per rad/s; aim a bit short
|
| 278 |
+
w = float(np.clip(np.degrees(abs(rest)) / 0.6, 5.0, SPIN_W))
|
| 279 |
+
self.env.sim.data.qvel[da + 5] = np.sign(rest) * w
|
| 280 |
+
|
| 281 |
+
# ------------------------------------------------------------ outcome
|
| 282 |
+
def where_target(self):
|
| 283 |
+
"""'basket', 'gripper', 'table' or 'other' for the ketchup."""
|
| 284 |
+
f = self.footprint(TARGET)
|
| 285 |
+
c = np.array(f["center"])
|
| 286 |
+
if self.sk is not None and self.sk.holding(TARGET) and f["zmin"] > envs.TABLE_Z + 0.02:
|
| 287 |
+
return "gripper", f
|
| 288 |
+
bp = envs.obj_pos(self.env, BASKET)
|
| 289 |
+
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:
|
| 290 |
+
return "basket", f
|
| 291 |
+
if f["zmin"] < envs.TABLE_Z + 0.01:
|
| 292 |
+
return "table", f
|
| 293 |
+
return "other", f
|
| 294 |
+
|
| 295 |
+
def box_state(self, name):
|
| 296 |
+
"""Pose error of a box w.r.t. its start pose and where it is."""
|
| 297 |
+
f = self.footprint(name)
|
| 298 |
+
s = self.start[name]
|
| 299 |
+
c, c0 = np.array(f["center"][:2]), np.array(s["center"][:2])
|
| 300 |
+
dpos = float(np.linalg.norm(c - c0))
|
| 301 |
+
dyaw = _wrap_half(f["yaw"] - s["yaw"])
|
| 302 |
+
held = bool(self.sk is not None and self.sk.holding(name))
|
| 303 |
+
upright = envs.obj_upright_cos(self.env, name) > 0.9
|
| 304 |
+
on_table = f["zmin"] < envs.TABLE_Z + 0.01
|
| 305 |
+
bp = envs.obj_pos(self.env, BASKET)
|
| 306 |
+
loc = ("gripper" if held else
|
| 307 |
+
"basket" if np.all(np.abs(c - bp[:2]) <= BASKET_IN + 0.02) and not on_table else
|
| 308 |
+
"table" if on_table and upright else
|
| 309 |
+
"table_tipped" if on_table else "other")
|
| 310 |
+
ok = bool(loc == "table" and dpos <= POS_TOL and abs(dyaw) <= YAW_TOL)
|
| 311 |
+
return dict(ok=ok, loc=loc, dpos=dpos, dyaw=float(dyaw), center=f["center"], yaw=f["yaw"],
|
| 312 |
+
offset=(c - c0).tolist())
|
| 313 |
+
|
| 314 |
+
@staticmethod
|
| 315 |
+
def _offset_words(off, dyaw):
|
| 316 |
+
"""robot-centric words for a displacement (current - start) and turn (for the offset tier only)"""
|
| 317 |
+
parts = []
|
| 318 |
+
if abs(off[0]) >= 0.005:
|
| 319 |
+
parts.append(f"{100 * abs(off[0]):.0f} cm {'forward' if off[0] > 0 else 'backward'}")
|
| 320 |
+
if abs(off[1]) >= 0.005:
|
| 321 |
+
parts.append(f"{100 * abs(off[1]):.0f} cm to the {'left' if off[1] > 0 else 'right'}")
|
| 322 |
+
s = (" and ".join(parts) + " of its starting spot") if parts else "at its starting spot"
|
| 323 |
+
if abs(dyaw) >= np.radians(3):
|
| 324 |
+
s += f", turned {abs(np.degrees(dyaw)):.0f} deg {'counter-clockwise' if dyaw > 0 else 'clockwise'} (seen from above)"
|
| 325 |
+
return s
|
| 326 |
+
|
| 327 |
+
def _describe(self, tloc, boxes, names, offset=False):
|
| 328 |
+
tn = names[TARGET]
|
| 329 |
+
msgs = []
|
| 330 |
+
if tloc != "basket":
|
| 331 |
+
msgs.append({"gripper": f"The {tn} is still in the gripper, not in the basket.",
|
| 332 |
+
"table": f"The {tn} is on the table, not in the basket."}
|
| 333 |
+
.get(tloc, f"The {tn} is not in the basket."))
|
| 334 |
+
for n in BOXES:
|
| 335 |
+
b = boxes[n]
|
| 336 |
+
if b["ok"]:
|
| 337 |
+
continue
|
| 338 |
+
if b["loc"] == "gripper":
|
| 339 |
+
msgs.append(f"The {names[n]} is in the gripper; it must be back where it was at the start.")
|
| 340 |
+
continue
|
| 341 |
+
if b["loc"] == "basket":
|
| 342 |
+
msgs.append(f"The {names[n]} is in the basket; it must be back where it was at the start.")
|
| 343 |
+
continue
|
| 344 |
+
if b["loc"] == "table_tipped":
|
| 345 |
+
msgs.append(f"The {names[n]} has tipped over and is not where it was at the start.")
|
| 346 |
+
continue
|
| 347 |
+
if b["loc"] != "table":
|
| 348 |
+
msgs.append(f"The {names[n]} is not where it was at the start.")
|
| 349 |
+
continue
|
| 350 |
+
what = []
|
| 351 |
+
if b["dpos"] > POS_TOL:
|
| 352 |
+
what.append("position")
|
| 353 |
+
if abs(b["dyaw"]) > YAW_TOL:
|
| 354 |
+
what.append("orientation")
|
| 355 |
+
m = f"The {names[n]} is not where it was at the start ({' and '.join(what)} changed)."
|
| 356 |
+
if offset:
|
| 357 |
+
m += f" It is {self._offset_words(b['offset'], b['dyaw'])}."
|
| 358 |
+
msgs.append(m)
|
| 359 |
+
if not msgs:
|
| 360 |
+
msgs.append(f"The {tn} is in the basket and every other item is where it was at the start.")
|
| 361 |
+
return " ".join(msgs)
|
| 362 |
+
|
| 363 |
+
def outcome(self, inst):
|
| 364 |
+
envs.settle(self.env, 30)
|
| 365 |
+
tloc, tf = self.where_target()
|
| 366 |
+
boxes = {n: self.box_state(n) for n in BOXES}
|
| 367 |
+
moved = [n for n in BOXES if not boxes[n]["ok"]]
|
| 368 |
+
success = bool(tloc == "basket" and not moved)
|
| 369 |
+
return dict(success=success, target_loc=tloc, moved=moved,
|
| 370 |
+
boxes={n: dict(ok=b["ok"], loc=b["loc"], dpos=round(b["dpos"], 4),
|
| 371 |
+
dyaw_deg=round(float(np.degrees(b["dyaw"])), 1)) for n, b in boxes.items()},
|
| 372 |
+
knocked=bool(self._inj and self._inj["knocked"]),
|
| 373 |
+
detail=self._describe(tloc, boxes, NAMES),
|
| 374 |
+
detail_indirect=self._describe(tloc, boxes, DESCR),
|
| 375 |
+
detail_offset=self._describe(tloc, boxes, NAMES, offset=True))
|
| 376 |
+
|
| 377 |
+
def feedback(self, inst, out, level="F2", indirect=False, offset=False):
|
| 378 |
+
"""F0: nothing, F1: success flag, F2: which item is out of place (never where it was).
|
| 379 |
+
offset=True (ablation tier 'F2+offset'): also the displacement from the start pose in robot-centric
|
| 380 |
+
words -- this externalises the memory and is not the default."""
|
| 381 |
+
if level == "F2":
|
| 382 |
+
key = "detail_offset" if offset else ("detail_indirect" if indirect else "detail")
|
| 383 |
+
out = dict(out, detail=out.get(key, out["detail"]))
|
| 384 |
+
return super().feedback(inst, out, level)
|
| 385 |
+
|
| 386 |
+
# ------------------------------------------------------------ scripted motions (Skills.move_to / set_gripper only)
|
| 387 |
+
def go_home(self):
|
| 388 |
+
"""End of an attempt: lift the arm out of the camera's way."""
|
| 389 |
+
sk = self.sk
|
| 390 |
+
p = sk.eef_pos()
|
| 391 |
+
sk.move_to([p[0], p[1], max(p[2], self._home[2])])
|
| 392 |
+
sk.move_to(self._home)
|
| 393 |
+
|
| 394 |
+
def pick_place(self, name, dest_xy, support_z, dest_yaw=None, carry_z=1.10, clearance=0.006, fp=None,
|
| 395 |
+
travel_z=1.15):
|
| 396 |
+
"""Top-down pick of `name` at its (measured) footprint, carry at eef height `carry_z`, release with the
|
| 397 |
+
object bottom `clearance` above `support_z` at dest_xy; `dest_yaw` = desired yaw of the long axis."""
|
| 398 |
+
sk = self.sk
|
| 399 |
+
f = fp or self.footprint(name)
|
| 400 |
+
c = np.array(f["center"])
|
| 401 |
+
h = f["zmax"] - f["zmin"]
|
| 402 |
+
gyaw = _wrap_half(f["yaw"]) # fingers close along eef y (= world y at yaw 0): across the short side
|
| 403 |
+
if name == TARGET:
|
| 404 |
+
zg = f["zmax"] - 0.035
|
| 405 |
+
else:
|
| 406 |
+
zg = max(f["zmin"] + 0.5 * h, f["zmin"] + 0.0145) # finger tips reach ~1.3 cm below the grip site
|
| 407 |
+
sk.set_gripper(False, steps=6)
|
| 408 |
+
p = sk.eef_pos()
|
| 409 |
+
if p[2] < travel_z - 0.02:
|
| 410 |
+
sk.move_to([p[0], p[1], travel_z])
|
| 411 |
+
sk.move_to([c[0], c[1], travel_z], yaw=gyaw)
|
| 412 |
+
sk.move_to([c[0], c[1], f["zmax"] + 0.03], speed=0.4)
|
| 413 |
+
sk.move_to([c[0], c[1], zg], tol=0.003, max_steps=80)
|
| 414 |
+
sk.set_gripper(True, steps=12)
|
| 415 |
+
sk.move_to([c[0], c[1], carry_z], speed=0.3)
|
| 416 |
+
gyaw2 = gyaw if dest_yaw is None else gyaw + _wrap_half(dest_yaw - f["yaw"])
|
| 417 |
+
sk.move_to([dest_xy[0], dest_xy[1], carry_z], yaw=gyaw2)
|
| 418 |
+
sk.move_to([dest_xy[0], dest_xy[1], support_z + (zg - f["zmin"]) + clearance], tol=0.003, speed=0.2,
|
| 419 |
+
max_steps=150)
|
| 420 |
+
sk.hold(4)
|
| 421 |
+
sk.set_gripper(False, steps=10)
|
| 422 |
+
sk.move_to([dest_xy[0], dest_xy[1], travel_z], speed=0.4)
|
| 423 |
+
|
| 424 |
+
def main_task(self, fp=None):
|
| 425 |
+
"""Ketchup -> basket (the instruction, as an agent without failure knowledge would do it)."""
|
| 426 |
+
b = envs.obj_pos(self.env, BASKET)
|
| 427 |
+
floor = envs.obj_min_z(self.env, BASKET) + BASKET_FLOOR
|
| 428 |
+
self.pick_place(TARGET, b[:2], floor, carry_z=1.27, clearance=0.006, fp=fp)
|
| 429 |
+
|
| 430 |
+
def restore(self, name, pose):
|
| 431 |
+
"""Put box `name` back at `pose` (a remembered footprint: centre xy + long-axis yaw)."""
|
| 432 |
+
self.pick_place(name, pose["center"][:2], envs.TABLE_Z, dest_yaw=pose["yaw"], carry_z=1.05,
|
| 433 |
+
clearance=0.004)
|
| 434 |
+
|
| 435 |
+
def do(self, actions, inst):
|
| 436 |
+
for act in actions:
|
| 437 |
+
if act[0] == "ketchup_to_basket":
|
| 438 |
+
self.main_task(fp=act[1] if len(act) > 1 else None)
|
| 439 |
+
elif act[0] == "restore": # ["restore", name, pose]
|
| 440 |
+
self.restore(act[1], act[2])
|
| 441 |
+
else:
|
| 442 |
+
raise ValueError(act)
|
| 443 |
+
|
| 444 |
+
# ------------------------------------------------------------ scripted reference policies
|
| 445 |
+
def _guess_pose(self, name, rng):
|
| 446 |
+
"""nomem control: a random free spot within 15 cm of where the box is now, random yaw."""
|
| 447 |
+
cur = np.array(self.footprint(name)["center"][:2])
|
| 448 |
+
others = [np.array(self.footprint(o)["center"][:2]) for o in BOXES if o != name]
|
| 449 |
+
for _ in range(200):
|
| 450 |
+
r, a = rng.uniform(0.03, 0.15), rng.uniform(0, 2 * np.pi)
|
| 451 |
+
p = cur + r * np.array([np.cos(a), np.sin(a)])
|
| 452 |
+
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):
|
| 453 |
+
return dict(center=[float(p[0]), float(p[1]), 0.0], yaw=float(rng.uniform(-np.pi / 2, np.pi / 2)))
|
| 454 |
+
return dict(center=[float(cur[0]), float(cur[1]), 0.0], yaw=float(rng.uniform(-np.pi / 2, np.pi / 2)))
|
| 455 |
+
|
| 456 |
+
def _plan(self, kind, inst, a, history, rng, memory):
|
| 457 |
+
"""Actions of one round: ["ketchup_to_basket"] / ["restore", name, pose]."""
|
| 458 |
+
if kind == "naive" or (a == 0 and kind in ("adaptive", "blind", "nomem")):
|
| 459 |
+
return [["ketchup_to_basket"]]
|
| 460 |
+
if kind == "oracle": # knows the victim: restores it right after the main task (start pose from memory)
|
| 461 |
+
return [["ketchup_to_basket"], ["restore", inst["victim"], memory[inst["victim"]]]]
|
| 462 |
+
last = history[-1]["outcome"]
|
| 463 |
+
if kind == "adaptive": # F2 says which items are out of place; the saved first frame says where they were
|
| 464 |
+
acts = [] if last["target_loc"] == "basket" else [["ketchup_to_basket"]]
|
| 465 |
+
return acts + [["restore", n, memory[n]] for n in last["moved"]]
|
| 466 |
+
if kind == "nomem": # F2 but no start frame: guesses
|
| 467 |
+
acts = [] if last["target_loc"] == "basket" else [["ketchup_to_basket"]]
|
| 468 |
+
return acts + [["restore", n, self._guess_pose(n, rng)] for n in last["moved"]]
|
| 469 |
+
if kind == "blind": # ignores the outcome: redoes the main task (ketchup wherever it is now, jittered grasp)
|
| 470 |
+
fp = self.footprint(TARGET)
|
| 471 |
+
fp["center"] = (np.array(fp["center"]) + np.r_[rng.normal(0, 0.005, 2), 0.0]).tolist()
|
| 472 |
+
return [["ketchup_to_basket", fp]]
|
| 473 |
+
raise ValueError(kind)
|
| 474 |
+
|
| 475 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 476 |
+
"""Within-episode protocol: one reset, attempt 1 = main task, attempts 2..k = corrective rounds."""
|
| 477 |
+
k = k or self.max_attempts
|
| 478 |
+
rng = np.random.default_rng(seed)
|
| 479 |
+
history = []
|
| 480 |
+
self.reset_instance(inst)
|
| 481 |
+
memory = {n: dict(center=self.start[n]["center"], yaw=self.start[n]["yaw"]) for n in BOXES} # Save
|
| 482 |
+
for a in range(k):
|
| 483 |
+
actions = self._plan(kind, inst, a, history, rng, memory)
|
| 484 |
+
self.do(actions, inst)
|
| 485 |
+
self.go_home()
|
| 486 |
+
out = self.outcome(inst)
|
| 487 |
+
params = dict(actions=[x[:1] if x[0] == "ketchup_to_basket" else
|
| 488 |
+
[x[0], x[1], [round(v, 3) for v in x[2]["center"][:2]], round(float(x[2]["yaw"]), 3)]
|
| 489 |
+
for x in actions])
|
| 490 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 491 |
+
if on_attempt:
|
| 492 |
+
on_attempt(a, params, out)
|
| 493 |
+
if out["success"] or kind in ("oracle", "naive"):
|
| 494 |
+
break
|
| 495 |
+
return history
|
| 496 |
+
|
| 497 |
+
# cross-protocol hooks are not used by this task
|
| 498 |
+
def default_params(self, inst):
|
| 499 |
+
return dict(policy="naive")
|
| 500 |
+
|
| 501 |
+
def oracle_params(self, inst):
|
| 502 |
+
return dict(policy="oracle")
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/l6_count.py
ADDED
|
@@ -0,0 +1,562 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L6-B count_into_box: put exactly N identical cubes into an opaque drop box; one carry is interrupted by a slip.
|
| 2 |
+
|
| 3 |
+
Scene: T identical orange 4 cm cubes scattered on the table and a dark, closed drop box (static fixture) at
|
| 4 |
+
one side of the table. The box lid has a square opening on the robot side; a cube released above it falls in,
|
| 5 |
+
lands on a low-friction ramp and slides under the closed part of the lid, where no camera can see it (once past
|
| 6 |
+
the opening it is moved to a storage slot at the far end, so that cubes never queue back under the opening).
|
| 7 |
+
Cubes cannot be taken back out.
|
| 8 |
+
|
| 9 |
+
Instruction: put exactly N cubes into the box (N in {4, 5}, given in the instruction).
|
| 10 |
+
|
| 11 |
+
Interruption: during the (p+1)-th carry (p cubes are already in the box, p in {1..N-1}, hidden) the carried
|
| 12 |
+
cube "slips": the gripper opens and the cube lands back on the table next to the spot it was picked from. The
|
| 13 |
+
number of cubes left on the table is R = N + e with e in {0, 1} drawn independently of p (T = R + p), so
|
| 14 |
+
neither the box nor the table tells how many cubes are inside: progress ("how many have I put in already")
|
| 15 |
+
is only in the agent's own history. Over-filling is irreversible (terminal failure); under-filling can be
|
| 16 |
+
completed in a later segment.
|
| 17 |
+
|
| 18 |
+
Protocol: within (one episode, no reset), like l6_swap_interrupt. An attempt (segment) ends when the agent
|
| 19 |
+
declares done; the outcome is measured; if the box holds fewer than N cubes the agent continues from the
|
| 20 |
+
current state. The slip is injected once per episode, inside attempt 1, by a per-control-step monitor (so it
|
| 21 |
+
also fires for agents driven by the harness). Events reported immediately (`drain_events`): "A cube dropped
|
| 22 |
+
into the box." after every cube that falls in, and the slip.
|
| 23 |
+
|
| 24 |
+
Scripted references (perception = simulator state, as in l6_swap):
|
| 25 |
+
oracle privileged box count: carries cubes until the box holds N.
|
| 26 |
+
adaptive counts its own successful drops (Save), notices the slip (the cube is back on the table, the
|
| 27 |
+
drop count is unchanged), carries cubes until its count reaches N (Retrieve + Utilize). Later
|
| 28 |
+
segments: if F2 says the box holds fewer than N, adds one cube per segment.
|
| 29 |
+
naive memoryless continuation (1 attempt): loses its count at the slip; re-plans from the current frame,
|
| 30 |
+
which shows no progress, so it guesses how many cubes are already inside (uniform over 0..N-1)
|
| 31 |
+
and adds the rest.
|
| 32 |
+
blind memoryless restart (k attempts): at the slip it does not know where it was and starts over
|
| 33 |
+
("the box must get N cubes"), every later segment again puts N cubes in (repeated steps).
|
| 34 |
+
Extra controls (not in the acceptance table): `skip` (counts carries instead of drops, i.e. counts the
|
| 35 |
+
slipped carry; with memory + F2 it adds the missing cube in segment 2) and `inc1` (stateless, adds one cube
|
| 36 |
+
per segment; shows that the within protocol's stop-at-first-success leaks progress to such a policy).
|
| 37 |
+
"""
|
| 38 |
+
import numpy as np
|
| 39 |
+
|
| 40 |
+
from .. import envs
|
| 41 |
+
from ..bddl import write_bddl
|
| 42 |
+
from ..objects import _fmt, _wrap, box_xml, register_generated
|
| 43 |
+
from ..task_base import LFFTask, register_task
|
| 44 |
+
|
| 45 |
+
CUBE_HALF = 0.02
|
| 46 |
+
CUBE_RGBA = (0.95, 0.50, 0.10, 1.0)
|
| 47 |
+
N_CUBES = 11 # objects declared in the BDDL; unused ones are parked on the floor out of view
|
| 48 |
+
LETTERS = "ABCDEFGHIJK"
|
| 49 |
+
CUBES = [f"cube_{i + 1}" for i in range(N_CUBES)]
|
| 50 |
+
|
| 51 |
+
# drop box (local frame: origin at the centre of the footprint on the table top, +x away from the robot)
|
| 52 |
+
WALL_T = 0.008
|
| 53 |
+
IN_HX, IN_HY = 0.100, 0.110 # inner half sizes
|
| 54 |
+
LID_Z = 0.095 # underside of the lid above the table
|
| 55 |
+
LID_T = 0.008
|
| 56 |
+
HOLE_X = (-0.090, -0.020) # opening in the lid (local x range), on the robot side
|
| 57 |
+
HOLE_HY = 0.035
|
| 58 |
+
RAMP_Z = (0.045, 0.006) # top surface of the ramp at the near (-x) and far (+x) inner walls
|
| 59 |
+
RAMP_T = 0.006
|
| 60 |
+
RAMP_MU = 0.03
|
| 61 |
+
BOX_RGBA = (0.30, 0.20, 0.13, 1.0)
|
| 62 |
+
INNER_RGBA = (0.08, 0.07, 0.06, 1.0)
|
| 63 |
+
HOLE_C = np.array([(HOLE_X[0] + HOLE_X[1]) / 2, 0.0])
|
| 64 |
+
OUT_HX, OUT_HY = IN_HX + WALL_T, IN_HY + WALL_T
|
| 65 |
+
RAMP_SLOPE = (RAMP_Z[0] - RAMP_Z[1]) / (2 * IN_HX)
|
| 66 |
+
RAMP_TH = float(np.arctan(RAMP_SLOPE))
|
| 67 |
+
# Storage slots under the closed part of the lid. A cube that has slid past the opening is moved to the next free
|
| 68 |
+
# slot (out of every camera's view) so that the cubes do not queue up along the slide line back under the opening.
|
| 69 |
+
# Order: the lane straight behind the opening (y = 0) is filled last, so that a newly dropped cube can always slide
|
| 70 |
+
# past the opening before it is moved; then a second layer on the far row. (x, y, layer)
|
| 71 |
+
_ROW = [IN_HX - CUBE_HALF - 0.002 - 0.044 * r for r in range(2)]
|
| 72 |
+
SLOTS = ([(_ROW[r], y, 0) for r in range(2) for y in (-0.088, 0.088, -0.044, 0.044)]
|
| 73 |
+
+ [(_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)])
|
| 74 |
+
|
| 75 |
+
BASE_X = -0.66
|
| 76 |
+
REACH = 0.70 # max horizontal distance of a cube from the robot base
|
| 77 |
+
CUBE_REGION = (-0.30, 0.07, -0.28, 0.28)
|
| 78 |
+
CUBE_MIN_DIST = 0.085
|
| 79 |
+
BOX_CLEAR = 0.12 # cube centre at least this far from the box footprint (the hand must not hit the lid)
|
| 80 |
+
Z_GRASP = envs.TABLE_Z + CUBE_HALF
|
| 81 |
+
Z_CARRY = envs.TABLE_Z + 0.20
|
| 82 |
+
Z_RELEASE = envs.TABLE_Z + LID_Z + LID_T + 0.012 + CUBE_HALF # cube bottom ~1.2 cm above the lid
|
| 83 |
+
PARK = [(-0.5 + 0.1 * i, 1.25) for i in range(N_CUBES)]
|
| 84 |
+
LIFTED = 0.05 # slip trigger: cube at least this far above its resting height
|
| 85 |
+
HAND_HALF = 0.11 # the Panda hand reaches about this far along the closing axis (it hits 4 cm cubes there)
|
| 86 |
+
HAND_CLEAR = 0.06 # neighbour centre at least this far from that segment for a collision-free grasp
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def hand_box_clear(p, a, box, half=HAND_HALF):
|
| 90 |
+
"""Smallest distance from the hand segment (closing axis at yaw a) to the drop box footprint."""
|
| 91 |
+
ax = np.array([-np.sin(a), np.cos(a)])
|
| 92 |
+
return min(float(np.linalg.norm(np.maximum(np.abs(np.asarray(p) + t * ax - box) - [OUT_HX, OUT_HY], 0.0)))
|
| 93 |
+
for t in np.linspace(-half, half, 9))
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def axis_clear(p, a, others, half=HAND_HALF):
|
| 97 |
+
"""Smallest distance from a neighbour centre to the hand segment p +- half * (closing axis at yaw a)."""
|
| 98 |
+
ax = np.array([-np.sin(a), np.cos(a)])
|
| 99 |
+
best = 1.0
|
| 100 |
+
for o in others:
|
| 101 |
+
v = np.asarray(o) - p
|
| 102 |
+
t = float(np.clip(v @ ax, -half, half))
|
| 103 |
+
best = min(best, float(np.linalg.norm(v - t * ax)))
|
| 104 |
+
return best
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def drop_box_xml(model_name):
|
| 108 |
+
"""Closed box with a square opening in the lid and an internal ramp (static fixture, collisions on)."""
|
| 109 |
+
parts = [] # (pos, half size, rgba, quat or None, friction or None)
|
| 110 |
+
H = LID_Z / 2
|
| 111 |
+
# walls
|
| 112 |
+
parts.append(((IN_HX + WALL_T / 2, 0, H), (WALL_T / 2, OUT_HY, H), BOX_RGBA))
|
| 113 |
+
parts.append(((-IN_HX - WALL_T / 2, 0, H), (WALL_T / 2, OUT_HY, H), BOX_RGBA))
|
| 114 |
+
parts.append(((0, IN_HY + WALL_T / 2, H), (IN_HX, WALL_T / 2, H), BOX_RGBA))
|
| 115 |
+
parts.append(((0, -IN_HY - WALL_T / 2, H), (IN_HX, WALL_T / 2, H), BOX_RGBA))
|
| 116 |
+
# lid around the opening
|
| 117 |
+
zc = LID_Z + LID_T / 2
|
| 118 |
+
x0, x1 = HOLE_X
|
| 119 |
+
parts.append((((-OUT_HX + x0) / 2, 0, zc), ((x0 + OUT_HX) / 2, OUT_HY, LID_T / 2), BOX_RGBA)) # near strip
|
| 120 |
+
parts.append((((x1 + OUT_HX) / 2, 0, zc), ((OUT_HX - x1) / 2, OUT_HY, LID_T / 2), BOX_RGBA)) # far part
|
| 121 |
+
for s in (-1, 1):
|
| 122 |
+
parts.append((((x0 + x1) / 2, s * (HOLE_HY + OUT_HY) / 2, zc), ((x1 - x0) / 2, (OUT_HY - HOLE_HY) / 2,
|
| 123 |
+
LID_T / 2), BOX_RGBA))
|
| 124 |
+
# floor (dark) and ramp
|
| 125 |
+
parts.append(((0, 0, 0.002), (IN_HX, IN_HY, 0.002), INNER_RGBA))
|
| 126 |
+
dz = RAMP_Z[0] - RAMP_Z[1]
|
| 127 |
+
th = float(np.arctan2(dz, 2 * IN_HX))
|
| 128 |
+
L = float(np.hypot(dz, 2 * IN_HX)) / 2
|
| 129 |
+
zmid = (RAMP_Z[0] + RAMP_Z[1]) / 2 - RAMP_T / 2 / np.cos(th)
|
| 130 |
+
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)
|
| 131 |
+
geoms = []
|
| 132 |
+
for k, p in enumerate(parts + [ramp]):
|
| 133 |
+
pos, half, rgba = p[:3]
|
| 134 |
+
quat = p[3] if len(p) > 3 else None
|
| 135 |
+
mu = p[4] if len(p) > 4 else None
|
| 136 |
+
q = f' quat="{_fmt(quat)}"' if quat is not None else ""
|
| 137 |
+
fr = f' friction="{mu} 0.005 0.0001" priority="2"' if mu is not None else ' friction="1.0 0.005 0.0001"'
|
| 138 |
+
geoms.append(f' <geom name="{model_name}_g{k}" type="box" pos="{_fmt(pos)}" size="{_fmt(half)}"{q} '
|
| 139 |
+
f'rgba="{_fmt(rgba)}" density="1000"{fr} group="0" />')
|
| 140 |
+
geoms.append(f' <geom type="box" pos="{_fmt(pos)}" size="{_fmt(half)}"{q} rgba="{_fmt(rgba)}" '
|
| 141 |
+
f'conaffinity="0" contype="0" group="1" />')
|
| 142 |
+
return _wrap(model_name, "\n".join(geoms), (LID_Z + LID_T) / 2, float(np.hypot(OUT_HX, OUT_HY)))
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def _wrap_q(a):
|
| 146 |
+
"""cubes are symmetric under 90 deg rotations: wrap to [-pi/4, pi/4)"""
|
| 147 |
+
return float((a + np.pi / 4) % (np.pi / 2) - np.pi / 4)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
@register_task
|
| 151 |
+
class CountIntoBox(LFFTask):
|
| 152 |
+
name = "l6_count_into_box"
|
| 153 |
+
level = "L6"
|
| 154 |
+
category = "procedural_memory"
|
| 155 |
+
capabilities = ("Perceive", "Save", "Retrieve", "Utilize")
|
| 156 |
+
protocol = "within"
|
| 157 |
+
agent_max_steps = 80 # robot commands per attempt for agents (a VLM needs ~40-55)
|
| 158 |
+
max_attempts = 5
|
| 159 |
+
_TEMPLATE = ("Put exactly {n} of the orange cubes into the dark box, through the opening in its lid. "
|
| 160 |
+
"Cubes cannot be taken back out of the box.")
|
| 161 |
+
_TEMPLATE_INDIRECT = ("Drop exactly {n} of the small orange blocks into the closed brown container through the "
|
| 162 |
+
"square hole in its top. Blocks cannot be taken back out of the container.")
|
| 163 |
+
instruction = _TEMPLATE.format(n="N") # replaced per instance (sample_instance / agent_instruction)
|
| 164 |
+
instruction_indirect = _TEMPLATE_INDIRECT.format(n="N")
|
| 165 |
+
inject = True
|
| 166 |
+
announce_drops = True # False: no "A cube dropped into the box." event (harder variant, counting from images)
|
| 167 |
+
agent_object_names = ["orange cube (several identical)", "drop box"]
|
| 168 |
+
|
| 169 |
+
WORDS = {3: "three", 4: "four", 5: "five", 6: "six"}
|
| 170 |
+
|
| 171 |
+
def agent_instruction(self, inst, variant="direct"):
|
| 172 |
+
t = self._TEMPLATE_INDIRECT if variant == "indirect" else self._TEMPLATE
|
| 173 |
+
return t.format(n=self.WORDS[inst["n_target"]])
|
| 174 |
+
|
| 175 |
+
def __init__(self, cam_res=None):
|
| 176 |
+
super().__init__(cam_res)
|
| 177 |
+
self._mon = False
|
| 178 |
+
orig_step = self.env.step
|
| 179 |
+
|
| 180 |
+
def step(action): # per-control-step monitor: also sees attempts driven by the agent harness
|
| 181 |
+
ret = orig_step(action)
|
| 182 |
+
if self._mon:
|
| 183 |
+
self._monitor()
|
| 184 |
+
return ret
|
| 185 |
+
|
| 186 |
+
self.env.step = step
|
| 187 |
+
|
| 188 |
+
# ------------------------------------------------------------ scene
|
| 189 |
+
def make_bddl(self):
|
| 190 |
+
objs = []
|
| 191 |
+
for i, L in enumerate(LETTERS[:N_CUBES]):
|
| 192 |
+
cat = register_generated(f"LffCountCube{L}", box_xml(f"lff_count_cube_{L.lower()}", (CUBE_HALF,) * 3,
|
| 193 |
+
CUBE_RGBA, density=600))
|
| 194 |
+
gx, gy = -0.30 + 0.15 * (i % 4), -0.40 + 0.2 * (i // 4)
|
| 195 |
+
objs.append((CUBES[i], cat, f"c{i + 1}_region", (gx - 0.01, gy - 0.01, gx + 0.01, gy + 0.01)))
|
| 196 |
+
box = register_generated("LffDropBox", drop_box_xml("lff_drop_box"), free=False)
|
| 197 |
+
fx = [("drop_box_1", box, "box_region", (0.19, 0.39, 0.21, 0.41))]
|
| 198 |
+
return write_bddl(self.name, self._TEMPLATE.format(n="N"), objs, fx)
|
| 199 |
+
|
| 200 |
+
def _box_body(self):
|
| 201 |
+
return self.env.sim.model.body_name2id(self.env.fixtures_dict["drop_box_1"].root_body)
|
| 202 |
+
|
| 203 |
+
def sample_instance(self, seed):
|
| 204 |
+
rng = np.random.default_rng(seed)
|
| 205 |
+
n = int(rng.choice([4, 5]))
|
| 206 |
+
p = int(rng.integers(1, n)) # cubes already inside when the slip happens
|
| 207 |
+
e = int(rng.integers(0, 2))
|
| 208 |
+
T = n + e + p
|
| 209 |
+
for _ in range(500):
|
| 210 |
+
side = int(rng.choice([-1, 1]))
|
| 211 |
+
box = np.array([rng.uniform(-0.08, -0.02), side * rng.uniform(0.22, 0.25)])
|
| 212 |
+
P = np.column_stack([rng.uniform(*CUBE_REGION[:2], 800), rng.uniform(*CUBE_REGION[2:], 800)])
|
| 213 |
+
P = P[np.hypot(P[:, 0] - BASE_X, P[:, 1]) <= REACH]
|
| 214 |
+
P = P[np.linalg.norm(np.maximum(np.abs(P - box) - np.array([OUT_HX, OUT_HY]), 0.0), axis=1) >= BOX_CLEAR]
|
| 215 |
+
cubes = []
|
| 216 |
+
for c in P: # random sequential addition
|
| 217 |
+
if all(np.linalg.norm(c - q) >= CUBE_MIN_DIST for q in cubes):
|
| 218 |
+
cubes.append(c)
|
| 219 |
+
if len(cubes) == T:
|
| 220 |
+
break
|
| 221 |
+
if len(cubes) < T:
|
| 222 |
+
continue
|
| 223 |
+
yaws = [] # each cube gets a yaw whose (small-rotation) grasp axis is free for the hand
|
| 224 |
+
for i in range(T):
|
| 225 |
+
oth = [cubes[j] for j in range(T) if j != i]
|
| 226 |
+
for _ in range(30):
|
| 227 |
+
y = float(rng.uniform(-np.pi / 4, np.pi / 4))
|
| 228 |
+
if axis_clear(cubes[i], y, oth) >= HAND_CLEAR and hand_box_clear(cubes[i], y, box) >= 0.035:
|
| 229 |
+
# |y| <= 45 deg: the grasp needs no large wrist rotation
|
| 230 |
+
yaws.append(y)
|
| 231 |
+
break
|
| 232 |
+
else:
|
| 233 |
+
break
|
| 234 |
+
if len(yaws) == T:
|
| 235 |
+
break
|
| 236 |
+
else:
|
| 237 |
+
raise RuntimeError("could not sample a layout")
|
| 238 |
+
inst = dict(seed=int(seed), n_target=n, p=p, e=e, n_cubes=T, box_xy=box.round(4).tolist(),
|
| 239 |
+
cubes=np.array(cubes).round(4).tolist(),
|
| 240 |
+
yaws=yaws,
|
| 241 |
+
trigger_dist=float(rng.uniform(0.05, 0.09)),
|
| 242 |
+
slip_r=float(rng.uniform(0.005, 0.02)), slip_ang=float(rng.uniform(0, 2 * np.pi)),
|
| 243 |
+
slip_yaw=float(rng.uniform(-np.pi / 4, np.pi / 4)))
|
| 244 |
+
# make_video prints task.instruction: keep it in sync with the last sampled instance
|
| 245 |
+
self.instruction = self.agent_instruction(inst, "direct")
|
| 246 |
+
self.instruction_indirect = self.agent_instruction(inst, "indirect")
|
| 247 |
+
return inst
|
| 248 |
+
|
| 249 |
+
def apply_instance(self, inst):
|
| 250 |
+
m = self.env.sim.model
|
| 251 |
+
bid = self._box_body()
|
| 252 |
+
m.body_pos[bid] = [inst["box_xy"][0], inst["box_xy"][1], envs.TABLE_Z]
|
| 253 |
+
m.body_quat[bid] = [1, 0, 0, 0]
|
| 254 |
+
T = inst["n_cubes"]
|
| 255 |
+
for i, c in enumerate(CUBES):
|
| 256 |
+
if i < T:
|
| 257 |
+
envs.set_obj_pose(self.env, c, [*inst["cubes"][i], envs.TABLE_Z + CUBE_HALF + 0.001],
|
| 258 |
+
yaw=inst["yaws"][i])
|
| 259 |
+
else:
|
| 260 |
+
envs.set_obj_pose(self.env, c, [*PARK[i], CUBE_HALF + 0.001])
|
| 261 |
+
self.env.sim.forward()
|
| 262 |
+
self._inst = inst
|
| 263 |
+
self.active = CUBES[:T]
|
| 264 |
+
self.slip = None
|
| 265 |
+
self.events = []
|
| 266 |
+
self._event_cursor = 0
|
| 267 |
+
self._outcome_cursor = 0
|
| 268 |
+
self.in_box = [] # cubes that fell into the box, in order
|
| 269 |
+
self.stored = [] # cubes moved to a storage slot
|
| 270 |
+
self._bad = set() # scripted policies: cubes whose grasp failed
|
| 271 |
+
self.rest_xy = {c: np.array(inst["cubes"][i]) for i, c in enumerate(self.active)}
|
| 272 |
+
self._mon = False
|
| 273 |
+
|
| 274 |
+
def reset_instance(self, inst, recorder=None):
|
| 275 |
+
self._mon = False
|
| 276 |
+
sk = super().reset_instance(inst, recorder=recorder)
|
| 277 |
+
self._home = sk.eef_pos()
|
| 278 |
+
self._mon = True
|
| 279 |
+
return sk
|
| 280 |
+
|
| 281 |
+
def go_home(self):
|
| 282 |
+
p = self.sk.eef_pos()
|
| 283 |
+
self.sk.move_to([p[0], p[1], max(p[2], self._home[2])])
|
| 284 |
+
self.sk.move_to(self._home)
|
| 285 |
+
|
| 286 |
+
# ------------------------------------------------------------ geometry helpers
|
| 287 |
+
def box_local(self, xyz):
|
| 288 |
+
b = self._inst["box_xy"]
|
| 289 |
+
return np.array([xyz[0] - b[0], xyz[1] - b[1], xyz[2] - envs.TABLE_Z])
|
| 290 |
+
|
| 291 |
+
def hole_world(self):
|
| 292 |
+
b = self._inst["box_xy"]
|
| 293 |
+
return np.array([b[0] + HOLE_C[0], b[1] + HOLE_C[1]])
|
| 294 |
+
|
| 295 |
+
def inside_box(self, c):
|
| 296 |
+
q = self.box_local(envs.obj_pos(self.env, c))
|
| 297 |
+
return bool(abs(q[0]) < IN_HX and abs(q[1]) < IN_HY and q[2] < LID_Z)
|
| 298 |
+
|
| 299 |
+
def on_lid(self, c):
|
| 300 |
+
q = self.box_local(envs.obj_pos(self.env, c))
|
| 301 |
+
return bool(abs(q[0]) < OUT_HX + 0.01 and abs(q[1]) < OUT_HY + 0.01 and q[2] >= LID_Z)
|
| 302 |
+
|
| 303 |
+
def on_table(self, c):
|
| 304 |
+
p = envs.obj_pos(self.env, c)
|
| 305 |
+
return bool(p[2] < envs.TABLE_Z + CUBE_HALF + 0.01 and not self.inside_box(c))
|
| 306 |
+
|
| 307 |
+
# ------------------------------------------------------------ monitor (every control step)
|
| 308 |
+
def _monitor(self):
|
| 309 |
+
env = self.env
|
| 310 |
+
for c in self.active:
|
| 311 |
+
if c in self.in_box:
|
| 312 |
+
if c not in self.stored and self.box_local(envs.obj_pos(env, c))[0] > HOLE_X[1] + 0.02:
|
| 313 |
+
self._store(c)
|
| 314 |
+
continue
|
| 315 |
+
p = envs.obj_pos(env, c)
|
| 316 |
+
if self.inside_box(c):
|
| 317 |
+
self.in_box.append(c)
|
| 318 |
+
if self.announce_drops:
|
| 319 |
+
self.events.append(dict(step=int(self.sk.n_steps), kind="drop", obj=c,
|
| 320 |
+
text="A cube dropped into the box."))
|
| 321 |
+
continue
|
| 322 |
+
if p[2] < envs.TABLE_Z + CUBE_HALF + 0.005: # resting on the table: remember where
|
| 323 |
+
self.rest_xy[c] = p[:2].copy()
|
| 324 |
+
continue
|
| 325 |
+
if (self.inject and self.slip is None and p[2] > envs.TABLE_Z + CUBE_HALF + LIFTED
|
| 326 |
+
and len(self.in_box) == self._inst["p"]
|
| 327 |
+
and np.linalg.norm(p[:2] - self.rest_xy[c]) >= self._inst["trigger_dist"]
|
| 328 |
+
and self.sk.holding(c)):
|
| 329 |
+
self._do_slip(c)
|
| 330 |
+
|
| 331 |
+
def _store(self, c):
|
| 332 |
+
sx, sy, layer = SLOTS[min(len(self.stored), len(SLOTS) - 1)]
|
| 333 |
+
b = self._inst["box_xy"]
|
| 334 |
+
z = RAMP_Z[0] - (sx + IN_HX) * RAMP_SLOPE + CUBE_HALF / np.cos(RAMP_TH) + 0.002 + layer * (2 * CUBE_HALF + 0.003)
|
| 335 |
+
envs.set_obj_pose(self.env, c, [b[0] + sx, b[1] + sy, envs.TABLE_Z + z],
|
| 336 |
+
quat_wxyz=[np.cos(RAMP_TH / 2), 0.0, np.sin(RAMP_TH / 2), 0.0])
|
| 337 |
+
self.stored.append(c)
|
| 338 |
+
|
| 339 |
+
def _do_slip(self, c):
|
| 340 |
+
inst = self._inst
|
| 341 |
+
src = self.rest_xy[c]
|
| 342 |
+
others = [envs.obj_pos(self.env, o)[:2] for o in self.active if o != c and o not in self.in_box]
|
| 343 |
+
xy, yaw = src, inst["slip_yaw"]
|
| 344 |
+
found = False
|
| 345 |
+
for r in (inst["slip_r"], inst["slip_r"] / 2, 0.0): # next to the pick-up spot, still graspable
|
| 346 |
+
cand = src + r * np.array([np.cos(inst["slip_ang"]), np.sin(inst["slip_ang"])])
|
| 347 |
+
if not all(np.linalg.norm(cand - o) >= 0.07 for o in others):
|
| 348 |
+
continue
|
| 349 |
+
for dy in (0.0, 0.3, -0.3, 0.6, -0.6):
|
| 350 |
+
y = _wrap_q(inst["slip_yaw"] + dy)
|
| 351 |
+
if axis_clear(cand, y, others) >= HAND_CLEAR and \
|
| 352 |
+
hand_box_clear(cand, y, np.asarray(inst["box_xy"])) >= 0.035:
|
| 353 |
+
xy, yaw, found = cand, y, True
|
| 354 |
+
break
|
| 355 |
+
if found:
|
| 356 |
+
break
|
| 357 |
+
envs.set_obj_pose(self.env, c, [xy[0], xy[1], envs.TABLE_Z + CUBE_HALF + 0.002], yaw=yaw)
|
| 358 |
+
self.sk.grip = -1.0 # the gripper opens
|
| 359 |
+
self.env.sim.forward()
|
| 360 |
+
text = "A cube slipped out of the gripper and fell back onto the table."
|
| 361 |
+
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),
|
| 362 |
+
in_box=len(self.in_box))
|
| 363 |
+
self.events.append(dict(step=int(self.sk.n_steps), kind="slip", obj=c, text=text))
|
| 364 |
+
|
| 365 |
+
def drain_events(self):
|
| 366 |
+
ev = self.events[self._event_cursor:]
|
| 367 |
+
self._event_cursor = len(self.events)
|
| 368 |
+
return [e["text"] for e in ev]
|
| 369 |
+
|
| 370 |
+
# ------------------------------------------------------------ outcome
|
| 371 |
+
def outcome(self, inst):
|
| 372 |
+
envs.settle(self.env, 20)
|
| 373 |
+
n_in = len(self.in_box)
|
| 374 |
+
N = inst["n_target"]
|
| 375 |
+
held = [c for c in self.active if self.sk.holding(c)]
|
| 376 |
+
n_table = sum(self.on_table(c) for c in self.active if c not in self.in_box)
|
| 377 |
+
n_lid = sum(self.on_lid(c) for c in self.active if c not in self.in_box)
|
| 378 |
+
success = bool(n_in == N and not held)
|
| 379 |
+
terminal = bool(n_in > N)
|
| 380 |
+
if success:
|
| 381 |
+
head = f"The box holds exactly {N} cubes."
|
| 382 |
+
elif terminal:
|
| 383 |
+
head = (f"The box holds more than {N} cubes. Cubes cannot be taken out of the box, so the task can no "
|
| 384 |
+
f"longer be completed.")
|
| 385 |
+
elif n_in == N:
|
| 386 |
+
head = f"The gripper is still holding a cube."
|
| 387 |
+
else:
|
| 388 |
+
head = f"The box holds fewer than {N} cubes."
|
| 389 |
+
state = f"Now {n_table} cube{'s are' if n_table != 1 else ' is'} on the table"
|
| 390 |
+
if n_lid:
|
| 391 |
+
state += f" and {n_lid} on the box lid"
|
| 392 |
+
state += "."
|
| 393 |
+
# F2 = verdict + currently observable state + the slip of this segment (never the number inside)
|
| 394 |
+
new = [e for e in self.events[self._outcome_cursor:] if e["kind"] == "slip"]
|
| 395 |
+
self._outcome_cursor = len(self.events)
|
| 396 |
+
detail = head + " " + state
|
| 397 |
+
if new:
|
| 398 |
+
detail = "During this attempt: " + " ".join(e["text"] for e in new) + " " + detail
|
| 399 |
+
return dict(success=success, terminal=terminal, n_in_box=n_in, n_target=N, n_table=n_table, n_lid=n_lid,
|
| 400 |
+
held=len(held), slip=self.slip, detail=detail)
|
| 401 |
+
|
| 402 |
+
# ------------------------------------------------------------ motion (scripted policies)
|
| 403 |
+
def _grasp_yaw(self, c):
|
| 404 |
+
"""The cube's grasp axis with the smaller wrist rotation (|yaw| <= 45 deg). Rotations near +-90 deg drive
|
| 405 |
+
the Panda wrist into its joint-6 limit at some positions (measured), so the other axis is used only if
|
| 406 |
+
the hand would hit a neighbour or the box on this one."""
|
| 407 |
+
R = self.env.sim.data.body_xmat[envs.body_id(self.env, c)].reshape(3, 3)
|
| 408 |
+
yaw = _wrap_q(float(np.arctan2(R[1, 0], R[0, 0])))
|
| 409 |
+
p = envs.obj_pos(self.env, c)[:2]
|
| 410 |
+
others = [envs.obj_pos(self.env, o)[:2] for o in self.active if o != c and o not in self.in_box]
|
| 411 |
+
box = np.asarray(self._inst["box_xy"])
|
| 412 |
+
|
| 413 |
+
def score(a):
|
| 414 |
+
return min(axis_clear(p, a, others), hand_box_clear(p, a, box) + 0.03)
|
| 415 |
+
if score(yaw) >= HAND_CLEAR:
|
| 416 |
+
return yaw
|
| 417 |
+
alt = yaw - np.pi / 2 if yaw >= 0 else yaw + np.pi / 2
|
| 418 |
+
return alt if score(alt) > score(yaw) + 0.02 else yaw
|
| 419 |
+
|
| 420 |
+
def _pick(self, c):
|
| 421 |
+
sk = self.sk
|
| 422 |
+
for _ in range(2):
|
| 423 |
+
p = envs.obj_pos(self.env, c)
|
| 424 |
+
sk.grasp_at(p[:2], Z_GRASP, yaw=self._grasp_yaw(c), lift=0.12)
|
| 425 |
+
if sk.holding(c):
|
| 426 |
+
return True
|
| 427 |
+
sk.set_gripper(False, steps=8)
|
| 428 |
+
sk.move_to([p[0], p[1], Z_GRASP + 0.12])
|
| 429 |
+
return False
|
| 430 |
+
|
| 431 |
+
def _carry(self, c):
|
| 432 |
+
"""Pick cube c and release it above the opening. Returns 'in', 'slipped', 'missed' or 'no_grasp'."""
|
| 433 |
+
n_ev = len(self.events)
|
| 434 |
+
n_in = len(self.in_box)
|
| 435 |
+
if not self._pick(c):
|
| 436 |
+
self._bad.add(c)
|
| 437 |
+
self.go_home() # un-wind the arm before the next try
|
| 438 |
+
return "no_grasp"
|
| 439 |
+
h = self.hole_world()
|
| 440 |
+
sk = self.sk
|
| 441 |
+
sk.move_to([h[0], h[1], Z_CARRY], yaw=0.0) # the slip may fire here; any yaw fits the opening
|
| 442 |
+
if any(e["kind"] == "slip" for e in self.events[n_ev:]):
|
| 443 |
+
return "slipped"
|
| 444 |
+
sk.move_to([h[0], h[1], Z_RELEASE], tol=0.004)
|
| 445 |
+
sk.set_gripper(False, steps=12)
|
| 446 |
+
sk.move_to([h[0], h[1], Z_CARRY])
|
| 447 |
+
sk.hold(10)
|
| 448 |
+
return "in" if len(self.in_box) > n_in else "missed"
|
| 449 |
+
|
| 450 |
+
def _next_cube(self):
|
| 451 |
+
"""nearest table cube to the opening (what any policy sees in the current frame)"""
|
| 452 |
+
h = self.hole_world()
|
| 453 |
+
cands = [c for c in self.active if c not in self.in_box and (self.on_table(c) or self.on_lid(c))]
|
| 454 |
+
cands = [c for c in cands if c not in self._bad] or cands # try another cube after a failed grasp
|
| 455 |
+
if not cands:
|
| 456 |
+
return None
|
| 457 |
+
return min(cands, key=lambda c: np.linalg.norm(envs.obj_pos(self.env, c)[:2] - h))
|
| 458 |
+
|
| 459 |
+
def _add(self, k, log, stop_on_slip=False):
|
| 460 |
+
"""Carry until k cubes went in (by the policy's own observation of each drop). Returns (added, slipped)."""
|
| 461 |
+
added, slipped = 0, False
|
| 462 |
+
guard = 0
|
| 463 |
+
while added < k and guard < 3 * k + 3:
|
| 464 |
+
guard += 1
|
| 465 |
+
c = self._next_cube()
|
| 466 |
+
if c is None:
|
| 467 |
+
break
|
| 468 |
+
r = self._carry(c)
|
| 469 |
+
log.append(r)
|
| 470 |
+
if r == "in":
|
| 471 |
+
added += 1
|
| 472 |
+
elif r == "slipped":
|
| 473 |
+
slipped = True
|
| 474 |
+
if stop_on_slip:
|
| 475 |
+
break
|
| 476 |
+
return added, slipped
|
| 477 |
+
|
| 478 |
+
# ------------------------------------------------------------ scripted references (within protocol)
|
| 479 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 480 |
+
k = k or self.max_attempts
|
| 481 |
+
rng = np.random.default_rng(seed + 7919)
|
| 482 |
+
self.reset_instance(inst)
|
| 483 |
+
N = inst["n_target"]
|
| 484 |
+
history = []
|
| 485 |
+
for a in range(k):
|
| 486 |
+
log = []
|
| 487 |
+
plan = dict(kind=kind, carries=log)
|
| 488 |
+
if a == 0:
|
| 489 |
+
if kind == "oracle":
|
| 490 |
+
while len(self.in_box) < N and len(log) < 3 * N + 3: # privileged count
|
| 491 |
+
c = self._next_cube()
|
| 492 |
+
if c is None:
|
| 493 |
+
break
|
| 494 |
+
log.append(self._carry(c))
|
| 495 |
+
plan["recovery"] = "oracle: privileged box count"
|
| 496 |
+
elif kind in ("adaptive", "skip"):
|
| 497 |
+
added, slipped = self._add(N, log) if kind == "adaptive" else (0, False)
|
| 498 |
+
if kind == "skip": # counts carries, not drops
|
| 499 |
+
n_car = 0
|
| 500 |
+
while n_car < N and len(log) < 3 * N:
|
| 501 |
+
c = self._next_cube()
|
| 502 |
+
if c is None:
|
| 503 |
+
break
|
| 504 |
+
r = self._carry(c)
|
| 505 |
+
log.append(r)
|
| 506 |
+
if r in ("in", "slipped"):
|
| 507 |
+
n_car += 1
|
| 508 |
+
if r == "in":
|
| 509 |
+
added += 1
|
| 510 |
+
plan["recovery"] = "counts carries (the slipped one too)"
|
| 511 |
+
else:
|
| 512 |
+
plan["recovery"] = "own drop count; the slipped carry is not counted"
|
| 513 |
+
else: # memoryless after the slip
|
| 514 |
+
added, slipped = self._add(N, log, stop_on_slip=True)
|
| 515 |
+
if slipped:
|
| 516 |
+
if kind == "naive":
|
| 517 |
+
guess = int(rng.integers(0, N))
|
| 518 |
+
plan["recovery"] = f"memoryless: guesses {guess} already inside, adds {N - guess}"
|
| 519 |
+
self._add(N - guess, log)
|
| 520 |
+
elif kind == "blind":
|
| 521 |
+
plan["recovery"] = f"memoryless restart: puts {N} cubes in"
|
| 522 |
+
self._add(N, log)
|
| 523 |
+
elif kind == "inc1":
|
| 524 |
+
plan["recovery"] = "stateless: adds one cube per segment"
|
| 525 |
+
self._add(1, log)
|
| 526 |
+
else:
|
| 527 |
+
raise ValueError(kind)
|
| 528 |
+
else:
|
| 529 |
+
plan["recovery"] = "none (no slip)"
|
| 530 |
+
else:
|
| 531 |
+
if kind in ("adaptive", "skip"):
|
| 532 |
+
plan["recovery"] = "memory + F2 'fewer than N': add one cube"
|
| 533 |
+
self._add(1, log)
|
| 534 |
+
elif kind == "blind":
|
| 535 |
+
plan["recovery"] = f"memoryless restart: puts {N} cubes in"
|
| 536 |
+
self._add(N, log)
|
| 537 |
+
elif kind == "inc1":
|
| 538 |
+
plan["recovery"] = "stateless: adds one cube"
|
| 539 |
+
self._add(1, log)
|
| 540 |
+
elif kind == "oracle":
|
| 541 |
+
while len(self.in_box) < N and len(log) < 3 * N + 3:
|
| 542 |
+
c = self._next_cube()
|
| 543 |
+
if c is None:
|
| 544 |
+
break
|
| 545 |
+
log.append(self._carry(c))
|
| 546 |
+
else:
|
| 547 |
+
raise ValueError(kind)
|
| 548 |
+
self.go_home()
|
| 549 |
+
out = self.outcome(inst)
|
| 550 |
+
history.append(dict(attempt=a + 1, params=plan, outcome=out))
|
| 551 |
+
if on_attempt:
|
| 552 |
+
on_attempt(a, plan, out)
|
| 553 |
+
if out["success"] or out["terminal"] or kind in ("oracle", "naive"):
|
| 554 |
+
break
|
| 555 |
+
return history
|
| 556 |
+
|
| 557 |
+
# cross-protocol hooks are not used by this task
|
| 558 |
+
def default_params(self, inst):
|
| 559 |
+
return dict(policy="naive")
|
| 560 |
+
|
| 561 |
+
def oracle_params(self, inst):
|
| 562 |
+
return dict(policy="oracle")
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/lh_bystander.py
ADDED
|
@@ -0,0 +1,830 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LH bystander: put three cubes into an open box while a tall glass bottle that is not part of the task stands right
|
| 2 |
+
in front of the box -- lowering a cube into the box, the robot's own forearm comes down onto the bottle and knocks it
|
| 3 |
+
over.
|
| 4 |
+
|
| 5 |
+
Family: long-horizon self-disturbance, environment level ("state_restoration"; LIBERO-Recover's damage category L4: the
|
| 6 |
+
damaged thing is not part of the task). Three easy pick-and-place stages; the instruction says plainly that nothing
|
| 7 |
+
else may be moved and that the bottle must be left standing where it is. The agent has to notice the fallen bottle and
|
| 8 |
+
stand it up again on its spot before finishing (within an attempt), or learn to keep its arm off the bottle (across
|
| 9 |
+
attempts).
|
| 10 |
+
|
| 11 |
+
Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y):
|
| 12 |
+
* 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;
|
| 13 |
+
centre x in [0.00, 0.04], 6-10 cm left or right of the middle;
|
| 14 |
+
* 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,
|
| 15 |
+
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
|
| 16 |
+
never passes over the bottle;
|
| 17 |
+
* 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,
|
| 18 |
+
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
|
| 19 |
+
bottle: it tips beyond 8.5 deg; pressed down on its cap, beyond 3.7 deg).
|
| 20 |
+
|
| 21 |
+
Instance variable (where the bottle stands): "hazard" (15 of every 20 consecutive seeds): right in front of the box,
|
| 22 |
+
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":
|
| 23 |
+
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
|
| 24 |
+
the physics is hidden. What the agent cannot see before acting is its own arm: the wrist camera shows the fingers, not
|
| 25 |
+
the forearm, and the agent steers the grasp point.
|
| 26 |
+
|
| 27 |
+
Disturbance (physics, no teleport): lowering a cube onto the box floor (grasp point ~4 cm above the table), the
|
| 28 |
+
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
|
| 29 |
+
and wrist (links 5-7) slope back from the hand towards the robot base, starting ~12 cm above the grasp point; over the
|
| 30 |
+
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
|
| 31 |
+
there. The bottle is pushed over (mostly
|
| 32 |
+
towards the robot) and lies on the table in front of the box; visible in agentview once the arm has moved away
|
| 33 |
+
(measured, task card). Not every contact knocks it: a descent can come to rest on the cap (pinched between links 5
|
| 34 |
+
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
|
| 35 |
+
lifts (measured: the smoke-test sequence on seed 3000; 6-7 of 8 hazard seeds still knocked with slow or near-first
|
| 36 |
+
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
|
| 37 |
+
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
|
| 38 |
+
transit). A careful packer keeps its arm above the bottle: carry at >= 24 cm and release the cube from >= 18 cm
|
| 39 |
+
(dropping it into the box) -- or moves the bottle out of the way and back, which the final-state judge would accept
|
| 40 |
+
but the instruction rules out.
|
| 41 |
+
|
| 42 |
+
Restoring (re-standable by a top-down gripper that only turns about the vertical): the body is square (a lying bottle
|
| 43 |
+
does not roll away from the closing fingers) and the cap is a ball with low torsional friction: grasped from above with
|
| 44 |
+
the fingers across the lying bottle's axis, the cap turns between the fingers, the lifted bottle swings down and hangs
|
| 45 |
+
straight; lowered onto the table it stands (measured: placement error ~1 mm). The instruction tells the agent that the
|
| 46 |
+
bottle hangs straight down when held by its cap (as lh_fence does for its knobs).
|
| 47 |
+
|
| 48 |
+
Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (every cube in the
|
| 49 |
+
box -- footprint inside the cavity, top below the rim, not held --, the bottle upright within 10 deg and its base
|
| 50 |
+
within 2 cm of where it stood, nothing held or touched, scene static) plus a per-step event log for the server log:
|
| 51 |
+
cube stages achieved / lost / restored; bottle_in_place lost / restored (with cause: arm / hand / cube, the robot geom,
|
| 52 |
+
the grasp point) plus the marker events bystander_knocked / bystander_restored / fallen. F1 gives the agent only
|
| 53 |
+
success / failure.
|
| 54 |
+
"""
|
| 55 |
+
import numpy as np
|
| 56 |
+
|
| 57 |
+
from .. import envs
|
| 58 |
+
from ..bddl import write_bddl
|
| 59 |
+
from ..objects import _SOLID, _fmt, _wrap, box_xml, register_generated
|
| 60 |
+
from ..skills import Skills
|
| 61 |
+
from ..task_base import LFFTask, register_task
|
| 62 |
+
|
| 63 |
+
Z = envs.TABLE_Z
|
| 64 |
+
# ---------------------------------------------------------------- geometry / physics
|
| 65 |
+
BOX = "box_1"
|
| 66 |
+
BOX_MODEL = "lff_lhb_box"
|
| 67 |
+
BOX_IN = 0.070 # cavity half width (14 x 14 cm)
|
| 68 |
+
WALL_T, FLOOR_T, WALL_H = 0.008, 0.006, 0.060
|
| 69 |
+
BOX_OUT = BOX_IN + WALL_T
|
| 70 |
+
RIM = FLOOR_T + WALL_H # rim height above the table
|
| 71 |
+
WOOD = (0.62, 0.45, 0.28, 1.0)
|
| 72 |
+
|
| 73 |
+
CUBES = ("red_cube_1", "yellow_cube_1", "blue_cube_1")
|
| 74 |
+
CUBE_COLOR = {"red_cube_1": "red", "yellow_cube_1": "yellow", "blue_cube_1": "blue"}
|
| 75 |
+
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))
|
| 76 |
+
CUBE_E = 0.040
|
| 77 |
+
CUBE_DENS = 500.0 # 32 g
|
| 78 |
+
CUBE_MU = 0.8
|
| 79 |
+
|
| 80 |
+
BOTTLE = "bottle_1"
|
| 81 |
+
BOTTLE_MODEL = "lff_lhb_bottle"
|
| 82 |
+
BOTTLE_CLASS = "LffLhbBottle"
|
| 83 |
+
RB, HB = 0.030, 0.185 # square body: half width, height
|
| 84 |
+
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
|
| 85 |
+
# 4.8 cm foot of the draft the forearm could come to rest on the cap and stall instead of
|
| 86 |
+
# knocking it (bottle pressed down like a column, tilt <= 5 deg; measured, see the task card)
|
| 87 |
+
RS, HS = 0.022, 0.015 # shoulder
|
| 88 |
+
RN, HN = 0.0115, 0.060 # neck
|
| 89 |
+
RK = 0.015 # ball cap radius; its centre sits RK - 6 mm above the neck top
|
| 90 |
+
CAP_SINK = 0.006
|
| 91 |
+
H_TOT = HB + HS + HN + 2 * RK - CAP_SINK # 0.284
|
| 92 |
+
CAP_Z = H_TOT - RK # cap centre above the bottle's bottom when standing
|
| 93 |
+
BOTTLE_MASS = 0.25
|
| 94 |
+
BOTTLE_COM = 0.12 # above the bottom (an empty glass bottle: ~42 % of its height)
|
| 95 |
+
BOTTLE_MU = 0.6
|
| 96 |
+
CAP_MU_T = 0.0005 # torsional friction of the cap (condim 4): the grasped cap turns freely, the swing is damped
|
| 97 |
+
GLASS = (0.16, 0.42, 0.26, 1.0)
|
| 98 |
+
CAP_RGBA = (0.78, 0.12, 0.10, 1.0)
|
| 99 |
+
|
| 100 |
+
# instances
|
| 101 |
+
P_HAZARD = 0.75 # 15 of every 20 consecutive seeds: bottle in front of the box
|
| 102 |
+
HAZ_GAP = (0.010, 0.025) # bottle body to the box's front wall
|
| 103 |
+
HAZ_LAT = (-0.010, 0.040) # bottle centre left (+y) of the box's centre line
|
| 104 |
+
BEN_GAP = (0.080, 0.110) # beside the box, on its outer side (away from the cubes)
|
| 105 |
+
BEN_DX = (-0.030, 0.030)
|
| 106 |
+
BOX_X = (0.0, 0.04) # the bottle in front of the box stays >= 2 cm clear of the fingers in the home pose
|
| 107 |
+
BOX_Y = (0.06, 0.10) # |y| of the box centre; the side is random
|
| 108 |
+
CUBE_Y = (0.19, 0.23) # |y| of the cube row (other side)
|
| 109 |
+
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):
|
| 110 |
+
# the straight carry to the box passes >= 2 cm from the bottle in front of it
|
| 111 |
+
|
| 112 |
+
# success predicate
|
| 113 |
+
POS_TOL = 0.020 # bottle base within 2 cm of where it stood
|
| 114 |
+
UPRIGHT = np.radians(10.0)
|
| 115 |
+
KNOCK_TILT = np.radians(10.0) # once in place, the bottle counts as disturbed when tilted beyond this (it tips at
|
| 116 |
+
# 8.5 deg: beyond, it is falling or leaning on something) or moved
|
| 117 |
+
POS_HYST = 0.003 # > POS_TOL + POS_HYST for DEBOUNCE checks (a nudge that rocks back within 0.6 s is no loss)
|
| 118 |
+
FALLEN = np.radians(60.0)
|
| 119 |
+
IN_TOL = 0.002 # a cube's footprint may reach this far past the inner walls
|
| 120 |
+
RIM_TOL = 0.004
|
| 121 |
+
BELOW_RIM = 0.010 # in_box: the cube's lowest point at least this far below the rim
|
| 122 |
+
DEBOUNCE = 6 # predicate checks (every 0.1 s) a change must persist
|
| 123 |
+
|
| 124 |
+
# scripted motion (heights of the grasp point above the table)
|
| 125 |
+
Z_CARRY = 0.15 # Sonnet's transit: 11-20 cm, often lifted to ~20 before moving
|
| 126 |
+
Z_REL = 0.040 # Sonnet-like release: cube set down on the box floor (grasp point 4 cm up)
|
| 127 |
+
Z_SAFE = 0.26 # careful transit
|
| 128 |
+
Z_DROP = 0.19 # careful release: the cube is dropped from above the rim, the forearm stays above the bottle
|
| 129 |
+
NAIVE_ERR = 0.008 # Sonnet's placement error 0.4-1.3 cm
|
| 130 |
+
SLOT = 0.033 # slot offset from the box centre (cavity 14 cm, cubes 4 cm)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def bottle_xml(name):
|
| 134 |
+
h = H_TOT / 2
|
| 135 |
+
zf, zb, zs, zn = -h + HF / 2, -h + HF + (HB - HF) / 2, -h + HB + HS / 2, -h + HB + HS + HN / 2
|
| 136 |
+
zk = -h + HB + HS + HN + RK - CAP_SINK
|
| 137 |
+
m = BOTTLE_MASS
|
| 138 |
+
ixx = m * ((2 * RB) ** 2 + H_TOT ** 2) / 16 # rough: most of the glass is in the body and the base
|
| 139 |
+
izz = m * (2 * (2 * RB) ** 2) / 12
|
| 140 |
+
parts = [("foot", "box", (0, 0, zf), (RF, RF, HF / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'),
|
| 141 |
+
("body", "box", (0, 0, zb), (RB, RB, (HB - HF) / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'),
|
| 142 |
+
("shoulder", "box", (0, 0, zs), (RS, RS, HS / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'),
|
| 143 |
+
("neck", "cylinder", (0, 0, zn), (RN, HN / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'),
|
| 144 |
+
("cap", "sphere", (0, 0, zk), (RK,), CAP_RGBA, f'friction="1 {CAP_MU_T} 0.0001" condim="4" priority="2"')]
|
| 145 |
+
s = [f' <inertial pos="0 0 {-h + BOTTLE_COM:.4f}" mass="{m}" diaginertia="{ixx:.6f} {ixx:.6f} {izz:.6f}" />']
|
| 146 |
+
for nm, typ, pos, size, c, extra in parts:
|
| 147 |
+
s.append(f' <geom name="{name}_{nm}" type="{typ}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(c)}" '
|
| 148 |
+
f'{extra} group="0" />')
|
| 149 |
+
s.append(f' <geom type="{typ}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(c)}" contype="0" '
|
| 150 |
+
f'conaffinity="0" group="1" />')
|
| 151 |
+
# a lighter label band (visual only) so the bottle reads as a bottle
|
| 152 |
+
s.append(f' <geom type="box" pos="0 0 {zb + 0.01:.4f}" size="{RB + 0.0008:.4f} {RB + 0.0008:.4f} 0.035" '
|
| 153 |
+
f'rgba="0.92 0.90 0.80 1" contype="0" conaffinity="0" group="1" />')
|
| 154 |
+
return _wrap(name, "\n".join(s), h, RB * 1.42)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def box_fixture_xml(name):
|
| 158 |
+
"""open wooden box, origin at the centre of its footprint, z = 0 at the table"""
|
| 159 |
+
ix = BOX_IN
|
| 160 |
+
parts = [((0, 0, FLOOR_T / 2), (BOX_OUT, BOX_OUT, FLOOR_T / 2)),
|
| 161 |
+
((ix + WALL_T / 2, 0, RIM / 2), (WALL_T / 2, BOX_OUT, RIM / 2)),
|
| 162 |
+
((-ix - WALL_T / 2, 0, RIM / 2), (WALL_T / 2, BOX_OUT, RIM / 2)),
|
| 163 |
+
((0, ix + WALL_T / 2, RIM / 2), (ix, WALL_T / 2, RIM / 2)),
|
| 164 |
+
((0, -ix - WALL_T / 2, RIM / 2), (ix, WALL_T / 2, RIM / 2))]
|
| 165 |
+
g = []
|
| 166 |
+
for k, (p, sz) in enumerate(parts):
|
| 167 |
+
g.append(f' <geom name="{name}_w{k}" type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(WOOD)}" '
|
| 168 |
+
f'friction="0.8 0.005 0.0001" {_SOLID} group="0" />')
|
| 169 |
+
g.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(WOOD)}" contype="0" '
|
| 170 |
+
f'conaffinity="0" group="1" />')
|
| 171 |
+
return f"""<mujoco model="{name}">
|
| 172 |
+
<worldbody>
|
| 173 |
+
<body>
|
| 174 |
+
<body name="object">
|
| 175 |
+
{chr(10).join(g)}
|
| 176 |
+
</body>
|
| 177 |
+
<site rgba="0 0 0 0" size="0.005" pos="0 0 0" name="bottom_site" />
|
| 178 |
+
<site rgba="0 0 0 0" size="0.005" pos="0 0 {RIM:.4f}" name="top_site" />
|
| 179 |
+
<site rgba="0 0 0 0" size="0.005" pos="{BOX_OUT:.4f} {BOX_OUT:.4f} 0" name="horizontal_radius_site" />
|
| 180 |
+
</body>
|
| 181 |
+
</worldbody>
|
| 182 |
+
</mujoco>"""
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
REACH_MAX = 0.74 # scripted policies: farthest grasp point (horizontal distance from the robot base) they rely on
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def _reach(p):
|
| 189 |
+
return float(np.hypot(p[0] + 0.66, p[1]))
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def _fb(v):
|
| 193 |
+
return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}"
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def _lr(v):
|
| 197 |
+
return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}"
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class BystanderSkills(Skills):
|
| 201 |
+
"""Skills that feed the task's per-step monitor."""
|
| 202 |
+
|
| 203 |
+
def __init__(self, env, task, recorder=None):
|
| 204 |
+
super().__init__(env, recorder=recorder)
|
| 205 |
+
self.task = task
|
| 206 |
+
|
| 207 |
+
def _act(self, dpos, drot, grip):
|
| 208 |
+
super()._act(dpos, drot, grip)
|
| 209 |
+
self.task.monitor_step()
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
@register_task
|
| 213 |
+
class Bystander(LFFTask):
|
| 214 |
+
name = "lh_bystander"
|
| 215 |
+
level = "L2"
|
| 216 |
+
category = "state_restoration"
|
| 217 |
+
capabilities = ("Perceive", "Reason", "Restore", "Plan")
|
| 218 |
+
protocol = "cross"
|
| 219 |
+
max_attempts = 3
|
| 220 |
+
agent_max_steps = 100 # careful: 3 cubes x ~7 commands + looking; standing the bottle up again ~8-10; + slack
|
| 221 |
+
instruction = ("Put the red, yellow and blue cubes into the open wooden box. Do not move anything else: the tall "
|
| 222 |
+
"glass bottle must be left standing upright exactly where it is now. (The bottle has a round red "
|
| 223 |
+
"cap; held by its cap, the bottle hangs straight down.)")
|
| 224 |
+
instruction_indirect = ("Pack the three small cubes (red, yellow, blue) into the wooden crate. Leave everything else "
|
| 225 |
+
"as it is -- the tall green bottle has to stay standing on its spot. (Its round red cap: held "
|
| 226 |
+
"by the cap, the bottle hangs straight down.)")
|
| 227 |
+
agent_object_names = ["red cube", "yellow cube", "blue cube", "open wooden box",
|
| 228 |
+
"tall glass bottle (square, with a round red cap; held by its cap it hangs straight down)"]
|
| 229 |
+
|
| 230 |
+
# ------------------------------------------------------------ scene
|
| 231 |
+
def make_bddl(self):
|
| 232 |
+
box = register_generated("LffLhbBox", box_fixture_xml(BOX_MODEL), free=False)
|
| 233 |
+
objs = []
|
| 234 |
+
for i, n in enumerate(CUBES):
|
| 235 |
+
c = CUBE_COLOR[n]
|
| 236 |
+
cat = register_generated(f"LffLhbCube{c.title()}",
|
| 237 |
+
box_xml(f"lff_lhb_cube_{c}", (CUBE_E / 2,) * 3, CUBE_RGBA[c], density=CUBE_DENS,
|
| 238 |
+
friction=(CUBE_MU, 0.005, 0.0001)).replace(_SOLID, ""))
|
| 239 |
+
objs.append((n, cat, f"{c}_cube_region", (-0.35, -0.25 + 0.15 * i, -0.33, -0.23 + 0.15 * i)))
|
| 240 |
+
bt = register_generated(BOTTLE_CLASS, bottle_xml(BOTTLE_MODEL))
|
| 241 |
+
objs.append((BOTTLE, bt, "bottle_region", (-0.35, 0.24, -0.33, 0.26)))
|
| 242 |
+
fx = [(BOX, box, "box_region", (-0.06, -0.01, -0.04, 0.01))]
|
| 243 |
+
return write_bddl(self.name, "put the cubes into the box and leave the bottle where it is", objs, fx)
|
| 244 |
+
|
| 245 |
+
def __init__(self, cam_res=None):
|
| 246 |
+
super().__init__(cam_res)
|
| 247 |
+
m = self.env.sim.model
|
| 248 |
+
self.box_bid = m.body_name2id(self.env.fixtures_dict[BOX].root_body)
|
| 249 |
+
self.box_gids = {g for g in range(m.ngeom) if m.geom_bodyid[g] in
|
| 250 |
+
{self.box_bid} | {c for c in range(m.nbody) if m.body_parentid[c] == self.box_bid}}
|
| 251 |
+
pre = f"{BOTTLE}_{BOTTLE_MODEL}"
|
| 252 |
+
self.cap_gid = m.geom_name2id(pre + "_cap")
|
| 253 |
+
self.bottle_gids = set(envs.obj_geom_ids(self.env, BOTTLE))
|
| 254 |
+
self.cube_gids = {n: set(envs.obj_geom_ids(self.env, n)) for n in CUBES}
|
| 255 |
+
# robot parts: 1 = hand / fingers (what the agent sees and steers), 2 = arm links (wrist, forearm, ...)
|
| 256 |
+
self.part = np.zeros(m.ngeom, int)
|
| 257 |
+
for g in envs.robot_geom_ids(self.env):
|
| 258 |
+
n = m.geom_id2name(g) or ""
|
| 259 |
+
self.part[g] = 1 if n.startswith("gripper0_") else 2
|
| 260 |
+
self.other = np.zeros(m.ngeom, int) # 3 = a cube, 4 = the box
|
| 261 |
+
for n in CUBES:
|
| 262 |
+
self.other[list(self.cube_gids[n])] = 3
|
| 263 |
+
self.other[list(self.box_gids)] = 4
|
| 264 |
+
self.is_bottle = np.zeros(m.ngeom, bool)
|
| 265 |
+
self.is_bottle[list(self.bottle_gids)] = True
|
| 266 |
+
# bottle contacts are collected after every MuJoCo substep (a fast hit can be shorter than a control step)
|
| 267 |
+
sim = self.env.sim
|
| 268 |
+
if not getattr(sim, "_lhb_wrapped", False):
|
| 269 |
+
orig = sim.step
|
| 270 |
+
|
| 271 |
+
def step(*a, **k):
|
| 272 |
+
orig(*a, **k)
|
| 273 |
+
t = getattr(sim, "_lhb_task", None)
|
| 274 |
+
if t is not None and t.mon is not None:
|
| 275 |
+
t._substep()
|
| 276 |
+
sim.step = step
|
| 277 |
+
sim._lhb_wrapped = True
|
| 278 |
+
sim._lhb_task = self
|
| 279 |
+
self._sub = {}
|
| 280 |
+
self.inst = None
|
| 281 |
+
self.mon = None
|
| 282 |
+
self.sk = None
|
| 283 |
+
|
| 284 |
+
def sample_instance(self, seed):
|
| 285 |
+
rng = np.random.default_rng(seed)
|
| 286 |
+
s = 1.0 if rng.random() < 0.5 else -1.0 # box on the left (+1) or right (-1)
|
| 287 |
+
bx, by = float(rng.uniform(*BOX_X)), s * float(rng.uniform(*BOX_Y))
|
| 288 |
+
# balanced blocks like lh_lid_box: exactly round(20 * P_HAZARD) of every 20 consecutive seeds are hazards
|
| 289 |
+
hazard = bool((int(seed) * 7) % 20 < round(20 * P_HAZARD))
|
| 290 |
+
if hazard:
|
| 291 |
+
gap, lat = float(rng.uniform(*HAZ_GAP)), float(rng.uniform(*HAZ_LAT))
|
| 292 |
+
bottle = [bx - BOX_OUT - gap - RB, by + lat]
|
| 293 |
+
else:
|
| 294 |
+
gap, lat = float(rng.uniform(*BEN_GAP)), float(rng.uniform(*BEN_DX))
|
| 295 |
+
bottle = [bx + lat, by + s * (BOX_OUT + gap + RB)]
|
| 296 |
+
cy = -s * float(rng.uniform(*CUBE_Y))
|
| 297 |
+
perm = rng.permutation(len(CUBES))
|
| 298 |
+
start = {CUBES[i]: [float(bx + CUBE_DX[j] + rng.uniform(-0.01, 0.01)), float(cy + rng.uniform(-0.01, 0.01))]
|
| 299 |
+
for j, i in enumerate(perm)}
|
| 300 |
+
start_yaw = {n: float(rng.uniform(-0.3, 0.3)) for n in CUBES}
|
| 301 |
+
return dict(seed=int(seed), hazard=hazard, bottle_side="front" if hazard else "outer side",
|
| 302 |
+
box_side="left" if s > 0 else "right", box_xy=[bx, by], bottle_xy=[float(bottle[0]), float(bottle[1])],
|
| 303 |
+
bottle_yaw=float(rng.uniform(-0.25, 0.25)), gap=gap, lat=lat, start=start, start_yaw=start_yaw)
|
| 304 |
+
|
| 305 |
+
def apply_instance(self, inst):
|
| 306 |
+
self.inst = inst
|
| 307 |
+
m = self.env.sim.model
|
| 308 |
+
bx, by = inst["box_xy"]
|
| 309 |
+
m.body_pos[self.box_bid] = [bx, by, Z]
|
| 310 |
+
m.body_quat[self.box_bid] = [1.0, 0.0, 0.0, 0.0]
|
| 311 |
+
for n, xy in inst["start"].items():
|
| 312 |
+
envs.place_upright(self.env, n, xy, yaw=inst["start_yaw"][n], clearance=0.001)
|
| 313 |
+
envs.set_friction(self.env, n, CUBE_MU)
|
| 314 |
+
envs.place_upright(self.env, BOTTLE, inst["bottle_xy"], yaw=inst["bottle_yaw"], clearance=0.001)
|
| 315 |
+
|
| 316 |
+
def reset_instance(self, inst, recorder=None):
|
| 317 |
+
self.mon = None
|
| 318 |
+
self.env.reset()
|
| 319 |
+
self.apply_instance(inst)
|
| 320 |
+
self.env.sim.forward()
|
| 321 |
+
envs.settle(self.env, 15)
|
| 322 |
+
self.sk = BystanderSkills(self.env, self, recorder=recorder)
|
| 323 |
+
self._sub = {}
|
| 324 |
+
self._init_monitor()
|
| 325 |
+
return self.sk
|
| 326 |
+
|
| 327 |
+
# ------------------------------------------------------------ state helpers
|
| 328 |
+
def R(self, name):
|
| 329 |
+
return self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3).copy()
|
| 330 |
+
|
| 331 |
+
def bottle_tilt(self):
|
| 332 |
+
return float(np.arccos(np.clip(self.R(BOTTLE)[2, 2], -1.0, 1.0)))
|
| 333 |
+
|
| 334 |
+
def bottle_base(self):
|
| 335 |
+
"""xy of the centre of the bottle's bottom face"""
|
| 336 |
+
d = self.env.sim.data
|
| 337 |
+
return (envs.obj_pos(self.env, BOTTLE) - self.R(BOTTLE)[:, 2] * H_TOT / 2)[:2]
|
| 338 |
+
|
| 339 |
+
def bottle_offset(self):
|
| 340 |
+
return self.bottle_base() - np.asarray(self.inst["bottle_xy"])
|
| 341 |
+
|
| 342 |
+
def cap_xyz(self):
|
| 343 |
+
return self.env.sim.data.geom_xpos[self.cap_gid].copy()
|
| 344 |
+
|
| 345 |
+
def held(self, name):
|
| 346 |
+
return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name]))
|
| 347 |
+
|
| 348 |
+
def bottle_in_place(self, tol=POS_TOL, tilt=UPRIGHT):
|
| 349 |
+
return bool(self.bottle_tilt() <= tilt and np.linalg.norm(self.bottle_offset()) <= tol
|
| 350 |
+
and envs.obj_min_z(self.env, BOTTLE) < Z + 0.01 and not self.held(BOTTLE))
|
| 351 |
+
|
| 352 |
+
def to_box(self, xy):
|
| 353 |
+
return np.asarray(xy, float)[:2] - np.asarray(self.inst["box_xy"])
|
| 354 |
+
|
| 355 |
+
def in_box(self, name):
|
| 356 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 357 |
+
g = next(iter(self.cube_gids[name]))
|
| 358 |
+
Rg = d.geom_xmat[g].reshape(3, 3)
|
| 359 |
+
c = self.to_box(d.geom_xpos[g][:2])
|
| 360 |
+
ext = np.abs(Rg[:2, :]) @ m.geom_size[g][:3]
|
| 361 |
+
# 10-14: "in the box" = footprint inside the cavity and the cube's lowest point well below the rim (it is held
|
| 362 |
+
# by the walls); a cube stacked on another one may stick out above the rim -- the instruction never asks for
|
| 363 |
+
# "below the rim" (two Sonnet pilot attempts that stacked the last cube were judged failures before this)
|
| 364 |
+
return bool(np.all(np.abs(c) + ext <= BOX_IN + IN_TOL) and envs.obj_min_z(self.env, name) <= Z + RIM - BELOW_RIM
|
| 365 |
+
and not self.held(name))
|
| 366 |
+
|
| 367 |
+
def over_box(self, name):
|
| 368 |
+
c = self.to_box(envs.obj_pos(self.env, name)[:2])
|
| 369 |
+
return bool(np.all(np.abs(c) <= BOX_OUT))
|
| 370 |
+
|
| 371 |
+
def stage_values(self):
|
| 372 |
+
v = {f"{CUBE_COLOR[n]}_in_box": self.in_box(n) for n in CUBES}
|
| 373 |
+
v["bottle_in_place"] = self.bottle_in_place()
|
| 374 |
+
return v
|
| 375 |
+
|
| 376 |
+
# ------------------------------------------------------------ per-step monitor
|
| 377 |
+
def _init_monitor(self):
|
| 378 |
+
keys = [f"{CUBE_COLOR[n]}_in_box" for n in CUBES] + ["bottle_in_place"]
|
| 379 |
+
st = {k: False for k in keys}
|
| 380 |
+
st["bottle_in_place"] = self.bottle_in_place()
|
| 381 |
+
self.mon = dict(state=st, ever=[k for k in keys if st[k]], lost=[], events=[], cand={k: 0 for k in keys},
|
| 382 |
+
step=0, last_touch=None, robot_touch_step=-10 ** 9, touch_parts=[], n_knocks=0, n_fallen=0,
|
| 383 |
+
fallen=False,
|
| 384 |
+
max_tilt_deg=0.0, max_offset_cm=0.0, first_knock_step=None, first_touch_step=None)
|
| 385 |
+
|
| 386 |
+
def _substep(self):
|
| 387 |
+
d = self.env.sim.data
|
| 388 |
+
n = d.ncon
|
| 389 |
+
if not n:
|
| 390 |
+
return
|
| 391 |
+
g1 = np.asarray(d.contact.geom1)[:n]
|
| 392 |
+
g2 = np.asarray(d.contact.geom2)[:n]
|
| 393 |
+
b1, b2 = self.is_bottle[g1], self.is_bottle[g2]
|
| 394 |
+
sel = b1 ^ b2
|
| 395 |
+
if not sel.any():
|
| 396 |
+
return
|
| 397 |
+
other = np.where(b1, g2, g1)[sel]
|
| 398 |
+
for o in other:
|
| 399 |
+
p = int(self.part[o])
|
| 400 |
+
if p:
|
| 401 |
+
who = "hand" if p == 1 else "arm"
|
| 402 |
+
prev = self._sub.get("robot")
|
| 403 |
+
self._sub["robot"] = "arm" if (who == "arm" or prev == "arm") else "hand"
|
| 404 |
+
self._sub.setdefault("geom", self.env.sim.model.geom_id2name(int(o)))
|
| 405 |
+
elif self.other[o] == 3:
|
| 406 |
+
self._sub["cube"] = True
|
| 407 |
+
|
| 408 |
+
def monitor_step(self):
|
| 409 |
+
mon = self.mon
|
| 410 |
+
if mon is None:
|
| 411 |
+
return
|
| 412 |
+
mon["step"] += 1
|
| 413 |
+
step = self.sk.n_steps if self.sk is not None else mon["step"]
|
| 414 |
+
sub, self._sub = self._sub, {}
|
| 415 |
+
if "robot" in sub:
|
| 416 |
+
mon["robot_touch_step"] = step
|
| 417 |
+
mon["last_touch"] = [sub["robot"], step, sub.get("geom", "")]
|
| 418 |
+
if sub["robot"] not in mon["touch_parts"]:
|
| 419 |
+
mon["touch_parts"].append(sub["robot"])
|
| 420 |
+
if mon["first_touch_step"] is None:
|
| 421 |
+
mon["first_touch_step"] = step
|
| 422 |
+
elif sub.get("cube") and (mon["last_touch"] is None or step - mon["last_touch"][1] > 20):
|
| 423 |
+
mon["last_touch"] = ["cube", step, ""]
|
| 424 |
+
tilt = self.bottle_tilt()
|
| 425 |
+
mon["max_tilt_deg"] = round(max(mon["max_tilt_deg"], float(np.degrees(tilt))), 1)
|
| 426 |
+
mon["max_offset_cm"] = round(max(mon["max_offset_cm"], 100 * float(np.linalg.norm(self.bottle_offset()))), 1)
|
| 427 |
+
if mon["step"] % 2:
|
| 428 |
+
return # predicates every other control step (0.1 s)
|
| 429 |
+
if not mon["fallen"] and tilt > FALLEN and not self.held(BOTTLE):
|
| 430 |
+
mon["fallen"] = True
|
| 431 |
+
mon["n_fallen"] += 1
|
| 432 |
+
mon["events"].append(dict(step=step, pred="bottle", ev="fallen", cause=self._cause(step)))
|
| 433 |
+
elif mon["fallen"] and tilt < UPRIGHT:
|
| 434 |
+
mon["fallen"] = False
|
| 435 |
+
for n in CUBES:
|
| 436 |
+
self._check(f"{CUBE_COLOR[n]}_in_box", self.in_box(n), step, n)
|
| 437 |
+
st = mon["state"]["bottle_in_place"]
|
| 438 |
+
# hysteresis: once in place it counts as lost only beyond 2.3 cm / 10 deg, held for 0.6 s (a nudge that rocks
|
| 439 |
+
# back is no loss)
|
| 440 |
+
now = self.bottle_in_place(POS_TOL + POS_HYST, KNOCK_TILT) if st else self.bottle_in_place()
|
| 441 |
+
self._check("bottle_in_place", now, step, BOTTLE)
|
| 442 |
+
|
| 443 |
+
def _cause(self, step):
|
| 444 |
+
lt = self.mon["last_touch"]
|
| 445 |
+
if lt is not None and step - lt[1] <= 60:
|
| 446 |
+
return lt[0]
|
| 447 |
+
return "other"
|
| 448 |
+
|
| 449 |
+
def _check(self, key, now, step, name):
|
| 450 |
+
mon = self.mon
|
| 451 |
+
if now == mon["state"][key]:
|
| 452 |
+
mon["cand"][key] = 0
|
| 453 |
+
return
|
| 454 |
+
if name == BOTTLE and not now and step - mon["robot_touch_step"] <= 6 and not self.held(BOTTLE):
|
| 455 |
+
# the arm is still pressing on the bottle (measured: a slow descent can come to rest on its cap and stall,
|
| 456 |
+
# tilting it ~12 deg; it rocks back when the arm lifts): a loss only once the robot has let go of it
|
| 457 |
+
mon["cand"][key] = 0
|
| 458 |
+
return
|
| 459 |
+
mon["cand"][key] += 1
|
| 460 |
+
if mon["cand"][key] < DEBOUNCE:
|
| 461 |
+
return
|
| 462 |
+
mon["cand"][key] = 0
|
| 463 |
+
mon["state"][key] = now
|
| 464 |
+
if now:
|
| 465 |
+
restored = key in mon["lost"]
|
| 466 |
+
ev = "restored" if restored else "achieved"
|
| 467 |
+
if key not in mon["ever"]:
|
| 468 |
+
mon["ever"].append(key)
|
| 469 |
+
if restored:
|
| 470 |
+
mon["lost"].remove(key)
|
| 471 |
+
mon["events"].append(dict(step=step, pred=key, ev=ev))
|
| 472 |
+
if key == "bottle_in_place" and restored:
|
| 473 |
+
mon["events"].append(dict(step=step, pred="bottle", ev="bystander_restored",
|
| 474 |
+
offset_cm=(100 * self.bottle_offset()).round(1).tolist()))
|
| 475 |
+
return
|
| 476 |
+
if key not in mon["ever"]:
|
| 477 |
+
return
|
| 478 |
+
cause = "picked_up" if self.held(name) else self._cause(step)
|
| 479 |
+
if key not in mon["lost"]:
|
| 480 |
+
mon["lost"].append(key)
|
| 481 |
+
e = dict(step=step, pred=key, ev="lost", cause=cause)
|
| 482 |
+
if name == BOTTLE:
|
| 483 |
+
ee = self.sk.eef_pos() if self.sk is not None else np.zeros(3)
|
| 484 |
+
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],
|
| 485 |
+
ee[2] - Z)] # grasp point rel. to the box centre / table
|
| 486 |
+
e.update(tilt_deg=round(float(np.degrees(self.bottle_tilt())), 1),
|
| 487 |
+
offset_cm=(100 * self.bottle_offset()).round(1).tolist())
|
| 488 |
+
if mon["last_touch"] is not None and mon["last_touch"][0] in ("arm", "hand"):
|
| 489 |
+
e["robot_geom"] = mon["last_touch"][2]
|
| 490 |
+
mon["events"].append(e)
|
| 491 |
+
if name == BOTTLE and cause != "picked_up":
|
| 492 |
+
mon["n_knocks"] += 1
|
| 493 |
+
if mon["first_knock_step"] is None:
|
| 494 |
+
mon["first_knock_step"] = step
|
| 495 |
+
mon["events"].append(dict(step=step, pred="bottle", ev="bystander_knocked", cause=cause,
|
| 496 |
+
robot_geom=e.get("robot_geom", ""), tilt_deg=e["tilt_deg"],
|
| 497 |
+
offset_cm=e["offset_cm"], eef_cm=e["eef_cm"]))
|
| 498 |
+
|
| 499 |
+
# ------------------------------------------------------------ outcome
|
| 500 |
+
def _static(self):
|
| 501 |
+
d = self.env.sim.data
|
| 502 |
+
for n in CUBES + (BOTTLE,):
|
| 503 |
+
_, da = envs.free_joint_addr(self.env, n)
|
| 504 |
+
if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5:
|
| 505 |
+
return False
|
| 506 |
+
return True
|
| 507 |
+
|
| 508 |
+
def robot_touching(self):
|
| 509 |
+
d = self.env.sim.data
|
| 510 |
+
out = []
|
| 511 |
+
for i in range(d.ncon):
|
| 512 |
+
c = d.contact[i]
|
| 513 |
+
for a, b in ((c.geom1, c.geom2), (c.geom2, c.geom1)):
|
| 514 |
+
if self.part[a] and (self.is_bottle[b] or self.other[b] == 3):
|
| 515 |
+
nm = "bottle" if self.is_bottle[b] else "a cube"
|
| 516 |
+
if nm not in out:
|
| 517 |
+
out.append(nm)
|
| 518 |
+
return out
|
| 519 |
+
|
| 520 |
+
def outcome(self, inst):
|
| 521 |
+
envs.settle(self.env, 30)
|
| 522 |
+
mon = self.mon
|
| 523 |
+
vals = self.stage_values()
|
| 524 |
+
static = self._static()
|
| 525 |
+
held = [n for n in CUBES + (BOTTLE,) if self.held(n)]
|
| 526 |
+
touching = self.robot_touching()
|
| 527 |
+
success = bool(all(vals.values()) and static and not held and not touching)
|
| 528 |
+
evs = mon["events"]
|
| 529 |
+
regress = [e for e in evs if e["ev"] == "lost"]
|
| 530 |
+
restored = [e for e in evs if e["ev"] == "restored"]
|
| 531 |
+
knocks = [e for e in evs if e["ev"] == "bystander_knocked"]
|
| 532 |
+
# trap fired: a knock was logged, or the bottle ends up out of place after the robot touched it (a slow push
|
| 533 |
+
# to just over 2 cm can stay inside the monitor's hysteresis band)
|
| 534 |
+
trap_fired = bool(knocks) or (not vals["bottle_in_place"] and not self.held(BOTTLE) and bool(mon["touch_parts"]))
|
| 535 |
+
recovered = bool(trap_fired and vals["bottle_in_place"])
|
| 536 |
+
off = self.bottle_offset()
|
| 537 |
+
tilt = float(np.degrees(self.bottle_tilt()))
|
| 538 |
+
parts = []
|
| 539 |
+
failure = None
|
| 540 |
+
if success:
|
| 541 |
+
parts.append("All three cubes are in the box and the bottle stands where it stood.")
|
| 542 |
+
else:
|
| 543 |
+
out_cubes = [n for n in CUBES if not vals[f"{CUBE_COLOR[n]}_in_box"]]
|
| 544 |
+
if not vals["bottle_in_place"]:
|
| 545 |
+
failure = ("bystander_held" if self.held(BOTTLE) else
|
| 546 |
+
"bystander_knocked" if tilt > np.degrees(UPRIGHT) else "bystander_moved")
|
| 547 |
+
elif held:
|
| 548 |
+
failure = "held"
|
| 549 |
+
elif out_cubes:
|
| 550 |
+
failure = "cube_not_in_box"
|
| 551 |
+
elif touching:
|
| 552 |
+
failure = "robot_touching"
|
| 553 |
+
else:
|
| 554 |
+
failure = "not_static"
|
| 555 |
+
if not vals["bottle_in_place"]:
|
| 556 |
+
if self.held(BOTTLE):
|
| 557 |
+
parts.append("The bottle is still held by the gripper.")
|
| 558 |
+
else:
|
| 559 |
+
pose = ("is lying on its side" if tilt > 60 else f"is tilted {tilt:.0f} degrees" if tilt > np.degrees(UPRIGHT)
|
| 560 |
+
else "stands upright")
|
| 561 |
+
txt = f"The bottle {pose}; its base is {_fb(off[0])} and {_lr(off[1])} of where it stood"
|
| 562 |
+
if knocks:
|
| 563 |
+
k = knocks[0]
|
| 564 |
+
who = {"arm": "the robot's arm (above the gripper)", "hand": "the gripper",
|
| 565 |
+
"cube": "a cube"}.get(k["cause"], "something")
|
| 566 |
+
txt += f" (it was knocked by {who}"
|
| 567 |
+
txt += " and stood up again later, but not back in place)." if restored and any(
|
| 568 |
+
e["pred"] == "bottle_in_place" for e in restored) else ")."
|
| 569 |
+
else:
|
| 570 |
+
txt += "."
|
| 571 |
+
parts.append(txt)
|
| 572 |
+
for n in out_cubes:
|
| 573 |
+
c = CUBE_COLOR[n]
|
| 574 |
+
if self.held(n):
|
| 575 |
+
parts.append(f"The {c} cube is still held by the gripper.")
|
| 576 |
+
elif self.over_box(n):
|
| 577 |
+
parts.append(f"The {c} cube rests on the box's rim instead of inside the box.")
|
| 578 |
+
else:
|
| 579 |
+
rel = self.to_box(envs.obj_pos(self.env, n)[:2])
|
| 580 |
+
parts.append(f"The {c} cube is not in the box: its centre is {_fb(rel[0])} and {_lr(rel[1])} of the "
|
| 581 |
+
f"box's centre.")
|
| 582 |
+
if touching and all(vals.values()):
|
| 583 |
+
parts.append("The robot was still touching " + " and ".join(touching) + " at the end.")
|
| 584 |
+
if not static and all(vals.values()):
|
| 585 |
+
parts.append("Something was still moving at the end.")
|
| 586 |
+
if trap_fired and vals["bottle_in_place"]:
|
| 587 |
+
parts.append(f"(The bottle was knocked out of place {len(knocks)} time(s) during the attempt and put back.)")
|
| 588 |
+
out = dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, touching=touching,
|
| 589 |
+
events=evs, n_regressions=len(regress), n_restored=len(restored), trap_fired=trap_fired,
|
| 590 |
+
recovered_in_attempt=recovered, n_knocks=len(knocks), n_fallen=mon["n_fallen"],
|
| 591 |
+
knock_causes=[k["cause"] for k in knocks], first_knock_step=mon["first_knock_step"],
|
| 592 |
+
bottle_touch_parts=list(mon["touch_parts"]), bottle_max_tilt_deg=mon["max_tilt_deg"],
|
| 593 |
+
bottle_max_offset_cm=mon["max_offset_cm"], bottle_tilt_deg=round(tilt, 1),
|
| 594 |
+
bottle_offset_cm=(100 * off).round(1).tolist(), hazard=bool(inst["hazard"]),
|
| 595 |
+
detail=" ".join(parts))
|
| 596 |
+
return out
|
| 597 |
+
|
| 598 |
+
# ------------------------------------------------------------ scripted primitives (perfect perception)
|
| 599 |
+
def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300):
|
| 600 |
+
return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
|
| 601 |
+
|
| 602 |
+
def _settle(self, name, max_checks=25):
|
| 603 |
+
d = self.env.sim.data
|
| 604 |
+
_, da = envs.free_joint_addr(self.env, name)
|
| 605 |
+
for _ in range(max_checks):
|
| 606 |
+
if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2:
|
| 607 |
+
return
|
| 608 |
+
self.sk.hold(2)
|
| 609 |
+
|
| 610 |
+
def _cube_yaw(self, name):
|
| 611 |
+
R = self.R(name)
|
| 612 |
+
i = int(np.argmin(np.abs(R[2])))
|
| 613 |
+
yaw = float(np.arctan2(R[1, i], R[0, i]))
|
| 614 |
+
y = float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4)
|
| 615 |
+
cands = [y + k * np.pi / 2 for k in (-1, 0, 1)]
|
| 616 |
+
return min(cands, key=lambda c: abs(c - self.sk.yaw) if abs(c) <= np.pi / 2 else 9.0)
|
| 617 |
+
|
| 618 |
+
def pick(self, name, z_carry, v=0.15, tries=2):
|
| 619 |
+
"""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,
|
| 620 |
+
close, lift to carry height"""
|
| 621 |
+
sk = self.sk
|
| 622 |
+
for _ in range(tries):
|
| 623 |
+
self._settle(name)
|
| 624 |
+
p = envs.obj_pos(self.env, name)
|
| 625 |
+
zg = p[2] - Z
|
| 626 |
+
yaw = self._cube_yaw(name)
|
| 627 |
+
sk.set_gripper(False, steps=8)
|
| 628 |
+
self._go([p[0], p[1], Z + max(z_carry, zg + 0.06)], yaw=yaw, speed=v)
|
| 629 |
+
self._go([p[0], p[1], Z + zg + 0.015], speed=0.1)
|
| 630 |
+
self._go([p[0], p[1], Z + zg], speed=0.04, tol=0.003, max_steps=120)
|
| 631 |
+
sk.set_gripper(True, steps=15)
|
| 632 |
+
self._go([p[0], p[1], Z + z_carry], speed=v)
|
| 633 |
+
if self.held(name):
|
| 634 |
+
return True
|
| 635 |
+
sk.set_gripper(False, steps=8)
|
| 636 |
+
return False
|
| 637 |
+
|
| 638 |
+
def put(self, xy, z_rel, z_carry, v=0.15, v_down=None):
|
| 639 |
+
"""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,
|
| 640 |
+
back up"""
|
| 641 |
+
sk = self.sk
|
| 642 |
+
self._go([xy[0], xy[1], Z + z_carry], speed=v)
|
| 643 |
+
if z_rel < z_carry - 0.02 and v_down:
|
| 644 |
+
self._go([xy[0], xy[1], Z + z_rel], speed=v_down, tol=0.003, max_steps=250)
|
| 645 |
+
elif z_rel < z_carry - 0.02:
|
| 646 |
+
self._go([xy[0], xy[1], Z + z_rel + 0.015], speed=0.1)
|
| 647 |
+
self._go([xy[0], xy[1], Z + z_rel], speed=0.03, tol=0.003, max_steps=150)
|
| 648 |
+
sk.set_gripper(False, steps=12)
|
| 649 |
+
self._go([xy[0], xy[1], Z + z_carry], speed=v)
|
| 650 |
+
sk.hold(5)
|
| 651 |
+
|
| 652 |
+
def slot_xy(self, k, order):
|
| 653 |
+
"""slot k of the scripted packing pattern, in world xy (box frame: u forward, v left)"""
|
| 654 |
+
u, v = order[k]
|
| 655 |
+
return np.asarray(self.inst["box_xy"]) + np.array([u, v]) * SLOT
|
| 656 |
+
|
| 657 |
+
def put_cube(self, name, k, order, z_rel, z_carry, noise=None, v=0.15, v_down=None):
|
| 658 |
+
if not self.pick(name, z_carry, v=v):
|
| 659 |
+
return False
|
| 660 |
+
xy = self.slot_xy(k, order) + (np.asarray(noise, float) if noise is not None else 0.0)
|
| 661 |
+
self.put(xy, z_rel, z_carry, v=v, v_down=v_down)
|
| 662 |
+
self._settle(name)
|
| 663 |
+
return True
|
| 664 |
+
|
| 665 |
+
def restand_bottle(self, z_carry=None):
|
| 666 |
+
"""stand the bottle up again on its spot: grasp the ball cap from above (fingers across the lying bottle's
|
| 667 |
+
axis), lift until it hangs free, carry it over its spot, lower until the bottom is ~2 mm above the table, let
|
| 668 |
+
go. Returns True if it is back in place."""
|
| 669 |
+
sk = self.sk
|
| 670 |
+
self._settle(BOTTLE)
|
| 671 |
+
for _ in range(2):
|
| 672 |
+
if _reach(self.cap_xyz()) > REACH_MAX and self.bottle_tilt() > FALLEN:
|
| 673 |
+
self.pull_in_bottle()
|
| 674 |
+
k = self.cap_xyz()
|
| 675 |
+
ax = self.R(BOTTLE)[:2, 2]
|
| 676 |
+
yaw = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else sk.yaw # finger axis across it
|
| 677 |
+
sk.set_gripper(False, steps=8)
|
| 678 |
+
cur = sk.eef_pos()
|
| 679 |
+
self._go([cur[0], cur[1], max(cur[2], Z + 0.15)], speed=0.15)
|
| 680 |
+
self._go([k[0], k[1], max(k[2] + 0.08, Z + 0.15)], yaw=yaw, speed=0.15)
|
| 681 |
+
sk.hold(5)
|
| 682 |
+
k = self.cap_xyz()
|
| 683 |
+
self._go([k[0], k[1], k[2] + 0.015], speed=0.1)
|
| 684 |
+
self._go([k[0], k[1], k[2]], speed=0.04, tol=0.003, max_steps=120)
|
| 685 |
+
sk.set_gripper(True, steps=15)
|
| 686 |
+
if not self.held(BOTTLE):
|
| 687 |
+
sk.set_gripper(False, steps=8)
|
| 688 |
+
self._go([k[0], k[1], k[2] + 0.08], speed=0.1)
|
| 689 |
+
continue
|
| 690 |
+
zl = Z + CAP_Z + 0.06
|
| 691 |
+
self._go([k[0], k[1], zl], speed=0.10)
|
| 692 |
+
sk.hold(15)
|
| 693 |
+
tx, ty = self.inst["bottle_xy"]
|
| 694 |
+
self._go([tx, ty, zl], speed=0.10)
|
| 695 |
+
sk.hold(25)
|
| 696 |
+
self._go([tx, ty, Z + CAP_Z + 0.015], speed=0.08)
|
| 697 |
+
self._go([tx, ty, Z + CAP_Z + 0.002], speed=0.03, tol=0.003, max_steps=120)
|
| 698 |
+
sk.set_gripper(False, steps=12)
|
| 699 |
+
self._go([tx, ty, Z + CAP_Z + 0.06], speed=0.08)
|
| 700 |
+
sk.hold(20)
|
| 701 |
+
self._settle(BOTTLE)
|
| 702 |
+
if self.bottle_in_place():
|
| 703 |
+
return True
|
| 704 |
+
return self.bottle_in_place()
|
| 705 |
+
|
| 706 |
+
def pull_in_bottle(self):
|
| 707 |
+
"""the lying bottle's cap is out of reach (it fell forward over the box): grasp the body near its bottom end
|
| 708 |
+
(fingers across it), lift it 3 cm, pull it towards the robot until the cap is within reach, set it down"""
|
| 709 |
+
sk = self.sk
|
| 710 |
+
Rb = self.R(BOTTLE)
|
| 711 |
+
ax = Rb[:, 2]
|
| 712 |
+
c = envs.obj_pos(self.env, BOTTLE)
|
| 713 |
+
g = c - ax * (H_TOT / 2 - 0.05) # 5 cm from the bottom end along the axis
|
| 714 |
+
zg = max(float(g[2] - Z), 0.02)
|
| 715 |
+
yaw = float(np.arctan2(ax[1], ax[0]))
|
| 716 |
+
need = _reach(self.cap_xyz()) - (REACH_MAX - 0.05)
|
| 717 |
+
to_base = np.array([-0.66, 0.0]) - g[:2]
|
| 718 |
+
to_base /= max(np.linalg.norm(to_base), 1e-6)
|
| 719 |
+
dst = g[:2] + to_base * need
|
| 720 |
+
sk.set_gripper(False, steps=8)
|
| 721 |
+
self._go([g[0], g[1], Z + 0.15], yaw=yaw, speed=0.15)
|
| 722 |
+
self._go([g[0], g[1], Z + zg + 0.015], speed=0.1)
|
| 723 |
+
self._go([g[0], g[1], Z + zg], speed=0.04, tol=0.003, max_steps=120)
|
| 724 |
+
sk.set_gripper(True, steps=15)
|
| 725 |
+
self._go([g[0], g[1], Z + zg + 0.03], speed=0.08)
|
| 726 |
+
self._go([dst[0], dst[1], Z + zg + 0.03], speed=0.08)
|
| 727 |
+
self._go([dst[0], dst[1], Z + zg + 0.005], speed=0.04)
|
| 728 |
+
sk.set_gripper(False, steps=12)
|
| 729 |
+
self._go([dst[0], dst[1], Z + 0.15], speed=0.1)
|
| 730 |
+
self._settle(BOTTLE)
|
| 731 |
+
|
| 732 |
+
def _fallen_cubes(self, done):
|
| 733 |
+
return [n for n in done if not self.in_box(n) and not self.over_box(n) and not self.held(n)]
|
| 734 |
+
|
| 735 |
+
# ------------------------------------------------------------ scripted policies
|
| 736 |
+
def execute(self, inst, params):
|
| 737 |
+
careful = params.get("careful", False)
|
| 738 |
+
zc = params.get("z_carry", Z_SAFE if careful else Z_CARRY)
|
| 739 |
+
zr = params.get("z_rel", Z_DROP if careful else Z_REL)
|
| 740 |
+
order = params.get("slots") or [(1, 1), (1, -1), (-1, 0)] # far row first (Sonnet fills from the far end)
|
| 741 |
+
cubes = params.get("cubes") or self._cube_order()
|
| 742 |
+
noise = params.get("noise") or {}
|
| 743 |
+
v = params.get("speed", 0.15)
|
| 744 |
+
done = []
|
| 745 |
+
for k, n in enumerate(cubes):
|
| 746 |
+
self.put_cube(n, k, order, zr, zc, noise=noise.get(n), v=v, v_down=params.get("v_down"))
|
| 747 |
+
done.append(n)
|
| 748 |
+
# looks after every step (Sonnet): re-places a cube that ended up outside the box ...
|
| 749 |
+
for f in self._fallen_cubes(done):
|
| 750 |
+
self.put_cube(f, done.index(f), order, zr, zc, v=v)
|
| 751 |
+
# ... and, if the bystander is in the policy's view of the task, stands the bottle up again
|
| 752 |
+
if params.get("restore") == "each" and not self.bottle_in_place():
|
| 753 |
+
self.restand_bottle()
|
| 754 |
+
if params.get("check"):
|
| 755 |
+
self.check_and_fix(order, zr, zc)
|
| 756 |
+
self.sk.hold(10)
|
| 757 |
+
|
| 758 |
+
def check_and_fix(self, order, zr, zc, rounds=2):
|
| 759 |
+
for _ in range(rounds):
|
| 760 |
+
v = self.stage_values()
|
| 761 |
+
if all(v.values()):
|
| 762 |
+
return True
|
| 763 |
+
for n in CUBES:
|
| 764 |
+
if not self.in_box(n):
|
| 765 |
+
self.put_cube(n, CUBES.index(n), order, zr, zc)
|
| 766 |
+
if not self.bottle_in_place():
|
| 767 |
+
self.restand_bottle()
|
| 768 |
+
return all(self.stage_values().values())
|
| 769 |
+
|
| 770 |
+
def _cube_order(self):
|
| 771 |
+
"""the cube nearest the box first"""
|
| 772 |
+
bxy = np.asarray(self.inst["box_xy"])
|
| 773 |
+
return sorted(CUBES, key=lambda n: float(np.linalg.norm(np.asarray(self.inst["start"][n]) - bxy)))
|
| 774 |
+
|
| 775 |
+
def default_params(self, inst):
|
| 776 |
+
"""Sonnet-like: cubes nearest-first, carried 15 cm up in straight lines, each lowered straight down onto the box
|
| 777 |
+
floor (far row first), looks after every step and re-places a cube that fell out; no special care for the
|
| 778 |
+
bottle (it is not part of the packing)"""
|
| 779 |
+
return dict(careful=False, restore=None, check=False)
|
| 780 |
+
|
| 781 |
+
def oracle_params(self, inst):
|
| 782 |
+
"""knows its arm: carries high (24 cm) and drops the cubes into the box from 16 cm, so the forearm stays above
|
| 783 |
+
the bottle; checks every stage at the end"""
|
| 784 |
+
return dict(careful=True, restore="each", check=True)
|
| 785 |
+
|
| 786 |
+
def adapt_params(self, inst, history):
|
| 787 |
+
"""attempt >= 2: the careful packing (high carry, drop from above the rim), stand the bottle up if needed,
|
| 788 |
+
check at the end"""
|
| 789 |
+
return dict(careful=True, restore="each", check=True)
|
| 790 |
+
|
| 791 |
+
def blind_params(self, inst, attempt, rng):
|
| 792 |
+
"""the natural behaviour again with small random variations, no history, no care for the bottle"""
|
| 793 |
+
pats = [[(1, 1), (1, -1), (-1, 0)], [(1, -1), (1, 1), (-1, 0)], [(0, 1), (0, -1), (-1, 0)],
|
| 794 |
+
[(1, 0), (-1, 1), (-1, -1)], [(1, 1), (-1, -1), (0, 0)]]
|
| 795 |
+
return dict(careful=False, restore=None, check=False, slots=pats[int(rng.integers(len(pats)))],
|
| 796 |
+
z_carry=float(rng.uniform(0.12, 0.20)), z_rel=float(rng.uniform(0.032, 0.055)),
|
| 797 |
+
noise={n: rng.uniform(-NAIVE_ERR, NAIVE_ERR, 2).tolist() for n in CUBES})
|
| 798 |
+
|
| 799 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 800 |
+
"""oracle / naive: one attempt; adaptive: attempt 1 = naive + stands the knocked bottle up again after every
|
| 801 |
+
step and checks at the end, attempts >= 2 careful; blind: naive with random variations.
|
| 802 |
+
Extra kinds (not in validate's table): switch (naive, then careful without restoring), oracle_noise (oracle with
|
| 803 |
+
+-5 mm placement noise)"""
|
| 804 |
+
k = k or self.max_attempts
|
| 805 |
+
rng = np.random.default_rng(seed)
|
| 806 |
+
history = []
|
| 807 |
+
for a in range(k):
|
| 808 |
+
self.reset_instance(inst)
|
| 809 |
+
if kind == "oracle":
|
| 810 |
+
params = self.oracle_params(inst)
|
| 811 |
+
elif kind == "naive":
|
| 812 |
+
params = self.default_params(inst)
|
| 813 |
+
elif kind == "adaptive":
|
| 814 |
+
params = dict(careful=False, restore="each", check=True) if a == 0 else self.adapt_params(inst, history)
|
| 815 |
+
elif kind == "blind":
|
| 816 |
+
params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
|
| 817 |
+
elif kind == "switch":
|
| 818 |
+
params = self.default_params(inst) if a == 0 else dict(careful=True, restore=None, check=False)
|
| 819 |
+
elif kind == "oracle_noise":
|
| 820 |
+
params = dict(self.oracle_params(inst), noise={n: rng.uniform(-0.005, 0.005, 2).tolist() for n in CUBES})
|
| 821 |
+
else:
|
| 822 |
+
raise ValueError(kind)
|
| 823 |
+
self.execute(inst, params)
|
| 824 |
+
out = self.outcome(inst)
|
| 825 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 826 |
+
if on_attempt:
|
| 827 |
+
on_attempt(a, params, out)
|
| 828 |
+
if out["success"] or kind in ("oracle", "naive", "oracle_noise"):
|
| 829 |
+
break
|
| 830 |
+
return history
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/agent_viewer/README.md
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Agent Viewer — historical replay
|
| 2 |
+
|
| 3 |
+
Export saved LFF-Bench API-player logs to one offline HTML page, including original
|
| 4 |
+
image bytes and the complete `rollout.mp4` when available. No model calls, simulator, server, build tools, or frontend dependencies
|
| 5 |
+
are required to generate or open the result.
|
| 6 |
+
|
| 7 |
+
From the repository root:
|
| 8 |
+
|
| 9 |
+
```bash
|
| 10 |
+
python scripts/agent_viewer/export.py \
|
| 11 |
+
--run runs/gpt/exp2d/exp2d-gpt-6-astra_l5_slide_to_target_s1000_full_F2_direct_k3_1007-060153_p9738 \
|
| 12 |
+
--out traces/agent-viewer-slide/index.html
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
Open the resulting HTML file in a browser. Repeat `--run` to include multiple
|
| 16 |
+
runs. If a run's original sandbox has moved, use `--sandbox /new/image/root`
|
| 17 |
+
with a single run. Relative images copied into the run directory take precedence.
|
| 18 |
+
The export remains usable after the original sandbox is removed.
|
| 19 |
+
|
| 20 |
+
## What the viewer shows
|
| 21 |
+
|
| 22 |
+
- Continuous execution video is the default view when `rollout.mp4` exists, with
|
| 23 |
+
native playback, seeking, fullscreen and playback speed controls. The original
|
| 24 |
+
MP4 is embedded byte-for-byte; no still-image slideshow is substituted.
|
| 25 |
+
- The separate step view retains input images and tool logs. Selecting an attempt
|
| 26 |
+
opens its step details. Video and logs are not automatically synchronized because
|
| 27 |
+
old recordings have no frame-to-event index and omit model waiting time.
|
| 28 |
+
|
| 29 |
+
- One step per recorded assistant response; tool calls and results stay together.
|
| 30 |
+
- The most recent observation **before** each decision, and separately the new
|
| 31 |
+
images returned **after** its actions. Older images may also be in model context;
|
| 32 |
+
the viewer shows the request's recorded image count when available.
|
| 33 |
+
- Camera switching, per-step playback, scrubbing, keyboard navigation (arrows and
|
| 34 |
+
space), and jumps to attempt verdicts. Playback uses fixed seconds per step,
|
| 35 |
+
with original elapsed/model latency shown separately.
|
| 36 |
+
- Tool arguments, raw tool results, public assistant replies, API retries, missing
|
| 37 |
+
images, and incomplete calls. Recorded reasoning summaries are exported verbatim between observation and action in the step details.
|
| 38 |
+
The summary of decision N is shown between the preceding feedback and action N.
|
| 39 |
+
Public replies are labeled separately; missing summaries stay explicitly missing.
|
| 40 |
+
These are recorded summaries, not full internal CoT or reconstructed reasoning.
|
| 41 |
+
- A reset warning when a failed `done` returns the next attempt's initial images.
|
| 42 |
+
Attempt success comes from server `done` events, not the assistant's claim.
|
| 43 |
+
|
| 44 |
+
## Current input contract and limitations
|
| 45 |
+
|
| 46 |
+
Supports the API-player `ev` schema in `transcript.jsonl` or
|
| 47 |
+
`gpt_transcript.jsonl`, with `session.json` and optional `events.jsonl`. Other
|
| 48 |
+
harness formats (MCP, native Codex/Claude, RPent, GPT-Policy) need adapters and
|
| 49 |
+
are not claimed as supported. Corrupt JSON and ambiguous result matching fail
|
| 50 |
+
explicitly instead of silently pairing the wrong steps.
|
| 51 |
+
|
| 52 |
+
Image files are copied byte-for-byte at export time. Old logs contain paths rather
|
| 53 |
+
than image hashes, so files overwritten since the run cannot be authenticated as
|
| 54 |
+
the original model inputs. Missing images are visibly marked; no replacement
|
| 55 |
+
frames are invented. Runs without a video fall back to step replay with the video tab disabled.
|
| 56 |
+
|
| 57 |
+
The sample video is 19.05 seconds, H.264, 640×376 at 20 fps. Its action segments
|
| 58 |
+
were recorded at 3× simulation speed; choose ⅓× playback to slow them back down.
|
| 59 |
+
The recording includes both attempts and their verdict cards, but not model/API
|
| 60 |
+
waiting time.
|
| 61 |
+
|
| 62 |
+
The sample `l5_slide_to_target`, seed 1000, has 14 assistant responses, 13 tool
|
| 63 |
+
calls, and two verdicts: failure then success. It is a historical development
|
| 64 |
+
run using depth perception and F2 feedback, not evidence of general benchmark
|
| 65 |
+
performance. The first push overshot by 4 cm; the next push reduced its endpoint
|
| 66 |
+
from x=-0.105 m to x=-0.145 m and succeeded.
|
| 67 |
+
|
| 68 |
+
## Verification
|
| 69 |
+
|
| 70 |
+
```bash
|
| 71 |
+
python -m unittest discover -s tests -p test_agent_viewer.py -v
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
Regression cases cover observation/action ordering, resets, carried-forward
|
| 75 |
+
observations, API retries, missing artifacts, incomplete calls, reordered call
|
| 76 |
+
IDs, malformed logs, path restrictions, and safe embedding of untrusted text.
|
| 77 |
+
|
| 78 |
+
## Recording future runs
|
| 79 |
+
|
| 80 |
+
`api_player.py` already requests provider summaries (`auto` for OpenAI) and
|
| 81 |
+
saves returned `reasoning_summary` plus public `text` for each assistant turn.
|
| 82 |
+
`run_agent.py` now also defaults `--reasoning-summary` to `auto`; pass `none`
|
| 83 |
+
when an endpoint cannot support the option. Both loggers add
|
| 84 |
+
`reasoning_summary_status`: `recorded` when a summary is present and
|
| 85 |
+
`not_returned` when the response contains none. This labels response availability,
|
| 86 |
+
not whether summaries were requested or whether the model reasoned internally.
|
| 87 |
+
|
| 88 |
+
Historical missing records are left unchanged. No extra model calls or
|
| 89 |
+
retrospective rationale generation are used. Changes apply to newly started
|
| 90 |
+
processes from this checkout; other worktrees and native CLI harnesses retain
|
| 91 |
+
their own logging behavior. The viewer still imports API-player transcripts;
|
| 92 |
+
`run_agent` logs use a different schema and need an adapter to view here.
|
| 93 |
+
|
| 94 |
+
## Live terminal viewer
|
| 95 |
+
|
| 96 |
+
`live.py` observes existing runs without contacting the robot/model or changing the
|
| 97 |
+
run. Use a terminal with truecolor support for low-resolution color image previews;
|
| 98 |
+
`--ascii` provides a monochrome fallback. Pillow is the only image dependency and
|
| 99 |
+
is already present in the evaluation environment.
|
| 100 |
+
|
| 101 |
+
```bash
|
| 102 |
+
python scripts/agent_viewer/live.py --batch /absolute/path/to/runs/api/BATCH
|
| 103 |
+
python scripts/agent_viewer/live.py --run /absolute/path/to/RUN --once --ascii
|
| 104 |
+
```
|
| 105 |
+
|
| 106 |
+
A batch view follows the first running run and switches when the manifest advances;
|
| 107 |
+
for concurrent runs in one batch, use `--run` to select another. Refresh defaults to
|
| 108 |
+
6 seconds. `Ctrl+C` exits; `--no-images`, `--width`, `--image-rows`, `--interval`, and
|
| 109 |
+
`--duration` control presentation. A redirected output uses ASCII and no screen
|
| 110 |
+
control codes. `--once` prints one snapshot.
|
| 111 |
+
|
| 112 |
+
Supported live sources: API-player transcripts; framework gateway/MCP tool logs;
|
| 113 |
+
and Codex `item.completed` events. Only successful `view_images` attachments or
|
| 114 |
+
API-player image inputs become displayed observations. Robot-produced files alone
|
| 115 |
+
do not establish that the Agent saw them. Matching embedded images from native
|
| 116 |
+
Codex events take precedence over file references; potentially overwritten files
|
| 117 |
+
are marked unavailable. The current view displays the latest observation batch,
|
| 118 |
+
not continuous video, and explicitly labels its age. Recorded summaries are shown
|
| 119 |
+
when the relevant stream provides them. It does not expose `session.json` tokens,
|
| 120 |
+
server-side hidden task parameters, or send any robot commands.
|
| 121 |
+
|
| 122 |
+
```bash
|
| 123 |
+
python -m unittest discover -s tests -p test_live_viewer.py -v
|
| 124 |
+
```
|
| 125 |
+
|
| 126 |
+
### Clearer terminal images
|
| 127 |
+
|
| 128 |
+
The old character preview was limited to 20 rows (at most ~40 vertical pixels).
|
| 129 |
+
It now uses available terminal height and width. `--camera main` or `--camera wrist`
|
| 130 |
+
selects a larger single view. Character mode is still a low-resolution preview.
|
| 131 |
+
|
| 132 |
+
For actual image pixels, use `--renderer iterm` (iTerm2 / WezTerm / VS Code with
|
| 133 |
+
`terminal.integrated.enableImages: true`) or `--renderer kitty`. Native mode
|
| 134 |
+
encodes original-resolution pixels as PNG; the terminal fits the display without
|
| 135 |
+
reducing the transmitted image to text-cell resolution. `auto` recognizes iTerm2,
|
| 136 |
+
WezTerm and Kitty environment markers; unknown terminals and multiplexers retain
|
| 137 |
+
the ANSI fallback. VS Code needs an explicit `--renderer iterm` after its setting
|
| 138 |
+
is enabled. Native protocol encoding is tested; visual compatibility still needs
|
| 139 |
+
to be checked in the user's terminal. Use a direct terminal outside tmux/screen
|
| 140 |
+
if image passthrough has not been configured. Redirected output always stays text.
|
| 141 |
+
|
| 142 |
+
Existing CLI processes keep their original interval and renderer: exit with Ctrl+C
|
| 143 |
+
and restart to pick up changes. Evaluation processes need no restart.
|
| 144 |
+
|
| 145 |
+
The user's Claude development terminal (`TERM_PROGRAM=claude-desktop`) displayed
|
| 146 |
+
an empty image area with the iTerm transport. In that environment, even an explicit
|
| 147 |
+
`--renderer iterm` now falls back to ANSI with a visible explanation. This avoids
|
| 148 |
+
blank frames but does not provide native image detail. Use `--camera main` for a
|
| 149 |
+
larger single-camera preview; original-resolution viewing needs an image-capable
|
| 150 |
+
viewer. No Claude terminal setting enabling inline images has been verified.
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/agent_viewer/export.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Export saved API-player runs as a portable, offline Agent Viewer.
|
| 2 |
+
|
| 3 |
+
No simulator/model calls are made. Original image bytes are embedded once.
|
| 4 |
+
Supports transcript.jsonl and gpt_transcript.jsonl (API-player event schema).
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
import base64
|
| 10 |
+
import hashlib
|
| 11 |
+
import json
|
| 12 |
+
import re
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def read_jsonl(path):
|
| 17 |
+
rows = []
|
| 18 |
+
for number, line in enumerate(path.read_text().splitlines(), 1):
|
| 19 |
+
if line.strip():
|
| 20 |
+
try:
|
| 21 |
+
rows.append(json.loads(line))
|
| 22 |
+
except json.JSONDecodeError as exc:
|
| 23 |
+
raise ValueError(f"{path.name}:{number}: malformed JSON; export a completed log") from exc
|
| 24 |
+
return rows
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def parse_output(value):
|
| 28 |
+
if isinstance(value, dict):
|
| 29 |
+
return value
|
| 30 |
+
try:
|
| 31 |
+
parsed = json.loads(value)
|
| 32 |
+
return parsed if isinstance(parsed, dict) else {}
|
| 33 |
+
except (ValueError, TypeError):
|
| 34 |
+
return {}
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def build_run(folder, assets, sandbox_override=None):
|
| 38 |
+
folder = Path(folder)
|
| 39 |
+
transcript = next((folder / name for name in ('transcript.jsonl', 'gpt_transcript.jsonl')
|
| 40 |
+
if (folder / name).exists()), None)
|
| 41 |
+
if not transcript:
|
| 42 |
+
raise ValueError(f"No supported API-player transcript in {folder}")
|
| 43 |
+
rows = read_jsonl(transcript)
|
| 44 |
+
if not any(row.get('ev') == 'assistant' for row in rows):
|
| 45 |
+
raise ValueError(f"No API-player assistant events in {transcript}")
|
| 46 |
+
session = json.loads((folder / 'session.json').read_text())
|
| 47 |
+
events = read_jsonl(folder / 'events.jsonl') if (folder / 'events.jsonl').exists() else []
|
| 48 |
+
start = next((r for r in rows if r.get('ev') == 'start'), {})
|
| 49 |
+
server = next((r for r in events if r.get('ev') == 'session_start'), {})
|
| 50 |
+
sandbox = Path(sandbox_override or session.get('sandbox', folder))
|
| 51 |
+
warnings, cache = [], {}
|
| 52 |
+
|
| 53 |
+
def images(refs, source, timestamp):
|
| 54 |
+
result = []
|
| 55 |
+
for ref in refs:
|
| 56 |
+
if not isinstance(ref, str):
|
| 57 |
+
raise ValueError('Expected image path strings in API-player transcript')
|
| 58 |
+
if ref not in cache:
|
| 59 |
+
relative = Path(ref)
|
| 60 |
+
roots = [folder, sandbox]
|
| 61 |
+
candidates = []
|
| 62 |
+
# Only export images within the explicitly selected run/sandbox.
|
| 63 |
+
for root in roots:
|
| 64 |
+
candidate = (root / relative).resolve()
|
| 65 |
+
if candidate.is_relative_to(root.resolve()):
|
| 66 |
+
candidates.append(candidate)
|
| 67 |
+
path = next((p for p in candidates if p.is_file()), None)
|
| 68 |
+
key = None
|
| 69 |
+
if path:
|
| 70 |
+
raw = path.read_bytes()
|
| 71 |
+
if raw.startswith(b'\xff\xd8\xff'):
|
| 72 |
+
mime = 'image/jpeg'
|
| 73 |
+
elif raw.startswith(b'\x89PNG\r\n\x1a\n'):
|
| 74 |
+
mime = 'image/png'
|
| 75 |
+
elif raw[:6] in (b'GIF87a', b'GIF89a'):
|
| 76 |
+
mime = 'image/gif'
|
| 77 |
+
elif raw[:4] == b'RIFF' and raw[8:12] == b'WEBP':
|
| 78 |
+
mime = 'image/webp'
|
| 79 |
+
else:
|
| 80 |
+
raise ValueError(f'Unsupported image bytes: {ref}')
|
| 81 |
+
key = hashlib.sha256(raw).hexdigest()[:24]
|
| 82 |
+
assets[key] = f'data:{mime};base64,' + base64.b64encode(raw).decode()
|
| 83 |
+
else:
|
| 84 |
+
warnings.append(f'图片缺失:{ref}')
|
| 85 |
+
name = relative.stem
|
| 86 |
+
camera = 'agentview' if 'agentview' in name else 'wrist' if 'wrist' in name else name
|
| 87 |
+
cache[ref] = {'asset': key, 'path': ref, 'camera': camera}
|
| 88 |
+
result.append({**cache[ref], 'source': source, 'at': timestamp})
|
| 89 |
+
return result
|
| 90 |
+
|
| 91 |
+
outcomes = [{'attempt': e.get('attempt'), 'success': e.get('success'),
|
| 92 |
+
'feedback': e.get('feedback', ''), 'at': e.get('t')}
|
| 93 |
+
for e in events if e.get('ev') == 'done']
|
| 94 |
+
steps, pending, latest, latest_text = [], [], [], ''
|
| 95 |
+
attempt, origin, active, task_text = 1, rows[0].get('t', 0), None, ''
|
| 96 |
+
for line, row in enumerate(rows, 1):
|
| 97 |
+
kind = row.get('ev')
|
| 98 |
+
if kind == 'user':
|
| 99 |
+
latest_text = row.get('text', '')
|
| 100 |
+
if not task_text:
|
| 101 |
+
match = re.search(r'\{.*\}', latest_text, re.S)
|
| 102 |
+
task_text = parse_output(match.group() if match else '').get('task', latest_text)
|
| 103 |
+
if row.get('images'):
|
| 104 |
+
latest = images(row['images'], line, row.get('t'))
|
| 105 |
+
elif kind in ('api_error', 'abort'):
|
| 106 |
+
pending.append({'kind': kind, 'text': row.get('error', ''), 'at': row.get('t')})
|
| 107 |
+
elif kind == 'assistant':
|
| 108 |
+
calls = row.get('tool_calls', [])
|
| 109 |
+
active = {
|
| 110 |
+
'index': len(steps), 'turn': row.get('turn'), 'attempt': attempt,
|
| 111 |
+
'at': row.get('t'), 'elapsed': max(0, row.get('t', origin) - origin),
|
| 112 |
+
'latency': row.get('latency_s'), 'before': list(latest),
|
| 113 |
+
'inputText': latest_text, 'text': row.get('text') or '',
|
| 114 |
+
'decisionSummary': row.get('reasoning_summary') or None,
|
| 115 |
+
'decisionSummaryStatus': row.get('reasoning_summary_status', 'not_recorded'),
|
| 116 |
+
'decisionSourceLine': line,
|
| 117 |
+
'actions': [{'id': c.get('id'), 'name': c.get('name', 'tool'),
|
| 118 |
+
'arguments': c.get('arguments', {}), 'result': None,
|
| 119 |
+
'after': []} for c in calls],
|
| 120 |
+
'notices': pending, 'verdict': None,
|
| 121 |
+
'requestImages': row.get('request_stats', {}).get('n_images'),
|
| 122 |
+
}
|
| 123 |
+
pending = []
|
| 124 |
+
steps.append(active)
|
| 125 |
+
elif kind == 'tool':
|
| 126 |
+
if active is None:
|
| 127 |
+
warnings.append(f'第 {line} 行工具结果缺少前置调用')
|
| 128 |
+
continue
|
| 129 |
+
if row.get('turn') is not None and row.get('turn') != active['turn']:
|
| 130 |
+
raise ValueError(f'Tool turn mismatch at transcript line {line}')
|
| 131 |
+
unresolved = [a for a in active['actions'] if a['result'] is None]
|
| 132 |
+
call_id = row.get('call_id') or row.get('tool_call_id')
|
| 133 |
+
action = next((a for a in unresolved if call_id and a['id'] == call_id), None)
|
| 134 |
+
if call_id and action is None:
|
| 135 |
+
raise ValueError(f'Unknown tool call id at transcript line {line}')
|
| 136 |
+
if action is None:
|
| 137 |
+
action = next((a for a in unresolved if isinstance(a['arguments'], dict)
|
| 138 |
+
and a['arguments'].get('command') == row.get('command')), None)
|
| 139 |
+
if action is None and len(unresolved) == 1:
|
| 140 |
+
action = unresolved[0]
|
| 141 |
+
if action is None:
|
| 142 |
+
raise ValueError(f'Ambiguous tool result at transcript line {line}')
|
| 143 |
+
output = row.get('output', '')
|
| 144 |
+
action['result'] = output
|
| 145 |
+
action['at'] = row.get('t')
|
| 146 |
+
action['after'] = images(row.get('images', []), line, row.get('t'))
|
| 147 |
+
parsed = parse_output(output)
|
| 148 |
+
action['ok'] = parsed.get('ok')
|
| 149 |
+
latest_text = output if isinstance(output, str) else json.dumps(output, ensure_ascii=False)
|
| 150 |
+
if action['after']:
|
| 151 |
+
latest = list(action['after'])
|
| 152 |
+
command = row.get('command') or (action['arguments'].get('command', '')
|
| 153 |
+
if isinstance(action['arguments'], dict) else '')
|
| 154 |
+
if command.split(' ', 1)[0] == 'done':
|
| 155 |
+
verdict = next((o for o in outcomes if o['attempt'] == attempt), None)
|
| 156 |
+
if verdict:
|
| 157 |
+
active['verdict'] = verdict
|
| 158 |
+
# A failed done may immediately return RESET images for the next attempt.
|
| 159 |
+
message = parsed.get('message', '')
|
| 160 |
+
next_attempt = re.search(r'Attempt\s+(\d+)\s+of', message)
|
| 161 |
+
if next_attempt:
|
| 162 |
+
attempt = int(next_attempt.group(1))
|
| 163 |
+
action['resetToAttempt'] = attempt
|
| 164 |
+
if pending:
|
| 165 |
+
steps[-1]['noticesAfter'] = pending
|
| 166 |
+
for step in steps:
|
| 167 |
+
step['incomplete'] = any(a['result'] is None for a in step['actions'])
|
| 168 |
+
status = 'success' if any(o['success'] is True for o in outcomes) else (
|
| 169 |
+
'failed' if outcomes and any(r.get('ev') == 'end' and r.get('finished') is True for r in rows) else 'incomplete')
|
| 170 |
+
video = None
|
| 171 |
+
video_path = folder / 'rollout.mp4'
|
| 172 |
+
if video_path.is_file():
|
| 173 |
+
raw = video_path.read_bytes()
|
| 174 |
+
if len(raw) < 12 or raw[4:8] != b'ftyp':
|
| 175 |
+
raise ValueError('rollout.mp4 is not an MP4 container')
|
| 176 |
+
key = 'video-' + hashlib.sha256(raw).hexdigest()[:24]
|
| 177 |
+
assets[key] = 'data:video/mp4;base64,' + base64.b64encode(raw).decode()
|
| 178 |
+
video = {'asset': key, 'name': 'rollout.mp4'}
|
| 179 |
+
return {'id': folder.name, 'video': video, 'task': server.get('task', folder.name),
|
| 180 |
+
'taskText': task_text, 'seed': server.get('seed'), 'model': start.get('model', '未记录'),
|
| 181 |
+
'perception': server.get('perception', '未记录'), 'feedback': server.get('feedback', '未记录'),
|
| 182 |
+
'status': status, 'steps': steps, 'outcomes': outcomes,
|
| 183 |
+
'warnings': sorted(set(warnings)), 'source': transcript.name,
|
| 184 |
+
'actionCount': sum(len(s['actions']) for s in steps)}
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def render(folders, output, sandbox_override=None):
|
| 188 |
+
assets = {}
|
| 189 |
+
runs = [build_run(folder, assets, sandbox_override) for folder in folders]
|
| 190 |
+
payload = json.dumps({'version': 1, 'runs': runs, 'assets': assets}, ensure_ascii=False)
|
| 191 |
+
# Logs are untrusted text, including strings containing HTML/script terminators.
|
| 192 |
+
payload = payload.replace('&', '\\u0026').replace('<', '\\u003c').replace('>', '\\u003e')
|
| 193 |
+
template = Path(__file__).with_name('viewer.html').read_text()
|
| 194 |
+
output = Path(output)
|
| 195 |
+
output.parent.mkdir(parents=True, exist_ok=True)
|
| 196 |
+
output.write_text(template.replace('/*__PAYLOAD__*/null', payload))
|
| 197 |
+
return runs
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def main():
|
| 201 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 202 |
+
parser.add_argument('--run', type=Path, action='append', required=True, help='Repeat to include multiple runs')
|
| 203 |
+
parser.add_argument('--out', type=Path, required=True)
|
| 204 |
+
parser.add_argument('--sandbox', type=Path, help='Relocated image directory for a single run')
|
| 205 |
+
args = parser.parse_args()
|
| 206 |
+
if args.sandbox and len(args.run) != 1:
|
| 207 |
+
parser.error('--sandbox requires exactly one --run')
|
| 208 |
+
try:
|
| 209 |
+
runs = render(args.run, args.out, args.sandbox)
|
| 210 |
+
except (ValueError, OSError, KeyError) as exc:
|
| 211 |
+
parser.exit(1, f'Export failed: {exc}\n')
|
| 212 |
+
print(json.dumps({'output': str(args.out.resolve()), 'runs': [
|
| 213 |
+
{'task': r['task'], 'steps': len(r['steps']), 'actions': r['actionCount'],
|
| 214 |
+
'outcomes': [o['success'] for o in r['outcomes']], 'warnings': r['warnings']} for r in runs
|
| 215 |
+
]}, ensure_ascii=False, indent=2))
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
if __name__ == '__main__':
|
| 219 |
+
main()
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/tools.py
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Agent-facing tool interface on top of `Skills`.
|
| 2 |
+
|
| 3 |
+
Every action tool calls the task's `Skills` object, so the task's hidden calibration `bias` keeps
|
| 4 |
+
acting on every commanded position. Proprioception is reported in the robot's own (possibly
|
| 5 |
+
miscalibrated) frame: reported eef = true eef - bias, i.e. the robot "believes" it reached the
|
| 6 |
+
commanded point; only the cameras show the truth. Camera-derived quantities (pixel_to_world) and
|
| 7 |
+
the privileged `locate` tool are in the true world frame.
|
| 8 |
+
|
| 9 |
+
Tool schemas are plain JSON schema (OpenAI strict-mode compatible: every property listed in
|
| 10 |
+
`required`, optional ones nullable, no additional properties).
|
| 11 |
+
"""
|
| 12 |
+
import json
|
| 13 |
+
import math
|
| 14 |
+
import time
|
| 15 |
+
from dataclasses import dataclass, field
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
|
| 19 |
+
from .. import envs
|
| 20 |
+
from . import camera as C
|
| 21 |
+
from .images import ImageRef
|
| 22 |
+
|
| 23 |
+
TABLE_Z = envs.TABLE_Z
|
| 24 |
+
# Workspace limits for commanded grasp-point positions (world frame, metres). Targets outside are
|
| 25 |
+
# clipped and the report says so.
|
| 26 |
+
WS_LO = np.array([-0.55, -0.45, TABLE_Z + 0.005])
|
| 27 |
+
WS_HI = np.array([0.35, 0.45, TABLE_Z + 0.50])
|
| 28 |
+
SPEED_RANGE = (0.02, 1.0)
|
| 29 |
+
PUSH_DIST_RANGE = (0.0, 0.40)
|
| 30 |
+
RUNUP_RANGE = (0.02, 0.30)
|
| 31 |
+
|
| 32 |
+
ACTION_TOOLS = ("move_to", "open_gripper", "close_gripper", "push")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _num(desc):
|
| 36 |
+
return {"type": "number", "description": desc}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _opt_num(desc):
|
| 40 |
+
return {"type": ["number", "null"], "description": desc}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _fn(name, desc, props=None):
|
| 44 |
+
props = props or {}
|
| 45 |
+
return dict(name=name, description=desc,
|
| 46 |
+
parameters={"type": "object", "properties": props, "required": list(props),
|
| 47 |
+
"additionalProperties": False})
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def tool_specs(privileged_locate=False, object_names=None, image_res=512):
|
| 51 |
+
"""Backend-neutral tool list: [{name, description, parameters}]."""
|
| 52 |
+
specs = [
|
| 53 |
+
_fn("move_to",
|
| 54 |
+
"Move the gripper's grasp point (midway between the fingertips) in a straight line to the world "
|
| 55 |
+
"position (x, y, z) with the gripper pointing straight down and rotated to `yaw`. The gripper "
|
| 56 |
+
"opening is not changed. Returns whether the target was reached, the end-effector position, gripper "
|
| 57 |
+
"width, whether an object is held and whether the arm touched an object during the motion.",
|
| 58 |
+
{"x": _num("target x, metres (world frame; +x away from the robot)"),
|
| 59 |
+
"y": _num("target y, metres (world frame; +y to the robot's left)"),
|
| 60 |
+
"z": _num(f"target z, metres (table top is z = {TABLE_Z:.2f})"),
|
| 61 |
+
"yaw": _num("gripper rotation about the vertical axis in DEGREES; 0 = fingers close along the world "
|
| 62 |
+
"y axis, 90 = fingers close along the world x axis. Taken modulo 180 (the two-finger "
|
| 63 |
+
"gripper is symmetric): the controller uses the equivalent angle closest to the current "
|
| 64 |
+
"yaw within +-113 deg; the report gives the yaw actually used"),
|
| 65 |
+
"speed": _opt_num("straight-line speed in m/s (0.02-1.0); null = as fast as the controller allows "
|
| 66 |
+
"(about 0.6 m/s)")}),
|
| 67 |
+
_fn("open_gripper", "Open the gripper fully (the arm holds its position)."),
|
| 68 |
+
_fn("close_gripper", "Close the gripper (the arm holds its position). Closing on an object grasps it."),
|
| 69 |
+
_fn("push",
|
| 70 |
+
"Straight-line push with the closed gripper. The gripper closes, moves above the point `runup` metres "
|
| 71 |
+
"behind (x, y) (opposite to the push direction), descends to height z, sweeps along (dir_x, dir_y) "
|
| 72 |
+
"through (x, y) and stops `distance` metres past (x, y), moving at `speed` m/s, then lifts 12 cm. The "
|
| 73 |
+
"gripper is rotated automatically to a fixed orientation relative to the push direction.",
|
| 74 |
+
{"x": _num("x of the point where the push should start acting (e.g. the near face of the object), m"),
|
| 75 |
+
"y": _num("y of that point, m"),
|
| 76 |
+
"dir_x": _num("x component of the push direction (normalised internally)"),
|
| 77 |
+
"dir_y": _num("y component of the push direction"),
|
| 78 |
+
"distance": _num("how far past (x, y) the gripper travels, metres (0-0.40)"),
|
| 79 |
+
"speed": _num("sweep speed, m/s (0.02-1.0; the controller saturates near 0.6)"),
|
| 80 |
+
"z": _opt_num(f"height of the grasp point during the sweep, m; null = {TABLE_Z + 0.02:.2f} "
|
| 81 |
+
"(2 cm above the table)"),
|
| 82 |
+
"runup": _opt_num("distance behind (x, y) where the sweep starts, m (0.02-0.30); null = 0.06. A longer "
|
| 83 |
+
"run-up lets the gripper reach the commanded speed before contact.")}),
|
| 84 |
+
_fn("get_observation",
|
| 85 |
+
"Return the current camera images (agentview and wrist) and the robot's proprioceptive state."),
|
| 86 |
+
_fn("pixel_to_world",
|
| 87 |
+
f"Back-project an image pixel to a 3-D world point using the camera's depth map. (u, v) are pixel "
|
| 88 |
+
f"coordinates in the {image_res}x{image_res} image exactly as you received it: u = column from the "
|
| 89 |
+
f"left edge, v = row from the top edge. Returns the world point (x, y, z) of the surface seen at that "
|
| 90 |
+
f"pixel and its height above the table.",
|
| 91 |
+
{"camera": {"type": "string", "enum": ["agentview", "wrist"], "description": "which image"},
|
| 92 |
+
"u": _num("column (0 = left edge)"), "v": _num("row (0 = top edge)")}),
|
| 93 |
+
_fn("done",
|
| 94 |
+
"Finish the current attempt. Call this when you believe the task is complete (or you want to stop). "
|
| 95 |
+
"Give a short reason: what you did and whether you think it worked.",
|
| 96 |
+
{"reason": {"type": "string", "description": "short explanation"}}),
|
| 97 |
+
]
|
| 98 |
+
if privileged_locate:
|
| 99 |
+
names = list(object_names or [])
|
| 100 |
+
prop = {"type": "string", "description": "object name"}
|
| 101 |
+
if names:
|
| 102 |
+
prop["enum"] = names
|
| 103 |
+
specs.insert(-1, _fn("locate",
|
| 104 |
+
"PRIVILEGED (ablation): return the true world position of an object's origin and its "
|
| 105 |
+
"axis-aligned bounding box.", {"object_name": prop}))
|
| 106 |
+
return specs
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
@dataclass
|
| 110 |
+
class ToolResult:
|
| 111 |
+
name: str
|
| 112 |
+
args: dict
|
| 113 |
+
ok: bool
|
| 114 |
+
report: dict
|
| 115 |
+
images: list = field(default_factory=list)
|
| 116 |
+
ended: bool = False
|
| 117 |
+
wall_s: float = 0.0
|
| 118 |
+
sim_steps: int = 0
|
| 119 |
+
|
| 120 |
+
def text(self):
|
| 121 |
+
return json.dumps(self.report, separators=(", ", ": "), default=_json_default)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _json_default(o):
|
| 125 |
+
if isinstance(o, (np.floating,)):
|
| 126 |
+
return float(o)
|
| 127 |
+
if isinstance(o, (np.integer,)):
|
| 128 |
+
return int(o)
|
| 129 |
+
if isinstance(o, np.ndarray):
|
| 130 |
+
return o.tolist()
|
| 131 |
+
if isinstance(o, (np.bool_,)):
|
| 132 |
+
return bool(o)
|
| 133 |
+
raise TypeError(type(o))
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _r(v, nd=4):
|
| 137 |
+
return [round(float(x), nd) for x in v]
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class ContactTracker:
|
| 141 |
+
"""Collects the objects the robot touches. Contacts are checked after every MuJoCo substep (a control
|
| 142 |
+
step is 25 substeps; a fast push touches the object for less than one control step, so checking only at
|
| 143 |
+
control-step boundaries misses it -- measured). Implemented by wrapping `env.sim.step` once per env; the
|
| 144 |
+
wrapper only reads contacts and dispatches to the currently active tracker."""
|
| 145 |
+
|
| 146 |
+
def __init__(self, env):
|
| 147 |
+
self.env = env
|
| 148 |
+
m = env.sim.model
|
| 149 |
+
self.is_robot = np.zeros(m.ngeom, bool)
|
| 150 |
+
self.is_robot[envs.robot_geom_ids(env)] = True
|
| 151 |
+
self.names = []
|
| 152 |
+
self.obj_of = np.full(m.ngeom, -1, int)
|
| 153 |
+
for name in list(env.objects_dict) + list(getattr(env, "fixtures_dict", {}) or {}):
|
| 154 |
+
try:
|
| 155 |
+
ids = envs.obj_geom_ids(env, name)
|
| 156 |
+
except Exception: # fixtures without contact geoms
|
| 157 |
+
continue
|
| 158 |
+
self.obj_of[ids] = len(self.names)
|
| 159 |
+
self.names.append(name)
|
| 160 |
+
self.touched = set()
|
| 161 |
+
sim = env.sim
|
| 162 |
+
if not getattr(sim, "_lff_step_wrapped", False):
|
| 163 |
+
orig = sim.step
|
| 164 |
+
|
| 165 |
+
def step(*a, **k):
|
| 166 |
+
orig(*a, **k)
|
| 167 |
+
t = getattr(sim, "_lff_tracker", None)
|
| 168 |
+
if t is not None:
|
| 169 |
+
t.check()
|
| 170 |
+
sim.step = step
|
| 171 |
+
sim._lff_step_wrapped = True
|
| 172 |
+
sim._lff_tracker = self
|
| 173 |
+
|
| 174 |
+
def reset(self):
|
| 175 |
+
self.touched = set()
|
| 176 |
+
|
| 177 |
+
def check(self):
|
| 178 |
+
d = self.env.sim.data
|
| 179 |
+
n = d.ncon
|
| 180 |
+
if not n:
|
| 181 |
+
return
|
| 182 |
+
g1 = np.asarray(d.contact.geom1)[:n]
|
| 183 |
+
g2 = np.asarray(d.contact.geom2)[:n]
|
| 184 |
+
hit = np.concatenate([self.obj_of[g2[self.is_robot[g1]]], self.obj_of[g1[self.is_robot[g2]]]])
|
| 185 |
+
for i in set(hit[hit >= 0].tolist()):
|
| 186 |
+
self.touched.add(self.names[i])
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def parse_args(raw):
|
| 190 |
+
if raw is None:
|
| 191 |
+
return {}
|
| 192 |
+
if isinstance(raw, dict):
|
| 193 |
+
return dict(raw)
|
| 194 |
+
raw = raw.strip()
|
| 195 |
+
return json.loads(raw) if raw else {}
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
class ToolExecutor:
|
| 199 |
+
"""Executes agent tool calls on a task whose instance has just been reset (task.sk is live)."""
|
| 200 |
+
|
| 201 |
+
def __init__(self, task, inst, image_res=512, cams=("agentview", "wrist"), privileged_locate=False,
|
| 202 |
+
grasp_report="bool", jpeg_quality=90, image_sink=None):
|
| 203 |
+
self.task = task
|
| 204 |
+
self.inst = inst
|
| 205 |
+
self.env = task.env
|
| 206 |
+
self.sk = task.sk # keep our own reference: the scripted backend may swap task.sk for a proxy
|
| 207 |
+
self.image_res = int(image_res)
|
| 208 |
+
self.cams = tuple(cams)
|
| 209 |
+
self.privileged_locate = privileged_locate
|
| 210 |
+
self.grasp_report = grasp_report # "bool" | "name" | "none"
|
| 211 |
+
self.jpeg_quality = jpeg_quality
|
| 212 |
+
self.image_sink = image_sink # callable(ImageRef) -> path (saves the image)
|
| 213 |
+
self.objects = list(self.env.objects_dict)
|
| 214 |
+
self.tracker = ContactTracker(self.env) # task recorders / hooks on Skills are left untouched
|
| 215 |
+
self._depth_cache = {}
|
| 216 |
+
self.n_calls = 0
|
| 217 |
+
|
| 218 |
+
# ------------------------------------------------------------------ state
|
| 219 |
+
def eef_yaw_deg(self):
|
| 220 |
+
R = self.sk.eef_mat() @ self.sk.R0.T
|
| 221 |
+
return math.degrees(math.atan2(R[1, 0], R[0, 0]))
|
| 222 |
+
|
| 223 |
+
def held(self):
|
| 224 |
+
names = [o for o in self.objects if self.sk.holding(o)]
|
| 225 |
+
return names
|
| 226 |
+
|
| 227 |
+
def _holding_field(self, names):
|
| 228 |
+
if self.grasp_report == "name":
|
| 229 |
+
return names[0] if names else None
|
| 230 |
+
if self.grasp_report == "none":
|
| 231 |
+
return None
|
| 232 |
+
return bool(names)
|
| 233 |
+
|
| 234 |
+
def proprio(self):
|
| 235 |
+
believed = self.sk.eef_pos() - self.sk.bias
|
| 236 |
+
p = dict(eef_pos=_r(believed), eef_yaw_deg=round(self.eef_yaw_deg(), 1),
|
| 237 |
+
gripper="closed" if self.sk.grip > 0 else "open",
|
| 238 |
+
gripper_width_m=round(self.sk.gripper_width(), 4))
|
| 239 |
+
if self.grasp_report != "none":
|
| 240 |
+
p["holding_object"] = self._holding_field(self.held())
|
| 241 |
+
return p
|
| 242 |
+
|
| 243 |
+
def render(self, cam, res=None):
|
| 244 |
+
res = res or self.image_res
|
| 245 |
+
return envs.render(self.env, C.mj_cam(cam), res)
|
| 246 |
+
|
| 247 |
+
def observe(self, label=""):
|
| 248 |
+
imgs = []
|
| 249 |
+
for cam in self.cams:
|
| 250 |
+
ref = ImageRef(camera=cam, array=self.render(cam), label=f"{label} {cam}".strip())
|
| 251 |
+
if self.image_sink is not None:
|
| 252 |
+
self.image_sink(ref)
|
| 253 |
+
imgs.append(ref)
|
| 254 |
+
self._depth_cache = {}
|
| 255 |
+
return imgs
|
| 256 |
+
|
| 257 |
+
# ------------------------------------------------------------------ dispatch
|
| 258 |
+
def call(self, name, raw_args):
|
| 259 |
+
t0 = time.time()
|
| 260 |
+
n0 = self.sk.n_steps
|
| 261 |
+
self.n_calls += 1
|
| 262 |
+
try:
|
| 263 |
+
args = parse_args(raw_args)
|
| 264 |
+
except Exception as e:
|
| 265 |
+
return ToolResult(name, {"_raw": str(raw_args)}, False, dict(ok=False, error=f"arguments are not valid JSON: {e}"),
|
| 266 |
+
wall_s=time.time() - t0)
|
| 267 |
+
fn = getattr(self, f"_t_{name}", None)
|
| 268 |
+
if fn is None or (name == "locate" and not self.privileged_locate):
|
| 269 |
+
return ToolResult(name, args, False, dict(ok=False, error=f"unknown tool {name!r}"), wall_s=time.time() - t0)
|
| 270 |
+
try:
|
| 271 |
+
res = fn(**args)
|
| 272 |
+
except TypeError as e:
|
| 273 |
+
res = ToolResult(name, args, False, dict(ok=False, error=f"bad arguments: {e}"))
|
| 274 |
+
except ValueError as e:
|
| 275 |
+
res = ToolResult(name, args, False, dict(ok=False, error=str(e)))
|
| 276 |
+
res.args = args
|
| 277 |
+
res.wall_s = time.time() - t0
|
| 278 |
+
res.sim_steps = self.sk.n_steps - n0
|
| 279 |
+
if res.sim_steps:
|
| 280 |
+
self._depth_cache = {}
|
| 281 |
+
hook = getattr(self.task, "on_agent_tool", None)
|
| 282 |
+
if hook is not None:
|
| 283 |
+
hook(self.inst, name, args, res.report)
|
| 284 |
+
drain = getattr(self.task, "drain_events", None) # task-side events (e.g. L6: an item slipped)
|
| 285 |
+
if drain is not None:
|
| 286 |
+
ev = drain()
|
| 287 |
+
if ev:
|
| 288 |
+
res.report["events"] = list(ev)
|
| 289 |
+
return res
|
| 290 |
+
|
| 291 |
+
# ------------------------------------------------------------------ helpers
|
| 292 |
+
def _clip_xyz(self, xyz):
|
| 293 |
+
xyz = np.asarray(xyz, float)
|
| 294 |
+
if not np.all(np.isfinite(xyz)):
|
| 295 |
+
raise ValueError("non-finite coordinates")
|
| 296 |
+
c = np.clip(xyz, WS_LO, WS_HI)
|
| 297 |
+
return c, (None if np.allclose(c, xyz) else _r(c))
|
| 298 |
+
|
| 299 |
+
@staticmethod
|
| 300 |
+
def _clip(v, lo_hi, what):
|
| 301 |
+
v = float(v)
|
| 302 |
+
if not math.isfinite(v):
|
| 303 |
+
raise ValueError(f"{what} must be finite")
|
| 304 |
+
return float(np.clip(v, *lo_hi))
|
| 305 |
+
|
| 306 |
+
def _action_report(self, name, extra=None):
|
| 307 |
+
names = self.held()
|
| 308 |
+
rep = dict(ok=True, tool=name)
|
| 309 |
+
if extra:
|
| 310 |
+
rep.update(extra)
|
| 311 |
+
rep.update(self.proprio())
|
| 312 |
+
if self.grasp_report == "name":
|
| 313 |
+
rep["touched_objects"] = sorted(self.tracker.touched)
|
| 314 |
+
elif self.grasp_report == "bool":
|
| 315 |
+
rep["touched_object"] = bool(self.tracker.touched)
|
| 316 |
+
rep["sim_time_s"] = round(self.sk.n_steps * 0.05, 2)
|
| 317 |
+
return rep
|
| 318 |
+
|
| 319 |
+
# ------------------------------------------------------------------ tools
|
| 320 |
+
def _t_move_to(self, x, y, z, yaw, speed=None):
|
| 321 |
+
tgt, clipped = self._clip_xyz([x, y, z])
|
| 322 |
+
spd = None if speed is None else self._clip(speed, SPEED_RANGE, "speed")
|
| 323 |
+
self.tracker.reset()
|
| 324 |
+
rep = self.sk.move_to(tgt, yaw=math.radians(float(yaw)), speed=spd) # Skills wraps yaw mod pi
|
| 325 |
+
extra = dict(reached=bool(rep["reached"]), yaw_used_deg=round(math.degrees(self.sk.yaw), 1))
|
| 326 |
+
if clipped:
|
| 327 |
+
extra["target_clipped_to"] = clipped
|
| 328 |
+
return ToolResult("move_to", {}, True, self._action_report("move_to", extra))
|
| 329 |
+
|
| 330 |
+
def _t_open_gripper(self):
|
| 331 |
+
self.tracker.reset()
|
| 332 |
+
self.sk.set_gripper(False)
|
| 333 |
+
return ToolResult("open_gripper", {}, True, self._action_report("open_gripper"))
|
| 334 |
+
|
| 335 |
+
def _t_close_gripper(self):
|
| 336 |
+
self.tracker.reset()
|
| 337 |
+
self.sk.set_gripper(True)
|
| 338 |
+
return ToolResult("close_gripper", {}, True, self._action_report("close_gripper"))
|
| 339 |
+
|
| 340 |
+
def _t_push(self, x, y, dir_x, dir_y, distance, speed, z=None, runup=None):
|
| 341 |
+
d = np.array([float(dir_x), float(dir_y)])
|
| 342 |
+
if not np.all(np.isfinite(d)) or np.linalg.norm(d) < 1e-6:
|
| 343 |
+
raise ValueError("push direction must be a non-zero vector")
|
| 344 |
+
start, clipped = self._clip_xyz([x, y, TABLE_Z + 0.02 if z is None else z])
|
| 345 |
+
dist = self._clip(distance, PUSH_DIST_RANGE, "distance")
|
| 346 |
+
spd = self._clip(speed, SPEED_RANGE, "speed")
|
| 347 |
+
pre = 0.06 if runup is None else self._clip(runup, RUNUP_RANGE, "runup")
|
| 348 |
+
self.tracker.reset()
|
| 349 |
+
rep = self.sk.push(start[:2], d, dist, spd, z=float(start[2]), pre=pre)
|
| 350 |
+
extra = dict(sweep_reached=bool(rep["reached"]))
|
| 351 |
+
if clipped:
|
| 352 |
+
extra["start_clipped_to"] = clipped
|
| 353 |
+
return ToolResult("push", {}, True, self._action_report("push", extra))
|
| 354 |
+
|
| 355 |
+
def _t_get_observation(self):
|
| 356 |
+
imgs = self.observe(label="requested")
|
| 357 |
+
return ToolResult("get_observation", {}, True, dict(ok=True, images=[i.camera for i in imgs], **self.proprio()),
|
| 358 |
+
images=imgs)
|
| 359 |
+
|
| 360 |
+
def _t_pixel_to_world(self, camera, u, v):
|
| 361 |
+
cam = str(camera)
|
| 362 |
+
if cam not in C.CAMERAS:
|
| 363 |
+
raise ValueError(f"camera must be one of {sorted(C.CAMERAS)}")
|
| 364 |
+
if cam not in self._depth_cache:
|
| 365 |
+
self._depth_cache[cam] = C.render_depth(self.env, cam, self.image_res)
|
| 366 |
+
r = C.pixel_to_world(self.env, cam, float(u), float(v), self.image_res, depth=self._depth_cache[cam])
|
| 367 |
+
rep = dict(ok=True, camera=cam, u=float(u), v=float(v), world_xyz=_r(r["xyz"]),
|
| 368 |
+
height_above_table_m=round(float(r["xyz"][2] - TABLE_Z), 4), depth_m=round(r["depth"], 4))
|
| 369 |
+
if not r["valid"]:
|
| 370 |
+
rep["warning"] = "pixel shows the far background; the point is unreliable"
|
| 371 |
+
return ToolResult("pixel_to_world", {}, True, rep)
|
| 372 |
+
|
| 373 |
+
def _t_locate(self, object_name):
|
| 374 |
+
if object_name not in self.env.objects_dict:
|
| 375 |
+
raise ValueError(f"unknown object {object_name!r}; known: {self.objects}")
|
| 376 |
+
lo, hi = self._aabb(object_name)
|
| 377 |
+
p = envs.obj_pos(self.env, object_name)
|
| 378 |
+
return ToolResult("locate", {}, True, dict(ok=True, object=object_name, position=_r(p), bbox_min=_r(lo),
|
| 379 |
+
bbox_max=_r(hi)))
|
| 380 |
+
|
| 381 |
+
def _aabb(self, name):
|
| 382 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 383 |
+
lo, hi = np.full(3, np.inf), np.full(3, -np.inf)
|
| 384 |
+
for g in envs.obj_geom_ids(self.env, name):
|
| 385 |
+
R = d.geom_xmat[g].reshape(3, 3)
|
| 386 |
+
c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3]
|
| 387 |
+
h = np.abs(R) @ m.geom_aabb[g, 3:]
|
| 388 |
+
lo, hi = np.minimum(lo, c - h), np.maximum(hi, c + h)
|
| 389 |
+
return lo, hi
|
| 390 |
+
|
| 391 |
+
def _t_done(self, reason=""):
|
| 392 |
+
return ToolResult("done", {}, True, dict(ok=True, ended=True), ended=True)
|
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/agent/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""LFF-Bench agent harness: tool interface, context packing, model backends, protocol runner."""
|
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/l5_iterative.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""[PARKED 2026-10-06 — fails acceptance: oracle 50% (n=12, k=3). The push response is not stationary:
|
| 2 |
+
the same commanded speed carries the cube 7.9 cm on one push and 11.4 cm on the next, because the arm reaches
|
| 3 |
+
different speeds at different extensions. Needs a configuration-independent striker before use.]
|
| 4 |
+
|
| 5 |
+
L5-B iterative_push: several pushes in ONE episode (MemMimic "Iterative Pushing" analogue).
|
| 6 |
+
|
| 7 |
+
The cube starts far from the target zone; each push is a straight strike away from the robot whose
|
| 8 |
+
only free parameter is the speed. Overshooting past the zone is unrecoverable (episode fails).
|
| 9 |
+
Hidden variable: cube-table friction mu, as in l5_slide_to_target. The information needed to choose
|
| 10 |
+
the next push (how far a push of a given speed carries the cube) is only available from the
|
| 11 |
+
outcomes of the previous pushes in the same episode -> within-episode learning from failure.
|
| 12 |
+
|
| 13 |
+
"Attempt" granularity for the history: one push.
|
| 14 |
+
"""
|
| 15 |
+
import numpy as np
|
| 16 |
+
|
| 17 |
+
from .. import envs
|
| 18 |
+
from ..task_base import register_task
|
| 19 |
+
from .l5_slide import CUBE_HALF, V_MAX, V_MIN, Z_PUSH, SlideToTarget
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@register_task
|
| 23 |
+
class IterativePush(SlideToTarget):
|
| 24 |
+
name = "l5_iterative_push"
|
| 25 |
+
level = "L5"
|
| 26 |
+
capabilities = ("Reason", "Save", "Utilize")
|
| 27 |
+
protocol = "within"
|
| 28 |
+
max_attempts = 3 # pushes per episode: too few to creep up on the target with small taps
|
| 29 |
+
instruction = ("Push the red cube away from the robot so that it comes to rest inside the green target zone. "
|
| 30 |
+
"You have at most three separate pushes. If the cube passes the zone, the task fails.")
|
| 31 |
+
instruction_indirect = instruction
|
| 32 |
+
tol_along = 0.015
|
| 33 |
+
|
| 34 |
+
def sample_instance(self, seed):
|
| 35 |
+
rng = np.random.default_rng(seed)
|
| 36 |
+
return dict(seed=int(seed),
|
| 37 |
+
cube_xy=[float(rng.uniform(-0.27, -0.23)), float(rng.uniform(-0.08, 0.08))],
|
| 38 |
+
target_dist=float(rng.uniform(0.22, 0.30)),
|
| 39 |
+
mu=float(np.exp(rng.uniform(np.log(0.035), np.log(0.08)))))
|
| 40 |
+
|
| 41 |
+
def make_bddl(self):
|
| 42 |
+
return super().make_bddl()
|
| 43 |
+
|
| 44 |
+
# --------------------------------------------------------------- one push from the current cube pose
|
| 45 |
+
def push_once(self, inst, speed):
|
| 46 |
+
c = envs.obj_pos(self.env, "cube_1")
|
| 47 |
+
x, y = c[0], c[1]
|
| 48 |
+
sk = self.sk
|
| 49 |
+
sk.set_gripper(True, steps=3)
|
| 50 |
+
sk.move_to([x - self.runup, y, Z_PUSH + 0.10], yaw=0.0)
|
| 51 |
+
sk.move_to([x - self.runup, y, Z_PUSH], tol=0.003)
|
| 52 |
+
sk.move_to([x - CUBE_HALF + 0.015, y, Z_PUSH], speed=float(np.clip(speed, V_MIN, V_MAX)), tol=0.01,
|
| 53 |
+
max_steps=80)
|
| 54 |
+
sk.move_to([x - CUBE_HALF + 0.015, y, Z_PUSH + 0.10], speed=0.3)
|
| 55 |
+
envs.settle(self.env, 40)
|
| 56 |
+
c1 = envs.obj_pos(self.env, "cube_1")
|
| 57 |
+
return float(c1[0] - x)
|
| 58 |
+
|
| 59 |
+
def outcome(self, inst):
|
| 60 |
+
x0, y0 = inst["cube_xy"]
|
| 61 |
+
c = envs.obj_pos(self.env, "cube_1")
|
| 62 |
+
along = (c[0] - x0) - inst["target_dist"]
|
| 63 |
+
across = c[1] - y0
|
| 64 |
+
success = bool(abs(along) <= self.tol_along and abs(across) <= self.tol_across and c[2] > envs.TABLE_Z)
|
| 65 |
+
overshoot = bool(along > self.tol_along)
|
| 66 |
+
if success:
|
| 67 |
+
detail = "The cube is inside the target zone."
|
| 68 |
+
elif overshoot:
|
| 69 |
+
detail = f"The cube passed the target zone: it is {100 * along:.1f} cm beyond its centre. The task has failed."
|
| 70 |
+
else:
|
| 71 |
+
detail = f"The cube is {100 * -along:.1f} cm short of the centre of the target zone."
|
| 72 |
+
return dict(success=success, overshoot=overshoot, along_err=float(along), across_err=float(across),
|
| 73 |
+
detail=detail)
|
| 74 |
+
|
| 75 |
+
# --------------------------------------------------------------- scripted references
|
| 76 |
+
S0 = 0.02 # distance the cube travels during the contact stroke itself
|
| 77 |
+
|
| 78 |
+
def _plan_speed(self, remaining, model, pushes_left=1):
|
| 79 |
+
"""Model: push distance d(v) = s0 + k v^2. With more than one push left, cover all but a short
|
| 80 |
+
final leg (a short push is more predictable); with one push left, aim at the zone centre."""
|
| 81 |
+
if model is None:
|
| 82 |
+
return 0.30
|
| 83 |
+
s0, k = model
|
| 84 |
+
goal = remaining if pushes_left <= 1 else max(remaining - 0.07, 0.0)
|
| 85 |
+
v = np.sqrt(max(goal - s0, 0.0) / max(k, 1e-6))
|
| 86 |
+
return float(np.clip(v, V_MIN, V_MAX))
|
| 87 |
+
|
| 88 |
+
@classmethod
|
| 89 |
+
def _fit(cls, pts):
|
| 90 |
+
"""pts: [(v, d)]. One point -> fix s0; two or more -> least squares on (s0, k)."""
|
| 91 |
+
if len(pts) == 1:
|
| 92 |
+
v, d = pts[0]
|
| 93 |
+
return cls.S0, max(d - cls.S0, 1e-4) / v ** 2
|
| 94 |
+
A = np.array([[1.0, v ** 2] for v, _ in pts])
|
| 95 |
+
b = np.array([d for _, d in pts])
|
| 96 |
+
s0, k = np.linalg.lstsq(A, b, rcond=None)[0]
|
| 97 |
+
if k <= 0:
|
| 98 |
+
return cls.S0, max(np.mean(b) - cls.S0, 1e-4) / np.mean([v ** 2 for v, _ in pts])
|
| 99 |
+
return float(np.clip(s0, 0.0, 0.05)), float(k)
|
| 100 |
+
|
| 101 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 102 |
+
k = k or self.max_attempts
|
| 103 |
+
rng = np.random.default_rng(seed)
|
| 104 |
+
self.reset_instance(inst)
|
| 105 |
+
history = []
|
| 106 |
+
model = None
|
| 107 |
+
if kind == "oracle":
|
| 108 |
+
model = self._oracle_model(inst)
|
| 109 |
+
for a in range(k):
|
| 110 |
+
out0 = self.outcome(inst)
|
| 111 |
+
remaining = -out0["along_err"]
|
| 112 |
+
if kind == "naive" or kind == "blind":
|
| 113 |
+
speed = 0.30 if kind == "naive" else float(np.clip(0.30 + rng.normal(0, 0.05), V_MIN, V_MAX))
|
| 114 |
+
if remaining < 0.06: # naive heuristic: tap gently near the end
|
| 115 |
+
speed = 0.20
|
| 116 |
+
else:
|
| 117 |
+
speed = self._plan_speed(remaining, model, pushes_left=k - a)
|
| 118 |
+
moved = self.push_once(inst, speed)
|
| 119 |
+
out = self.outcome(inst)
|
| 120 |
+
history.append(dict(attempt=a + 1, params=dict(speed=speed), outcome=dict(out, moved=moved)))
|
| 121 |
+
if kind == "adaptive" and moved > 0.005:
|
| 122 |
+
pts = [(h["params"]["speed"], h["outcome"]["moved"]) for h in history if h["outcome"]["moved"] > 0.005]
|
| 123 |
+
model = self._fit(pts)
|
| 124 |
+
if out["success"] or out["overshoot"]:
|
| 125 |
+
break
|
| 126 |
+
# mark only the final state as the episode outcome
|
| 127 |
+
return history
|
| 128 |
+
|
| 129 |
+
def _oracle_model(self, inst):
|
| 130 |
+
"""Privileged: measure the push model with the true mu in scratch rollouts."""
|
| 131 |
+
pts = []
|
| 132 |
+
for v in (0.2, 0.35, 0.5):
|
| 133 |
+
self.reset_instance(inst)
|
| 134 |
+
pts.append((v, self.push_once(inst, v)))
|
| 135 |
+
self.reset_instance(inst)
|
| 136 |
+
return self._fit(pts)
|
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/agent_compare.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ΔICL between two agent run directories on the same seeds.
|
| 2 |
+
|
| 3 |
+
python scripts/agent_compare.py --with runs/agent/<task>/<full-memory run> --iid runs/agent/<task>/<memory-none run>
|
| 4 |
+
|
| 5 |
+
ΔICL = succ@k(with history) - pass@k_iid(independent retries), paired by instance seed, with a paired
|
| 6 |
+
bootstrap 95% interval. Also prints the analytic i.i.d. reference 1-(1-p1)^k from the 'with' run.
|
| 7 |
+
"""
|
| 8 |
+
import argparse
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
import sys
|
| 12 |
+
|
| 13 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 14 |
+
|
| 15 |
+
from lffbench.agent.metrics import paired_delta # noqa: E402
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def load(d):
|
| 19 |
+
with open(os.path.join(d, "summary.json")) as f:
|
| 20 |
+
return json.load(f)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def main():
|
| 24 |
+
ap = argparse.ArgumentParser()
|
| 25 |
+
ap.add_argument("--with", dest="with_", required=True)
|
| 26 |
+
ap.add_argument("--iid", required=True)
|
| 27 |
+
ap.add_argument("--k", type=int, default=None)
|
| 28 |
+
a = ap.parse_args()
|
| 29 |
+
w, i = load(a.with_), load(a.iid)
|
| 30 |
+
k = a.k or min(w["k"], i["k"])
|
| 31 |
+
res = paired_delta(w["runs"], i["runs"], k)
|
| 32 |
+
res["k"] = k
|
| 33 |
+
res["with"] = dict(memory=w["memory"], feedback=w["feedback"], attempt1=w["aggregate"]["attempt1_success"],
|
| 34 |
+
pass_at_k_iid_analytic=w["aggregate"]["pass_at_k_iid_analytic"])
|
| 35 |
+
res["iid"] = dict(memory=i["memory"], feedback=i["feedback"])
|
| 36 |
+
print(json.dumps(res, indent=1))
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
if __name__ == "__main__":
|
| 40 |
+
main()
|
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/check_breakfast_mechanisms.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Mechanism-on/off controls and negative judge fixtures, separate from rollouts."""
|
| 2 |
+
import argparse, copy, json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
from lffbench.tasks.lh_breakfast_service import BreakfastService
|
| 6 |
+
from lffbench import envs
|
| 7 |
+
|
| 8 |
+
def main():
|
| 9 |
+
p=argparse.ArgumentParser();p.add_argument('--liquid-only',action='store_true')
|
| 10 |
+
p.add_argument('--judge-only',action='store_true');args=p.parse_args()
|
| 11 |
+
out=Path(__file__).resolve().parents[1]/'results/lh_breakfast_service/mechanisms'
|
| 12 |
+
out.mkdir(parents=True,exist_ok=True);t=BreakfastService();rows=[]
|
| 13 |
+
if args.judge_only:rows=json.loads((out/'controls_progress.json').read_text())
|
| 14 |
+
for seed in ([] if args.liquid_only or args.judge_only else range(1000,1003)):
|
| 15 |
+
for enabled in (True,False):
|
| 16 |
+
inst=t.sample_instance(seed);inst['mechanisms']['L1']=enabled;t.reset_instance(inst)
|
| 17 |
+
t.calibration_probe();row=dict(seed=seed,mechanism='L1',enabled=enabled,triggered=t.traps['L1'])
|
| 18 |
+
rows.append(row);print(json.dumps(row),flush=True)
|
| 19 |
+
assert row['triggered']==enabled,row
|
| 20 |
+
inst=t.sample_instance(seed);inst['mechanisms']['L3']=enabled;t.reset_instance(inst);t.sk.correction=t.sk.bias.copy()
|
| 21 |
+
t.direct_carton_lift();row=dict(seed=seed,mechanism='L3',enabled=enabled,**t.pull_probe)
|
| 22 |
+
rows.append(row);print(json.dumps(row),flush=True)
|
| 23 |
+
assert row['held_before'] and ((row['displacement_m']<.01) if enabled else (row['displacement_m']>.04)),row
|
| 24 |
+
inst=t.sample_instance(seed);inst['mechanisms']['L2']=enabled;t.reset_instance(inst);t.sk.correction=t.sk.bias.copy()
|
| 25 |
+
for _ in range(2):t.open_lid();t.close_lid(False)
|
| 26 |
+
t.sk.hold(300);failure=t.lid_deg()
|
| 27 |
+
if enabled:t.open_lid();t.close_lid(True);t.sk.hold(300)
|
| 28 |
+
row=dict(seed=seed,mechanism='L2',enabled=enabled,lid_after_quick_closes=failure,final_lid=t.lid_deg())
|
| 29 |
+
rows.append(row);print(json.dumps(row),flush=True)
|
| 30 |
+
assert (failure>10 if enabled else failure<4) and row['final_lid']<4,row
|
| 31 |
+
(out/'controls_progress.json').write_text(json.dumps(rows,indent=2))
|
| 32 |
+
liquid_controls=json.loads((out/'liquid_controls.json').read_text()) if args.judge_only else []
|
| 33 |
+
for case in ([] if args.judge_only else ('upright','tilted_aligned','tilted_misaligned')):
|
| 34 |
+
inst=t.sample_instance(1000);t.reset_instance(inst)
|
| 35 |
+
if case!='upright':t.env.sim.data.qpos[t.pour_qa]=1.35
|
| 36 |
+
if case=='tilted_misaligned':t.env.sim.model.body_pos[t.cup_bid,0]+=.20
|
| 37 |
+
t.env.sim.forward();t.sk.hold(160)
|
| 38 |
+
q=t.liquid;inflight=sum(p['ml'] for p in q['parcels'])
|
| 39 |
+
row=dict(case=case,cup_ml=q['cup'],spill_ml=q['spill'],reservoir_ml=q['reservoir'],
|
| 40 |
+
conservation_error_ml=abs(300-q['cup']-q['spill']-q['reservoir']-inflight))
|
| 41 |
+
liquid_controls.append(row);print(json.dumps(row),flush=True)
|
| 42 |
+
assert row['conservation_error_ml']<1e-8,row
|
| 43 |
+
if case=='upright':assert q['cup']==q['spill']==0,row
|
| 44 |
+
elif case=='tilted_aligned':assert q['cup']>=179 and q['spill']>50,row
|
| 45 |
+
else:assert q['cup']==0 and q['spill']>200,row
|
| 46 |
+
if args.liquid_only:
|
| 47 |
+
(out/'liquid_controls.json').write_text(json.dumps(liquid_controls,indent=2))
|
| 48 |
+
t.env.close();return
|
| 49 |
+
# Obtain a successful physical endpoint before mutating diagnostic scoring fixtures.
|
| 50 |
+
inst=t.sample_instance(1000);t.reset_instance(inst);t.execute(inst,{'mode':'oracle'});baseline=t.outcome(inst)
|
| 51 |
+
assert baseline['success'],baseline
|
| 52 |
+
state=copy.deepcopy(t.env.sim.get_state());liquid=copy.deepcopy(t.liquid)
|
| 53 |
+
mon=copy.deepcopy(t.mon);closes=t.closes_done;latch=t.active_latch
|
| 54 |
+
negatives=[]
|
| 55 |
+
for case in ('no_milk','too_much_milk','spill','bread_off_plate','butter_outside','lid_open','carton_tilted','gripper_closed'):
|
| 56 |
+
t.env.sim.set_state(state);t.env.sim.forward();t.liquid=copy.deepcopy(liquid);t.sk.grip=-1.;t.drift_active=False
|
| 57 |
+
t.mon=copy.deepcopy(mon);t.closes_done=closes;t.active_latch=latch
|
| 58 |
+
if case=='no_milk':t.liquid['reservoir']+=t.liquid['cup'];t.liquid['cup']=0
|
| 59 |
+
elif case=='too_much_milk':
|
| 60 |
+
t.liquid['reservoir']-=175-t.liquid['cup'];t.liquid['cup']=175
|
| 61 |
+
elif case=='spill':t.liquid['reservoir']-=25;t.liquid['spill']=25;t.liquid['spill_xy']=[.2,0]
|
| 62 |
+
elif case=='bread_off_plate':envs.set_obj_pose(t.env,'bread_1',[-.30,.03,.912])
|
| 63 |
+
elif case=='butter_outside':envs.set_obj_pose(t.env,'butter_1',[-.35,-.32,.914])
|
| 64 |
+
elif case=='lid_open':t.env.sim.data.qpos[t.qa]=1.0
|
| 65 |
+
elif case=='carton_tilted':t.env.sim.data.qpos[t.pour_qa]=1.35
|
| 66 |
+
elif case=='gripper_closed':t.sk.grip=1.
|
| 67 |
+
t.env.sim.forward();result=t.outcome(inst)
|
| 68 |
+
negatives.append(dict(case=case,accepted=result['success'],failure=result['failure'],stages=result['stages']))
|
| 69 |
+
print(json.dumps(negatives[-1],default=lambda v:v.item()),flush=True)
|
| 70 |
+
predicate={'no_milk':'milk_served','too_much_milk':'milk_served','spill':'spill_ok',
|
| 71 |
+
'bread_off_plate':'bread_on_plate','butter_outside':'butter_in_box','lid_open':'lid_closed',
|
| 72 |
+
'carton_tilted':'carton_upright','gripper_closed':'gripper_open'}[case]
|
| 73 |
+
assert not result['success'] and not result['stages'][predicate],case
|
| 74 |
+
data=dict(controls=rows,liquid_controls=liquid_controls,negative_fixtures=negatives,
|
| 75 |
+
scope='Controlled interventions are diagnostics, not agent rollouts')
|
| 76 |
+
(out/'result.json').write_text(json.dumps(data,indent=2,default=lambda v:v.item()))
|
| 77 |
+
t.env.close()
|
| 78 |
+
|
| 79 |
+
if __name__=='__main__':main()
|
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/full_report.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Summarise a full run (all tasks x harnesses) from the robot-server logs only, so every harness is measured
|
| 2 |
+
the same way.
|
| 3 |
+
|
| 4 |
+
python scripts/full_report.py --batch full1 [--out ../docs/full1_table.md]
|
| 5 |
+
|
| 6 |
+
Per run: outcome of every attempt, attempts used, robot commands, close_gripper calls that ended holding an
|
| 7 |
+
object, "empty done" attempts (the agent ended an attempt without a single move / gripper command in it), and
|
| 8 |
+
wall time from the first to the last server request.
|
| 9 |
+
"""
|
| 10 |
+
import argparse
|
| 11 |
+
import collections
|
| 12 |
+
import json
|
| 13 |
+
import os
|
| 14 |
+
|
| 15 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 16 |
+
LEVEL = {"l1": "L1", "l2": "L2", "l3": "L3", "l4": "L4", "l5": "L5", "l6": "L6", "l7": "L7"}
|
| 17 |
+
HARNESS_NAME = {"gpt_player": "ours", "rpent": "RPent", "gptpolicy": "GPT-Policy", "claude": "ours (Claude CLI)"}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def run_info(r):
|
| 21 |
+
ev = [json.loads(l) for l in open(os.path.join(r["log"], "events.jsonl"))]
|
| 22 |
+
calls = [e for e in ev if e["ev"] == "call"]
|
| 23 |
+
dones = [e for e in ev if e["ev"] == "done"]
|
| 24 |
+
http = [e for e in ev if e["ev"] == "http"]
|
| 25 |
+
# v1: move_to / open_gripper / close_gripper; v2 and la: move_eef [gripper=open|close] (holding is only in `raw`,
|
| 26 |
+
# the agent never sees it)
|
| 27 |
+
acts_per_attempt = collections.Counter(e["attempt"] for e in calls if e["cmd"] in ("move_to", "open_gripper", "close_gripper")
|
| 28 |
+
or (e["cmd"] == "move_eef" and (e.get("report") or {}).get("ok")))
|
| 29 |
+
empty = sum(1 for d in dones if acts_per_attempt.get(d["attempt"], 0) == 0)
|
| 30 |
+
closes = [e for e in calls if e["cmd"] == "close_gripper"
|
| 31 |
+
or (e["cmd"] == "move_eef" and (e.get("args") or {}).get("gripper") == "close" and (e.get("report") or {}).get("ok"))]
|
| 32 |
+
held = sum(1 for e in closes if (e.get("report") or {}).get("holding_object") or (e.get("raw") or {}).get("holding_object"))
|
| 33 |
+
first = next((d["attempt"] for d in dones if d["success"]), None)
|
| 34 |
+
wall = (http[-1]["t_send"] - http[0]["t_recv"]) / 60 if http else None
|
| 35 |
+
return dict(outcomes="".join("S" if d["success"] else "F" for d in dones), attempts=len(dones), first=first,
|
| 36 |
+
cmds=len(calls), closes=len(closes), held=held, empty=empty, wall=wall)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def main():
|
| 40 |
+
ap = argparse.ArgumentParser()
|
| 41 |
+
ap.add_argument("--batch", default="full1")
|
| 42 |
+
ap.add_argument("--out", default=None)
|
| 43 |
+
ap.add_argument("--runs", default="gpt", help="runs/<runs>/<batch>/manifest.json (gpt or claude)")
|
| 44 |
+
a = ap.parse_args()
|
| 45 |
+
m = json.load(open(os.path.join(ROOT, "runs", a.runs, a.batch, "manifest.json")))
|
| 46 |
+
rows = {}
|
| 47 |
+
for r in m["runs"]:
|
| 48 |
+
try:
|
| 49 |
+
h = r.get("harness") or ("claude" if r.get("cond") in ("harness", "noharness") else "gpt_player")
|
| 50 |
+
rows[(r["task"], h)] = dict(run_info(r), k=r["k"])
|
| 51 |
+
except FileNotFoundError:
|
| 52 |
+
pass
|
| 53 |
+
tasks = sorted({t for t, _ in rows}, key=lambda t: (t[:2], t))
|
| 54 |
+
hs = [h for h in ("gpt_player", "rpent", "gptpolicy", "claude") if any(k[1] == h for k in rows)]
|
| 55 |
+
L = [f"# {a.batch}: one run per task x harness (see manifest for model / perception / style)", "",
|
| 56 |
+
"Cell = outcome of each attempt (S success, F failure); `·` = run missing. Measured from robot-server logs.", "",
|
| 57 |
+
"| task | level | " + " | ".join(HARNESS_NAME[h] for h in hs) + " |", "|---|---|" + "---|" * len(hs)]
|
| 58 |
+
for t in tasks:
|
| 59 |
+
cells = []
|
| 60 |
+
for h in hs:
|
| 61 |
+
x = rows.get((t, h))
|
| 62 |
+
cells.append("·" if x is None else (x["outcomes"] or "—"))
|
| 63 |
+
L.append(f"| {t} | {LEVEL.get(t[:2], '?')} | " + " | ".join(cells) + " |")
|
| 64 |
+
L += ["", "| harness | runs | success @1 | success @3 | grasps held / close_gripper | empty-done attempts | "
|
| 65 |
+
"commands / attempt | wall min / run |", "|---|---|---|---|---|---|---|---|"]
|
| 66 |
+
for h in hs:
|
| 67 |
+
xs = [x for (t, hh), x in rows.items() if hh == h and x["attempts"] > 0]
|
| 68 |
+
n = len(xs)
|
| 69 |
+
att = sum(x["attempts"] for x in xs)
|
| 70 |
+
L.append(f"| {HARNESS_NAME[h]} | {n} | {sum(1 for x in xs if x['first'] == 1)} | "
|
| 71 |
+
f"{sum(1 for x in xs if x['first'])} | {sum(x['held'] for x in xs)} / {sum(x['closes'] for x in xs)} | "
|
| 72 |
+
f"{sum(x['empty'] for x in xs)} / {att} | {sum(x['cmds'] for x in xs) / max(att, 1):.1f} | "
|
| 73 |
+
f"{sum(x['wall'] or 0 for x in xs) / max(n, 1):.0f} |")
|
| 74 |
+
by_level = collections.defaultdict(lambda: [0, 0])
|
| 75 |
+
for (t, h), x in rows.items():
|
| 76 |
+
if x["attempts"]:
|
| 77 |
+
by_level[LEVEL.get(t[:2], "?")][0] += bool(x["first"])
|
| 78 |
+
by_level[LEVEL.get(t[:2], "?")][1] += 1
|
| 79 |
+
L += ["", "Success @3 by level (all harnesses pooled): " +
|
| 80 |
+
", ".join(f"{lv} {s}/{n}" for lv, (s, n) in sorted(by_level.items()))]
|
| 81 |
+
txt = "\n".join(L)
|
| 82 |
+
print(txt)
|
| 83 |
+
if a.out:
|
| 84 |
+
with open(a.out, "w") as f:
|
| 85 |
+
f.write(txt + "\n")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
if __name__ == "__main__":
|
| 89 |
+
main()
|
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/harness_run.py
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run one robot_server session (style la) with one agent harness through its adapter (lffbench/harnesses, docs/15).
|
| 2 |
+
|
| 3 |
+
python scripts/harness_run.py --harness claude_code --session runs/<...>/session.json --model claude-sonnet-5-5 --effort high
|
| 4 |
+
python scripts/harness_run.py --harness codex --session ... --model gpt-6-astra --effort high
|
| 5 |
+
python scripts/harness_run.py --harness ours --session ... --provider anthropic --model ... --effort high
|
| 6 |
+
|
| 7 |
+
Harnesses: ours (scripts/api_player.py, unchanged), claude_code (arm B, --bare), claude_code_full (arm B', no --bare),
|
| 8 |
+
codex (arm F), rpent_codex (RPent, a robot harness framework, on the same Codex; tools through the episode's tool
|
| 9 |
+
gateway, lffbench/harnesses/rpent.py). Native harnesses get the reference driver's instructions + first status report as their first user
|
| 10 |
+
message (byte-identical README), only our MCP server (scripts/mcp_robot_server.py) as tools, a one-time HOME / config
|
| 11 |
+
dir, an opaque work dir /tmp/lffrun/<12 hex> and a process environment that is exactly a whitelist.
|
| 12 |
+
|
| 13 |
+
API variables (never inherited from the calling Claude Code / Codex session):
|
| 14 |
+
claude_code*: --claude-auth oauth (default for claude_code_full): a Claude subscription, the long-lived token of
|
| 15 |
+
`claude setup-token` from LFF_CLAUDE_OAUTH_TOKEN or the KEY=value file LFF_CLAUDE_OAUTH_FILE (key
|
| 16 |
+
LFF_CLAUDE_OAUTH_TOKEN or CLAUDE_CODE_OAUTH_TOKEN), passed as CLAUDE_CODE_OAUTH_TOKEN;
|
| 17 |
+
--claude-auth apikey (default and only choice for claude_code, which is --bare): key
|
| 18 |
+
LFF_ANTHROPIC_API_KEY or ANTHROPIC_API_KEY;
|
| 19 |
+
endpoint --api-base-url or LFF_ANTHROPIC_BASE_URL (default: the CLI's own default, the official API)
|
| 20 |
+
codex: --codex-provider deepseek: DeepSeek's Responses endpoint (https://api.deepseek.com/), key
|
| 21 |
+
LFF_DEEPSEEK_API_KEY or DEEPSEEK_API_KEY (passed to Codex as its provider's OPENAI_API_KEY);
|
| 22 |
+
--codex-provider opencode: OpenCode Go's Responses endpoint (OPENCODE_GO_URL), key LFF_OPENCODE_API_KEY
|
| 23 |
+
or OPENCODE_API_KEY (the model gateway adds the x-opencode-session header OpenCode Go requires);
|
| 24 |
+
--codex-auth chatgpt (default): the ChatGPT subscription login of LFF_CODEX_AUTH_HOME / CODEX_HOME
|
| 25 |
+
(a copy of its auth.json, no API key; endpoint the ChatGPT Codex backend unless --api-base-url);
|
| 26 |
+
--codex-auth apikey: key LFF_OPENAI_API_KEY or OPENAI_API_KEY; endpoint --api-base-url,
|
| 27 |
+
LFF_OPENAI_BASE_URL or OPENAI_BASE_URL (as api_player), else https://api.openai.com/v1
|
| 28 |
+
dsh: DeepSeek's Messages endpoint (DEEPSEEK_ANTHROPIC_URL), or --api-base-url / LFF_DSH_BASE_URL (OpenCode Go:
|
| 29 |
+
https://opencode.ai/inference/go), key LFF_DEEPSEEK_API_KEY or DEEPSEEK_API_KEY (passed as DEEPSEEK_API_KEY)
|
| 30 |
+
ours: as api_player.py (its own environment)
|
| 31 |
+
|
| 32 |
+
Writes into the run's log dir: contract.json, first_message.txt, harness.json (harness name, version, argv with the
|
| 33 |
+
first message replaced by its sha256, env key names, contract_sha256, first_message_sha256, config_sha256, preflight
|
| 34 |
+
result), harness_preflight.json (full normalised fingerprint), the native event stream, trajectory.jsonl,
|
| 35 |
+
harness_audit.json. Exit codes: 0 done, 2 refused at launch (fail-closed), 3 harness error, 143 stopped.
|
| 36 |
+
"""
|
| 37 |
+
import argparse
|
| 38 |
+
import json
|
| 39 |
+
import os
|
| 40 |
+
import signal
|
| 41 |
+
import sys
|
| 42 |
+
import time
|
| 43 |
+
import traceback
|
| 44 |
+
|
| 45 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 46 |
+
sys.path.insert(0, ROOT)
|
| 47 |
+
from lffbench.harnesses import NAMES, ROBOT_HARNESSES, PROVIDER, EpisodeSpec, HarnessRefused, get_adapter, render_first_message # noqa: E402
|
| 48 |
+
from lffbench.harnesses import contract as C # noqa: E402
|
| 49 |
+
from lffbench.harnesses import redteam as RT # noqa: E402
|
| 50 |
+
|
| 51 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 52 |
+
from api_player import MAX_NO_TOOL, call_server, continue_nudge # noqa: E402
|
| 53 |
+
from tool_gateway import start_gateway, stop_gateway # noqa: E402
|
| 54 |
+
import model_gateway as MG # noqa: E402
|
| 55 |
+
|
| 56 |
+
ANTHROPIC_API = "https://api.anthropic.com"
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def claude_oauth_token():
|
| 60 |
+
"""The subscription token for claude_code_full --claude-auth oauth: LFF_CLAUDE_OAUTH_TOKEN, else the KEY=value
|
| 61 |
+
file LFF_CLAUDE_OAUTH_FILE. Never CLAUDE_CODE_OAUTH_TOKEN of the calling environment (that may be the calling
|
| 62 |
+
Claude Code session's own login)."""
|
| 63 |
+
tok = os.environ.get("LFF_CLAUDE_OAUTH_TOKEN")
|
| 64 |
+
if tok:
|
| 65 |
+
return tok.strip()
|
| 66 |
+
path = os.environ.get("LFF_CLAUDE_OAUTH_FILE")
|
| 67 |
+
if path and os.path.isfile(path):
|
| 68 |
+
for line in open(path):
|
| 69 |
+
k, _, v = line.strip().partition("=")
|
| 70 |
+
if k.strip().removeprefix("export ").strip() in ("LFF_CLAUDE_OAUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN") and v:
|
| 71 |
+
return v.strip().strip("'\"")
|
| 72 |
+
raise SystemExit("claude --claude-auth oauth: no token; run `claude setup-token` and put LFF_CLAUDE_OAUTH_TOKEN=... "
|
| 73 |
+
"into the file named by LFF_CLAUDE_OAUTH_FILE (or export LFF_CLAUDE_OAUTH_TOKEN)")
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def default_claude_auth(harness):
|
| 77 |
+
return "apikey" if harness == "claude_code" else "oauth"
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def api_env_for(harness, base_url, codex_auth="apikey", claude_auth="apikey", codex_provider="openai"):
|
| 81 |
+
"""-> (variables passed to the harness, endpoint or None, endpoint label for harness.json). Endpoints are never
|
| 82 |
+
written to the logs, only where they came from."""
|
| 83 |
+
if harness in ROBOT_HARNESSES:
|
| 84 |
+
if harness == "rpent_codex":
|
| 85 |
+
codex_auth = "apikey" # historical RPent implementation stays unchanged
|
| 86 |
+
harness = "codex"
|
| 87 |
+
if harness.startswith("claude_code"):
|
| 88 |
+
e = {}
|
| 89 |
+
if claude_auth == "oauth":
|
| 90 |
+
e["CLAUDE_CODE_OAUTH_TOKEN"] = claude_oauth_token()
|
| 91 |
+
else:
|
| 92 |
+
key = os.environ.get("LFF_ANTHROPIC_API_KEY") or os.environ.get("ANTHROPIC_API_KEY")
|
| 93 |
+
if key:
|
| 94 |
+
e["ANTHROPIC_API_KEY"] = key
|
| 95 |
+
url = base_url or os.environ.get("LFF_ANTHROPIC_BASE_URL")
|
| 96 |
+
if url:
|
| 97 |
+
e["ANTHROPIC_BASE_URL"] = url
|
| 98 |
+
dflt = "CLI default (official)" + (", subscription token" if claude_auth == "oauth" else "")
|
| 99 |
+
return e, url, ("--api-base-url" if base_url else "LFF_ANTHROPIC_BASE_URL") if url else dflt
|
| 100 |
+
if harness == "dsh":
|
| 101 |
+
key = os.environ.get("LFF_DEEPSEEK_API_KEY") or os.environ.get("DEEPSEEK_API_KEY")
|
| 102 |
+
from lffbench.harnesses.dsh import DEEPSEEK_ANTHROPIC_URL
|
| 103 |
+
url = base_url or os.environ.get("LFF_DSH_BASE_URL")
|
| 104 |
+
return ({"DEEPSEEK_API_KEY": key} if key else {}), url or DEEPSEEK_ANTHROPIC_URL, \
|
| 105 |
+
("--api-base-url" if base_url else "LFF_DSH_BASE_URL") if url else \
|
| 106 |
+
"DeepSeek (DEEPSEEK_ANTHROPIC_URL, key LFF_DEEPSEEK_API_KEY / DEEPSEEK_API_KEY)"
|
| 107 |
+
if harness == "codex" and codex_provider == "deepseek": # DeepSeek's own Responses endpoint, an API key
|
| 108 |
+
key = os.environ.get("LFF_DEEPSEEK_API_KEY") or os.environ.get("DEEPSEEK_API_KEY")
|
| 109 |
+
from lffbench.harnesses.codex import DEEPSEEK_URL
|
| 110 |
+
return ({"OPENAI_API_KEY": key} if key else {}), base_url or DEEPSEEK_URL, \
|
| 111 |
+
"--api-base-url" if base_url else "DeepSeek (DEEPSEEK_URL, key LFF_DEEPSEEK_API_KEY / DEEPSEEK_API_KEY)"
|
| 112 |
+
if harness == "codex" and codex_provider == "opencode": # OpenCode Go's Responses endpoint, an API key
|
| 113 |
+
key = os.environ.get("LFF_OPENCODE_API_KEY") or os.environ.get("OPENCODE_API_KEY")
|
| 114 |
+
from lffbench.harnesses.codex import OPENCODE_GO_URL
|
| 115 |
+
return ({"OPENAI_API_KEY": key} if key else {}), base_url or OPENCODE_GO_URL, \
|
| 116 |
+
"--api-base-url" if base_url else "OpenCode Go (OPENCODE_GO_URL, key LFF_OPENCODE_API_KEY / OPENCODE_API_KEY)"
|
| 117 |
+
if harness == "codex" and codex_auth == "chatgpt":
|
| 118 |
+
return {}, base_url, "--api-base-url" if base_url else "ChatGPT Codex backend (subscription login)"
|
| 119 |
+
if harness == "codex":
|
| 120 |
+
key = os.environ.get("LFF_OPENAI_API_KEY") or os.environ.get("OPENAI_API_KEY")
|
| 121 |
+
src = ("--api-base-url" if base_url else "LFF_OPENAI_BASE_URL" if os.environ.get("LFF_OPENAI_BASE_URL")
|
| 122 |
+
else "OPENAI_BASE_URL (same as api_player)" if os.environ.get("OPENAI_BASE_URL") else "official default")
|
| 123 |
+
url = base_url or os.environ.get("LFF_OPENAI_BASE_URL") or os.environ.get("OPENAI_BASE_URL")
|
| 124 |
+
return ({"OPENAI_API_KEY": key} if key else {}), url, src
|
| 125 |
+
return {}, None, "api_player's own environment"
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
RESUME_RETRIES = 3 # a resumed CLI that exits before writing any event is started again (nothing reached the model)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def mcp_tool_state(log_dir):
|
| 132 |
+
"""-> (number of MCP tool calls so far, whether our MCP server saw the episode end) from mcp_transcript.jsonl."""
|
| 133 |
+
n, finished = 0, False
|
| 134 |
+
try:
|
| 135 |
+
for line in open(os.path.join(log_dir, "mcp_transcript.jsonl")):
|
| 136 |
+
try:
|
| 137 |
+
d = json.loads(line)
|
| 138 |
+
except ValueError:
|
| 139 |
+
continue
|
| 140 |
+
if d.get("ev") == "tool":
|
| 141 |
+
n, finished = n + 1, bool(d.get("finished"))
|
| 142 |
+
except OSError:
|
| 143 |
+
pass
|
| 144 |
+
return n, finished
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def continue_episode(ad, h, ep, stop):
|
| 148 |
+
"""The CLI exited although the episode is not over (it ends when the model replies without a tool call): send
|
| 149 |
+
the reference driver's nudge as a user turn, as api_player does after such a reply, and wait again. Same rule:
|
| 150 |
+
after MAX_NO_TOOL nudges in a row without a tool call in between, the next such reply ends the run. -> log list."""
|
| 151 |
+
out, no_tool, (n_calls, _) = [], 0, mcp_tool_state(ep.log_dir)
|
| 152 |
+
deadline = h.t_start + h.spec.timeout_s
|
| 153 |
+
while ad.can_resume and h.exit_reason == "exited" and not stop["flag"]:
|
| 154 |
+
n, finished = mcp_tool_state(ep.log_dir)
|
| 155 |
+
if finished: # api_player stops here too, without a status call
|
| 156 |
+
break
|
| 157 |
+
try: # the status call api_player makes for its nudge
|
| 158 |
+
stx = json.loads(call_server(ep.port, ep.token, "status", {}))
|
| 159 |
+
except Exception as e:
|
| 160 |
+
out.append(dict(ev="status_failed", error=f"{type(e).__name__}: {e}"[:300], t=time.time()))
|
| 161 |
+
break
|
| 162 |
+
if stx.get("finished"):
|
| 163 |
+
break
|
| 164 |
+
no_tool = 1 if n > n_calls else no_tool + 1
|
| 165 |
+
n_calls = n
|
| 166 |
+
if no_tool > MAX_NO_TOOL:
|
| 167 |
+
out.append(dict(ev="abort", reason=f"no tool call {no_tool} times", t=time.time()))
|
| 168 |
+
break
|
| 169 |
+
if time.time() >= deadline:
|
| 170 |
+
h.exit_reason = "timeout"
|
| 171 |
+
break
|
| 172 |
+
msg = continue_nudge(ep.port, ep.token, stx)
|
| 173 |
+
out.append(dict(ev="resume", message=msg, attempt=stx.get("attempt"), mcp_tool_calls=n, t=time.time()))
|
| 174 |
+
for retry in range(RESUME_RETRIES + 1):
|
| 175 |
+
size0 = os.path.getsize(h.spec.stdout_path) if os.path.exists(h.spec.stdout_path) else 0
|
| 176 |
+
ad.resume(h, msg)
|
| 177 |
+
ad.wait(h, timeout=max(1.0, deadline - time.time()))
|
| 178 |
+
grew = os.path.exists(h.spec.stdout_path) and os.path.getsize(h.spec.stdout_path) > size0
|
| 179 |
+
if h.exit_reason == "exited" or grew or stop["flag"] or retry == RESUME_RETRIES \
|
| 180 |
+
or time.time() + 30 >= deadline:
|
| 181 |
+
break
|
| 182 |
+
# the resumed CLI exited before writing any event (2026-10-20: the MCP handshake timed out on a loaded
|
| 183 |
+
# machine), so nothing reached the model: start the same resume again
|
| 184 |
+
out.append(dict(ev="resume_retry", exit_reason=h.exit_reason, t=time.time()))
|
| 185 |
+
time.sleep(30)
|
| 186 |
+
return out
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def model_upstream(harness, url, codex_auth):
|
| 190 |
+
"""-> (gateway kind, the model API the harness would call without the gateway)."""
|
| 191 |
+
if harness.startswith("claude_code") or harness == "dsh":
|
| 192 |
+
return "anthropic", url or ANTHROPIC_API
|
| 193 |
+
from lffbench.harnesses.codex import CHATGPT_BACKEND, OFFICIAL_API
|
| 194 |
+
if harness == "rpent_codex":
|
| 195 |
+
return "openai", url or OFFICIAL_API
|
| 196 |
+
return "openai", url or (CHATGPT_BACKEND if codex_auth == "chatgpt" else OFFICIAL_API)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def plain_config_sha256(ad, spec, ep, mg):
|
| 200 |
+
"""config_sha256 as if the harness called its model API directly: the model gateway is plumbing (like the
|
| 201 |
+
proxy variables, base.py PROXY_KEYS), so runs with and without it keep the same configuration hash."""
|
| 202 |
+
if not mg:
|
| 203 |
+
return ad.config_sha256(spec, ep)
|
| 204 |
+
import copy
|
| 205 |
+
s2 = copy.copy(spec)
|
| 206 |
+
s2.argv = [a.replace(mg["url"], mg["upstream"]) if isinstance(a, str) else a for a in spec.argv]
|
| 207 |
+
s2.env = {k: (v.replace(mg["url"], mg["upstream"]) if isinstance(v, str) else v) for k, v in spec.env.items()}
|
| 208 |
+
return ad.config_sha256(s2, ep)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def write_json(path, d):
|
| 212 |
+
tmp = path + ".tmp"
|
| 213 |
+
with open(tmp, "w") as f:
|
| 214 |
+
json.dump(d, f, indent=1, ensure_ascii=False, default=str)
|
| 215 |
+
os.replace(tmp, path)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def run(a, adapter_kw=None):
|
| 219 |
+
"""Returns (exit code, harness.json dict). adapter_kw overrides adapter construction (self-check)."""
|
| 220 |
+
provider = a.provider or PROVIDER.get(a.harness, "")
|
| 221 |
+
ep = EpisodeSpec.from_session(a.session, a.model, a.effort, provider)
|
| 222 |
+
if getattr(a, "red_team", False): # before the contract: red-team runs get their own contract_sha256
|
| 223 |
+
if a.harness == "ours":
|
| 224 |
+
raise SystemExit("--red-team is for native harnesses")
|
| 225 |
+
RT.mark(ep.log_dir)
|
| 226 |
+
contract, csha = C.write_contract(ep.log_dir)
|
| 227 |
+
mg_box = {} # the model gateway process, stopped whatever happens below
|
| 228 |
+
try:
|
| 229 |
+
return _run(a, adapter_kw, provider, ep, csha, mg_box)
|
| 230 |
+
finally:
|
| 231 |
+
MG.stop_model_gateway(mg_box.get("proc"))
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def _run(a, adapter_kw, provider, ep, csha, mg_box):
|
| 235 |
+
mg = None
|
| 236 |
+
if adapter_kw is None:
|
| 237 |
+
a.codex_auth = getattr(a, "codex_auth", None) or ("apikey" if a.harness in ROBOT_HARNESSES else "chatgpt")
|
| 238 |
+
if a.harness == "rpent_codex" and a.codex_auth != "apikey":
|
| 239 |
+
raise SystemExit("Historical RPent adapter supports apikey only")
|
| 240 |
+
claude_auth = getattr(a, "claude_auth", None) or default_claude_auth(a.harness)
|
| 241 |
+
if getattr(a, "codex_provider", "openai") in ("deepseek", "opencode"):
|
| 242 |
+
a.codex_auth = "apikey" # no subscription login for DeepSeek / OpenCode Go
|
| 243 |
+
api_env, url, endpoint = api_env_for(a.harness, a.api_base_url, getattr(a, "codex_auth", "apikey"),
|
| 244 |
+
claude_auth, getattr(a, "codex_provider", "openai"))
|
| 245 |
+
if a.harness != "ours" and not getattr(a, "no_model_gateway", False):
|
| 246 |
+
# the harness reaches its model API only through the model gateway (scripts/model_gateway.py)
|
| 247 |
+
kind, upstream = model_upstream(a.harness, url, a.codex_auth)
|
| 248 |
+
mg_box["proc"], mginfo = MG.start_model_gateway(upstream, kind, ep.log_dir,
|
| 249 |
+
getattr(a, "token_budget_in", None),
|
| 250 |
+
getattr(a, "token_budget_out", None),
|
| 251 |
+
allow_files=a.harness == "dsh")
|
| 252 |
+
mg = dict(url=mginfo["url"], upstream=upstream, kind=kind, upstream_host=mginfo["upstream_host"],
|
| 253 |
+
pid=mginfo["pid"])
|
| 254 |
+
url = mg["url"]
|
| 255 |
+
if a.harness.startswith("claude_code"):
|
| 256 |
+
api_env["ANTHROPIC_BASE_URL"] = url
|
| 257 |
+
adapter_kw = dict(timeout_s=a.timeout)
|
| 258 |
+
if a.harness.startswith("claude_code"):
|
| 259 |
+
adapter_kw.update(api_env=api_env, max_budget_usd=a.max_budget_usd, allow_unpinned=a.allow_unpinned,
|
| 260 |
+
auth=claude_auth)
|
| 261 |
+
elif a.harness == "codex":
|
| 262 |
+
adapter_kw.update(api_env=api_env, base_url=url, allow_unpinned=a.allow_unpinned, auth=a.codex_auth,
|
| 263 |
+
catalog=a.codex_catalog)
|
| 264 |
+
elif a.harness == "dsh":
|
| 265 |
+
adapter_kw.update(api_env=api_env, base_url=url, allow_unpinned=a.allow_unpinned)
|
| 266 |
+
elif a.harness in ROBOT_HARNESSES:
|
| 267 |
+
adapter_kw.update(api_env=api_env, base_url=url, allow_unpinned=a.allow_unpinned,
|
| 268 |
+
auth=a.codex_auth, catalog=a.codex_catalog)
|
| 269 |
+
if a.harness == "rpent_codex": # historical, explicitly exposed RPent experiment settings
|
| 270 |
+
adapter_kw.update(sessions=a.rpent_sessions, attempts_per_session=a.rpent_attempts_per_session,
|
| 271 |
+
max_turns=a.rpent_max_turns)
|
| 272 |
+
if getattr(a, "jail", False):
|
| 273 |
+
if a.harness == "ours":
|
| 274 |
+
raise SystemExit("--jail is for native harnesses")
|
| 275 |
+
adapter_kw["jail"] = True
|
| 276 |
+
else:
|
| 277 |
+
adapter_kw.update(provider=provider)
|
| 278 |
+
else:
|
| 279 |
+
endpoint = "set by the caller (self-check)"
|
| 280 |
+
ad = get_adapter(a.harness, **adapter_kw)
|
| 281 |
+
ver = ad.version()
|
| 282 |
+
hj_path = os.path.join(ep.log_dir, "harness.json")
|
| 283 |
+
hj = dict(harness=ad.name, version=ver.get("version"), binary=ver.get("binary"), model=a.model, effort=a.effort,
|
| 284 |
+
provider=provider, capabilities={k: vars(c) for k, c in ad.capabilities.items()},
|
| 285 |
+
contract_sha256=csha, task=ep.task, seed=ep.seed, api_endpoint_from=endpoint, status="preparing",
|
| 286 |
+
t_prepare=time.time(), jail=ad.jail_info(), auth=ad.auth_info() if ad.name != "ours" else None,
|
| 287 |
+
config=ad.config_info() if hasattr(ad, "config_info") else None,
|
| 288 |
+
model_gateway=({k: mg[k] for k in ("kind", "upstream_host", "pid")} if mg else None))
|
| 289 |
+
if ad.name == "ours":
|
| 290 |
+
first = None
|
| 291 |
+
spec = ad.prepare(ep)
|
| 292 |
+
else:
|
| 293 |
+
first, _ = render_first_message(ep)
|
| 294 |
+
if getattr(a, "red_team", False):
|
| 295 |
+
first = RT.first_message(first)
|
| 296 |
+
hj["red_team"] = RT.marker(ep.log_dir)
|
| 297 |
+
with open(os.path.join(ep.log_dir, "first_message.txt"), "w") as f:
|
| 298 |
+
f.write(first)
|
| 299 |
+
spec = ad.prepare(ep, first, **(dict(reuse_state=a.reuse_state) if getattr(a, "reuse_state", None) else {}))
|
| 300 |
+
hj["first_message_sha256"] = C.sha256_text(first)
|
| 301 |
+
hj.update(argv=ad.logged_argv(spec), cwd=spec.cwd, env_keys=sorted(spec.env),
|
| 302 |
+
env_mode="exact whitelist (Popen env=, same as env -i)" if ad.name != "ours" else "inherited (own code)",
|
| 303 |
+
state_dirs=spec.state_dirs, config_sha256=plain_config_sha256(ad, spec, ep, mg), status="launching")
|
| 304 |
+
write_json(hj_path, hj)
|
| 305 |
+
h, code, gw = None, 0, None
|
| 306 |
+
stop = dict(flag=False)
|
| 307 |
+
|
| 308 |
+
def on_term(*_):
|
| 309 |
+
stop["flag"] = True
|
| 310 |
+
if h is not None and h.proc is not None:
|
| 311 |
+
ad.kill(h)
|
| 312 |
+
signal.signal(signal.SIGTERM, on_term)
|
| 313 |
+
try:
|
| 314 |
+
if (ad.uses_mcp or ad.uses_gateway) and not getattr(a, "no_gateway", False): # the episode's tools, for
|
| 315 |
+
# every MCP process of the run / every SDK client of a framework adapter (base.HarnessAdapter.uses_gateway)
|
| 316 |
+
gw, ginfo = start_gateway(ep.session_path)
|
| 317 |
+
hj["gateway"] = dict(url=ginfo["url"], pid=ginfo["pid"])
|
| 318 |
+
try:
|
| 319 |
+
h = ad.launch(spec, ep, skip_preflight=getattr(a, "skip_preflight", False))
|
| 320 |
+
except HarnessRefused as e:
|
| 321 |
+
pre = dict(spec.preflight or {})
|
| 322 |
+
hj.update(status="refused", refused=str(e), preflight={k: v for k, v in pre.items() if k != "fingerprint"})
|
| 323 |
+
write_json(hj_path, hj)
|
| 324 |
+
print("REFUSED:", e, flush=True)
|
| 325 |
+
return 2, hj
|
| 326 |
+
pre = dict(spec.preflight or {})
|
| 327 |
+
if "fingerprint" in pre:
|
| 328 |
+
write_json(os.path.join(ep.log_dir, "harness_preflight.json"), pre)
|
| 329 |
+
hj.update(status="running", pid=h.pid, env_observed_keys=h.env_observed_keys, t_start=h.t_start,
|
| 330 |
+
preflight={k: v for k, v in pre.items() if k != "fingerprint"}, init=h.info.get("init"))
|
| 331 |
+
write_json(hj_path, hj)
|
| 332 |
+
ad.wait(h)
|
| 333 |
+
cont = [] if getattr(a, "no_continue", False) else continue_episode(ad, h, ep, stop)
|
| 334 |
+
if cont:
|
| 335 |
+
hj["continuation"] = cont
|
| 336 |
+
write_json(hj_path, hj)
|
| 337 |
+
if stop["flag"]:
|
| 338 |
+
h.exit_reason, code = "stopped", 143
|
| 339 |
+
tw = ad.collect(h)
|
| 340 |
+
au = ad.audit(h)
|
| 341 |
+
if ad.name == "ours" and spec.first_message:
|
| 342 |
+
hj["first_message_sha256"] = C.sha256_text(spec.first_message)
|
| 343 |
+
hj.update(status="done" if code == 0 else "stopped", exit_code=h.exit_code, exit_reason=h.exit_reason,
|
| 344 |
+
t_end=h.t_end, wall_s=round(h.t_end - h.t_start, 1), audit_ok=au.get("ok"),
|
| 345 |
+
violations=au.get("violations"), final_metrics=(tw.final or {}).get("final_metrics"))
|
| 346 |
+
if mg: # refusals do not void the trial; they flag it for a look (EFE running.md "Usage gateway")
|
| 347 |
+
tot = MG.read_totals(ep.log_dir) or {}
|
| 348 |
+
hj["model_gateway"].update({k: tot.get(k) for k in MG.Totals.KEYS}, tokens=tot.get("tokens"),
|
| 349 |
+
models=tot.get("models"), budget_stop=tot.get("budget_stop"))
|
| 350 |
+
hj["review_flags"] = ["model_gateway:" + k for k in MG.flagged(tot)] + (
|
| 351 |
+
["model_gateway:other_model"] if set(tot.get("models") or {}) - {a.model} else [])
|
| 352 |
+
if code == 0 and h.exit_code not in (0, None):
|
| 353 |
+
code = 3
|
| 354 |
+
write_json(hj_path, hj)
|
| 355 |
+
return code, hj
|
| 356 |
+
except Exception as e:
|
| 357 |
+
hj.update(status="error", error=f"{type(e).__name__}: {e}", traceback=traceback.format_exc()[-3000:])
|
| 358 |
+
write_json(hj_path, hj)
|
| 359 |
+
if h is not None and h.proc is not None and h.proc.poll() is None:
|
| 360 |
+
ad.kill(h)
|
| 361 |
+
return 3, hj
|
| 362 |
+
finally:
|
| 363 |
+
stop_gateway(gw)
|
| 364 |
+
if not getattr(a, "keep_run_dir", False):
|
| 365 |
+
ad.cleanup(spec)
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def parser():
|
| 369 |
+
ap = argparse.ArgumentParser()
|
| 370 |
+
ap.add_argument("--harness", required=True, choices=NAMES)
|
| 371 |
+
ap.add_argument("--session", required=True)
|
| 372 |
+
ap.add_argument("--provider", default=None, help="ours: openai / anthropic / gemini / chat")
|
| 373 |
+
ap.add_argument("--model", required=True)
|
| 374 |
+
ap.add_argument("--effort", default="high")
|
| 375 |
+
ap.add_argument("--api-base-url", default=None)
|
| 376 |
+
ap.add_argument("--codex-auth", default=None, choices=["chatgpt", "apikey"],
|
| 377 |
+
help="Codex authentication: chatgpt defaults for codex; apikey defaults for Robot Harnesses. "
|
| 378 |
+
"SenseNova/EmbodiedEvo also support chatgpt; historical RPent is apikey only")
|
| 379 |
+
ap.add_argument("--claude-auth", default=None, choices=["oauth", "apikey"],
|
| 380 |
+
help="claude_code*: subscription token (default for claude_code_full) or an API key (claude_code, "
|
| 381 |
+
"--bare, takes only an API key); see above")
|
| 382 |
+
ap.add_argument("--codex-provider", default="openai", choices=["openai", "deepseek", "opencode"],
|
| 383 |
+
help="codex: model provider; deepseek = DeepSeek's Responses endpoint with LFF_DEEPSEEK_API_KEY / "
|
| 384 |
+
"DEEPSEEK_API_KEY, opencode = OpenCode Go's with LFF_OPENCODE_API_KEY / OPENCODE_API_KEY "
|
| 385 |
+
"(both imply --codex-auth apikey)")
|
| 386 |
+
ap.add_argument("--codex-catalog", default="generic", choices=["generic", "native"],
|
| 387 |
+
help="codex: model catalog, the main table's shared configuration (default) or Codex's native "
|
| 388 |
+
"one (control); see lffbench/harnesses/codex.py")
|
| 389 |
+
ap.add_argument("--max-budget-usd", type=float, default=None, help="claude_code*: --max-budget-usd")
|
| 390 |
+
ap.add_argument("--rpent-sessions", type=int, default=5,
|
| 391 |
+
help="rpent_codex: planner sessions per episode (RPent --explore-sessions; default 5 = k + 2 spare)")
|
| 392 |
+
ap.add_argument("--rpent-attempts-per-session", type=int, default=1,
|
| 393 |
+
help="rpent_codex: attempts one session may use (RPent --explore-attempts-per-session): 1 = "
|
| 394 |
+
"variant H, a fresh session with a handoff after each failed attempt (default); 0 = no limit")
|
| 395 |
+
ap.add_argument("--rpent-max-turns", type=int, default=100,
|
| 396 |
+
help="rpent_codex: model responses per session (RPent --max-turns)")
|
| 397 |
+
ap.add_argument("--timeout", type=float, default=10800)
|
| 398 |
+
ap.add_argument("--allow-unpinned", action="store_true",
|
| 399 |
+
help="launch even if no pin exists for this version / model / effort (the preflight still runs)")
|
| 400 |
+
ap.add_argument("--keep-run-dir", action="store_true", help="do not delete the one-time dirs (debugging)")
|
| 401 |
+
ap.add_argument("--no-gateway", action="store_true",
|
| 402 |
+
help="native harnesses: run the tools inside each MCP server process instead of the episode's "
|
| 403 |
+
"tool gateway (scripts/tool_gateway.py; same ToolCore, budget carried over via the transcript)")
|
| 404 |
+
ap.add_argument("--no-model-gateway", action="store_true",
|
| 405 |
+
help="native harnesses: call the model API directly instead of through the run's model gateway "
|
| 406 |
+
"(scripts/model_gateway.py: model calls only, provider-side tools refused, tokens counted)")
|
| 407 |
+
ap.add_argument("--token-budget-in", type=int, default=None,
|
| 408 |
+
help="model gateway: refuse further model calls once this many input tokens were used (cached "
|
| 409 |
+
"input counts in full)")
|
| 410 |
+
ap.add_argument("--token-budget-out", type=int, default=None,
|
| 411 |
+
help="model gateway: ... output tokens (reasoning included)")
|
| 412 |
+
ap.add_argument("--red-team", action="store_true",
|
| 413 |
+
help="adversarial acceptance run (lffbench/harnesses/redteam.py): the first message starts with the "
|
| 414 |
+
"red-team notice; own contract_sha256; read with scripts/redteam_report.py")
|
| 415 |
+
ap.add_argument("--no-continue", action="store_true",
|
| 416 |
+
help="do not resume a CLI that exited before the episode was over (self-check / debugging)")
|
| 417 |
+
ap.add_argument("--jail", action="store_true",
|
| 418 |
+
help="native harnesses: run the CLI in the native-harness jail (docs/15 §3.4): as uid 65534, no host "
|
| 419 |
+
"path visible, MCP server outside behind a socket relay")
|
| 420 |
+
return ap
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
def main():
|
| 424 |
+
code, hj = run(parser().parse_args())
|
| 425 |
+
print(json.dumps({k: hj.get(k) for k in ("harness", "status", "exit_reason", "audit_ok", "violations",
|
| 426 |
+
"contract_sha256", "final_metrics")}, default=str), flush=True)
|
| 427 |
+
sys.exit(code)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
if __name__ == "__main__":
|
| 431 |
+
main()
|
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/lerobot_export.py
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars.
|
| 2 |
+
|
| 3 |
+
Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding
|
| 4 |
+
can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan):
|
| 5 |
+
|
| 6 |
+
python scripts/lerobot_export.py plan --raw <raw_root>[,<raw_root2>] --runs-root <lffbench>/runs/api \
|
| 7 |
+
--paper <paper/latex> --task-set <lffbench>/sets/main_v2_1inst.txt --work <work_dir> [--batches ...] [--limit N]
|
| 8 |
+
python scripts/lerobot_export.py shard --work <work_dir> --shard i --nshards N
|
| 9 |
+
python scripts/lerobot_export.py merge --work <work_dir> --nshards N --out <dataset_root>
|
| 10 |
+
|
| 11 |
+
Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0
|
| 12 |
+
mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped.
|
| 13 |
+
|
| 14 |
+
LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t):
|
| 15 |
+
observation.images.image agentview RGB 256x256 (upright; LIBERO naming)
|
| 16 |
+
observation.images.wrist_image wrist (eye-in-hand) RGB 256x256
|
| 17 |
+
observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout)
|
| 18 |
+
observation.joint_pos / joint_vel 7 arm joints (rad, rad/s)
|
| 19 |
+
observation.eef_quat 4: xyzw; observation.gripper_width 1 (m)
|
| 20 |
+
action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad),
|
| 21 |
+
gripper (-1 open, +1 close)
|
| 22 |
+
annotation.attempt_index attempt (1-based) the frame belongs to
|
| 23 |
+
annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`)
|
| 24 |
+
annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action)
|
| 25 |
+
annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt
|
| 26 |
+
annotation.task_event number of task-monitor events (error / progress events) registered at this step
|
| 27 |
+
Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table),
|
| 28 |
+
runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state
|
| 29 |
+
per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/.
|
| 30 |
+
"""
|
| 31 |
+
import argparse
|
| 32 |
+
import glob
|
| 33 |
+
import json
|
| 34 |
+
import os
|
| 35 |
+
import re
|
| 36 |
+
import shutil
|
| 37 |
+
import time
|
| 38 |
+
|
| 39 |
+
import numpy as np
|
| 40 |
+
|
| 41 |
+
FPS = 20
|
| 42 |
+
RES = 256
|
| 43 |
+
BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke",
|
| 44 |
+
"cc_smoke", "cc_opus_smoke"]
|
| 45 |
+
BATCH_NOTES = {
|
| 46 |
+
"cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog",
|
| 47 |
+
"cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267",
|
| 48 |
+
"cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299",
|
| 49 |
+
"cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances",
|
| 50 |
+
"cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)",
|
| 51 |
+
"cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the "
|
| 52 |
+
"with-history continuation of failed runs is incomplete",
|
| 53 |
+
"cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early",
|
| 54 |
+
"cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt",
|
| 55 |
+
"cc_opus_smoke": "smoke test: single attempt",
|
| 56 |
+
}
|
| 57 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 58 |
+
CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)",
|
| 59 |
+
"L2": "disturbed state to restore (incl. damage the agent causes)",
|
| 60 |
+
"L3": "infeasible manipulation strategy (grasp / contact / tool must change)",
|
| 61 |
+
"L4": "misjudged geometry (size, shape, fit, hidden structure)",
|
| 62 |
+
"L5": "misjudged physics (mass distribution, friction, dynamics)"}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def features():
|
| 66 |
+
vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]}
|
| 67 |
+
f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names}
|
| 68 |
+
i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None}
|
| 69 |
+
return {
|
| 70 |
+
"observation.images.image": vid(),
|
| 71 |
+
"observation.images.wrist_image": vid(),
|
| 72 |
+
"observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z",
|
| 73 |
+
"finger_qpos_left", "finger_qpos_right"]),
|
| 74 |
+
"observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 75 |
+
"observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 76 |
+
"observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]),
|
| 77 |
+
"observation.gripper_width": f32(1, ["width_m"]),
|
| 78 |
+
"action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y",
|
| 79 |
+
"eef_delta_rot_aa_z", "gripper_close"]),
|
| 80 |
+
"annotation.attempt_index": i64(),
|
| 81 |
+
"annotation.command_index": i64(),
|
| 82 |
+
"annotation.phase": i64(),
|
| 83 |
+
"annotation.attempt_success": i64(),
|
| 84 |
+
"annotation.task_event": i64(),
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ------------------------------------------------------------------------------------------------ paper metadata
|
| 89 |
+
|
| 90 |
+
def _clean_tex(s):
|
| 91 |
+
s = re.sub(r"%.*", "", s)
|
| 92 |
+
for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"),
|
| 93 |
+
(r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"),
|
| 94 |
+
(r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"),
|
| 95 |
+
(r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"),
|
| 96 |
+
(r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]:
|
| 97 |
+
s = re.sub(a, b, s)
|
| 98 |
+
s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s)
|
| 99 |
+
s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s)
|
| 100 |
+
for _ in range(3):
|
| 101 |
+
s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s)
|
| 102 |
+
s = re.sub(r"\$([^$]*)\$", r"\1", s)
|
| 103 |
+
s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ")
|
| 104 |
+
s = re.sub(r"\{([^{}]*)\}", r"\1", s)
|
| 105 |
+
s = re.sub(r"\\[a-zA-Z]+\*?", "", s)
|
| 106 |
+
return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def paper_tasks(paper_dir):
|
| 110 |
+
"""{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the
|
| 111 |
+
paper's task table and task appendix (empty if the paper sources are not there)."""
|
| 112 |
+
out = {}
|
| 113 |
+
if not paper_dir:
|
| 114 |
+
return out
|
| 115 |
+
app = os.path.join(paper_dir, "sections", "appendix_tasks.tex")
|
| 116 |
+
tab = os.path.join(paper_dir, "sections", "tab_tasks.tex")
|
| 117 |
+
if os.path.exists(app):
|
| 118 |
+
txt = open(app).read()
|
| 119 |
+
parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt)
|
| 120 |
+
for i in range(1, len(parts) - 1, 2):
|
| 121 |
+
if parts[i] != "\\paragraph{":
|
| 122 |
+
continue
|
| 123 |
+
body = parts[i + 1]
|
| 124 |
+
m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S)
|
| 125 |
+
if not m:
|
| 126 |
+
continue
|
| 127 |
+
name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip()
|
| 128 |
+
desc = _clean_tex(body[m.end():])
|
| 129 |
+
out[code] = dict(name=name, cause=_clean_tex(cause), description=desc)
|
| 130 |
+
if os.path.exists(tab):
|
| 131 |
+
names = {v["name"].lower(): k for k, v in out.items()}
|
| 132 |
+
for line in open(tab):
|
| 133 |
+
cells = [c.strip() for c in line.split("&")]
|
| 134 |
+
if len(cells) != 6 or not cells[-1].endswith("\\\\"):
|
| 135 |
+
continue
|
| 136 |
+
nm = re.sub(r"\\contscene", "", cells[0]).strip().lower()
|
| 137 |
+
code = names.get(nm)
|
| 138 |
+
if not code:
|
| 139 |
+
continue
|
| 140 |
+
out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]),
|
| 141 |
+
repair_within_attempt=_clean_tex(cells[3]) == "yes",
|
| 142 |
+
oracle_first_attempt_pct=_clean_tex(cells[4]),
|
| 143 |
+
naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip()))
|
| 144 |
+
return out
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
# ------------------------------------------------------------------------------------------------ collection
|
| 148 |
+
|
| 149 |
+
def manifest_status(runs_root, batch, run, cache={}):
|
| 150 |
+
if batch not in cache:
|
| 151 |
+
p = os.path.join(runs_root, batch, "manifest.json")
|
| 152 |
+
cache[batch] = json.load(open(p)) if os.path.exists(p) else {}
|
| 153 |
+
m = cache[batch]
|
| 154 |
+
for r in m.get("runs", []):
|
| 155 |
+
if r.get("run") == run:
|
| 156 |
+
return r.get("status", "?"), r
|
| 157 |
+
for r in m.get("superseded", []):
|
| 158 |
+
if r.get("run") == run:
|
| 159 |
+
return "superseded_" + str(r.get("status", "?")), r
|
| 160 |
+
return "not_in_manifest", {}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def collect(raw_roots, runs_root, batches, task_order):
|
| 164 |
+
"""Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root."""
|
| 165 |
+
eps, rejected, seen = [], [], set()
|
| 166 |
+
for root in raw_roots:
|
| 167 |
+
for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))):
|
| 168 |
+
rep = json.load(open(rj))
|
| 169 |
+
batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"]
|
| 170 |
+
if (batches and batch not in batches) or (batch, run) in seen:
|
| 171 |
+
continue
|
| 172 |
+
seen.add((batch, run))
|
| 173 |
+
ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff")
|
| 174 |
+
status, entry = manifest_status(runs_root, batch, run)
|
| 175 |
+
if not ok:
|
| 176 |
+
never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked")
|
| 177 |
+
rejected.append(dict(run=run, batch=batch, run_status=status,
|
| 178 |
+
reason="run never started (no contract, no robot command)" if never else
|
| 179 |
+
"replay does not reproduce the log (the log has gaps or the replay diverged)",
|
| 180 |
+
detail=rep.get("first_mismatches")))
|
| 181 |
+
continue
|
| 182 |
+
for ep in rep.get("episodes", []):
|
| 183 |
+
d = os.path.join(root, ep["dir"])
|
| 184 |
+
ann = json.load(open(os.path.join(d, "annotation.json")))
|
| 185 |
+
judged = [a for a in ann["attempts"] if a.get("success") is not None]
|
| 186 |
+
if not judged or ep["n_frames"] == 0:
|
| 187 |
+
rejected.append(dict(run=run, batch=batch, episode=ep["dir"],
|
| 188 |
+
reason="no judged attempt" if not judged else "no frames"))
|
| 189 |
+
continue
|
| 190 |
+
ann["source"]["run_status"] = status
|
| 191 |
+
ann["source"]["manifest_id"] = entry.get("id")
|
| 192 |
+
ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"],
|
| 193 |
+
max_eef_dev_m=rep["max_eef_dev_m"])
|
| 194 |
+
key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99),
|
| 195 |
+
{"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2),
|
| 196 |
+
ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"])
|
| 197 |
+
eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann))
|
| 198 |
+
eps.sort(key=lambda x: x["key"])
|
| 199 |
+
return eps, rejected
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# ------------------------------------------------------------------------------------------------ writing
|
| 203 |
+
|
| 204 |
+
def frames_of(path):
|
| 205 |
+
import av
|
| 206 |
+
with av.open(path) as c:
|
| 207 |
+
for fr in c.decode(video=0):
|
| 208 |
+
yield fr.to_ndarray(format="rgb24")
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def flat_row(i, ann, n, idx0):
|
| 212 |
+
s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"]
|
| 213 |
+
att = ann["attempts"]
|
| 214 |
+
a0 = att[0]
|
| 215 |
+
return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n,
|
| 216 |
+
batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"],
|
| 217 |
+
memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"),
|
| 218 |
+
episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att],
|
| 219 |
+
harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"),
|
| 220 |
+
effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"),
|
| 221 |
+
task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"),
|
| 222 |
+
category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"],
|
| 223 |
+
success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att],
|
| 224 |
+
feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att],
|
| 225 |
+
auto_ended=[a.get("auto_ended") for a in att],
|
| 226 |
+
corrected_later_in_run=[a.get("corrected_later_in_run") for a in att],
|
| 227 |
+
error_event_in_attempt=[a.get("error_event_in_attempt") for a in att],
|
| 228 |
+
run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"),
|
| 229 |
+
n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]),
|
| 230 |
+
first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def cmd_plan(a):
|
| 234 |
+
task_order = {}
|
| 235 |
+
if a.task_set and os.path.exists(a.task_set):
|
| 236 |
+
for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")):
|
| 237 |
+
task_order[line.split(":")[0].strip()] = i
|
| 238 |
+
batches = [b for b in a.batches.split(",") if b] if a.batches else None
|
| 239 |
+
eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order)
|
| 240 |
+
if a.limit:
|
| 241 |
+
eps = eps[:a.limit]
|
| 242 |
+
paper = paper_tasks(a.paper)
|
| 243 |
+
idx0 = 0
|
| 244 |
+
for i, e in enumerate(eps):
|
| 245 |
+
ann = e["ann"]
|
| 246 |
+
tname = ann["task"]["name"]
|
| 247 |
+
if tname in paper:
|
| 248 |
+
ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"}
|
| 249 |
+
ann["episode_index"] = i
|
| 250 |
+
ann["dataset_index_range"] = [idx0, idx0 + e["n"]]
|
| 251 |
+
e["index"], e["from"] = i, idx0
|
| 252 |
+
idx0 += e["n"]
|
| 253 |
+
del e["key"]
|
| 254 |
+
os.makedirs(a.work, exist_ok=True)
|
| 255 |
+
with open(os.path.join(a.work, "plan.json"), "w") as f:
|
| 256 |
+
json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f,
|
| 257 |
+
ensure_ascii=False)
|
| 258 |
+
print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def shard_range(n_eps, i, k):
|
| 262 |
+
return (n_eps * i) // k, (n_eps * (i + 1)) // k
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def cmd_shard(a):
|
| 266 |
+
from lerobot.datasets.lerobot_dataset import LeRobotDataset
|
| 267 |
+
t0 = time.time()
|
| 268 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 269 |
+
eps = plan["episodes"]
|
| 270 |
+
lo, hi = shard_range(len(eps), a.shard, a.nshards)
|
| 271 |
+
out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}")
|
| 272 |
+
if os.path.exists(os.path.join(out, "DONE")):
|
| 273 |
+
print(f"shard {a.shard}: done already", flush=True)
|
| 274 |
+
return
|
| 275 |
+
shutil.rmtree(out, ignore_errors=True)
|
| 276 |
+
ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out,
|
| 277 |
+
robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads,
|
| 278 |
+
vcodec=a.vcodec)
|
| 279 |
+
nfr = 0
|
| 280 |
+
for e in eps[lo:hi]:
|
| 281 |
+
d, ann, n = e["dir"], e["ann"], e["n"]
|
| 282 |
+
fr = np.load(os.path.join(d, "frames.npz"))
|
| 283 |
+
assert len(fr["action"]) == n, d
|
| 284 |
+
succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]}
|
| 285 |
+
evc = np.zeros(n, np.int64)
|
| 286 |
+
for ev in ann["task_events"]:
|
| 287 |
+
if 0 <= ev["frame"] < n:
|
| 288 |
+
evc[ev["frame"]] += 1
|
| 289 |
+
state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32)
|
| 290 |
+
instr = ann["task"]["instruction"]
|
| 291 |
+
k = 0
|
| 292 |
+
for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))):
|
| 293 |
+
if k >= n:
|
| 294 |
+
break
|
| 295 |
+
ds.add_frame({
|
| 296 |
+
"observation.images.image": img, "observation.images.wrist_image": wr,
|
| 297 |
+
"observation.state": state[k],
|
| 298 |
+
"observation.joint_pos": fr["joint_pos"][k].astype(np.float32),
|
| 299 |
+
"observation.joint_vel": fr["joint_vel"][k].astype(np.float32),
|
| 300 |
+
"observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32),
|
| 301 |
+
"observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32),
|
| 302 |
+
"action": fr["action"][k].astype(np.float32),
|
| 303 |
+
"annotation.attempt_index": np.array([fr["attempt"][k]], np.int64),
|
| 304 |
+
"annotation.command_index": np.array([fr["command"][k]], np.int64),
|
| 305 |
+
"annotation.phase": np.array([fr["phase"][k]], np.int64),
|
| 306 |
+
"annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64),
|
| 307 |
+
"annotation.task_event": np.array([evc[k]], np.int64),
|
| 308 |
+
"task": instr,
|
| 309 |
+
})
|
| 310 |
+
k += 1
|
| 311 |
+
if k != n:
|
| 312 |
+
raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames")
|
| 313 |
+
ds.save_episode()
|
| 314 |
+
nfr += n
|
| 315 |
+
ds.finalize()
|
| 316 |
+
shutil.rmtree(os.path.join(out, "images"), ignore_errors=True)
|
| 317 |
+
open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n")
|
| 318 |
+
print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def cmd_merge(a):
|
| 322 |
+
from pathlib import Path
|
| 323 |
+
from lerobot.datasets.aggregate import aggregate_datasets
|
| 324 |
+
t0 = time.time()
|
| 325 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 326 |
+
eps = plan["episodes"]
|
| 327 |
+
roots, ids = [], []
|
| 328 |
+
for i in range(a.nshards):
|
| 329 |
+
lo, hi = shard_range(len(eps), i, a.nshards)
|
| 330 |
+
if hi <= lo:
|
| 331 |
+
continue
|
| 332 |
+
r = os.path.join(a.work, "shards", f"shard_{i:03d}")
|
| 333 |
+
if not os.path.exists(os.path.join(r, "DONE")):
|
| 334 |
+
raise SystemExit(f"shard {i} is not done")
|
| 335 |
+
roots.append(Path(r))
|
| 336 |
+
ids.append(f"{plan['repo_id']}-shard{i:03d}")
|
| 337 |
+
if os.path.exists(a.out):
|
| 338 |
+
raise SystemExit(f"{a.out} exists; refusing to overwrite")
|
| 339 |
+
aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out))
|
| 340 |
+
print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True)
|
| 341 |
+
write_sidecars(a, plan)
|
| 342 |
+
print(f"merge done in {time.time() - t0:.0f}s", flush=True)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def write_sidecars(a, plan):
|
| 346 |
+
eps, paper = plan["episodes"], plan["paper"]
|
| 347 |
+
lff = os.path.join(a.out, "lff")
|
| 348 |
+
for sub in ("annotations", "sim_state", "final", "code"):
|
| 349 |
+
os.makedirs(os.path.join(lff, sub), exist_ok=True)
|
| 350 |
+
rows, runs, tasks = [], {}, {}
|
| 351 |
+
for e in eps:
|
| 352 |
+
i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"]
|
| 353 |
+
name = f"episode_{i:06d}"
|
| 354 |
+
if os.path.exists(os.path.join(d, "sim_state.npy")):
|
| 355 |
+
shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy"))
|
| 356 |
+
shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz"))
|
| 357 |
+
for cam, key in (("agentview", "image"), ("wrist", "wrist_image")):
|
| 358 |
+
shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png"))
|
| 359 |
+
with open(os.path.join(lff, "annotations", name + ".json"), "w") as f:
|
| 360 |
+
json.dump(ann, f, indent=1, ensure_ascii=False)
|
| 361 |
+
rows.append(flat_row(i, ann, n, e["from"]))
|
| 362 |
+
tname = ann["task"]["name"]
|
| 363 |
+
rk = (ann["source"]["batch"], ann["source"]["run"])
|
| 364 |
+
r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"),
|
| 365 |
+
run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"],
|
| 366 |
+
memory_free_chain_of=ann["source"].get("memory_free_chain_of"),
|
| 367 |
+
memory_free_rep=ann["source"].get("memory_free_rep"), task=tname,
|
| 368 |
+
seed=ann["task"]["seed"], model=ann["agent"].get("model"),
|
| 369 |
+
harness=ann["agent"].get("harness"),
|
| 370 |
+
harness_version=ann["agent"].get("harness_version"),
|
| 371 |
+
codex_catalog=ann["agent"].get("codex_catalog"),
|
| 372 |
+
outcome_class=ann["run_outcome"].get("outcome_class"),
|
| 373 |
+
attempt_history=ann["run_outcome"].get("attempt_history"),
|
| 374 |
+
agent_final_report=ann["run_outcome"].get("agent_final_report"),
|
| 375 |
+
episodes=[]))
|
| 376 |
+
for x in ann["attempts"]:
|
| 377 |
+
r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success")))
|
| 378 |
+
if tname not in tasks:
|
| 379 |
+
tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")}
|
| 380 |
+
if tname in paper:
|
| 381 |
+
tasks[tname]["paper"] = paper[tname]
|
| 382 |
+
tasks[tname]["instances"] = {}
|
| 383 |
+
tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"]
|
| 384 |
+
# memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id)
|
| 385 |
+
by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")}
|
| 386 |
+
for r in runs.values():
|
| 387 |
+
if r.get("memory_free_chain_of"):
|
| 388 |
+
r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"]))
|
| 389 |
+
for (b, rn), r in runs.items():
|
| 390 |
+
r["memory_free_retries"] = sorted((x["run"] for x in runs.values()
|
| 391 |
+
if x["batch"] == b and x.get("memory_free_chain_of_run") == rn),
|
| 392 |
+
key=lambda q: runs[(b, q)].get("memory_free_rep") or 0)
|
| 393 |
+
with open(os.path.join(lff, "episodes.jsonl"), "w") as f:
|
| 394 |
+
for row in rows:
|
| 395 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 396 |
+
with open(os.path.join(lff, "runs.jsonl"), "w") as f:
|
| 397 |
+
for r in runs.values():
|
| 398 |
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 399 |
+
with open(os.path.join(lff, "tasks.json"), "w") as f:
|
| 400 |
+
json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False)
|
| 401 |
+
with open(os.path.join(lff, "batches.json"), "w") as f:
|
| 402 |
+
json.dump(BATCH_NOTES, f, indent=1)
|
| 403 |
+
with open(os.path.join(lff, "rejected.json"), "w") as f:
|
| 404 |
+
json.dump(plan["rejected"], f, indent=1)
|
| 405 |
+
here = os.path.dirname(os.path.abspath(__file__))
|
| 406 |
+
for s in ("lerobot_replay.py", "lerobot_export.py"):
|
| 407 |
+
shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s))
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def main():
|
| 411 |
+
ap = argparse.ArgumentParser()
|
| 412 |
+
ap.add_argument("step", choices=["plan", "shard", "merge"])
|
| 413 |
+
ap.add_argument("--work", required=True)
|
| 414 |
+
ap.add_argument("--raw", default="")
|
| 415 |
+
ap.add_argument("--runs-root", default="")
|
| 416 |
+
ap.add_argument("--out", default="")
|
| 417 |
+
ap.add_argument("--paper", default="")
|
| 418 |
+
ap.add_argument("--task-set", default="")
|
| 419 |
+
ap.add_argument("--repo-id", default="lffbench/agent-replays")
|
| 420 |
+
ap.add_argument("--batches", default="")
|
| 421 |
+
ap.add_argument("--limit", type=int, default=0)
|
| 422 |
+
ap.add_argument("--shard", type=int, default=0)
|
| 423 |
+
ap.add_argument("--nshards", type=int, default=1)
|
| 424 |
+
ap.add_argument("--threads", type=int, default=2)
|
| 425 |
+
ap.add_argument("--vcodec", default="libsvtav1")
|
| 426 |
+
a = ap.parse_args()
|
| 427 |
+
{"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
if __name__ == "__main__":
|
| 431 |
+
main()
|
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/lerobot_replay.py
ADDED
|
@@ -0,0 +1,744 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay
|
| 2 |
+
against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the
|
| 3 |
+
LeRobot export (scripts/lerobot_export.py).
|
| 4 |
+
|
| 5 |
+
python scripts/lerobot_replay.py check <run_dir> [<run_dir> ...] [--json out.json] # replay only, print fidelity
|
| 6 |
+
python scripts/lerobot_replay.py record <run_dir> --out <raw_root> [--res 256]
|
| 7 |
+
|
| 8 |
+
Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot
|
| 9 |
+
commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite
|
| 10 |
+
is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly
|
| 11 |
+
like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same
|
| 12 |
+
outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width,
|
| 13 |
+
ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code
|
| 14 |
+
hashes equal the current files are expected to match (check_code()).
|
| 15 |
+
|
| 16 |
+
Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB,
|
| 17 |
+
proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes:
|
| 18 |
+
protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode
|
| 19 |
+
per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the
|
| 20 |
+
fidelity check runs in record mode too. Per episode the recorder writes <raw_root>/<batch>/<run>/epNN/:
|
| 21 |
+
agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes)
|
| 22 |
+
frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase
|
| 23 |
+
sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel)
|
| 24 |
+
final_*.png, final.npz observation after the last control step (the state the outcome was judged in)
|
| 25 |
+
annotation.json episode annotation (build_annotation)
|
| 26 |
+
and <raw_root>/<batch>/<run>/replay.json (fidelity) when the whole run is done.
|
| 27 |
+
"""
|
| 28 |
+
import argparse
|
| 29 |
+
import ast
|
| 30 |
+
import hashlib
|
| 31 |
+
import importlib
|
| 32 |
+
import json
|
| 33 |
+
import math
|
| 34 |
+
import os
|
| 35 |
+
import pkgutil
|
| 36 |
+
import re
|
| 37 |
+
import shutil
|
| 38 |
+
import sys
|
| 39 |
+
import time
|
| 40 |
+
from collections import defaultdict
|
| 41 |
+
|
| 42 |
+
import numpy as np
|
| 43 |
+
|
| 44 |
+
LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 45 |
+
sys.path.insert(0, LFF_ROOT)
|
| 46 |
+
|
| 47 |
+
from lffbench import envs # noqa: E402
|
| 48 |
+
from lffbench import tasks as task_pkg # noqa: E402
|
| 49 |
+
from lffbench.agent import camera as C # noqa: E402
|
| 50 |
+
from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402
|
| 51 |
+
from lffbench.task_base import TASKS # noqa: E402
|
| 52 |
+
|
| 53 |
+
for _m in pkgutil.iter_modules(task_pkg.__path__):
|
| 54 |
+
importlib.import_module(f"lffbench.tasks.{_m.name}")
|
| 55 |
+
|
| 56 |
+
# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the
|
| 57 |
+
# task's outcome() check after `finish` (the arm holds still; not an agent action)
|
| 58 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 59 |
+
FPS = 20
|
| 60 |
+
SCHEMA = "lff-replay-1"
|
| 61 |
+
|
| 62 |
+
# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR"
|
| 63 |
+
ERROR_FLAGS = ("trap_fired", "recovered_in_attempt")
|
| 64 |
+
ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events",
|
| 65 |
+
"n_missed_strikes", "n_open_gripper_pushes")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def load_jsonl(p):
|
| 69 |
+
out = []
|
| 70 |
+
if not os.path.exists(p):
|
| 71 |
+
return out
|
| 72 |
+
with open(p) as f:
|
| 73 |
+
for line in f:
|
| 74 |
+
line = line.strip()
|
| 75 |
+
if line:
|
| 76 |
+
try:
|
| 77 |
+
out.append(json.loads(line))
|
| 78 |
+
except ValueError:
|
| 79 |
+
pass
|
| 80 |
+
return out
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def norm_json(o):
|
| 84 |
+
return json.loads(json.dumps(o, default=_json_default))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def sha256(p):
|
| 88 |
+
with open(p, "rb") as f:
|
| 89 |
+
return hashlib.sha256(f.read()).hexdigest()
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def check_code(run_dir):
|
| 93 |
+
"""[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract."""
|
| 94 |
+
p = os.path.join(run_dir, "contract.json")
|
| 95 |
+
if not os.path.exists(p):
|
| 96 |
+
return [("contract.json", None, None)]
|
| 97 |
+
files = json.load(open(p))["contract"].get("server_code_files", {})
|
| 98 |
+
bad = []
|
| 99 |
+
for f, h in files.items():
|
| 100 |
+
q = os.path.join(LFF_ROOT, f)
|
| 101 |
+
cur = sha256(q) if os.path.exists(q) else None
|
| 102 |
+
if cur != h:
|
| 103 |
+
bad.append((f, h, cur))
|
| 104 |
+
return bad
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def diff_json(a, b, path="", tol=0.0, out=None, limit=20):
|
| 108 |
+
"""Differences between two JSON values (numbers compared with an absolute tolerance)."""
|
| 109 |
+
out = [] if out is None else out
|
| 110 |
+
if len(out) >= limit:
|
| 111 |
+
return out
|
| 112 |
+
if isinstance(a, dict) and isinstance(b, dict):
|
| 113 |
+
for k in sorted(set(a) | set(b)):
|
| 114 |
+
if k not in a or k not in b:
|
| 115 |
+
out.append((f"{path}.{k}", a.get(k, "<missing>"), b.get(k, "<missing>")))
|
| 116 |
+
else:
|
| 117 |
+
diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit)
|
| 118 |
+
elif isinstance(a, list) and isinstance(b, list):
|
| 119 |
+
if len(a) != len(b):
|
| 120 |
+
out.append((path, f"len {len(a)}", f"len {len(b)}"))
|
| 121 |
+
else:
|
| 122 |
+
for i, (x, y) in enumerate(zip(a, b)):
|
| 123 |
+
diff_json(x, y, f"{path}[{i}]", tol, out, limit)
|
| 124 |
+
elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
|
| 125 |
+
if a != b:
|
| 126 |
+
out.append((path, a, b))
|
| 127 |
+
elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))):
|
| 128 |
+
out.append((path, a, b))
|
| 129 |
+
return out
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def error_event(o):
|
| 133 |
+
"""True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none."""
|
| 134 |
+
if not isinstance(o, dict):
|
| 135 |
+
return None
|
| 136 |
+
keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o]
|
| 137 |
+
if not keys:
|
| 138 |
+
return None
|
| 139 |
+
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)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# ====================================================================================================== logs -> notes
|
| 143 |
+
|
| 144 |
+
class RunLog:
|
| 145 |
+
"""Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's
|
| 146 |
+
narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition."""
|
| 147 |
+
|
| 148 |
+
def __init__(self, run_dir, manifest=None):
|
| 149 |
+
self.run_dir = os.path.abspath(run_dir.rstrip("/"))
|
| 150 |
+
self.run = os.path.basename(self.run_dir)
|
| 151 |
+
self.batch = os.path.basename(os.path.dirname(self.run_dir))
|
| 152 |
+
self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl"))
|
| 153 |
+
self.start = next(e for e in self.ev if e["ev"] == "session_start")
|
| 154 |
+
self.calls, self.dones, self.harness_status = {}, [], []
|
| 155 |
+
last = None
|
| 156 |
+
for e in self.ev:
|
| 157 |
+
if e["ev"] == "call":
|
| 158 |
+
self.calls[(int(e["attempt"]), int(e["step"]))] = e
|
| 159 |
+
last = e
|
| 160 |
+
elif e["ev"] == "done":
|
| 161 |
+
self.dones.append(e)
|
| 162 |
+
last = e
|
| 163 |
+
elif e["ev"] == "http" and last is not None and "think_s" not in last:
|
| 164 |
+
ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \
|
| 165 |
+
(last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe"))
|
| 166 |
+
if ok:
|
| 167 |
+
last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s")
|
| 168 |
+
self.manifest = manifest or {}
|
| 169 |
+
self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {}
|
| 170 |
+
p = os.path.join(self.run_dir, "harness.json")
|
| 171 |
+
self.harness = json.load(open(p)) if os.path.exists(p) else {}
|
| 172 |
+
self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl"))
|
| 173 |
+
self._narration()
|
| 174 |
+
|
| 175 |
+
# ---------------------------------------------------------------- agent narration
|
| 176 |
+
def _narration(self):
|
| 177 |
+
"""notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one;
|
| 178 |
+
finish_notes[attempt] likewise for the agent's finish call; final_report = its last message."""
|
| 179 |
+
self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", []
|
| 180 |
+
buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
|
| 181 |
+
attempt = 1
|
| 182 |
+
|
| 183 |
+
def take():
|
| 184 |
+
nonlocal buf
|
| 185 |
+
out = {k: v for k, v in buf.items() if v}
|
| 186 |
+
buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
|
| 187 |
+
return out
|
| 188 |
+
|
| 189 |
+
last_msg = ""
|
| 190 |
+
for t in self.traj:
|
| 191 |
+
if t.get("kind") == "header":
|
| 192 |
+
self.headers.append(t.get("agent") or {})
|
| 193 |
+
continue
|
| 194 |
+
if t.get("kind") != "step":
|
| 195 |
+
continue
|
| 196 |
+
if (t.get("message") or "").strip():
|
| 197 |
+
buf["messages"].append(t["message"].strip())
|
| 198 |
+
last_msg = t["message"].strip()
|
| 199 |
+
if (t.get("reasoning_content") or "").strip():
|
| 200 |
+
buf["reasoning"].append(t["reasoning_content"].strip())
|
| 201 |
+
res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])}
|
| 202 |
+
for c in t.get("tool_calls") or []:
|
| 203 |
+
fn, args = c.get("function_name"), c.get("arguments") or {}
|
| 204 |
+
if fn == "shell":
|
| 205 |
+
buf["shell"].append(str(args.get("command", ""))[:2000])
|
| 206 |
+
elif fn == "view_images":
|
| 207 |
+
buf["viewed"].extend(args.get("paths") or [])
|
| 208 |
+
elif fn == "robot":
|
| 209 |
+
cmd = str(args.get("command", "")).strip()
|
| 210 |
+
r = res.get(c.get("tool_call_id")) or {}
|
| 211 |
+
try:
|
| 212 |
+
rep = json.loads(r.get("content") or "{}")
|
| 213 |
+
except ValueError:
|
| 214 |
+
rep = {}
|
| 215 |
+
word = cmd.split()[0] if cmd else ""
|
| 216 |
+
m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", "")))
|
| 217 |
+
if word in ("move_eef", "observe") and m:
|
| 218 |
+
a, s = int(m.group(1)), int(m.group(2))
|
| 219 |
+
n = take()
|
| 220 |
+
n["command"] = cmd
|
| 221 |
+
self.notes[(a, s)] = n
|
| 222 |
+
attempt = a
|
| 223 |
+
elif word in ("finish", "done"):
|
| 224 |
+
n = take()
|
| 225 |
+
n["command"] = cmd
|
| 226 |
+
n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)}
|
| 227 |
+
self.finish_notes.setdefault(attempt, n)
|
| 228 |
+
if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"):
|
| 229 |
+
attempt += 1
|
| 230 |
+
# status / help / errors: their narration stays in the buffer for the next command
|
| 231 |
+
self.final_report = last_msg
|
| 232 |
+
|
| 233 |
+
# ---------------------------------------------------------------- run-level labels
|
| 234 |
+
def attempts(self):
|
| 235 |
+
out = []
|
| 236 |
+
for e in self.dones:
|
| 237 |
+
o = e.get("outcome") or {}
|
| 238 |
+
if isinstance(o, str):
|
| 239 |
+
try:
|
| 240 |
+
o = ast.literal_eval(o)
|
| 241 |
+
except (ValueError, SyntaxError):
|
| 242 |
+
o = {}
|
| 243 |
+
out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o,
|
| 244 |
+
reason=e.get("reason") or ""))
|
| 245 |
+
return sorted(out, key=lambda x: x["attempt"])
|
| 246 |
+
|
| 247 |
+
def condition(self):
|
| 248 |
+
s, en = self.start, self.entry
|
| 249 |
+
mem = s.get("memory", en.get("mem"))
|
| 250 |
+
chain = en.get("chain")
|
| 251 |
+
if mem == "full":
|
| 252 |
+
cond = "with_history"
|
| 253 |
+
elif chain:
|
| 254 |
+
cond = "memory_free_retry"
|
| 255 |
+
else:
|
| 256 |
+
cond = "independent_single_attempt"
|
| 257 |
+
return cond, chain
|
| 258 |
+
|
| 259 |
+
def outcome_class(self):
|
| 260 |
+
"""CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None."""
|
| 261 |
+
att = self.attempts()
|
| 262 |
+
if not att or self.start.get("memory") != "full":
|
| 263 |
+
return None, "".join("S" if a["success"] else "F" for a in att)
|
| 264 |
+
hist = "".join("S" if a["success"] else "F" for a in att)
|
| 265 |
+
if att[0]["success"]:
|
| 266 |
+
ev = error_event(att[0]["outcome"])
|
| 267 |
+
cls = "S?" if ev is None else ("IR" if ev else "CS")
|
| 268 |
+
else:
|
| 269 |
+
cls = "XR" if any(a["success"] for a in att) else "F"
|
| 270 |
+
return cls, hist
|
| 271 |
+
|
| 272 |
+
def agent_info(self):
|
| 273 |
+
h, en = self.harness, self.entry
|
| 274 |
+
hdr = self.headers[0] if self.headers else {}
|
| 275 |
+
return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"),
|
| 276 |
+
harness_version=h.get("version") or hdr.get("version"),
|
| 277 |
+
harness_binary_sha256=(h.get("binary") or {}).get("sha256"),
|
| 278 |
+
model=h.get("model") or en.get("model") or hdr.get("model_name"),
|
| 279 |
+
effort=h.get("effort") or en.get("effort") or hdr.get("effort"),
|
| 280 |
+
provider=h.get("provider") or en.get("provider"),
|
| 281 |
+
codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"),
|
| 282 |
+
jail=en.get("jail"))
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
# ====================================================================================================== recording
|
| 286 |
+
|
| 287 |
+
class EpisodeSink:
|
| 288 |
+
"""Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed."""
|
| 289 |
+
|
| 290 |
+
def __init__(self, path):
|
| 291 |
+
self.path = path
|
| 292 |
+
os.makedirs(path, exist_ok=True)
|
| 293 |
+
self.w = None
|
| 294 |
+
self.num = defaultdict(list)
|
| 295 |
+
self.n = 0
|
| 296 |
+
|
| 297 |
+
def add(self, st, imgs):
|
| 298 |
+
import imageio
|
| 299 |
+
if self.w is None:
|
| 300 |
+
self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb",
|
| 301 |
+
pixelformat="rgb24", macro_block_size=1,
|
| 302 |
+
ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error")
|
| 303 |
+
for k in ("agentview", "wrist")]
|
| 304 |
+
for w, im in zip(self.w, imgs):
|
| 305 |
+
w.append_data(im)
|
| 306 |
+
for k, v in st.items():
|
| 307 |
+
self.num[k].append(v)
|
| 308 |
+
self.n += 1
|
| 309 |
+
|
| 310 |
+
def close(self, final_state, final_imgs):
|
| 311 |
+
from PIL import Image
|
| 312 |
+
if self.w is not None:
|
| 313 |
+
for w in self.w:
|
| 314 |
+
w.close()
|
| 315 |
+
arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"}
|
| 316 |
+
np.savez(os.path.join(self.path, "frames.npz"), **arr)
|
| 317 |
+
if self.num.get("sim_state"):
|
| 318 |
+
np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64))
|
| 319 |
+
np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()})
|
| 320 |
+
for k, im in zip(("agentview", "wrist"), final_imgs):
|
| 321 |
+
Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png"))
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
class Recorder:
|
| 325 |
+
"""Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink."""
|
| 326 |
+
|
| 327 |
+
def __init__(self, rp, res):
|
| 328 |
+
self.rp, self.res = rp, int(res)
|
| 329 |
+
self.active = False
|
| 330 |
+
self.sink = None
|
| 331 |
+
self.cur = dict(attempt=1, command=-1, phase=PHASES["move"])
|
| 332 |
+
env = rp.task.env
|
| 333 |
+
self.env, self.rob = env, env.robots[0]
|
| 334 |
+
self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist"))
|
| 335 |
+
orig = env.step
|
| 336 |
+
|
| 337 |
+
def step(a):
|
| 338 |
+
if self.active and self.sink is not None:
|
| 339 |
+
self.capture(np.asarray(a, np.float64))
|
| 340 |
+
out = orig(a)
|
| 341 |
+
if self.active and self.sink is not None:
|
| 342 |
+
self.rp.poll_events(self.sink.n - 1)
|
| 343 |
+
return out
|
| 344 |
+
|
| 345 |
+
env.step = step
|
| 346 |
+
|
| 347 |
+
@property
|
| 348 |
+
def n(self):
|
| 349 |
+
return self.sink.n if self.sink is not None else 0
|
| 350 |
+
|
| 351 |
+
def state(self):
|
| 352 |
+
import robosuite.utils.transform_utils as T
|
| 353 |
+
env, rob = self.env, self.rob
|
| 354 |
+
d = env.sim.data
|
| 355 |
+
eef = np.array(d.site_xpos[rob.eef_site_id], np.float64)
|
| 356 |
+
q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw")
|
| 357 |
+
gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64)
|
| 358 |
+
try:
|
| 359 |
+
flat = np.asarray(env.sim.get_state().flatten(), np.float64)
|
| 360 |
+
except Exception:
|
| 361 |
+
flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64)
|
| 362 |
+
sk = self.rp.task.sk
|
| 363 |
+
return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64),
|
| 364 |
+
gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64),
|
| 365 |
+
joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64),
|
| 366 |
+
gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64),
|
| 367 |
+
eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)),
|
| 368 |
+
sim_time=np.float64(d.time), sim_state=flat)
|
| 369 |
+
|
| 370 |
+
def images(self):
|
| 371 |
+
return [envs.render(self.env, c, self.res) for c in self.cams]
|
| 372 |
+
|
| 373 |
+
def capture(self, a):
|
| 374 |
+
st = self.state()
|
| 375 |
+
st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]),
|
| 376 |
+
phase=np.int64(self.cur["phase"]))
|
| 377 |
+
self.sink.add(st, self.images())
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
class RunReplay:
|
| 381 |
+
def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None):
|
| 382 |
+
self.run_dir = os.path.abspath(run_dir.rstrip("/"))
|
| 383 |
+
self.run_name = os.path.basename(self.run_dir)
|
| 384 |
+
self.log = RunLog(self.run_dir, manifest)
|
| 385 |
+
self.ev = self.log.ev
|
| 386 |
+
self.start = self.log.start
|
| 387 |
+
cp = os.path.join(self.run_dir, "contract.json")
|
| 388 |
+
self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {}
|
| 389 |
+
spec = self.contract.get("image_spec") or {}
|
| 390 |
+
self.image_res = int(spec.get("width", 512))
|
| 391 |
+
self.code_diff = check_code(self.run_dir)
|
| 392 |
+
s = self.start
|
| 393 |
+
self.task = TASKS[s["task"]](cam_res=self.image_res)
|
| 394 |
+
inst = self.task.sample_instance(s["seed"])
|
| 395 |
+
logged = s.get("inst") or {}
|
| 396 |
+
sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")})
|
| 397 |
+
self.inst_diff = diff_json(sampled, logged, "inst")
|
| 398 |
+
if s.get("arm", "none") not in (None, "none") or logged.get("nominal"):
|
| 399 |
+
inst.update(logged) # controlled arms / nominal: the server overrode these instance fields
|
| 400 |
+
self.inst_diff = []
|
| 401 |
+
self.inst = inst
|
| 402 |
+
self.protocol = getattr(self.task, "protocol", "cross")
|
| 403 |
+
self.k = int(s.get("k") or self.task.max_attempts)
|
| 404 |
+
self.attempt = 1
|
| 405 |
+
self.mismatch = [] # (where, what, logged, replayed)
|
| 406 |
+
self.n_checked = 0
|
| 407 |
+
self.max_dev_m = 0.0
|
| 408 |
+
self.unfinished = None
|
| 409 |
+
self.rec = Recorder(self, res) if record else None
|
| 410 |
+
self.res = int(res)
|
| 411 |
+
self.out_root = out_root
|
| 412 |
+
self.n_mon = 0
|
| 413 |
+
self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0
|
| 414 |
+
self.episodes = [] # summaries of the written episodes
|
| 415 |
+
self.task.reset_instance(self.inst)
|
| 416 |
+
self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
|
| 417 |
+
sim = self.task.env.sim
|
| 418 |
+
bid = sim.model.body_name2id("robot0_base")
|
| 419 |
+
self.base_off = np.array(sim.data.body_xpos[bid], float).copy()
|
| 420 |
+
if self.rec:
|
| 421 |
+
self._open_episode()
|
| 422 |
+
|
| 423 |
+
# ------------------------------------------------------------------ episodes
|
| 424 |
+
def _ep_dir(self):
|
| 425 |
+
return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}")
|
| 426 |
+
|
| 427 |
+
def _open_episode(self):
|
| 428 |
+
self.rec.sink = EpisodeSink(self._ep_dir())
|
| 429 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
|
| 430 |
+
self.rec.active = True
|
| 431 |
+
self.events, self.spans, self.ep_attempts = [], [], []
|
| 432 |
+
self.ep_initial = self.rec.state() # state right after the reset (before frame 0)
|
| 433 |
+
|
| 434 |
+
def close_episode(self):
|
| 435 |
+
if not self.rec:
|
| 436 |
+
self.ep_attempts = []
|
| 437 |
+
return
|
| 438 |
+
sink = self.rec.sink
|
| 439 |
+
st = self.rec.state()
|
| 440 |
+
imgs = self.rec.images()
|
| 441 |
+
st.pop("sim_state", None)
|
| 442 |
+
sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs)
|
| 443 |
+
ann = build_annotation(self, sink)
|
| 444 |
+
with open(os.path.join(sink.path, "annotation.json"), "w") as f:
|
| 445 |
+
json.dump(ann, f, indent=1, default=_json_default)
|
| 446 |
+
self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n,
|
| 447 |
+
attempts=[a["attempt"] for a in self.ep_attempts]))
|
| 448 |
+
self.rec.active = False
|
| 449 |
+
self.rec.sink = None
|
| 450 |
+
self.ep_index += 1
|
| 451 |
+
|
| 452 |
+
# ------------------------------------------------------------------ monitor events (task-side error events)
|
| 453 |
+
def poll_events(self, frame):
|
| 454 |
+
mon = getattr(self.task, "mon", None)
|
| 455 |
+
evs = mon.get("events") if isinstance(mon, dict) else None
|
| 456 |
+
if not isinstance(evs, list):
|
| 457 |
+
return
|
| 458 |
+
if len(evs) < self.n_mon: # monitor was rebuilt
|
| 459 |
+
self.n_mon = 0
|
| 460 |
+
for e in evs[self.n_mon:]:
|
| 461 |
+
self.events.append(dict(frame=int(frame), attempt=self.attempt,
|
| 462 |
+
event=norm_json(e) if isinstance(e, dict) else str(e)))
|
| 463 |
+
self.n_mon = len(evs)
|
| 464 |
+
|
| 465 |
+
# ------------------------------------------------------------------ state as the server reports it
|
| 466 |
+
def proprio_la(self):
|
| 467 |
+
p = self.ex.proprio()
|
| 468 |
+
pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off]
|
| 469 |
+
return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"])
|
| 470 |
+
|
| 471 |
+
def compare(self, where, rep_logged, rep):
|
| 472 |
+
self.n_checked += 1
|
| 473 |
+
for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"):
|
| 474 |
+
if k not in rep_logged or k not in rep:
|
| 475 |
+
continue
|
| 476 |
+
a, b = rep_logged[k], rep[k]
|
| 477 |
+
if k == "eef_pos":
|
| 478 |
+
dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float))))
|
| 479 |
+
self.max_dev_m = max(self.max_dev_m, dev)
|
| 480 |
+
if dev > 1.5e-4:
|
| 481 |
+
self.mismatch.append((where, k, a, b))
|
| 482 |
+
elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4):
|
| 483 |
+
self.mismatch.append((where, k, a, b))
|
| 484 |
+
if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)):
|
| 485 |
+
self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok")))
|
| 486 |
+
|
| 487 |
+
def _span(self, e, f0, kind):
|
| 488 |
+
if self.rec:
|
| 489 |
+
self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0,
|
| 490 |
+
frame_end=self.rec.n))
|
| 491 |
+
|
| 492 |
+
# ------------------------------------------------------------------ commands (robot_server._handle_v2)
|
| 493 |
+
def move_eef(self, e):
|
| 494 |
+
args = e.get("args") or {}
|
| 495 |
+
where = f"a{e['attempt']}s{e['step']}"
|
| 496 |
+
logged = e.get("report") or {}
|
| 497 |
+
f0 = self.rec.n if self.rec else 0
|
| 498 |
+
p = self.ex.proprio()
|
| 499 |
+
if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}:
|
| 500 |
+
self._span(e, f0, "error")
|
| 501 |
+
return self.compare(where, logged, dict(ok=False))
|
| 502 |
+
off = self.base_off
|
| 503 |
+
try:
|
| 504 |
+
cur = np.asarray(p["eef_pos"], float) - off
|
| 505 |
+
tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
|
| 506 |
+
yaw = float(args.get("yaw", p["eef_yaw_deg"]))
|
| 507 |
+
speed = None if args.get("speed") in (None, "") else float(args["speed"])
|
| 508 |
+
except (TypeError, ValueError):
|
| 509 |
+
self._span(e, f0, "error")
|
| 510 |
+
return self.compare(where, logged, dict(ok=False))
|
| 511 |
+
grip = args.get("gripper")
|
| 512 |
+
if grip not in (None, "open", "close"):
|
| 513 |
+
self._span(e, f0, "error")
|
| 514 |
+
return self.compare(where, logged, dict(ok=False))
|
| 515 |
+
moving = any(k in args for k in ("x", "y", "z", "yaw"))
|
| 516 |
+
tgt_w = np.asarray(tgt) + off
|
| 517 |
+
if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)):
|
| 518 |
+
self._span(e, f0, "rejected")
|
| 519 |
+
return self.compare(where, logged, dict(ok=False, **self.proprio_la()))
|
| 520 |
+
raw = {}
|
| 521 |
+
if self.rec:
|
| 522 |
+
self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"])
|
| 523 |
+
if moving:
|
| 524 |
+
mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw)
|
| 525 |
+
if speed is not None:
|
| 526 |
+
mv["speed"] = speed
|
| 527 |
+
raw.update(self.ex.call("move_to", mv).report)
|
| 528 |
+
if grip is not None:
|
| 529 |
+
if self.rec:
|
| 530 |
+
self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"])
|
| 531 |
+
raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report)
|
| 532 |
+
rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la())
|
| 533 |
+
self.compare(where, logged, rep)
|
| 534 |
+
lr = e.get("raw") or {}
|
| 535 |
+
for k in ("holding_object", "touched_object"):
|
| 536 |
+
if k in lr and k in raw and bool(lr[k]) != bool(raw[k]):
|
| 537 |
+
self.mismatch.append((where, "raw." + k, lr[k], raw[k]))
|
| 538 |
+
self._span(e, f0, "move_eef")
|
| 539 |
+
|
| 540 |
+
def observe(self, e):
|
| 541 |
+
f0 = self.rec.n if self.rec else 0
|
| 542 |
+
self._span(e, f0, "observe")
|
| 543 |
+
|
| 544 |
+
def done(self, e):
|
| 545 |
+
f0 = self.rec.n if self.rec else 0
|
| 546 |
+
if self.rec:
|
| 547 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"])
|
| 548 |
+
out = self.task.outcome(self.inst)
|
| 549 |
+
succ = bool(out["success"])
|
| 550 |
+
where = f"a{e['attempt']}done"
|
| 551 |
+
if succ != bool(e.get("success") in (True, "True")):
|
| 552 |
+
self.mismatch.append((where, "success", e.get("success"), succ))
|
| 553 |
+
lo = e.get("outcome") or {}
|
| 554 |
+
ro = norm_json({k: v for k, v in out.items() if k != "feedback"})
|
| 555 |
+
if isinstance(lo, dict):
|
| 556 |
+
for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8):
|
| 557 |
+
self.mismatch.append((where,) + d)
|
| 558 |
+
info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""),
|
| 559 |
+
feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")),
|
| 560 |
+
think_s=e.get("think_s"))
|
| 561 |
+
try:
|
| 562 |
+
info["feedback_f2"] = self.task.feedback(self.inst, out, "F2")
|
| 563 |
+
except Exception as ex_:
|
| 564 |
+
info["feedback_f2"] = f"<unavailable: {type(ex_).__name__}>"
|
| 565 |
+
if self.rec:
|
| 566 |
+
info["judge_frames"] = [f0, self.rec.n]
|
| 567 |
+
self.ep_attempts.append(info)
|
| 568 |
+
last = self.attempt >= self.k or succ or bool(out.get("terminal"))
|
| 569 |
+
if self.protocol == "cross" or last:
|
| 570 |
+
self.close_episode()
|
| 571 |
+
if last:
|
| 572 |
+
return True
|
| 573 |
+
self.attempt += 1
|
| 574 |
+
if self.protocol == "cross":
|
| 575 |
+
self.task.reset_instance(self.inst)
|
| 576 |
+
self.n_mon = 0
|
| 577 |
+
if self.rec:
|
| 578 |
+
self._open_episode()
|
| 579 |
+
elif self.rec:
|
| 580 |
+
self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
|
| 581 |
+
self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
|
| 582 |
+
return False
|
| 583 |
+
|
| 584 |
+
def run(self):
|
| 585 |
+
t0 = time.time()
|
| 586 |
+
finished = False
|
| 587 |
+
for e in self.ev:
|
| 588 |
+
if e["ev"] == "call":
|
| 589 |
+
if e.get("cmd") == "move_eef":
|
| 590 |
+
self.move_eef(e)
|
| 591 |
+
elif e.get("cmd") == "observe":
|
| 592 |
+
self.observe(e)
|
| 593 |
+
else:
|
| 594 |
+
self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None))
|
| 595 |
+
elif e["ev"] == "done":
|
| 596 |
+
finished = self.done(e)
|
| 597 |
+
if finished:
|
| 598 |
+
break
|
| 599 |
+
self.unfinished = not finished
|
| 600 |
+
if not finished and self.rec and self.rec.sink is not None:
|
| 601 |
+
# the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged
|
| 602 |
+
if self.rec.n or self.ep_attempts:
|
| 603 |
+
self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True,
|
| 604 |
+
finish_reason="", feedback_shown="", auto_ended=False))
|
| 605 |
+
self.close_episode()
|
| 606 |
+
else:
|
| 607 |
+
shutil.rmtree(self.rec.sink.path, ignore_errors=True)
|
| 608 |
+
self.rec.sink = None
|
| 609 |
+
self.wall_s = time.time() - t0
|
| 610 |
+
return self
|
| 611 |
+
|
| 612 |
+
def summary(self):
|
| 613 |
+
return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"],
|
| 614 |
+
protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff),
|
| 615 |
+
n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6),
|
| 616 |
+
unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1),
|
| 617 |
+
first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]])
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
# ====================================================================================================== annotation
|
| 621 |
+
|
| 622 |
+
def task_info(task, inst):
|
| 623 |
+
cls = type(task)
|
| 624 |
+
return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable",
|
| 625 |
+
category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"),
|
| 626 |
+
max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)),
|
| 627 |
+
instruction=cls.instruction)
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
def build_annotation(rp, sink):
|
| 631 |
+
"""Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2
|
| 632 |
+
failure description), run-level outcome class, every robot command with its frame span and the agent's narration,
|
| 633 |
+
task-side error events with frame indices."""
|
| 634 |
+
log = rp.log
|
| 635 |
+
s = rp.start
|
| 636 |
+
cond, chain = log.condition()
|
| 637 |
+
cls, hist = log.outcome_class()
|
| 638 |
+
att_all = log.attempts()
|
| 639 |
+
attempts = []
|
| 640 |
+
for a in rp.ep_attempts:
|
| 641 |
+
a = dict(a)
|
| 642 |
+
n = a["attempt"]
|
| 643 |
+
later = [x for x in att_all if x["attempt"] > n]
|
| 644 |
+
a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later))
|
| 645 |
+
a["is_last_attempt_of_run"] = not later
|
| 646 |
+
fn = log.finish_notes.get(n)
|
| 647 |
+
if fn:
|
| 648 |
+
a["agent_finish"] = fn
|
| 649 |
+
a["error_event_in_attempt"] = error_event(a.get("outcome"))
|
| 650 |
+
attempts.append(a)
|
| 651 |
+
# post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command)
|
| 652 |
+
for a in attempts:
|
| 653 |
+
nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1])
|
| 654 |
+
if a.get("success") is False and nxt:
|
| 655 |
+
note = log.notes[nxt[0]]
|
| 656 |
+
a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note}
|
| 657 |
+
commands = []
|
| 658 |
+
for sp in rp.spans:
|
| 659 |
+
e = log.calls.get((sp["attempt"], sp["step"])) or {}
|
| 660 |
+
rep = e.get("report") or {}
|
| 661 |
+
c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"],
|
| 662 |
+
frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]),
|
| 663 |
+
args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"),
|
| 664 |
+
stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"),
|
| 665 |
+
gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"),
|
| 666 |
+
touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"),
|
| 667 |
+
agent_obs_images=rep.get("images"))
|
| 668 |
+
note = log.notes.get((sp["attempt"], sp["step"]))
|
| 669 |
+
if note:
|
| 670 |
+
c["agent_note"] = {k: v for k, v in note.items() if k != "command"}
|
| 671 |
+
commands.append(c)
|
| 672 |
+
t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x]
|
| 673 |
+
return dict(
|
| 674 |
+
schema=SCHEMA,
|
| 675 |
+
source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts],
|
| 676 |
+
episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain,
|
| 677 |
+
memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None),
|
| 678 |
+
feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"),
|
| 679 |
+
k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"),
|
| 680 |
+
contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256")
|
| 681 |
+
if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)),
|
| 682 |
+
agent=log.agent_info(),
|
| 683 |
+
task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"),
|
| 684 |
+
instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}),
|
| 685 |
+
run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all),
|
| 686 |
+
run_success=any(x["success"] for x in att_all) if att_all else None,
|
| 687 |
+
agent_final_report=log.final_report[:6000] or None,
|
| 688 |
+
mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)),
|
| 689 |
+
attempts=attempts,
|
| 690 |
+
commands=commands,
|
| 691 |
+
task_events=rp.events,
|
| 692 |
+
frames=dict(n=sink.n, fps=FPS, image_res=rp.res,
|
| 693 |
+
phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"],
|
| 694 |
+
joint_pos=rp.ep_initial["joint_pos"],
|
| 695 |
+
gripper_qpos=rp.ep_initial["gripper_qpos"])),
|
| 696 |
+
)
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
# ====================================================================================================== CLI
|
| 700 |
+
|
| 701 |
+
def load_manifest(run_dir):
|
| 702 |
+
p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json")
|
| 703 |
+
return json.load(open(p)) if os.path.exists(p) else {}
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
def main():
|
| 707 |
+
ap = argparse.ArgumentParser()
|
| 708 |
+
ap.add_argument("mode", choices=["check", "record"])
|
| 709 |
+
ap.add_argument("runs", nargs="+")
|
| 710 |
+
ap.add_argument("--json", default="")
|
| 711 |
+
ap.add_argument("--out", default="")
|
| 712 |
+
ap.add_argument("--res", type=int, default=256)
|
| 713 |
+
ap.add_argument("--force", action="store_true", help="record again even if replay.json exists")
|
| 714 |
+
a = ap.parse_args()
|
| 715 |
+
rows = []
|
| 716 |
+
for r in a.runs:
|
| 717 |
+
r = r.rstrip("/")
|
| 718 |
+
try:
|
| 719 |
+
if a.mode == "check":
|
| 720 |
+
s = RunReplay(r, manifest=load_manifest(r)).run().summary()
|
| 721 |
+
else:
|
| 722 |
+
batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r)
|
| 723 |
+
rd = os.path.join(a.out, batch, name)
|
| 724 |
+
if os.path.exists(os.path.join(rd, "replay.json")) and not a.force:
|
| 725 |
+
print(json.dumps(dict(run=name, skipped="exists")), flush=True)
|
| 726 |
+
continue
|
| 727 |
+
shutil.rmtree(rd, ignore_errors=True)
|
| 728 |
+
rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run()
|
| 729 |
+
s = rp.summary()
|
| 730 |
+
s["episodes"] = rp.episodes
|
| 731 |
+
with open(os.path.join(rd, "replay.json"), "w") as f:
|
| 732 |
+
json.dump(s, f, indent=1)
|
| 733 |
+
except Exception:
|
| 734 |
+
import traceback
|
| 735 |
+
s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:])
|
| 736 |
+
rows.append(s)
|
| 737 |
+
print(json.dumps(s), flush=True)
|
| 738 |
+
if a.json:
|
| 739 |
+
with open(a.json, "w") as f:
|
| 740 |
+
json.dump(rows, f, indent=1)
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
if __name__ == "__main__":
|
| 744 |
+
main()
|