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/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/batches.json +9 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/objects.py +98 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/task_base.py +129 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/agent_cost.py +77 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/usage_stats.py +178 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/harnesses/codex_catalogs/generic_0.163.0.json +64 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/harnesses/codex_catalogs/native_0.163.0.json +0 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-fable-5-1_high.json +15 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/agent_viewer/viewer.html +111 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/agent/README.md +297 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/agent/audit_state.py +79 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/agent/harness.py +300 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/agent/metrics.py +97 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/agent/runlog.py +62 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/codex_catalogs/native_0.163.0.json +0 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/embodied_evo.py +135 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-fable-5-1_high.json +15 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6-astra_medium.json +23 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/codex_0.156.0_78a11f06e0a2dda4_gpt-6-astra_high.json +36 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/objects.py +98 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/real/DRIVER.md +144 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/real/protocol.py +364 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/real/tasks.py +123 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l1_bias.py +390 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l1_height.py +448 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l3_tool.py +549 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l3_wide.py +435 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l6_swap.py +466 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l7_key_turn.py +461 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/lh_order_dispatch.py +242 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/lh_wobbly_table.py +1177 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/agent_compare.py +40 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/agent_cost.py +77 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/cs_ir_report.py +87 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/ladder_plan.py +120 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/lerobot_replay.py +744 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/lerobot_sft_dataset.py +473 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/start_robot_session.sh +24 -0
- leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-fable-5-1_high.json +15 -0
- leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json +15 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/client/pyproject.toml +13 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/real/DRIVER.md +144 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/real/__init__.py +10 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/real/driver_template.py +196 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/real/protocol.py +364 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/real/tasks.py +123 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/tasks/l2_turntable.py +469 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/tasks/l3_card_shelf.py +587 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/scripts/cs_ir_report.py +87 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/scripts/l6_controls.py +92 -0
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/batches.json
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"breakfast_v2_20261103_opus": {
|
| 3 |
+
"source_manifest": "/mnt/cpfs/workspace/agentic-robotics/ops/breakfast_v2_eval_20261103/source/runs/api/breakfast_v2_20261103_opus/manifest.json",
|
| 4 |
+
"supplement": true,
|
| 5 |
+
"selected_runs": 9,
|
| 6 |
+
"exported_runs": 9,
|
| 7 |
+
"note": "Original condition and feedback dossier are in each episode annotation source.evaluation_config."
|
| 8 |
+
}
|
| 9 |
+
}
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/objects.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Procedurally generated objects for LFF-Bench, registered into LIBERO's object registry.
|
| 2 |
+
|
| 3 |
+
Each generated object is an MJCF file with the layout robosuite's MujocoXMLObject expects
|
| 4 |
+
(an outer body containing body "object" plus bottom/top/horizontal_radius sites).
|
| 5 |
+
"""
|
| 6 |
+
import os
|
| 7 |
+
import re
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
from robosuite.models.objects import MujocoXMLObject
|
| 11 |
+
|
| 12 |
+
from libero.libero.envs.base_object import OBJECTS_DICT, register_object
|
| 13 |
+
|
| 14 |
+
GEN_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "assets_gen")
|
| 15 |
+
os.makedirs(GEN_DIR, exist_ok=True)
|
| 16 |
+
|
| 17 |
+
_SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"'
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _fmt(v):
|
| 21 |
+
return " ".join(f"{x:.5f}" for x in v)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _wrap(model_name, geoms_xml, half_height, radius):
|
| 25 |
+
return f"""<mujoco model="{model_name}">
|
| 26 |
+
<worldbody>
|
| 27 |
+
<body>
|
| 28 |
+
<body name="object">
|
| 29 |
+
{geoms_xml}
|
| 30 |
+
</body>
|
| 31 |
+
<site rgba="0 0 0 0" size="0.005" pos="0 0 {-half_height:.5f}" name="bottom_site" />
|
| 32 |
+
<site rgba="0 0 0 0" size="0.005" pos="0 0 {half_height:.5f}" name="top_site" />
|
| 33 |
+
<site rgba="0 0 0 0" size="0.005" pos="{radius:.5f} {radius:.5f} 0" name="horizontal_radius_site" />
|
| 34 |
+
</body>
|
| 35 |
+
</worldbody>
|
| 36 |
+
</mujoco>
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def box_xml(model_name, half, rgba, density=500.0, friction=(1.0, 0.005, 0.0001)):
|
| 41 |
+
"""Solid box; one geom used for both collision and rendering."""
|
| 42 |
+
g = (f' <geom name="{model_name}_g0" type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" '
|
| 43 |
+
f'density="{density}" friction="{_fmt(friction)}" {_SOLID} group="0" />\n'
|
| 44 |
+
f' <geom type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" conaffinity="0" contype="0" group="1" />')
|
| 45 |
+
return _wrap(model_name, g, half[2], float(np.hypot(half[0], half[1])))
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def bin_xml(model_name, inner_half_xy, wall_h, wall_t=0.006, floor_t=0.006, rgba=(0.6, 0.6, 0.65, 1.0),
|
| 49 |
+
density=800.0):
|
| 50 |
+
"""Open-top box. Origin at the center of the outer footprint, z=0 at mid height."""
|
| 51 |
+
ix, iy = inner_half_xy
|
| 52 |
+
H = (wall_h + floor_t) / 2.0
|
| 53 |
+
geoms = []
|
| 54 |
+
parts = [
|
| 55 |
+
((0, 0, -H + floor_t / 2), (ix + wall_t, iy + wall_t, floor_t / 2)), # floor
|
| 56 |
+
((ix + wall_t / 2, 0, floor_t / 2), (wall_t / 2, iy + wall_t, wall_h / 2)), # +x wall
|
| 57 |
+
((-ix - wall_t / 2, 0, floor_t / 2), (wall_t / 2, iy + wall_t, wall_h / 2)), # -x wall
|
| 58 |
+
((0, iy + wall_t / 2, floor_t / 2), (ix, wall_t / 2, wall_h / 2)), # +y wall
|
| 59 |
+
((0, -iy - wall_t / 2, floor_t / 2), (ix, wall_t / 2, wall_h / 2)), # -y wall
|
| 60 |
+
]
|
| 61 |
+
for k, (p, s) in enumerate(parts):
|
| 62 |
+
geoms.append(f' <geom name="{model_name}_g{k}" type="box" pos="{_fmt(p)}" size="{_fmt(s)}" '
|
| 63 |
+
f'rgba="{_fmt(rgba)}" density="{density}" friction="1.0 0.005 0.0001" {_SOLID} group="0" />')
|
| 64 |
+
geoms.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(rgba)}" '
|
| 65 |
+
f'conaffinity="0" contype="0" group="1" />')
|
| 66 |
+
return _wrap(model_name, "\n".join(geoms), H, float(np.hypot(ix + wall_t, iy + wall_t)))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _key(class_name):
|
| 70 |
+
return "_".join(re.sub(r"([A-Z0-9])", r" \1", class_name).split()).lower()
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def register_generated(class_name, xml_text, free=True):
|
| 74 |
+
"""Write the MJCF and register a LIBERO object class. Returns the BDDL category name."""
|
| 75 |
+
key = _key(class_name)
|
| 76 |
+
path = os.path.join(GEN_DIR, f"{key}.xml")
|
| 77 |
+
# write to a private temp file and rename atomically: several servers / validators may build the same task at
|
| 78 |
+
# once, and a reader must never see a half-written file (seen 2026-10-09 by the lh_* builders)
|
| 79 |
+
tmp = f"{path}.{os.getpid()}.tmp"
|
| 80 |
+
with open(tmp, "w") as f:
|
| 81 |
+
f.write(xml_text)
|
| 82 |
+
os.replace(tmp, path)
|
| 83 |
+
if key in OBJECTS_DICT:
|
| 84 |
+
return key
|
| 85 |
+
|
| 86 |
+
default_joints = [dict(type="free", damping="0.0005")] if free else None
|
| 87 |
+
|
| 88 |
+
def __init__(self, name=key, joints="default"):
|
| 89 |
+
j = default_joints if joints == "default" else joints
|
| 90 |
+
MujocoXMLObject.__init__(self, path, name=name, joints=j, obj_type="all", duplicate_collision_geoms=False)
|
| 91 |
+
self.category_name = key
|
| 92 |
+
self.rotation = (0.0, 0.0)
|
| 93 |
+
self.rotation_axis = "z"
|
| 94 |
+
self.object_properties = {"vis_site_names": {}}
|
| 95 |
+
|
| 96 |
+
cls = type(class_name, (MujocoXMLObject,), {"__init__": __init__})
|
| 97 |
+
register_object(cls)
|
| 98 |
+
return key
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/task_base.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Task interface shared by all LFF-Bench tasks.
|
| 2 |
+
|
| 3 |
+
A task = a LIBERO scene + an instance sampler (layout and hidden variables) + a success / outcome
|
| 4 |
+
measurement + scripted reference policies used to validate that the task really requires learning
|
| 5 |
+
from failure:
|
| 6 |
+
|
| 7 |
+
oracle knows the hidden variables; should succeed on attempt 1
|
| 8 |
+
naive acts on the prior (what an agent would do without the failure information)
|
| 9 |
+
adaptive scripted learner that updates its parameters from structured (F2) feedback
|
| 10 |
+
blind repeats the naive behaviour with small random variation, no history
|
| 11 |
+
|
| 12 |
+
Tasks whose policies can be expressed as "execute(params)" get the cross-attempt protocol for free.
|
| 13 |
+
Tasks that need within-episode recovery override `run_scripted`.
|
| 14 |
+
"""
|
| 15 |
+
import numpy as np
|
| 16 |
+
|
| 17 |
+
from . import envs
|
| 18 |
+
from .skills import Skills
|
| 19 |
+
|
| 20 |
+
TASKS = {}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def register_task(cls):
|
| 24 |
+
TASKS[cls.name] = cls
|
| 25 |
+
return cls
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class LFFTask:
|
| 29 |
+
name = "base"
|
| 30 |
+
level = "L?"
|
| 31 |
+
# the user's 7 categories (2026-10-06): hidden information -> required capability -> adapted action
|
| 32 |
+
category = "" # system_identification | dynamics_adaptation | failed_interaction_inference |
|
| 33 |
+
# state_restoration | procedural_memory | strategy_switching | geometry_inference
|
| 34 |
+
capabilities = ()
|
| 35 |
+
max_attempts = 5
|
| 36 |
+
protocol = "cross" # "cross": reset between attempts; "within": one episode, recover in place
|
| 37 |
+
instruction = "" # direct reference
|
| 38 |
+
instruction_indirect = "" # descriptive reference (perception / semantic reasoning variant)
|
| 39 |
+
cam_res = 256
|
| 40 |
+
|
| 41 |
+
def __init__(self, cam_res=None):
|
| 42 |
+
if cam_res:
|
| 43 |
+
self.cam_res = cam_res
|
| 44 |
+
self.bddl_path = self.make_bddl()
|
| 45 |
+
self.env = envs.make_env(self.bddl_path, cam_res=self.cam_res)
|
| 46 |
+
self.env.reset()
|
| 47 |
+
self.sk = None
|
| 48 |
+
|
| 49 |
+
# ------------------------------------------------------------ to implement
|
| 50 |
+
def make_bddl(self):
|
| 51 |
+
raise NotImplementedError
|
| 52 |
+
|
| 53 |
+
def sample_instance(self, seed):
|
| 54 |
+
"""Return a JSON-serialisable dict with layout + hidden variables."""
|
| 55 |
+
raise NotImplementedError
|
| 56 |
+
|
| 57 |
+
def apply_instance(self, inst):
|
| 58 |
+
"""Place objects / set hidden physics after env.reset()."""
|
| 59 |
+
raise NotImplementedError
|
| 60 |
+
|
| 61 |
+
def outcome(self, inst):
|
| 62 |
+
"""dict with at least {'success': bool}; may contain structured measurements."""
|
| 63 |
+
raise NotImplementedError
|
| 64 |
+
|
| 65 |
+
def feedback(self, inst, out, level="F2"):
|
| 66 |
+
"""Text the agent receives after an attempt. F0: nothing, F1: success flag, F2: measurement."""
|
| 67 |
+
if level == "F0":
|
| 68 |
+
return ""
|
| 69 |
+
s = "Attempt succeeded." if out["success"] else "Attempt failed."
|
| 70 |
+
if level == "F1":
|
| 71 |
+
return s
|
| 72 |
+
return s + (" " + out["detail"] if out.get("detail") else "")
|
| 73 |
+
|
| 74 |
+
def skill_bias(self, inst):
|
| 75 |
+
return None
|
| 76 |
+
|
| 77 |
+
# scripted references (cross protocol) ----------------------------------
|
| 78 |
+
def default_params(self, inst):
|
| 79 |
+
raise NotImplementedError
|
| 80 |
+
|
| 81 |
+
def oracle_params(self, inst):
|
| 82 |
+
raise NotImplementedError
|
| 83 |
+
|
| 84 |
+
def adapt_params(self, inst, history):
|
| 85 |
+
raise NotImplementedError
|
| 86 |
+
|
| 87 |
+
def blind_params(self, inst, attempt, rng):
|
| 88 |
+
return self.default_params(inst)
|
| 89 |
+
|
| 90 |
+
def execute(self, inst, params):
|
| 91 |
+
raise NotImplementedError
|
| 92 |
+
|
| 93 |
+
# ------------------------------------------------------------ shared
|
| 94 |
+
def reset_instance(self, inst, recorder=None):
|
| 95 |
+
self.env.reset()
|
| 96 |
+
self.apply_instance(inst)
|
| 97 |
+
self.env.sim.forward()
|
| 98 |
+
envs.settle(self.env, 10)
|
| 99 |
+
self.sk = Skills(self.env, bias=self.skill_bias(inst), recorder=recorder)
|
| 100 |
+
return self.sk
|
| 101 |
+
|
| 102 |
+
def snapshot(self, cam="agentview", res=None):
|
| 103 |
+
return envs.render(self.env, cam, res or self.cam_res)
|
| 104 |
+
|
| 105 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 106 |
+
"""Cross-attempt protocol with a scripted policy. Returns the per-attempt history."""
|
| 107 |
+
k = k or self.max_attempts
|
| 108 |
+
rng = np.random.default_rng(seed)
|
| 109 |
+
history = []
|
| 110 |
+
for a in range(k):
|
| 111 |
+
self.reset_instance(inst)
|
| 112 |
+
if kind == "oracle":
|
| 113 |
+
params = self.oracle_params(inst)
|
| 114 |
+
elif kind == "naive":
|
| 115 |
+
params = self.default_params(inst)
|
| 116 |
+
elif kind == "adaptive":
|
| 117 |
+
params = self.default_params(inst) if a == 0 else self.adapt_params(inst, history)
|
| 118 |
+
elif kind == "blind":
|
| 119 |
+
params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
|
| 120 |
+
else:
|
| 121 |
+
raise ValueError(kind)
|
| 122 |
+
self.execute(inst, params)
|
| 123 |
+
out = self.outcome(inst)
|
| 124 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 125 |
+
if on_attempt:
|
| 126 |
+
on_attempt(a, params, out)
|
| 127 |
+
if out["success"] or kind in ("oracle", "naive"):
|
| 128 |
+
break
|
| 129 |
+
return history
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/agent_cost.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Project GPT-6 cost / latency of a protocol from a run directory.
|
| 2 |
+
|
| 3 |
+
Works on (a) a real OpenAI run (uses the logged usage and latencies) or (b) a dry run of another backend made
|
| 4 |
+
with --dry-run-payload (uses the logged request sizes of every call). For (b) all numbers are ESTIMATES:
|
| 5 |
+
input tokens per call = text_chars / 4 + n_images * 256 (512 px images; image accounting is an assumption)
|
| 6 |
+
cached tokens per call = input tokens of the previous call in the same attempt (append-only prefix) --
|
| 7 |
+
the first call of an attempt is counted as uncached (conservative)
|
| 8 |
+
output tokens per call = --out-tokens (reasoning + visible; unknown for GPT-6 Astra, default 1500)
|
| 9 |
+
latency per call = --latency (seconds; RoboICL measured ~30-50 s per GPT-6 Astra call at 50-90K input
|
| 10 |
+
tokens and high/xhigh effort -- treat as an upper-range planning number)
|
| 11 |
+
The number of model calls of a scripted run is a LOWER bound for an LLM agent (no perception / checking calls).
|
| 12 |
+
|
| 13 |
+
python scripts/agent_cost.py runs/agent/l5_slide_to_target/<run> --out-tokens 1500 --latency 20 --calls-scale 2
|
| 14 |
+
"""
|
| 15 |
+
import argparse
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
import sys
|
| 19 |
+
from collections import defaultdict
|
| 20 |
+
|
| 21 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 22 |
+
|
| 23 |
+
from lffbench.agent.cost import PRICES, call_cost # noqa: E402
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def main():
|
| 27 |
+
ap = argparse.ArgumentParser()
|
| 28 |
+
ap.add_argument("run_dir")
|
| 29 |
+
ap.add_argument("--model", default="gpt-6-astra")
|
| 30 |
+
ap.add_argument("--out-tokens", type=float, default=1500)
|
| 31 |
+
ap.add_argument("--latency", type=float, default=20.0)
|
| 32 |
+
ap.add_argument("--calls-scale", type=float, default=1.0, help="multiply the call count (LLM vs scripted)")
|
| 33 |
+
a = ap.parse_args()
|
| 34 |
+
ev = [json.loads(l) for l in open(os.path.join(a.run_dir, "events.jsonl"))]
|
| 35 |
+
calls = [e for e in ev if e["type"] == "llm_call"]
|
| 36 |
+
runs = {e["seed"] for e in ev if e["type"] == "run_start"}
|
| 37 |
+
real = [c for c in calls if c.get("usage")]
|
| 38 |
+
if real and not any("dry_run_request" in c for c in calls):
|
| 39 |
+
cost = sum(call_cost(c["usage"], a.model) or 0 for c in real)
|
| 40 |
+
lat = [c["latency_s"] for c in real]
|
| 41 |
+
u = defaultdict(int)
|
| 42 |
+
for c in real:
|
| 43 |
+
for kk, v in c["usage"].items():
|
| 44 |
+
u[kk] += v
|
| 45 |
+
out = dict(mode="measured", runs=len(runs), calls=len(real), calls_per_run=len(real) / max(len(runs), 1),
|
| 46 |
+
usage=dict(u), cost_usd=cost, cost_per_run=cost / max(len(runs), 1),
|
| 47 |
+
latency_mean_s=sum(lat) / len(lat), api_time_per_run_s=sum(lat) / max(len(runs), 1))
|
| 48 |
+
else:
|
| 49 |
+
prev = {}
|
| 50 |
+
tot_in = tot_cached = 0
|
| 51 |
+
cost1 = 0.0 # priced per call (the long-context surcharge applies per request)
|
| 52 |
+
for c in calls:
|
| 53 |
+
d = c.get("dry_run_request")
|
| 54 |
+
if not d:
|
| 55 |
+
continue
|
| 56 |
+
key = (c["seed"], c["attempt"])
|
| 57 |
+
tin = d["est_input_tokens"]
|
| 58 |
+
cached = min(prev.get(key, 0), tin)
|
| 59 |
+
prev[key] = tin
|
| 60 |
+
tot_in += tin
|
| 61 |
+
tot_cached += cached
|
| 62 |
+
cost1 += call_cost(dict(input_tokens=tin, cached_tokens=cached, output_tokens=a.out_tokens), a.model)
|
| 63 |
+
n = len(calls) * a.calls_scale
|
| 64 |
+
scale = a.calls_scale
|
| 65 |
+
usage = dict(input_tokens=tot_in * scale, cached_tokens=tot_cached * scale, output_tokens=n * a.out_tokens)
|
| 66 |
+
cost = cost1 * scale
|
| 67 |
+
out = dict(mode="estimate (dry run)", runs=len(runs), calls=n, calls_per_run=n / max(len(runs), 1),
|
| 68 |
+
input_tokens_per_call=tot_in / max(len(calls), 1), cached_fraction=tot_cached / max(tot_in, 1),
|
| 69 |
+
usage=usage, cost_usd=cost, cost_per_run=cost / max(len(runs), 1),
|
| 70 |
+
api_time_per_run_s=n * a.latency / max(len(runs), 1), prices=PRICES.get(a.model),
|
| 71 |
+
assumptions=dict(out_tokens_per_call=a.out_tokens, latency_s_per_call=a.latency,
|
| 72 |
+
calls_scale=a.calls_scale, image_tokens_512px=256))
|
| 73 |
+
print(json.dumps(out, indent=1, default=str))
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
if __name__ == "__main__":
|
| 77 |
+
main()
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/usage_stats.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Token and time usage of api_batch.py --memfree followup batches, per run and per instance.
|
| 2 |
+
|
| 3 |
+
Sources (all written by the run itself, nothing re-estimated here):
|
| 4 |
+
harness.json wall_s (agent CLI start to end, all resume segments) and final_metrics (total_prompt_tokens incl.
|
| 5 |
+
cache reads, total_completion_tokens incl. reasoning / thinking, total_cached_tokens,
|
| 6 |
+
reasoning_tokens [Codex], total_cost_usd [Claude Code's own API-price estimate; we pay by subscription])
|
| 7 |
+
events.jsonl per robot-server request: think_s = time since the server's previous reply (model inference + other
|
| 8 |
+
tool calls such as shell / view_images + harness overhead), server_s = simulator time; done events
|
| 9 |
+
mark the attempts.
|
| 10 |
+
Rows: "history" = the history run (1-3 attempts in one agent session), "memfree" = the memory-free chain runs (one
|
| 11 |
+
fresh-agent attempt each, attempt 1 is shared with the history run). Per-attempt tokens are not split here: Codex only
|
| 12 |
+
reports usage per exec / resume segment, not per attempt.
|
| 13 |
+
|
| 14 |
+
python scripts/usage_stats.py --batch cx_main1 --batch cc_main1 --batch cc_opus1 [--check] [--json out.json]
|
| 15 |
+
|
| 16 |
+
--check re-adds the native usage records (codex_events.jsonl turn.completed / claude_stream.jsonl result) and reports
|
| 17 |
+
runs whose totals differ from final_metrics.
|
| 18 |
+
"""
|
| 19 |
+
import argparse
|
| 20 |
+
import json
|
| 21 |
+
import os
|
| 22 |
+
import statistics
|
| 23 |
+
import sys
|
| 24 |
+
|
| 25 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 26 |
+
import api_batch # noqa: E402
|
| 27 |
+
import outcomes # noqa: E402
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def run_usage(log):
|
| 31 |
+
h = json.load(open(os.path.join(log, "harness.json")))
|
| 32 |
+
fm = h.get("final_metrics") or {}
|
| 33 |
+
think, server, att = {}, {}, {}
|
| 34 |
+
for line in open(os.path.join(log, "events.jsonl")):
|
| 35 |
+
e = json.loads(line)
|
| 36 |
+
if e.get("ev") == "http":
|
| 37 |
+
a = e.get("attempt")
|
| 38 |
+
think[a] = think.get(a, 0.0) + (e.get("think_s") or 0.0)
|
| 39 |
+
server[a] = server.get(a, 0.0) + (e.get("server_s") or 0.0)
|
| 40 |
+
elif e.get("ev") == "done":
|
| 41 |
+
att[e["attempt"]] = e["success"] in (True, "True")
|
| 42 |
+
return dict(wall_s=h.get("wall_s"), think_s=sum(think.values()), server_s=sum(server.values()),
|
| 43 |
+
think_per_attempt=[round(think.get(a, 0.0), 1) for a in sorted(att)], n_attempts=len(att),
|
| 44 |
+
prompt=fm.get("total_prompt_tokens") or 0, completion=fm.get("total_completion_tokens") or 0,
|
| 45 |
+
cached=fm.get("total_cached_tokens") or 0, reasoning=fm.get("reasoning_tokens"),
|
| 46 |
+
cost_usd=fm.get("total_cost_usd"), steps=fm.get("total_steps"), model=h.get("model"),
|
| 47 |
+
harness=h.get("harness"), version=h.get("version"))
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def native_totals(log):
|
| 51 |
+
"""(prompt, completion, records) re-added from the CLI's own event stream, None if there is none."""
|
| 52 |
+
p = os.path.join(log, "codex_events.jsonl")
|
| 53 |
+
if os.path.exists(p):
|
| 54 |
+
tot = [0, 0, 0]
|
| 55 |
+
for line in open(p):
|
| 56 |
+
if '"turn.completed"' in line:
|
| 57 |
+
u = json.loads(line)["usage"]
|
| 58 |
+
tot = [tot[0] + u["input_tokens"], tot[1] + u["output_tokens"], tot[2] + 1]
|
| 59 |
+
return tuple(tot)
|
| 60 |
+
p = os.path.join(log, "claude_stream.jsonl")
|
| 61 |
+
if os.path.exists(p):
|
| 62 |
+
tot = [0, 0, 0]
|
| 63 |
+
for line in open(p):
|
| 64 |
+
if '"type":"result"' in line:
|
| 65 |
+
d = json.loads(line)
|
| 66 |
+
if d.get("type") != "result":
|
| 67 |
+
continue
|
| 68 |
+
u = d["usage"]
|
| 69 |
+
tot = [tot[0] + u["input_tokens"] + u["cache_read_input_tokens"] + u["cache_creation_input_tokens"],
|
| 70 |
+
tot[1] + u["output_tokens"], tot[2] + 1]
|
| 71 |
+
return tuple(tot)
|
| 72 |
+
return None
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def batch_rows(batch):
|
| 76 |
+
m = api_batch.load(batch)
|
| 77 |
+
hist = {r["task"] + "|" + str(r["seed"]): r for r in m["runs"]
|
| 78 |
+
if r["cond"] == "harness" and r.get("followup") and r["status"] == "done"}
|
| 79 |
+
out = dict(batch=batch, runs=[], instances=[])
|
| 80 |
+
for key, r in hist.items():
|
| 81 |
+
h = dict(run_usage(r["log"]), id=r["id"], log=r["log"], kind="history",
|
| 82 |
+
outcome="".join("S" if s else "F" for _, s, _, _ in outcomes.attempts(r["log"])))
|
| 83 |
+
chain = sorted((x for x in m["runs"] if x.get("chain") == r["id"] and x["status"] == "done"),
|
| 84 |
+
key=lambda x: x["rep"])
|
| 85 |
+
mf = [dict(run_usage(x["log"]), id=x["id"], log=x["log"], kind="memfree", rep=x["rep"]) for x in chain]
|
| 86 |
+
out["runs"] += [h] + mf
|
| 87 |
+
out["instances"].append(dict(task=r["task"], seed=r["seed"], history=h, memfree=mf))
|
| 88 |
+
return out
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def agg(runs):
|
| 92 |
+
if not runs:
|
| 93 |
+
return None
|
| 94 |
+
att = sum(x["n_attempts"] for x in runs)
|
| 95 |
+
cost = [x["cost_usd"] for x in runs if x["cost_usd"] is not None]
|
| 96 |
+
per_att = [t for x in runs for t in x["think_per_attempt"]]
|
| 97 |
+
return dict(n_runs=len(runs), n_attempts=att, wall_h=sum(x["wall_s"] or 0 for x in runs) / 3600,
|
| 98 |
+
think_h=sum(x["think_s"] for x in runs) / 3600, server_h=sum(x["server_s"] for x in runs) / 3600,
|
| 99 |
+
think_min_per_attempt_mean=sum(per_att) / max(1, len(per_att)) / 60,
|
| 100 |
+
think_min_per_attempt_median=statistics.median(per_att) / 60 if per_att else None,
|
| 101 |
+
prompt_M=sum(x["prompt"] for x in runs) / 1e6, cached_M=sum(x["cached"] for x in runs) / 1e6,
|
| 102 |
+
completion_M=sum(x["completion"] for x in runs) / 1e6,
|
| 103 |
+
reasoning_M=(sum(x["reasoning"] or 0 for x in runs) / 1e6
|
| 104 |
+
if any(x["reasoning"] is not None for x in runs) else None),
|
| 105 |
+
prompt_M_per_attempt=sum(x["prompt"] for x in runs) / 1e6 / max(1, att),
|
| 106 |
+
completion_k_per_attempt=sum(x["completion"] for x in runs) / 1e3 / max(1, att),
|
| 107 |
+
cost_usd=sum(cost) if cost else None)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def fmt(v, f):
|
| 111 |
+
return "—" if v is None else format(v, f)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def main():
|
| 115 |
+
ap = argparse.ArgumentParser()
|
| 116 |
+
ap.add_argument("--batch", action="append", required=True)
|
| 117 |
+
ap.add_argument("--check", action="store_true")
|
| 118 |
+
ap.add_argument("--json", default=None)
|
| 119 |
+
a = ap.parse_args()
|
| 120 |
+
B = [batch_rows(b) for b in a.batch]
|
| 121 |
+
|
| 122 |
+
print("| batch | model | runs | runs (attempts) | wall h | agent-side h | sim h | agent-side min / attempt (mean · median)"
|
| 123 |
+
" | prompt M (cached) | completion M (reasoning) | prompt M / attempt | completion k / attempt | API-price USD |")
|
| 124 |
+
print("|---|---|---|---|---|---|---|---|---|---|---|---|---|")
|
| 125 |
+
summ = {}
|
| 126 |
+
for b in B:
|
| 127 |
+
model = b["runs"][0]["model"] if b["runs"] else "?"
|
| 128 |
+
for kind in ("history", "memfree", "all"):
|
| 129 |
+
runs = [x for x in b["runs"] if kind == "all" or x["kind"] == kind]
|
| 130 |
+
s = agg(runs)
|
| 131 |
+
summ[f"{b['batch']}/{kind}"] = s
|
| 132 |
+
if not s:
|
| 133 |
+
continue
|
| 134 |
+
print(f"| {b['batch']} | {model} | {kind} | {s['n_runs']} ({s['n_attempts']}) | {s['wall_h']:.1f} | "
|
| 135 |
+
f"{s['think_h']:.1f} | {s['server_h']:.1f} | {s['think_min_per_attempt_mean']:.1f} · "
|
| 136 |
+
f"{s['think_min_per_attempt_median']:.1f} | {s['prompt_M']:.1f} ({s['cached_M']:.1f}) | "
|
| 137 |
+
f"{s['completion_M']:.2f} ({fmt(s['reasoning_M'], '.2f')}) | {s['prompt_M_per_attempt']:.2f} | "
|
| 138 |
+
f"{s['completion_k_per_attempt']:.1f} | {fmt(s['cost_usd'], '.0f')} |")
|
| 139 |
+
|
| 140 |
+
# per instance: history run, then the memory-free chain added up
|
| 141 |
+
keys = sorted({(i["task"], i["seed"]) for b in B for i in b["instances"]})
|
| 142 |
+
print("\nPer instance. Cell = outcome · agent-side min · prompt M / completion k (history run); "
|
| 143 |
+
"memory-free cell = runs · agent-side min · prompt M / completion k, added up.\n")
|
| 144 |
+
print("| task | seed | " + " | ".join(f"{b['batch']} history | {b['batch']} memory-free" for b in B) + " |")
|
| 145 |
+
print("|---|---|" + "---|---|" * len(B))
|
| 146 |
+
for task, seed in keys:
|
| 147 |
+
cells = []
|
| 148 |
+
for b in B:
|
| 149 |
+
i = next((x for x in b["instances"] if (x["task"], x["seed"]) == (task, seed)), None)
|
| 150 |
+
if i is None:
|
| 151 |
+
cells += ["—", "—"]
|
| 152 |
+
continue
|
| 153 |
+
h = i["history"]
|
| 154 |
+
cells.append(f"{h['outcome']} · {h['think_s'] / 60:.0f} · {h['prompt'] / 1e6:.1f}/{h['completion'] / 1e3:.0f}")
|
| 155 |
+
mf = i["memfree"]
|
| 156 |
+
cells.append("—" if not mf else
|
| 157 |
+
f"{len(mf)} · {sum(x['think_s'] for x in mf) / 60:.0f} · "
|
| 158 |
+
f"{sum(x['prompt'] for x in mf) / 1e6:.1f}/{sum(x['completion'] for x in mf) / 1e3:.0f}")
|
| 159 |
+
print(f"| {task} | {seed} | " + " | ".join(cells) + " |")
|
| 160 |
+
|
| 161 |
+
if a.check:
|
| 162 |
+
bad, n = [], 0
|
| 163 |
+
for b in B:
|
| 164 |
+
for x in b["runs"]:
|
| 165 |
+
nt = native_totals(x["log"])
|
| 166 |
+
if nt is None:
|
| 167 |
+
continue
|
| 168 |
+
n += 1
|
| 169 |
+
if (nt[0], nt[1]) != (x["prompt"], x["completion"]):
|
| 170 |
+
bad.append((b["batch"], x["id"], nt, x["prompt"], x["completion"]))
|
| 171 |
+
print(f"\ncheck: {n} runs re-added from native streams, {len(bad)} differ from final_metrics", bad[:5])
|
| 172 |
+
if a.json:
|
| 173 |
+
with open(a.json, "w") as f:
|
| 174 |
+
json.dump(dict(summary=summ, batches=B), f, indent=1, ensure_ascii=False)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
if __name__ == "__main__":
|
| 178 |
+
main()
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/harnesses/codex_catalogs/generic_0.163.0.json
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"codex_version": "0.163.0",
|
| 3 |
+
"created": "2026-10-20",
|
| 4 |
+
"note": "Shared ('generic') Codex configuration for the main table (user 2026-10-20): every model gets this one catalog entry, with only slug / display_name / input_modalities / supported_reasoning_levels set per model. base_instructions and the other fields reproduce what Codex 0.163.0 sends for a model slug it has no entry for and no model_catalog_json is given (measured against the fake API: identical request apart from message ids): its generic Codex CLI prompt, plain function tools (no code mode), parallel tool calls, reasoning summary auto, no verbosity. See docs/15 8.9.",
|
| 5 |
+
"entry": {
|
| 6 |
+
"description": "",
|
| 7 |
+
"default_reasoning_level": "medium",
|
| 8 |
+
"supported_reasoning_levels": [
|
| 9 |
+
{
|
| 10 |
+
"effort": "low",
|
| 11 |
+
"description": "Fast responses with lighter reasoning"
|
| 12 |
+
},
|
| 13 |
+
{
|
| 14 |
+
"effort": "medium",
|
| 15 |
+
"description": "Balances speed and reasoning depth for everyday tasks"
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"effort": "high",
|
| 19 |
+
"description": "Greater reasoning depth for complex problems"
|
| 20 |
+
},
|
| 21 |
+
{
|
| 22 |
+
"effort": "xhigh",
|
| 23 |
+
"description": "Extra high reasoning depth for complex problems"
|
| 24 |
+
}
|
| 25 |
+
],
|
| 26 |
+
"shell_type": "default",
|
| 27 |
+
"visibility": "list",
|
| 28 |
+
"supported_in_api": true,
|
| 29 |
+
"priority": 99,
|
| 30 |
+
"additional_speed_tiers": [],
|
| 31 |
+
"service_tiers": [],
|
| 32 |
+
"availability_nux": null,
|
| 33 |
+
"upgrade": null,
|
| 34 |
+
"model_messages": null,
|
| 35 |
+
"include_skills_usage_instructions": false,
|
| 36 |
+
"include_plugin_usage_instructions": false,
|
| 37 |
+
"include_apps_usage_instructions": false,
|
| 38 |
+
"default_reasoning_summary": "auto",
|
| 39 |
+
"support_verbosity": false,
|
| 40 |
+
"default_verbosity": null,
|
| 41 |
+
"apply_patch_tool_type": null,
|
| 42 |
+
"web_search_tool_type": "text",
|
| 43 |
+
"truncation_policy": {
|
| 44 |
+
"mode": "bytes",
|
| 45 |
+
"limit": 10000
|
| 46 |
+
},
|
| 47 |
+
"supports_image_detail_original": false,
|
| 48 |
+
"context_window": 272000,
|
| 49 |
+
"max_context_window": 272000,
|
| 50 |
+
"effective_context_window_percent": 95,
|
| 51 |
+
"experimental_supported_tools": [],
|
| 52 |
+
"input_modalities": [
|
| 53 |
+
"text",
|
| 54 |
+
"image"
|
| 55 |
+
],
|
| 56 |
+
"supports_search_tool": false,
|
| 57 |
+
"supports_experimental_context": false,
|
| 58 |
+
"use_responses_lite": false,
|
| 59 |
+
"supports_reasoning_effort_updates": false,
|
| 60 |
+
"node_repl_auto_review_required": false,
|
| 61 |
+
"node_repl_disabled": false,
|
| 62 |
+
"base_instructions": "You are a coding agent running in the Codex CLI, a terminal-based coding assistant. Codex CLI is an open source project led by OpenAI. You are expected to be precise, safe, and helpful.\n\nYour capabilities:\n\n- Receive user prompts and other context provided by the harness, such as files in the workspace.\n- Communicate with the user by streaming thinking & responses, and by making & updating plans.\n- Emit function calls to run terminal commands and apply patches. Depending on how this specific run is configured, you can request that these function calls be escalated to the user for approval before running. More on this in the \"Sandbox and approvals\" section.\n\nWithin this context, Codex refers to the open-source agentic coding interface (not the old Codex language model built by OpenAI).\n\n# How you work\n\n## Personality\n\nYour default personality and tone is concise, direct, and friendly. You communicate efficiently, always keeping the user clearly informed about ongoing actions without unnecessary detail. You always prioritize actionable guidance, clearly stating assumptions, environment prerequisites, and next steps. Unless explicitly asked, you avoid excessively verbose explanations about your work.\n\n# AGENTS.md spec\n- Repos often contain AGENTS.md files. These files can appear anywhere within the repository.\n- These files are a way for humans to give you (the agent) instructions or tips for working within the container.\n- Some examples might be: coding conventions, info about how code is organized, or instructions for how to run or test code.\n- Instructions in AGENTS.md files:\n - The scope of an AGENTS.md file is the entire directory tree rooted at the folder that contains it.\n - For every file you touch in the final patch, you must obey instructions in any AGENTS.md file whose scope includes that file.\n - Instructions about code style, structure, naming, etc. apply only to code within the AGENTS.md file's scope, unless the file states otherwise.\n - More-deeply-nested AGENTS.md files take precedence in the case of conflicting instructions.\n - Direct system/developer/user instructions (as part of a prompt) take precedence over AGENTS.md instructions.\n- The contents of the AGENTS.md file at the root of the repo and any directories from the CWD up to the root are included with the developer message and don't need to be re-read. When working in a subdirectory of CWD, or a directory outside the CWD, check for any AGENTS.md files that may be applicable.\n\n## Responsiveness\n\n### Preamble messages\n\nBefore making tool calls, send a brief preamble to the user explaining what you’re about to do. When sending preamble messages, follow these principles and examples:\n\n- **Logically group related actions**: if you’re about to run several related commands, describe them together in one preamble rather than sending a separate note for each.\n- **Keep it concise**: be no more than 1-2 sentences, focused on immediate, tangible next steps. (8–12 words for quick updates).\n- **Build on prior context**: if this is not your first tool call, use the preamble message to connect the dots with what’s been done so far and create a sense of momentum and clarity for the user to understand your next actions.\n- **Keep your tone light, friendly and curious**: add small touches of personality in preambles feel collaborative and engaging.\n- **Exception**: Avoid adding a preamble for every trivial read (e.g., `cat` a single file) unless it’s part of a larger grouped action.\n\n**Examples:**\n\n- “I’ve explored the repo; now checking the API route definitions.”\n- “Next, I’ll patch the config and update the related tests.”\n- “I’m about to scaffold the CLI commands and helper functions.”\n- “Ok cool, so I’ve wrapped my head around the repo. Now digging into the API routes.”\n- “Config’s looking tidy. Next up is patching helpers to keep things in sync.”\n- “Finished poking at the DB gateway. I will now chase down error handling.”\n- “Alright, build pipeline order is interesting. Checking how it reports failures.”\n- “Spotted a clever caching util; now hunting where it gets used.”\n\n## Task execution\n\nYou are a coding agent. Please keep going until the query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved. Autonomously resolve the query to the best of your ability, using the tools available to you, before coming back to the user. Do NOT guess or make up an answer.\n\nYou MUST adhere to the following criteria when solving queries:\n\n- Working on the repo(s) in the current environment is allowed, even if they are proprietary.\n- Analyzing code for vulnerabilities is allowed.\n- Showing user code and tool call details is allowed.\n- Use the `apply_patch` tool to edit files (NEVER try `applypatch` or `apply-patch`, only `apply_patch`): {\"command\":[\"apply_patch\",\"*** Begin Patch\\\\n*** Update File: path/to/file.py\\\\n@@ def example():\\\\n- pass\\\\n+ return 123\\\\n*** End Patch\"]}\n\nIf completing the user's task requires writing or modifying files, your code and final answer should follow these coding guidelines, though user instructions (i.e. AGENTS.md) may override these guidelines:\n\n- Fix the problem at the root cause rather than applying surface-level patches, when possible.\n- Avoid unneeded complexity in your solution.\n- Do not attempt to fix unrelated bugs or broken tests. It is not your responsibility to fix them. (You may mention them to the user in your final message though.)\n- Update documentation as necessary.\n- Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task.\n- Use `git log` and `git blame` to search the history of the codebase if additional context is required.\n- NEVER add copyright or license headers unless specifically requested.\n- Do not waste tokens by re-reading files after calling `apply_patch` on them. The tool call will fail if it didn't work. The same goes for making folders, deleting folders, etc.\n- Do not `git commit` your changes or create new git branches unless explicitly requested.\n- Do not add inline comments within code unless explicitly requested.\n- Do not use one-letter variable names unless explicitly requested.\n- NEVER output inline citations like \"【F:README.md†L5-L14】\" in your outputs. The CLI is not able to render these so they will just be broken in the UI. Instead, if you output valid filepaths, users will be able to click on them to open the files in their editor.\n\n## Validating your work\n\nIf the codebase has tests or the ability to build or run, consider using them to verify that your work is complete. \n\nWhen testing, your philosophy should be to start as specific as possible to the code you changed so that you can catch issues efficiently, then make your way to broader tests as you build confidence. If there's no test for the code you changed, and if the adjacent patterns in the codebases show that there's a logical place for you to add a test, you may do so. However, do not add tests to codebases with no tests.\n\nSimilarly, once you're confident in correctness, you can suggest or use formatting commands to ensure that your code is well formatted. If there are issues you can iterate up to 3 times to get formatting right, but if you still can't manage it's better to save the user time and present them a correct solution where you call out the formatting in your final message. If the codebase does not have a formatter configured, do not add one.\n\nFor all of testing, running, building, and formatting, do not attempt to fix unrelated bugs. It is not your responsibility to fix them. (You may mention them to the user in your final message though.)\n\nBe mindful of whether to run validation commands proactively. In the absence of behavioral guidance:\n\n- When running in the non-interactive approval mode **never**, proactively run tests, lint and do whatever you need to ensure you've completed the task.\n- When working in interactive approval modes like **untrusted**, or **on-request**, hold off on running tests or lint commands until the user is ready for you to finalize your output, because these commands take time to run and slow down iteration. Instead suggest what you want to do next, and let the user confirm first.\n- When working on test-related tasks, such as adding tests, fixing tests, or reproducing a bug to verify behavior, you may proactively run tests regardless of approval mode. Use your judgement to decide whether this is a test-related task.\n\n## Ambition vs. precision\n\nFor tasks that have no prior context (i.e. the user is starting something brand new), you should feel free to be ambitious and demonstrate creativity with your implementation.\n\nIf you're operating in an existing codebase, you should make sure you do exactly what the user asks with surgical precision. Treat the surrounding codebase with respect, and don't overstep (i.e. changing filenames or variables unnecessarily). You should balance being sufficiently ambitious and proactive when completing tasks of this nature.\n\nYou should use judicious initiative to decide on the right level of detail and complexity to deliver based on the user's needs. This means showing good judgment that you're capable of doing the right extras without gold-plating. This might be demonstrated by high-value, creative touches when scope of the task is vague; while being surgical and targeted when scope is tightly specified.\n\n## Sharing progress updates\n\nFor especially longer tasks that you work on (i.e. requiring many tool calls, or a plan with multiple steps), you should provide progress updates back to the user at reasonable intervals. These updates should be structured as a concise sentence or two (no more than 8-10 words long) recapping progress so far in plain language: this update demonstrates your understanding of what needs to be done, progress so far (i.e. files explores, subtasks complete), and where you're going next.\n\nBefore doing large chunks of work that may incur latency as experienced by the user (i.e. writing a new file), you should send a concise message to the user with an update indicating what you're about to do to ensure they know what you're spending time on. Don't start editing or writing large files before informing the user what you are doing and why.\n\nThe messages you send before tool calls should describe what is immediately about to be done next in very concise language. If there was previous work done, this preamble message should also include a note about the work done so far to bring the user along.\n\n## Presenting your work and final message\n\nYour final message should read naturally, like an update from a concise teammate. For casual conversation, brainstorming tasks, or quick questions from the user, respond in a friendly, conversational tone. You should ask questions, suggest ideas, and adapt to the user’s style. If you've finished a large amount of work, when describing what you've done to the user, you should follow the final answer formatting guidelines to communicate substantive changes. You don't need to add structured formatting for one-word answers, greetings, or purely conversational exchanges.\n\nYou can skip heavy formatting for single, simple actions or confirmations. In these cases, respond in plain sentences with any relevant next step or quick option. Reserve multi-section structured responses for results that need grouping or explanation.\n\nThe user is working on the same computer as you, and has access to your work. As such there's no need to show the full contents of large files you have already written unless the user explicitly asks for them. Similarly, if you've created or modified files using `apply_patch`, there's no need to tell users to \"save the file\" or \"copy the code into a file\"—just reference the file path.\n\nIf there's something that you think you could help with as a logical next step, concisely ask the user if they want you to do so. Good examples of this are running tests, committing changes, or building out the next logical component. If there’s something that you couldn't do (even with approval) but that the user might want to do (such as verifying changes by running the app), include those instructions succinctly.\n\nBrevity is very important as a default. You should be very concise (i.e. no more than 10 lines), but can relax this requirement for tasks where additional detail and comprehensiveness is important for the user's understanding.\n\n### Final answer structure and style guidelines\n\nYou are producing plain text that will later be styled by the CLI. Follow these rules exactly. Formatting should make results easy to scan, but not feel mechanical. Use judgment to decide how much structure adds value.\n\n**Section Headers**\n\n- Use only when they improve clarity — they are not mandatory for every answer.\n- Choose descriptive names that fit the content\n- Keep headers short (1–3 words) and in `**Title Case**`. Always start headers with `**` and end with `**`\n- Leave no blank line before the first bullet under a header.\n- Section headers should only be used where they genuinely improve scanability; avoid fragmenting the answer.\n\n**Bullets**\n\n- Use `-` followed by a space for every bullet.\n- Merge related points when possible; avoid a bullet for every trivial detail.\n- Keep bullets to one line unless breaking for clarity is unavoidable.\n- Group into short lists (4–6 bullets) ordered by importance.\n- Use consistent keyword phrasing and formatting across sections.\n\n**Monospace**\n\n- Wrap all commands, file paths, env vars, and code identifiers in backticks (`` `...` ``).\n- Apply to inline examples and to bullet keywords if the keyword itself is a literal file/command.\n- Never mix monospace and bold markers; choose one based on whether it’s a keyword (`**`) or inline code/path (`` ` ``).\n\n**File References**\nWhen referencing files in your response, make sure to include the relevant start line and always follow the below rules:\n * Use inline code to make file paths clickable.\n * Each reference should have a stand alone path. Even if it's the same file.\n * Accepted: absolute, workspace‑relative, a/ or b/ diff prefixes, or bare filename/suffix.\n * Line/column (1‑based, optional): :line[:column] or #Lline[Ccolumn] (column defaults to 1).\n * Do not use URIs like file://, vscode://, or https://.\n * Do not provide range of lines\n * Examples: src/app.ts, src/app.ts:42, b/server/index.js#L10, C:\\repo\\project\\main.rs:12:5\n\n**Structure**\n\n- Place related bullets together; don’t mix unrelated concepts in the same section.\n- Order sections from general → specific → supporting info.\n- For subsections (e.g., “Binaries” under “Rust Workspace”), introduce with a bolded keyword bullet, then list items under it.\n- Match structure to complexity:\n - Multi-part or detailed results → use clear headers and grouped bullets.\n - Simple results → minimal headers, possibly just a short list or paragraph.\n\n**Tone**\n\n- Keep the voice collaborative and natural, like a coding partner handing off work.\n- Be concise and factual — no filler or conversational commentary and avoid unnecessary repetition\n- Use present tense and active voice (e.g., “Runs tests” not “This will run tests”).\n- Keep descriptions self-contained; don’t refer to “above” or “below”.\n- Use parallel structure in lists for consistency.\n\n**Don’t**\n\n- Don’t use literal words “bold” or “monospace” in the content.\n- Don’t nest bullets or create deep hierarchies.\n- Don’t output ANSI escape codes directly — the CLI renderer applies them.\n- Don’t cram unrelated keywords into a single bullet; split for clarity.\n- Don’t let keyword lists run long — wrap or reformat for scanability.\n\nGenerally, ensure your final answers adapt their shape and depth to the request. For example, answers to code explanations should have a precise, structured explanation with code references that answer the question directly. For tasks with a simple implementation, lead with the outcome and supplement only with what’s needed for clarity. Larger changes can be presented as a logical walkthrough of your approach, grouping related steps, explaining rationale where it adds value, and highlighting next actions to accelerate the user. Your answers should provide the right level of detail while being easily scannable.\n\nFor casual greetings, acknowledgements, or other one-off conversational messages that are not delivering substantive information or structured results, respond naturally without section headers or bullet formatting.\n\n# Tool Guidelines\n\n## Shell commands\n\nWhen using the shell, you must adhere to the following guidelines:\n\n- When searching for text or files, prefer using `rg` or `rg --files` respectively because `rg` is much faster than alternatives like `grep`. (If the `rg` command is not found, then use alternatives.)\n- Do not use python scripts to attempt to output larger chunks of a file.\n\n"
|
| 63 |
+
}
|
| 64 |
+
}
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/harnesses/codex_catalogs/native_0.163.0.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-fable-5-1_high.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "claude_code_full-oauth|2.1.299|2d894a4b1bfaaa9a|claude-fable-5-1|high",
|
| 3 |
+
"fingerprint_sha256": "f44d5ded7b8b847b934c86d8f7b51fa90ae396a1f33bca51e1c946f09da1031b",
|
| 4 |
+
"written": "2026-10-21 05:19:35",
|
| 5 |
+
"summary": {
|
| 6 |
+
"system_chars": 11701,
|
| 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-fable-5-1"
|
| 14 |
+
}
|
| 15 |
+
}
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/agent_viewer/viewer.html
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!doctype html>
|
| 2 |
+
<html lang="zh-CN">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
| 5 |
+
<title>Agent Viewer · 历史回放</title>
|
| 6 |
+
<style>
|
| 7 |
+
:root{color-scheme:light;--bg:#f6f7f6;--paper:#fff;--text:#192b31;--muted:#62747a;--border:#dfe7e6;--teal:#087f79;--soft:#e9f5f1;--orange:#b56624;--red:#af4545;--mono:ui-monospace,SFMono-Regular,Consolas,monospace;font-family:Inter,-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;color:var(--text);background:var(--bg)}
|
| 8 |
+
*{box-sizing:border-box}body{margin:0}button,input,select{font:inherit}button,select{cursor:pointer}button{border:1px solid var(--border);background:var(--paper);color:var(--text);border-radius:7px;padding:9px 13px;font-size:13px}button:hover{background:var(--soft)}button:disabled{opacity:.4;cursor:default}button:focus-visible,input:focus-visible,select:focus-visible{outline:3px solid #55bbb1;outline-offset:2px}button.active,button[aria-pressed="true"]{border-color:var(--teal);color:var(--teal);background:var(--soft)}.primary{background:var(--teal);border-color:var(--teal);color:white}.primary:hover{background:#076762}.muted{color:var(--muted)}.mono,code{font-family:var(--mono)}.eyebrow{font-size:10px;text-transform:uppercase;letter-spacing:1.7px;font-weight:700;color:var(--muted)}
|
| 9 |
+
header{height:72px;padding:0 28px;display:flex;align-items:center;gap:18px;border-bottom:1px solid var(--border);background:var(--paper)}.brand{font-size:21px;font-weight:750;letter-spacing:-.6px;display:flex;align-items:center;gap:11px}.brandmark{background:var(--teal);color:#fff;border-radius:9px;padding:4px 8px;font-size:20px}.divider{height:23px;width:1px;background:var(--border)}.mode{margin-left:auto;font-size:12px;color:var(--teal);background:var(--soft);padding:7px 12px;border-radius:6px}.shell{display:grid;grid-template-columns:235px minmax(0,1fr);min-height:calc(100vh - 72px)}aside{padding:27px 18px;border-right:1px solid var(--border);background:#f9faf9}.aside-title{display:flex;justify-content:space-between;align-items:center;margin-bottom:21px;font-size:13px}.run{display:block;text-align:left;width:100%;padding:15px 13px;border-radius:9px;margin-bottom:9px}.run strong{display:block;font-size:13px;line-height:1.6;overflow-wrap:anywhere}.run small{display:block;line-height:1.9;color:var(--muted);font-size:11px}.run .state{font-size:11px;color:var(--teal);margin-bottom:9px;display:block}.aside-section{border-top:1px solid var(--border);margin-top:27px;padding-top:22px}.attempt{display:block;width:100%;text-align:left;margin-top:9px;font-size:12px}.attempt span{float:right}.success{color:var(--teal)}.failed{color:var(--red)}.aside-note{font-size:11px;line-height:1.9;margin-top:25px;color:var(--muted)}
|
| 10 |
+
main{min-width:0;padding:28px 30px}.heading{display:flex;justify-content:space-between;gap:20px;align-items:flex-start;margin-bottom:22px}h1{font-size:26px;letter-spacing:-.8px;line-height:1.3;margin:7px 0 9px}h2{font-size:15px;margin:0}h3{font-size:13px;margin:0}.subtitle{font-size:12px;line-height:1.8;color:var(--muted)}.pill{display:inline-block;white-space:nowrap;font-size:11px;padding:6px 10px;border-radius:20px;background:var(--soft);color:var(--teal)}.workspace{display:grid;grid-template-columns:minmax(320px,1.5fr) minmax(280px,1fr);gap:22px}.panel{background:var(--paper);border:1px solid var(--border);border-radius:12px;overflow:hidden}.panel-top{display:flex;align-items:center;justify-content:space-between;padding:17px 19px;border-bottom:1px solid var(--border);gap:10px}.panel-top small{font-size:11px;color:var(--muted)}.switches{padding:14px 18px;display:flex;gap:7px;flex-wrap:wrap}.switches button{font-size:11px;padding:7px 10px}.image-stage{background:#e9eeec;margin:0 18px;min-height:230px;display:grid;place-items:center;position:relative;border-radius:7px;overflow:hidden}.image-stage img{display:block;width:100%;height:clamp(290px,36vw,480px);object-fit:contain}.image-stage .empty{padding:45px;text-align:center;color:var(--muted);line-height:1.8}.caption{padding:12px 19px;font-size:11px;color:var(--muted);line-height:1.7;overflow-wrap:anywhere}.camera-strip{display:flex;gap:12px;padding:0 18px 18px;flex-wrap:wrap}.camera{display:grid;grid-template-columns:58px 1fr;align-items:center;gap:9px;text-align:left;padding:5px 10px 5px 5px;min-width:140px}.camera img{width:58px;height:46px;object-fit:contain;background:#e9eeec;border-radius:4px}.camera span{font-size:11px}.task{margin:0 18px 18px;padding:14px 0 0;border-top:1px solid var(--border);font-size:12px;line-height:1.8}.task p{margin:6px 0 0}.step-title{display:flex;align-items:center;justify-content:space-between;margin-bottom:15px}.step-title small{font-size:11px;color:var(--muted)}.flowcard{background:var(--paper);border:1px solid var(--border);border-radius:10px;margin-bottom:12px;padding:16px}.cardtitle{display:flex;align-items:center;gap:9px;margin-bottom:12px;font-size:12px;font-weight:650}.number{color:var(--muted);background:var(--bg);border:1px solid var(--border);border-radius:5px;padding:4px;font:10px var(--mono)}.flowcard p{font-size:12px;line-height:1.8;margin:7px 0;color:var(--muted)}pre{margin:9px 0 0;font:11px/1.7 var(--mono);white-space:pre-wrap;overflow-wrap:anywhere;background:var(--bg);border:1px solid var(--border);padding:12px;border-radius:6px;max-height:230px;overflow:auto}details{margin-top:9px}summary{font-size:11px;color:var(--muted);cursor:pointer;padding:5px 0}.result-message{font-size:13px;line-height:1.8}.notice{border:1px solid #e9cfab;background:#fff8ec;color:#89541d;padding:10px 12px;border-radius:7px;margin-top:10px;font-size:11px;line-height:1.8}.statement{border-left:2px solid var(--teal);padding-left:10px;font-size:12px;line-height:1.8;margin:12px 0}.subtle{font-size:11px;line-height:1.8;color:var(--muted)}
|
| 11 |
+
.timeline{margin-top:22px;padding:18px 20px}.controls{display:flex;align-items:center;gap:9px;flex-wrap:wrap}.controls .count{font:12px var(--mono);margin:0 8px}.controls select{padding:7px;border:1px solid var(--border);background:var(--paper);border-radius:6px;font-size:11px}.controls small{margin-left:auto;font-size:11px;color:var(--muted)}input[type=range]{width:100%;accent-color:var(--teal);margin:18px 0 10px;cursor:pointer}.filmstrip{display:flex;gap:9px;overflow-x:auto;padding:3px 0 7px;scroll-behavior:smooth}.frame{flex:0 0 95px;padding:4px;position:relative}.frame img,.frame .placeholder{display:block;width:85px;height:64px;object-fit:contain;background:#e9eeec;border-radius:4px}.frame .label{display:block;font-size:10px;margin:7px 0 3px}.frame .dot{position:absolute;top:8px;right:8px;border:2px solid white;width:10px;height:10px;border-radius:50%;background:var(--teal)}.frame .dot.bad{background:var(--orange)}.timeline-foot{display:flex;justify-content:space-between;gap:15px;font-size:10px;color:var(--muted);margin-top:10px;line-height:1.8}footer{display:flex;justify-content:space-between;font-size:10px;color:var(--muted);margin-top:18px;gap:15px;line-height:1.8}.warning-list{font-size:11px;color:var(--orange)}
|
| 12 |
+
@media(min-width:1600px){main{max-width:1600px;width:100%;margin:auto}}@media(max-width:1100px){.shell{grid-template-columns:185px minmax(0,1fr)}main{padding:23px 20px}.workspace{gap:15px;grid-template-columns:minmax(250px,1.2fr) minmax(250px,1fr)}aside{padding:25px 12px}.image-stage img{height:320px}}@media(max-width:850px){.shell{display:block}aside{border-right:0;border-bottom:1px solid var(--border);padding:15px 20px}.aside-title,.aside-note,.aside-section .eyebrow{display:none}#runs{display:flex;gap:10px}.run{width:auto;min-width:190px;margin:0}.aside-section{margin:12px 0 0;padding:0;border:0;display:flex;gap:8px}.attempt{width:auto}.attempt span{float:none;margin-left:10px}.workspace{grid-template-columns:minmax(0,1fr)}.image-stage img{height:400px}header{padding:0 18px;height:63px}.heading{margin-bottom:17px}main{padding:22px 18px}.details-col{display:grid;grid-template-columns:1fr 1fr;gap:12px}.step-title{grid-column:1/-1;margin-bottom:0}.flowcard{margin:0}.flowcard:last-child{grid-column:1/-1}}@media(max-width:480px){header .divider,header>.muted{display:none}header{gap:8px}.brand{font-size:18px}.mode{font-size:10px;padding:6px 8px}.heading{display:block}h1{font-size:23px}.heading>.pill{margin-top:9px}.details-col{display:block}.flowcard{margin-top:12px}.image-stage{margin:0 10px}.image-stage img{height:280px}.panel-top{padding:14px}.camera-strip{padding:0 10px 12px;gap:6px}.camera{min-width:120px;padding-right:6px;grid-template-columns:42px 1fr}.camera img{width:42px;height:38px}.timeline{padding:14px 10px}.controls{gap:5px}.controls .count{margin:0 3px;font-size:10px}.controls small{display:none}.controls button{padding:9px 10px}.timeline-foot,footer{flex-direction:column;gap:3px}}
|
| 13 |
+
[hidden]{display:none!important}.view-tabs{display:flex;gap:8px;margin-bottom:18px}.video-panel{margin-bottom:22px}.video-stage{background:#101817;padding:16px;text-align:center}.video-stage video{display:block;width:100%;max-height:68vh;min-height:200px;margin:auto;aspect-ratio:640/376;background:#101817}.video-toolbar{display:flex;align-items:center;gap:12px;flex-wrap:wrap;padding:14px 19px}.video-toolbar label{font-size:12px}.video-toolbar select{padding:6px;border:1px solid var(--border);border-radius:6px;background:var(--paper);color:var(--text)}.video-toolbar .subtle{margin-left:auto}.video-note{padding:0 19px 16px;font-size:12px;line-height:1.8;color:var(--muted)}
|
| 14 |
+
.reason-copy{white-space:pre-wrap;font-size:12px;line-height:1.8;background:var(--soft);border-radius:7px;padding:12px;margin:9px 0}.reason-empty{background:none;color:var(--muted);padding:0}.reason-public{white-space:pre-wrap;font-size:12px;line-height:1.8;border-left:2px solid var(--teal);padding-left:10px;margin:9px 0}.view-tabs{flex-wrap:wrap}
|
| 15 |
+
</style>
|
| 16 |
+
</head>
|
| 17 |
+
<body>
|
| 18 |
+
<header><div class="brand"><span class="brandmark">⌘</span>Agent Viewer</div><span class="divider"></span><span class="muted" style="font-size:12px">LFF-Bench</span><span class="mode">◷ 历史回放</span></header>
|
| 19 |
+
<div class="shell">
|
| 20 |
+
<aside><div class="aside-title"><strong>运行记录</strong><span id="run-count" class="muted"></span></div><nav id="runs" aria-label="运行记录"></nav><div class="aside-section" id="attempts"></div><div class="aside-note">回放已保存的观察与工具记录。<br>画面来自模型输入的历史图片文件。<br>视频支持连续播放与全屏。<br>逐步视图:← → 切换,空格播放。</div></aside>
|
| 21 |
+
<main>
|
| 22 |
+
<div class="heading"><div><div class="eyebrow">OBSERVE / ACT / REVIEW</div><h1 id="title"></h1><div class="subtitle" id="subtitle"></div></div><span id="status" class="pill"></span></div>
|
| 23 |
+
<div class="view-tabs" aria-label="回放视图"><button id="video-tab" aria-pressed="false">▶ 完整执行视频</button><button id="steps-tab" aria-pressed="false">逐步输入与日志</button></div>
|
| 24 |
+
<section id="video-view" class="panel video-panel" hidden><div class="panel-top"><h2>完整执行录像</h2><small>主相机 + 腕部相机</small></div><div class="video-stage"><video id="execution-video" controls playsinline preload="metadata" aria-label="任务完整执行录像">浏览器不支持视频播放。</video></div><div class="video-toolbar"><label for="video-rate">播放速度</label><select id="video-rate"><option value="0.3333333333333333">⅓×</option><option value="0.5">0.5×</option><option value="1" selected>1× 原录像</option><option value="2">2×</option></select><span class="subtle">连续播放 · 拖动进度 · 全屏查看</span></div><div class="video-note">播放原始执行录像,保留尝试切换与结果画面。录像时间不等于日志中的等待时间;查看单步输入与工具返回可切换到“逐步输入与日志”。</div><div id="video-error" class="notice" hidden role="alert"></div></section>
|
| 25 |
+
<div id="step-view"><div class="workspace">
|
| 26 |
+
<section class="panel"><div class="panel-top"><h2>Agent 看到的画面</h2><small id="attempt-label"></small></div><div class="switches"><button id="before" aria-pressed="true">决策前 · 最近观察</button><button id="after" aria-pressed="false">执行后 · 返回图片</button></div><div class="image-stage" id="stage"></div><div class="caption" id="caption"></div><div class="camera-strip" id="cameras"></div><div class="task"><span class="eyebrow">TASK</span><p id="task"></p></div></section>
|
| 27 |
+
<section class="details-col" aria-label="当前步骤"><div class="step-title"><h2 id="step-title"></h2><small id="time"></small></div><div class="flowcard"><div class="cardtitle"><span class="number">01</span>观察输入</div><div id="observation-note" class="subtle"></div><details><summary>查看最近输入文本</summary><pre id="input-text"></pre></details></div><div class="flowcard"><div class="cardtitle"><span class="number">02</span>步骤间思考</div><div id="reason-transition" class="subtle"></div><div id="reason-summary" class="reason-copy"></div><div id="reason-public-wrap"><span class="subtle">Agent 文字说明</span><div id="reason-public" class="reason-public"></div></div><details><summary>前一步反馈与记录来源</summary><pre id="reason-feedback"></pre><p id="reason-source" class="subtle"></p><p class="subtle">显示已记录的模型摘要与文字回复,不代表完整内部 CoT。</p></details></div><div class="flowcard"><div class="cardtitle"><span class="number">03</span>执行动作</div><div id="actions"></div></div><div class="flowcard"><div class="cardtitle"><span class="number">04</span>执行反馈</div><div id="results"></div><div id="notices"></div></div></section>
|
| 28 |
+
</div>
|
| 29 |
+
<section class="panel timeline" aria-label="回放时间轴"><div class="controls"><button id="prev" aria-label="上一步">←</button><button id="play" class="primary" aria-label="播放回放">▶ 播放</button><button id="next" aria-label="下一步">→</button><span class="count" id="count" aria-live="polite"></span><select id="speed" aria-label="每步播放时长"><option value="2000">2 秒 / 步</option><option value="1000">1 秒 / 步</option><option value="4000">4 秒 / 步</option></select><small>按步骤播放 · 不按实际等待时间</small></div><input id="scrubber" type="range" min="0" value="0" aria-label="选择回放步骤"><div class="filmstrip" id="filmstrip"></div><div class="timeline-foot"><span>● 绿色:尝试成功 ● 橙色:失败 / API 重试</span><span id="step-meta"></span></div></section>
|
| 30 |
+
</div>
|
| 31 |
+
<div id="warnings" class="warning-list"></div><footer><span>真实历史记录 · 原始执行录像与输入图片 · 离线可用</span><span>逐步视图展示最近观察;模型上下文可能包含更早图片。</span></footer>
|
| 32 |
+
</main></div>
|
| 33 |
+
<script id="viewer-data" type="application/json">/*__PAYLOAD__*/null</script>
|
| 34 |
+
<script>
|
| 35 |
+
'use strict';
|
| 36 |
+
const DATA=JSON.parse(document.getElementById('viewer-data').textContent);
|
| 37 |
+
const $=id=>document.getElementById(id);
|
| 38 |
+
const names={l5_slide_to_target:'把红色方块滑入目标区',l1_bias_place:'校准偏差下的抓取放置'};
|
| 39 |
+
let runIndex=0, index=0, phase='before', camera='agentview', selectedFrameKey=null, timer=null, viewMode='steps';
|
| 40 |
+
const run=()=>DATA.runs[runIndex];
|
| 41 |
+
const step=()=>run().steps[index];
|
| 42 |
+
function el(tag,text,cls){const e=document.createElement(tag);if(text!==undefined)e.textContent=text;if(cls)e.className=cls;return e;}
|
| 43 |
+
function fmt(value){return typeof value==='string'?value:JSON.stringify(value,null,2);}
|
| 44 |
+
function clock(seconds){const s=Math.max(0,Math.round(seconds||0));return `${Math.floor(s/60)}:${String(s%60).padStart(2,'0')}`;}
|
| 45 |
+
function cameraName(name){return name==='agentview'?'主相机':name==='wrist'?'腕部相机':name;}
|
| 46 |
+
function stop(){if(timer)clearInterval(timer);timer=null;$('play').textContent='▶ 播放';$('play').setAttribute('aria-label','播放回放');}
|
| 47 |
+
function setMode(mode){stop();viewMode=mode==='video'&&run().video?'video':'steps';$('video-view').hidden=viewMode!=='video';$('step-view').hidden=viewMode!=='steps';$('video-tab').setAttribute('aria-pressed',String(viewMode==='video'));$('steps-tab').setAttribute('aria-pressed',String(viewMode==='steps'));if(viewMode!=='video')$('execution-video').pause();}
|
| 48 |
+
function setupVideo(){const v=$('execution-video');v.pause();v.removeAttribute('src');$('video-error').hidden=true;$('video-tab').disabled=!run().video;if(run().video)v.src=DATA.assets[run().video.asset];v.load();$('video-rate').value='1';v.playbackRate=1;setMode(run().video?'video':'steps');}
|
| 49 |
+
function move(value,manual=true){if(manual)stop();index=Math.max(0,Math.min(run().steps.length-1,value));render();}
|
| 50 |
+
function img(frame){const image=el('img');image.alt=`${cameraName(frame.camera)} · ${frame.path}`;image.src=DATA.assets[frame.asset];return image;}
|
| 51 |
+
function allAfter(s){return s.actions.flatMap(a=>a.after||[]);}
|
| 52 |
+
function renderRun(){
|
| 53 |
+
const r=run();$('title').textContent=names[r.task]||r.task;$('subtitle').textContent=`${r.model} / seed ${r.seed??'—'} / ${r.actionCount} 次工具调用 / ${r.feedback} · ${r.perception}`;
|
| 54 |
+
$('task').textContent=r.taskText;$('status').textContent=r.status==='success'?'● 最终成功':r.status==='failed'?'● 尝试未成功':'◌ 记录未完成';
|
| 55 |
+
$('status').style.color=r.status==='failed'?'var(--red)':'';$('run-count').textContent=DATA.runs.length;
|
| 56 |
+
$('runs').replaceChildren(...DATA.runs.map((item,n)=>{const b=el('button',undefined,'run'+(n===runIndex?' active':''));b.setAttribute('aria-pressed',String(n===runIndex));b.append(el('span',item.status==='success'?'● 已完成 · 成功':'◌ '+(item.status==='failed'?'未成功':'未完成'),'state'),el('strong',names[item.task]||item.task),el('small',`${item.model} · seed ${item.seed??'—'}`),el('small',`${item.steps.length} 步决策 · ${item.outcomes.length} 次提交`));b.onclick=()=>{stop();runIndex=n;index=0;phase='before';renderRun();render();};return b;}));
|
| 57 |
+
$('attempts').replaceChildren(el('div','ATTEMPTS','eyebrow'),...r.outcomes.map(o=>{const b=el('button',`第 ${o.attempt} 次尝试`,'attempt');b.append(el('span',o.success?'成功 ↗':'失败 ↗',o.success?'success':'failed'));b.title=o.feedback;b.onclick=()=>{setMode('steps');phase='before';move(r.steps.findIndex(s=>s.verdict?.attempt===o.attempt));};return b;}));
|
| 58 |
+
$('scrubber').max=r.steps.length-1;
|
| 59 |
+
$('warnings').replaceChildren(...r.warnings.map(w=>el('p',w)));
|
| 60 |
+
$('filmstrip').replaceChildren(...r.steps.map((s,n)=>{const b=el('button',undefined,'frame');b.setAttribute('aria-label',`第 ${n+1} 步,尝试 ${s.attempt}`);const f=s.before.find(f=>f.camera==='agentview')||s.before[0];b.append(f?.asset?img(f):el('span','无图片','placeholder'));b.append(el('span',`${String(n+1).padStart(2,'0')} · 尝试 ${s.attempt}`,'label'));if(s.verdict||s.notices.length)b.append(el('span',undefined,'dot'+(s.verdict?.success?'':' bad')));b.onclick=()=>move(n);return b;}));
|
| 61 |
+
setupVideo();
|
| 62 |
+
}
|
| 63 |
+
function renderReason(){
|
| 64 |
+
const s=step(),previous=run().steps[index-1];
|
| 65 |
+
$('reason-transition').textContent=index===0?'任务输入 → 第 1 步':`第 ${index} 步反馈 → 第 ${index+1} 步决策`;
|
| 66 |
+
$('reason-feedback').textContent=previous?previous.actions.map(a=>a.result===null?'结果未记录':fmt(a.result)).join('\n\n')||previous.text||'没有工具反馈':s.inputText||'初始输入未记录';
|
| 67 |
+
$('reason-summary').textContent=s.decisionSummary||(s.decisionSummaryStatus==='not_returned'?'模型未返回摘要。':'本步未记录摘要。');
|
| 68 |
+
$('reason-summary').classList.toggle('reason-empty',!s.decisionSummary);
|
| 69 |
+
$('reason-public-wrap').hidden=!s.text;$('reason-public').textContent=s.text||'';
|
| 70 |
+
$('reason-source').textContent=`来源:${run().source} 第 ${s.decisionSourceLine} 行 · turn ${s.turn??'—'}`;
|
| 71 |
+
}
|
| 72 |
+
function render(){
|
| 73 |
+
renderReason();
|
| 74 |
+
const r=run(),s=step(),after=allAfter(s),frames=phase==='before'?s.before:after;
|
| 75 |
+
const selected=frames.find(f=>`${f.path}@${f.source}`===selectedFrameKey)||frames.find(f=>f.camera===camera)||frames[0];if(selected)camera=selected.camera;
|
| 76 |
+
$('before').setAttribute('aria-pressed',String(phase==='before'));$('after').setAttribute('aria-pressed',String(phase==='after'));
|
| 77 |
+
$('attempt-label').textContent=`尝试 ${s.attempt} · 步骤 ${index+1}`;$('step-title').textContent=`Step ${String(index+1).padStart(2,'0')}`;
|
| 78 |
+
$('time').textContent=`+${clock(s.elapsed)}${s.latency==null?'':` · 模型耗时 ${s.latency.toFixed(1)}s`}`;
|
| 79 |
+
$('stage').replaceChildren(selected?.asset?img(selected):el('div',selected?'该图片文件缺失':'此步骤没有返回新图片','empty'));
|
| 80 |
+
const reset=s.actions.find(a=>a.resetToAttempt);
|
| 81 |
+
$('caption').textContent=selected?`${cameraName(selected.camera)} · ${selected.path} · 来源:transcript 第 ${selected.source} 行${phase==='after'&&reset?` · 已重置为尝试 ${reset.resetToAttempt}`:''}`:'日志未记录新图片;切换“决策前”查看最近观察。';
|
| 82 |
+
$('cameras').replaceChildren(...frames.map((f,n)=>{const b=el('button',undefined,'camera');b.setAttribute('aria-pressed',String(f===selected));if(f.asset)b.append(img(f));b.append(el('span',cameraName(f.camera)));b.onclick=()=>{camera=f.camera;selectedFrameKey=`${f.path}@${f.source}`;render();};return b;}));
|
| 83 |
+
$('observation-note').textContent=`最近一次收到 ${s.before.length} 张图片${s.requestImages==null?'':`;本次请求记录共 ${s.requestImages} 张图片(含历史)`}。`;
|
| 84 |
+
$('input-text').textContent=s.inputText||'没有记录输入文本。';
|
| 85 |
+
$('actions').replaceChildren(...s.actions.map(a=>{const box=el('div');box.append(el('div',a.name,'subtle'),el('pre',fmt(a.arguments)));return box;}));
|
| 86 |
+
if(!s.actions.length)$('actions').append(el('p','本步没有工具调用,Agent 输出最终报告。'));
|
| 87 |
+
$('results').replaceChildren();
|
| 88 |
+
if(s.verdict){$('results').append(el('div',s.verdict.success?'✓ 本次尝试成功':'↻ 本次尝试失败',`result-message ${s.verdict.success?'success':'failed'}`),el('p',s.verdict.feedback));}
|
| 89 |
+
for(const a of s.actions){
|
| 90 |
+
if(!s.verdict)$('results').append(el('div',a.result===null?'等待结果 / 日志缺失':a.ok===false?'工具返回错误':'工具已返回',`result-message ${a.ok===false?'failed':''}`));
|
| 91 |
+
if(a.resetToAttempt)$('results').append(el('div',`场景已重置:返回图片属于第 ${a.resetToAttempt} 次尝试。`,'notice'));
|
| 92 |
+
const d=el('details');d.append(el('summary',`${a.name} · 完整返回`),el('pre',a.result===null?'未记录':fmt(a.result)));$('results').append(d);
|
| 93 |
+
}
|
| 94 |
+
if(!s.actions.length)$('results').append(el('p','最终文字报告;结果以尝试判定为准。'));
|
| 95 |
+
const notices=[...s.notices,...(s.noticesAfter||[])];$('notices').replaceChildren(...notices.map(n=>el('div',`${n.kind==='api_error'?'API 重试':'运行中断'} · ${n.text}`,'notice')));
|
| 96 |
+
$('count').textContent=`${String(index+1).padStart(2,'0')} / ${r.steps.length}`;$('scrubber').value=index;$('prev').disabled=index===0;$('next').disabled=index===r.steps.length-1;
|
| 97 |
+
$('step-meta').textContent=`turn ${s.turn??'—'} · ${s.actions.length} 次工具调用${s.incomplete?' · 结果不完整':''}`;
|
| 98 |
+
[...$('filmstrip').children].forEach((b,n)=>b.setAttribute('aria-pressed',String(n===index)));
|
| 99 |
+
const selectedButton=$('filmstrip').children[index];if(selectedButton){const strip=$('filmstrip'),a=selectedButton.getBoundingClientRect(),b=strip.getBoundingClientRect();if(a.left<b.left||a.right>b.right)strip.scrollLeft+=a.left-b.left-strip.clientWidth/2+selectedButton.offsetWidth/2;}
|
| 100 |
+
}
|
| 101 |
+
$('prev').onclick=()=>move(index-1);$('next').onclick=()=>move(index+1);$('scrubber').oninput=e=>move(Number(e.target.value));
|
| 102 |
+
$('before').onclick=()=>{phase='before';render();};$('after').onclick=()=>{phase='after';render();};
|
| 103 |
+
$('play').onclick=()=>{if(timer){stop();return;}if(index===run().steps.length-1)move(0);$('play').textContent='Ⅱ 暂停';$('play').setAttribute('aria-label','暂停回放');timer=setInterval(()=>{if(index>=run().steps.length-1){stop();return;}move(index+1,false);if(index===run().steps.length-1)stop();},Number($('speed').value));};
|
| 104 |
+
$('speed').onchange=()=>{if(timer){stop();$('play').click();}};
|
| 105 |
+
$('video-tab').onclick=()=>setMode('video');$('steps-tab').onclick=()=>setMode('steps');
|
| 106 |
+
$('video-rate').onchange=e=>{$('execution-video').playbackRate=Number(e.target.value);};
|
| 107 |
+
$('execution-video').onerror=()=>{if(!run().video)return;$('video-error').textContent='视频加载失败,请刷新重试;仍可查看逐步输入与日志。';$('video-error').hidden=false;};
|
| 108 |
+
document.addEventListener('keydown',e=>{if(viewMode==='video')return;if(e.target.closest('input,select,textarea,button,summary'))return;if(e.key==='ArrowLeft'){e.preventDefault();move(index-1);}if(e.key==='ArrowRight'){e.preventDefault();move(index+1);}if(e.code==='Space'&&viewMode==='steps'){e.preventDefault();$('play').click();}});
|
| 109 |
+
renderRun();render();
|
| 110 |
+
</script>
|
| 111 |
+
</body></html>
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/agent/README.md
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LFF-Bench agent harness(`lffbench/agent/`)
|
| 2 |
+
|
| 3 |
+
把 VLM 智能体(默认 GPT-6 Astra,经 OpenAI Responses API)接到 LFF-Bench 任务上:工具接口、观测与历史打包、
|
| 4 |
+
记忆模式、反馈粒度、协议控制(cross / within)、日志与指标。对应设计文档 `docs/02-benchmark设计.md` §4、§5。
|
| 5 |
+
|
| 6 |
+
> 本文档里"实测"指在本机跑出来的结果;"假设 / 估计"是没验证过的,单独标出。
|
| 7 |
+
|
| 8 |
+
## 1. 文件
|
| 9 |
+
|
| 10 |
+
| 文件 | 内容 |
|
| 11 |
+
|---|---|
|
| 12 |
+
| `tools.py` | 工具 JSON schema(`tool_specs`)和执行器 `ToolExecutor`(底层全部调 `Skills`) |
|
| 13 |
+
| `camera.py` | 相机内外参、深度反投影 `pixel_to_world`、`world_to_pixel`、图像方向说明(robosuite `camera_utils`) |
|
| 14 |
+
| `context.py` | 后端无关的对话结构、尝试记录 `AttemptRecord`、记忆选择 `select_history`、全部提示词文本 `PromptBuilder`、关键帧选择、旧图裁剪 |
|
| 15 |
+
| `harness.py` | 协议控制器 `AgentHarness` + `HarnessConfig` |
|
| 16 |
+
| `backends/openai_responses.py` | `OpenAIResponsesBackend`(GPT-6 Astra) |
|
| 17 |
+
| `backends/scripted.py` | `ScriptedBackend`:不调模型,把任务自带的 scripted 策略经工具接口跑一遍 |
|
| 18 |
+
| `backends/chat_completions.py` | `ChatCompletionsBackend`:OpenAI 兼容 Chat Completions(本地 Qwen3-VL 服务、vLLM 等) |
|
| 19 |
+
| `backends/anthropic_messages.py` | `AnthropicMessagesBackend`:Anthropic Messages API(自适应思考 + effort、思考块原样回放、自动缓存,2026-10-11) |
|
| 20 |
+
| `backends/gemini.py` | `GeminiBackend`:Gemini API(google-genai;thought_signature 原样回放,2026-10-11) |
|
| 21 |
+
| `../../scripts/api_player.py` / `api_batch.py` / `mcp_robot_server.py` | LA 接口的统一驱动、批处理调度、给原生 harness 的 MCP server(见 docs/12-统一harness.md) |
|
| 22 |
+
| `runlog.py` / `replay.py` | 运行目录写入;从运行目录重建尝试记录(给 mismatched 当 donor) |
|
| 23 |
+
| `metrics.py` / `cost.py` | succ@k、ΔICL、重复动作率;token 计价 |
|
| 24 |
+
| `../../scripts/run_agent.py` | 命令行入口 |
|
| 25 |
+
| `../../scripts/agent_compare.py` | 两个运行目录配对算 ΔICL(bootstrap 区间) |
|
| 26 |
+
| `../../scripts/agent_cost.py` | 从运行目录(真实或 dry run)估算 GPT-6 成本 / 延迟 |
|
| 27 |
+
| `../../tests/test_agent_*.py` | 单元测试 + 仿真端到端测试 |
|
| 28 |
+
|
| 29 |
+
## 2. 快速开始
|
| 30 |
+
|
| 31 |
+
```bash
|
| 32 |
+
cd <repo> && source run_env.sh && export OMP_NUM_THREADS=1
|
| 33 |
+
# 管线自检(不调模型;同时记录"如果换成 GPT-6,每次请求多大")
|
| 34 |
+
python scripts/run_agent.py --task l5_slide_to_target --backend scripted --memory full --feedback F2 --n 3 --k 5 --dry-run-payload
|
| 35 |
+
# GPT-6(需要 key;见 §6)
|
| 36 |
+
export OPENAI_API_KEY=... # 必需
|
| 37 |
+
export OPENAI_BASE_URL=... # 可选:走网关 / 代理时
|
| 38 |
+
python scripts/run_agent.py --task l5_slide_to_target --backend openai --effort medium --memory full --feedback F2 --n 20 --k 5 --seed0 5000
|
| 39 |
+
python scripts/run_agent.py --task l5_slide_to_target --backend openai --effort medium --memory none --feedback F2 --n 20 --k 5 --seed0 5000
|
| 40 |
+
python scripts/agent_compare.py --with runs/agent/l5_slide_to_target/<full 运行> --iid runs/agent/l5_slide_to_target/<none 运行>
|
| 41 |
+
# 测试
|
| 42 |
+
python -m pytest -q tests/test_agent_payload.py tests/test_agent_protocol.py # 无仿真,约 1–2 分钟(CPFS 上 import 慢)
|
| 43 |
+
python -m pytest -q tests/test_agent_sim.py # 仿真,含 n=3 端到端
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
常用开关:`--instruction direct|indirect`、`--privileged-locate`(消融:给 `locate`)、`--image-res 512`、
|
| 47 |
+
`--keyframes 4`、`--keyframe-res`、`--max-steps 30`(每次尝试的工具调用上限)、`--no-auto-obs`(只在 `get_observation` 时给图)、
|
| 48 |
+
`--grasp-report bool|name|none`、`--early-stop auto|yes|no`、`--donor-run DIR`(mismatched 的 donor)、`--seeds 5000,5001`。
|
| 49 |
+
种子约定(我定的):1000–1999 开发(validate.py 也用 1000+),5000+ 留作正式测试。
|
| 50 |
+
|
| 51 |
+
## 3. 工具接口
|
| 52 |
+
|
| 53 |
+
坐标一律**世界系、米**(按本次任务要求;设计文档 §4 草稿写的是"机器人基座系",两者只差一个平移,这里统一用世界系,与 Skills 和各任务代码一致):桌面 z = 0.90,机器人基座在 x = −0.66, y = 0,+x 远离机器人,+y 机器人左侧,+z 向上。
|
| 54 |
+
位置指夹爪抓取点(两指尖中点,`gripper0_grip_site`)。夹爪始终竖直向下;`yaw` 单位是**度**(LLM 处理度比弧度少出错),
|
| 55 |
+
yaw 0 时两指沿世界 y 轴开合(实测:手指 body 在 y = ±0.02),yaw 90 沿 x 轴。yaw 按 180° 取模:`Skills.move_to`(共享代码,
|
| 56 |
+
2026-10-06 协调者改)会取与当前 yaw 最近、且 |yaw| ≤ 90°+0.4 rad(约 113°)的等价角,避免手腕绕 180° 把手臂卷进关节限位;
|
| 57 |
+
`move_to` 报告里的 `yaw_used_deg` 是实际用的角度。
|
| 58 |
+
肘关节(`robot0_joint4`)上限从 Panda 原厂的 −0.07 rad 收紧到 −0.55(`envs.ELBOW_Q4_MAX`,2026-10-19):原来快速移动越过手臂伸到最远的姿态(约 −0.47)后,肘关节会弯到反方向,被上限挡住,之后的移动都停在离目标 4–17 cm 处。收紧后可达范围不变。
|
| 59 |
+
方向词:harness 生成的文字里一律以机器人为参照,并在 system prompt 里定义——forward = +x、backward = −x、left = +y(机器人左手)、
|
| 60 |
+
right = −y、up = +z,"不是图像里的左右";同时说明 agentview 图里机器人的左边出现在图像右侧。任务自己的 F2 文本由任务作者统一。
|
| 61 |
+
|
| 62 |
+
| 工具 | 参数 | 底层 | 说明 |
|
| 63 |
+
|---|---|---|---|
|
| 64 |
+
| `move_to` | x, y, z, yaw, speed∣null | `Skills.move_to` | speed 为 null 时按控制器最快(约 0.6 m/s);yaw 按 180° 取模;超出工作空间的目标被裁剪并在报告里注明 |
|
| 65 |
+
| `open_gripper` / `close_gripper` | – | `Skills.set_gripper` | |
|
| 66 |
+
| `push` | x, y, dir_x, dir_y, distance, speed, z∣null, runup∣null | `Skills.push` | 语义与 `Skills.push` 完全一致:闭爪,到 (x,y) 后方 runup(默认 0.06)处、高度 z(默认 0.92),沿方向扫到 (x,y) 前方 distance 处,再抬 12 cm;朝向由 `Skills.push` 自动定 |
|
| 67 |
+
| `get_observation` | – | 渲染 | 返回 agentview + 腕部图像和本体状态 |
|
| 68 |
+
| `pixel_to_world` | camera(agentview∣wrist), u, v | 深度反投影 | u=列(从左数)、v=行(从上数),坐标就是模型看到的那张图(默认 512×512);返回世界点、离桌面高度、深度 |
|
| 69 |
+
| `done` | reason | – | 结束本次尝试(within 协议:结束一个分段,任务被检查) |
|
| 70 |
+
| `locate`(仅 `--privileged-locate`) | object_name(枚举) | 特权 | 物体原点的真实世界坐标 + 碰撞体 AABB;只用于"去掉感知难度"的消融 |
|
| 71 |
+
|
| 72 |
+
所有工具 schema 都是 OpenAI strict 模式(所有字段 required、可选字段可为 null、禁止额外字段)。
|
| 73 |
+
|
| 74 |
+
**动作工具的执行报告**(JSON 文本,作为 function_call_output 返回):
|
| 75 |
+
```json
|
| 76 |
+
{"ok": true, "tool": "move_to", "reached": true, "yaw_used_deg": 0.0, "eef_pos": [-0.418, 0.019, 0.920], "eef_yaw_deg": 0.5,
|
| 77 |
+
"gripper": "closed", "gripper_width_m": 0.001, "holding_object": false, "touched_object": false, "sim_time_s": 13.7}
|
| 78 |
+
```
|
| 79 |
+
- `reached`:控制器是否到达(2 cm 内,`Skills` 的判据);`push` 给 `sweep_reached`。
|
| 80 |
+
- `holding_object` / `touched_object`:默认只给布尔(`--grasp-report bool`)——真实机器人能感知"夹住了东西 / 碰到了东西",
|
| 81 |
+
但不知道是哪个物体;物体名会泄露识别类任务的答案。`--grasp-report name` 时给物体名(调试 / 消融)。
|
| 82 |
+
接触在**每个 MuJoCo 子步**检查(包装 `env.sim.step`,一个控制步 = 25 子步):实测快推时手指与方块的接触不到一个控制步,只在控制步边界查会漏掉(l5 上推了 4.4 cm 却一次接触都没记到)。不碰 `Skills.recorder`,任务自己的注入钩子不受影响。
|
| 83 |
+
- 任务若定义 `drain_events()`(L6 有),其返回的事件文本会作为 `events` 加进当次报告(L6 作者的约定)。
|
| 84 |
+
- 参数错误、未知工具、JSON 解析失败都返回 `{"ok": false, "error": ...}`,占一步预算,不中断尝试。
|
| 85 |
+
|
| 86 |
+
**隐藏 bias(L1)怎么处理**:所有命令位置都经 `Skills`,bias 照常加上。本体状态按"机器人自己以为的位置"报告:
|
| 87 |
+
`eef_pos = 真实末端 − bias`。也就是说机器人认为自己准确到了指令点,只有相机能看出偏差——这就是标定误差的本义;
|
| 88 |
+
如果报告真实末端,agent 对比指令和报告就能直接读出 bias,L1 就失效了。`pixel_to_world` 和 `locate` 给真实世界坐标。
|
| 89 |
+
(测试 `test_tool_reports_and_hidden_bias` 实测:bias (3, −2, 0) cm 时报告与指令差 < 1 cm,真实末端 = 指令 + bias。)
|
| 90 |
+
L1 任务作者在 `l1_bias.py` 的 `TrackedSkills.reported_eef_pos()` 里独立采用了同一约定,两边一致。
|
| 91 |
+
|
| 92 |
+
**`pixel_to_world` 精度(实测,l5 场景方块顶面中心,投影→反投影)**:agentview 512px 误差约 1.5 mm,256px 约 3.4 mm;
|
| 93 |
+
wrist 均 < 0.1 mm。图像方向(由外参算出并写进 system prompt):agentview 图右 = +y、图下 = +x(机器人在图上方);
|
| 94 |
+
wrist 在 yaw 0 时图右 = −y、图下 = −x。
|
| 95 |
+
|
| 96 |
+
## 4. 观测、消息格式与历史打包
|
| 97 |
+
|
| 98 |
+
请求由三部分组成,按缓存友好的顺序排列:
|
| 99 |
+
1. **instructions(system)**:机器人 / 坐标 / 相机 / 工具约定、协议(k 次尝试、重置到同一状态)、反馈粒度说明、
|
| 100 |
+
"新尝试开始前先用 1–3 句话评估前几次尝试"(这句话就是"自报失败原因"的来源,记录为 `diagnosis`)。
|
| 101 |
+
2. **历史项(user,非 live,不裁剪)**:`TASK: <指令>` + 前几次尝试的打包(按记忆模式选择)。
|
| 102 |
+
3. **当前尝试(live)**:尝试编号 + 当前 agentview / wrist 图 + 本体状态;之后每一步:模型的 function_call →
|
| 103 |
+
function_call_output(执行报告)→ 新观测(两张图 + 本体状态)。
|
| 104 |
+
|
| 105 |
+
每次尝试的打包(≤4 张关键帧 + 动作摘要 + 反馈)。下面是 scripted dry run 第 2 次尝试第 1 次调用的 `input`,原样摘自
|
| 106 |
+
`runs/agent/l5_slide_to_target/20261006-060757_scripted-adaptive_full_F2_e2e/requests/request_007.json`(图像以占位符代替,
|
| 107 |
+
`[BREAKPOINT]` 表示该内容块带 `prompt_cache_breakpoint`):
|
| 108 |
+
```
|
| 109 |
+
== user(历史项,live=False)
|
| 110 |
+
TASK: Push the red cube once, straight away from the robot, so that it slides and comes to rest inside the green target zone.
|
| 111 |
+
|
| 112 |
+
=== Your earlier attempts ===
|
| 113 |
+
|
| 114 |
+
--- Attempt 1 ---
|
| 115 |
+
Actions executed:
|
| 116 |
+
1. close_gripper() -> eef (-0.208, 0.000, 1.173); width 0.002 m
|
| 117 |
+
2. move_to(x=-0.419, y=0.021, z=1.02, yaw=0, speed=null) -> NOT reached; eef (-0.394, 0.023, 1.032)
|
| 118 |
+
3. move_to(x=-0.419, y=0.021, z=0.92, yaw=0, speed=null) -> reached; eef (-0.418, 0.019, 0.920)
|
| 119 |
+
4. move_to(x=-0.204, y=0.021, z=0.92, yaw=0, speed=0.3) -> reached; eef (-0.202, 0.021, 0.921); touched an object
|
| 120 |
+
5. move_to(x=-0.204, y=0.021, z=1, yaw=0, speed=0.3) -> reached; eef (-0.205, 0.020, 0.997)
|
| 121 |
+
6. done(reason="scripted adaptive policy finished with params {'speed': 0.3}")
|
| 122 |
+
Outcome feedback: Attempt failed. The cube stopped 5.2 cm past the centre of the target zone.
|
| 123 |
+
Key images (start of attempt, after step 1 (close_gripper), after step 4 (move_to), end of attempt, after objects settled):
|
| 124 |
+
[start of attempt] <image>
|
| 125 |
+
[after step 1 (close_gripper)] <image>
|
| 126 |
+
[after step 4 (move_to)] <image>
|
| 127 |
+
[end of attempt, after objects settled] <image>
|
| 128 |
+
=== End of earlier attempts === [BREAKPOINT]
|
| 129 |
+
== user(当前尝试,live=True)
|
| 130 |
+
This is attempt 2 of at most 5. The scene has been reset.
|
| 131 |
+
|
| 132 |
+
Current observation:
|
| 133 |
+
agentview camera: <image>
|
| 134 |
+
wrist camera: <image>
|
| 135 |
+
Proprioception: {"eef_pos": [-0.2085, -0.0, 1.1733], "eef_yaw_deg": 0.0, "gripper": "open", "gripper_width_m": 0.0411, "holding_object": false} [BREAKPOINT]
|
| 136 |
+
```
|
| 137 |
+
之后每一步依次追加:模型输出项(reasoning(加密)/ message / function_call)→ `function_call_output`(执行报告 JSON)→
|
| 138 |
+
user 项 `Observation after step N (<tool>):` + 两张图 + 本体状态。完整请求(含 instructions 和 tools)见同目录 `requests/*.json`。
|
| 139 |
+
- 关键帧(agentview):尝试开始、最多 2 张中间帧(优先 push / 开合爪 / 碰到物体的步)、结束帧(`task.outcome()` 让物体静止之后渲染)。
|
| 140 |
+
- 反馈:`task.feedback(inst, outcome, level)`。F0 不给反馈行;F1 只有成功 / 失败;F2 加结构化测量(任务的 `detail`)。
|
| 141 |
+
- 历史头不带计数,所以第 j+1 次尝试的历史项以第 j 次的为前缀(只多一块),前缀可被缓存命中(单测 `test_history_prefix_is_append_only`)。
|
| 142 |
+
- live 图像超过 `max_live_images`(默认 16)时,把最旧的裁到预算的一半(滞回,减少前缀变化);历史关键帧从不裁剪。
|
| 143 |
+
- 一张图就是一个 JPEG(quality 90);发给模型的字节和 `images/` 下存的文件完全相同。
|
| 144 |
+
|
| 145 |
+
**记忆模式**(`--memory`):
|
| 146 |
+
|
| 147 |
+
| 模式 | 下一次尝试看到什么 | 用途 |
|
| 148 |
+
|---|---|---|
|
| 149 |
+
| `none` | 什么都没有;提示词里也不提"多次尝试",每次请求与第 1 次完全相同 | 独立重来,测 pass@k^iid |
|
| 150 |
+
| `full` | 之前全部尝试 | 主条件 |
|
| 151 |
+
| `last` | 只有最近一次 | 记忆长度消融 |
|
| 152 |
+
| `mismatched` | 另一个实例(不同布局和隐变量)的前 j−1 次尝试,措辞与 full 完全相同 | 错配对照:用的是具体信息还是"泛泛练习" |
|
| 153 |
+
|
| 154 |
+
mismatched 的 donor:`--donor-run DIR` 复用一个已跑完的 full 运行(按种子循环错位配对,保证 donor ≠ 自己;不用再付一次钱);
|
| 155 |
+
不给时自动用同一后端、memory=full 在 `seed + 10000` 上先跑一遍 donor(存到运行目录下 `donors/`)。
|
| 156 |
+
|
| 157 |
+
**早停与 F0**:默认(`--early-stop auto`)F1/F2 在首次成功时结束 run;F0 不早停、跑满 k 次——否则"还有下一次尝试"本身就泄露了"上次失败"。
|
| 158 |
+
|
| 159 |
+
**协议**:`cross` 每次尝试前 `reset_instance`(同布局、同隐变量)。`within` 只在开始重置一次;`done` 结束一个分段:
|
| 160 |
+
(若任务定义 `go_home()` 先调用它,L6 有)→ 保持 20 个控制步 → `outcome()`;未成功且未到终止条件(`outcome["terminal"]` 或
|
| 161 |
+
`outcome["overshoot"]`,或任务的 `is_terminal(out)`)就带着反馈从当前状态继续。within 下各记忆模式的语义同上(none = 每段都清空上下文)。
|
| 162 |
+
|
| 163 |
+
## 5. 后端
|
| 164 |
+
|
| 165 |
+
- **`OpenAIResponsesBackend`**(`--backend openai`):`client.responses.create(model="gpt-6-astra", instructions, input, tools,
|
| 166 |
+
tool_choice="auto", parallel_tool_calls=False, store=False, include=["reasoning.encrypted_content"], reasoning={"effort": ...})`。
|
| 167 |
+
- 无状态:每次请求重发完整(裁剪后的)上下文;上一轮返回的 reasoning 项(加密内容)原样回放,模型在一次尝试内保留思路。
|
| 168 |
+
- effort 校验:gpt-6-astra 只接受 low / medium / high / xhigh / max(不支持 none)。
|
| 169 |
+
- 缓存:自动把 `prompt_cache_key` 设为 `lffbench:<task>:<seed>`;默认在"历史项末尾"和"最新输入末尾"打显式
|
| 170 |
+
`prompt_cache_breakpoint`(openai SDK 3.24 的字段,gpt-5.6 以后支持)。网关不认这个字段时用 `--cache-breakpoints none`。
|
| 171 |
+
`--prompt-cache-options '{"ttl":"30m"}'`、`--prompt-cache-retention 24h`、`--service-tier`、`--extra-body` 透传。
|
| 172 |
+
- 用量:记录 input / cached / cache_write / output / reasoning tokens 和每次调用的墙钟延迟。
|
| 173 |
+
- **`ScriptedBackend`**(`--backend scripted --scripted-policy adaptive|naive|oracle|blind`):任务自己的 `execute(inst, params)`
|
| 174 |
+
在工作线程里跑,`task.sk` 换成代理,每个 `Skills` 原语变成一次 schema 合法的工具调用交给 harness 在主线程执行
|
| 175 |
+
(队列交接,同一时刻只有一个线程碰 MuJoCo)。参数来自任务的 `default/adapt/blind/oracle_params`,只看记忆模式允许的历史、
|
| 176 |
+
只看反馈粒度允许的字段(F2 结构化测量 / F1 成功标志 / F0 无;看不够就退回 blind 规则)。它读实例布局(特权),只用来测管线。
|
| 177 |
+
支持实现了 `execute` 的 cross 任务;within 任务和只重写了 `run_scripted` 的任务不支持(会报错说明)。
|
| 178 |
+
- **`ChatCompletionsBackend`**(`--backend chat --chat-base-url http://127.0.0.1:8765/v1 --chat-model ...`):OpenAI 兼容
|
| 179 |
+
Chat Completions + function calling,用于本地开源 VLM(见 §8)或任何 vLLM / SGLang 端点。live 图像上限降到 4。
|
| 180 |
+
|
| 181 |
+
## 6. 怎么接 GPT-6(需要用户提供)
|
| 182 |
+
|
| 183 |
+
1. `OPENAI_API_KEY`(必需),可选 `OPENAI_BASE_URL`(网关 / 代理)。本机没有 key,代码从未发过真实请求。
|
| 184 |
+
2. 账号对 `gpt-6-astra` 的访问权限和 Tier(Tier 1 限额 500 RPM / 500K TPM;单个 run 串行,每次调用 ≤ 几十 K token,Tier 1 够用)。
|
| 185 |
+
3. Python 包:`setup/install.sh` 建的 venv 里直接装了 `openai==3.24.0`。(原开发机的 libero-cpu venv 没有 `openai`,
|
| 186 |
+
它装在一个 `pip install --target` 目录里,由环境变量 `LFF_OPENAI_SDK_DIR` 指定;后端在 `import openai` 失败时把该目录
|
| 187 |
+
**追加**到 `sys.path` 末尾,venv 里已有的包始终优先。)
|
| 188 |
+
4. 第一次真跑建议:`--n 2 --k 3 --effort low --dump-requests 5`,看 `requests/*.json`(图像已省略)和 `events.jsonl` 里的
|
| 189 |
+
`llm_call.usage`,确认网关接受 `prompt_cache_breakpoint` / `include` 等字段后再放大。
|
| 190 |
+
5. 并行:一个进程一个 MuJoCo 环境、串行跑实例;要并行就按 `--seeds` 切分开多个进程(每个进程 `OMP_NUM_THREADS=1`)。
|
| 191 |
+
6. 代理(实测):本机环境变量里有 `HTTPS_PROXY=http://127.0.0.1:1080` 和 `ALL_PROXY=socks5h://127.0.0.1:1080`。openai SDK 3.x
|
| 192 |
+
底层的 httpx2 只要看到 socks 代理变量就要 `socksio`,否则建客户端时直接 ImportError;我已把 `socksio==1.0.0` 装进同一目录,
|
| 193 |
+
现在在这些变量存在时能正常建客户端(实测)。真实请求会走 `HTTPS_PROXY`;能否经这个代理到达 OpenAI / 你的网关没测(没有 key)。
|
| 194 |
+
|
| 195 |
+
## 7. 日志与指标
|
| 196 |
+
|
| 197 |
+
运行目录 `runs/agent/<task>/<时间>_<backend>_<memory>_<feedback>[_tag]/`:
|
| 198 |
+
- `config.json`:命令行、harness 配置、后端配置、任务信息。
|
| 199 |
+
- `events.jsonl`:`run_start`(实例参数,去掉 `_` 开头的私有键)、`llm_call`(延迟、usage、成本估计、模型文本、reasoning 摘要、
|
| 200 |
+
工具调用、请求大小;dry run 时加 `dry_run_request`)、`tool_call`(参数、报告、仿真墙钟、仿真步数)、`observation`(图像路径、本体)、
|
| 201 |
+
`attempt_end`(outcome 全字段、给模型看的反馈、F2 反馈、结束原因、done 理由、自我诊断、显示了哪些历史、关键帧路径、动作摘要、
|
| 202 |
+
该尝试的 LLM 延迟和仿真时间)、`run_end`(run 级汇总)、`llm_error`。
|
| 203 |
+
- `images/seed<s>/a<attempt>_s<step>_<n>_<cam>.jpg`:模型看到的每一张图。
|
| 204 |
+
- `summary.json`:每个 run 的 `first_success`、`success_by_attempt`、残差(outcome 里所有 `*_err`)、token、成本、延迟;以及汇总:
|
| 205 |
+
`succ_at`(j = 1..k,按 run 计)+ Wilson 95% 区间、`attempt1_success`、首次成功尝试数均值 / 中位数、
|
| 206 |
+
`pass_at_k_iid_analytic = 1 − (1 − p1)^k`、`repeated_action_rate`(失败后下一次动作序列与上次相同(1 cm 取整)的比例,
|
| 207 |
+
"同错复犯"的通用近似)、每 run 调用数 / 延迟 / token / 成本、缓存命中率。
|
| 208 |
+
- ΔICL:正式算法是同种子配对的 `succ@k(full) − succ@k(none)`(`scripts/agent_compare.py`,配对 bootstrap 区间、不一致对计数);
|
| 209 |
+
`delta_icl_vs_analytic_iid` 只是用本组 attempt-1 成功率算的便宜参照。
|
| 210 |
+
|
| 211 |
+
## 8. 成本 / 延迟估算方法
|
| 212 |
+
|
| 213 |
+
- 真实运行:成本 = Σ调用 [(input − cached − cache_write)·$10 + cache_write·$12.5 + cached·$1 + output·$50] / 1e6
|
| 214 |
+
(gpt-6-astra 价格,>272K 输入时输入 ×2、输出 ×1.5;见 `cost.py`);延迟直接用记录的每次调用墙钟。`scripts/agent_cost.py <运行目录>`。
|
| 215 |
+
- 跑之前:用 scripted 后端加 `--dry-run-payload` 跑同一配置,记录每次��用如果发给 GPT-6 的请求大小,再
|
| 216 |
+
`scripts/agent_cost.py <dry run 目录> --out-tokens 1500 --latency 20 --calls-scale 2` 外推。假设(未验证):图像按 32px patch
|
| 217 |
+
每 patch 1 token 计(512² ≈ 256 token);文本 4 字符 ≈ 1 token;同一尝试内上一调用的输入全部命中缓存、每次尝试第一调用全不命中(偏保守);
|
| 218 |
+
scripted 的调用次数是 LLM 的下限(LLM 还会看图、反投影、检查),用 `--calls-scale` 放大;每次调用输出 token 和延迟按参数给
|
| 219 |
+
(RoboICL 实测 GPT-6 Astra 每次调用 30–50 s,那是 50–90K 输入、high/xhigh 时的数)。
|
| 220 |
+
- 本机 dry run 实测数字见 §10。
|
| 221 |
+
|
| 222 |
+
## 9. 已知限制
|
| 223 |
+
|
| 224 |
+
- **l5_slide_to_target 的绿色目标区在图像里看不见(实测,任务侧问题,未改任务文件)**:`apply_instance` 把 zone 的碰撞关掉了,
|
| 225 |
+
但它是 free joint,`settle` 期间直接穿过桌面掉下去(reset 后 z ≈ 0.81),agentview 和腕部图里都没有绿色区域。
|
| 226 |
+
scripted 测试不受影响(它只看 F2 数字),但 VLM 智能体只能靠 F2 的文字找目标——F0/F1 条件下这个任务对 VLM 不可解。
|
| 227 |
+
需要任务作者把 zone 固定住(例如不加 free joint、或每步把它放回 / 设 gravcomp / 设为 mocap)。
|
| 228 |
+
- l5 的 scripted 执行里第一个 `move_to`(到推杆起点上方 x≈−0.42, z≈1.02)每次都跑满 250 步(12.5 s 仿真)仍差约 2.5 cm 报 `NOT reached`,
|
| 229 |
+
下一步下降时又到位了;这是 `Skills.move_to` 在靠近基座处的行为,不是 harness 的问题,但 VLM 会在报告里看到 `NOT reached`。
|
| 230 |
+
- 渲染:每步两张 512² 图(OSMesa CPU)约 0.5 s;本机负载高时更慢。仿真时间对比 LLM 延迟可以忽略。
|
| 231 |
+
- 一个 run 内串行调用模型;没有实现 async tool calling / mid-turn steering / WebSocket(Ultrafast 推荐)。
|
| 232 |
+
- 没有实现"每次尝试后单独问一次模型失败原因"(会多一次调用);自报原因来自每次新尝试开头的那 1–3 句(`diagnosis`)。
|
| 233 |
+
- `ScriptedBackend` 不支持 within 协议任务(L2 / L3-within / L5-B / L6 的 scripted 参照写在各自的 `run_scripted` 里,
|
| 234 |
+
不是 `execute(params)`);within 协议逻辑用假任务做了单测。
|
| 235 |
+
- 工具里没有 `wait`;scripted 代理遇到 `Skills.hold` 直接执行并计数(`backend_meta.untooled_hold_steps`)。
|
| 236 |
+
- 图像 token 的计法、GPT-6 每次调用的延迟都是假设,第一次真跑后用 `usage` 和 `latency_s` 校准。
|
| 237 |
+
- 本地开源 VLM 后端:见 §11。
|
| 238 |
+
|
| 239 |
+
**任务作者可选的钩子**(harness 会自动使用,没有就跳过):`agent_instruction(inst, variant)`、`agent_object_names`、
|
| 240 |
+
`on_agent_tool(inst, name, args, report)`(每次工具调用后,可用于注入)、`drain_events()`(事件文本进报告)、
|
| 241 |
+
`go_home()`(每次尝试结束、测 outcome 之前调用)、`is_terminal(out)` 或 `outcome["terminal"]`(within 不可恢复失败)、
|
| 242 |
+
`feedback(..., indirect=bool)`(按指令写法改写反馈)。
|
| 243 |
+
|
| 244 |
+
## 10. 测试与实测结果(2026-10-06,本机实测,8 核负载 30–40)
|
| 245 |
+
|
| 246 |
+
单元测试(`source run_env.sh` 后 `python -m pytest -q tests/test_agent_*.py`):
|
| 247 |
+
- `test_agent_payload.py` 6 项通过:请求结构、strict 工具、图像 data URL 能解码成 512² JPEG、缓存断点位置、effort 校验、
|
| 248 |
+
无 key 报错;**真实 openai SDK 3.24 + 进程内 mock HTTP 传输**的两轮往返(URL `…/v1/responses`、`Bearer` 头、body、usage
|
| 249 |
+
解析含 cache_write、reasoning 加密项回放、function_call / function_call_output 的 call_id 配对);chat 后端消息格式。
|
| 250 |
+
- `test_agent_protocol.py` 9 项通过(假任务、无仿真):full / none / last / mismatched、F0 / F1 / F2、F0 不早停、within 不重置、
|
| 251 |
+
历史前缀只追加、关键帧选择、配对 ΔICL。
|
| 252 |
+
- `test_agent_sim.py` 5 项通过(单独 143 s;协调者改了 `Skills.move_to` 的 yaw 取模之后,三个文件 20 项一起重跑,305 s,全部通过):像素↔世界往返、bias 隐藏、工具报错 / 裁剪 / locate 门控 / 接触检测、
|
| 253 |
+
**ScriptedBackend 在 l5_slide_to_target 上 n=3、k=5 端到端**、mismatched 自动 donor。
|
| 254 |
+
|
| 255 |
+
端到端运行(留在 `runs/agent/l5_slide_to_target/` 下,可以直接看图和 events):
|
| 256 |
+
|
| 257 |
+
| 运行 | succ@1..5 | 首次成功(seed 1000/1001/1002) | 每 run 调用数 | 每 run 仿真 + 渲染墙钟 |
|
| 258 |
+
|---|---|---|---|---|
|
| 259 |
+
| `20261006-060757_scripted-adaptive_full_F2_e2e` | 0.33 / 0.67 / 1 / 1 / 1 | 3 / 2 / 1 | 12 | 15.5 s |
|
| 260 |
+
| `20261006-060913_scripted-adaptive_none_F2_e2e` | 0.33 / 0.33 / 0.33 / 0.33 / 0.33 | – / – / 1 | 22 | 16.2 s |
|
| 261 |
+
|
| 262 |
+
- 经工具接口跑的 scripted adaptive 与任务自己的参照 rollout(`results/l5_slide_to_target/validate.json`)**逐次一致**:
|
| 263 |
+
8 次尝试的推速完全相同,停止误差 along_err 相同到 0.1 mm(如 seed 1000:+5.22 / −1.14 / −0.49 cm)。说明工具接口足以表达
|
| 264 |
+
这个任务的参照策略,bias / 物理没有被 harness 改变。
|
| 265 |
+
- memory=none 时 scripted 策略每次都用默认推速,结果完全重复(`repeated_action_rate` = 1.0),正好是"独立重来"的退化情形;
|
| 266 |
+
`agent_compare.py` 给出 ΔICL = 1.0 − 0.33 = 0.67(n=3,bootstrap 区间 [0, 1],只是管线演示)。
|
| 267 |
+
- dry run 请求大小(`agent_cost.py`):每次调用约 4.7K 输入 token(估计:文本 /4 + 每张 512² 图 256 token),同一尝试内
|
| 268 |
+
约 78% 可命中缓存;第 2 次尝试首个请求 6 张图(4 关键帧 + 2 实时),到尝试末尾约 16 张。
|
| 269 |
+
估计成本(gpt-6-astra 价格,**输出 token 和延迟是假设**):每次调用输出 1500 token、20 s 时,每 run 约 $1.1、API 时间约 4 分钟;
|
| 270 |
+
按 LLM 调用数是 scripted 的 2 倍算,约 $2.1 / run、8 分钟;输出 4000 token、40 s 时约 $5.1 / run、16 分钟。
|
| 271 |
+
成本主要在输出(reasoning)token,不在图像。一组条件 20 个实例 ≈ $40–100;ΔICL 至少要 full + none 两组。
|
| 272 |
+
|
| 273 |
+
另外用 scripted 后端在 **l1_bias_place**(别人刚写的 L1 任务,cross 协议)上跑了 n=2、k=5 的兼容性检查(运行目录在 scratch,未保留):
|
| 274 |
+
两个种子都在第 2 次尝试成功(第 1 次 F2 反馈"夹爪在奶酪中心右侧 3.9 cm、后方 1.4 cm",adaptive 据此补偿 offset),
|
| 275 |
+
0 个错误——harness 不需要为 L1 做任何改动;L1 作者的 `TrackedSkills` 记录、bias 都经工具调用照常生效。
|
| 276 |
+
|
| 277 |
+
## 11. 本地开源 VLM 后端(Qwen3-VL-8B-Instruct,PPU)
|
| 278 |
+
|
| 279 |
+
能跑(实测)。由子代理在约 1 小时内做通:`scripts/qwen_vl_server.py` + `scripts/qwen_vl_server.sh`(OpenAI 兼容
|
| 280 |
+
`/v1/chat/completions`,支持工具调用 / 多图 / 多轮),用系统 python3.12(torch 2.6 PPU 版)+ 单独目录
|
| 281 |
+
`/mnt/cpfs/workspace/env/qwen3vl-ppu-overlay`(只放 transformers 4.57.6 / tokenizers 0.22.1 / huggingface_hub 0.36.0,
|
| 282 |
+
只对服务进程加 PYTHONPATH,不改任何已有环境)。PPU 上 SDPA 自带 GQA 在解码步会报错,服务里改成先展开 K/V 头再算(`--sdpa-native-gqa` 可恢复)。
|
| 283 |
+
|
| 284 |
+
```bash
|
| 285 |
+
nohup bash scripts/qwen_vl_server.sh --port 8765 --warmup > logs/qwen_vl_server.log 2>&1 & # 等日志出现 "serving ..."
|
| 286 |
+
python scripts/run_agent.py --task l5_slide_to_target --backend chat --chat-base-url http://127.0.0.1:8765/v1 \
|
| 287 |
+
--chat-model Qwen3-VL-8B-Instruct --memory full --feedback F2 --n 2 --k 3 --max-steps 15 --keyframes 3
|
| 288 |
+
kill <服务 PID> # 用完停掉,显存约 18 GB
|
| 289 |
+
```
|
| 290 |
+
- 加载:页缓存热时权重 18 s(本次实测);冷读 CPFS 约 6.5 分钟(子代理实测 385 s)。
|
| 291 |
+
- 端到端实测(`runs/agent/l5_slide_to_target/20261006-061100_chat_full_F2_qwen_smoke`,n=2、k=3、每次尝试 15 步上限):
|
| 292 |
+
81 次模型调用、0 次后端错误、0 次格式错误的工具调用;每次调用延迟均值 5.1 s(p50 4.9 s,p95 9.5 s),
|
| 293 |
+
输入均值 6.3K token(最大 10.3K),输出均值 113 token;用到了 move_to / push / close_gripper / get_observation / pixel_to_world / done,
|
| 294 |
+
新尝试开头都写了对上一次的评估(`diagnosis`)。成功 0/2:模型反复 `move_to(0, 0, 0.9)`、没有先定位方块,
|
| 295 |
+
加上 l5 的目标区本来就看不见(§9)。这只说明**管线对真实 VLM 是通的**,不说明 8B 模型的能力;之后我在 system prompt 里加了
|
| 296 |
+
"物体位置不会直接给出,用 pixel_to_world 从图像定位"一句(这次运行之后加的,未再测)。
|
| 297 |
+
- 用途:在花 GPT-6 的钱之前,先用本地模型检查提示词、工具描述、日志和指标。
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/agent/audit_state.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Host-only, read-only physical evidence for CS/IR review (opt-in).
|
| 2 |
+
|
| 3 |
+
Never call outcome(), forward(), step() or a task measurement here: those can
|
| 4 |
+
settle physics or consume event cursors. Samples are at control-step boundaries,
|
| 5 |
+
not every MuJoCo substep. No sample itself is an error or repair classification.
|
| 6 |
+
"""
|
| 7 |
+
import json
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def _json_value(value):
|
| 11 |
+
if hasattr(value, "tolist"):
|
| 12 |
+
return value.tolist()
|
| 13 |
+
raise TypeError(f"Unsupported audit value: {type(value).__name__}")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class AuditStateRecorder:
|
| 17 |
+
def __init__(self, path):
|
| 18 |
+
self.path = path
|
| 19 |
+
self.env = None
|
| 20 |
+
self.original_step = None
|
| 21 |
+
self.wrapped_step = None
|
| 22 |
+
self.sequence = 0
|
| 23 |
+
|
| 24 |
+
def write(self, record):
|
| 25 |
+
# A separate host-side file, never copied into the agent's sandbox.
|
| 26 |
+
with open(self.path, "a", encoding="utf-8") as stream:
|
| 27 |
+
stream.write(json.dumps(record, separators=(",", ":"), default=_json_value) + "\n")
|
| 28 |
+
|
| 29 |
+
def detach(self):
|
| 30 |
+
if self.env is not None and self.env.step is self.wrapped_step:
|
| 31 |
+
self.env.step = self.original_step
|
| 32 |
+
self.env = None
|
| 33 |
+
|
| 34 |
+
def attach(self, env, attempt, command_step):
|
| 35 |
+
self.detach()
|
| 36 |
+
self.env, self.attempt, self.command_step = env, attempt, command_step
|
| 37 |
+
self.original_step = env.step
|
| 38 |
+
original_step = self.original_step
|
| 39 |
+
model = env.sim.model
|
| 40 |
+
self.write(dict(kind="attempt_start", schema="lff-audit-state-1", attempt=attempt,
|
| 41 |
+
sampling="after_env_step", bodies=[model.body_id2name(i) for i in range(model.nbody)],
|
| 42 |
+
geoms=[model.geom_id2name(i) for i in range(model.ngeom)]))
|
| 43 |
+
|
| 44 |
+
def wrapped(action):
|
| 45 |
+
result = original_step(action)
|
| 46 |
+
if self.env is env and self.wrapped_step is wrapped:
|
| 47 |
+
self.sample("control_step")
|
| 48 |
+
return result
|
| 49 |
+
|
| 50 |
+
self.wrapped_step = wrapped
|
| 51 |
+
env.step = wrapped
|
| 52 |
+
self.sample("initial")
|
| 53 |
+
|
| 54 |
+
def sample(self, phase):
|
| 55 |
+
data = self.env.sim.data
|
| 56 |
+
self.sequence += 1
|
| 57 |
+
self.write(dict(kind="state", sequence=self.sequence, attempt=self.attempt,
|
| 58 |
+
command_step=self.command_step(), phase=phase, sim_time=float(data.time),
|
| 59 |
+
qpos=data.qpos.tolist(), qvel=data.qvel.tolist(),
|
| 60 |
+
body_xyz=data.body_xpos.tolist(), body_quat_wxyz=data.body_xquat.tolist(),
|
| 61 |
+
contacts=[[int(c.geom1), int(c.geom2), float(c.dist)]
|
| 62 |
+
for c in data.contact[:data.ncon]]))
|
| 63 |
+
|
| 64 |
+
def boundary(self, task, phase):
|
| 65 |
+
"""Capture after skill callbacks too (some injections happen after env.step).
|
| 66 |
+
|
| 67 |
+
Copy existing event lists without calling monitor/outcome methods or
|
| 68 |
+
advancing their cursors. These are raw observations, not adjudications.
|
| 69 |
+
"""
|
| 70 |
+
self.sample(phase)
|
| 71 |
+
streams = {}
|
| 72 |
+
for name, obj in (("task", task), ("skills", getattr(task, "sk", None)),
|
| 73 |
+
("monitor", getattr(task, "mon", None))):
|
| 74 |
+
attrs = obj if isinstance(obj, dict) else getattr(obj, "__dict__", {})
|
| 75 |
+
for key in ("events", "turns", "strikes", "box_moves", "lifts", "grasp_tries"):
|
| 76 |
+
if isinstance(attrs.get(key), list):
|
| 77 |
+
streams[f"{name}.{key}"] = attrs[key]
|
| 78 |
+
self.write(dict(kind="event_snapshot", attempt=self.attempt,
|
| 79 |
+
command_step=self.command_step(), phase=phase, streams=streams))
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/agent/harness.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Protocol controller: runs a backend on task instances, attempt by attempt.
|
| 2 |
+
|
| 3 |
+
cross protocol : reset to the same instance (same layout + hidden variables) before every attempt
|
| 4 |
+
within protocol: one continuous episode; each `done` call closes a segment ("attempt") that is checked;
|
| 5 |
+
the agent continues from the current state if it failed and budget remains
|
| 6 |
+
Both protocols pack finished attempts the same way (keyframes <= 4, action summary, feedback F0/F1/F2) and
|
| 7 |
+
show them according to the memory mode (none / full / last / mismatched).
|
| 8 |
+
"""
|
| 9 |
+
import time
|
| 10 |
+
from dataclasses import asdict, dataclass, field
|
| 11 |
+
|
| 12 |
+
from .context import (FEEDBACK_LEVELS, MEMORY_MODES, AttemptRecord, Conversation, PromptBuilder, StepRecord,
|
| 13 |
+
pick_keyframes, select_history, summarize_actions)
|
| 14 |
+
from .cost import call_cost, estimate_request_tokens
|
| 15 |
+
from .metrics import run_summary
|
| 16 |
+
from .backends.base import AttemptInfo, RunInfo
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@dataclass
|
| 20 |
+
class HarnessConfig:
|
| 21 |
+
memory: str = "full"
|
| 22 |
+
feedback: str = "F2"
|
| 23 |
+
k: int = None # attempts (cross) / done calls (within); default task.max_attempts
|
| 24 |
+
image_res: int = 512
|
| 25 |
+
keyframe_res: int = None # default = image_res
|
| 26 |
+
n_keyframes: int = 4
|
| 27 |
+
cams: tuple = ("agentview", "wrist")
|
| 28 |
+
auto_obs: bool = True # send new images after every action tool
|
| 29 |
+
max_steps: int = 30 # tool calls per attempt
|
| 30 |
+
max_no_tool: int = 3 # consecutive replies without a tool call before the attempt is ended
|
| 31 |
+
privileged_locate: bool = False
|
| 32 |
+
grasp_report: str = "bool" # "bool" | "name" | "none"
|
| 33 |
+
instruction: str = "direct" # "direct" | "indirect"
|
| 34 |
+
early_stop: str = "auto" # "auto" (stop at first success unless F0), "yes", "no"
|
| 35 |
+
settle_within: int = 20 # control steps held still before checking a within-protocol segment
|
| 36 |
+
jpeg_quality: int = 90
|
| 37 |
+
save_images: bool = True
|
| 38 |
+
model_for_cost: str = "gpt-6-astra"
|
| 39 |
+
extra: dict = field(default_factory=dict)
|
| 40 |
+
|
| 41 |
+
def validate(self):
|
| 42 |
+
assert self.memory in MEMORY_MODES, self.memory
|
| 43 |
+
assert self.feedback in FEEDBACK_LEVELS, self.feedback
|
| 44 |
+
assert self.grasp_report in ("bool", "name", "none")
|
| 45 |
+
assert self.instruction in ("direct", "indirect")
|
| 46 |
+
assert self.early_stop in ("auto", "yes", "no")
|
| 47 |
+
assert 1 <= self.n_keyframes <= 4 or self.n_keyframes == 0
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def clean_inst(inst):
|
| 51 |
+
return {k: v for k, v in inst.items() if not str(k).startswith("_")}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class AgentHarness:
|
| 55 |
+
def __init__(self, task, backend, cfg: HarnessConfig, logger, payload_probe=None, executor_factory=None,
|
| 56 |
+
cam_axes=None):
|
| 57 |
+
cfg.validate()
|
| 58 |
+
self.task, self.backend, self.cfg, self.log = task, backend, cfg, logger
|
| 59 |
+
self.protocol = getattr(task, "protocol", "cross")
|
| 60 |
+
self.k = cfg.k or task.max_attempts
|
| 61 |
+
self.payload_probe = payload_probe # optional OpenAIResponsesBackend used only to size requests (dry run)
|
| 62 |
+
self.executor_factory = executor_factory # tests: build a fake executor instead of ToolExecutor
|
| 63 |
+
self._cam_axes = cam_axes
|
| 64 |
+
|
| 65 |
+
# ------------------------------------------------------------------ helpers
|
| 66 |
+
def instruction(self, inst):
|
| 67 |
+
hook = getattr(self.task, "agent_instruction", None)
|
| 68 |
+
if hook is not None:
|
| 69 |
+
return hook(inst, self.cfg.instruction)
|
| 70 |
+
if self.cfg.instruction == "indirect" and getattr(self.task, "instruction_indirect", ""):
|
| 71 |
+
return self.task.instruction_indirect
|
| 72 |
+
return self.task.instruction
|
| 73 |
+
|
| 74 |
+
def feedback(self, inst, out, level):
|
| 75 |
+
import inspect
|
| 76 |
+
fn = self.task.feedback
|
| 77 |
+
if "indirect" in inspect.signature(fn).parameters: # tasks that phrase feedback per instruction variant
|
| 78 |
+
return fn(inst, out, level, indirect=self.cfg.instruction == "indirect")
|
| 79 |
+
return fn(inst, out, level)
|
| 80 |
+
|
| 81 |
+
def early_stop(self):
|
| 82 |
+
if self.cfg.early_stop == "auto":
|
| 83 |
+
return self.cfg.feedback != "F0"
|
| 84 |
+
return self.cfg.early_stop == "yes"
|
| 85 |
+
|
| 86 |
+
def terminal(self, out):
|
| 87 |
+
hook = getattr(self.task, "is_terminal", None)
|
| 88 |
+
if hook is not None:
|
| 89 |
+
return bool(hook(out))
|
| 90 |
+
return bool(out.get("terminal") or out.get("overshoot"))
|
| 91 |
+
|
| 92 |
+
def _executor(self, inst):
|
| 93 |
+
if self.executor_factory is not None:
|
| 94 |
+
return self.executor_factory(self, inst)
|
| 95 |
+
from .tools import ToolExecutor
|
| 96 |
+
return ToolExecutor(self.task, inst, image_res=self.cfg.image_res, cams=self.cfg.cams,
|
| 97 |
+
privileged_locate=self.cfg.privileged_locate, grasp_report=self.cfg.grasp_report,
|
| 98 |
+
jpeg_quality=self.cfg.jpeg_quality, image_sink=self._sink)
|
| 99 |
+
|
| 100 |
+
def _sink(self, ref):
|
| 101 |
+
self._img_counter += 1
|
| 102 |
+
rel = f"seed{self._seed}/a{self._attempt}_s{self._step:02d}_{self._img_counter:03d}_{ref.camera}.jpg"
|
| 103 |
+
return self.log.save_image(ref, rel)
|
| 104 |
+
|
| 105 |
+
def _keyframe(self, ref):
|
| 106 |
+
"""Separate (possibly smaller) copy of an agentview frame for the history."""
|
| 107 |
+
from .images import ImageRef
|
| 108 |
+
kres = self.cfg.keyframe_res or self.cfg.image_res
|
| 109 |
+
kf = ImageRef(camera=ref.camera, array=ref.array, label=ref.label)
|
| 110 |
+
if kres == self.cfg.image_res:
|
| 111 |
+
kf.jpeg, kf.path = ref.jpeg, ref.path
|
| 112 |
+
return kf
|
| 113 |
+
self._img_counter += 1
|
| 114 |
+
rel = f"seed{self._seed}/a{self._attempt}_key_{self._img_counter:03d}_{ref.camera}.jpg"
|
| 115 |
+
return self.log.save_image(kf, rel, res=kres)
|
| 116 |
+
|
| 117 |
+
def prompts(self, executor):
|
| 118 |
+
if self._cam_axes is None:
|
| 119 |
+
from . import camera as C
|
| 120 |
+
self._cam_axes = {c: C.describe_axes(self.task.env, c, self.cfg.image_res) for c in C.CAMERAS}
|
| 121 |
+
names = getattr(self.task, "agent_object_names", None) or list(self.task.env.objects_dict)
|
| 122 |
+
return PromptBuilder(self.task, self.protocol, self.k, self.cfg.memory, self.cfg.feedback, self.cfg.image_res,
|
| 123 |
+
self._cam_axes, privileged_locate=self.cfg.privileged_locate, object_names=names,
|
| 124 |
+
grasp_report=self.cfg.grasp_report, cams=self.cfg.cams)
|
| 125 |
+
|
| 126 |
+
# ------------------------------------------------------------------ run
|
| 127 |
+
def run_instance(self, seed, donor=None):
|
| 128 |
+
"""donor: AttemptRecords of another instance (memory=mismatched). Returns (summary, records)."""
|
| 129 |
+
task, cfg = self.task, self.cfg
|
| 130 |
+
inst = task.sample_instance(seed)
|
| 131 |
+
self._seed, self._attempt, self._step, self._img_counter = seed, 0, 0, 0
|
| 132 |
+
self._llm_calls = []
|
| 133 |
+
t_run = time.time()
|
| 134 |
+
sim_wall = 0.0
|
| 135 |
+
info = RunInfo(task=task, inst=inst, seed=seed, k=self.k, protocol=self.protocol, feedback=cfg.feedback,
|
| 136 |
+
memory=cfg.memory)
|
| 137 |
+
self.backend.begin_run(info)
|
| 138 |
+
self.log.event("run_start", seed=seed, inst=clean_inst(inst), task=task.name, protocol=self.protocol, k=self.k,
|
| 139 |
+
memory=cfg.memory, feedback=cfg.feedback, donor_seed=donor[0].seed if donor else None)
|
| 140 |
+
records, executor, status = [], None, "ok"
|
| 141 |
+
for a in range(1, self.k + 1):
|
| 142 |
+
self._attempt, self._step = a, 0
|
| 143 |
+
if self.protocol == "cross" or executor is None:
|
| 144 |
+
t0 = time.time()
|
| 145 |
+
task.reset_instance(inst)
|
| 146 |
+
executor = self._executor(inst)
|
| 147 |
+
sim_wall += time.time() - t0
|
| 148 |
+
visible = select_history(cfg.memory, records, donor)
|
| 149 |
+
rec, attempt_sim = self._attempt_loop(inst, seed, a, visible, executor,
|
| 150 |
+
continuing=self.protocol == "within" and a > 1)
|
| 151 |
+
sim_wall += attempt_sim
|
| 152 |
+
records.append(rec)
|
| 153 |
+
if rec.ended_by == "backend_error":
|
| 154 |
+
status = "error"
|
| 155 |
+
break
|
| 156 |
+
if rec.success and self.early_stop():
|
| 157 |
+
break
|
| 158 |
+
if self.protocol == "within" and (rec.success or self.terminal(rec.outcome)):
|
| 159 |
+
break
|
| 160 |
+
self.backend.end_run()
|
| 161 |
+
summ = run_summary(seed, records, self.k, status=status, llm_calls=self._llm_calls,
|
| 162 |
+
extra=dict(sim_wall_s=round(sim_wall, 2), wall_s=round(time.time() - t_run, 2),
|
| 163 |
+
donor_seed=donor[0].seed if donor else None))
|
| 164 |
+
self.log.event("run_end", **summ)
|
| 165 |
+
summ["_llm_calls"] = self._llm_calls
|
| 166 |
+
return summ, records
|
| 167 |
+
|
| 168 |
+
def _attempt_loop(self, inst, seed, a, visible, ex, continuing):
|
| 169 |
+
cfg, task, backend = self.cfg, self.task, self.backend
|
| 170 |
+
P = self.prompts(ex)
|
| 171 |
+
tools = self.tool_specs()
|
| 172 |
+
conv = Conversation(P.system_prompt())
|
| 173 |
+
backend.begin_attempt(AttemptInfo(attempt=a, history=visible, continuing=continuing))
|
| 174 |
+
sim_t = 0.0
|
| 175 |
+
t0 = time.time()
|
| 176 |
+
obs0 = ex.observe(label="start")
|
| 177 |
+
sim_t += time.time() - t0
|
| 178 |
+
conv.add_user(P.history_parts(self.instruction(inst), visible), live=False)
|
| 179 |
+
conv.add_user(P.current_parts(a, obs0, ex.proprio(), continuing), live=True)
|
| 180 |
+
steps, diagnosis, done_reason, ended_by = [], None, None, None
|
| 181 |
+
n_calls, no_tool = 0, 0
|
| 182 |
+
while ended_by is None:
|
| 183 |
+
if len(steps) >= cfg.max_steps:
|
| 184 |
+
ended_by = "step_budget"
|
| 185 |
+
break
|
| 186 |
+
try:
|
| 187 |
+
resp = backend.act(conv, tools)
|
| 188 |
+
except Exception as e: # API failure after retries, crashed scripted policy, ...
|
| 189 |
+
self.log.event("llm_error", seed=seed, attempt=a, call=n_calls + 1, error=repr(e)[:4000])
|
| 190 |
+
ended_by = "backend_error"
|
| 191 |
+
break
|
| 192 |
+
n_calls += 1
|
| 193 |
+
call_rec = self._log_llm_call(seed, a, n_calls, resp, conv, tools)
|
| 194 |
+
self._llm_calls.append(call_rec)
|
| 195 |
+
if n_calls == 1 and resp.text:
|
| 196 |
+
diagnosis = resp.text
|
| 197 |
+
conv.add_assistant(resp.text, resp.tool_calls, raw=resp.raw, backend=backend.name)
|
| 198 |
+
if not resp.tool_calls:
|
| 199 |
+
no_tool += 1
|
| 200 |
+
if no_tool >= cfg.max_no_tool:
|
| 201 |
+
ended_by = "no_tool_call"
|
| 202 |
+
break
|
| 203 |
+
conv.add_user(P.nudge(), live=True)
|
| 204 |
+
continue
|
| 205 |
+
no_tool = 0
|
| 206 |
+
acted = None
|
| 207 |
+
for tc in resp.tool_calls:
|
| 208 |
+
self._step = len(steps) + 1
|
| 209 |
+
res = ex.call(tc.name, tc.raw_arguments or tc.arguments)
|
| 210 |
+
sim_t += res.wall_s
|
| 211 |
+
conv.add_tool_output(tc.id, tc.name, res.text())
|
| 212 |
+
backend.on_tool_result(tc, res)
|
| 213 |
+
st = StepRecord(step=self._step, name=tc.name, args=res.args, report=res.report, ok=res.ok,
|
| 214 |
+
wall_s=round(res.wall_s, 3), sim_steps=res.sim_steps)
|
| 215 |
+
steps.append(st)
|
| 216 |
+
if res.images:
|
| 217 |
+
conv.add_user(P.observation_parts(f"Images returned by get_observation (step {self._step})",
|
| 218 |
+
res.images, ex.proprio()), live=True)
|
| 219 |
+
if tc.name in ("move_to", "open_gripper", "close_gripper", "push") and res.ok:
|
| 220 |
+
acted = st
|
| 221 |
+
self.log.event("tool_call", seed=seed, attempt=a, step=self._step, call_id=tc.id, name=tc.name,
|
| 222 |
+
args=res.args, ok=res.ok, report=res.report, wall_s=round(res.wall_s, 3),
|
| 223 |
+
sim_steps=res.sim_steps, images=[i.path for i in res.images])
|
| 224 |
+
if res.ended:
|
| 225 |
+
done_reason = res.args.get("reason")
|
| 226 |
+
ended_by = "done"
|
| 227 |
+
break
|
| 228 |
+
if len(steps) >= cfg.max_steps:
|
| 229 |
+
break
|
| 230 |
+
if ended_by is None and acted is not None:
|
| 231 |
+
t1 = time.time()
|
| 232 |
+
if cfg.auto_obs:
|
| 233 |
+
obs = ex.observe(label=f"step{acted.step}")
|
| 234 |
+
conv.add_user(P.step_observation(acted.step, acted.name, obs, ex.proprio()), live=True)
|
| 235 |
+
acted.frame = next((o for o in obs if o.camera == "agentview"), obs[0])
|
| 236 |
+
else: # still keep an agentview frame for the history keyframes / logs
|
| 237 |
+
from .images import ImageRef
|
| 238 |
+
acted.frame = self._sink(ImageRef(camera="agentview", array=ex.render("agentview"),
|
| 239 |
+
label=f"step{acted.step}"))
|
| 240 |
+
sim_t += time.time() - t1
|
| 241 |
+
self.log.event("observation", seed=seed, attempt=a, step=acted.step,
|
| 242 |
+
images=[acted.frame.path] if not cfg.auto_obs else [o.path for o in obs],
|
| 243 |
+
proprio=ex.proprio())
|
| 244 |
+
meta = backend.end_attempt() or {}
|
| 245 |
+
# ------------------------------------------------------------ outcome + packing
|
| 246 |
+
t1 = time.time()
|
| 247 |
+
home = getattr(task, "go_home", None) # task-defined end-of-attempt motion (e.g. L6: arm out of view)
|
| 248 |
+
if home is not None and ended_by != "backend_error":
|
| 249 |
+
home()
|
| 250 |
+
if self.protocol == "within" and cfg.settle_within:
|
| 251 |
+
ex.sk.hold(cfg.settle_within)
|
| 252 |
+
out = task.outcome(inst)
|
| 253 |
+
from .images import ImageRef
|
| 254 |
+
self._step = 99
|
| 255 |
+
final = self._sink(ImageRef(camera="agentview", array=ex.render("agentview", cfg.keyframe_res or cfg.image_res),
|
| 256 |
+
label="end"))
|
| 257 |
+
sim_t += time.time() - t1
|
| 258 |
+
fb = self.feedback(inst, out, cfg.feedback)
|
| 259 |
+
fb_full = self.feedback(inst, out, "F2")
|
| 260 |
+
init_frame = next((o for o in obs0 if o.camera == "agentview"), None)
|
| 261 |
+
for s in steps:
|
| 262 |
+
if s.frame is not None and (cfg.keyframe_res or cfg.image_res) != cfg.image_res:
|
| 263 |
+
s.frame = self._keyframe(s.frame)
|
| 264 |
+
if init_frame is not None and (cfg.keyframe_res or cfg.image_res) != cfg.image_res:
|
| 265 |
+
init_frame = self._keyframe(init_frame)
|
| 266 |
+
kfs = pick_keyframes(steps, init_frame, final, cfg.n_keyframes) if cfg.n_keyframes else []
|
| 267 |
+
rec = AttemptRecord(seed=seed, attempt=a, steps=steps, keyframes=kfs, outcome=dict(out),
|
| 268 |
+
success=bool(out.get("success")), feedback=fb, done_reason=done_reason, diagnosis=diagnosis,
|
| 269 |
+
ended_by=ended_by, backend_meta=meta)
|
| 270 |
+
calls = [c for c in self._llm_calls if c["attempt"] == a]
|
| 271 |
+
self.log.event("attempt_end", seed=seed, attempt=a, success=rec.success, outcome=out, feedback_shown=fb,
|
| 272 |
+
feedback_f2=fb_full, ended_by=ended_by, done_reason=done_reason, diagnosis=diagnosis,
|
| 273 |
+
n_steps=len(steps), n_llm_calls=len(calls), backend_meta=meta,
|
| 274 |
+
history_shown=[(h.seed, h.attempt) for h in visible],
|
| 275 |
+
keyframes=[(c, r.path) for c, r in kfs], action_summary=summarize_actions(steps),
|
| 276 |
+
llm_latency_s=round(sum(c["latency_s"] for c in calls), 3), sim_wall_s=round(sim_t, 3))
|
| 277 |
+
return rec, sim_t
|
| 278 |
+
|
| 279 |
+
def tool_specs(self):
|
| 280 |
+
from .tools import tool_specs
|
| 281 |
+
names = getattr(self.task, "agent_object_names", None) or list(self.task.env.objects_dict)
|
| 282 |
+
return tool_specs(self.cfg.privileged_locate, names, self.cfg.image_res)
|
| 283 |
+
|
| 284 |
+
def _log_llm_call(self, seed, a, n, resp, conv, tools):
|
| 285 |
+
rec = dict(seed=seed, attempt=a, call=n, latency_s=round(resp.latency_s, 3), usage=resp.usage,
|
| 286 |
+
cost_usd=call_cost(resp.usage, self.cfg.model_for_cost) if resp.usage else None,
|
| 287 |
+
status=resp.status, error=resp.error, text=resp.text, reasoning_summary=resp.reasoning_summary,
|
| 288 |
+
reasoning_summary_status="recorded" if resp.reasoning_summary else "not_returned",
|
| 289 |
+
tool_calls=[dict(id=t.id, name=t.name, arguments=t.arguments) for t in resp.tool_calls],
|
| 290 |
+
request=resp.request_stats, conv_images=conv.n_images())
|
| 291 |
+
if self.payload_probe is not None: # dry run: size of the request GPT-6 would have received
|
| 292 |
+
stats = self.payload_probe.request_stats(self.payload_probe.build_request(conv, tools))
|
| 293 |
+
stats["est_input_tokens"] = estimate_request_tokens(stats, self.cfg.image_res)
|
| 294 |
+
rec["dry_run_request"] = stats
|
| 295 |
+
self.log.event("llm_call", **rec)
|
| 296 |
+
return rec
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def config_dict(cfg):
|
| 300 |
+
return asdict(cfg)
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/agent/metrics.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run-level metrics (design doc 02 §5): succ@k per run, attempt-1 success, first-success attempt,
|
| 2 |
+
fields for ΔICL = succ@k(with history) - pass@k_iid(independent retries), same-mistake (repeated
|
| 3 |
+
action) rate, residuals, tokens / cost / latency."""
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
from .context import wilson
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def run_summary(seed, records, k, status="ok", llm_calls=(), extra=None):
|
| 10 |
+
"""records: list[AttemptRecord] of one run (one instance)."""
|
| 11 |
+
succ = [bool(r.success) for r in records]
|
| 12 |
+
first = next((r.attempt for r in records if r.success), None)
|
| 13 |
+
fails = [r for r in records if not r.success]
|
| 14 |
+
pairs = [(a, b) for a, b in zip(records, records[1:]) if not a.success]
|
| 15 |
+
repeats = [a.action_signature() == b.action_signature() for a, b in pairs]
|
| 16 |
+
residuals = [{kk: v for kk, v in r.outcome.items() if kk.endswith("_err") and isinstance(v, (int, float))}
|
| 17 |
+
for r in records]
|
| 18 |
+
lat = [c.get("latency_s", 0.0) for c in llm_calls]
|
| 19 |
+
usage = {key: int(sum((c.get("usage") or {}).get(key, 0) or 0 for c in llm_calls))
|
| 20 |
+
for key in ("input_tokens", "cached_tokens", "cache_write_tokens", "output_tokens",
|
| 21 |
+
"reasoning_tokens")}
|
| 22 |
+
cost = [c.get("cost_usd") for c in llm_calls if c.get("cost_usd") is not None]
|
| 23 |
+
out = dict(seed=seed, status=status, k=k, n_attempts=len(records), success_by_attempt=succ,
|
| 24 |
+
first_success=first, success=first is not None, attempt1_success=bool(succ[0]) if succ else False,
|
| 25 |
+
ended_by=[r.ended_by for r in records], n_failed_attempts=len(fails),
|
| 26 |
+
repeated_action_pairs=int(sum(repeats)), failed_pairs=len(pairs), residuals=residuals,
|
| 27 |
+
n_llm_calls=len(llm_calls), llm_latency_s=float(sum(lat)), usage=usage,
|
| 28 |
+
cost_usd=float(sum(cost)) if cost else None,
|
| 29 |
+
n_tool_calls=int(sum(len(r.steps) for r in records)))
|
| 30 |
+
if extra:
|
| 31 |
+
out.update(extra)
|
| 32 |
+
return out
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def aggregate(runs, k):
|
| 36 |
+
ok = [r for r in runs if r["status"] == "ok"]
|
| 37 |
+
n = len(ok)
|
| 38 |
+
first = [r["first_success"] for r in ok]
|
| 39 |
+
curve, ci = [], []
|
| 40 |
+
for j in range(1, k + 1):
|
| 41 |
+
s = sum(1 for f in first if f is not None and f <= j)
|
| 42 |
+
curve.append(s / n if n else float("nan"))
|
| 43 |
+
ci.append(wilson(s, n))
|
| 44 |
+
p1 = curve[0] if curve else float("nan")
|
| 45 |
+
succ_first = [f for f in first if f is not None]
|
| 46 |
+
calls = [c for r in ok for c in r.get("_llm_calls", [])]
|
| 47 |
+
lat = np.array([c.get("latency_s", 0.0) for c in calls]) if calls else np.zeros(0)
|
| 48 |
+
pairs = sum(r["failed_pairs"] for r in ok)
|
| 49 |
+
tot = {key: int(sum(r["usage"].get(key, 0) for r in ok))
|
| 50 |
+
for key in ("input_tokens", "cached_tokens", "cache_write_tokens", "output_tokens", "reasoning_tokens")}
|
| 51 |
+
costs = [r["cost_usd"] for r in ok if r.get("cost_usd") is not None]
|
| 52 |
+
return dict(
|
| 53 |
+
n_runs=n, n_error_runs=len(runs) - n, k=k,
|
| 54 |
+
succ_at=curve, succ_at_ci95=ci, succ_at_k=curve[-1] if curve else float("nan"),
|
| 55 |
+
attempt1_success=p1,
|
| 56 |
+
# ΔICL needs pass@k of independent retries: measure it with --memory none on the same seeds and
|
| 57 |
+
# compare with scripts/agent_compare.py. The analytic value assumes i.i.d. attempts with the
|
| 58 |
+
# attempt-1 success rate of THIS run set (a cheaper but weaker reference).
|
| 59 |
+
pass_at_k_iid_analytic=1 - (1 - p1) ** k if n else float("nan"),
|
| 60 |
+
delta_icl_vs_analytic_iid=(curve[-1] - (1 - (1 - p1) ** k)) if n else float("nan"),
|
| 61 |
+
mean_first_success=float(np.mean(succ_first)) if succ_first else None,
|
| 62 |
+
median_first_success=float(np.median(succ_first)) if succ_first else None,
|
| 63 |
+
repeated_action_rate=(sum(r["repeated_action_pairs"] for r in ok) / pairs) if pairs else None,
|
| 64 |
+
llm_calls_per_run=float(np.mean([r["n_llm_calls"] for r in ok])) if ok else None,
|
| 65 |
+
llm_latency_mean_s=float(lat.mean()) if lat.size else None,
|
| 66 |
+
llm_latency_p50_s=float(np.percentile(lat, 50)) if lat.size else None,
|
| 67 |
+
llm_latency_p95_s=float(np.percentile(lat, 95)) if lat.size else None,
|
| 68 |
+
llm_latency_per_run_s=float(np.mean([r["llm_latency_s"] for r in ok])) if ok else None,
|
| 69 |
+
sim_wall_per_run_s=float(np.mean([r.get("sim_wall_s", 0.0) for r in ok])) if ok else None,
|
| 70 |
+
tool_calls_per_run=float(np.mean([r["n_tool_calls"] for r in ok])) if ok else None,
|
| 71 |
+
usage_total=tot,
|
| 72 |
+
cache_hit_rate=(tot["cached_tokens"] / tot["input_tokens"]) if tot["input_tokens"] else None,
|
| 73 |
+
cost_usd_total=float(sum(costs)) if costs else None,
|
| 74 |
+
cost_usd_per_run=float(np.mean(costs)) if costs else None,
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def paired_delta(with_runs, iid_runs, k, n_boot=10000, seed=0):
|
| 79 |
+
"""ΔICL = succ@k(with) - succ@k(iid) on the seeds both run sets share, with a paired bootstrap CI."""
|
| 80 |
+
a = {r["seed"]: r for r in with_runs if r["status"] == "ok"}
|
| 81 |
+
b = {r["seed"]: r for r in iid_runs if r["status"] == "ok"}
|
| 82 |
+
seeds = sorted(set(a) & set(b))
|
| 83 |
+
if not seeds:
|
| 84 |
+
return dict(n=0)
|
| 85 |
+
|
| 86 |
+
def ok(r):
|
| 87 |
+
return r["first_success"] is not None and r["first_success"] <= k
|
| 88 |
+
|
| 89 |
+
x = np.array([ok(a[s]) for s in seeds], float)
|
| 90 |
+
y = np.array([ok(b[s]) for s in seeds], float)
|
| 91 |
+
d = x - y
|
| 92 |
+
rng = np.random.default_rng(seed)
|
| 93 |
+
idx = rng.integers(0, len(d), size=(n_boot, len(d)))
|
| 94 |
+
boot = d[idx].mean(1)
|
| 95 |
+
return dict(n=len(seeds), succ_at_k_with=float(x.mean()), succ_at_k_iid=float(y.mean()), delta_icl=float(d.mean()),
|
| 96 |
+
ci95=[float(np.percentile(boot, 2.5)), float(np.percentile(boot, 97.5))],
|
| 97 |
+
discordant=dict(with_only=int(((x == 1) & (y == 0)).sum()), iid_only=int(((x == 0) & (y == 1)).sum())))
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/agent/runlog.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run directory: config.json, events.jsonl (one JSON object per line), images/, summary.json."""
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import time
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
from .images import encode_jpeg, resize
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _default(o):
|
| 12 |
+
if isinstance(o, np.ndarray):
|
| 13 |
+
return o.tolist()
|
| 14 |
+
if isinstance(o, (np.floating,)):
|
| 15 |
+
return float(o)
|
| 16 |
+
if isinstance(o, (np.integer,)):
|
| 17 |
+
return int(o)
|
| 18 |
+
if isinstance(o, (np.bool_,)):
|
| 19 |
+
return bool(o)
|
| 20 |
+
if hasattr(o, "__dataclass_fields__"):
|
| 21 |
+
return {k: getattr(o, k) for k in o.__dataclass_fields__}
|
| 22 |
+
return str(o)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def dumps(obj):
|
| 26 |
+
return json.dumps(obj, default=_default)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class RunLogger:
|
| 30 |
+
def __init__(self, run_dir, save_images=True, jpeg_quality=90):
|
| 31 |
+
self.run_dir = run_dir
|
| 32 |
+
self.save_images = save_images
|
| 33 |
+
self.jpeg_quality = jpeg_quality
|
| 34 |
+
os.makedirs(os.path.join(run_dir, "images"), exist_ok=True)
|
| 35 |
+
self.f = open(os.path.join(run_dir, "events.jsonl"), "a")
|
| 36 |
+
self.t0 = time.time()
|
| 37 |
+
|
| 38 |
+
def event(self, type, **fields):
|
| 39 |
+
rec = dict(type=type, t=round(time.time() - self.t0, 3), **fields)
|
| 40 |
+
self.f.write(dumps(rec) + "\n")
|
| 41 |
+
self.f.flush()
|
| 42 |
+
return rec
|
| 43 |
+
|
| 44 |
+
def write_json(self, name, obj):
|
| 45 |
+
with open(os.path.join(self.run_dir, name), "w") as f:
|
| 46 |
+
json.dump(obj, f, indent=1, default=_default)
|
| 47 |
+
|
| 48 |
+
def save_image(self, ref, rel, res=None):
|
| 49 |
+
"""Encode once (this exact JPEG is what the model receives) and save it under images/."""
|
| 50 |
+
if res is not None:
|
| 51 |
+
ref.array = resize(ref.array, res)
|
| 52 |
+
ref.jpeg = encode_jpeg(ref.array, self.jpeg_quality)
|
| 53 |
+
if self.save_images:
|
| 54 |
+
path = os.path.join(self.run_dir, "images", rel)
|
| 55 |
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
| 56 |
+
with open(path, "wb") as f:
|
| 57 |
+
f.write(ref.jpeg)
|
| 58 |
+
ref.path = os.path.relpath(path, self.run_dir)
|
| 59 |
+
return ref
|
| 60 |
+
|
| 61 |
+
def close(self):
|
| 62 |
+
self.f.close()
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/codex_catalogs/native_0.163.0.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/embodied_evo.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""EmbodiedEvo's Codex launcher and skills/lessons workflow on LFF's MCP.
|
| 2 |
+
|
| 3 |
+
Controlled port: same-episode knowledge only, no Playground pretraining, recipes,
|
| 4 |
+
native simulator execution or reset. Programs generate/revise action plans in
|
| 5 |
+
shell; individual robot commands are executed through MCP. This is explicitly
|
| 6 |
+
not EmbodiedEvo's full native code-as-policy evaluation.
|
| 7 |
+
"""
|
| 8 |
+
import copy
|
| 9 |
+
import hashlib
|
| 10 |
+
import importlib.util
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
import subprocess
|
| 14 |
+
import sys
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
from . import contract as C, pins
|
| 18 |
+
from .base import HarnessRefused
|
| 19 |
+
from .codex import Codex, DISABLE, codex_bin
|
| 20 |
+
from .rpent import tree_sha256
|
| 21 |
+
|
| 22 |
+
DEFAULT_SOURCE = "/mnt/cpfs/workspace/env/embodied-evo/src"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def load_source(path, module_name):
|
| 26 |
+
if sys.version_info < (3, 11):
|
| 27 |
+
import tomli
|
| 28 |
+
sys.modules.setdefault("tomllib", tomli)
|
| 29 |
+
spec = importlib.util.spec_from_file_location(module_name, path)
|
| 30 |
+
mod = importlib.util.module_from_spec(spec)
|
| 31 |
+
spec.loader.exec_module(mod)
|
| 32 |
+
return mod
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def workflow(source):
|
| 36 |
+
text = (Path(source) / "tasks/RoboDojo/Workspace/playground.md").read_text()
|
| 37 |
+
loop = text.split("Organize your work as an iterative loop:", 1)[1].split("# Environment and Primitives", 1)[0]
|
| 38 |
+
evolution = text.split("# Evolution: skills and lessons", 1)[1].split("# Playground rules", 1)[0]
|
| 39 |
+
evolution = evolution.replace("Read `skills/example.md` and `lessons/example.md` first.",
|
| 40 |
+
"Start with empty skills/ and lessons/; create them through shell when needed.")
|
| 41 |
+
return ("You are an embodied coding agent. Follow the EmbodiedEvo workflow below, adapted to the "
|
| 42 |
+
"benchmark's MCP interface. The benchmark instructions following this workflow are authoritative.\n\n"
|
| 43 |
+
"Organize your work as an iterative loop:" + loop + "\n# Skills and lessons\n" + evolution +
|
| 44 |
+
"\n# MCP adaptation\n"
|
| 45 |
+
"Use shell to write and run Python for visual analysis and incremental action-plan generation. "
|
| 46 |
+
"Keep reusable helpers and preconditions in skills/, failure evidence and corrections in lessons/, "
|
| 47 |
+
"and current plans in submission/. Execute each robot command with the robot MCP tool and inspect "
|
| 48 |
+
"its feedback before the next stage; Python in shell cannot contact the robot. Use view_images "
|
| 49 |
+
"for obs/ images. Do not assume scripts/env.py, native step(), get_observation(), reset(), or "
|
| 50 |
+
"Playground records exist. No preloaded recipes or skills are supplied. Preserve and revise your "
|
| 51 |
+
"skills and lessons across attempts of this episode only; the benchmark controls resets and "
|
| 52 |
+
"termination. Never replay earlier actions just because you rewrote a plan.\n\n")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class EmbodiedEvoCodex(Codex):
|
| 56 |
+
name = "embodied_evo_codex"
|
| 57 |
+
|
| 58 |
+
def __init__(self, *args, source=None, **kwargs):
|
| 59 |
+
self.source = source or os.environ.get("LFF_EMBODIED_EVO_SOURCE", DEFAULT_SOURCE)
|
| 60 |
+
self._source_info = None
|
| 61 |
+
self.prefix = workflow(self.source)
|
| 62 |
+
self.native_launch = load_source(Path(self.source) / "orchestrator/launch_agent.py", "lff_evo_launch")
|
| 63 |
+
self.native_recovery = load_source(Path(self.source) / "orchestrator/agent_recovery.py", "lff_evo_recovery")
|
| 64 |
+
super().__init__(*args, **kwargs)
|
| 65 |
+
if self.catalog != "generic":
|
| 66 |
+
raise HarnessRefused("EmbodiedEvo controlled variant requires generic catalog")
|
| 67 |
+
|
| 68 |
+
def source_info(self):
|
| 69 |
+
if self._source_info is None:
|
| 70 |
+
commit = subprocess.check_output(["git", "-C", self.source, "rev-parse", "HEAD"], text=True).strip()
|
| 71 |
+
self._source_info = dict(commit=commit, tree_sha256=tree_sha256(self.source),
|
| 72 |
+
workflow_sha256=hashlib.sha256(self.prefix.encode()).hexdigest())
|
| 73 |
+
return self._source_info
|
| 74 |
+
|
| 75 |
+
def version(self):
|
| 76 |
+
return dict(super().version(), framework=self.source_info())
|
| 77 |
+
|
| 78 |
+
def pin_key(self, ep):
|
| 79 |
+
v = self.version()
|
| 80 |
+
identity = C.sha256_json(v["framework"])[:12]
|
| 81 |
+
mode = "" if self.auth == "apikey" else "-chatgpt"
|
| 82 |
+
return pins.key(self.name + mode + "-generic-" + identity, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
|
| 83 |
+
|
| 84 |
+
def config_info(self):
|
| 85 |
+
return dict(super().config_info(), framework=self.source_info(), variant="mcp-skills-lessons",
|
| 86 |
+
history="same-thread", cross_episode_memory=False, native_code_execution=False)
|
| 87 |
+
|
| 88 |
+
def argv(self, ep, session_path, base_url, first_message, codex_home):
|
| 89 |
+
prompt = first_message if first_message.startswith(self.prefix) else self.prefix + first_message
|
| 90 |
+
args = self.native_launch.agent_argv("codex", prompt, model=ep.model, effort=ep.effort)
|
| 91 |
+
args[0] = codex_bin()
|
| 92 |
+
args[args.index("--sandbox") + 1] = "read-only"
|
| 93 |
+
# The benchmark fixes the middle layer; native orchestration provides the workflow and launch.
|
| 94 |
+
extra = ["--json", "--ignore-user-config", "--ignore-rules"]
|
| 95 |
+
for feature in DISABLE:
|
| 96 |
+
extra += ["--disable", feature]
|
| 97 |
+
for setting in self.config_args(ep, session_path, base_url, codex_home):
|
| 98 |
+
extra += ["-c", setting]
|
| 99 |
+
return args[:-1] + extra + [prompt]
|
| 100 |
+
|
| 101 |
+
def resume_argv(self, handle, message):
|
| 102 |
+
thread = self.thread_id(handle.spec.stdout_path)
|
| 103 |
+
if not thread:
|
| 104 |
+
raise HarnessRefused("EmbodiedEvo resume: missing current thread ID")
|
| 105 |
+
args = list(handle.spec.argv)
|
| 106 |
+
binary, args[0] = args[0], "codex"
|
| 107 |
+
i = args.index("--sandbox")
|
| 108 |
+
mode = args[i+1]
|
| 109 |
+
del args[i:i+2]
|
| 110 |
+
args[-1:-1] = ["-c", "sandbox_mode=" + json.dumps(mode)]
|
| 111 |
+
args = self.native_recovery.resume_argv(args, thread)
|
| 112 |
+
args[0], args[-1] = binary, message # benchmark-owned continuation; same native resume construction
|
| 113 |
+
return args
|
| 114 |
+
|
| 115 |
+
def preflight(self, spec, ep, record_dir=None):
|
| 116 |
+
proxy = copy.copy(spec)
|
| 117 |
+
proxy.first_message = self.prefix + spec.first_message
|
| 118 |
+
# super checks all middle-layer fields; this adapter's pin binds the source and workflow hash too.
|
| 119 |
+
out = super().preflight(proxy, ep, record_dir)
|
| 120 |
+
v = self.version()
|
| 121 |
+
anchor_name = "codex-generic" if self.auth == "apikey" else "codex-chatgpt-generic"
|
| 122 |
+
anchor_key = pins.key(anchor_name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
|
| 123 |
+
anchor = pins.load(anchor_key, self.pins_dir)
|
| 124 |
+
if anchor is None or anchor["fingerprint_sha256"] != out["fingerprint_sha256"]:
|
| 125 |
+
raise HarnessRefused("EmbodiedEvo middle layer does not match the pinned Codex baseline")
|
| 126 |
+
out.update(anchor_status="match", middle_fingerprint_sha256=out["fingerprint_sha256"],
|
| 127 |
+
framework_prefix_sha256=self.source_info()["workflow_sha256"],
|
| 128 |
+
framework_prefix_chars=len(self.prefix))
|
| 129 |
+
return out
|
| 130 |
+
|
| 131 |
+
def collect(self, handle):
|
| 132 |
+
traj = super().collect(handle)
|
| 133 |
+
# Preserve provenance alongside native CLI traces.
|
| 134 |
+
(Path(handle.ep.log_dir) / "framework.json").write_text(json.dumps(self.config_info(), indent=2))
|
| 135 |
+
return traj
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-fable-5-1_high.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "claude_code_full-oauth|2.1.299|2d894a4b1bfaaa9a|claude-fable-5-1|high",
|
| 3 |
+
"fingerprint_sha256": "f44d5ded7b8b847b934c86d8f7b51fa90ae396a1f33bca51e1c946f09da1031b",
|
| 4 |
+
"written": "2026-10-21 05:19:35",
|
| 5 |
+
"summary": {
|
| 6 |
+
"system_chars": 11701,
|
| 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-fable-5-1"
|
| 14 |
+
}
|
| 15 |
+
}
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6-astra_medium.json
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "codex-chatgpt-generic|0.163.0|399ff69c431c066e|gpt-6-astra|medium",
|
| 3 |
+
"fingerprint_sha256": "ae30000e0db69f6b50aefe798b87406f633e414e071a66fd0f5e85b006d8b0ea",
|
| 4 |
+
"written": "2026-10-20 02:33:27",
|
| 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": "medium",
|
| 17 |
+
"model_in_request": "gpt-6-astra",
|
| 18 |
+
"sandbox": {
|
| 19 |
+
"sandbox": "seccomp",
|
| 20 |
+
"sandbox_mode": "read-only"
|
| 21 |
+
}
|
| 22 |
+
}
|
| 23 |
+
}
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/codex_0.156.0_78a11f06e0a2dda4_gpt-6-astra_high.json
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "codex|0.156.0|78a11f06e0a2dda4|gpt-6-astra|high",
|
| 3 |
+
"fingerprint_sha256": "e999df1acbc0c137d1922832262b7b326df0ac8240b9647761158a1c368486c2",
|
| 4 |
+
"written": "2026-10-13 04:13:13",
|
| 5 |
+
"summary": {
|
| 6 |
+
"developer_chars": 23961,
|
| 7 |
+
"top_tools": [
|
| 8 |
+
"collaboration.followup_task",
|
| 9 |
+
"collaboration.interrupt_agent",
|
| 10 |
+
"collaboration.list_agents",
|
| 11 |
+
"collaboration.send_message",
|
| 12 |
+
"collaboration.spawn_agent",
|
| 13 |
+
"collaboration.wait_agent",
|
| 14 |
+
"functions.exec",
|
| 15 |
+
"functions.request_user_input",
|
| 16 |
+
"functions.request_user_input_async",
|
| 17 |
+
"functions.wait"
|
| 18 |
+
],
|
| 19 |
+
"all_tools": [
|
| 20 |
+
"apply_patch",
|
| 21 |
+
"clock__curr_time",
|
| 22 |
+
"list_mcp_resource_templates",
|
| 23 |
+
"list_mcp_resources",
|
| 24 |
+
"mcp__lff__robot",
|
| 25 |
+
"mcp__lff__shell",
|
| 26 |
+
"mcp__lff__view_images",
|
| 27 |
+
"read_mcp_resource"
|
| 28 |
+
],
|
| 29 |
+
"effort_in_request": "high",
|
| 30 |
+
"model_in_request": "gpt-6-astra",
|
| 31 |
+
"sandbox": {
|
| 32 |
+
"sandbox": "seccomp",
|
| 33 |
+
"sandbox_mode": "read-only"
|
| 34 |
+
}
|
| 35 |
+
}
|
| 36 |
+
}
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/objects.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Procedurally generated objects for LFF-Bench, registered into LIBERO's object registry.
|
| 2 |
+
|
| 3 |
+
Each generated object is an MJCF file with the layout robosuite's MujocoXMLObject expects
|
| 4 |
+
(an outer body containing body "object" plus bottom/top/horizontal_radius sites).
|
| 5 |
+
"""
|
| 6 |
+
import os
|
| 7 |
+
import re
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
from robosuite.models.objects import MujocoXMLObject
|
| 11 |
+
|
| 12 |
+
from libero.libero.envs.base_object import OBJECTS_DICT, register_object
|
| 13 |
+
|
| 14 |
+
GEN_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "assets_gen")
|
| 15 |
+
os.makedirs(GEN_DIR, exist_ok=True)
|
| 16 |
+
|
| 17 |
+
_SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"'
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _fmt(v):
|
| 21 |
+
return " ".join(f"{x:.5f}" for x in v)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _wrap(model_name, geoms_xml, half_height, radius):
|
| 25 |
+
return f"""<mujoco model="{model_name}">
|
| 26 |
+
<worldbody>
|
| 27 |
+
<body>
|
| 28 |
+
<body name="object">
|
| 29 |
+
{geoms_xml}
|
| 30 |
+
</body>
|
| 31 |
+
<site rgba="0 0 0 0" size="0.005" pos="0 0 {-half_height:.5f}" name="bottom_site" />
|
| 32 |
+
<site rgba="0 0 0 0" size="0.005" pos="0 0 {half_height:.5f}" name="top_site" />
|
| 33 |
+
<site rgba="0 0 0 0" size="0.005" pos="{radius:.5f} {radius:.5f} 0" name="horizontal_radius_site" />
|
| 34 |
+
</body>
|
| 35 |
+
</worldbody>
|
| 36 |
+
</mujoco>
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def box_xml(model_name, half, rgba, density=500.0, friction=(1.0, 0.005, 0.0001)):
|
| 41 |
+
"""Solid box; one geom used for both collision and rendering."""
|
| 42 |
+
g = (f' <geom name="{model_name}_g0" type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" '
|
| 43 |
+
f'density="{density}" friction="{_fmt(friction)}" {_SOLID} group="0" />\n'
|
| 44 |
+
f' <geom type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" conaffinity="0" contype="0" group="1" />')
|
| 45 |
+
return _wrap(model_name, g, half[2], float(np.hypot(half[0], half[1])))
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def bin_xml(model_name, inner_half_xy, wall_h, wall_t=0.006, floor_t=0.006, rgba=(0.6, 0.6, 0.65, 1.0),
|
| 49 |
+
density=800.0):
|
| 50 |
+
"""Open-top box. Origin at the center of the outer footprint, z=0 at mid height."""
|
| 51 |
+
ix, iy = inner_half_xy
|
| 52 |
+
H = (wall_h + floor_t) / 2.0
|
| 53 |
+
geoms = []
|
| 54 |
+
parts = [
|
| 55 |
+
((0, 0, -H + floor_t / 2), (ix + wall_t, iy + wall_t, floor_t / 2)), # floor
|
| 56 |
+
((ix + wall_t / 2, 0, floor_t / 2), (wall_t / 2, iy + wall_t, wall_h / 2)), # +x wall
|
| 57 |
+
((-ix - wall_t / 2, 0, floor_t / 2), (wall_t / 2, iy + wall_t, wall_h / 2)), # -x wall
|
| 58 |
+
((0, iy + wall_t / 2, floor_t / 2), (ix, wall_t / 2, wall_h / 2)), # +y wall
|
| 59 |
+
((0, -iy - wall_t / 2, floor_t / 2), (ix, wall_t / 2, wall_h / 2)), # -y wall
|
| 60 |
+
]
|
| 61 |
+
for k, (p, s) in enumerate(parts):
|
| 62 |
+
geoms.append(f' <geom name="{model_name}_g{k}" type="box" pos="{_fmt(p)}" size="{_fmt(s)}" '
|
| 63 |
+
f'rgba="{_fmt(rgba)}" density="{density}" friction="1.0 0.005 0.0001" {_SOLID} group="0" />')
|
| 64 |
+
geoms.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(rgba)}" '
|
| 65 |
+
f'conaffinity="0" contype="0" group="1" />')
|
| 66 |
+
return _wrap(model_name, "\n".join(geoms), H, float(np.hypot(ix + wall_t, iy + wall_t)))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _key(class_name):
|
| 70 |
+
return "_".join(re.sub(r"([A-Z0-9])", r" \1", class_name).split()).lower()
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def register_generated(class_name, xml_text, free=True):
|
| 74 |
+
"""Write the MJCF and register a LIBERO object class. Returns the BDDL category name."""
|
| 75 |
+
key = _key(class_name)
|
| 76 |
+
path = os.path.join(GEN_DIR, f"{key}.xml")
|
| 77 |
+
# write to a private temp file and rename atomically: several servers / validators may build the same task at
|
| 78 |
+
# once, and a reader must never see a half-written file (seen 2026-10-09 by the lh_* builders)
|
| 79 |
+
tmp = f"{path}.{os.getpid()}.tmp"
|
| 80 |
+
with open(tmp, "w") as f:
|
| 81 |
+
f.write(xml_text)
|
| 82 |
+
os.replace(tmp, path)
|
| 83 |
+
if key in OBJECTS_DICT:
|
| 84 |
+
return key
|
| 85 |
+
|
| 86 |
+
default_joints = [dict(type="free", damping="0.0005")] if free else None
|
| 87 |
+
|
| 88 |
+
def __init__(self, name=key, joints="default"):
|
| 89 |
+
j = default_joints if joints == "default" else joints
|
| 90 |
+
MujocoXMLObject.__init__(self, path, name=name, joints=j, obj_type="all", duplicate_collision_geoms=False)
|
| 91 |
+
self.category_name = key
|
| 92 |
+
self.rotation = (0.0, 0.0)
|
| 93 |
+
self.rotation_axis = "z"
|
| 94 |
+
self.object_properties = {"vis_site_names": {}}
|
| 95 |
+
|
| 96 |
+
cls = type(class_name, (MujocoXMLObject,), {"__init__": __init__})
|
| 97 |
+
register_object(cls)
|
| 98 |
+
return key
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/real/DRIVER.md
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LFF-Bench 真机驱动说明(给负责机械臂的同学)
|
| 2 |
+
|
| 3 |
+
> 协议版本 1(`protocol.py` 的 `PROTOCOL_VERSION`)。2026-10-19 起草;参考实现是仿真版假驱动 `fake_driver.py`,
|
| 4 |
+
> 它通过了本文 §7 的自检和 `tests/real_selfcheck.py` 的全部对照。
|
| 5 |
+
|
| 6 |
+
## 0. 一句话
|
| 7 |
+
|
| 8 |
+
你只需要在机器人电脑上跑一个**驱动进程**:收到 HTTP 请求就动臂、动夹爪、拍两张照片,或者在终端里问操作员。
|
| 9 |
+
模型、harness、命令预算、尝试次数、日志都在跑评测的那台机器上,你那边不用装。
|
| 10 |
+
|
| 11 |
+
```
|
| 12 |
+
评测机(跑模型的人) 机器人电脑(你)
|
| 13 |
+
Codex / Claude Code(订阅) 驱动进程 ← 你写,从 driver_template.py 改
|
| 14 |
+
└ MCP:robot / shell / view_images ├ 机械臂 SDK(松灵 PiPER ……)
|
| 15 |
+
└ 真机版 robot_server(预算、尝试、README、日志) ├ 两台相机:agentview + wrist
|
| 16 |
+
└ HTTP ── SSH 隧道 ──────────────────────────→ └ 操作员终端(复原场景、判成败)
|
| 17 |
+
```
|
| 18 |
+
|
| 19 |
+
模型永远看不到你的电脑,你的驱动也不知道模型是谁。所有运动只走 `/move`、`/gripper`、`/home` 三个接口。
|
| 20 |
+
|
| 21 |
+
## 1. 你要交付的东西
|
| 22 |
+
|
| 23 |
+
1. 驱动进程:`driver_template.py` 里 5 个 TODO(连臂、笛卡尔直线运动、读位姿、夹爪、取图),`/ik` 可选。
|
| 24 |
+
2. 两台相机:`agentview`(固定,能看到整个工作区)和 `wrist`(装在夹爪上)。
|
| 25 |
+
3. 场景道具,见 §6。
|
| 26 |
+
4. `scripts/real_check_driver.py` 全部 PASS(§7)。
|
| 27 |
+
5. 一位操作员,按 §8 的规程操作。可以就是你。
|
| 28 |
+
|
| 29 |
+
需要的文件只有三个:`lffbench/real/protocol.py`、`lffbench/real/driver_template.py`、`scripts/real_check_driver.py`。
|
| 30 |
+
放在同一个目录即可。依赖:Python 3、numpy、Pillow;录像另需 imageio + imageio-ffmpeg;再加上你的臂和相机 SDK。
|
| 31 |
+
|
| 32 |
+
## 2. 坐标与约定(最重要的一节)
|
| 33 |
+
|
| 34 |
+
| 量 | 约定 |
|
| 35 |
+
|---|---|
|
| 36 |
+
| 坐标系 | 机械臂**基座坐标系**:原点在基座,+x 是机器人正前方(远离基座),+y 是机器人的左手边,+z 向上;单位米 |
|
| 37 |
+
| 位置 `eef_pos` | **抓取点**(TCP):两指中间、比指尖高约 1 cm。在 SDK 里把 TCP 设到这里,或者自己做固定偏移 |
|
| 38 |
+
| 姿态 | 夹爪始终**竖直朝下**,只有一个自由度 yaw(绕基座 z 轴)。`yaw = 0`:两指沿基座 **y** 方向开合;`yaw = +90`:沿 x 方向开合;从上往下看,**正方向是逆时针** |
|
| 39 |
+
| yaw 范围 | `yaw_range_deg` 由你声明,跨度至少 180°(两指夹爪转 180° 等价,评测端会挑离当前 yaw 最近的等价角,保证落在你声明的范围里) |
|
| 40 |
+
| `gripper_width_m` | 两指尖之间的距离,单位米(空合 < 1 cm,张开 > 3 cm) |
|
| 41 |
+
| `joint_pos_rad` | 全部关节角(基座到腕,弧度),个数 = `n_joints` |
|
| 42 |
+
| `motion_s` | 这条命令实际运动了多少秒(评测按它扣"运动时间"预算:每次尝试 3 s × 命令条数) |
|
| 43 |
+
|
| 44 |
+
这些都和仿真一致(仿真里 yaw 0 也是"沿 y 开合")。模型拿到的 README 写的是
|
| 45 |
+
"You control a real `<robot>` robot arm (`<n_joints>` joints) with a two-finger parallel gripper",`robot` 和 `n_joints` 就取你在 `/info` 里填的值。
|
| 46 |
+
|
| 47 |
+
## 3. 接口
|
| 48 |
+
|
| 49 |
+
所有请求都是 `POST http://127.0.0.1:<port>/<endpoint>`,带 JSON body,请求头 `X-Driver-Token: <token>`。
|
| 50 |
+
所有回复都是 JSON,含 `"ok": true|false`。**`"fault": true` 表示机器人不可信了**(保护性停止、急停、通信断开……),评测端会立刻结束这个 run 并标为无效。
|
| 51 |
+
模板里任何未捕获的异常都会自动变成 fault。
|
| 52 |
+
|
| 53 |
+
| 接口 | 请求 | 回复(`ok` 之外) | 说明 |
|
| 54 |
+
|---|---|---|---|
|
| 55 |
+
| `info` | `{}` | `protocol` = 1,`robot`,`n_joints`,`cameras` = `["agentview","wrist"]`,`workspace` = `{lo:[x,y,z], hi:[x,y,z]}`,`yaw_range_deg` = `[lo,hi]`,`max_speed`(m/s),`ik`(bool),`driver_version` | 启动时调一次,内容写进每个 run 的契约 |
|
| 56 |
+
| `home` | `{}` | `state` | 回到初始位姿、张开夹爪。每次复原场景之前调用 |
|
| 57 |
+
| `move` | `{x, y, z, yaw_deg, speed}`,`speed` 可为 null(= `max_speed`) | `motion_s`,`state`;被拒时 `ok:false` + `error` | **阻塞**,臂停下才返回;尽量走笛卡尔直线(MoveL)。目标超出你的硬工作空间或者没有 IK 解时,**动之前**拒绝,回 `ok:false`(不是 fault) |
|
| 58 |
+
| `gripper` | `{close: true/false}` | `motion_s`,`state` | 阻塞。合爪要限力,夹到东西或合到底就停 |
|
| 59 |
+
| `state` | `{}` | `state` = `{eef_pos, eef_yaw_deg, gripper_width_m, joint_pos_rad}` | 报**真实**位姿。标定偏差由评测端在软件里加,驱动不要加 |
|
| 60 |
+
| `observe` | `{}` | `images` = `{agentview: {format, data}, wrist: {...}}`(base64 的 jpeg 或 png),`state` | 取**最新**一帧(先清相机缓冲)。任意分辨率都行:评测端会���心裁成正方形、缩到 512²,再存成 JPEG q90 |
|
| 61 |
+
| `ik` | `{eef_pos, yaw_deg}` | `joint_pos_rad` | 可选,只有 `real_bias_place` 需要(`info.ik = true`)。只算不动;返回离当前关节角最近的解 |
|
| 62 |
+
| `operator` | `{kind: reset/judge/notice, run, attempt, setup, checklist, text}` | reset:`{}`;judge:`{success, note}` | 模板里已经实现成终端提示,会阻塞到操作员回答为止(§8) |
|
| 63 |
+
| `event` | `{ev, run, attempt}`,`ev` ∈ session_start / attempt_start / attempt_end / episode_end / session_end / run_invalid | `{}` | 用来开始、停止录像。模板在 attempt_start 开录、attempt_end 停录,每次尝试存一个 mp4 |
|
| 64 |
+
|
| 65 |
+
驱动是单线程的:请求一条一条执行,操作员提示没回答之前,别的请求都在排队,所以复原场景时臂不会动。
|
| 66 |
+
|
| 67 |
+
## 4. 安全(必须做)
|
| 68 |
+
|
| 69 |
+
- **硬工作空间**:驱动自己检查(模板的 `_inside` 已经写好)。z 下限要保证指尖离桌面至少 5 mm;盒子任务要用指尖贴近桌面推,所以 z 下限别留太高。
|
| 70 |
+
- **速度上限**:`max_speed` 建议不超过 0.25 m/s。模型可以要求更慢,但不能更快。
|
| 71 |
+
- **力保护**:推盒子本来就要接触物体,但模型也可能让夹爪压桌面、撞东西。打开臂自带的碰撞检测或电流保护;保护停止触发时回 fault。
|
| 72 |
+
- **急停**放在操作员手边。急停之后这个 run 作废,在 judge 提示里选 `x`,或者驱动自己回 fault。
|
| 73 |
+
- `/move` 里**不要做任何"聪明"的补偿**,比如自动抬高、自动避障、自动纠偏。那样会改变任务本身。超范围就拒绝,其他情况照命令执行。
|
| 74 |
+
|
| 75 |
+
## 5. 模型那边看到的和你有关的东西
|
| 76 |
+
|
| 77 |
+
- 每条命令之后的两张图(agentview、wrist)和末端状态。所以 agentview 必须拍到整个工作区:盒子、目标框、起点。
|
| 78 |
+
光照要稳定;模型运行时,画面里不要有人和多余的东西。
|
| 79 |
+
- 被拒绝的目标,模型看到的是 "target rejected: the arm cannot reach it; the arm did not move"。
|
| 80 |
+
- 评测端声明给模型的工作空间就是你 `/info` 里的 `workspace`(`real_bias_place` 会在 xy 方向每边再缩 4 cm)。模型不知道具体数值,只会在越界时被拒。
|
| 81 |
+
|
| 82 |
+
## 6. 两个任务的场景
|
| 83 |
+
|
| 84 |
+
实例(配重放哪、布局用哪组)由种子决定,每次复原前会显示在你的终端里,照做就行。正式 run 用 5000 以后的种子。
|
| 85 |
+
|
| 86 |
+
### 6.1 `real_offcenter_push`:重心偏的长盒子推进绿框(对应仿真 `l7_offcenter_push`)
|
| 87 |
+
|
| 88 |
+
模型看到的指令(与仿真相同):*Slowly push the long brown box with the closed gripper so that it ends up completely inside the green rectangle ahead of it (farther from the robot).*
|
| 89 |
+
|
| 90 |
+
- **盒子**:不透明的棕色长盒(纸盒或 3D 打印都行),带盖。仿真尺寸是 9 × 22 × 4 cm(沿推的方向 × 长 × 高)。
|
| 91 |
+
可以按 PiPER 的可达范围缩小,但沿推的方向的尺寸要比夹爪最大开口宽至少 2 cm,保证夹不起来。长边横放(沿 y)。
|
| 92 |
+
- **配重**:盒内每端隔两格(最外一格、往里一格),共 4 格。配重块(钢块、铅块)放在实例指定的那一格;空格可以塞泡沫,免得配重滑动。
|
| 93 |
+
合上盖子,两端外观一模一样,贴同样的胶带。
|
| 94 |
+
- **起点**:桌上贴定位角标,盒子每次都按角标摆,长边横放。
|
| 95 |
+
- **目标框**:绿色胶带围成的矩形,每边比盒子底面大 2 cm,在起点正前方,框中心离盒子中心 8–13 cm(仿真值;选一个固定值就行)。
|
| 96 |
+
- **桌面**:摩擦要均匀,盒子不能一推就滑出去很远。
|
| 97 |
+
- **先验证 headroom(必须做,不用模型)**:合上夹爪,以 5–8 cm/s 推盒子背面中点,盒子要明显转动(仿真里转 25–33°,转完就出框);
|
| 98 |
+
对准重心正后方推,盒子要基本不转、能进框。转得不明显就加重配重、把配重往外移,或者换更滑的桌垫。左右两种配重位置各试几次,记下来。
|
| 99 |
+
- **判成功**(终端里显示的清单):盒子四个底角都在绿框内(压线算出框);盒子没翻倒;一直是合着夹爪推的;夹爪没碰着盒子。
|
| 100 |
+
|
| 101 |
+
### 6.2 `real_bias_place`:带标定偏差的抓放(对应仿真 `l1_bias_place`)
|
| 102 |
+
|
| 103 |
+
模型看到的指令:*Pick up the red cube and put it into the bowl.*
|
| 104 |
+
|
| 105 |
+
- 红色方块(约 4 cm,能稳稳夹起),一个浅碗(内径 ≥ 12 cm)。
|
| 106 |
+
- 桌上贴 4 组标记 A–D:`A1` 放方块、`A2` 放碗,B、C、D 同理。各组之间、方块和碗之间都相距 ≥ 20 cm,全部在工作空间内,离工作空间边界 ≥ 5 cm。
|
| 107 |
+
- **偏差不用你管**:评测端给每条命令加一个隐藏的 2.5–4 cm 水平偏移,回报位姿时再减掉,臂本身不变。
|
| 108 |
+
但你需要实现 `/ik`(并把 `info()` 里的 `ik` 改成 True),否则回报的关节角会泄露偏差,评测端会拒绝启动这个任务。
|
| 109 |
+
- **判成功**:方块在碗里(落在碗底,不在碗沿上);夹爪张开,没夹着方��。
|
| 110 |
+
|
| 111 |
+
## 7. 联调步骤
|
| 112 |
+
|
| 113 |
+
1. 把 §1 的三个文件拷到机器人电脑上,填好 `driver_template.py` 的 TODO 和顶部的配置(`ROBOT`、`N_JOINTS`、`WORKSPACE_*`、`YAW_RANGE_DEG`、`HOME`)。
|
| 114 |
+
2. 启动驱动(token 自己定,私下发给跑评测的人):
|
| 115 |
+
```bash
|
| 116 |
+
python driver_template.py --port 9900 --token <token> --log driver_logs
|
| 117 |
+
```
|
| 118 |
+
3. 在机器人电脑上自检。臂会小幅运动:上下 3 cm、转 30°、开合夹爪,速度 5 cm/s,手放在急停上:
|
| 119 |
+
```bash
|
| 120 |
+
python real_check_driver.py --driver http://127.0.0.1:9900 --token <token> --operator
|
| 121 |
+
```
|
| 122 |
+
全部 PASS 才算完成;WARN 要看一下原因,NOTE 要人工确认(yaw 正方向是否为逆时针)。
|
| 123 |
+
4. 建 SSH 隧道,让评测机能访问 `127.0.0.1:9900`。二选一:
|
| 124 |
+
- 评测机能 ssh 到机器人电脑:在评测机上执行 `ssh -N -L 9900:127.0.0.1:9900 <user>@<机器人电脑>`
|
| 125 |
+
- 只能反过来连:在机器人电脑上执行 `ssh -N -R 9900:127.0.0.1:9900 <user>@<评测机>`
|
| 126 |
+
5. 跑评测的人在评测机上经隧道再跑一次 `real_check_driver.py`(加 `--yes`)。
|
| 127 |
+
6. 正式 run:评测机启动 session 后,你的终端会先出现 **RESET** 提示:按 setup 摆好场景,人离开画面,回车,模型开始操作。
|
| 128 |
+
一次尝试结束时出现 **JUDGE** 提示:按清单判 y / n / x。还有下一次尝试的话,臂会先回 home,再出现 RESET 提示。
|
| 129 |
+
|
| 130 |
+
## 8. 操作员规程
|
| 131 |
+
|
| 132 |
+
- 只照终端提示做;setup 要严格照做,每次复原都一样(角标对齐、配重格子对、盖子合好)。
|
| 133 |
+
- 模型运行期间,人不进相机画面,不碰场景,也不对任何人说配重在哪(除非要急停)。
|
| 134 |
+
- 判 y / n 只看清单本身,不看模型"努力了没有"。
|
| 135 |
+
- `x` = 这个 run 作废:机器人报错、相机掉线、有人碰了场景、配重摆错了。note 里写一句原因。
|
| 136 |
+
- 时间:模型每步要几秒到几十秒,一个 run 大约 15–60 分钟(估计,没实测),最长一次尝试约 40 条命令。
|
| 137 |
+
|
| 138 |
+
## 9. 常见问题
|
| 139 |
+
|
| 140 |
+
- **相机不是正方形**:可以。评测端会中心裁成正方形,两边各裁掉 (宽−高)/2 像素,所以工作区要在画面中间。
|
| 141 |
+
- **被物体挡住、没到目标**:位置控制会继续顶。设好电流或力矩保护;保护停止就回 fault,没触发就照常返回,模型会从位姿和图里看出没到。
|
| 142 |
+
- **到不了的目标**:`/move` 回 `ok:false` + `error`,并且不能动。不要回 fault。
|
| 143 |
+
- **延迟**:每个请求 1 秒内回完就行(取图建议 < 0.5 s)。瓶颈在模型。
|
| 144 |
+
- **PiPER 的 SDK 细节**:模板里只写了提示,没有在真机上验证过,以 SDK 文档为准。
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/real/protocol.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Robot-driver protocol v1: what a real arm (or a fake one) must answer so that LFF-Bench can run on it.
|
| 2 |
+
|
| 3 |
+
The benchmark side (lffbench/real/session.py, on the machine that runs the agent harness) talks to one *driver*
|
| 4 |
+
process (on the robot PC) over HTTP. The driver only moves the arm, reads its state, grabs camera frames and talks
|
| 5 |
+
to the human operator; budgets, attempts, README, logs and the agent interface stay on the benchmark side, so the
|
| 6 |
+
agent sees exactly the same tools as in simulation. Spec for driver authors: lffbench/real/DRIVER.md.
|
| 7 |
+
|
| 8 |
+
This file is shared by both sides and needs only the Python standard library + numpy + Pillow (no simulator):
|
| 9 |
+
DriverClient benchmark side: typed calls to a driver
|
| 10 |
+
DriverServer driver side: HTTP plumbing; subclass it and implement the hardware methods (driver_template.py)
|
| 11 |
+
ConsoleOperator driver side: the operator's terminal (blocking prompts for reset / judging)
|
| 12 |
+
|
| 13 |
+
Every request is POST <url>/<endpoint> with a JSON body and header X-Driver-Token: <token>.
|
| 14 |
+
Every reply is JSON with "ok": true|false. A reply with "fault": true means the robot can no longer be trusted
|
| 15 |
+
(protective stop, e-stop, lost connection, ...): the benchmark ends the run and marks it invalid.
|
| 16 |
+
"""
|
| 17 |
+
import base64
|
| 18 |
+
import io
|
| 19 |
+
import json
|
| 20 |
+
import math
|
| 21 |
+
import os
|
| 22 |
+
import secrets
|
| 23 |
+
import sys
|
| 24 |
+
import time
|
| 25 |
+
import traceback
|
| 26 |
+
import urllib.error
|
| 27 |
+
import urllib.request
|
| 28 |
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
| 29 |
+
|
| 30 |
+
import numpy as np
|
| 31 |
+
|
| 32 |
+
PROTOCOL_VERSION = 1
|
| 33 |
+
CAMERAS = ("agentview", "wrist")
|
| 34 |
+
TOKEN_HEADER = "X-Driver-Token"
|
| 35 |
+
ENDPOINTS = ("info", "home", "move", "gripper", "state", "observe", "ik", "operator", "event")
|
| 36 |
+
OPERATOR_KINDS = ("reset", "judge", "notice")
|
| 37 |
+
EVENTS = ("session_start", "attempt_start", "attempt_end", "episode_end", "session_end", "run_invalid")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class DriverError(RuntimeError):
|
| 41 |
+
"""The driver answered something that breaks the protocol (or did not answer)."""
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class DriverFault(DriverError):
|
| 45 |
+
"""The driver reports a robot fault: the run must stop and is invalid."""
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# ------------------------------------------------------------------------------------------------ images
|
| 49 |
+
def encode_image(arr, fmt="png", quality=95):
|
| 50 |
+
"""uint8 HxWx3 -> {"format": "png"|"jpeg", "data": base64}. PNG is lossless (the benchmark re-encodes every frame
|
| 51 |
+
as 512x512 JPEG q90 itself, so a JPEG from the driver is compressed twice); JPEG is smaller over a slow link."""
|
| 52 |
+
from PIL import Image
|
| 53 |
+
buf = io.BytesIO()
|
| 54 |
+
im = Image.fromarray(np.asarray(arr, dtype=np.uint8))
|
| 55 |
+
if fmt == "jpeg":
|
| 56 |
+
im.save(buf, format="JPEG", quality=int(quality))
|
| 57 |
+
else:
|
| 58 |
+
im.save(buf, format="PNG")
|
| 59 |
+
return dict(format=fmt, data=base64.b64encode(buf.getvalue()).decode("ascii"))
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def decode_image(obj):
|
| 63 |
+
"""{"format", "data"} -> uint8 HxWx3 (RGB)."""
|
| 64 |
+
from PIL import Image
|
| 65 |
+
if not isinstance(obj, dict) or "data" not in obj:
|
| 66 |
+
raise DriverError("image must be {\"format\": \"png\"|\"jpeg\", \"data\": <base64>}")
|
| 67 |
+
im = Image.open(io.BytesIO(base64.b64decode(obj["data"])))
|
| 68 |
+
return np.asarray(im.convert("RGB"), dtype=np.uint8)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def square_resize(arr, res):
|
| 72 |
+
"""Centre-crop to a square, then resize to res x res. A frame that is already res x res is returned unchanged
|
| 73 |
+
(bit for bit), so a simulator-backed driver gives exactly the simulator's pixels."""
|
| 74 |
+
from PIL import Image
|
| 75 |
+
arr = np.asarray(arr, dtype=np.uint8)
|
| 76 |
+
h, w = arr.shape[:2]
|
| 77 |
+
if h == res and w == res:
|
| 78 |
+
return arr
|
| 79 |
+
s = min(h, w)
|
| 80 |
+
y0, x0 = (h - s) // 2, (w - s) // 2
|
| 81 |
+
arr = arr[y0:y0 + s, x0:x0 + s]
|
| 82 |
+
if s == res:
|
| 83 |
+
return np.ascontiguousarray(arr)
|
| 84 |
+
return np.asarray(Image.fromarray(arr).resize((res, res), Image.BICUBIC))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
# ------------------------------------------------------------------------------------------------ validation
|
| 88 |
+
def _vec(v, n):
|
| 89 |
+
return isinstance(v, (list, tuple)) and len(v) == n and all(isinstance(x, (int, float)) and math.isfinite(x) for x in v)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def info_problems(info):
|
| 93 |
+
"""-> list of problems with an /info reply (empty = fine)."""
|
| 94 |
+
p = []
|
| 95 |
+
if info.get("protocol") != PROTOCOL_VERSION:
|
| 96 |
+
p.append(f"protocol must be {PROTOCOL_VERSION}, got {info.get('protocol')!r}")
|
| 97 |
+
if not isinstance(info.get("robot"), str) or not info["robot"].strip():
|
| 98 |
+
p.append("robot: non-empty string (e.g. \"AgileX PiPER\")")
|
| 99 |
+
if not isinstance(info.get("n_joints"), int) or not 4 <= info["n_joints"] <= 8:
|
| 100 |
+
p.append("n_joints: integer 4..8")
|
| 101 |
+
if sorted(info.get("cameras") or []) != sorted(CAMERAS):
|
| 102 |
+
p.append(f"cameras must be exactly {list(CAMERAS)}")
|
| 103 |
+
ws = info.get("workspace") or {}
|
| 104 |
+
if not (_vec(ws.get("lo"), 3) and _vec(ws.get("hi"), 3) and all(a < b for a, b in zip(ws["lo"], ws["hi"]))):
|
| 105 |
+
p.append("workspace: {lo: [x, y, z], hi: [x, y, z]} with lo < hi (robot-base frame, metres)")
|
| 106 |
+
yr = info.get("yaw_range_deg")
|
| 107 |
+
if not (_vec(yr, 2) and yr[0] < yr[1] and yr[1] - yr[0] >= 180.0):
|
| 108 |
+
p.append("yaw_range_deg: [lo, hi] with hi - lo >= 180 (the gripper is symmetric, every yaw must be reachable)")
|
| 109 |
+
if not (isinstance(info.get("max_speed"), (int, float)) and 0.01 <= info["max_speed"] <= 1.0):
|
| 110 |
+
p.append("max_speed: m/s, 0.01..1.0")
|
| 111 |
+
if not isinstance(info.get("ik"), bool):
|
| 112 |
+
p.append("ik: true|false (whether /ik is implemented; needed only for tasks with a calibration bias)")
|
| 113 |
+
if not isinstance(info.get("driver_version"), str):
|
| 114 |
+
p.append("driver_version: string (your git commit or a date; it is written into every run's log)")
|
| 115 |
+
return p
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def state_problems(st, n_joints):
|
| 119 |
+
p = []
|
| 120 |
+
if not _vec(st.get("eef_pos"), 3):
|
| 121 |
+
p.append("state.eef_pos: [x, y, z] metres")
|
| 122 |
+
if not (isinstance(st.get("eef_yaw_deg"), (int, float)) and math.isfinite(st["eef_yaw_deg"])):
|
| 123 |
+
p.append("state.eef_yaw_deg: number")
|
| 124 |
+
if not (isinstance(st.get("gripper_width_m"), (int, float)) and 0.0 <= st["gripper_width_m"] <= 0.2):
|
| 125 |
+
p.append("state.gripper_width_m: number 0..0.2")
|
| 126 |
+
if not _vec(st.get("joint_pos_rad"), n_joints):
|
| 127 |
+
p.append(f"state.joint_pos_rad: {n_joints} numbers (radians)")
|
| 128 |
+
return p
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# ------------------------------------------------------------------------------------------------ benchmark side
|
| 132 |
+
class DriverClient:
|
| 133 |
+
"""Typed calls to a driver. `url` like http://127.0.0.1:9900 (an SSH tunnel to the robot PC)."""
|
| 134 |
+
|
| 135 |
+
def __init__(self, url, token, timeout=120.0):
|
| 136 |
+
self.url, self.token, self.timeout = url.rstrip("/"), token, float(timeout)
|
| 137 |
+
self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) # never through a web proxy
|
| 138 |
+
|
| 139 |
+
def call(self, endpoint, payload=None, timeout=None, allow_not_ok=False):
|
| 140 |
+
req = urllib.request.Request(f"{self.url}/{endpoint}", data=json.dumps(payload or {}).encode(),
|
| 141 |
+
headers={"Content-Type": "application/json", TOKEN_HEADER: self.token})
|
| 142 |
+
try:
|
| 143 |
+
with self.opener.open(req, timeout=timeout if timeout is not None else self.timeout) as r:
|
| 144 |
+
rep = json.loads(r.read().decode())
|
| 145 |
+
except (urllib.error.URLError, OSError, ValueError) as e:
|
| 146 |
+
raise DriverError(f"/{endpoint}: no valid reply from the driver ({type(e).__name__}: {e})") from e
|
| 147 |
+
if not isinstance(rep, dict) or "ok" not in rep:
|
| 148 |
+
raise DriverError(f"/{endpoint}: reply is not a JSON object with \"ok\"")
|
| 149 |
+
if rep.get("fault"):
|
| 150 |
+
raise DriverFault(f"/{endpoint}: robot fault: {rep.get('error', '')}")
|
| 151 |
+
if not rep["ok"] and not allow_not_ok:
|
| 152 |
+
raise DriverError(f"/{endpoint}: {rep.get('error', 'not ok')}")
|
| 153 |
+
return rep
|
| 154 |
+
|
| 155 |
+
def info(self):
|
| 156 |
+
rep = self.call("info")
|
| 157 |
+
prob = info_problems(rep)
|
| 158 |
+
if prob:
|
| 159 |
+
raise DriverError("/info: " + "; ".join(prob))
|
| 160 |
+
return rep
|
| 161 |
+
|
| 162 |
+
def home(self):
|
| 163 |
+
return self.call("home", timeout=max(self.timeout, 300))
|
| 164 |
+
|
| 165 |
+
def move(self, x, y, z, yaw_deg, speed=None):
|
| 166 |
+
"""-> reply; ok=false (not a fault) means the target was rejected and the arm did not move."""
|
| 167 |
+
return self.call("move", dict(x=float(x), y=float(y), z=float(z), yaw_deg=float(yaw_deg),
|
| 168 |
+
speed=None if speed is None else float(speed)), allow_not_ok=True)
|
| 169 |
+
|
| 170 |
+
def gripper(self, close):
|
| 171 |
+
return self.call("gripper", dict(close=bool(close)))
|
| 172 |
+
|
| 173 |
+
def state(self):
|
| 174 |
+
return self.call("state")["state"]
|
| 175 |
+
|
| 176 |
+
def observe(self):
|
| 177 |
+
rep = self.call("observe")
|
| 178 |
+
imgs = rep.get("images") or {}
|
| 179 |
+
missing = [c for c in CAMERAS if c not in imgs]
|
| 180 |
+
if missing:
|
| 181 |
+
raise DriverError(f"/observe: missing camera(s) {missing}")
|
| 182 |
+
return {c: decode_image(imgs[c]) for c in CAMERAS}, rep["state"]
|
| 183 |
+
|
| 184 |
+
def ik(self, eef_pos, yaw_deg):
|
| 185 |
+
return self.call("ik", dict(eef_pos=[float(v) for v in eef_pos], yaw_deg=float(yaw_deg)))["joint_pos_rad"]
|
| 186 |
+
|
| 187 |
+
def operator(self, kind, **kw):
|
| 188 |
+
"""Blocks until the operator has answered (no timeout)."""
|
| 189 |
+
assert kind in OPERATOR_KINDS, kind
|
| 190 |
+
return self.call("operator", dict(kind=kind, **kw), timeout=24 * 3600)
|
| 191 |
+
|
| 192 |
+
def event(self, ev, **kw):
|
| 193 |
+
assert ev in EVENTS, ev
|
| 194 |
+
return self.call("event", dict(ev=ev, **kw))
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
# ------------------------------------------------------------------------------------------------ driver side
|
| 198 |
+
class ConsoleOperator:
|
| 199 |
+
"""The operator's terminal on the robot PC. Prompts block the driver (the robot must not move while the operator
|
| 200 |
+
resets the scene). Answers are appended to `log_path` (JSON lines)."""
|
| 201 |
+
|
| 202 |
+
def __init__(self, log_path=None, stream_in=None, stream_out=None):
|
| 203 |
+
self.log_path = log_path
|
| 204 |
+
self.inp = stream_in or sys.stdin
|
| 205 |
+
self.out = stream_out or sys.stdout
|
| 206 |
+
|
| 207 |
+
def _say(self, s=""):
|
| 208 |
+
self.out.write(s + "\n")
|
| 209 |
+
self.out.flush()
|
| 210 |
+
|
| 211 |
+
def _ask(self, prompt):
|
| 212 |
+
self.out.write(prompt)
|
| 213 |
+
self.out.flush()
|
| 214 |
+
line = self.inp.readline()
|
| 215 |
+
if not line:
|
| 216 |
+
raise EOFError("operator input closed")
|
| 217 |
+
return line.strip()
|
| 218 |
+
|
| 219 |
+
def _log(self, d):
|
| 220 |
+
if self.log_path:
|
| 221 |
+
os.makedirs(os.path.dirname(os.path.abspath(self.log_path)), exist_ok=True)
|
| 222 |
+
with open(self.log_path, "a") as f:
|
| 223 |
+
f.write(json.dumps(dict(d, t=time.time()), ensure_ascii=False) + "\n")
|
| 224 |
+
|
| 225 |
+
def __call__(self, kind, run="", attempt=None, text="", setup="", checklist=None, **_):
|
| 226 |
+
bar = "=" * 72
|
| 227 |
+
self._say("\n" + bar)
|
| 228 |
+
self._say(f"[{time.strftime('%H:%M:%S')}] run {run} attempt {attempt} -- {kind.upper()}")
|
| 229 |
+
if text:
|
| 230 |
+
self._say(text)
|
| 231 |
+
if kind == "reset":
|
| 232 |
+
if setup:
|
| 233 |
+
self._say("\nScene for this attempt (do it exactly; do not talk to anyone about it):\n" + setup)
|
| 234 |
+
self._ask("\nArm is at home. Put the scene back as described, step out of the cameras, press Enter... ")
|
| 235 |
+
self._log(dict(kind=kind, run=run, attempt=attempt))
|
| 236 |
+
return dict(ok=True)
|
| 237 |
+
if kind == "judge":
|
| 238 |
+
for i, c in enumerate(checklist or [], 1):
|
| 239 |
+
self._say(f" {i}. {c}")
|
| 240 |
+
while True:
|
| 241 |
+
a = self._ask("\nAll conditions met? y = success, n = failure, x = run invalid (robot / camera "
|
| 242 |
+
"problem): ").lower()
|
| 243 |
+
if a in ("y", "n", "x"):
|
| 244 |
+
break
|
| 245 |
+
note = self._ask("Note (one line, optional): ")
|
| 246 |
+
self._log(dict(kind=kind, run=run, attempt=attempt, answer=a, note=note))
|
| 247 |
+
if a == "x":
|
| 248 |
+
return dict(ok=False, fault=True, error=f"operator marked the run invalid: {note}")
|
| 249 |
+
return dict(ok=True, success=a == "y", note=note)
|
| 250 |
+
self._log(dict(kind=kind, run=run, attempt=attempt, text=text))
|
| 251 |
+
return dict(ok=True)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
class DriverServer:
|
| 255 |
+
"""HTTP plumbing for a driver. Subclass and implement the hardware methods below; see driver_template.py.
|
| 256 |
+
The server is single-threaded on purpose: requests are executed one at a time, and an operator prompt blocks
|
| 257 |
+
every other request until it is answered."""
|
| 258 |
+
|
| 259 |
+
# ---- implement these ------------------------------------------------------------------------------
|
| 260 |
+
def info(self):
|
| 261 |
+
"""-> dict (see DRIVER.md §3): protocol, robot, n_joints, cameras, workspace, yaw_range_deg, max_speed, ik,
|
| 262 |
+
driver_version."""
|
| 263 |
+
raise NotImplementedError
|
| 264 |
+
|
| 265 |
+
def home(self):
|
| 266 |
+
"""Move to the home pose (gripper open, pointing down). -> state dict."""
|
| 267 |
+
raise NotImplementedError
|
| 268 |
+
|
| 269 |
+
def move(self, x, y, z, yaw_deg, speed):
|
| 270 |
+
"""Blocking straight-line move of the grasp point; speed m/s or None (= max_speed).
|
| 271 |
+
-> (ok, error_or_None, motion_s). ok=False: rejected BEFORE moving (outside the hard limits / no IK)."""
|
| 272 |
+
raise NotImplementedError
|
| 273 |
+
|
| 274 |
+
def gripper(self, close):
|
| 275 |
+
"""Blocking open / close (force-limited close). -> motion_s."""
|
| 276 |
+
raise NotImplementedError
|
| 277 |
+
|
| 278 |
+
def state(self):
|
| 279 |
+
"""-> dict eef_pos, eef_yaw_deg, gripper_width_m, joint_pos_rad."""
|
| 280 |
+
raise NotImplementedError
|
| 281 |
+
|
| 282 |
+
def images(self):
|
| 283 |
+
"""-> {"agentview": uint8 HxWx3 RGB, "wrist": ...}, taken now (after the arm has stopped)."""
|
| 284 |
+
raise NotImplementedError
|
| 285 |
+
|
| 286 |
+
def ik(self, eef_pos, yaw_deg):
|
| 287 |
+
"""Optional (info()["ik"] = True): joint angles that put the grasp point at eef_pos / yaw_deg (pointing
|
| 288 |
+
down), close to the current joint angles. -> list of n_joints floats."""
|
| 289 |
+
raise NotImplementedError
|
| 290 |
+
|
| 291 |
+
def operator(self, kind, **kw):
|
| 292 |
+
"""Default: the terminal. -> dict (reset: {ok}; judge: {ok, success, note}; notice: {ok})."""
|
| 293 |
+
return self.console(kind, **kw)
|
| 294 |
+
|
| 295 |
+
def event(self, ev, **kw):
|
| 296 |
+
"""Start / stop your own recordings here (attempt_start / attempt_end / episode_end ...)."""
|
| 297 |
+
return None
|
| 298 |
+
|
| 299 |
+
image_format = "png"
|
| 300 |
+
|
| 301 |
+
# ---- plumbing -------------------------------------------------------------------------------------
|
| 302 |
+
def dispatch(self, endpoint, a):
|
| 303 |
+
if endpoint == "info":
|
| 304 |
+
return dict(ok=True, **self.info())
|
| 305 |
+
if endpoint == "home":
|
| 306 |
+
return dict(ok=True, state=self.home())
|
| 307 |
+
if endpoint == "move":
|
| 308 |
+
ok, err, motion_s = self.move(float(a["x"]), float(a["y"]), float(a["z"]), float(a["yaw_deg"]),
|
| 309 |
+
None if a.get("speed") is None else float(a["speed"]))
|
| 310 |
+
rep = dict(ok=bool(ok), motion_s=float(motion_s or 0.0), state=self.state())
|
| 311 |
+
if not ok:
|
| 312 |
+
rep["error"] = err or "rejected"
|
| 313 |
+
return rep
|
| 314 |
+
if endpoint == "gripper":
|
| 315 |
+
motion_s = self.gripper(bool(a["close"]))
|
| 316 |
+
return dict(ok=True, motion_s=float(motion_s or 0.0), state=self.state())
|
| 317 |
+
if endpoint == "state":
|
| 318 |
+
return dict(ok=True, state=self.state())
|
| 319 |
+
if endpoint == "observe":
|
| 320 |
+
imgs = self.images()
|
| 321 |
+
return dict(ok=True, images={c: encode_image(imgs[c], self.image_format) for c in CAMERAS},
|
| 322 |
+
state=self.state())
|
| 323 |
+
if endpoint == "ik":
|
| 324 |
+
return dict(ok=True, joint_pos_rad=[float(v) for v in self.ik(a["eef_pos"], float(a["yaw_deg"]))])
|
| 325 |
+
if endpoint == "operator":
|
| 326 |
+
kw = {k: v for k, v in a.items() if k != "kind"}
|
| 327 |
+
return self.operator(a["kind"], **kw)
|
| 328 |
+
if endpoint == "event":
|
| 329 |
+
self.event(a.get("ev", ""), **{k: v for k, v in a.items() if k != "ev"})
|
| 330 |
+
return dict(ok=True)
|
| 331 |
+
return dict(ok=False, error=f"unknown endpoint {endpoint!r}")
|
| 332 |
+
|
| 333 |
+
def serve(self, port, token=None, host="127.0.0.1", operator_log=None):
|
| 334 |
+
"""Serve forever on host:port (keep 127.0.0.1 and reach it through an SSH tunnel)."""
|
| 335 |
+
self.token = token or os.environ.get("LFF_DRIVER_TOKEN") or secrets.token_hex(12)
|
| 336 |
+
self.console = ConsoleOperator(operator_log)
|
| 337 |
+
drv = self
|
| 338 |
+
|
| 339 |
+
class H(BaseHTTPRequestHandler):
|
| 340 |
+
def log_message(self, *x):
|
| 341 |
+
pass
|
| 342 |
+
|
| 343 |
+
def do_POST(self):
|
| 344 |
+
try:
|
| 345 |
+
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)) or b"{}")
|
| 346 |
+
if self.headers.get(TOKEN_HEADER) != drv.token:
|
| 347 |
+
rep = dict(ok=False, error="unauthorised")
|
| 348 |
+
else:
|
| 349 |
+
rep = drv.dispatch(self.path.strip("/"), body)
|
| 350 |
+
except NotImplementedError as e:
|
| 351 |
+
rep = dict(ok=False, error=f"not implemented: {self.path} {e}")
|
| 352 |
+
except Exception as e: # anything unexpected on the robot side is a fault: stop the run
|
| 353 |
+
traceback.print_exc()
|
| 354 |
+
rep = dict(ok=False, fault=True, error=f"{type(e).__name__}: {e}")
|
| 355 |
+
data = json.dumps(rep).encode()
|
| 356 |
+
self.send_response(200)
|
| 357 |
+
self.send_header("Content-Type", "application/json")
|
| 358 |
+
self.send_header("Content-Length", str(len(data)))
|
| 359 |
+
self.end_headers()
|
| 360 |
+
self.wfile.write(data)
|
| 361 |
+
|
| 362 |
+
srv = HTTPServer((host, int(port)), H)
|
| 363 |
+
print(f"driver ready on http://{host}:{port} token={self.token}", flush=True)
|
| 364 |
+
srv.serve_forever()
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/real/tasks.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Real-robot tasks. Same idea as lffbench/tasks/ (an instruction, a hidden variable the agent cannot see before it acts,
|
| 2 |
+
a success rule), but the scene is physical: the instance is a setup sheet the operator follows, and the operator
|
| 3 |
+
judges the end state. The hidden variable is drawn from the seed, so the instance list of a run is reproducible and
|
| 4 |
+
nobody has to choose it by hand.
|
| 5 |
+
|
| 6 |
+
Seeds: 5000+ for real-robot runs (same convention as simulation: 1000-1999 development, 3000 pilots, 5000+ test).
|
| 7 |
+
"""
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
REAL_TASKS = {}
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def register_real(cls):
|
| 14 |
+
REAL_TASKS[cls.name] = cls
|
| 15 |
+
return cls
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class RealTask:
|
| 19 |
+
name = "real_base"
|
| 20 |
+
sim_counterpart = "" # the simulated task with the same hidden variable (for the paper's mapping only)
|
| 21 |
+
protocol = "cross"
|
| 22 |
+
max_attempts = 3
|
| 23 |
+
agent_max_steps = 40
|
| 24 |
+
instruction = ""
|
| 25 |
+
instruction_indirect = ""
|
| 26 |
+
needs_ik = False # True if the instance carries a calibration bias (believed joint angles need the driver's /ik)
|
| 27 |
+
bias_margin = 0.0 # largest possible |bias| (m): the agent-facing workspace is shrunk by it, so a rejected target
|
| 28 |
+
# never depends on the hidden bias
|
| 29 |
+
judge = None # set by RealRobotSession: inst -> outcome dict, asks the operator
|
| 30 |
+
|
| 31 |
+
def outcome(self, inst):
|
| 32 |
+
"""Same role as LFFTask.outcome: called by robot_server's _done when an attempt ends."""
|
| 33 |
+
return self.judge(inst)
|
| 34 |
+
|
| 35 |
+
def sample_instance(self, seed):
|
| 36 |
+
raise NotImplementedError
|
| 37 |
+
|
| 38 |
+
def setup_text(self, inst):
|
| 39 |
+
"""What the operator builds before every attempt (shown on the robot PC only, never to the agent)."""
|
| 40 |
+
raise NotImplementedError
|
| 41 |
+
|
| 42 |
+
def checklist(self, inst):
|
| 43 |
+
"""Conditions the operator checks when an attempt ends; success = all of them."""
|
| 44 |
+
raise NotImplementedError
|
| 45 |
+
|
| 46 |
+
def bias(self, inst):
|
| 47 |
+
"""Hidden calibration error added to every commanded position (robot-base frame, metres)."""
|
| 48 |
+
return np.zeros(3)
|
| 49 |
+
|
| 50 |
+
def feedback(self, inst, out, level="F1"):
|
| 51 |
+
# same text as LFFTask.feedback (F0 / F1); F2 needs simulator measurements and is refused at session start
|
| 52 |
+
if level == "F0":
|
| 53 |
+
return ""
|
| 54 |
+
return "Attempt succeeded." if out["success"] else "Attempt failed."
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@register_real
|
| 58 |
+
class RealOffcenterPush(RealTask):
|
| 59 |
+
"""L7 l7_offcenter_push on a real arm: a long opaque box with a hidden weight at one end. Pushing the middle of
|
| 60 |
+
its back face turns it (visible in the agentview); the fix is to push nearer the heavy end or to straighten it
|
| 61 |
+
afterwards. Physical build and scene layout: DRIVER.md §6.1."""
|
| 62 |
+
name = "real_offcenter_push"
|
| 63 |
+
sim_counterpart = "l7_offcenter_push"
|
| 64 |
+
# same wording as the simulated task (2026-10-19): end state only, no hint about the weight or where to push
|
| 65 |
+
instruction = ("Slowly push the long brown box with the closed gripper so that it ends up completely inside the "
|
| 66 |
+
"green rectangle ahead of it (farther from the robot).")
|
| 67 |
+
instruction_indirect = ("Slowly push the long cardboard-coloured block with the closed gripper so that it ends up "
|
| 68 |
+
"completely inside the marked green area ahead of it (farther from the robot).")
|
| 69 |
+
SLOTS = ("end", "inner") # weight compartments per side: at the very end, or one compartment further in
|
| 70 |
+
|
| 71 |
+
def sample_instance(self, seed):
|
| 72 |
+
rng = np.random.default_rng(seed)
|
| 73 |
+
return dict(seed=int(seed), weight_side=str(rng.choice(["left", "right"])), weight_slot=str(rng.choice(self.SLOTS)))
|
| 74 |
+
|
| 75 |
+
def setup_text(self, inst):
|
| 76 |
+
side = {"left": "LEFT (the robot's left, +y)", "right": "RIGHT (the robot's right, -y)"}[inst["weight_side"]]
|
| 77 |
+
slot = {"end": "the outermost compartment", "inner": "the second compartment from that end"}[inst["weight_slot"]]
|
| 78 |
+
return "\n".join([
|
| 79 |
+
f"- weight block inside the box: {side} end, in {slot};",
|
| 80 |
+
"- the other compartments stay empty; close the lid; both ends look the same from outside;",
|
| 81 |
+
"- box on the START tape marks: long side across the robot (left-right), back face on the back mark;",
|
| 82 |
+
"- nothing else on the table; the green target rectangle tape unchanged.",
|
| 83 |
+
])
|
| 84 |
+
|
| 85 |
+
def checklist(self, inst):
|
| 86 |
+
return ["all four bottom corners of the box are inside the green rectangle (a corner on the tape = outside)",
|
| 87 |
+
"the box is standing on its bottom face (not tipped over)",
|
| 88 |
+
"the box was only pushed with the closed gripper (no pushes with the fingers open)",
|
| 89 |
+
"the gripper is not touching the box"]
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@register_real
|
| 93 |
+
class RealBiasPlace(RealTask):
|
| 94 |
+
"""L1 l1_bias_place on a real arm: pick-and-place with a calibration error injected in software (the benchmark
|
| 95 |
+
adds `bias` to every commanded position and subtracts it from every reported one, exactly as in simulation).
|
| 96 |
+
The arm itself is unchanged; the cameras show where the gripper really is. Physical build: DRIVER.md §6.2."""
|
| 97 |
+
name = "real_bias_place"
|
| 98 |
+
sim_counterpart = "l1_bias_place"
|
| 99 |
+
instruction = "Pick up the red cube and put it into the bowl."
|
| 100 |
+
instruction_indirect = "Pick up the small red block and put it into the round bowl."
|
| 101 |
+
needs_ik = True
|
| 102 |
+
R_MIN, R_MAX = 0.025, 0.040 # bias magnitude (m), as l1_bias_place
|
| 103 |
+
bias_margin = R_MAX
|
| 104 |
+
LAYOUTS = ("A", "B", "C", "D") # taped (cube mark, bowl mark) pairs; DRIVER.md §6.2
|
| 105 |
+
|
| 106 |
+
def sample_instance(self, seed):
|
| 107 |
+
rng = np.random.default_rng(seed)
|
| 108 |
+
r, th = float(rng.uniform(self.R_MIN, self.R_MAX)), float(rng.uniform(-np.pi, np.pi))
|
| 109 |
+
return dict(seed=int(seed), layout=str(rng.choice(self.LAYOUTS)),
|
| 110 |
+
bias=[round(r * np.cos(th), 4), round(r * np.sin(th), 4), 0.0], bias_r=round(r, 4),
|
| 111 |
+
bias_theta=round(th, 4))
|
| 112 |
+
|
| 113 |
+
def bias(self, inst):
|
| 114 |
+
return np.asarray(inst["bias"], float)
|
| 115 |
+
|
| 116 |
+
def setup_text(self, inst):
|
| 117 |
+
L = inst["layout"]
|
| 118 |
+
return "\n".join([f"- red cube on mark {L}1, bowl on mark {L}2 (layout {L});",
|
| 119 |
+
"- nothing else on the table."])
|
| 120 |
+
|
| 121 |
+
def checklist(self, inst):
|
| 122 |
+
return ["the red cube is inside the bowl (resting in it, not on the rim)",
|
| 123 |
+
"the gripper is open and not holding the cube"]
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l1_bias.py
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L1-A bias_place: pick up the cream cheese and put it into the bowl, with a miscalibrated arm.
|
| 2 |
+
|
| 3 |
+
Level L1 (action fine-tuning): the method (top-down pick across the cheese's short side, carry, release
|
| 4 |
+
above the bowl) and the scene understanding are right; only execution precision is off.
|
| 5 |
+
|
| 6 |
+
Hidden variable: a fixed calibration offset b = r (cos th, sin th, 0), r ~ U[R_MIN, R_MAX], th ~ U[0, 2 pi),
|
| 7 |
+
added to every commanded gripper position (`Skills(bias=b)`). The agent never sees b; positions reported
|
| 8 |
+
back to it must be in the commanded frame (`TrackedSkills.reported_eef_pos`), otherwise b leaks.
|
| 9 |
+
|
| 10 |
+
Robot: the gripper is a short-stroke parallel gripper (max opening GRIPPER_MAX_OPEN = 5.0 cm, e.g. a
|
| 11 |
+
Robotiq Hand-E; implemented by narrowing the Panda finger actuators' ctrlrange). The cream cheese is
|
| 12 |
+
4.27 cm wide, so the open fingers clear it by ~3.5 mm per side.
|
| 13 |
+
|
| 14 |
+
Why the prior fails. Sent to the true cheese position, the gripper arrives b away. If the component of b
|
| 15 |
+
across the cheese (jaw-closing direction) exceeds ~0.7-1.0 cm (measured), a finger comes down on top of the
|
| 16 |
+
cheese, the hand stops ~1.5 cm too high and the jaws close above it -> missed grasp, visible in both
|
| 17 |
+
cameras. With the stock 8 cm Panda stroke the measured tolerance is ~2.4 cm, so most r in [2, 4] cm would
|
| 18 |
+
not fail; that is why the stroke is reduced. The component of b along the cheese does not matter much
|
| 19 |
+
(the finger pads can grip anywhere along its 8.1 cm length, and the in-hand offset cancels at the place
|
| 20 |
+
because the same b is added there), and the bowl is forgiving.
|
| 21 |
+
|
| 22 |
+
What has to be learned: the F2 feedback reports where the gripper closed relative to the cheese's centre
|
| 23 |
+
(forward/backward, left/right in the robot frame). That offset is b itself, so after one failure b can be
|
| 24 |
+
estimated and subtracted from every commanded position (pick and place alike).
|
| 25 |
+
"""
|
| 26 |
+
import numpy as np
|
| 27 |
+
|
| 28 |
+
from .. import envs
|
| 29 |
+
from ..bddl import write_bddl
|
| 30 |
+
from ..skills import Skills
|
| 31 |
+
from ..task_base import LFFTask, register_task
|
| 32 |
+
|
| 33 |
+
CHEESE, BOWL = "cream_cheese_1", "akita_black_bowl_1"
|
| 34 |
+
JUICE = "orange_juice_1"
|
| 35 |
+
DISTRACTORS = ("butter_1", "chocolate_pudding_1", JUICE)
|
| 36 |
+
ALL = (CHEESE, BOWL) + DISTRACTORS
|
| 37 |
+
NAMES = {CHEESE: "cream cheese", BOWL: "bowl", "butter_1": "butter", "chocolate_pudding_1": "chocolate pudding",
|
| 38 |
+
JUICE: "orange juice carton"}
|
| 39 |
+
# descriptive names for the indirect variant (same wording as l2_knock_restore where objects overlap)
|
| 40 |
+
DESCR = {CHEESE: "blue box", BOWL: "grey bowl", "butter_1": "small orange box", "chocolate_pudding_1": "brown box",
|
| 41 |
+
JUICE: "tall juice carton"}
|
| 42 |
+
# Cream cheese collision box: 8.12 x 4.27 x 1.79 cm, lying flat, long side along its x axis.
|
| 43 |
+
# Realistic masses (LIBERO's are 5-10 g): a 6 g cheese is shoved aside by a finger landing on its edge.
|
| 44 |
+
MASS = {CHEESE: 0.227, "butter_1": 0.250, "chocolate_pudding_1": 0.200, BOWL: 0.300}
|
| 45 |
+
|
| 46 |
+
# finger tips (0.97 cm below the gripper site) just clear the table; the pads cover 0.6-1.8 cm of the cheese
|
| 47 |
+
Z_GRASP = envs.TABLE_Z + 0.0105
|
| 48 |
+
Z_CARRY = envs.TABLE_Z + 0.20 # clears the 13 cm juice carton with the cheese hanging below the fingers
|
| 49 |
+
BOWL_RIM = 0.0505 # rim height of the akita bowl above its lowest point
|
| 50 |
+
BOWL_R_IN = 0.046 # inner radius of the bowl at the rim
|
| 51 |
+
RELEASE_ABOVE_RIM = 0.012 # gripper site above the rim at release (finger pads clear the rim)
|
| 52 |
+
|
| 53 |
+
R_MIN, R_MAX = 0.025, 0.040 # bias magnitude range (m)
|
| 54 |
+
GRIPPER_MAX_OPEN = 0.050 # short-stroke gripper: max finger gap (m); the cheese is 4.27 cm wide
|
| 55 |
+
CHEESE_YAW_MAX = np.deg2rad(10)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
HOME_XY = np.array([-0.21, 0.0]) # gripper xy at reset
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _seg_dist(p, a, b):
|
| 62 |
+
"""distance from point p to segment ab (2-D)"""
|
| 63 |
+
ab = b - a
|
| 64 |
+
u = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0, 1)
|
| 65 |
+
return float(np.linalg.norm(a + u * ab - p))
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _q(axis, a):
|
| 69 |
+
h = a / 2
|
| 70 |
+
return {"y": np.array([np.cos(h), 0, np.sin(h), 0]), "z": np.array([np.cos(h), 0, 0, np.sin(h)])}[axis]
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _qmul(a, b):
|
| 74 |
+
"""wxyz quaternion product a*b"""
|
| 75 |
+
w1, x1, y1, z1 = a
|
| 76 |
+
w2, x2, y2, z2 = b
|
| 77 |
+
return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
|
| 78 |
+
w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2])
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def set_gripper_stroke(env, max_open):
|
| 82 |
+
"""Limit the jaw opening: each finger's position actuator gets the range [0, max_open/2] (robosuite maps
|
| 83 |
+
the open/close command onto the actuator ctrlrange, so "open" now means max_open). The pad faces sit
|
| 84 |
+
0.5 mm inside the joint position, hence the small correction."""
|
| 85 |
+
m = env.sim.model
|
| 86 |
+
half = max_open / 2 + 0.0005
|
| 87 |
+
a1, a2 = [m.actuator_name2id(a) for a in env.robots[0].gripper.actuators]
|
| 88 |
+
m.actuator_ctrlrange[a1] = [0.0, half]
|
| 89 |
+
m.actuator_ctrlrange[a2] = [-half, 0.0]
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def dir_words(dx, dy):
|
| 93 |
+
"""Robot-frame description: +x = forward (away from the robot), +y = the robot's left."""
|
| 94 |
+
parts = []
|
| 95 |
+
if abs(dy) >= 0.0005:
|
| 96 |
+
parts.append(f"{100 * abs(dy):.1f} cm to the robot's {'left (+y)' if dy > 0 else 'right (-y)'}")
|
| 97 |
+
if abs(dx) >= 0.0005:
|
| 98 |
+
parts.append(f"{100 * abs(dx):.1f} cm {'forward (+x, away from the robot)' if dx > 0 else 'backward (-x, toward the robot)'}")
|
| 99 |
+
return " and ".join(parts) if parts else "exactly at the position"
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class TrackedSkills(Skills):
|
| 103 |
+
"""Skills that log what the outcome measurement needs, whoever drives them (scripted policy or agent):
|
| 104 |
+
where the gripper was and what the fingers touched when the jaws closed, and where the cheese was when
|
| 105 |
+
the jaws opened while holding it."""
|
| 106 |
+
|
| 107 |
+
def __init__(self, env, bias=None, recorder=None):
|
| 108 |
+
super().__init__(env, bias=bias, recorder=recorder)
|
| 109 |
+
self.events = []
|
| 110 |
+
self.cheese_z0 = float(envs.obj_pos(env, CHEESE)[2])
|
| 111 |
+
self.cheese_zmax = self.cheese_z0
|
| 112 |
+
m = env.sim.model
|
| 113 |
+
self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_")]
|
| 114 |
+
self._obj_geoms = {n: envs.obj_geom_ids(env, n) for n in ALL}
|
| 115 |
+
# where the cheese was before the gripper last touched it (the reference for the grasp offset, so that
|
| 116 |
+
# a finger shoving the cheese aside on the way down does not corrupt the measurement)
|
| 117 |
+
self.cheese_ref = envs.obj_pos(env, CHEESE)
|
| 118 |
+
|
| 119 |
+
def reported_eef_pos(self):
|
| 120 |
+
"""End-effector position as the miscalibrated robot believes it to be (commanded frame). Anything
|
| 121 |
+
shown to the agent must use this, never eef_pos(), which is the true position and reveals b."""
|
| 122 |
+
return self.eef_pos() - self.bias
|
| 123 |
+
|
| 124 |
+
def move_to(self, target, *args, **kwargs):
|
| 125 |
+
rep = super().move_to(target, *args, **kwargs)
|
| 126 |
+
rep["pos"] = np.round(self.reported_eef_pos(), 4).tolist() # do not leak b through the report
|
| 127 |
+
return rep
|
| 128 |
+
|
| 129 |
+
def touching(self):
|
| 130 |
+
"""Objects the gripper is in contact with right now."""
|
| 131 |
+
return [n for n, gs in self._obj_geoms.items() if envs.contacts_between(self.env, self._grip_geoms, gs)]
|
| 132 |
+
|
| 133 |
+
def _act(self, dpos, drot, grip):
|
| 134 |
+
super()._act(dpos, drot, grip)
|
| 135 |
+
self.cheese_zmax = max(self.cheese_zmax, float(envs.obj_pos(self.env, CHEESE)[2]))
|
| 136 |
+
if self.grip < 0 and not envs.contacts_between(self.env, self._grip_geoms, self._obj_geoms[CHEESE]):
|
| 137 |
+
self.cheese_ref = envs.obj_pos(self.env, CHEESE)
|
| 138 |
+
|
| 139 |
+
def set_gripper(self, close, steps=15):
|
| 140 |
+
if close and self.grip < 0:
|
| 141 |
+
self.events.append(dict(kind="close", eef=self.eef_pos().tolist(),
|
| 142 |
+
cheese=envs.obj_pos(self.env, CHEESE).tolist(),
|
| 143 |
+
cheese_ref=np.asarray(self.cheese_ref).tolist(), touching=self.touching(),
|
| 144 |
+
cheese_top=envs.obj_max_z(self.env, CHEESE), step=self.n_steps))
|
| 145 |
+
elif not close and self.grip > 0 and self.holding(CHEESE):
|
| 146 |
+
self.events.append(dict(kind="release", eef=self.eef_pos().tolist(),
|
| 147 |
+
cheese=envs.obj_pos(self.env, CHEESE).tolist(),
|
| 148 |
+
bowl=envs.obj_pos(self.env, BOWL).tolist(), step=self.n_steps))
|
| 149 |
+
return super().set_gripper(close, steps)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
@register_task
|
| 153 |
+
class BiasPlace(LFFTask):
|
| 154 |
+
name = "l1_bias_place"
|
| 155 |
+
level = "L1"
|
| 156 |
+
category = "system_identification"
|
| 157 |
+
capabilities = ("Perceive", "Utilize")
|
| 158 |
+
protocol = "cross"
|
| 159 |
+
# LIBERO calls the bowl "akita black bowl", but under our renderer it looks silver-grey with a gold rim, so
|
| 160 |
+
# the colour is not used in the direct instruction (there is only one bowl).
|
| 161 |
+
instruction = "Pick up the cream cheese and put it into the bowl."
|
| 162 |
+
instruction_indirect = "Pick up the flat blue box with the white oval label and put it into the round grey bowl."
|
| 163 |
+
pick_lift_min = 0.03 # cheese counted as picked up if it rose this much
|
| 164 |
+
|
| 165 |
+
# ------------------------------------------------------------ scene
|
| 166 |
+
def make_bddl(self):
|
| 167 |
+
# regions are only used by LIBERO's reset-time sampler (the layout is overridden in apply_instance)
|
| 168 |
+
objs = [(CHEESE, "cream_cheese", "cheese_region", (-0.16, -0.22, -0.14, -0.20)),
|
| 169 |
+
(BOWL, "akita_black_bowl", "bowl_region", (-0.01, 0.15, 0.01, 0.17)),
|
| 170 |
+
("butter_1", "butter", "butter_region", (-0.16, 0.10, -0.14, 0.12)),
|
| 171 |
+
("chocolate_pudding_1", "chocolate_pudding", "pudding_region", (0.04, -0.17, 0.06, -0.15)),
|
| 172 |
+
(JUICE, "orange_juice", "juice_region", (-0.15, -0.03, -0.13, -0.01))]
|
| 173 |
+
return write_bddl(self.name, self.instruction, objs)
|
| 174 |
+
|
| 175 |
+
def __init__(self, cam_res=None):
|
| 176 |
+
super().__init__(cam_res)
|
| 177 |
+
# LIBERO's own upright orientation of every object, read off the reset state
|
| 178 |
+
self._base_quat = {n: envs.obj_quat(self.env, n) for n in ALL}
|
| 179 |
+
|
| 180 |
+
def _place(self, name, xy, yaw):
|
| 181 |
+
q = _qmul(_q("z", yaw), self._base_quat[name])
|
| 182 |
+
envs.set_obj_pose(self.env, name, [xy[0], xy[1], envs.TABLE_Z + 0.3], quat_wxyz=q)
|
| 183 |
+
self.env.sim.forward()
|
| 184 |
+
qa, _ = envs.free_joint_addr(self.env, name)
|
| 185 |
+
self.env.sim.data.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (envs.TABLE_Z + 0.0005)
|
| 186 |
+
self.env.sim.forward()
|
| 187 |
+
|
| 188 |
+
def sample_instance(self, seed):
|
| 189 |
+
rng = np.random.default_rng(seed)
|
| 190 |
+
while True:
|
| 191 |
+
c = np.array([rng.uniform(-0.16, 0.04), rng.uniform(-0.20, 0.20)])
|
| 192 |
+
bowl = np.array([rng.uniform(-0.15, 0.08), rng.uniform(-0.24, 0.24)])
|
| 193 |
+
if np.linalg.norm(bowl - c) < 0.20:
|
| 194 |
+
continue
|
| 195 |
+
placed = [c, bowl]
|
| 196 |
+
dis = {}
|
| 197 |
+
for name in DISTRACTORS:
|
| 198 |
+
for _ in range(300):
|
| 199 |
+
p = np.array([rng.uniform(-0.22, 0.10), rng.uniform(-0.27, 0.27)])
|
| 200 |
+
if any(np.linalg.norm(p - o) < (0.13 if k < 2 else 0.11) for k, o in enumerate(placed)):
|
| 201 |
+
continue
|
| 202 |
+
if name == JUICE:
|
| 203 |
+
# the 13 cm carton is taller than the hand when it grasps / releases: the Panda hand spans
|
| 204 |
+
# +-10.5 cm across the jaws, so keep the carton >= 17 cm from the cheese and the bowl;
|
| 205 |
+
# it must also not hide them from the front camera, and must stay >= 10 cm off the
|
| 206 |
+
# straight paths home->cheese, home->bowl and cheese->bowl
|
| 207 |
+
if np.linalg.norm(p - c) < 0.17 or np.linalg.norm(p - bowl) < 0.17:
|
| 208 |
+
continue
|
| 209 |
+
if any(p[0] > t[0] - 0.03 and abs(p[1] - t[1]) < 0.14 for t in (c, bowl)):
|
| 210 |
+
continue
|
| 211 |
+
if any(_seg_dist(p, a, b) < 0.10 for a, b in ((c, bowl), (HOME_XY, c), (HOME_XY, bowl))):
|
| 212 |
+
continue
|
| 213 |
+
break
|
| 214 |
+
else:
|
| 215 |
+
break
|
| 216 |
+
placed.append(p)
|
| 217 |
+
dis[name] = dict(xy=p.round(5).tolist(), yaw=float(rng.uniform(-np.pi, np.pi)))
|
| 218 |
+
if len(dis) == len(DISTRACTORS):
|
| 219 |
+
break
|
| 220 |
+
psi = float(rng.uniform(-CHEESE_YAW_MAX, CHEESE_YAW_MAX))
|
| 221 |
+
n = np.array([-np.sin(psi), np.cos(psi)]) # jaw-closing direction for a grasp across the cheese
|
| 222 |
+
l = np.array([np.cos(psi), np.sin(psi)])
|
| 223 |
+
r = rng.uniform(R_MIN, R_MAX)
|
| 224 |
+
th = rng.uniform(0, 2 * np.pi)
|
| 225 |
+
b = np.array([r * np.cos(th), r * np.sin(th)])
|
| 226 |
+
return dict(seed=int(seed), cheese_xy=c.round(5).tolist(), cheese_yaw=psi, bowl_xy=bowl.round(5).tolist(),
|
| 227 |
+
distractors=dis, bias=[float(b[0]), float(b[1]), 0.0], bias_r=float(r), bias_theta=float(th),
|
| 228 |
+
bias_across=float(b @ n), bias_along=float(b @ l))
|
| 229 |
+
|
| 230 |
+
def apply_instance(self, inst):
|
| 231 |
+
set_gripper_stroke(self.env, GRIPPER_MAX_OPEN)
|
| 232 |
+
for name, mass in MASS.items():
|
| 233 |
+
envs.scale_mass(self.env, name, mass)
|
| 234 |
+
self._place(CHEESE, inst["cheese_xy"], inst["cheese_yaw"])
|
| 235 |
+
self._place(BOWL, inst["bowl_xy"], 0.0)
|
| 236 |
+
for name, v in inst["distractors"].items():
|
| 237 |
+
self._place(name, v["xy"], v["yaw"])
|
| 238 |
+
|
| 239 |
+
def skill_bias(self, inst):
|
| 240 |
+
return np.array(inst["bias"], float)
|
| 241 |
+
|
| 242 |
+
def reset_instance(self, inst, recorder=None):
|
| 243 |
+
self.env.reset()
|
| 244 |
+
self.apply_instance(inst)
|
| 245 |
+
self.env.sim.forward()
|
| 246 |
+
envs.settle(self.env, 10)
|
| 247 |
+
self.sk = TrackedSkills(self.env, bias=self.skill_bias(inst), recorder=recorder)
|
| 248 |
+
self.start_pos = {n: envs.obj_pos(self.env, n) for n in ALL}
|
| 249 |
+
return self.sk
|
| 250 |
+
|
| 251 |
+
# ------------------------------------------------------------ outcome
|
| 252 |
+
def in_bowl(self):
|
| 253 |
+
k = envs.obj_pos(self.env, BOWL)
|
| 254 |
+
c = envs.obj_pos(self.env, CHEESE)
|
| 255 |
+
base = envs.obj_min_z(self.env, BOWL)
|
| 256 |
+
return bool(np.linalg.norm(c[:2] - k[:2]) < BOWL_R_IN and c[2] < base + BOWL_RIM
|
| 257 |
+
and envs.obj_upright_cos(self.env, BOWL) > 0.9 and base < envs.TABLE_Z + 0.01)
|
| 258 |
+
|
| 259 |
+
def outcome(self, inst):
|
| 260 |
+
envs.settle(self.env, 40)
|
| 261 |
+
sk = self.sk
|
| 262 |
+
k = envs.obj_pos(self.env, BOWL)
|
| 263 |
+
c = envs.obj_pos(self.env, CHEESE)
|
| 264 |
+
held = sk.holding(CHEESE)
|
| 265 |
+
success = bool(self.in_bowl() and not held)
|
| 266 |
+
picked = sk.cheese_zmax > sk.cheese_z0 + self.pick_lift_min
|
| 267 |
+
closes = [e for e in sk.events if e["kind"] == "close"]
|
| 268 |
+
last_close = closes[-1] if closes else None
|
| 269 |
+
releases = [e for e in sk.events if e["kind"] == "release" and last_close and e["step"] >= last_close["step"]]
|
| 270 |
+
end_off = c[:2] - k[:2]
|
| 271 |
+
moved = {n: float(np.linalg.norm(envs.obj_pos(self.env, n)[:2] - self.start_pos[n][:2]))
|
| 272 |
+
for n in DISTRACTORS}
|
| 273 |
+
out = dict(success=success, picked=bool(picked), held_at_end=bool(held),
|
| 274 |
+
cheese_end=c.round(4).tolist(), bowl_end=k.round(4).tolist(), end_offset=end_off.round(4).tolist(),
|
| 275 |
+
grasp_offset=None, release_offset=None, touched_at_close=None,
|
| 276 |
+
distractors_moved_cm={n: round(100 * v, 1) for n, v in moved.items()})
|
| 277 |
+
grasp_txt = ""
|
| 278 |
+
if last_close is not None:
|
| 279 |
+
go = np.array(last_close["eef"][:2]) - np.array(last_close["cheese_ref"][:2])
|
| 280 |
+
out["grasp_offset"] = go.round(4).tolist()
|
| 281 |
+
out["touched_at_close"] = last_close["touching"]
|
| 282 |
+
out["cheese_pushed_cm"] = round(100 * float(np.linalg.norm(
|
| 283 |
+
np.array(last_close["cheese"][:2]) - np.array(last_close["cheese_ref"][:2]))), 1)
|
| 284 |
+
grasp_txt = (f"The gripper closed {dir_words(*go)} of the centre of the cream cheese (measured where "
|
| 285 |
+
f"the cheese was before the fingers touched it)")
|
| 286 |
+
if releases:
|
| 287 |
+
r = releases[-1]
|
| 288 |
+
out["release_offset"] = (np.array(r["cheese"][:2]) - np.array(r["bowl"][:2])).round(4).tolist()
|
| 289 |
+
if success:
|
| 290 |
+
out["failure"] = None
|
| 291 |
+
detail = "The cream cheese is in the bowl."
|
| 292 |
+
if grasp_txt:
|
| 293 |
+
detail += f" {grasp_txt}."
|
| 294 |
+
elif not picked:
|
| 295 |
+
out["failure"] = "missed_grasp"
|
| 296 |
+
if last_close is None:
|
| 297 |
+
detail = "The gripper never closed; the cream cheese was not picked up."
|
| 298 |
+
else:
|
| 299 |
+
on = [NAMES[n] for n in last_close["touching"] if n != CHEESE]
|
| 300 |
+
why = ""
|
| 301 |
+
if on:
|
| 302 |
+
why = (f" A finger landed on top of the {' and the '.join(on)} instead of going down beside the "
|
| 303 |
+
f"cheese, so the jaws closed above the cheese.")
|
| 304 |
+
elif CHEESE in last_close["touching"] and not sk.holding(CHEESE):
|
| 305 |
+
why = " A finger came down on top of the cream cheese instead of beside it."
|
| 306 |
+
elif not last_close["touching"] and last_close.get("cheese_top") is not None:
|
| 307 |
+
above = last_close["eef"][2] - envs.FINGERTIP_BELOW_SITE - last_close["cheese_top"]
|
| 308 |
+
if above > 0.002: # closed in the air, entirely above the cheese
|
| 309 |
+
why = (f" The fingers closed in the air without touching anything: the fingertips were "
|
| 310 |
+
f"{100 * above:.1f} cm above the top of the cream cheese.")
|
| 311 |
+
detail = f"{grasp_txt} and did not pick it up.{why} The cream cheese is still on the table."
|
| 312 |
+
elif held:
|
| 313 |
+
out["failure"] = "not_released"
|
| 314 |
+
detail = f"{grasp_txt} and picked it up, but the cream cheese is still in the gripper."
|
| 315 |
+
elif releases:
|
| 316 |
+
out["failure"] = "missed_place"
|
| 317 |
+
detail = (f"{grasp_txt} and picked it up. When the gripper opened, the cream cheese was "
|
| 318 |
+
f"{dir_words(*out['release_offset'])} of the bowl's centre; it did not end up in the bowl "
|
| 319 |
+
f"(it is now {dir_words(*end_off)} of the bowl's centre).")
|
| 320 |
+
else:
|
| 321 |
+
out["failure"] = "dropped"
|
| 322 |
+
detail = (f"{grasp_txt} and picked it up, but it slipped out of the gripper before it was released; "
|
| 323 |
+
f"it is now {dir_words(*end_off)} of the bowl's centre.")
|
| 324 |
+
out["detail"] = detail
|
| 325 |
+
ind = detail
|
| 326 |
+
for k in (JUICE, "chocolate_pudding_1", "butter_1", CHEESE, BOWL): # longest names first
|
| 327 |
+
ind = ind.replace(NAMES[k], DESCR[k])
|
| 328 |
+
out["detail_indirect"] = ind
|
| 329 |
+
return out
|
| 330 |
+
|
| 331 |
+
def feedback(self, inst, out, level="F2", indirect=False):
|
| 332 |
+
"""F0: nothing, F1: success flag, F2: measured offsets. `indirect` uses descriptive object names."""
|
| 333 |
+
if indirect and level == "F2":
|
| 334 |
+
out = dict(out, detail=out.get("detail_indirect", out["detail"]))
|
| 335 |
+
return super().feedback(inst, out, level)
|
| 336 |
+
|
| 337 |
+
# ------------------------------------------------------------ scripted execution (cross protocol)
|
| 338 |
+
def execute(self, inst, params):
|
| 339 |
+
"""Top-down pick across the cheese's short side, carry, release above the bowl.
|
| 340 |
+
params['offset'] (xy) is the policy's own correction, added to every commanded position."""
|
| 341 |
+
sk = self.sk
|
| 342 |
+
off = np.array(params.get("offset", [0.0, 0.0]), float)
|
| 343 |
+
c = envs.obj_pos(self.env, CHEESE) # perfect perception of the current scene
|
| 344 |
+
yaw = self.grasp_yaw()
|
| 345 |
+
k = envs.obj_pos(self.env, BOWL)
|
| 346 |
+
z_rel = envs.obj_min_z(self.env, BOWL) + BOWL_RIM + RELEASE_ABOVE_RIM
|
| 347 |
+
g, p = c[:2] + off, k[:2] + off
|
| 348 |
+
sk.set_gripper(False, steps=8)
|
| 349 |
+
sk.move_to([g[0], g[1], Z_CARRY], yaw=yaw) # approach from above, clear of the 13 cm carton
|
| 350 |
+
sk.move_to([g[0], g[1], Z_GRASP + 0.08], tol=0.002)
|
| 351 |
+
sk.move_to([g[0], g[1], Z_GRASP], tol=0.003, max_steps=80)
|
| 352 |
+
sk.set_gripper(True, steps=15)
|
| 353 |
+
sk.move_to([g[0], g[1], Z_CARRY], speed=0.3)
|
| 354 |
+
if not sk.holding(CHEESE): # missed: a real controller sees the jaws closed on nothing and stops
|
| 355 |
+
return
|
| 356 |
+
sk.move_to([p[0], p[1], Z_CARRY], tol=0.003)
|
| 357 |
+
sk.move_to([p[0], p[1], z_rel], tol=0.003, max_steps=100)
|
| 358 |
+
sk.set_gripper(False, steps=12)
|
| 359 |
+
sk.move_to([p[0], p[1], Z_CARRY], speed=0.3)
|
| 360 |
+
|
| 361 |
+
def grasp_yaw(self):
|
| 362 |
+
"""Gripper yaw that closes the jaws across the cheese's short side (yaw 0 closes along world y)."""
|
| 363 |
+
xmat = self.env.sim.data.body_xmat[envs.body_id(self.env, CHEESE)].reshape(3, 3)
|
| 364 |
+
a = np.arctan2(xmat[1, 0], xmat[0, 0]) # direction of the cheese's long (x) axis
|
| 365 |
+
return float((a + np.pi / 2) % np.pi - np.pi / 2)
|
| 366 |
+
|
| 367 |
+
def default_params(self, inst):
|
| 368 |
+
return dict(offset=[0.0, 0.0])
|
| 369 |
+
|
| 370 |
+
def oracle_params(self, inst):
|
| 371 |
+
return dict(offset=(-np.array(inst["bias"][:2])).tolist())
|
| 372 |
+
|
| 373 |
+
def adapt_params(self, inst, history):
|
| 374 |
+
"""Scripted F2 learner: the reported grasp offset (where the gripper closed relative to the cheese's
|
| 375 |
+
centre) measures the calibration offset; accumulate it into the correction subtracted from every
|
| 376 |
+
commanded position. If the gripper never closed, fall back to the release offset."""
|
| 377 |
+
last = history[-1]
|
| 378 |
+
off = np.array(last["params"]["offset"], float)
|
| 379 |
+
o = last["outcome"]
|
| 380 |
+
if o.get("grasp_offset") is not None:
|
| 381 |
+
off = off - np.array(o["grasp_offset"])
|
| 382 |
+
elif o.get("release_offset") is not None:
|
| 383 |
+
off = off - np.array(o["release_offset"])
|
| 384 |
+
return dict(offset=off.round(4).tolist())
|
| 385 |
+
|
| 386 |
+
blind_sigma = 0.005
|
| 387 |
+
|
| 388 |
+
def blind_params(self, inst, attempt, rng):
|
| 389 |
+
"""Retry the same plan with a small random perturbation of the targets; no use of history."""
|
| 390 |
+
return dict(offset=rng.normal(0.0, self.blind_sigma, 2).round(4).tolist())
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l1_height.py
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L1-B height_bias: pick up a thin tile from the top of a wooden block and put it on the plate, with an arm whose
|
| 2 |
+
vertical calibration is off.
|
| 3 |
+
|
| 4 |
+
Category system_identification (level L1, action fine-tuning): the method (top-down pick across the tile's short
|
| 5 |
+
side with the fingertips just above the block's top, carry, release above the plate) and the scene understanding
|
| 6 |
+
are right; only the robot's own vertical execution is off.
|
| 7 |
+
|
| 8 |
+
Hidden variable: a fixed vertical calibration offset dz ~ U[2.0, 3.5] cm (always upward), added to every
|
| 9 |
+
commanded gripper position (`Skills(bias=(0, 0, dz))`): the gripper stops dz higher than commanded. The agent never
|
| 10 |
+
sees dz; positions reported back to it are in the commanded frame (`HeightSkills.reported_eef_pos`, and the agent
|
| 11 |
+
harness reports eef - bias), so the robot "believes" it reached the commanded height.
|
| 12 |
+
|
| 13 |
+
Why the prior fails: the tile is 1.0 cm thick. Sent to the right height (fingertips just above the block's top), the
|
| 14 |
+
fingertips actually stop 2-3.5 cm higher, i.e. 1.1-2.6 cm above the tile's top face, and the jaws close in the air
|
| 15 |
+
above it (measured tolerance, 6 layouts: upward errors up to 0.4 cm still grasp, >= 0.7 cm never do, i.e. the fingers
|
| 16 |
+
must overlap the tile by ~4 mm). dz >= 2 cm also defeats a prior that aims lower: even with the grasp point commanded
|
| 17 |
+
level with the block's top (fingertips ~1 cm into the block), the fingertips end up >= 1.05 cm above the block's
|
| 18 |
+
top, i.e. not below the tile's top face -> missed.
|
| 19 |
+
Visible in the agentview image (gap between the closed fingers and the tile) and in the wrist image (fingers closed
|
| 20 |
+
over the tile).
|
| 21 |
+
A downward error would not fail (the fingertips land on the block's top and the compliant OSC still closes on the
|
| 22 |
+
tile; measured for -1 and -2 cm), so the offset is upward only.
|
| 23 |
+
|
| 24 |
+
Why a raised block: the agent's move_to clips commanded targets to >= table + 0.5 cm. With the tile on the table,
|
| 25 |
+
compensating a 2-3.5 cm upward offset would need commands below the table top, which the interface refuses; on a
|
| 26 |
+
6-10 cm block the compensated commands stay well inside the workspace.
|
| 27 |
+
|
| 28 |
+
What has to be learned: F2 reports how far above the tile's top face the grasp point and the fingertips were when the
|
| 29 |
+
jaws closed. Compared with where the policy meant to put them, that is dz itself, so after one failure dz can be
|
| 30 |
+
estimated and subtracted from every commanded height (pick and place alike).
|
| 31 |
+
"""
|
| 32 |
+
import re
|
| 33 |
+
|
| 34 |
+
import numpy as np
|
| 35 |
+
|
| 36 |
+
from .. import envs
|
| 37 |
+
from ..bddl import write_bddl
|
| 38 |
+
from ..objects import box_xml, register_generated
|
| 39 |
+
from ..skills import Skills
|
| 40 |
+
from ..task_base import LFFTask, register_task
|
| 41 |
+
|
| 42 |
+
TILE, STAND, PLATE = "tile_1", "stand_1", "plate_1"
|
| 43 |
+
DISTRACTORS = ("butter_1", "chocolate_pudding_1")
|
| 44 |
+
FREE_OBJECTS = (TILE, PLATE) + DISTRACTORS
|
| 45 |
+
NAMES = {TILE: "red tile", STAND: "wooden block", PLATE: "plate", "butter_1": "butter",
|
| 46 |
+
"chocolate_pudding_1": "chocolate pudding"}
|
| 47 |
+
DESCR = {TILE: "thin red slab", STAND: "large wooden pedestal", PLATE: "round white dish", "butter_1": "small orange box",
|
| 48 |
+
"chocolate_pudding_1": "brown box"}
|
| 49 |
+
|
| 50 |
+
TILE_HALF = (0.040, 0.0225, 0.005) # 8.0 x 4.5 x 1.0 cm (long side along the tile's x axis)
|
| 51 |
+
TILE_T = 2 * TILE_HALF[2]
|
| 52 |
+
STAND_HALF_XY = (0.075, 0.085) # 15 x 17 cm top
|
| 53 |
+
STAND_H_RANGE = (0.06, 0.10)
|
| 54 |
+
MASS = {TILE: 0.072, "butter_1": 0.250, "chocolate_pudding_1": 0.200, PLATE: 0.350}
|
| 55 |
+
|
| 56 |
+
FINGER_BELOW_SITE = 0.0095 # lowest point of the finger collision meshes below the grasp site (measured 0.95 cm)
|
| 57 |
+
SITE_ABOVE_SURFACE = 0.0105 # scripted grasp height: grasp point 1.05 cm above the block top (fingertips ~1 mm above)
|
| 58 |
+
CARRY_ABOVE = 0.12 # carry height above the block top
|
| 59 |
+
RELEASE_GAP = 0.012 # tile bottom this far above the plate's rim at release
|
| 60 |
+
PLATE_R_OK = 0.040 # success: tile centre within this horizontal distance of the plate centre
|
| 61 |
+
DZ_MIN, DZ_MAX = 0.020, 0.035
|
| 62 |
+
TILE_YAW_MAX = np.deg2rad(40)
|
| 63 |
+
HOME_XY = np.array([-0.21, 0.0])
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _seg_dist(p, a, b):
|
| 67 |
+
ab = b - a
|
| 68 |
+
u = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0, 1)
|
| 69 |
+
return float(np.linalg.norm(a + u * ab - p))
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _q(axis, a):
|
| 73 |
+
h = a / 2
|
| 74 |
+
return {"z": np.array([np.cos(h), 0, 0, np.sin(h)])}[axis]
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _qmul(a, b):
|
| 78 |
+
w1, x1, y1, z1 = a
|
| 79 |
+
w2, x2, y2, z2 = b
|
| 80 |
+
return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
|
| 81 |
+
w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2])
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def dir_words(dx, dy):
|
| 85 |
+
"""Robot-frame description: +x = forward (away from the robot), +y = the robot's left."""
|
| 86 |
+
parts = []
|
| 87 |
+
if abs(dy) >= 0.0005:
|
| 88 |
+
parts.append(f"{100 * abs(dy):.1f} cm to the robot's {'left (+y)' if dy > 0 else 'right (-y)'}")
|
| 89 |
+
if abs(dx) >= 0.0005:
|
| 90 |
+
parts.append(f"{100 * abs(dx):.1f} cm {'forward (+x, away from the robot)' if dx > 0 else 'backward (-x, toward the robot)'}")
|
| 91 |
+
return " and ".join(parts) if parts else "exactly at the position"
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def vert_words(h, what):
|
| 95 |
+
if h >= 0.0005:
|
| 96 |
+
return f"{100 * h:.1f} cm above {what}"
|
| 97 |
+
if h <= -0.0005:
|
| 98 |
+
return f"{100 * -h:.1f} cm below {what}"
|
| 99 |
+
return f"level with {what}"
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class HeightSkills(Skills):
|
| 103 |
+
"""Skills that log what the outcome measurement needs, whoever drives them (scripted policy or agent)."""
|
| 104 |
+
|
| 105 |
+
def __init__(self, env, bias=None, recorder=None, stand_geoms=()):
|
| 106 |
+
super().__init__(env, bias=bias, recorder=recorder)
|
| 107 |
+
self.events = []
|
| 108 |
+
m = env.sim.model
|
| 109 |
+
self._finger_geoms = {
|
| 110 |
+
side: [m.geom_name2id(g) for g in env.robots[0].gripper.important_geoms[side]]
|
| 111 |
+
for side in ("left_finger", "right_finger")}
|
| 112 |
+
self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_")]
|
| 113 |
+
self._obj_geoms = {n: envs.obj_geom_ids(env, n) for n in FREE_OBJECTS}
|
| 114 |
+
self._obj_geoms[STAND] = list(stand_geoms)
|
| 115 |
+
self.tile_z0 = float(envs.obj_pos(env, TILE)[2])
|
| 116 |
+
self.tile_zmax = self.tile_z0
|
| 117 |
+
self.tile_ref = envs.obj_pos(env, TILE) # tile position before the fingers last touched it
|
| 118 |
+
self.tile_ref_yaw = self.tile_yaw()
|
| 119 |
+
|
| 120 |
+
def reported_eef_pos(self):
|
| 121 |
+
"""End-effector position as the miscalibrated robot believes it to be (commanded frame). Anything shown to
|
| 122 |
+
the agent must use this, never eef_pos(), which is the true position and reveals the bias."""
|
| 123 |
+
return self.eef_pos() - self.bias
|
| 124 |
+
|
| 125 |
+
def move_to(self, target, *args, **kwargs):
|
| 126 |
+
rep = super().move_to(target, *args, **kwargs)
|
| 127 |
+
rep["pos"] = np.round(self.reported_eef_pos(), 4).tolist()
|
| 128 |
+
return rep
|
| 129 |
+
|
| 130 |
+
def touching(self):
|
| 131 |
+
return [n for n, gs in self._obj_geoms.items() if envs.contacts_between(self.env, self._grip_geoms, gs)]
|
| 132 |
+
|
| 133 |
+
def holding_tile(self):
|
| 134 |
+
"""Both fingers in contact with the tile (robosuite's _check_grasp needs the finger *pads*, which miss a
|
| 135 |
+
1 cm tile when it is gripped low on the finger meshes)."""
|
| 136 |
+
tg = self._obj_geoms[TILE]
|
| 137 |
+
return all(envs.contacts_between(self.env, gs, tg) for gs in self._finger_geoms.values())
|
| 138 |
+
|
| 139 |
+
def holding(self, obj_name):
|
| 140 |
+
"""The agent harness reports `holding_object` through this; use the finger-contact test for the tile so a
|
| 141 |
+
tile gripped low on the fingers is not reported as dropped."""
|
| 142 |
+
if obj_name == TILE:
|
| 143 |
+
return self.holding_tile()
|
| 144 |
+
return super().holding(obj_name)
|
| 145 |
+
|
| 146 |
+
def tile_yaw(self):
|
| 147 |
+
xmat = self.env.sim.data.body_xmat[envs.body_id(self.env, TILE)].reshape(3, 3)
|
| 148 |
+
return float(np.arctan2(xmat[1, 0], xmat[0, 0]))
|
| 149 |
+
|
| 150 |
+
def finger_min_z(self):
|
| 151 |
+
return float(self.eef_pos()[2] - FINGER_BELOW_SITE)
|
| 152 |
+
|
| 153 |
+
def _act(self, dpos, drot, grip):
|
| 154 |
+
super()._act(dpos, drot, grip)
|
| 155 |
+
self.tile_zmax = max(self.tile_zmax, float(envs.obj_pos(self.env, TILE)[2]))
|
| 156 |
+
if self.grip < 0 and not envs.contacts_between(self.env, self._grip_geoms, self._obj_geoms[TILE]):
|
| 157 |
+
self.tile_ref = envs.obj_pos(self.env, TILE)
|
| 158 |
+
self.tile_ref_yaw = self.tile_yaw()
|
| 159 |
+
|
| 160 |
+
def set_gripper(self, close, steps=15):
|
| 161 |
+
if close and self.grip < 0:
|
| 162 |
+
self.events.append(dict(kind="close", eef=self.eef_pos().tolist(), finger_z=self.finger_min_z(),
|
| 163 |
+
tile=envs.obj_pos(self.env, TILE).tolist(),
|
| 164 |
+
tile_ref=np.asarray(self.tile_ref).tolist(), tile_ref_yaw=self.tile_ref_yaw,
|
| 165 |
+
touching=self.touching(),
|
| 166 |
+
step=self.n_steps))
|
| 167 |
+
elif not close and self.grip > 0 and self.holding_tile():
|
| 168 |
+
self.events.append(dict(kind="release", eef=self.eef_pos().tolist(),
|
| 169 |
+
tile=envs.obj_pos(self.env, TILE).tolist(),
|
| 170 |
+
plate=envs.obj_pos(self.env, PLATE).tolist(), step=self.n_steps))
|
| 171 |
+
return super().set_gripper(close, steps)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
@register_task
|
| 175 |
+
class HeightBias(LFFTask):
|
| 176 |
+
name = "l1_height_bias"
|
| 177 |
+
level = "L1"
|
| 178 |
+
category = "system_identification"
|
| 179 |
+
capabilities = ("Perceive", "Utilize")
|
| 180 |
+
protocol = "cross"
|
| 181 |
+
instruction = "Pick up the red tile from the top of the wooden block and put it on the plate."
|
| 182 |
+
instruction_indirect = ("Pick up the thin flat red slab lying on the large wooden pedestal and put it on the "
|
| 183 |
+
"round white dish.")
|
| 184 |
+
pick_lift_min = 0.03
|
| 185 |
+
|
| 186 |
+
# ------------------------------------------------------------ scene
|
| 187 |
+
def make_bddl(self):
|
| 188 |
+
tile = register_generated("LffHbTile", box_xml("lff_hb_tile", TILE_HALF, (0.80, 0.16, 0.12, 1.0),
|
| 189 |
+
density=2000))
|
| 190 |
+
stand = register_generated("LffHbStand", box_xml("lff_hb_stand", STAND_HALF_XY + (STAND_H_RANGE[1] / 2,),
|
| 191 |
+
(0.62, 0.47, 0.30, 1.0), density=1000), free=False)
|
| 192 |
+
objs = [(TILE, tile, "tile_region", (-0.21, -0.26, -0.19, -0.24)),
|
| 193 |
+
(PLATE, "plate", "plate_region", (-0.01, 0.24, 0.01, 0.26)),
|
| 194 |
+
("butter_1", "butter", "butter_region", (-0.21, 0.24, -0.19, 0.26)),
|
| 195 |
+
("chocolate_pudding_1", "chocolate_pudding", "pudding_region", (0.15, -0.26, 0.17, -0.24))]
|
| 196 |
+
fx = [(STAND, stand, "stand_region", (0.09, -0.01, 0.11, 0.01))]
|
| 197 |
+
return write_bddl(self.name, self.instruction, objs, fx)
|
| 198 |
+
|
| 199 |
+
def __init__(self, cam_res=None):
|
| 200 |
+
super().__init__(cam_res)
|
| 201 |
+
self._base_quat = {n: envs.obj_quat(self.env, n) for n in FREE_OBJECTS}
|
| 202 |
+
m = self.env.sim.model
|
| 203 |
+
bid = m.body_name2id(self.env.fixtures_dict[STAND].root_body)
|
| 204 |
+
|
| 205 |
+
def under(b):
|
| 206 |
+
while b > 0:
|
| 207 |
+
if b == bid:
|
| 208 |
+
return True
|
| 209 |
+
b = m.body_parentid[b]
|
| 210 |
+
return False
|
| 211 |
+
|
| 212 |
+
self._stand_bid = bid
|
| 213 |
+
self._stand_geoms = [g for g in range(m.ngeom) if under(m.geom_bodyid[g])]
|
| 214 |
+
|
| 215 |
+
def _place(self, name, xy, yaw, z0=envs.TABLE_Z):
|
| 216 |
+
q = _qmul(_q("z", yaw), self._base_quat[name])
|
| 217 |
+
envs.set_obj_pose(self.env, name, [xy[0], xy[1], z0 + 0.3], quat_wxyz=q)
|
| 218 |
+
self.env.sim.forward()
|
| 219 |
+
qa, _ = envs.free_joint_addr(self.env, name)
|
| 220 |
+
self.env.sim.data.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (z0 + 0.0005)
|
| 221 |
+
self.env.sim.forward()
|
| 222 |
+
|
| 223 |
+
def sample_instance(self, seed):
|
| 224 |
+
rng = np.random.default_rng(seed)
|
| 225 |
+
while True:
|
| 226 |
+
s = np.array([rng.uniform(-0.10, 0.02), rng.uniform(-0.17, 0.17)])
|
| 227 |
+
plate = np.array([rng.uniform(-0.17, 0.08), rng.uniform(-0.25, 0.25)])
|
| 228 |
+
if np.linalg.norm(plate - s) < 0.24 or abs(plate[1] - s[1]) < 0.12:
|
| 229 |
+
continue # not right behind the block as seen from the front camera
|
| 230 |
+
placed = [s, plate]
|
| 231 |
+
dis = {}
|
| 232 |
+
for name in DISTRACTORS:
|
| 233 |
+
for _ in range(300):
|
| 234 |
+
p = np.array([rng.uniform(-0.22, 0.12), rng.uniform(-0.27, 0.27)])
|
| 235 |
+
if np.linalg.norm(p - s) < 0.16 or any(np.linalg.norm(p - o) < 0.12 for o in placed[1:]):
|
| 236 |
+
continue
|
| 237 |
+
if any(_seg_dist(p, a, b) < 0.09 for a, b in ((s, plate), (HOME_XY, s))):
|
| 238 |
+
continue
|
| 239 |
+
break
|
| 240 |
+
else:
|
| 241 |
+
break
|
| 242 |
+
placed.append(p)
|
| 243 |
+
dis[name] = dict(xy=p.round(5).tolist(), yaw=float(rng.uniform(-np.pi, np.pi)))
|
| 244 |
+
if len(dis) == len(DISTRACTORS):
|
| 245 |
+
break
|
| 246 |
+
stand_h = float(rng.uniform(*STAND_H_RANGE))
|
| 247 |
+
tile_xy = s + rng.uniform(-0.02, 0.02, 2)
|
| 248 |
+
tile_yaw = float(rng.uniform(-TILE_YAW_MAX, TILE_YAW_MAX))
|
| 249 |
+
dz = float(rng.uniform(DZ_MIN, DZ_MAX))
|
| 250 |
+
return dict(seed=int(seed), stand_xy=s.round(5).tolist(), stand_h=stand_h, tile_xy=tile_xy.round(5).tolist(),
|
| 251 |
+
tile_yaw=tile_yaw, plate_xy=plate.round(5).tolist(), distractors=dis, bias=[0.0, 0.0, dz],
|
| 252 |
+
bias_dz=dz)
|
| 253 |
+
|
| 254 |
+
def stand_top(self, inst):
|
| 255 |
+
return envs.TABLE_Z + inst["stand_h"]
|
| 256 |
+
|
| 257 |
+
def apply_instance(self, inst):
|
| 258 |
+
m = self.env.sim.model
|
| 259 |
+
h = inst["stand_h"]
|
| 260 |
+
for g in self._stand_geoms:
|
| 261 |
+
m.geom_size[g, 2] = h / 2
|
| 262 |
+
m.body_pos[self._stand_bid] = [inst["stand_xy"][0], inst["stand_xy"][1], envs.TABLE_Z + h / 2]
|
| 263 |
+
m.body_quat[self._stand_bid] = [1, 0, 0, 0]
|
| 264 |
+
for name, mass in MASS.items():
|
| 265 |
+
envs.scale_mass(self.env, name, mass)
|
| 266 |
+
self.env.sim.forward()
|
| 267 |
+
self._place(TILE, inst["tile_xy"], inst["tile_yaw"], z0=self.stand_top(inst))
|
| 268 |
+
self._place(PLATE, inst["plate_xy"], 0.0)
|
| 269 |
+
for name, v in inst["distractors"].items():
|
| 270 |
+
self._place(name, v["xy"], v["yaw"])
|
| 271 |
+
|
| 272 |
+
def skill_bias(self, inst):
|
| 273 |
+
return np.array(inst["bias"], float)
|
| 274 |
+
|
| 275 |
+
def reset_instance(self, inst, recorder=None):
|
| 276 |
+
self.env.reset()
|
| 277 |
+
self.apply_instance(inst)
|
| 278 |
+
self.env.sim.forward()
|
| 279 |
+
envs.settle(self.env, 10)
|
| 280 |
+
self.sk = HeightSkills(self.env, bias=self.skill_bias(inst), recorder=recorder, stand_geoms=self._stand_geoms)
|
| 281 |
+
self.start_pos = {n: envs.obj_pos(self.env, n) for n in FREE_OBJECTS}
|
| 282 |
+
return self.sk
|
| 283 |
+
|
| 284 |
+
# ------------------------------------------------------------ outcome
|
| 285 |
+
def plate_rim_z(self):
|
| 286 |
+
lo, hi = self._aabb(PLATE)
|
| 287 |
+
return float(hi[2])
|
| 288 |
+
|
| 289 |
+
def _aabb(self, name):
|
| 290 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 291 |
+
lo, hi = np.full(3, np.inf), np.full(3, -np.inf)
|
| 292 |
+
for g in envs.obj_geom_ids(self.env, name):
|
| 293 |
+
R = d.geom_xmat[g].reshape(3, 3)
|
| 294 |
+
c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3]
|
| 295 |
+
hh = np.abs(R) @ m.geom_aabb[g, 3:]
|
| 296 |
+
lo, hi = np.minimum(lo, c - hh), np.maximum(hi, c + hh)
|
| 297 |
+
return lo, hi
|
| 298 |
+
|
| 299 |
+
def on_plate(self):
|
| 300 |
+
p = envs.obj_pos(self.env, PLATE)
|
| 301 |
+
t = envs.obj_pos(self.env, TILE)
|
| 302 |
+
return bool(np.linalg.norm(t[:2] - p[:2]) < PLATE_R_OK and t[2] < self.plate_rim_z() + 0.015
|
| 303 |
+
and envs.obj_upright_cos(self.env, PLATE) > 0.9 and envs.obj_min_z(self.env, PLATE) < envs.TABLE_Z + 0.01)
|
| 304 |
+
|
| 305 |
+
def outcome(self, inst):
|
| 306 |
+
envs.settle(self.env, 40)
|
| 307 |
+
sk = self.sk
|
| 308 |
+
top = self.stand_top(inst)
|
| 309 |
+
p = envs.obj_pos(self.env, PLATE)
|
| 310 |
+
t = envs.obj_pos(self.env, TILE)
|
| 311 |
+
held = sk.holding_tile()
|
| 312 |
+
success = bool(self.on_plate() and not held)
|
| 313 |
+
picked = sk.tile_zmax > sk.tile_z0 + self.pick_lift_min
|
| 314 |
+
closes = [e for e in sk.events if e["kind"] == "close"]
|
| 315 |
+
last_close = closes[-1] if closes else None
|
| 316 |
+
releases = [e for e in sk.events if e["kind"] == "release" and last_close and e["step"] >= last_close["step"]]
|
| 317 |
+
end_off = t[:2] - p[:2]
|
| 318 |
+
on_stand = bool(t[2] > top - 0.005)
|
| 319 |
+
out = dict(success=success, picked=bool(picked), held_at_end=bool(held), tile_end=t.round(4).tolist(),
|
| 320 |
+
plate_end=p.round(4).tolist(), end_offset=end_off.round(4).tolist(), grasp_height=None,
|
| 321 |
+
fingertip_gap=None, grasp_xy_offset=None, touched_at_close=None, release_offset=None)
|
| 322 |
+
grasp_txt = ""
|
| 323 |
+
over_tile = True
|
| 324 |
+
if last_close is not None:
|
| 325 |
+
tile_top = last_close["tile_ref"][2] + TILE_HALF[2]
|
| 326 |
+
gh = last_close["eef"][2] - tile_top
|
| 327 |
+
fg = last_close["finger_z"] - tile_top
|
| 328 |
+
go = np.array(last_close["eef"][:2]) - np.array(last_close["tile_ref"][:2])
|
| 329 |
+
a = last_close.get("tile_ref_yaw", 0.0)
|
| 330 |
+
along, across = go @ [np.cos(a), np.sin(a)], go @ [-np.sin(a), np.cos(a)]
|
| 331 |
+
# grasp point over the tile's footprint (the open fingers straddle it across its short side)
|
| 332 |
+
over_tile = bool(abs(along) <= TILE_HALF[0] and abs(across) <= TILE_HALF[1] + 0.01)
|
| 333 |
+
out["grasp_height"] = round(gh, 4)
|
| 334 |
+
out["fingertip_gap"] = round(fg, 4)
|
| 335 |
+
out["grasp_xy_offset"] = go.round(4).tolist()
|
| 336 |
+
out["grasp_over_tile"] = over_tile
|
| 337 |
+
out["touched_at_close"] = last_close["touching"]
|
| 338 |
+
face = "the top face of the red tile" if over_tile else "the level of the red tile's top face"
|
| 339 |
+
grasp_txt = (f"When the jaws closed, the grasp point (midway between the fingertips) was "
|
| 340 |
+
f"{vert_words(gh, face)} and the lowest points of the fingertips "
|
| 341 |
+
f"were {vert_words(fg, 'it')} (the tile is {100 * TILE_T:.1f} cm thick)")
|
| 342 |
+
if not over_tile or np.linalg.norm(go) >= 0.01:
|
| 343 |
+
grasp_txt += (f"; horizontally the grasp point was {dir_words(*go)} of the tile's centre"
|
| 344 |
+
+ ("" if over_tile else ", i.e. not over the tile"))
|
| 345 |
+
if success:
|
| 346 |
+
out["failure"] = None
|
| 347 |
+
detail = "The red tile is on the plate."
|
| 348 |
+
if grasp_txt:
|
| 349 |
+
detail += f" {grasp_txt}."
|
| 350 |
+
elif not picked:
|
| 351 |
+
out["failure"] = "missed_grasp"
|
| 352 |
+
if last_close is None:
|
| 353 |
+
detail = "The gripper never closed; the red tile was not picked up."
|
| 354 |
+
else:
|
| 355 |
+
touch = last_close["touching"]
|
| 356 |
+
if not over_tile and TILE not in touch:
|
| 357 |
+
why = " The gripper was not over the tile when it closed."
|
| 358 |
+
elif fg > 0.0005 and TILE not in touch:
|
| 359 |
+
why = " The fingers closed in the air above the tile without touching it."
|
| 360 |
+
elif STAND in touch and TILE not in touch:
|
| 361 |
+
why = " The fingertips were pressed on the top of the wooden block but did not grip the tile."
|
| 362 |
+
elif TILE in touch:
|
| 363 |
+
why = " The fingers touched the tile but did not get a grip on it."
|
| 364 |
+
else:
|
| 365 |
+
why = ""
|
| 366 |
+
where = "still on the wooden block" if on_stand else "no longer on the wooden block"
|
| 367 |
+
detail = f"{grasp_txt}, and the tile was not picked up.{why} The tile is {where}."
|
| 368 |
+
elif held:
|
| 369 |
+
out["failure"] = "not_released"
|
| 370 |
+
detail = f"{grasp_txt}, and the tile was picked up, but it is still in the gripper."
|
| 371 |
+
elif releases:
|
| 372 |
+
r = releases[-1]
|
| 373 |
+
out["release_offset"] = (np.array(r["tile"][:2]) - np.array(r["plate"][:2])).round(4).tolist()
|
| 374 |
+
out["failure"] = "missed_place"
|
| 375 |
+
detail = (f"{grasp_txt}, and the tile was picked up. When the gripper opened, the tile was "
|
| 376 |
+
f"{dir_words(*out['release_offset'])} of the plate's centre; it did not end up on the plate "
|
| 377 |
+
f"(it is now {dir_words(*end_off)} of the plate's centre).")
|
| 378 |
+
else:
|
| 379 |
+
out["failure"] = "dropped"
|
| 380 |
+
detail = (f"{grasp_txt}, and the tile was lifted, but it slipped out of the fingers before it was "
|
| 381 |
+
f"released; it is now {dir_words(*end_off)} of the plate's centre.")
|
| 382 |
+
out["detail"] = detail
|
| 383 |
+
ind = detail
|
| 384 |
+
for k in sorted(NAMES, key=lambda n: -len(NAMES[n])):
|
| 385 |
+
ind = ind.replace(NAMES[k], DESCR[k])
|
| 386 |
+
ind = re.sub(r"\btile\b", "slab", ind) # the bare noun would give the direct name away
|
| 387 |
+
out["detail_indirect"] = ind
|
| 388 |
+
return out
|
| 389 |
+
|
| 390 |
+
def feedback(self, inst, out, level="F2", indirect=False):
|
| 391 |
+
if indirect and level == "F2":
|
| 392 |
+
out = dict(out, detail=out.get("detail_indirect", out["detail"]))
|
| 393 |
+
return super().feedback(inst, out, level)
|
| 394 |
+
|
| 395 |
+
# ------------------------------------------------------------ scripted execution (cross protocol)
|
| 396 |
+
def grasp_yaw(self):
|
| 397 |
+
"""Gripper yaw that closes the jaws across the tile's short side (yaw 0 closes along world y)."""
|
| 398 |
+
xmat = self.env.sim.data.body_xmat[envs.body_id(self.env, TILE)].reshape(3, 3)
|
| 399 |
+
a = np.arctan2(xmat[1, 0], xmat[0, 0])
|
| 400 |
+
return float((a + np.pi / 2) % np.pi - np.pi / 2)
|
| 401 |
+
|
| 402 |
+
def execute(self, inst, params):
|
| 403 |
+
"""Top-down pick across the tile's short side with the fingertips just above the block top, carry, release
|
| 404 |
+
above the plate. params['dz'] is the policy's own height correction, added to every commanded z."""
|
| 405 |
+
sk = self.sk
|
| 406 |
+
dz = float(params.get("dz", 0.0))
|
| 407 |
+
t = envs.obj_pos(self.env, TILE) # perfect perception of the current scene
|
| 408 |
+
top = self.stand_top(inst)
|
| 409 |
+
yaw = self.grasp_yaw()
|
| 410 |
+
p = envs.obj_pos(self.env, PLATE)
|
| 411 |
+
z_grasp = top + SITE_ABOVE_SURFACE + dz
|
| 412 |
+
z_carry = top + CARRY_ABOVE + dz
|
| 413 |
+
z_rel = self.plate_rim_z() + RELEASE_GAP + SITE_ABOVE_SURFACE + dz
|
| 414 |
+
sk.set_gripper(False, steps=8)
|
| 415 |
+
sk.move_to([t[0], t[1], z_carry], yaw=yaw)
|
| 416 |
+
sk.move_to([t[0], t[1], z_grasp + 0.05], tol=0.002)
|
| 417 |
+
sk.move_to([t[0], t[1], z_grasp], tol=0.003, max_steps=80)
|
| 418 |
+
sk.set_gripper(True, steps=15)
|
| 419 |
+
sk.move_to([t[0], t[1], z_carry], speed=0.3)
|
| 420 |
+
if not sk.holding_tile(): # missed: a real controller sees the jaws closed on nothing and stops
|
| 421 |
+
return
|
| 422 |
+
sk.move_to([p[0], p[1], z_carry], tol=0.003)
|
| 423 |
+
sk.move_to([p[0], p[1], z_rel], tol=0.003, max_steps=100)
|
| 424 |
+
sk.set_gripper(False, steps=12)
|
| 425 |
+
sk.move_to([p[0], p[1], z_carry], speed=0.3)
|
| 426 |
+
|
| 427 |
+
def default_params(self, inst):
|
| 428 |
+
return dict(dz=0.0)
|
| 429 |
+
|
| 430 |
+
def oracle_params(self, inst):
|
| 431 |
+
return dict(dz=-float(inst["bias"][2]))
|
| 432 |
+
|
| 433 |
+
def adapt_params(self, inst, history):
|
| 434 |
+
"""Scripted F2 learner: the reported grasp height above the tile's top face, minus the height this policy
|
| 435 |
+
meant to put the grasp point at (SITE_ABOVE_SURFACE - tile thickness), is the vertical offset; accumulate
|
| 436 |
+
it into the correction subtracted from every commanded height."""
|
| 437 |
+
last = history[-1]
|
| 438 |
+
dz = float(last["params"]["dz"])
|
| 439 |
+
o = last["outcome"]
|
| 440 |
+
if o.get("grasp_height") is not None:
|
| 441 |
+
dz -= o["grasp_height"] - (SITE_ABOVE_SURFACE - TILE_T)
|
| 442 |
+
return dict(dz=round(dz, 4))
|
| 443 |
+
|
| 444 |
+
blind_sigma = 0.005
|
| 445 |
+
|
| 446 |
+
def blind_params(self, inst, attempt, rng):
|
| 447 |
+
"""Retry the same plan with a small random perturbation of the commanded heights; no use of history."""
|
| 448 |
+
return dict(dz=round(float(rng.normal(0.0, self.blind_sigma)), 4))
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l3_tool.py
ADDED
|
@@ -0,0 +1,549 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L3-C under_table_tool: a cube sits under a low glass side table; put it into the bin (tool use).
|
| 2 |
+
|
| 3 |
+
v2 (2026-10-08, user review of cla2): in v1 the hidden information was "the hand does not fit under the glass top".
|
| 4 |
+
Every Sonnet run (4/4) saw the T-shaped stick lying next to the low table and used it straight away, i.e. the task
|
| 5 |
+
was solved by reasoning before acting and nothing had to be learned from a failure. v2 keeps the scene and moves the
|
| 6 |
+
hidden information to something no image shows:
|
| 7 |
+
|
| 8 |
+
Hidden: the side of the low table AWAY from the stick is closed by a clear acrylic panel (between the two legs,
|
| 9 |
+
tabletop to glass top; collision only, nothing is rendered). The bin stands on that side, beyond the panel. The other
|
| 10 |
+
three sides are open.
|
| 11 |
+
|
| 12 |
+
Why the prior fails: the stick lies on one side with its head pointing at the low table, and the bin is on the
|
| 13 |
+
opposite side, so the obvious plan is "slide the stick in and push the cube straight across, out towards the bin".
|
| 14 |
+
The cube then stops against the invisible panel, still completely under the glass top (the hand cannot reach it
|
| 15 |
+
there: the glass is 7 cm above the tabletop). Pushing harder or again from the same side fails the same way.
|
| 16 |
+
|
| 17 |
+
What must be learned from the failure (F1: from the images -- the cube stopped at the edge and did not come out):
|
| 18 |
+
something blocks that side -> change the push: put the stick down behind the low table (the robot's side) pointing
|
| 19 |
+
forward, push the cube out of the FRONT side (away from the robot), then grasp it and carry it to the bin.
|
| 20 |
+
|
| 21 |
+
Layout (randomised per instance): position of the low table, cube position under it (+-1 cm around the centre),
|
| 22 |
+
the stick lying beside the low table (left or right) with its head pointing at it (+-10 deg), the panel and the bin
|
| 23 |
+
on the other side.
|
| 24 |
+
|
| 25 |
+
Protocol: cross (reset to the same instance before every attempt), k = 5. v1 is kept in l3_tool.py.bak-20261008-pane.
|
| 26 |
+
"""
|
| 27 |
+
import numpy as np
|
| 28 |
+
|
| 29 |
+
from .. import envs
|
| 30 |
+
from ..bddl import write_bddl
|
| 31 |
+
from ..objects import _SOLID, _fmt, _wrap, bin_xml, box_xml, register_generated
|
| 32 |
+
from ..skills import DT, _rot_err
|
| 33 |
+
from ..task_base import LFFTask, register_task
|
| 34 |
+
|
| 35 |
+
CUBE_HALF = 0.02
|
| 36 |
+
TOP_HALF = (0.06, 0.06, 0.005) # glass top 12 x 12 cm, 1 cm thick
|
| 37 |
+
TOP_UNDER = 0.07 # underside of the glass top above the tabletop
|
| 38 |
+
LEG_HALF = 0.008
|
| 39 |
+
HANDLE_HALF = (0.12, 0.008, 0.01) # stick handle 24 x 1.6 x 2 cm, along local x
|
| 40 |
+
HEAD_HALF = (0.008, 0.025, 0.01) # crossbar 1.6 x 5 x 2 cm at the +x end
|
| 41 |
+
BIN_IN = (0.06, 0.06)
|
| 42 |
+
BIN_WALL_H = 0.05
|
| 43 |
+
GRIP_END = 0.035 # scripted grasp point: this far from the free end of the handle
|
| 44 |
+
GRIP_FRONT = 0.07 # v2 front push: grasp this far from the free end (keeps the hand clear of the glass edge)
|
| 45 |
+
Z_STICK = envs.TABLE_Z + 0.0125 # site height when grasping / sliding the stick (pads 0.75-2.4 cm above the table)
|
| 46 |
+
TIP_BELOW_SITE = 0.0095
|
| 47 |
+
# clear acrylic panel between the two legs of one y side, tabletop to glass underside (collision only, invisible)
|
| 48 |
+
PANE_HALF = (TOP_HALF[0] - 2 * LEG_HALF, 0.002, TOP_UNDER / 2)
|
| 49 |
+
PANE_Y = TOP_HALF[1] - LEG_HALF # in the plane of the leg centres
|
| 50 |
+
STICK_COM = 0.0221 # the stick's centre of mass is this far from the handle centre, towards the head
|
| 51 |
+
BIN_GAP = (0.04, 0.06) # tabletop gap between the low table's far side and the bin's outer wall
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def low_table_xml(model_name):
|
| 55 |
+
glass, leg = (0.70, 0.85, 0.95, 0.30), (0.35, 0.25, 0.18, 1.0)
|
| 56 |
+
z_top = TOP_UNDER + TOP_HALF[2]
|
| 57 |
+
parts = [((0, 0, z_top), TOP_HALF, glass)]
|
| 58 |
+
for sx in (-1, 1):
|
| 59 |
+
for sy in (-1, 1):
|
| 60 |
+
parts.append(((sx * (TOP_HALF[0] - LEG_HALF), sy * (TOP_HALF[1] - LEG_HALF), TOP_UNDER / 2),
|
| 61 |
+
(LEG_HALF, LEG_HALF, TOP_UNDER / 2), leg))
|
| 62 |
+
g = []
|
| 63 |
+
for k, (p, s, c) in enumerate(parts):
|
| 64 |
+
g.append(f' <geom name="{model_name}_g{k}" type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" '
|
| 65 |
+
f'density="800" friction="1.0 0.005 0.0001" {_SOLID} group="0" />')
|
| 66 |
+
g.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" conaffinity="0" '
|
| 67 |
+
f'contype="0" group="1" />')
|
| 68 |
+
# acrylic panels on both y sides; apply_instance turns the collision of the one next to the stick off.
|
| 69 |
+
# Fully transparent (rgba alpha 0) and no visual twin: nothing is rendered.
|
| 70 |
+
for k, sy in enumerate((1, -1)):
|
| 71 |
+
g.append(f' <geom name="{model_name}_pane{k}" type="box" pos="{_fmt((0, sy * PANE_Y, PANE_HALF[2]))}" '
|
| 72 |
+
f'size="{_fmt(PANE_HALF)}" rgba="1 1 1 0" density="800" friction="0.6 0.005 0.0001" {_SOLID} '
|
| 73 |
+
f'group="0" />')
|
| 74 |
+
# origin at the tabletop (z = 0 is the bottom of the legs)
|
| 75 |
+
return _wrap(model_name, "\n".join(g), 0.0, float(np.hypot(TOP_HALF[0], TOP_HALF[1])))
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def stick_xml(model_name):
|
| 79 |
+
c = (0.80, 0.62, 0.30, 1.0)
|
| 80 |
+
parts = [((0, 0, 0), HANDLE_HALF), ((HANDLE_HALF[0] + HEAD_HALF[0], 0, 0), HEAD_HALF)]
|
| 81 |
+
g = []
|
| 82 |
+
for k, (p, s) in enumerate(parts):
|
| 83 |
+
g.append(f' <geom name="{model_name}_g{k}" type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" '
|
| 84 |
+
f'density="600" friction="1.0 0.005 0.0001" {_SOLID} group="0" />')
|
| 85 |
+
g.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" conaffinity="0" '
|
| 86 |
+
f'contype="0" group="1" />')
|
| 87 |
+
return _wrap(model_name, "\n".join(g), HANDLE_HALF[2], HANDLE_HALF[0] + 2 * HEAD_HALF[0])
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _yaw_of(quat_wxyz):
|
| 91 |
+
w, x, y, z = quat_wxyz
|
| 92 |
+
return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)))
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
@register_task
|
| 96 |
+
class UnderTableTool(LFFTask):
|
| 97 |
+
name = "l3_under_table_tool"
|
| 98 |
+
level = "L3"
|
| 99 |
+
category = "strategy_switching"
|
| 100 |
+
capabilities = ("Perceive", "Reason", "Plan")
|
| 101 |
+
protocol = "cross"
|
| 102 |
+
instruction = "Put the red cube into the gray bin."
|
| 103 |
+
instruction_indirect = "Put the small red block that is under the low glass table into the gray container."
|
| 104 |
+
|
| 105 |
+
def __init__(self, cam_res=None):
|
| 106 |
+
super().__init__(cam_res)
|
| 107 |
+
self._mon = None
|
| 108 |
+
self.inst = None
|
| 109 |
+
orig_step = self.env.step
|
| 110 |
+
|
| 111 |
+
def step(action):
|
| 112 |
+
ret = orig_step(action)
|
| 113 |
+
if self._mon is not None:
|
| 114 |
+
self._monitor_step()
|
| 115 |
+
return ret
|
| 116 |
+
|
| 117 |
+
self.env.step = step
|
| 118 |
+
|
| 119 |
+
# ------------------------------------------------------------ scene
|
| 120 |
+
def make_bddl(self):
|
| 121 |
+
cube = register_generated("LffBenchCube", box_xml("lff_bench_cube", (CUBE_HALF,) * 3, (0.85, 0.12, 0.12, 1.0),
|
| 122 |
+
density=800))
|
| 123 |
+
stick = register_generated("LffBenchStick", stick_xml("lff_bench_stick"))
|
| 124 |
+
table = register_generated("LffLowGlassTable", low_table_xml("lff_low_glass_table"), free=False)
|
| 125 |
+
tray = register_generated("LffBenchBin", bin_xml("lff_bench_bin", BIN_IN, BIN_WALL_H), free=False)
|
| 126 |
+
objs = [("cube_1", cube, "cube_region", (-0.21, -0.26, -0.19, -0.24)),
|
| 127 |
+
("stick_1", stick, "stick_region", (-0.01, 0.24, 0.01, 0.26))]
|
| 128 |
+
fx = [("lowtable_1", table, "lowtable_region", (0.19, -0.01, 0.21, 0.01)),
|
| 129 |
+
("bin_1", tray, "bin_region", (0.19, 0.29, 0.21, 0.31))]
|
| 130 |
+
return write_bddl(self.name, self.instruction, objs, fx)
|
| 131 |
+
|
| 132 |
+
def _fixture(self, name):
|
| 133 |
+
if not hasattr(self, "_fx"):
|
| 134 |
+
self._fx = {}
|
| 135 |
+
if name not in self._fx:
|
| 136 |
+
m = self.env.sim.model
|
| 137 |
+
bid = m.body_name2id(self.env.fixtures_dict[name].root_body)
|
| 138 |
+
|
| 139 |
+
def under(b):
|
| 140 |
+
while b > 0:
|
| 141 |
+
if b == bid:
|
| 142 |
+
return True
|
| 143 |
+
b = m.body_parentid[b]
|
| 144 |
+
return False
|
| 145 |
+
|
| 146 |
+
self._fx[name] = (bid, [g for g in range(m.ngeom) if under(m.geom_bodyid[g])])
|
| 147 |
+
return self._fx[name]
|
| 148 |
+
|
| 149 |
+
def _panes(self):
|
| 150 |
+
"""[(geom id, +1 / -1 = which y side of the low table)] of the two acrylic panel geoms"""
|
| 151 |
+
if not hasattr(self, "_pane_ids"):
|
| 152 |
+
m = self.env.sim.model
|
| 153 |
+
self._pane_ids = [(g, int(np.sign(m.geom_pos[g][1]))) for g in self._fixture("lowtable_1")[1]
|
| 154 |
+
if np.allclose(m.geom_size[g], PANE_HALF, atol=1e-6)]
|
| 155 |
+
assert len(self._pane_ids) == 2, self._pane_ids
|
| 156 |
+
return self._pane_ids
|
| 157 |
+
|
| 158 |
+
def sample_instance(self, seed):
|
| 159 |
+
rng = np.random.default_rng(seed)
|
| 160 |
+
side = int(rng.choice([-1, 1])) # the stick lies on the left (+1) or right (-1) of the low table
|
| 161 |
+
# v2: 4 cm further from the robot than v1 (-0.16..-0.10), so that a stick pushed forward from behind the
|
| 162 |
+
# low table is within reach (gripper about 25 cm in front of the robot base at the start of that push)
|
| 163 |
+
t_xy = np.array([rng.uniform(-0.12, -0.06), -side * rng.uniform(0.04, 0.07)])
|
| 164 |
+
cube_xy = t_xy + rng.uniform(-0.01, 0.01, 2)
|
| 165 |
+
# the stick lies beside the low table, its head pointing roughly at it (+-10 deg), 2.5-4.5 cm from its edge
|
| 166 |
+
yaw = -side * np.pi / 2 + float(rng.uniform(-np.radians(10), np.radians(10)))
|
| 167 |
+
d = np.array([np.cos(yaw), np.sin(yaw)])
|
| 168 |
+
head_front = np.array([cube_xy[0] + rng.uniform(-0.01, 0.01), t_xy[1] + side * (TOP_HALF[1] + rng.uniform(0.025, 0.045))])
|
| 169 |
+
stick_xy = head_front - d * (HANDLE_HALF[0] + 2 * HEAD_HALF[0])
|
| 170 |
+
# v2: the bin stands on the far side (the panel's side), so pushing the cube straight across looks like the
|
| 171 |
+
# way to the bin
|
| 172 |
+
gap = rng.uniform(*BIN_GAP)
|
| 173 |
+
bin_xy = np.array([t_xy[0] + rng.uniform(-0.02, 0.02),
|
| 174 |
+
t_xy[1] - side * (TOP_HALF[1] + gap + BIN_IN[1] + 0.006)])
|
| 175 |
+
return dict(seed=int(seed), table_xy=t_xy.tolist(), cube_xy=cube_xy.tolist(), side=side, pane_side=-side,
|
| 176 |
+
stick_xy=stick_xy.tolist(), stick_yaw=float(yaw), bin_xy=bin_xy.tolist())
|
| 177 |
+
|
| 178 |
+
def apply_instance(self, inst):
|
| 179 |
+
self.inst = inst
|
| 180 |
+
m = self.env.sim.model
|
| 181 |
+
bid, _ = self._fixture("lowtable_1")
|
| 182 |
+
m.body_pos[bid] = [inst["table_xy"][0], inst["table_xy"][1], envs.TABLE_Z]
|
| 183 |
+
m.body_quat[bid] = [1, 0, 0, 0]
|
| 184 |
+
for g, sy in self._panes(): # only the panel on the far side (away from the stick) collides
|
| 185 |
+
on = sy == inst.get("pane_side", -inst["side"])
|
| 186 |
+
m.geom_contype[g] = 1 if on else 0
|
| 187 |
+
m.geom_conaffinity[g] = 1 if on else 0
|
| 188 |
+
bbid, _ = self._fixture("bin_1")
|
| 189 |
+
m.body_pos[bbid] = [inst["bin_xy"][0], inst["bin_xy"][1], envs.TABLE_Z + (BIN_WALL_H + 0.006) / 2]
|
| 190 |
+
m.body_quat[bbid] = [1, 0, 0, 0]
|
| 191 |
+
cx, cy = inst["cube_xy"]
|
| 192 |
+
envs.set_obj_pose(self.env, "cube_1", [cx, cy, envs.TABLE_Z + CUBE_HALF + 0.0005])
|
| 193 |
+
sx, sy = inst["stick_xy"]
|
| 194 |
+
envs.set_obj_pose(self.env, "stick_1", [sx, sy, envs.TABLE_Z + HANDLE_HALF[2] + 0.0005], yaw=inst["stick_yaw"])
|
| 195 |
+
|
| 196 |
+
def reset_instance(self, inst, recorder=None):
|
| 197 |
+
self._mon = None
|
| 198 |
+
sk = super().reset_instance(inst, recorder=recorder)
|
| 199 |
+
self._start_monitor()
|
| 200 |
+
return sk
|
| 201 |
+
|
| 202 |
+
# ------------------------------------------------------------ state
|
| 203 |
+
def stick_pose(self):
|
| 204 |
+
d = self.env.sim.data
|
| 205 |
+
bid = envs.body_id(self.env, "stick_1")
|
| 206 |
+
return d.body_xpos[bid].copy(), d.body_xmat[bid].reshape(3, 3).copy()
|
| 207 |
+
|
| 208 |
+
def observe(self):
|
| 209 |
+
p, R = self.stick_pose()
|
| 210 |
+
ax = R[:2, 0] / max(np.linalg.norm(R[:2, 0]), 1e-9)
|
| 211 |
+
return dict(cube=envs.obj_pos(self.env, "cube_1"), table_xy=np.array(self.inst["table_xy"]),
|
| 212 |
+
bin_xy=np.array(self.inst["bin_xy"]), stick_xy=p[:2], stick_dir=ax,
|
| 213 |
+
free_end=p[:2] - ax * HANDLE_HALF[0], head=p[:2] + ax * (HANDLE_HALF[0] + HEAD_HALF[0]))
|
| 214 |
+
|
| 215 |
+
def under_table(self, xy=None, margin=0.0):
|
| 216 |
+
"""is the cube's footprint (any part) under the glass top?"""
|
| 217 |
+
xy = envs.obj_pos(self.env, "cube_1")[:2] if xy is None else np.asarray(xy)
|
| 218 |
+
rel = np.abs(xy - np.array(self.inst["table_xy"]))
|
| 219 |
+
return bool((rel < np.array(TOP_HALF[:2]) + CUBE_HALF + margin).all())
|
| 220 |
+
|
| 221 |
+
def outside_dist(self):
|
| 222 |
+
"""how far the cube's footprint is outside the glass top (m, < 0: still partly under it)"""
|
| 223 |
+
rel = np.abs(envs.obj_pos(self.env, "cube_1")[:2] - np.array(self.inst["table_xy"]))
|
| 224 |
+
return float(max(rel - np.array(TOP_HALF[:2]) - CUBE_HALF))
|
| 225 |
+
|
| 226 |
+
def in_bin(self):
|
| 227 |
+
p = envs.obj_pos(self.env, "cube_1")
|
| 228 |
+
rel = np.abs(p[:2] - np.array(self.inst["bin_xy"]))
|
| 229 |
+
return bool(p[2] < envs.TABLE_Z + BIN_WALL_H and (rel < np.array(BIN_IN)).all())
|
| 230 |
+
|
| 231 |
+
# ------------------------------------------------------------ contacts / monitor
|
| 232 |
+
def _groups(self):
|
| 233 |
+
if not hasattr(self, "_gg"):
|
| 234 |
+
m = self.env.sim.model
|
| 235 |
+
robot = set(envs.robot_geom_ids(self.env))
|
| 236 |
+
tbl = self._fixture("lowtable_1")[1]
|
| 237 |
+
top = {g for g in tbl if m.geom_contype[g] and abs(m.geom_size[g, 0] - TOP_HALF[0]) < 1e-6}
|
| 238 |
+
self._gg = (robot, set(tbl), top, set(envs.obj_geom_ids(self.env, "stick_1")),
|
| 239 |
+
set(envs.obj_geom_ids(self.env, "cube_1")))
|
| 240 |
+
return self._gg
|
| 241 |
+
|
| 242 |
+
def _robot_contacts(self):
|
| 243 |
+
"""labels of what the robot touches: 'glass_top', 'pane', 'table_leg', 'stick', 'cube'"""
|
| 244 |
+
robot, tbl, top, stick, cube = self._groups()
|
| 245 |
+
panes = {g for g, _ in self._panes()}
|
| 246 |
+
d = self.env.sim.data
|
| 247 |
+
out = set()
|
| 248 |
+
for i in range(d.ncon):
|
| 249 |
+
c = d.contact[i]
|
| 250 |
+
if c.geom1 in robot:
|
| 251 |
+
o = c.geom2
|
| 252 |
+
elif c.geom2 in robot:
|
| 253 |
+
o = c.geom1
|
| 254 |
+
else:
|
| 255 |
+
continue
|
| 256 |
+
if o in top:
|
| 257 |
+
out.add("glass_top")
|
| 258 |
+
elif o in panes:
|
| 259 |
+
out.add("pane")
|
| 260 |
+
elif o in tbl:
|
| 261 |
+
out.add("table_leg")
|
| 262 |
+
elif o in stick:
|
| 263 |
+
out.add("stick")
|
| 264 |
+
elif o in cube:
|
| 265 |
+
out.add("cube")
|
| 266 |
+
return out
|
| 267 |
+
|
| 268 |
+
def _start_monitor(self):
|
| 269 |
+
c = envs.obj_pos(self.env, "cube_1")
|
| 270 |
+
self._mon = dict(start=c.copy(), top_hit=None, stick_held=False, stick_touched_cube=False, max_cube_dz=0.0,
|
| 271 |
+
cube_out=not self.under_table(), cube_hit_pane=False, stick_hit_pane=False,
|
| 272 |
+
robot_hit_pane=False)
|
| 273 |
+
|
| 274 |
+
def _monitor_step(self):
|
| 275 |
+
mon, sk = self._mon, self.sk
|
| 276 |
+
if sk is None:
|
| 277 |
+
return
|
| 278 |
+
hits = self._robot_contacts()
|
| 279 |
+
if "glass_top" in hits:
|
| 280 |
+
e = sk.eef_pos()
|
| 281 |
+
rel = np.abs(e[:2] - np.array(self.inst["table_xy"]))
|
| 282 |
+
mon["top_hit"] = dict(above=bool((rel < np.array(TOP_HALF[:2])).all()),
|
| 283 |
+
tip=float(e[2] - TIP_BELOW_SITE - envs.TABLE_Z),
|
| 284 |
+
outside=float(max(rel - np.array(TOP_HALF[:2]))))
|
| 285 |
+
if sk.holding("stick_1"):
|
| 286 |
+
mon["stick_held"] = True
|
| 287 |
+
if "pane" in hits:
|
| 288 |
+
mon["robot_hit_pane"] = True
|
| 289 |
+
robot, tbl, top, stick, cube = self._groups()
|
| 290 |
+
panes = {g for g, _ in self._panes()}
|
| 291 |
+
d = self.env.sim.data
|
| 292 |
+
for i in range(d.ncon):
|
| 293 |
+
c = d.contact[i]
|
| 294 |
+
pair = (c.geom1, c.geom2)
|
| 295 |
+
if (pair[0] in stick and pair[1] in cube) or (pair[1] in stick and pair[0] in cube):
|
| 296 |
+
mon["stick_touched_cube"] = True
|
| 297 |
+
if (pair[0] in panes and pair[1] in cube) or (pair[1] in panes and pair[0] in cube):
|
| 298 |
+
mon["cube_hit_pane"] = True
|
| 299 |
+
if (pair[0] in panes and pair[1] in stick) or (pair[1] in panes and pair[0] in stick):
|
| 300 |
+
mon["stick_hit_pane"] = True
|
| 301 |
+
p = envs.obj_pos(self.env, "cube_1")
|
| 302 |
+
mon["max_cube_dz"] = max(mon["max_cube_dz"], float(p[2] - mon["start"][2]))
|
| 303 |
+
if not self.under_table():
|
| 304 |
+
mon["cube_out"] = True
|
| 305 |
+
|
| 306 |
+
# ------------------------------------------------------------ outcome / F2
|
| 307 |
+
def outcome(self, inst):
|
| 308 |
+
envs.settle(self.env, 30)
|
| 309 |
+
mon = self._mon or {}
|
| 310 |
+
p = envs.obj_pos(self.env, "cube_1")
|
| 311 |
+
held = bool(self.sk.holding("cube_1")) if self.sk is not None else False
|
| 312 |
+
success = bool(self.in_bin() and not held)
|
| 313 |
+
moved = float(np.linalg.norm(p[:2] - mon.get("start", p)[:2]))
|
| 314 |
+
under = self.under_table()
|
| 315 |
+
brel = p[:2] - np.array(inst["bin_xy"])
|
| 316 |
+
parts, mode = [], "success"
|
| 317 |
+
top = mon.get("top_hit")
|
| 318 |
+
if success:
|
| 319 |
+
parts.append("The cube is in the bin.")
|
| 320 |
+
elif p[2] < envs.TABLE_Z - 0.05:
|
| 321 |
+
mode = "fell_off"
|
| 322 |
+
parts.append("The cube fell off the table.")
|
| 323 |
+
elif held:
|
| 324 |
+
mode = "held"
|
| 325 |
+
parts.append("The cube is still held by the gripper; it was not released into the bin.")
|
| 326 |
+
elif under:
|
| 327 |
+
mode = "under"
|
| 328 |
+
if top is not None and not mon.get("stick_touched_cube"):
|
| 329 |
+
mode = "blocked"
|
| 330 |
+
if top["above"]:
|
| 331 |
+
parts.append(f"The gripper came down on the glass top of the low table: its fingertips stopped "
|
| 332 |
+
f"{100 * max(top['tip'], 0.0):.1f} cm above the tabletop, while the cube is underneath "
|
| 333 |
+
f"the glass (the glass underside is {100 * TOP_UNDER:.1f} cm above the tabletop), so the "
|
| 334 |
+
f"gripper never got to the cube.")
|
| 335 |
+
else:
|
| 336 |
+
parts.append(f"The hand ran into the edge of the glass top of the low table (fingertips "
|
| 337 |
+
f"{100 * max(top['tip'], 0.0):.1f} cm above the tabletop, gripper "
|
| 338 |
+
f"{100 * max(top['outside'], 0.0):.1f} cm outside the edge) and could not move in "
|
| 339 |
+
f"under the glass.")
|
| 340 |
+
if mon.get("cube_hit_pane"):
|
| 341 |
+
mode = "pane"
|
| 342 |
+
parts.append(f"The cube was pushed against a clear acrylic panel that closes the "
|
| 343 |
+
f"{'left' if inst.get('pane_side', -inst['side']) > 0 else 'right'} side of the low "
|
| 344 |
+
f"table (between its two legs, from the tabletop up to the glass); it cannot leave the "
|
| 345 |
+
f"low table on that side.")
|
| 346 |
+
if moved > 0.01:
|
| 347 |
+
parts.append(f"The cube was moved {100 * moved:.1f} cm but is still under the low table "
|
| 348 |
+
f"({100 * -self.outside_dist():.1f} cm from getting completely out from under it).")
|
| 349 |
+
else:
|
| 350 |
+
parts.append("The cube did not move; it is still under the low table.")
|
| 351 |
+
else:
|
| 352 |
+
mode = "out_not_in_bin"
|
| 353 |
+
lifted = mon.get("max_cube_dz", 0.0) > 0.03
|
| 354 |
+
parts.append(("The cube was lifted but ended outside the bin" if lifted else
|
| 355 |
+
"The cube is out from under the low table but not in the bin") +
|
| 356 |
+
f": it is {100 * abs(brel[0]):.1f} cm {'forward' if brel[0] > 0 else 'backward'} and "
|
| 357 |
+
f"{100 * abs(brel[1]):.1f} cm {'left' if brel[1] > 0 else 'right'} of the bin's centre.")
|
| 358 |
+
out = dict(success=success, mode=mode, moved=moved, under=under, cube_rel_bin=[float(brel[0]), float(brel[1])],
|
| 359 |
+
stick_used=bool(mon.get("stick_held")), terminal=bool(p[2] < envs.TABLE_Z - 0.05),
|
| 360 |
+
cube_hit_pane=bool(mon.get("cube_hit_pane")), stick_hit_pane=bool(mon.get("stick_hit_pane")),
|
| 361 |
+
robot_hit_pane=bool(mon.get("robot_hit_pane")), detail=" ".join(parts))
|
| 362 |
+
self._start_monitor()
|
| 363 |
+
return out
|
| 364 |
+
|
| 365 |
+
# ------------------------------------------------------------ primitives for the scripted policies
|
| 366 |
+
def _yaw_near(self, yaw):
|
| 367 |
+
cands = [yaw + k * np.pi for k in (-2, -1, 0, 1, 2)]
|
| 368 |
+
cands = [c for c in cands if abs(c) <= np.pi / 2 + 0.4] or cands
|
| 369 |
+
return float(min(cands, key=lambda c: abs(c - self.sk.yaw)))
|
| 370 |
+
|
| 371 |
+
def _align(self, tol=0.03, max_steps=60):
|
| 372 |
+
sk = self.sk
|
| 373 |
+
for _ in range(max_steps):
|
| 374 |
+
R = sk._R() @ sk.eef_mat().T
|
| 375 |
+
if np.arccos(np.clip((np.trace(R) - 1) / 2, -1, 1)) < tol:
|
| 376 |
+
break
|
| 377 |
+
sk.hold(1)
|
| 378 |
+
|
| 379 |
+
def _guarded_descent(self, xyz, speed=0.12, max_steps=80):
|
| 380 |
+
sk = self.sk
|
| 381 |
+
p0 = sk.eef_pos()
|
| 382 |
+
tgt = np.asarray(xyz, float)
|
| 383 |
+
dist = max(np.linalg.norm(tgt - p0), 1e-6)
|
| 384 |
+
R = sk._R()
|
| 385 |
+
for k in range(max_steps):
|
| 386 |
+
ref = p0 + (tgt - p0) * min(1.0, (k + 1) * speed * DT / dist)
|
| 387 |
+
sk._act(ref - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip)
|
| 388 |
+
if self._robot_contacts() - {"cube"} and sk.eef_pos()[2] > tgt[2] + 0.005:
|
| 389 |
+
break
|
| 390 |
+
if np.linalg.norm(tgt - sk.eef_pos()) < 0.003:
|
| 391 |
+
break
|
| 392 |
+
sk.hold(4)
|
| 393 |
+
|
| 394 |
+
def grasp_cube_and_bin(self, dxy=(0.0, 0.0), dyaw=0.0):
|
| 395 |
+
"""Top-down grasp of the cube where it is (+ offsets); if held, drop it into the bin."""
|
| 396 |
+
sk, o = self.sk, self.observe()
|
| 397 |
+
c = o["cube"]
|
| 398 |
+
gx, gy = c[0] + dxy[0], c[1] + dxy[1]
|
| 399 |
+
# the hand is 20 cm long along the closing direction: keep that direction parallel to the low table's edge
|
| 400 |
+
v = c[:2] - o["table_xy"]
|
| 401 |
+
yaw = (np.pi / 2 if abs(v[1]) > abs(v[0]) else 0.0) + dyaw
|
| 402 |
+
sk.set_gripper(False, steps=8)
|
| 403 |
+
sk.move_to([gx, gy, envs.TABLE_Z + 0.15], yaw=self._yaw_near(yaw))
|
| 404 |
+
self._align()
|
| 405 |
+
self._guarded_descent([gx, gy, envs.TABLE_Z + 0.017])
|
| 406 |
+
sk.set_gripper(True, steps=15)
|
| 407 |
+
e = sk.eef_pos()
|
| 408 |
+
sk.move_to([e[0], e[1], envs.TABLE_Z + 0.16], speed=0.25)
|
| 409 |
+
if sk.holding("cube_1"):
|
| 410 |
+
bx, by = o["bin_xy"]
|
| 411 |
+
sk.move_to([bx, by, envs.TABLE_Z + 0.16])
|
| 412 |
+
sk.move_to([bx, by, envs.TABLE_Z + BIN_WALL_H + 0.05])
|
| 413 |
+
sk.set_gripper(False, steps=12)
|
| 414 |
+
sk.move_to([bx, by, envs.TABLE_Z + 0.16])
|
| 415 |
+
else:
|
| 416 |
+
sk.set_gripper(False, steps=6)
|
| 417 |
+
|
| 418 |
+
def tool_push_out(self, extra=0.0):
|
| 419 |
+
"""Pick the stick up by the end of its handle (it already points at the low table), lift it a few mm and slide
|
| 420 |
+
it along its own axis under the glass top so that its head pushes the cube out on the far side; put it down."""
|
| 421 |
+
sk, o = self.sk, self.observe()
|
| 422 |
+
ax = o["stick_dir"]
|
| 423 |
+
g = o["free_end"] + ax * GRIP_END
|
| 424 |
+
sk.set_gripper(False, steps=8)
|
| 425 |
+
sk.move_to([g[0], g[1], Z_STICK + 0.08], yaw=self._yaw_near(float(np.arctan2(ax[1], ax[0]))))
|
| 426 |
+
self._align()
|
| 427 |
+
sk.move_to([g[0], g[1], Z_STICK], tol=0.003)
|
| 428 |
+
sk.set_gripper(True, steps=15)
|
| 429 |
+
sk.move_to([g[0], g[1], Z_STICK + 0.006], speed=0.05)
|
| 430 |
+
o2 = self.observe()
|
| 431 |
+
c, t_xy = o2["cube"][:2], o2["table_xy"]
|
| 432 |
+
n = np.array([0.0, -float(self.inst["side"])]) # push straight across the low table (normal of its far edge)
|
| 433 |
+
perp = np.array([-n[1], n[0]])
|
| 434 |
+
head = o2["head"]
|
| 435 |
+
# line the head up with the cube by sliding the stick sideways (no turning: a turned stick slips in the grasp)
|
| 436 |
+
lat = float((c - head) @ perp)
|
| 437 |
+
e = sk.eef_pos()
|
| 438 |
+
sk.move_to([e[0] + perp[0] * lat, e[1] + perp[1] * lat, e[2]], speed=0.05)
|
| 439 |
+
o3 = self.observe()
|
| 440 |
+
head_front = float((o3["head"] + o3["stick_dir"] * HEAD_HALF[0]) @ n)
|
| 441 |
+
gap = max(float(c @ n) - CUBE_HALF - head_front, 0.0)
|
| 442 |
+
need = (TOP_HALF[1] + CUBE_HALF + 0.05 + extra) - float((c - t_xy) @ n) # cube travel until it is clear
|
| 443 |
+
e = sk.eef_pos()
|
| 444 |
+
tgt = e[:2] + n * (gap + need)
|
| 445 |
+
sk.move_to([tgt[0], tgt[1], e[2]], speed=0.08, tol=0.004, max_steps=500)
|
| 446 |
+
sk.hold(3)
|
| 447 |
+
for _ in range(3): # still (partly) under the glass top: push on a little
|
| 448 |
+
if not self.under_table() or not sk.holding("stick_1"):
|
| 449 |
+
break
|
| 450 |
+
e = sk.eef_pos()
|
| 451 |
+
tgt = e[:2] + n * 0.025
|
| 452 |
+
sk.move_to([tgt[0], tgt[1], e[2]], speed=0.06, tol=0.004, max_steps=100)
|
| 453 |
+
sk.hold(3)
|
| 454 |
+
ax = n
|
| 455 |
+
back = sk.eef_pos()[:2] - ax * 0.05
|
| 456 |
+
sk.move_to([back[0], back[1], e[2]], speed=0.08)
|
| 457 |
+
sk.set_gripper(False, steps=10)
|
| 458 |
+
sk.move_to([back[0], back[1], envs.TABLE_Z + 0.12], speed=0.2)
|
| 459 |
+
|
| 460 |
+
def tool_push_front(self, extra=0.0):
|
| 461 |
+
"""v2 reference solution. Pick the stick up at its centre of mass, turn it to point forward (+x, away from the
|
| 462 |
+
robot) in the air, put it down behind the low table in line with the cube, re-grasp it GRIP_FRONT from its
|
| 463 |
+
free end and slide it forward under the glass top so that its head pushes the cube out of the FRONT side;
|
| 464 |
+
pull the stick back a little and put it down.
|
| 465 |
+
|
| 466 |
+
Reach: the re-grasp point is about 25 cm in front of the robot base at the start of the push; it stays
|
| 467 |
+
>= 3 cm behind the glass top's back edge at the end (the hand is about 4-13 cm above the fingertips and
|
| 468 |
+
would hit the glass edge)."""
|
| 469 |
+
sk, o = self.sk, self.observe()
|
| 470 |
+
ax = o["stick_dir"]
|
| 471 |
+
com = o["stick_xy"] + ax * STICK_COM
|
| 472 |
+
phi = float(np.arctan2(ax[1], ax[0])) # the stick points this way (handle -> head); about +-90 deg
|
| 473 |
+
sk.set_gripper(False, steps=8)
|
| 474 |
+
# grasp with gripper yaw = phi (not phi +- pi), so that turning the stick to point forward is a wrist turn to
|
| 475 |
+
# yaw 0, inside the wrist's range
|
| 476 |
+
sk.move_to([com[0], com[1], Z_STICK + 0.08], yaw=phi, wrap_yaw=False)
|
| 477 |
+
self._align()
|
| 478 |
+
sk.move_to([com[0], com[1], Z_STICK], tol=0.003)
|
| 479 |
+
sk.set_gripper(True, steps=15)
|
| 480 |
+
sk.move_to([com[0], com[1], Z_STICK + 0.10], speed=0.15)
|
| 481 |
+
c, t_xy = o["cube"][:2], o["table_xy"]
|
| 482 |
+
head_front_x = t_xy[0] - TOP_HALF[0] - 0.006 # just outside the glass top's back edge
|
| 483 |
+
put_x = head_front_x - (HANDLE_HALF[0] + 2 * HEAD_HALF[0]) + STICK_COM
|
| 484 |
+
e = sk.eef_pos()
|
| 485 |
+
sk.move_to([e[0], e[1], e[2]], yaw=0.0, wrap_yaw=False)
|
| 486 |
+
self._align()
|
| 487 |
+
sk.move_to([put_x, c[1], Z_STICK + 0.10], speed=0.2)
|
| 488 |
+
sk.move_to([put_x, c[1], Z_STICK + 0.004], speed=0.08, tol=0.003)
|
| 489 |
+
sk.set_gripper(False, steps=10)
|
| 490 |
+
sk.move_to([put_x, c[1], Z_STICK + 0.06], speed=0.15)
|
| 491 |
+
# re-grasp near the free end
|
| 492 |
+
o2 = self.observe()
|
| 493 |
+
ax2 = o2["stick_dir"]
|
| 494 |
+
g = o2["free_end"] + ax2 * GRIP_FRONT
|
| 495 |
+
sk.move_to([g[0], g[1], Z_STICK + 0.06], yaw=self._yaw_near(float(np.arctan2(ax2[1], ax2[0]))))
|
| 496 |
+
self._align()
|
| 497 |
+
sk.move_to([g[0], g[1], Z_STICK], tol=0.003)
|
| 498 |
+
sk.set_gripper(True, steps=15)
|
| 499 |
+
sk.move_to([g[0], g[1], Z_STICK + 0.006], speed=0.05)
|
| 500 |
+
# line the head up with the cube (sideways slide), then push forward
|
| 501 |
+
o3 = self.observe()
|
| 502 |
+
lat = float(c[1] - o3["head"][1])
|
| 503 |
+
e = sk.eef_pos()
|
| 504 |
+
sk.move_to([e[0], e[1] + lat, e[2]], speed=0.05)
|
| 505 |
+
o4 = self.observe()
|
| 506 |
+
head_front = float(o4["head"][0] + HEAD_HALF[0])
|
| 507 |
+
cube_tgt = t_xy[0] + TOP_HALF[0] + CUBE_HALF + 0.03 + extra
|
| 508 |
+
travel = (cube_tgt - CUBE_HALF) - head_front
|
| 509 |
+
e = sk.eef_pos()
|
| 510 |
+
sk.move_to([e[0] + travel, e[1], e[2]], speed=0.08, tol=0.004, max_steps=500)
|
| 511 |
+
sk.hold(3)
|
| 512 |
+
e = sk.eef_pos()
|
| 513 |
+
sk.move_to([e[0] - 0.05, e[1], e[2]], speed=0.08)
|
| 514 |
+
sk.set_gripper(False, steps=10)
|
| 515 |
+
e = sk.eef_pos()
|
| 516 |
+
sk.move_to([e[0], e[1], envs.TABLE_Z + 0.12], speed=0.2)
|
| 517 |
+
|
| 518 |
+
def execute(self, inst, params):
|
| 519 |
+
if params["mode"] == "tool":
|
| 520 |
+
self.tool_push_out(params.get("extra", 0.0))
|
| 521 |
+
elif params["mode"] == "front":
|
| 522 |
+
self.tool_push_front(params.get("extra", 0.0))
|
| 523 |
+
self.grasp_cube_and_bin(params.get("dxy", (0.0, 0.0)), params.get("dyaw", 0.0))
|
| 524 |
+
|
| 525 |
+
# ------------------------------------------------------------ scripted references
|
| 526 |
+
def default_params(self, inst):
|
| 527 |
+
"""v2 prior: what every cla2 Sonnet run did -- take the stick and push the cube straight across (towards
|
| 528 |
+
the bin, which is now behind the hidden panel)"""
|
| 529 |
+
return dict(mode="tool")
|
| 530 |
+
|
| 531 |
+
def oracle_params(self, inst):
|
| 532 |
+
return dict(mode="front")
|
| 533 |
+
|
| 534 |
+
def blind_params(self, inst, attempt, rng):
|
| 535 |
+
"""no history: the prior with a random extra push length"""
|
| 536 |
+
return dict(mode="tool", extra=float(abs(rng.normal(0, 0.03))))
|
| 537 |
+
|
| 538 |
+
def adapt_params(self, inst, history):
|
| 539 |
+
"""v2: the cube stayed under the low table after a push across -> something blocks that side: push it out of
|
| 540 |
+
the front instead. Hand grasp blocked by the glass -> use the stick (the v1 lesson). Front push that did not
|
| 541 |
+
get it out -> push further."""
|
| 542 |
+
out, prm = history[-1]["outcome"], history[-1]["params"]
|
| 543 |
+
if prm["mode"] == "grasp":
|
| 544 |
+
return dict(mode="tool") if out["mode"] in ("blocked", "under") else dict(prm)
|
| 545 |
+
if prm["mode"] == "tool":
|
| 546 |
+
return dict(mode="front") if out["mode"] in ("pane", "under", "blocked") else dict(prm)
|
| 547 |
+
if out["mode"] in ("under", "blocked"):
|
| 548 |
+
return dict(prm, extra=prm.get("extra", 0.0) + 0.02)
|
| 549 |
+
return dict(prm)
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l3_wide.py
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L3-B too_wide_push: a box that is slightly too wide for the gripper must be pushed into a square on the table.
|
| 2 |
+
|
| 3 |
+
Why the prior fails: the box looks like an ordinary graspable box (narrow side 8.3-8.9 cm, long side 11-13 cm,
|
| 4 |
+
4 cm high), but the Panda's fingers open to only 7.9 cm. A top-down grasp across the narrow side therefore puts
|
| 5 |
+
both fingers on top of the box; closing them grips nothing. Across the long side it is worse, and retrying the
|
| 6 |
+
same grasp with small variations fails the same way. A difference of 4-10 mm between the box and the maximum
|
| 7 |
+
opening is not readable from the camera images, and the agent is not told the gripper's opening.
|
| 8 |
+
|
| 9 |
+
What must be learned from the failure: this object cannot be picked up at all -> change the manipulation mode:
|
| 10 |
+
close the gripper and push the box (there is no push primitive: the agent closes the gripper, lowers it beside
|
| 11 |
+
the box and moves it along the table with move_to), keeping the box from turning, until it lies completely
|
| 12 |
+
inside the square.
|
| 13 |
+
|
| 14 |
+
Layout (randomised per instance): box size, position and yaw (long side roughly along x or along y, +-10 deg),
|
| 15 |
+
target square (18 x 18 cm inner, axis-aligned) 16-22 cm away along one world axis (forward, backward, left or
|
| 16 |
+
right) with a lateral offset of up to 3 cm.
|
| 17 |
+
|
| 18 |
+
Protocol: cross (reset to the same instance before every attempt), k = 5.
|
| 19 |
+
"""
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
from .. import envs
|
| 23 |
+
from ..bddl import write_bddl
|
| 24 |
+
from ..objects import box_xml, register_generated
|
| 25 |
+
from ..skills import DT, _rot_err
|
| 26 |
+
from ..task_base import LFFTask, register_task
|
| 27 |
+
from .l5_slide import square_frame_xml
|
| 28 |
+
|
| 29 |
+
BOX_HALF_MAX = (0.07, 0.05, 0.02) # registered size (x = long, y = narrow, z); shrunk per instance
|
| 30 |
+
BOX_HALF_Z = 0.02 # 4 cm high
|
| 31 |
+
BOX_MASS = 0.40
|
| 32 |
+
BOX_MU = 0.6 # box sliding friction (priority over the table's 1.0 and the fingers')
|
| 33 |
+
GRIP_OPEN = 0.079 # measured distance between the finger pads when fully open
|
| 34 |
+
SQ_IN = 0.09 # target square: 18 cm inner side
|
| 35 |
+
SQ_LINE = 0.008
|
| 36 |
+
Z_GRASP = envs.TABLE_Z + 0.022 # site height of a normal top-down grasp of a 4 cm box (pads 1.7-3.4 cm above table)
|
| 37 |
+
Z_PUSH = envs.TABLE_Z + 0.02 # site height while pushing: finger tips ~1 cm above the table
|
| 38 |
+
PUSH_SPEED = 0.08
|
| 39 |
+
FRONT_GAP = 0.03 # where a push stroke starts: this far behind the box face
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _wrap_pi(a):
|
| 43 |
+
return float((a + np.pi) % (2 * np.pi) - np.pi)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _yaw_of(quat_wxyz):
|
| 47 |
+
w, x, y, z = quat_wxyz
|
| 48 |
+
return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)))
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
DIRS = {"forward": (1.0, 0.0), "backward": (-1.0, 0.0), "left": (0.0, 1.0), "right": (0.0, -1.0)}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@register_task
|
| 55 |
+
class TooWidePush(LFFTask):
|
| 56 |
+
name = "l3_too_wide_push"
|
| 57 |
+
level = "L3"
|
| 58 |
+
category = "strategy_switching"
|
| 59 |
+
capabilities = ("Perceive", "Reason", "Plan")
|
| 60 |
+
protocol = "cross"
|
| 61 |
+
instruction = "Put the brown box completely inside the green square marked on the table."
|
| 62 |
+
instruction_indirect = "Put the cardboard-coloured package completely inside the green outlined area on the table."
|
| 63 |
+
|
| 64 |
+
def __init__(self, cam_res=None):
|
| 65 |
+
super().__init__(cam_res)
|
| 66 |
+
self._mon = None
|
| 67 |
+
self.inst = None
|
| 68 |
+
orig_step = self.env.step
|
| 69 |
+
|
| 70 |
+
def step(action): # per-control-step event monitor (also sees agent-driven attempts)
|
| 71 |
+
ret = orig_step(action)
|
| 72 |
+
if self._mon is not None:
|
| 73 |
+
self._monitor_step()
|
| 74 |
+
return ret
|
| 75 |
+
|
| 76 |
+
self.env.step = step
|
| 77 |
+
|
| 78 |
+
# ------------------------------------------------------------ scene
|
| 79 |
+
def make_bddl(self):
|
| 80 |
+
box = register_generated("LffWideBox", box_xml("lff_wide_box", BOX_HALF_MAX, (0.62, 0.45, 0.28, 1.0),
|
| 81 |
+
density=500))
|
| 82 |
+
sq = register_generated("LffWideSquare", square_frame_xml("lff_wide_square", inner_half=SQ_IN, line_w=SQ_LINE),
|
| 83 |
+
free=False)
|
| 84 |
+
objs = [("box_1", box, "box_region", (-0.11, -0.21, -0.09, -0.19))]
|
| 85 |
+
fx = [("square_1", sq, "square_region", (-0.01, 0.19, 0.01, 0.21))]
|
| 86 |
+
return write_bddl(self.name, self.instruction, objs, fx)
|
| 87 |
+
|
| 88 |
+
def _box_geoms(self):
|
| 89 |
+
if not hasattr(self, "_bg"):
|
| 90 |
+
m = self.env.sim.model
|
| 91 |
+
bid = envs.body_id(self.env, "box_1")
|
| 92 |
+
self._bg = [g for g in range(m.ngeom) if m.geom_bodyid[g] == bid]
|
| 93 |
+
return self._bg
|
| 94 |
+
|
| 95 |
+
def sample_instance(self, seed):
|
| 96 |
+
rng = np.random.default_rng(seed)
|
| 97 |
+
while True:
|
| 98 |
+
narrow = float(rng.uniform(0.083, 0.089))
|
| 99 |
+
long_ = float(rng.uniform(0.11, 0.13))
|
| 100 |
+
long_axis = str(rng.choice(["x", "y"]))
|
| 101 |
+
yaw = (0.0 if long_axis == "x" else np.pi / 2) + float(rng.uniform(-np.radians(10), np.radians(10)))
|
| 102 |
+
dname = str(rng.choice(list(DIRS)))
|
| 103 |
+
u = np.array(DIRS[dname])
|
| 104 |
+
# half extent of the box along the push direction (box roughly axis aligned)
|
| 105 |
+
ext = 0.5 * (long_ if (long_axis == "x") == (dname in ("forward", "backward")) else narrow)
|
| 106 |
+
dist = float(rng.uniform(SQ_IN + ext + 0.01, SQ_IN + ext + 0.07))
|
| 107 |
+
lat = float(rng.uniform(-0.03, 0.03))
|
| 108 |
+
box_xy = np.array([rng.uniform(-0.20, 0.04), rng.uniform(-0.20, 0.20)])
|
| 109 |
+
sq_xy = box_xy + u * dist + np.array([-u[1], u[0]]) * lat
|
| 110 |
+
# reach: pushing backward needs the hand ~5 cm beyond the box's far face; the arm's reach at table height
|
| 111 |
+
# ends around x = 0.05-0.08 (seed 1015 of the first version: hand stalled at x = 0.09, box never moved)
|
| 112 |
+
reach_ok = dname != "backward" or box_xy[0] + ext <= -0.01
|
| 113 |
+
if -0.22 <= sq_xy[0] <= 0.06 and -0.20 <= sq_xy[1] <= 0.20 and reach_ok:
|
| 114 |
+
return dict(seed=int(seed), box_half=[long_ / 2, narrow / 2], box_yaw=float(yaw), box_xy=box_xy.tolist(),
|
| 115 |
+
square_xy=sq_xy.tolist(), direction=dname, long_axis=long_axis)
|
| 116 |
+
|
| 117 |
+
def apply_instance(self, inst):
|
| 118 |
+
self.inst = inst
|
| 119 |
+
m = self.env.sim.model
|
| 120 |
+
for g in self._box_geoms():
|
| 121 |
+
m.geom_size[g, 0], m.geom_size[g, 1] = inst["box_half"]
|
| 122 |
+
m.geom_size[g, 2] = BOX_HALF_Z
|
| 123 |
+
envs.scale_mass(self.env, "box_1", BOX_MASS)
|
| 124 |
+
envs.set_friction(self.env, "box_1", BOX_MU)
|
| 125 |
+
sq = self.env.fixtures_dict["square_1"]
|
| 126 |
+
for g in range(m.ngeom):
|
| 127 |
+
if (m.geom_id2name(g) or "").startswith("square_1_"):
|
| 128 |
+
m.geom_contype[g] = 0
|
| 129 |
+
m.geom_conaffinity[g] = 0
|
| 130 |
+
bid = m.body_name2id(sq.root_body)
|
| 131 |
+
m.body_pos[bid] = [inst["square_xy"][0], inst["square_xy"][1], envs.TABLE_Z + 0.0002]
|
| 132 |
+
m.body_quat[bid] = [1.0, 0.0, 0.0, 0.0]
|
| 133 |
+
bx, by = inst["box_xy"]
|
| 134 |
+
envs.set_obj_pose(self.env, "box_1", [bx, by, envs.TABLE_Z + BOX_HALF_Z + 0.0005], yaw=inst["box_yaw"])
|
| 135 |
+
|
| 136 |
+
def reset_instance(self, inst, recorder=None):
|
| 137 |
+
self._mon = None
|
| 138 |
+
sk = super().reset_instance(inst, recorder=recorder)
|
| 139 |
+
self._start_monitor()
|
| 140 |
+
return sk
|
| 141 |
+
|
| 142 |
+
# ------------------------------------------------------------ geometry / perception stand-in
|
| 143 |
+
def observe(self):
|
| 144 |
+
"""What a perfect perceiver reads off the image: box centre, yaw and footprint, square centre."""
|
| 145 |
+
b = envs.obj_pos(self.env, "box_1")
|
| 146 |
+
return dict(box_xy=b[:2].copy(), box_yaw=_yaw_of(envs.obj_quat(self.env, "box_1")),
|
| 147 |
+
square_xy=np.array(self.inst["square_xy"], float), half=np.array(self.inst["box_half"], float))
|
| 148 |
+
|
| 149 |
+
def corners3d(self):
|
| 150 |
+
"""the 8 corners of the box (world)"""
|
| 151 |
+
d = self.env.sim.data
|
| 152 |
+
bid = envs.body_id(self.env, "box_1")
|
| 153 |
+
R = d.body_xmat[bid].reshape(3, 3)
|
| 154 |
+
h = np.array([self.inst["box_half"][0], self.inst["box_half"][1], BOX_HALF_Z])
|
| 155 |
+
return np.array([d.body_xpos[bid] + R @ (h * [sx, sy, sz]) for sx in (-1, 1) for sy in (-1, 1)
|
| 156 |
+
for sz in (-1, 1)])
|
| 157 |
+
|
| 158 |
+
def corners(self, o=None):
|
| 159 |
+
"""footprint corners (xy) of the box in its current pose (also when it is tilted or on its side)"""
|
| 160 |
+
return self.corners3d()[:, :2]
|
| 161 |
+
|
| 162 |
+
def protrusion(self, o=None):
|
| 163 |
+
"""How far the box footprint sticks out beyond each edge of the square (m, >0 = outside)."""
|
| 164 |
+
o = o or self.observe()
|
| 165 |
+
rel = self.corners(o) - o["square_xy"]
|
| 166 |
+
return {"forward": float(rel[:, 0].max() - SQ_IN), "backward": float(-rel[:, 0].min() - SQ_IN),
|
| 167 |
+
"left": float(rel[:, 1].max() - SQ_IN), "right": float(-rel[:, 1].min() - SQ_IN)}
|
| 168 |
+
|
| 169 |
+
def extent_along(self, u, o=None):
|
| 170 |
+
"""half extent of the box footprint along the unit xy vector u"""
|
| 171 |
+
o = o or self.observe()
|
| 172 |
+
c, s = np.cos(o["box_yaw"]), np.sin(o["box_yaw"])
|
| 173 |
+
hx, hy = o["half"]
|
| 174 |
+
return float(hx * abs(u @ [c, s]) + hy * abs(u @ [-s, c]))
|
| 175 |
+
|
| 176 |
+
# ------------------------------------------------------------ contacts / event monitor
|
| 177 |
+
def _groups(self):
|
| 178 |
+
if not hasattr(self, "_gg"):
|
| 179 |
+
m = self.env.sim.model
|
| 180 |
+
fg = {g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_finger")}
|
| 181 |
+
robot = set(envs.robot_geom_ids(self.env))
|
| 182 |
+
self._gg = (fg, robot, set(envs.obj_geom_ids(self.env, "box_1")))
|
| 183 |
+
return self._gg
|
| 184 |
+
|
| 185 |
+
def _finger_landings(self):
|
| 186 |
+
"""{'box' | 'table' | 'other': n_fingers} for fingers resting on a top surface (contact normal vertical)."""
|
| 187 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 188 |
+
fg, robot, box = self._groups()
|
| 189 |
+
out = {}
|
| 190 |
+
for i in range(d.ncon):
|
| 191 |
+
c = d.contact[i]
|
| 192 |
+
if c.geom1 in fg and c.geom2 not in robot:
|
| 193 |
+
f, other = c.geom1, c.geom2
|
| 194 |
+
elif c.geom2 in fg and c.geom1 not in robot:
|
| 195 |
+
f, other = c.geom2, c.geom1
|
| 196 |
+
else:
|
| 197 |
+
continue
|
| 198 |
+
if abs(c.frame[2]) < 0.7:
|
| 199 |
+
continue
|
| 200 |
+
lab = "box" if other in box else ("table" if (m.geom_id2name(other) or "").startswith("table") else "other")
|
| 201 |
+
name = m.geom_id2name(f) or ""
|
| 202 |
+
out.setdefault(lab, set()).add("1" if "finger1" in name else "2")
|
| 203 |
+
return out
|
| 204 |
+
|
| 205 |
+
def _closing_axis(self):
|
| 206 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 207 |
+
jid = m.joint_name2id(self.env.robots[0].gripper.joints[0])
|
| 208 |
+
a = d.xaxis[jid][:2]
|
| 209 |
+
return a / max(np.linalg.norm(a), 1e-9)
|
| 210 |
+
|
| 211 |
+
def _start_monitor(self):
|
| 212 |
+
b = envs.obj_pos(self.env, "box_1")
|
| 213 |
+
self._mon = dict(rest_z=float(b[2]), start_xy=b[:2].copy(), start_yaw=_yaw_of(envs.obj_quat(self.env, "box_1")),
|
| 214 |
+
max_dz=0.0, top_hit=None, prev=set(), was_held=False)
|
| 215 |
+
|
| 216 |
+
def _monitor_step(self):
|
| 217 |
+
mon = self._mon
|
| 218 |
+
zmin = float(self.corners3d()[:, 2].min())
|
| 219 |
+
mon["max_dz"] = max(mon["max_dz"], zmin - envs.TABLE_Z) # whole box above the table
|
| 220 |
+
hits = self._finger_landings()
|
| 221 |
+
open_ = self.sk is not None and self.sk.gripper_width() > 0.03
|
| 222 |
+
if "box" in hits and "box" not in mon["prev"] and open_: # an open gripper landing on the box top = a grasp
|
| 223 |
+
o = self.observe()
|
| 224 |
+
ca = self._closing_axis()
|
| 225 |
+
e = self.env.sim.data.site_xpos[self.env.robots[0].eef_site_id]
|
| 226 |
+
mon["top_hit"] = dict(span=2 * self.extent_along(ca, o), n_fingers=len(hits["box"]),
|
| 227 |
+
offset=float(np.linalg.norm(e[:2] - o["box_xy"])))
|
| 228 |
+
if "box" in hits and len(hits["box"]) == 2 and mon["top_hit"] is not None and open_:
|
| 229 |
+
mon["top_hit"]["n_fingers"] = 2
|
| 230 |
+
mon["prev"] = set(hits)
|
| 231 |
+
|
| 232 |
+
# ------------------------------------------------------------ outcome / F2
|
| 233 |
+
def outcome(self, inst):
|
| 234 |
+
"""Success = the whole box footprint inside the square, box resting on the table, released."""
|
| 235 |
+
envs.settle(self.env, 30)
|
| 236 |
+
env, mon = self.env, self._mon or {}
|
| 237 |
+
o = self.observe()
|
| 238 |
+
b = envs.obj_pos(env, "box_1")
|
| 239 |
+
prot = self.protrusion(o)
|
| 240 |
+
inside = max(prot.values()) <= 0.0
|
| 241 |
+
upright = abs(envs.obj_upright_cos(env, "box_1")) > 0.9
|
| 242 |
+
held = bool(self.sk.holding("box_1")) if self.sk is not None else False
|
| 243 |
+
zmin = float(self.corners3d()[:, 2].min())
|
| 244 |
+
resting = abs(zmin - envs.TABLE_Z) < 0.01
|
| 245 |
+
success = bool(inside and resting and not held)
|
| 246 |
+
rel = o["box_xy"] - o["square_xy"]
|
| 247 |
+
moved = float(np.linalg.norm(o["box_xy"] - mon.get("start_xy", o["box_xy"])))
|
| 248 |
+
turned = float(np.degrees(_wrap_pi(o["box_yaw"] - mon.get("start_yaw", o["box_yaw"])))) if upright else 0.0
|
| 249 |
+
lifted = mon.get("max_dz", 0.0) > 0.01
|
| 250 |
+
top = mon.get("top_hit")
|
| 251 |
+
parts, mode = [], "success"
|
| 252 |
+
|
| 253 |
+
def where():
|
| 254 |
+
return (f"its centre is {100 * abs(rel[0]):.1f} cm {'forward' if rel[0] > 0 else 'backward'} and "
|
| 255 |
+
f"{100 * abs(rel[1]):.1f} cm {'left' if rel[1] > 0 else 'right'} of the square's centre")
|
| 256 |
+
|
| 257 |
+
def sticking():
|
| 258 |
+
return ", ".join(f"{100 * v:.1f} cm beyond the square's {k} edge" for k, v in
|
| 259 |
+
sorted(prot.items(), key=lambda kv: -kv[1]) if v > 0.0)
|
| 260 |
+
|
| 261 |
+
if success:
|
| 262 |
+
parts.append("The box lies completely inside the square.")
|
| 263 |
+
elif b[2] < envs.TABLE_Z - 0.05:
|
| 264 |
+
mode = "fell_off"
|
| 265 |
+
parts.append("The box fell off the table.")
|
| 266 |
+
elif held:
|
| 267 |
+
mode = "held"
|
| 268 |
+
parts.append(f"The box is still held by the gripper; {where()}.")
|
| 269 |
+
elif not resting:
|
| 270 |
+
mode = "not_resting"
|
| 271 |
+
parts.append(f"The box is not resting on the table (it is propped up or tilted); {where()}.")
|
| 272 |
+
else:
|
| 273 |
+
mode = "outside"
|
| 274 |
+
if top is not None and not lifted:
|
| 275 |
+
mode = "too_wide"
|
| 276 |
+
if top["n_fingers"] >= 2 or top["span"] > GRIP_OPEN:
|
| 277 |
+
parts.append(f"The fingers came down on top of the box instead of on either side of it: along the "
|
| 278 |
+
f"gripper's closing direction the box measures {100 * top['span']:.1f} cm, wider than "
|
| 279 |
+
f"the gripper's maximum opening ({100 * GRIP_OPEN:.1f} cm). The box was not grasped.")
|
| 280 |
+
else:
|
| 281 |
+
parts.append(f"A finger came down on top of the box (the gripper was {100 * top['offset']:.1f} cm "
|
| 282 |
+
f"from the box centre). The box was not grasped.")
|
| 283 |
+
if moved < 0.01:
|
| 284 |
+
mode = "not_moved" if mode == "outside" else mode
|
| 285 |
+
parts.append(f"The box did not move; it sticks out {sticking()}.")
|
| 286 |
+
else:
|
| 287 |
+
parts.append(f"The box was moved {100 * moved:.1f} cm but is not completely inside the square: it "
|
| 288 |
+
f"sticks out {sticking()}; {where()}.")
|
| 289 |
+
if abs(turned) >= 5:
|
| 290 |
+
rot = "counter-clockwise" if turned > 0 else "clockwise"
|
| 291 |
+
parts.append(f"It turned by {abs(turned):.0f} deg ({rot} seen from above).")
|
| 292 |
+
if not success and not upright and mode not in ("fell_off",):
|
| 293 |
+
parts.append("The box is no longer lying on its large bottom face.")
|
| 294 |
+
out = dict(success=success, mode=mode, inside=bool(inside), protrusion=prot, rel=[float(rel[0]), float(rel[1])],
|
| 295 |
+
moved=moved, turned_deg=turned, lifted=bool(lifted), held=held, upright=bool(upright),
|
| 296 |
+
top_hit_span=None if top is None else float(top["span"]),
|
| 297 |
+
terminal=bool(b[2] < envs.TABLE_Z - 0.05), detail=" ".join(parts))
|
| 298 |
+
self._start_monitor()
|
| 299 |
+
return out
|
| 300 |
+
|
| 301 |
+
# ------------------------------------------------------------ primitives for the scripted policies
|
| 302 |
+
def _yaw_near(self, yaw):
|
| 303 |
+
cands = [yaw + k * np.pi for k in (-2, -1, 0, 1, 2)]
|
| 304 |
+
cands = [c for c in cands if abs(c) <= np.pi / 2 + 0.4] or cands
|
| 305 |
+
return float(min(cands, key=lambda c: abs(c - self.sk.yaw)))
|
| 306 |
+
|
| 307 |
+
def _align(self, tol=0.03, max_steps=60):
|
| 308 |
+
sk = self.sk
|
| 309 |
+
for _ in range(max_steps):
|
| 310 |
+
R = sk._R() @ sk.eef_mat().T
|
| 311 |
+
if np.arccos(np.clip((np.trace(R) - 1) / 2, -1, 1)) < tol:
|
| 312 |
+
break
|
| 313 |
+
sk.hold(1)
|
| 314 |
+
|
| 315 |
+
def _guarded_descent(self, xyz, speed=0.12, max_steps=60):
|
| 316 |
+
"""descent that stops when a finger lands on a top surface above the target (contact sensing)"""
|
| 317 |
+
sk = self.sk
|
| 318 |
+
p0 = sk.eef_pos()
|
| 319 |
+
tgt = np.asarray(xyz, float)
|
| 320 |
+
dist = max(np.linalg.norm(tgt - p0), 1e-6)
|
| 321 |
+
R = sk._R()
|
| 322 |
+
for k in range(max_steps):
|
| 323 |
+
ref = p0 + (tgt - p0) * min(1.0, (k + 1) * speed * DT / dist)
|
| 324 |
+
sk._act(ref - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip)
|
| 325 |
+
if self._finger_landings() and sk.eef_pos()[2] > tgt[2] + 0.005:
|
| 326 |
+
break
|
| 327 |
+
if np.linalg.norm(tgt - sk.eef_pos()) < 0.003:
|
| 328 |
+
break
|
| 329 |
+
sk.hold(4)
|
| 330 |
+
|
| 331 |
+
def _finger_front(self, direction):
|
| 332 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 333 |
+
e = self.sk.eef_pos()
|
| 334 |
+
best = 0.0
|
| 335 |
+
for g in range(m.ngeom):
|
| 336 |
+
if not (m.geom_id2name(g) or "").startswith("gripper0_finger") or m.geom_type[g] != 7:
|
| 337 |
+
continue
|
| 338 |
+
mid = m.geom_dataid[g]
|
| 339 |
+
v = m.mesh_vert[m.mesh_vertadr[mid]:m.mesh_vertadr[mid] + m.mesh_vertnum[mid]]
|
| 340 |
+
w = v @ d.geom_xmat[g].reshape(3, 3).T + d.geom_xpos[g] - e
|
| 341 |
+
best = max(best, float((w[:, :2] @ direction).max()))
|
| 342 |
+
return best
|
| 343 |
+
|
| 344 |
+
def grasp_and_place(self, dx=0.0, dy=0.0, dyaw=0.0, across="narrow"):
|
| 345 |
+
"""Top-down grasp across the box's narrow side at its centre (+ offsets); if it is held, put it in the square."""
|
| 346 |
+
sk, o = self.sk, self.observe()
|
| 347 |
+
gx, gy = o["box_xy"][0] + dx, o["box_xy"][1] + dy
|
| 348 |
+
# yaw 0 closes along world y; to close across the narrow side (box local y) use the box yaw
|
| 349 |
+
yaw = self._yaw_near(o["box_yaw"] + (0.0 if across == "narrow" else np.pi / 2) + dyaw)
|
| 350 |
+
sk.set_gripper(False, steps=8)
|
| 351 |
+
sk.move_to([gx, gy, Z_GRASP + 0.10], yaw=yaw)
|
| 352 |
+
self._align()
|
| 353 |
+
self._guarded_descent([gx, gy, Z_GRASP])
|
| 354 |
+
sk.set_gripper(True, steps=15)
|
| 355 |
+
z0 = envs.obj_pos(self.env, "box_1")[2]
|
| 356 |
+
sk.move_to([gx, gy, Z_GRASP + 0.12], speed=0.25)
|
| 357 |
+
if not (sk.holding("box_1") and envs.obj_pos(self.env, "box_1")[2] > z0 + 0.06):
|
| 358 |
+
sk.set_gripper(False, steps=8)
|
| 359 |
+
return
|
| 360 |
+
sx, sy = o["square_xy"]
|
| 361 |
+
sk.move_to([sx, sy, Z_GRASP + 0.12])
|
| 362 |
+
sk.move_to([sx, sy, Z_GRASP + 0.005])
|
| 363 |
+
sk.set_gripper(False, steps=12)
|
| 364 |
+
sk.move_to([sx, sy, Z_GRASP + 0.12])
|
| 365 |
+
|
| 366 |
+
def push_stroke(self, u, dist):
|
| 367 |
+
"""Closed gripper behind the box face opposite to u (fingers side by side across the push direction), sweep
|
| 368 |
+
along u so that the box moves `dist`, then lift away. Built from move_to + close only."""
|
| 369 |
+
sk, o = self.sk, self.observe()
|
| 370 |
+
u = np.asarray(u, float) / np.linalg.norm(u)
|
| 371 |
+
c = o["box_xy"]
|
| 372 |
+
ext = self.extent_along(u, o)
|
| 373 |
+
yaw = self._yaw_near(float(np.arctan2(u[1], u[0]))) # yaw a: closing axis along (-sin a, cos a), i.e. across u
|
| 374 |
+
sk.set_gripper(True, steps=6)
|
| 375 |
+
face = c - u * ext
|
| 376 |
+
p_hi = face - u * 0.08
|
| 377 |
+
sk.move_to([p_hi[0], p_hi[1], Z_PUSH + 0.10], yaw=yaw)
|
| 378 |
+
self._align()
|
| 379 |
+
front = self._finger_front(u)
|
| 380 |
+
start = face - u * (front + FRONT_GAP)
|
| 381 |
+
stop = face + u * (dist - front)
|
| 382 |
+
sk.move_to([start[0], start[1], Z_PUSH + 0.10])
|
| 383 |
+
sk.move_to([start[0], start[1], Z_PUSH], tol=0.003)
|
| 384 |
+
sk.move_to([stop[0], stop[1], Z_PUSH], speed=PUSH_SPEED, tol=0.004, max_steps=400)
|
| 385 |
+
sk.hold(3)
|
| 386 |
+
back = stop - u * 0.02
|
| 387 |
+
sk.move_to([back[0], back[1], Z_PUSH], speed=0.1, max_steps=40)
|
| 388 |
+
sk.move_to([back[0], back[1], Z_PUSH + 0.10], speed=0.25)
|
| 389 |
+
|
| 390 |
+
def push_to(self, goal_xy, max_strokes=4, tol=0.008):
|
| 391 |
+
"""Closed-loop push along the box's own axes (each stroke perpendicular to a face keeps the box from turning):
|
| 392 |
+
re-observe after every stroke, push along the axis with the larger remaining error."""
|
| 393 |
+
for _ in range(max_strokes):
|
| 394 |
+
o = self.observe()
|
| 395 |
+
d = np.asarray(goal_xy, float) - o["box_xy"]
|
| 396 |
+
c, s = np.cos(o["box_yaw"]), np.sin(o["box_yaw"])
|
| 397 |
+
axes = [np.array([c, s]), np.array([-s, c])]
|
| 398 |
+
comps = [float(d @ a) for a in axes]
|
| 399 |
+
i = int(np.argmax(np.abs(comps)))
|
| 400 |
+
if abs(comps[i]) < tol:
|
| 401 |
+
break
|
| 402 |
+
u = axes[i] * np.sign(comps[i])
|
| 403 |
+
self.push_stroke(u, abs(comps[i]))
|
| 404 |
+
|
| 405 |
+
def execute(self, inst, params):
|
| 406 |
+
if params["mode"] == "push":
|
| 407 |
+
goal = np.array(inst["square_xy"]) + np.asarray(params.get("goal_offset", (0.0, 0.0)))
|
| 408 |
+
self.push_to(goal, max_strokes=params.get("strokes", 4))
|
| 409 |
+
else:
|
| 410 |
+
self.grasp_and_place(params.get("dx", 0.0), params.get("dy", 0.0), params.get("dyaw", 0.0),
|
| 411 |
+
params.get("across", "narrow"))
|
| 412 |
+
|
| 413 |
+
# ------------------------------------------------------------ scripted references
|
| 414 |
+
def default_params(self, inst):
|
| 415 |
+
return dict(mode="grasp")
|
| 416 |
+
|
| 417 |
+
def oracle_params(self, inst):
|
| 418 |
+
return dict(mode="push")
|
| 419 |
+
|
| 420 |
+
def blind_params(self, inst, attempt, rng):
|
| 421 |
+
return dict(mode="grasp", dx=float(rng.normal(0, 0.008)), dy=float(rng.normal(0, 0.008)),
|
| 422 |
+
dyaw=float(rng.normal(0, 0.15)))
|
| 423 |
+
|
| 424 |
+
def adapt_params(self, inst, history):
|
| 425 |
+
"""too_wide (fingers on top of the box, span > opening) -> the box cannot be picked up: push it instead.
|
| 426 |
+
A push that leaves the box outside -> push again, aiming past the reported miss (box centre offset)."""
|
| 427 |
+
out, prm = history[-1]["outcome"], history[-1]["params"]
|
| 428 |
+
if prm["mode"] != "push":
|
| 429 |
+
if out["mode"] in ("too_wide", "not_moved"):
|
| 430 |
+
return dict(mode="push")
|
| 431 |
+
return dict(prm)
|
| 432 |
+
if out["mode"] == "outside":
|
| 433 |
+
off = np.asarray(prm.get("goal_offset", (0.0, 0.0))) - 0.5 * np.asarray(out["rel"])
|
| 434 |
+
return dict(mode="push", goal_offset=off.tolist())
|
| 435 |
+
return dict(prm)
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l6_swap.py
ADDED
|
@@ -0,0 +1,466 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L6-A swap_interrupt: swap two items between identical pads; the second carry is interrupted by a slip.
|
| 2 |
+
|
| 3 |
+
Scene: four identical dark round pads (flat markers, no collision). The cream cheese (X) starts on pad A,
|
| 4 |
+
the butter (Y) on pad B, pads C and D are empty. Pad positions, which pad is which and the drop spot are
|
| 5 |
+
random per seed. Goal: X on B and Y on A.
|
| 6 |
+
|
| 7 |
+
Standard procedure: X: A -> C (temporary), Y: B -> A, X: C -> B. During the second carry (whichever item is
|
| 8 |
+
carried while the other one has already left its start pad), the carried item "slips": the gripper opens
|
| 9 |
+
and the item lands on the table at a hidden spot that is on no pad. Afterwards X sits on C, Y lies on the
|
| 10 |
+
table and A, B, D are empty -- the current image no longer shows which empty pad was whose. The information
|
| 11 |
+
needed to finish ("what has been done, where did each item start") is only in the agent's own history.
|
| 12 |
+
|
| 13 |
+
The drop spot is placed next to a *lure* pad: the spare pad ("spare", 50 %), the carried item's own start pad
|
| 14 |
+
("source", 25 %) or its true destination ("dest", 25 %). So "put it on the nearest pad" is usually wrong and
|
| 15 |
+
proximity is close to uninformative; a stronger bias towards the start pad would open a memoryless shortcut
|
| 16 |
+
(tidy both items onto their nearest pads = undo, then swap again), see the task card.
|
| 17 |
+
|
| 18 |
+
Protocol: within (one episode, no reset). Attempt granularity: an attempt is everything the agent does until
|
| 19 |
+
it declares the task done; after each attempt the outcome is measured (F1/F2 feedback) and, if it failed, the
|
| 20 |
+
agent continues from the current state. The slip is injected once per episode, inside attempt 1 (it is an
|
| 21 |
+
in-attempt failure event, reported immediately: see `drain_events`). Scripted references:
|
| 22 |
+
|
| 23 |
+
oracle knows the true start layout; after the slip puts Y on A and X on B.
|
| 24 |
+
adaptive saves the start layout from its first frame (Save), recalls it after the slip (Retrieve) and
|
| 25 |
+
finishes the swap from the right step (Utilize); later attempts fix residual misplacements from
|
| 26 |
+
memory + F2 feedback.
|
| 27 |
+
naive memoryless continuation (one attempt): after the slip it re-plans from the current frame only --
|
| 28 |
+
the stray item goes to the nearest empty pad, the item that is still on a pad goes to the nearest
|
| 29 |
+
remaining empty pad.
|
| 30 |
+
blind memoryless restart (k attempts): does not know which step it was at; tidies the stray item onto
|
| 31 |
+
the nearest empty pad and then performs the whole swap again from the current frame; every later
|
| 32 |
+
attempt again swaps the two items (repeated swap, cf. RMBench).
|
| 33 |
+
blind_continue (extra control, not in the acceptance table) attempt 1 = naive, later attempts = swap again.
|
| 34 |
+
"""
|
| 35 |
+
import numpy as np
|
| 36 |
+
|
| 37 |
+
from .. import envs
|
| 38 |
+
from ..bddl import write_bddl
|
| 39 |
+
from ..objects import _wrap, register_generated
|
| 40 |
+
from ..task_base import LFFTask, register_task
|
| 41 |
+
|
| 42 |
+
N_PADS = 4
|
| 43 |
+
PAD_R = 0.055 # pad radius (11 cm discs); items are 8 x 4.3 x 1.8 cm boxes lying flat
|
| 44 |
+
PAD_HALF_T = 0.0008
|
| 45 |
+
PAD_RGBA = (0.22, 0.24, 0.28, 1.0)
|
| 46 |
+
SUCC_R = 0.04 # item centre within 4 cm of the pad centre counts as "on that pad" for success
|
| 47 |
+
PAD_MIN_DIST = 0.17
|
| 48 |
+
PAD_REGION = (-0.26, 0.04, -0.25, 0.25) # x0, x1, y0, y1 (world)
|
| 49 |
+
PAD_REACH = 0.71 # max horizontal distance of a pad centre from the robot base
|
| 50 |
+
DROP_REGION = (-0.31, 0.07, -0.30, 0.30)
|
| 51 |
+
# beyond ~0.75 m from the base the arm ends up fully stretched (elbow at its joint limit) and the OSC gets stuck
|
| 52 |
+
MAX_REACH = 0.73
|
| 53 |
+
DROP_CLEAR = PAD_R + 0.05 # drop centre this far from every pad centre -> item fully off the pads
|
| 54 |
+
LURE_MARGIN = 0.03 # the lure pad is nearer to the drop spot than any other pad by at least this much
|
| 55 |
+
GRASP_DZ = 0.012 # gripper-site height above the table for a top-down grasp of the flat boxes
|
| 56 |
+
LIFT = 0.15
|
| 57 |
+
BASE_X = -0.66 # robot base x (world); base-frame coordinates = (x - BASE_X, y)
|
| 58 |
+
LURE_P = (("source", 0.25), ("spare", 0.5), ("dest", 0.25))
|
| 59 |
+
|
| 60 |
+
X, Y = "cream_cheese_1", "butter_1"
|
| 61 |
+
NAME = {X: "cream cheese", Y: "butter"}
|
| 62 |
+
PADS = [f"pad_{i + 1}" for i in range(N_PADS)]
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _pad_xml(model_name):
|
| 66 |
+
c = " ".join(f"{v:.3f}" for v in PAD_RGBA)
|
| 67 |
+
g = (f' <geom name="{model_name}_g0" type="cylinder" size="{PAD_R:.4f} {PAD_HALF_T:.4f}" rgba="{c}" '
|
| 68 |
+
f'density="10" contype="0" conaffinity="0" group="0" />\n'
|
| 69 |
+
f' <geom type="cylinder" size="{PAD_R:.4f} {PAD_HALF_T:.4f}" rgba="{c}" conaffinity="0" '
|
| 70 |
+
f'contype="0" group="1" />')
|
| 71 |
+
# flat marker without collisions: gravity compensation keeps it from sinking through the table
|
| 72 |
+
return _wrap(model_name, g, PAD_HALF_T, PAD_R).replace('<body name="object">',
|
| 73 |
+
'<body name="object" gravcomp="1">')
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _yaw_of(env, obj):
|
| 77 |
+
R = env.sim.data.body_xmat[envs.body_id(env, obj)].reshape(3, 3)
|
| 78 |
+
yaw = float(np.arctan2(R[1, 0], R[0, 0])) # long axis of the boxes = body x
|
| 79 |
+
return (yaw + np.pi / 2) % np.pi - np.pi / 2 # boxes are symmetric under pi
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def drop_spot(pads, src, dest, other_xy, lure, phase, dist):
|
| 83 |
+
"""Geometry of the injected drop. pads: (N,2); src / dest: start pads of the carried / other item;
|
| 84 |
+
other_xy: current xy of the other item. Returns (xy, lure_pad) or (None, None)."""
|
| 85 |
+
pads = np.asarray(pads, float)
|
| 86 |
+
rest = [i for i in range(len(pads)) if i not in (src, dest)]
|
| 87 |
+
# spare = an empty pad that is neither start pad and not the one the other item is parked on
|
| 88 |
+
occ = [i for i in rest if np.linalg.norm(pads[i] - other_xy) < PAD_R]
|
| 89 |
+
spare_c = [i for i in rest if i not in occ] or rest
|
| 90 |
+
spare = max(spare_c, key=lambda i: np.linalg.norm(pads[i] - other_xy))
|
| 91 |
+
lp = {"source": src, "dest": dest, "spare": spare}[lure]
|
| 92 |
+
for d in (dist, dist + 0.01, dist - 0.01, dist + 0.02):
|
| 93 |
+
for ang in phase + np.linspace(0, 2 * np.pi, 48, endpoint=False):
|
| 94 |
+
xy = pads[lp] + d * np.array([np.cos(ang), np.sin(ang)])
|
| 95 |
+
if not (DROP_REGION[0] <= xy[0] <= DROP_REGION[1] and DROP_REGION[2] <= xy[1] <= DROP_REGION[3]):
|
| 96 |
+
continue
|
| 97 |
+
if np.hypot(xy[0] - BASE_X, xy[1]) > MAX_REACH:
|
| 98 |
+
continue
|
| 99 |
+
dd = np.linalg.norm(pads - xy, axis=1)
|
| 100 |
+
if dd.min() < DROP_CLEAR or np.linalg.norm(xy - other_xy) < 0.12:
|
| 101 |
+
continue
|
| 102 |
+
if np.any(np.delete(dd, lp) < dd[lp] + LURE_MARGIN):
|
| 103 |
+
continue
|
| 104 |
+
return xy, int(lp)
|
| 105 |
+
return None, None
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
@register_task
|
| 109 |
+
class SwapInterrupt(LFFTask):
|
| 110 |
+
name = "l6_swap_interrupt"
|
| 111 |
+
level = "L6"
|
| 112 |
+
category = "procedural_memory"
|
| 113 |
+
capabilities = ("Perceive", "Save", "Retrieve", "Utilize")
|
| 114 |
+
protocol = "within"
|
| 115 |
+
max_attempts = 5
|
| 116 |
+
instruction = ("Swap the positions of the cream cheese and the butter: each must end up on the round pad "
|
| 117 |
+
"where the other one started. You may use the empty pads as temporary spots.")
|
| 118 |
+
instruction_indirect = ("Swap the positions of the pale blue box with the oval logo and the red-and-yellow "
|
| 119 |
+
"box: each must end up on the round pad where the other one started. You may use the "
|
| 120 |
+
"empty pads as temporary spots.")
|
| 121 |
+
inject = True # set False to run the same scene without the slip (sanity check)
|
| 122 |
+
|
| 123 |
+
# ------------------------------------------------------------ scene
|
| 124 |
+
def make_bddl(self):
|
| 125 |
+
cats = [register_generated(f"LffSwapPad{L}", _pad_xml(f"lff_swap_pad_{L.lower()}")) for L in "ABCD"]
|
| 126 |
+
objs = [(X, "cream_cheese", "cc_region", (-0.21, -0.21, -0.19, -0.19)),
|
| 127 |
+
(Y, "butter", "bu_region", (-0.21, 0.19, -0.19, 0.21)),
|
| 128 |
+
(PADS[0], cats[0], "p1_region", (0.05, -0.21, 0.07, -0.19)),
|
| 129 |
+
(PADS[1], cats[1], "p2_region", (0.05, 0.19, 0.07, 0.21)),
|
| 130 |
+
(PADS[2], cats[2], "p3_region", (-0.06, -0.01, -0.04, 0.01)),
|
| 131 |
+
(PADS[3], cats[3], "p4_region", (-0.31, -0.01, -0.29, 0.01))]
|
| 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(1000):
|
| 137 |
+
pads = []
|
| 138 |
+
while len(pads) < N_PADS:
|
| 139 |
+
p = np.array([rng.uniform(*PAD_REGION[:2]), rng.uniform(*PAD_REGION[2:])])
|
| 140 |
+
if np.hypot(p[0] - BASE_X, p[1]) > PAD_REACH:
|
| 141 |
+
continue
|
| 142 |
+
if all(np.linalg.norm(p - q) >= PAD_MIN_DIST for q in pads):
|
| 143 |
+
pads.append(p)
|
| 144 |
+
pads = np.array(pads)
|
| 145 |
+
x_pad, y_pad = 0, 1 # pad order is already random
|
| 146 |
+
u, acc = rng.uniform(), 0.0
|
| 147 |
+
for lure, pr in LURE_P:
|
| 148 |
+
acc += pr
|
| 149 |
+
if u < acc:
|
| 150 |
+
break
|
| 151 |
+
phase, dist = float(rng.uniform(0, 2 * np.pi)), float(rng.uniform(0.115, 0.14))
|
| 152 |
+
# canonical execution: X parked on the empty pad nearest to its start pad, then Y is carried
|
| 153 |
+
empt = [i for i in range(N_PADS) if i not in (x_pad, y_pad)]
|
| 154 |
+
buf = min(empt, key=lambda i: np.linalg.norm(pads[i] - pads[x_pad]))
|
| 155 |
+
xy, lp = drop_spot(pads, y_pad, x_pad, pads[buf], lure, phase, dist)
|
| 156 |
+
if xy is None:
|
| 157 |
+
continue
|
| 158 |
+
return dict(seed=int(seed), pads=pads.round(4).tolist(), x_pad=x_pad, y_pad=y_pad,
|
| 159 |
+
yaw_x=float(rng.uniform(-0.3, 0.3)), yaw_y=float(rng.uniform(-0.3, 0.3)),
|
| 160 |
+
lure=lure, drop_phase=phase, drop_dist=dist, drop_yaw=float(rng.uniform(-1.4, 1.4)),
|
| 161 |
+
trigger_dist=float(rng.uniform(0.05, 0.10)),
|
| 162 |
+
canonical_buffer=int(buf), canonical_drop_xy=xy.round(4).tolist())
|
| 163 |
+
raise RuntimeError("could not sample a layout")
|
| 164 |
+
|
| 165 |
+
def apply_instance(self, inst):
|
| 166 |
+
for i, p in enumerate(inst["pads"]):
|
| 167 |
+
envs.set_obj_pose(self.env, PADS[i], [p[0], p[1], envs.TABLE_Z + PAD_HALF_T + 0.0001])
|
| 168 |
+
envs.place_upright(self.env, X, inst["pads"][inst["x_pad"]], inst["yaw_x"])
|
| 169 |
+
envs.place_upright(self.env, Y, inst["pads"][inst["y_pad"]], inst["yaw_y"])
|
| 170 |
+
self.env.sim.forward()
|
| 171 |
+
self.slip = None
|
| 172 |
+
self.events = []
|
| 173 |
+
self._event_cursor = 0 # for drain_events (harness, per tool call)
|
| 174 |
+
self._outcome_cursor = 0 # for outcome (per attempt)
|
| 175 |
+
self._inst = inst
|
| 176 |
+
|
| 177 |
+
def reset_instance(self, inst, recorder=None):
|
| 178 |
+
sk = super().reset_instance(inst)
|
| 179 |
+
self._user_recorder = recorder
|
| 180 |
+
sk.recorder = self._on_step # slip trigger is checked on every control step
|
| 181 |
+
sk.record_every = 1
|
| 182 |
+
self._home = sk.eef_pos()
|
| 183 |
+
return sk
|
| 184 |
+
|
| 185 |
+
def go_home(self):
|
| 186 |
+
"""Lift the arm out of the camera's way (end of an attempt)."""
|
| 187 |
+
p = self.sk.eef_pos()
|
| 188 |
+
self.sk.move_to([p[0], p[1], max(p[2], self._home[2])])
|
| 189 |
+
self.sk.move_to(self._home)
|
| 190 |
+
|
| 191 |
+
# ------------------------------------------------------------ slip injection (state triggered)
|
| 192 |
+
def _on_step(self, env):
|
| 193 |
+
if self.inject and self.slip is None:
|
| 194 |
+
self._maybe_slip()
|
| 195 |
+
if self._user_recorder is not None and self.sk.n_steps % 4 == 0:
|
| 196 |
+
self._user_recorder(env)
|
| 197 |
+
|
| 198 |
+
def _maybe_slip(self):
|
| 199 |
+
"""Fires during the first carry of an item while the other item has already left its start pad,
|
| 200 |
+
i.e. the second transport of a swap, whatever order the agent chose."""
|
| 201 |
+
inst, env = self._inst, self.env
|
| 202 |
+
pads = np.asarray(inst["pads"])
|
| 203 |
+
start = {X: inst["x_pad"], Y: inst["y_pad"]}
|
| 204 |
+
for o, other in ((X, Y), (Y, X)):
|
| 205 |
+
p = envs.obj_pos(env, o)
|
| 206 |
+
if p[2] < envs.TABLE_Z + 0.05:
|
| 207 |
+
continue
|
| 208 |
+
if np.linalg.norm(p[:2] - pads[start[o]]) < inst["trigger_dist"]:
|
| 209 |
+
continue
|
| 210 |
+
q = envs.obj_pos(env, other)
|
| 211 |
+
if np.linalg.norm(q[:2] - pads[start[other]]) < PAD_R:
|
| 212 |
+
continue
|
| 213 |
+
if not self.sk.holding(o):
|
| 214 |
+
continue
|
| 215 |
+
self._do_slip(o, other, q[:2])
|
| 216 |
+
return
|
| 217 |
+
|
| 218 |
+
def _do_slip(self, o, other, other_xy):
|
| 219 |
+
inst = self._inst
|
| 220 |
+
start = {X: inst["x_pad"], Y: inst["y_pad"]}
|
| 221 |
+
args = (inst["pads"], start[o], start[other], other_xy)
|
| 222 |
+
xy, lp = drop_spot(*args, inst["lure"], inst["drop_phase"], inst["drop_dist"])
|
| 223 |
+
lure = inst["lure"]
|
| 224 |
+
for alt in ("source", "spare", "dest"): # fallback (only if the agent did something unusual)
|
| 225 |
+
if xy is not None:
|
| 226 |
+
break
|
| 227 |
+
xy, lp = drop_spot(*args, alt, inst["drop_phase"], inst["drop_dist"])
|
| 228 |
+
lure = alt
|
| 229 |
+
if xy is None:
|
| 230 |
+
xy, lp, lure = np.asarray(inst["canonical_drop_xy"]), -1, "fallback"
|
| 231 |
+
envs.place_upright(self.env, o, xy, inst["drop_yaw"])
|
| 232 |
+
self.sk.grip = -1.0 # the gripper opens
|
| 233 |
+
self.env.sim.forward()
|
| 234 |
+
text = f"The {NAME[o]} slipped out of the gripper and fell onto the table."
|
| 235 |
+
self.slip = dict(obj=o, xy=[float(v) for v in xy], lure=lure, lure_pad=lp, step=int(self.sk.n_steps))
|
| 236 |
+
self.events.append(dict(step=int(self.sk.n_steps), kind="slip", obj=o, text=text))
|
| 237 |
+
|
| 238 |
+
def drain_events(self):
|
| 239 |
+
"""Event texts since the last call (for the harness: append to the current tool-call report)."""
|
| 240 |
+
ev = self.events[self._event_cursor:]
|
| 241 |
+
self._event_cursor = len(self.events)
|
| 242 |
+
return [e["text"] for e in ev]
|
| 243 |
+
|
| 244 |
+
# ------------------------------------------------------------ perception helpers (what an agent can see)
|
| 245 |
+
def pad_xy(self):
|
| 246 |
+
return np.array([envs.obj_pos(self.env, p)[:2] for p in PADS])
|
| 247 |
+
|
| 248 |
+
def on_pad(self, o, r=PAD_R):
|
| 249 |
+
d = np.linalg.norm(self.pad_xy() - envs.obj_pos(self.env, o)[:2], axis=1)
|
| 250 |
+
return int(np.argmin(d)) if d.min() < r else None
|
| 251 |
+
|
| 252 |
+
def empty_pads(self):
|
| 253 |
+
occ = {self.on_pad(X), self.on_pad(Y)}
|
| 254 |
+
return [i for i in range(N_PADS) if i not in occ]
|
| 255 |
+
|
| 256 |
+
def _nearest(self, cands, xy):
|
| 257 |
+
pads = self.pad_xy()
|
| 258 |
+
return min(cands, key=lambda i: np.linalg.norm(pads[i] - np.asarray(xy)[:2]))
|
| 259 |
+
|
| 260 |
+
@staticmethod
|
| 261 |
+
def _bf(xy):
|
| 262 |
+
return f"({xy[0] - BASE_X:.2f}, {xy[1]:+.2f})"
|
| 263 |
+
|
| 264 |
+
def pad_label(self, i, cur=None):
|
| 265 |
+
"""Robot-centric name of pad i relative to the other pads (no coordinates in agent feedback)."""
|
| 266 |
+
cur = self.pad_xy() if cur is None else cur
|
| 267 |
+
c = cur.mean(axis=0)
|
| 268 |
+
fb = "far" if cur[i][0] > c[0] else "near"
|
| 269 |
+
lr = "left" if cur[i][1] > c[1] else "right"
|
| 270 |
+
same = [j for j in range(len(cur)) if ("far" if cur[j][0] > c[0] else "near") == fb
|
| 271 |
+
and ("left" if cur[j][1] > c[1] else "right") == lr]
|
| 272 |
+
lab = f"the {fb}-{lr} pad"
|
| 273 |
+
if len(same) > 1: # two pads in the same quadrant: tell them apart left to right
|
| 274 |
+
order = sorted(same, key=lambda j: -cur[j][1])
|
| 275 |
+
side = "more to the robot's left" if order.index(i) == 0 else "more to the robot's right"
|
| 276 |
+
lab += f" ({side} of the two)"
|
| 277 |
+
return lab
|
| 278 |
+
|
| 279 |
+
# ------------------------------------------------------------ outcome
|
| 280 |
+
def outcome(self, inst):
|
| 281 |
+
envs.settle(self.env, 20)
|
| 282 |
+
pads = np.asarray(inst["pads"])
|
| 283 |
+
target = {X: inst["y_pad"], Y: inst["x_pad"]}
|
| 284 |
+
res, ok = {}, True
|
| 285 |
+
for o in (X, Y):
|
| 286 |
+
p = envs.obj_pos(self.env, o)
|
| 287 |
+
dt = float(np.linalg.norm(p[:2] - pads[target[o]]))
|
| 288 |
+
resting = bool(envs.TABLE_Z - 0.01 < p[2] < envs.TABLE_Z + 0.05 and not self.sk.holding(o))
|
| 289 |
+
res[o] = dict(xy=[float(p[0]), float(p[1])], on_pad=self.on_pad(o), dist_to_target=dt, resting=resting)
|
| 290 |
+
ok = ok and resting and dt <= SUCC_R
|
| 291 |
+
# F2 detail: only what is observable now + events of this attempt; nothing about the start layout
|
| 292 |
+
parts = []
|
| 293 |
+
cur = self.pad_xy()
|
| 294 |
+
for o in (X, Y):
|
| 295 |
+
r = res[o]
|
| 296 |
+
if r["on_pad"] is not None:
|
| 297 |
+
parts.append(f"the {NAME[o]} is on {self.pad_label(r['on_pad'], cur)}")
|
| 298 |
+
else:
|
| 299 |
+
dd = np.linalg.norm(cur - np.asarray(r["xy"]), axis=1)
|
| 300 |
+
d = dd.min() - PAD_R
|
| 301 |
+
parts.append(f"the {NAME[o]} is on the table, on no pad "
|
| 302 |
+
f"({100 * d:.0f} cm from the edge of {self.pad_label(int(dd.argmin()), cur)})")
|
| 303 |
+
emp = [self.pad_label(i, cur) for i in self.empty_pads()]
|
| 304 |
+
detail = ("Now " + "; ".join(parts) + "; empty: " + (", ".join(emp) if emp else "none")
|
| 305 |
+
+ " (left/right = the robot's left/right, near/far = toward/away from the robot).")
|
| 306 |
+
new_ev = [e["text"] for e in self.events[self._outcome_cursor:]]
|
| 307 |
+
self._outcome_cursor = len(self.events)
|
| 308 |
+
if new_ev:
|
| 309 |
+
detail = "During this attempt: " + " ".join(new_ev) + " " + detail
|
| 310 |
+
return dict(success=bool(ok), items={NAME[o]: res[o] for o in (X, Y)},
|
| 311 |
+
slip=self.slip, detail=detail)
|
| 312 |
+
|
| 313 |
+
# ------------------------------------------------------------ motion
|
| 314 |
+
def _pick(self, o):
|
| 315 |
+
sk = self.sk
|
| 316 |
+
for _ in range(2):
|
| 317 |
+
p = envs.obj_pos(self.env, o)
|
| 318 |
+
sk.grasp_at(p[:2], envs.TABLE_Z + GRASP_DZ, yaw=_yaw_of(self.env, o), lift=LIFT)
|
| 319 |
+
if sk.holding(o):
|
| 320 |
+
return True
|
| 321 |
+
sk.set_gripper(False, steps=8)
|
| 322 |
+
sk.move_to([p[0], p[1], envs.TABLE_Z + LIFT])
|
| 323 |
+
return False
|
| 324 |
+
|
| 325 |
+
def _move(self, o, pad, log):
|
| 326 |
+
"""Pick item o and put it on pad `pad`. Returns False if the item slipped on the way."""
|
| 327 |
+
n_ev = len(self.events)
|
| 328 |
+
frm = self.on_pad(o)
|
| 329 |
+
ok = self._pick(o)
|
| 330 |
+
rec = dict(obj=NAME[o], from_pad=frm, to_pad=int(pad), grasped=ok)
|
| 331 |
+
log.append(rec)
|
| 332 |
+
if not ok:
|
| 333 |
+
return True
|
| 334 |
+
xy = self.pad_xy()[pad]
|
| 335 |
+
sk = self.sk
|
| 336 |
+
sk.move_to([xy[0], xy[1], envs.TABLE_Z + GRASP_DZ + LIFT]) # carry (the slip may fire here)
|
| 337 |
+
if len(self.events) > n_ev:
|
| 338 |
+
rec["slipped"] = True
|
| 339 |
+
return False
|
| 340 |
+
sk.move_to([xy[0], xy[1], envs.TABLE_Z + GRASP_DZ + 0.004], tol=0.004)
|
| 341 |
+
sk.set_gripper(False, steps=12)
|
| 342 |
+
sk.move_to([xy[0], xy[1], envs.TABLE_Z + GRASP_DZ + 0.10])
|
| 343 |
+
return True
|
| 344 |
+
|
| 345 |
+
def _run(self, moves, log):
|
| 346 |
+
"""moves: list of (item, pad) computed up front (an open-loop plan). Stops at a slip."""
|
| 347 |
+
for o, pad in moves:
|
| 348 |
+
if not self._move(o, pad, log):
|
| 349 |
+
return False
|
| 350 |
+
return True
|
| 351 |
+
|
| 352 |
+
def _swap_now(self, log, rng=None):
|
| 353 |
+
"""The standard swap of the two items' *current* pads via an empty pad (no memory)."""
|
| 354 |
+
a, b = self.on_pad(X), self.on_pad(Y)
|
| 355 |
+
empt = self.empty_pads()
|
| 356 |
+
if a is None or b is None or not empt:
|
| 357 |
+
return
|
| 358 |
+
buf = int(rng.choice(empt)) if rng is not None else self._nearest(empt, self.pad_xy()[a])
|
| 359 |
+
self._run([(X, buf), (Y, a), (X, b)], log)
|
| 360 |
+
|
| 361 |
+
def _tidy_stray(self, log):
|
| 362 |
+
for o in (X, Y):
|
| 363 |
+
if self.on_pad(o) is None and self.empty_pads():
|
| 364 |
+
self._move(o, self._nearest(self.empty_pads(), envs.obj_pos(self.env, o)), log)
|
| 365 |
+
|
| 366 |
+
def _fixup(self, target, log):
|
| 367 |
+
"""Move items until each is on its target pad (target: item -> pad index)."""
|
| 368 |
+
pads = self.pad_xy()
|
| 369 |
+
for _ in range(6):
|
| 370 |
+
todo = [o for o in (Y, X) if np.linalg.norm(envs.obj_pos(self.env, o)[:2] - pads[target[o]]) > SUCC_R]
|
| 371 |
+
if not todo:
|
| 372 |
+
return
|
| 373 |
+
free = [o for o in todo if self.on_pad({X: Y, Y: X}[o], r=PAD_R) != target[o]]
|
| 374 |
+
if free:
|
| 375 |
+
self._move(free[0], target[free[0]], log)
|
| 376 |
+
else: # the two items block each other: park one on an empty pad that is no one's target
|
| 377 |
+
o = todo[0]
|
| 378 |
+
spare = [i for i in self.empty_pads() if i not in target.values()] or self.empty_pads()
|
| 379 |
+
self._move(o, self._nearest(spare, envs.obj_pos(self.env, o)), log)
|
| 380 |
+
|
| 381 |
+
# ------------------------------------------------------------ scripted references (within protocol)
|
| 382 |
+
def _memory(self):
|
| 383 |
+
"""Save: what the agent sees in its first frame -- which pad (by position) each item starts on."""
|
| 384 |
+
return {X: self.pad_xy()[self.on_pad(X)].tolist(), Y: self.pad_xy()[self.on_pad(Y)].tolist()}
|
| 385 |
+
|
| 386 |
+
def saved_memory(self, first):
|
| 387 |
+
"""What the adaptive policy recalls after the slip (identity; patched by the mismatched-memory control)."""
|
| 388 |
+
return first
|
| 389 |
+
|
| 390 |
+
def _attempt1(self, kind, inst, mem, rng, first):
|
| 391 |
+
log = []
|
| 392 |
+
plan = dict(kind=kind, moves=log)
|
| 393 |
+
a = self._nearest(range(N_PADS), first[X]) # the open-loop plan is made from the first frame
|
| 394 |
+
b = self._nearest(range(N_PADS), first[Y])
|
| 395 |
+
empt = [i for i in range(N_PADS) if i not in (a, b)]
|
| 396 |
+
buf = self._nearest(empt, self.pad_xy()[a])
|
| 397 |
+
plan["plan"] = f"X->{buf}, Y->{a}, X->{b}"
|
| 398 |
+
if self._run([(X, buf), (Y, a), (X, b)], log):
|
| 399 |
+
plan["recovery"] = "none (no slip)"
|
| 400 |
+
return plan
|
| 401 |
+
# ---- the carry was interrupted by the slip: recover
|
| 402 |
+
if kind == "oracle": # privileged: true start layout
|
| 403 |
+
plan["recovery"] = "oracle: true layout"
|
| 404 |
+
self._fixup({X: inst["y_pad"], Y: inst["x_pad"]}, log)
|
| 405 |
+
elif kind == "adaptive": # Retrieve the saved first frame and the step log; finish from the right step
|
| 406 |
+
ta = self._nearest(range(N_PADS), mem[X])
|
| 407 |
+
tb = self._nearest(range(N_PADS), mem[Y])
|
| 408 |
+
plan["recovery"] = f"memory: butter -> pad {ta} (cream cheese's start), cream cheese -> pad {tb}"
|
| 409 |
+
self._fixup({X: tb, Y: ta}, log)
|
| 410 |
+
elif kind in ("naive", "blind_continue"): # memoryless continuation from the current frame
|
| 411 |
+
stray = [o for o in (X, Y) if self.on_pad(o) is None]
|
| 412 |
+
parked = [o for o in (X, Y) if self.on_pad(o) is not None]
|
| 413 |
+
plan["recovery"] = "current frame: stray item -> nearest empty pad; parked item -> nearest empty pad"
|
| 414 |
+
for o in stray:
|
| 415 |
+
self._move(o, self._nearest(self.empty_pads(), envs.obj_pos(self.env, o)), log)
|
| 416 |
+
for o in parked:
|
| 417 |
+
if self.empty_pads():
|
| 418 |
+
self._move(o, self._nearest(self.empty_pads(), envs.obj_pos(self.env, o)), log)
|
| 419 |
+
elif kind == "blind": # memoryless restart: tidy up, then the whole swap again
|
| 420 |
+
plan["recovery"] = "restart: stray item -> nearest empty pad, then swap again"
|
| 421 |
+
self._tidy_stray(log)
|
| 422 |
+
self._swap_now(log, rng)
|
| 423 |
+
else:
|
| 424 |
+
raise ValueError(kind)
|
| 425 |
+
return plan
|
| 426 |
+
|
| 427 |
+
def _retry(self, kind, inst, mem, rng):
|
| 428 |
+
log = []
|
| 429 |
+
plan = dict(kind=kind, moves=log)
|
| 430 |
+
if kind == "adaptive":
|
| 431 |
+
ta = self._nearest(range(N_PADS), mem[X])
|
| 432 |
+
tb = self._nearest(range(N_PADS), mem[Y])
|
| 433 |
+
plan["recovery"] = "memory + F2: fix items not on their targets"
|
| 434 |
+
self._fixup({X: tb, Y: ta}, log)
|
| 435 |
+
elif kind in ("blind", "blind_continue"):
|
| 436 |
+
plan["recovery"] = "no history: tidy, then swap the two items again"
|
| 437 |
+
self._tidy_stray(log)
|
| 438 |
+
self._swap_now(log, rng)
|
| 439 |
+
else:
|
| 440 |
+
raise ValueError(kind)
|
| 441 |
+
return plan
|
| 442 |
+
|
| 443 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 444 |
+
k = k or self.max_attempts
|
| 445 |
+
rng = np.random.default_rng(seed)
|
| 446 |
+
self.reset_instance(inst)
|
| 447 |
+
first = self._memory()
|
| 448 |
+
mem = self.saved_memory(first)
|
| 449 |
+
history = []
|
| 450 |
+
for a in range(k):
|
| 451 |
+
plan = self._attempt1(kind, inst, mem, rng, first) if a == 0 else self._retry(kind, inst, mem, rng)
|
| 452 |
+
self.go_home() # "done": the agent declares the attempt finished
|
| 453 |
+
out = self.outcome(inst)
|
| 454 |
+
history.append(dict(attempt=a + 1, params=plan, outcome=out))
|
| 455 |
+
if on_attempt:
|
| 456 |
+
on_attempt(a, plan, out)
|
| 457 |
+
if out["success"] or kind in ("oracle", "naive"):
|
| 458 |
+
break
|
| 459 |
+
return history
|
| 460 |
+
|
| 461 |
+
# cross-protocol hooks are not used by this task
|
| 462 |
+
def default_params(self, inst):
|
| 463 |
+
return dict(policy="naive")
|
| 464 |
+
|
| 465 |
+
def oracle_params(self, inst):
|
| 466 |
+
return dict(policy="oracle")
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l7_key_turn.py
ADDED
|
@@ -0,0 +1,461 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L7 key_turn: unlock a lock whose key turns only one way; which way is hidden.
|
| 2 |
+
|
| 3 |
+
Category: failed_interaction_inference ("why did this contact not do what I expected?").
|
| 4 |
+
|
| 5 |
+
Scene: a grey lock box (9 x 9 x 5 cm) on the table with a brass key standing in the keyhole on its top; the key's
|
| 6 |
+
flat head (3.6 cm wide, 1.6 cm thick, 3 cm tall) sticks up so the gripper can grasp it from above and turn it by
|
| 7 |
+
rotating the wrist. A red bolt sticks out of the box's front face (+x, towards the front camera) while it is locked
|
| 8 |
+
and slides in once the key has been turned to the open position.
|
| 9 |
+
|
| 10 |
+
Hidden variable: the turning direction that opens the lock, clockwise (CW) or counterclockwise (CCW) seen from
|
| 11 |
+
above (alternates with the seed parity, so every block of instances is balanced). The other way the key has 3 deg of
|
| 12 |
+
play and then a hard stop. Both look exactly the same.
|
| 13 |
+
|
| 14 |
+
Turns per attempt: not limited (2026-10-16, user). Until then the instruction allowed one turn per attempt and an
|
| 15 |
+
attempt with more than one turn failed; in every logged run whose first turn went the wrong way the agent turned the
|
| 16 |
+
other way within the same attempt and opened the lock, so the rule only made it repeat that correction in the next
|
| 17 |
+
attempt. The attempt now succeeds once the lock is open, however many turns it took. The trap is logged as an error
|
| 18 |
+
event instead: a turn "hits the stop" when it drives the key onto the stop on the locked side before the lock is open;
|
| 19 |
+
`trap_fired` = some turn did, `n_wrong_way` = how many did, `recovered_in_attempt` = trap fired and the lock was then
|
| 20 |
+
opened in the same attempt. A "turn" is any move_to that starts with the key held and changes the commanded yaw by
|
| 21 |
+
>= 5 deg, or that rotates the key by > 3 deg. A wrong turn costs one command, so this task does not meet design rule
|
| 22 |
+
R3 (the common-sense interaction must have a cost); its signal is clean success (first turn the right way) vs.
|
| 23 |
+
in-attempt recovery, and whether the agent keeps twisting the wrong way.
|
| 24 |
+
|
| 25 |
+
Why the prior fails: the user's example -- many people first try counterclockwise. The scripted prior turns CCW by
|
| 26 |
+
90 deg, so it fails on every CW instance (half of them): the key rotates by its 3 deg of play, then the wrist stalls.
|
| 27 |
+
What must be learned from the failure: "the key would not turn this way at all" (not "my grip slipped") -> turn it
|
| 28 |
+
the other way. One failure is enough.
|
| 29 |
+
|
| 30 |
+
Mechanics notes (measured in the prototype, 2026-10-08):
|
| 31 |
+
* the Panda's finger servo squeezes with kp * (finger opening) N, i.e. only ~4 N on a 7 mm head; the head then
|
| 32 |
+
twisted between the fingers and wedged them open. A 16 mm thick head gives ~8 N and turns reliably.
|
| 33 |
+
* without a stalling wrist the OSC keeps twisting against a blocked key, the fingers wedge open and on release
|
| 34 |
+
they knock the key 15-45 deg the free way (leaking the answer). `KeySkills` therefore stops rotating the wrist
|
| 35 |
+
once the held key sits on a stop and the gripper has twisted 6 deg past it (a torque-limited wrist), and limits
|
| 36 |
+
the wrist to 90 deg/s while turning.
|
| 37 |
+
* the stops use a stiff solref/solimp: with the defaults a hard twist pushed the key 10-15 deg past its stop.
|
| 38 |
+
* commanded yaw is taken literally in this task (nearest representation to the current yaw, clipped to
|
| 39 |
+
+-113 deg). The shared Skills.wrap_yaw maps yaw modulo 180 deg, which is right for grasping but would turn
|
| 40 |
+
"yaw = +95" into -85 deg, i.e. turn the key the wrong way.
|
| 41 |
+
"""
|
| 42 |
+
import numpy as np
|
| 43 |
+
|
| 44 |
+
from .. import envs
|
| 45 |
+
from ..bddl import write_bddl
|
| 46 |
+
from ..objects import _SOLID, _fmt, register_generated
|
| 47 |
+
from ..skills import DT, Skills, _rot_err, _rotz
|
| 48 |
+
from ..task_base import LFFTask, register_task
|
| 49 |
+
|
| 50 |
+
LOCK = "lock_1"
|
| 51 |
+
MODEL = "lff_l7_lock"
|
| 52 |
+
LX, LY, LH = 0.045, 0.045, 0.05 # housing half x, half y, full height
|
| 53 |
+
HEAD = (0.018, 0.008, 0.015) # key head half extents: local x = width, y = thickness, z = height
|
| 54 |
+
HEAD_Z = 0.004 + HEAD[2] # head centre above the housing top
|
| 55 |
+
BOLT = (0.008, 0.012, 0.006) # red bolt (visual only) half extents
|
| 56 |
+
BOLT_OUT = (LX + BOLT[0], 0.0, 0.022)
|
| 57 |
+
BOLT_IN = (LX - BOLT[0] - 0.002, 0.0, 0.022)
|
| 58 |
+
PLAY = np.radians(3.0)
|
| 59 |
+
STOP = np.radians(90.0)
|
| 60 |
+
UNLOCK_AT = np.radians(80.0)
|
| 61 |
+
KEY_FRICTION = 0.04 # N m
|
| 62 |
+
W_MAX = np.radians(90.0) # wrist speed limit while turning (rad/s)
|
| 63 |
+
TWIST_MAX = np.radians(6.0) # wrist stalls when it has twisted this far past a blocked key
|
| 64 |
+
STALL_EXIT = 20 # control steps of stalling before the move gives up
|
| 65 |
+
TURN_YAW = np.radians(5.0)
|
| 66 |
+
TURN_KEY = np.radians(3.0)
|
| 67 |
+
STOP_HIT = PLAY - np.radians(0.5) # key this far the locked way = sitting on the locked-side stop
|
| 68 |
+
Z_GRIP = envs.TABLE_Z + LH + HEAD_Z # grasp-point height for the key head (its centre)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def lock_xml(name, body_rgba=(0.55, 0.57, 0.60, 1.0), key_rgba=(0.80, 0.64, 0.22, 1.0), bolt_rgba=(0.80, 0.12, 0.10, 1.0)):
|
| 72 |
+
g = [f'<geom name="{name}_housing" type="box" pos="0 0 {LH / 2:.4f}" size="{_fmt((LX, LY, LH / 2))}" '
|
| 73 |
+
f'rgba="{_fmt(body_rgba)}" friction="1 0.005 0.0001" {_SOLID} group="0"/>',
|
| 74 |
+
f'<geom type="box" pos="0 0 {LH / 2:.4f}" size="{_fmt((LX, LY, LH / 2))}" rgba="{_fmt(body_rgba)}" '
|
| 75 |
+
f'contype="0" conaffinity="0" group="1"/>',
|
| 76 |
+
f'<geom name="{name}_bolt" type="box" pos="{_fmt(BOLT_OUT)}" size="{_fmt(BOLT)}" rgba="{_fmt(bolt_rgba)}" '
|
| 77 |
+
f'contype="0" conaffinity="0" group="1"/>',
|
| 78 |
+
f'<geom type="cylinder" pos="0 0 {LH + 0.0005:.4f}" size="0.011 0.0005" rgba="0.35 0.36 0.38 1" '
|
| 79 |
+
f'contype="0" conaffinity="0" group="1"/>']
|
| 80 |
+
k = ['<inertial pos="0 0 0.01" mass="0.03" diaginertia="0.00001 0.00001 0.00001"/>',
|
| 81 |
+
# placeholder range: the open direction is set per instance (apply_instance)
|
| 82 |
+
f'<joint name="{name}_key_joint" type="hinge" axis="0 0 1" pos="0 0 0" limited="true" range="-0.05 1.6" '
|
| 83 |
+
f'damping="0.01" frictionloss="{KEY_FRICTION}" armature="0.0002"/>',
|
| 84 |
+
f'<geom name="{name}_head" type="box" pos="0 0 {HEAD_Z:.4f}" size="{_fmt(HEAD)}" rgba="{_fmt(key_rgba)}" '
|
| 85 |
+
f'friction="1 0.005 0.0001" {_SOLID} group="0"/>',
|
| 86 |
+
f'<geom type="box" pos="0 0 {HEAD_Z:.4f}" size="{_fmt(HEAD)}" rgba="{_fmt(key_rgba)}" contype="0" '
|
| 87 |
+
f'conaffinity="0" group="1"/>',
|
| 88 |
+
f'<geom type="cylinder" pos="0 0 0.002" size="0.006 0.002" rgba="{_fmt(key_rgba)}" contype="0" '
|
| 89 |
+
f'conaffinity="0" group="1"/>']
|
| 90 |
+
shell = "\n ".join(g)
|
| 91 |
+
key = "\n ".join(k)
|
| 92 |
+
return f"""<mujoco model="{name}">
|
| 93 |
+
<worldbody>
|
| 94 |
+
<body>
|
| 95 |
+
<body name="object">
|
| 96 |
+
{shell}
|
| 97 |
+
<body name="key" pos="0 0 {LH:.4f}">
|
| 98 |
+
{key}
|
| 99 |
+
</body>
|
| 100 |
+
</body>
|
| 101 |
+
<site rgba="0 0 0 0" size="0.005" pos="0 0 0" name="bottom_site" />
|
| 102 |
+
<site rgba="0 0 0 0" size="0.005" pos="0 0 {LH:.4f}" name="top_site" />
|
| 103 |
+
<site rgba="0 0 0 0" size="0.005" pos="{LX:.4f} {LY:.4f} 0" name="horizontal_radius_site" />
|
| 104 |
+
</body>
|
| 105 |
+
</worldbody>
|
| 106 |
+
</mujoco>"""
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _wrap_pi(a):
|
| 110 |
+
return float((a + np.pi) % (2 * np.pi) - np.pi)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _wrap_half(a):
|
| 114 |
+
"""the gripper is symmetric under a rotation by pi"""
|
| 115 |
+
return float((a + np.pi / 2) % np.pi - np.pi / 2)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _rot_words(deg):
|
| 119 |
+
return f"{abs(deg):.0f} deg {'counterclockwise' if deg > 0 else 'clockwise'}"
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def _lr(v):
|
| 123 |
+
return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}"
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _fb(v):
|
| 127 |
+
return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}"
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def _turn_txt(t, lead):
|
| 131 |
+
"""F2 sentence for one logged turn: what the wrist and the key did, and whether the gripper held the key."""
|
| 132 |
+
dk = t["key_end_deg"] - t["key_start_deg"]
|
| 133 |
+
txt = f"{lead} the wrist rotated {_rot_words(t['wrist_turn_deg'])} (seen from above)"
|
| 134 |
+
if abs(dk) < 1.0:
|
| 135 |
+
txt += " and the key did not rotate at all"
|
| 136 |
+
else:
|
| 137 |
+
txt += f" and the key rotated {_rot_words(dk)}"
|
| 138 |
+
if t["stalled"]:
|
| 139 |
+
txt += ", then it would not turn any further and the wrist stopped there"
|
| 140 |
+
if t["held_at_start"]:
|
| 141 |
+
txt += ("; the gripper lost hold of the key during the turn." if not t["held_at_end"]
|
| 142 |
+
else "; the gripper held the key throughout the turn.")
|
| 143 |
+
else:
|
| 144 |
+
txt += "; the gripper was not holding the key when that move started."
|
| 145 |
+
return txt
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
class KeySkills(Skills):
|
| 149 |
+
"""Skills for the key task: literal yaw, wrist speed limit, stalling wrist, and a log of turns / grasps / unlock."""
|
| 150 |
+
|
| 151 |
+
def __init__(self, env, task, recorder=None):
|
| 152 |
+
super().__init__(env, recorder=recorder)
|
| 153 |
+
self.task = task
|
| 154 |
+
m = env.sim.model
|
| 155 |
+
self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith(("gripper0_", "robot0_"))]
|
| 156 |
+
self.turns = [] # one entry per move_to that counts as a turn
|
| 157 |
+
self.closes = [] # close_gripper events: gripper centre relative to the key head, held afterwards?
|
| 158 |
+
self.stall_steps = 0
|
| 159 |
+
self._grasp_off = None # gripper yaw minus key yaw when the key was grasped
|
| 160 |
+
self.touch_since_report = False
|
| 161 |
+
|
| 162 |
+
# ------------------------------------------------------------ state
|
| 163 |
+
def eef_yaw(self):
|
| 164 |
+
R = self.eef_mat() @ self.R0.T
|
| 165 |
+
return float(np.arctan2(R[1, 0], R[0, 0]))
|
| 166 |
+
|
| 167 |
+
def holding_key(self):
|
| 168 |
+
return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=[self.task.head_geom_name]))
|
| 169 |
+
|
| 170 |
+
def _touching_key(self):
|
| 171 |
+
d = self.env.sim.data
|
| 172 |
+
g, kg = set(self._grip_geoms), self.task.head_gid
|
| 173 |
+
for i in range(d.ncon):
|
| 174 |
+
c = d.contact[i]
|
| 175 |
+
if (c.geom1 in g and c.geom2 == kg) or (c.geom2 in g and c.geom1 == kg):
|
| 176 |
+
return True
|
| 177 |
+
return False
|
| 178 |
+
|
| 179 |
+
def wrap_yaw(self, yaw):
|
| 180 |
+
"""Literal yaw: the representation of `yaw` closest to the current wrist yaw, clipped to the wrist range."""
|
| 181 |
+
cur = self.eef_yaw()
|
| 182 |
+
y = cur + _wrap_pi(float(yaw) - cur)
|
| 183 |
+
return float(np.clip(y, -self.YAW_LIMIT, self.YAW_LIMIT))
|
| 184 |
+
|
| 185 |
+
# ------------------------------------------------------------ low level
|
| 186 |
+
def _act(self, dpos, drot, grip):
|
| 187 |
+
t = self.task
|
| 188 |
+
if self.grip > 0 and self._grasp_off is not None:
|
| 189 |
+
q = t.key_q()
|
| 190 |
+
lo, hi = t.key_range()
|
| 191 |
+
twist = _wrap_half(self.eef_yaw() - t.key_world_yaw() - self._grasp_off)
|
| 192 |
+
at_hi, at_lo = q >= hi - np.radians(1.5), q <= lo + np.radians(1.5)
|
| 193 |
+
if (at_hi and twist > TWIST_MAX and drot[2] > 0) or (at_lo and twist < -TWIST_MAX and drot[2] < 0):
|
| 194 |
+
drot = np.array(drot, float).copy()
|
| 195 |
+
drot[2] = -np.sign(twist) * 0.02 # force-limited wrist: back off instead of twisting further
|
| 196 |
+
self.stall_steps += 1
|
| 197 |
+
super()._act(dpos, drot, grip)
|
| 198 |
+
t.check_unlock()
|
| 199 |
+
if self._touching_key():
|
| 200 |
+
self.touch_since_report = True
|
| 201 |
+
|
| 202 |
+
def move_to(self, target, yaw=None, speed=None, tol=0.004, max_steps=250, apply_bias=True, wrap_yaw=True):
|
| 203 |
+
"""Skills.move_to with the wrist reference rotating at <= W_MAX and an early stop when the wrist stalls.
|
| 204 |
+
Logs the move as a turn when it starts with the key held and rotates the wrist, or when it rotates the key;
|
| 205 |
+
`hit_stop`: the turn went the locked way (wrist command if the key was held, else the key's motion) and the key
|
| 206 |
+
was on the locked-side stop during it, while the lock was still locked (the trap)."""
|
| 207 |
+
t = self.task
|
| 208 |
+
tgt = np.asarray(target, float) + (self.bias if apply_bias else 0.0)
|
| 209 |
+
if yaw is not None:
|
| 210 |
+
self.yaw = self.wrap_yaw(float(yaw)) if wrap_yaw else float(yaw)
|
| 211 |
+
yaw0 = self.eef_yaw()
|
| 212 |
+
dyaw = self.yaw - yaw0
|
| 213 |
+
R_goal = self._R()
|
| 214 |
+
p0 = self.eef_pos()
|
| 215 |
+
q0, held0, locked0 = t.key_q(), self.holding_key(), not t.unlocked
|
| 216 |
+
q_open_min = t.open_sign() * q0 # lowest key angle the open way during the move
|
| 217 |
+
dist = np.linalg.norm(tgt - p0)
|
| 218 |
+
direction = (tgt - p0) / max(dist, 1e-9)
|
| 219 |
+
s = 0.0
|
| 220 |
+
self.stall_steps = 0
|
| 221 |
+
for k in range(max_steps):
|
| 222 |
+
if speed is not None:
|
| 223 |
+
s = min(dist, s + speed * DT)
|
| 224 |
+
ref = p0 + direction * s + direction * min(dist - s, speed * DT * 1.5)
|
| 225 |
+
else:
|
| 226 |
+
ref = tgt
|
| 227 |
+
frac = min(1.0, (k + 1) * DT * W_MAX / max(abs(dyaw), 1e-6))
|
| 228 |
+
R = _rotz(yaw0 + frac * dyaw) @ self.R0
|
| 229 |
+
self._act(ref - self.eef_pos(), _rot_err(R, self.eef_mat()), self.grip)
|
| 230 |
+
q_open_min = min(q_open_min, t.open_sign() * t.key_q())
|
| 231 |
+
if self.stall_steps >= STALL_EXIT:
|
| 232 |
+
break
|
| 233 |
+
if (np.linalg.norm(tgt - self.eef_pos()) < tol and (speed is None or s >= dist) and frac >= 1.0
|
| 234 |
+
and np.linalg.norm(_rot_err(R_goal, self.eef_mat())) < 0.03):
|
| 235 |
+
break
|
| 236 |
+
stalled = self.stall_steps >= STALL_EXIT
|
| 237 |
+
if stalled:
|
| 238 |
+
# give up the unreached wrist angle; otherwise every later hold (e.g. while the gripper opens) keeps
|
| 239 |
+
# driving the wrist towards it and the arm swings away (seen in the agent self-test, 2026-10-08)
|
| 240 |
+
self.yaw = self.eef_yaw()
|
| 241 |
+
rep = dict(prim="move_to", reached=bool(np.linalg.norm(tgt - self.eef_pos()) < 0.02),
|
| 242 |
+
pos=self.eef_pos().round(4).tolist(), steps=k + 1, stalled=bool(stalled))
|
| 243 |
+
self.log.append(rep)
|
| 244 |
+
dq = t.key_q() - q0
|
| 245 |
+
locked_way = t.open_sign() * (dyaw if held0 else dq) < 0
|
| 246 |
+
if (held0 and abs(dyaw) >= TURN_YAW) or abs(dq) > TURN_KEY:
|
| 247 |
+
self.turns.append(dict(step=self.n_steps, held_at_start=bool(held0), held_at_end=self.holding_key(),
|
| 248 |
+
key_start_deg=round(float(np.degrees(q0)), 1),
|
| 249 |
+
key_end_deg=round(float(np.degrees(t.key_q())), 1),
|
| 250 |
+
wrist_cmd_deg=round(float(np.degrees(dyaw)), 1),
|
| 251 |
+
wrist_turn_deg=round(float(np.degrees(self.eef_yaw() - yaw0)), 1),
|
| 252 |
+
stalled=bool(stalled),
|
| 253 |
+
hit_stop=bool(locked0 and locked_way and q_open_min <= -STOP_HIT)))
|
| 254 |
+
return rep
|
| 255 |
+
|
| 256 |
+
def set_gripper(self, close, steps=15):
|
| 257 |
+
was_open = self.grip < 0
|
| 258 |
+
rep = super().set_gripper(close, steps)
|
| 259 |
+
if close:
|
| 260 |
+
if self.holding_key():
|
| 261 |
+
self._grasp_off = _wrap_half(self.eef_yaw() - self.task.key_world_yaw())
|
| 262 |
+
if was_open:
|
| 263 |
+
off = self.eef_pos() - self.task.head_xyz()
|
| 264 |
+
self.closes.append(dict(step=self.n_steps, offset=off.round(4).tolist(), held=self.holding_key(),
|
| 265 |
+
width=round(self.gripper_width(), 4)))
|
| 266 |
+
else:
|
| 267 |
+
self._grasp_off = None
|
| 268 |
+
return rep
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
@register_task
|
| 272 |
+
class KeyTurn(LFFTask):
|
| 273 |
+
name = "l7_key_turn"
|
| 274 |
+
level = "L7"
|
| 275 |
+
category = "failed_interaction_inference"
|
| 276 |
+
capabilities = ("Perceive", "Reason", "Plan")
|
| 277 |
+
protocol = "cross"
|
| 278 |
+
instruction = ("Unlock the lock on the grey box: grasp the flat head of the brass key from above and turn the key "
|
| 279 |
+
"a quarter turn (90 degrees). The red bolt on the box slides in when it is unlocked.")
|
| 280 |
+
instruction_indirect = ("Open the lock of the small grey metal box: take hold of the flat gold-coloured tab that "
|
| 281 |
+
"sticks up out of its top and rotate it a quarter turn (90 degrees). The red block on the "
|
| 282 |
+
"box slides in when it is open.")
|
| 283 |
+
|
| 284 |
+
# ------------------------------------------------------------ scene
|
| 285 |
+
def make_bddl(self):
|
| 286 |
+
lock = register_generated("LffKeyLock", lock_xml(MODEL), free=False)
|
| 287 |
+
return write_bddl(self.name, "unlock the lock", [],
|
| 288 |
+
fixtures=[(LOCK, lock, "lock_region", (-0.11, -0.01, -0.09, 0.01))])
|
| 289 |
+
|
| 290 |
+
def __init__(self, cam_res=None):
|
| 291 |
+
super().__init__(cam_res)
|
| 292 |
+
m = self.env.sim.model
|
| 293 |
+
pre = f"{LOCK}_{MODEL}"
|
| 294 |
+
self.jid = m.joint_name2id(pre + "_key_joint")
|
| 295 |
+
self.qa = m.jnt_qposadr[self.jid]
|
| 296 |
+
self.dof = m.jnt_dofadr[self.jid]
|
| 297 |
+
self.lock_bid = m.body_name2id(self.env.fixtures_dict[LOCK].root_body)
|
| 298 |
+
self.head_geom_name = pre + "_head"
|
| 299 |
+
self.head_gid = m.geom_name2id(self.head_geom_name)
|
| 300 |
+
self.bolt_gid = m.geom_name2id(pre + "_bolt")
|
| 301 |
+
self.inst = None
|
| 302 |
+
self.unlocked = False
|
| 303 |
+
|
| 304 |
+
# agent-facing hooks -------------------------------------------------------
|
| 305 |
+
def on_agent_tool(self, inst, name, args, report):
|
| 306 |
+
"""The lock is a fixture, so the harness's `holding_object` / `touched_object` (movable objects only) never see
|
| 307 |
+
the key; add an explicit `holding_key` field and count key contacts as touches."""
|
| 308 |
+
if self.sk is None or not isinstance(report, dict):
|
| 309 |
+
return
|
| 310 |
+
touched = self.sk.touch_since_report
|
| 311 |
+
self.sk.touch_since_report = False
|
| 312 |
+
if report.get("ok") and name in ("move_to", "open_gripper", "close_gripper", "push"):
|
| 313 |
+
report["holding_key"] = self.sk.holding_key()
|
| 314 |
+
if touched and "touched_object" in report:
|
| 315 |
+
report["touched_object"] = True
|
| 316 |
+
|
| 317 |
+
# ------------------------------------------------------------ state helpers
|
| 318 |
+
def key_q(self):
|
| 319 |
+
return float(self.env.sim.data.qpos[self.qa])
|
| 320 |
+
|
| 321 |
+
def key_range(self):
|
| 322 |
+
return self.env.sim.model.jnt_range[self.jid]
|
| 323 |
+
|
| 324 |
+
def key_world_yaw(self):
|
| 325 |
+
return float(self.inst["lock_yaw"]) + self.key_q()
|
| 326 |
+
|
| 327 |
+
def head_xyz(self):
|
| 328 |
+
return self.env.sim.data.geom_xpos[self.head_gid].copy()
|
| 329 |
+
|
| 330 |
+
def open_sign(self):
|
| 331 |
+
return 1.0 if self.inst["direction"] == "CCW" else -1.0
|
| 332 |
+
|
| 333 |
+
def check_unlock(self):
|
| 334 |
+
"""latch: the bolt is thrown back once the key reaches the open position (and stays back)"""
|
| 335 |
+
if not self.unlocked and self.open_sign() * self.key_q() >= UNLOCK_AT:
|
| 336 |
+
self.unlocked = True
|
| 337 |
+
self.env.sim.model.geom_pos[self.bolt_gid] = BOLT_IN
|
| 338 |
+
|
| 339 |
+
def sample_instance(self, seed):
|
| 340 |
+
rng = np.random.default_rng(seed)
|
| 341 |
+
return dict(seed=int(seed), direction="CCW" if seed % 2 == 0 else "CW",
|
| 342 |
+
lock_xy=[float(rng.uniform(-0.15, -0.02)), float(rng.uniform(-0.15, 0.15))],
|
| 343 |
+
lock_yaw=float(rng.uniform(-np.radians(15), np.radians(15))))
|
| 344 |
+
|
| 345 |
+
def apply_instance(self, inst):
|
| 346 |
+
self.inst = inst
|
| 347 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 348 |
+
cx, cy = inst["lock_xy"]
|
| 349 |
+
a = inst["lock_yaw"]
|
| 350 |
+
m.body_pos[self.lock_bid] = [cx, cy, envs.TABLE_Z]
|
| 351 |
+
m.body_quat[self.lock_bid] = [np.cos(a / 2), 0.0, 0.0, np.sin(a / 2)]
|
| 352 |
+
m.jnt_range[self.jid] = [-PLAY, STOP] if inst["direction"] == "CCW" else [-STOP, PLAY]
|
| 353 |
+
m.jnt_solref[self.jid] = [0.004, 1.0]
|
| 354 |
+
m.jnt_solimp[self.jid] = [0.99, 0.999, 0.001, 0.5, 2.0]
|
| 355 |
+
m.dof_frictionloss[self.dof] = KEY_FRICTION
|
| 356 |
+
m.geom_pos[self.bolt_gid] = BOLT_OUT
|
| 357 |
+
d.qpos[self.qa] = 0.0
|
| 358 |
+
d.qvel[self.dof] = 0.0
|
| 359 |
+
self.unlocked = False
|
| 360 |
+
|
| 361 |
+
def reset_instance(self, inst, recorder=None):
|
| 362 |
+
self.env.reset()
|
| 363 |
+
self.apply_instance(inst)
|
| 364 |
+
self.env.sim.forward()
|
| 365 |
+
envs.settle(self.env, 10)
|
| 366 |
+
self.sk = KeySkills(self.env, self, recorder=recorder)
|
| 367 |
+
return self.sk
|
| 368 |
+
|
| 369 |
+
# ------------------------------------------------------------ outcome
|
| 370 |
+
def outcome(self, inst):
|
| 371 |
+
envs.settle(self.env, 20)
|
| 372 |
+
sk = self.sk
|
| 373 |
+
n_turns = len(sk.turns)
|
| 374 |
+
n_wrong = sum(t["hit_stop"] for t in sk.turns)
|
| 375 |
+
success = bool(self.unlocked)
|
| 376 |
+
open_deg = float(np.degrees(self.open_sign() * self.key_q()))
|
| 377 |
+
out = dict(success=success, unlocked=bool(self.unlocked), n_turns=n_turns, n_wrong_way=n_wrong,
|
| 378 |
+
trap_fired=n_wrong > 0, recovered_in_attempt=bool(n_wrong and success),
|
| 379 |
+
key_deg=round(np.degrees(self.key_q()), 1), open_deg=round(open_deg, 1), turns=sk.turns,
|
| 380 |
+
closes=sk.closes, first_turn=sk.turns[0] if sk.turns else None)
|
| 381 |
+
parts = []
|
| 382 |
+
grasp_txt = ""
|
| 383 |
+
if sk.closes:
|
| 384 |
+
c = sk.closes[0]
|
| 385 |
+
o = c["offset"]
|
| 386 |
+
top = envs.TABLE_Z + LH + HEAD_Z + HEAD[2]
|
| 387 |
+
below = top - (o[2] + self.head_xyz()[2])
|
| 388 |
+
grasp_txt = (f"When the gripper first closed, its centre was {_fb(o[0])} and {_lr(o[1])} of the centre of "
|
| 389 |
+
f"the key's head and {100 * below:.1f} cm below the top of the head; it "
|
| 390 |
+
+ ("was holding the key." if c["held"] else "did not get hold of the key."))
|
| 391 |
+
if success:
|
| 392 |
+
out["failure"] = None
|
| 393 |
+
parts.append("The lock is unlocked.")
|
| 394 |
+
elif n_turns == 0:
|
| 395 |
+
out["failure"] = "no_turn"
|
| 396 |
+
parts.append("The lock is still locked: the key was never turned.")
|
| 397 |
+
else:
|
| 398 |
+
out["failure"] = "still_locked"
|
| 399 |
+
parts.append("The lock is still locked.")
|
| 400 |
+
if n_turns == 1:
|
| 401 |
+
parts.append(_turn_txt(sk.turns[0], "During your turn"))
|
| 402 |
+
else:
|
| 403 |
+
parts.append(f"The key was turned (or pushed round) in {n_turns} separate moves.")
|
| 404 |
+
parts.append(_turn_txt(sk.turns[0], "During the first one"))
|
| 405 |
+
parts.append(_turn_txt(sk.turns[-1], "During the last one"))
|
| 406 |
+
if grasp_txt and not success:
|
| 407 |
+
parts.append(grasp_txt)
|
| 408 |
+
out["detail"] = " ".join(parts)
|
| 409 |
+
return out
|
| 410 |
+
|
| 411 |
+
# ------------------------------------------------------------ scripted execution (cross protocol)
|
| 412 |
+
def execute(self, inst, params):
|
| 413 |
+
"""Grasp the key head from above across its thickness (+ jitter), one wrist turn of `turn` degrees
|
| 414 |
+
(+ = counterclockwise seen from above), release, lift."""
|
| 415 |
+
sk = self.sk
|
| 416 |
+
p = self.head_xyz() + np.r_[params.get("dxy", (0.0, 0.0)), params.get("dz", 0.0)] # perfect perception
|
| 417 |
+
yaw0 = self.key_world_yaw() + np.radians(params.get("dyaw", 0.0))
|
| 418 |
+
sk.set_gripper(False, steps=8)
|
| 419 |
+
sk.move_to([p[0], p[1], p[2] + 0.08], yaw=yaw0)
|
| 420 |
+
sk.move_to([p[0], p[1], p[2]], tol=0.003)
|
| 421 |
+
sk.set_gripper(True, steps=15)
|
| 422 |
+
sk.move_to([p[0], p[1], p[2]], yaw=sk.eef_yaw() + np.radians(float(params["turn"])), max_steps=200)
|
| 423 |
+
sk.set_gripper(False, steps=8)
|
| 424 |
+
e = sk.eef_pos()
|
| 425 |
+
sk.move_to([e[0], e[1], e[2] + 0.08])
|
| 426 |
+
|
| 427 |
+
def default_params(self, inst):
|
| 428 |
+
"""the prior from the user's example: try counterclockwise first"""
|
| 429 |
+
return dict(turn=90.0)
|
| 430 |
+
|
| 431 |
+
def oracle_params(self, inst):
|
| 432 |
+
return dict(turn=90.0 * (1 if inst["direction"] == "CCW" else -1))
|
| 433 |
+
|
| 434 |
+
def adapt_params(self, inst, history):
|
| 435 |
+
"""Scripted F2 learner. A turn after which the key rotated less than 10 deg the commanded way (it stopped)
|
| 436 |
+
-> that way is blocked -> turn the other way. A turn that rotated the key further but not far enough -> same
|
| 437 |
+
way, a bit more. Anything else (no turn, lost grip) -> repeat the last direction."""
|
| 438 |
+
blocked = set()
|
| 439 |
+
good = 0
|
| 440 |
+
for h in history:
|
| 441 |
+
t = h["outcome"].get("first_turn")
|
| 442 |
+
if t is None:
|
| 443 |
+
continue
|
| 444 |
+
sgn = int(np.sign(h["params"]["turn"]))
|
| 445 |
+
dk = t["key_end_deg"] - t["key_start_deg"]
|
| 446 |
+
if t["held_at_start"] and sgn * dk < 10.0:
|
| 447 |
+
blocked.add(sgn)
|
| 448 |
+
elif sgn * dk >= 10.0:
|
| 449 |
+
good = sgn
|
| 450 |
+
if good:
|
| 451 |
+
return dict(turn=100.0 * good)
|
| 452 |
+
last = int(np.sign(history[-1]["params"]["turn"]))
|
| 453 |
+
sgn = -last if last in blocked else last
|
| 454 |
+
if sgn in blocked:
|
| 455 |
+
sgn = -sgn
|
| 456 |
+
return dict(turn=90.0 * sgn)
|
| 457 |
+
|
| 458 |
+
def blind_params(self, inst, attempt, rng):
|
| 459 |
+
"""Same plan (counterclockwise quarter turn) with small random variation; no history."""
|
| 460 |
+
return dict(turn=float(np.clip(rng.normal(90.0, 8.0), 70.0, 105.0)), dxy=rng.normal(0.0, 0.002, 2).tolist(),
|
| 461 |
+
dyaw=float(rng.normal(0.0, 4.0)))
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/lh_order_dispatch.py
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Development composite: physically load two products and a card, then steer a weighted shipping tray.
|
| 2 |
+
L1 fixed calibration bias, L3 card edge strategy, L5 off-centre loaded push. Not in the main set.
|
| 3 |
+
"""
|
| 4 |
+
import numpy as np
|
| 5 |
+
import copy
|
| 6 |
+
import xml.etree.ElementTree as ET
|
| 7 |
+
from .. import envs
|
| 8 |
+
from ..bddl import write_bddl
|
| 9 |
+
from ..objects import box_xml, register_generated
|
| 10 |
+
from ..task_base import LFFTask, register_task
|
| 11 |
+
from .l3_card_edge import CardEdge, card_xml, BOARD_HALF, BOARD_TOP, CARD_HALF, GRASP_OUT
|
| 12 |
+
from .l7_offcenter_push import (OffcenterPush, PushSkills, long_box_xml, rect_frame_xml, HALF,
|
| 13 |
+
MASS, MU, box_fit, box_corners, _yaw, _rot)
|
| 14 |
+
|
| 15 |
+
PRODUCTS = ('product_red_1', 'product_blue_1')
|
| 16 |
+
CARGO = PRODUCTS + ('card_1',)
|
| 17 |
+
PH = .014
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def shipping_xml():
|
| 21 |
+
xml = long_box_xml('lff_dispatch_box')
|
| 22 |
+
parts=[]
|
| 23 |
+
for k,(p,h) in enumerate([((.042,0,.025),(.003,.11,.005)),((-.042,0,.025),(.003,.11,.005)),
|
| 24 |
+
((0,.107,.032),(.039,.003,.012)),((0,-.107,.032),(.039,.003,.012))]):
|
| 25 |
+
parts.append(f'<geom name="dispatch_wall{k}" type="box" pos="{p[0]} {p[1]} {p[2]}" size="{h[0]} {h[1]} {h[2]}" group="0" mass=".001" friction=".5 .005 .0001" rgba=".6 .4 .2 1"/>')
|
| 26 |
+
return xml.replace(' </body>', '\n'.join(parts)+'\n </body>',1)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class DispatchSkills(PushSkills):
|
| 30 |
+
def __init__(self, env, task, bias, recorder=None):
|
| 31 |
+
super().__init__(env,bias=bias,recorder=recorder,target=task.target_xy(task.inst))
|
| 32 |
+
self.task=task
|
| 33 |
+
self.closes=[]
|
| 34 |
+
self.correction=np.zeros(3)
|
| 35 |
+
self.n_commands=0
|
| 36 |
+
def reported_eef_pos(self):
|
| 37 |
+
return self.eef_pos()-self.bias
|
| 38 |
+
def move_to(self,target,*args,**kwargs):
|
| 39 |
+
self.n_commands+=1
|
| 40 |
+
if self.n_commands>self.task.agent_max_steps:raise RuntimeError("dispatch command budget exceeded")
|
| 41 |
+
rep=super().move_to(np.asarray(target)-self.correction,*args,**kwargs)
|
| 42 |
+
rep['pos']=np.round(self.reported_eef_pos(),4).tolist()
|
| 43 |
+
return rep
|
| 44 |
+
def _act(self,dpos,drot,grip):
|
| 45 |
+
super()._act(dpos,drot,grip)
|
| 46 |
+
self.task.monitor_step()
|
| 47 |
+
if self.n_steps*.05>=3*self.task.agent_max_steps:raise RuntimeError('dispatch simulation budget exceeded')
|
| 48 |
+
def set_gripper(self,close,steps=15):
|
| 49 |
+
self.n_commands+=1
|
| 50 |
+
if self.n_commands>self.task.agent_max_steps:raise RuntimeError("dispatch command budget exceeded")
|
| 51 |
+
ctx=self.task.close_context() if close and self.grip<0 else None
|
| 52 |
+
rep=super().set_gripper(close,steps)
|
| 53 |
+
if ctx is not None:
|
| 54 |
+
ctx.update(held=self.holding('card_1'),width=round(self.gripper_width(),4))
|
| 55 |
+
self.closes.append(ctx)
|
| 56 |
+
return rep
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@register_task
|
| 60 |
+
class OrderDispatch(CardEdge,OffcenterPush):
|
| 61 |
+
name='lh_order_dispatch'
|
| 62 |
+
level='L1'
|
| 63 |
+
failure_causes=('L1','L3','L5')
|
| 64 |
+
failure_types=failure_causes
|
| 65 |
+
category='system_identification'
|
| 66 |
+
capabilities=('Perceive','Reason','Plan','Restore')
|
| 67 |
+
protocol='cross'
|
| 68 |
+
max_attempts=5
|
| 69 |
+
agent_max_steps=180
|
| 70 |
+
instruction=('Load both small products and the red order card into the brown shipping tray, while it is in '
|
| 71 |
+
'the yellow loading rectangle. Then push the loaded tray with the closed gripper completely inside the green '
|
| 72 |
+
'delivery rectangle. All three items must remain inside the tray, with the gripper open and clear.')
|
| 73 |
+
instruction_indirect=('Pack the two small coloured cubes and the thin red rectangle into the long brown '
|
| 74 |
+
'container while the container is at its starting position, then push the loaded container with the closed '
|
| 75 |
+
'gripper completely into the green marked area. Keep every item inside, and finish with the '
|
| 76 |
+
'gripper open and clear.')
|
| 77 |
+
def make_bddl(self):
|
| 78 |
+
card=register_generated('LffDispatchCard',card_xml('lff_dispatch_card'))
|
| 79 |
+
board=register_generated('LffDispatchBoard',box_xml('lff_dispatch_board',BOARD_HALF,(.62,.45,.27,1),friction=(.3,.005,.0001)),free=False)
|
| 80 |
+
box=register_generated('LffDispatchBox',shipping_xml())
|
| 81 |
+
zone_xml=ET.fromstring(rect_frame_xml('lff_dispatch_zone'))
|
| 82 |
+
load_xml=ET.fromstring(rect_frame_xml('lff_dispatch_loading',inner_half=(.10,.15),line_rgba=(.8,.6,.05,1),fill_rgba=(.95,.88,.55,1)))
|
| 83 |
+
body=zone_xml.find('worldbody/body/body')
|
| 84 |
+
for geom in load_xml.find('worldbody/body/body'):
|
| 85 |
+
q=np.fromstring(geom.get('pos','0 0 0'),sep=' ');q[0]-=.11;geom.set('pos',' '.join(map(str,q)));body.append(geom)
|
| 86 |
+
zone=register_generated('LffDispatchZone',ET.tostring(zone_xml,encoding='unicode'),free=False)
|
| 87 |
+
objs=[('card_1',card,'card_region',(-.305,.395,-.295,.405)),('box_1',box,'box_region',(-.255,-.005,-.245,.005))]
|
| 88 |
+
for k,o in enumerate(PRODUCTS):
|
| 89 |
+
cat=register_generated('LffDispatchProduct'+('Red' if k==0 else 'Blue'),box_xml('lff_dispatch_product_'+str(k),(PH,PH,PH),((.9,.1,.1,1) if k==0 else (.1,.2,.9,1)),density=500))
|
| 90 |
+
objs.append((o,cat,'prod_region'+str(k),(-.305+.25*k,-.405,-.295+.25*k,-.395)))
|
| 91 |
+
return write_bddl(self.name,self.instruction,objs,[('board_1',board,'board_region',(.295,.345,.305,.355)),('zone_1',zone,'zone_region',(.295,-.355,.305,-.345))])
|
| 92 |
+
def __init__(self,cam_res=None):
|
| 93 |
+
LFFTask.__init__(self,cam_res)
|
| 94 |
+
self.board_bid=self.env.sim.model.body_name2id(self.env.fixtures_dict['board_1'].root_body)
|
| 95 |
+
self.inst=None;self.mon=None
|
| 96 |
+
def sample_instance(self,seed):
|
| 97 |
+
rng=np.random.default_rng(seed)
|
| 98 |
+
bx=-.18;by=.20
|
| 99 |
+
return dict(seed=int(seed),board_xy=[bx,by],card_xy=[bx,by],card_yaw=0.,card_along='x',
|
| 100 |
+
bin_xy=[-.21,-.08],box_xy=[-.21,-.08],target_dist=.11,
|
| 101 |
+
bias=[0.,float(rng.choice([-1,1])*.055),0.],com_offset=float(rng.choice([-1,1])*.06),
|
| 102 |
+
mechanisms={'L1':True,'L3':True,'L5':True})
|
| 103 |
+
def apply_instance(self,inst):
|
| 104 |
+
self.inst=inst
|
| 105 |
+
OffcenterPush.apply_instance(self,inst)
|
| 106 |
+
m=self.env.sim.model
|
| 107 |
+
m.body_pos[self.board_bid]=[*inst['board_xy'],envs.TABLE_Z+BOARD_HALF[2]]
|
| 108 |
+
m.body_quat[self.board_bid]=[1,0,0,0]
|
| 109 |
+
envs.set_obj_pose(self.env,'card_1',[*inst['card_xy'],BOARD_TOP+CARD_HALF[2]+.0003],yaw=inst['card_yaw'])
|
| 110 |
+
for k,o in enumerate(PRODUCTS):
|
| 111 |
+
envs.set_obj_pose(self.env,o,[-.25+.14*k,-.31,envs.TABLE_Z+PH+.001])
|
| 112 |
+
bid=envs.body_id(self.env,'box_1')
|
| 113 |
+
if not inst['mechanisms']['L5']:m.body_ipos[bid]=[0,0,0];envs.refit_bounds(self.env,bid)
|
| 114 |
+
if not inst['mechanisms']['L3']:
|
| 115 |
+
# Initial overhang removes the flat-card obstruction; reset-time placement only.
|
| 116 |
+
envs.set_obj_pose(self.env,'card_1',[inst['board_xy'][0]-BOARD_HALF[0]+CARD_HALF[0]-.03,inst['board_xy'][1],BOARD_TOP+CARD_HALF[2]+.0003])
|
| 117 |
+
def reset_instance(self,inst,recorder=None):
|
| 118 |
+
self.mon=None;self.env.reset();self.apply_instance(inst);self.env.sim.forward();envs.settle(self.env,15)
|
| 119 |
+
self.sk=DispatchSkills(self.env,self,np.array(inst['bias']) if inst['mechanisms']['L1'] else np.zeros(3),recorder)
|
| 120 |
+
self.mon=dict(start_xy=self.card_pose()['xy'].copy(),max_lift=0.,max_overhang=0.,fell=False,
|
| 121 |
+
loaded=False,load_step=None,departed_unloaded=False,events=[],states={o:False for o in CARGO},l1_attempts=[])
|
| 122 |
+
self.sim0=0;self.ncmd=0;self.budget=None
|
| 123 |
+
return self.sk
|
| 124 |
+
def in_cargo(self,o,require_support=True):
|
| 125 |
+
p=envs.obj_pos(self.env,o);b=envs.obj_pos(self.env,'box_1');R=_rot(_yaw(envs.obj_quat(self.env,'box_1')))
|
| 126 |
+
rel=R.T@(p[:2]-b[:2]);half=PH if o in PRODUCTS else 0.
|
| 127 |
+
# Full footprint containment, including card corners.
|
| 128 |
+
if o=='card_1':
|
| 129 |
+
rels=(self.card_corners()[:,:2]-b[:2])@R
|
| 130 |
+
footprint=bool(np.all(np.abs(rels[:,0])<.039) and np.all(np.abs(rels[:,1])<.104))
|
| 131 |
+
else:
|
| 132 |
+
rot=self.env.sim.data.body_xmat[envs.body_id(self.env,o)].reshape(3,3)
|
| 133 |
+
corners=np.array([p+rot@np.array([a*PH,b*PH,c*PH]) for a in (-1,1) for b in (-1,1) for c in (-1,1)])
|
| 134 |
+
rels=(corners[:,:2]-b[:2])@R
|
| 135 |
+
footprint=bool(np.all(np.abs(rels[:,0])<.039) and np.all(np.abs(rels[:,1])<.104))
|
| 136 |
+
support=any(envs.contacts_between(self.env,envs.obj_geom_ids(self.env,o),envs.obj_geom_ids(self.env,q)) for q in CARGO+('box_1',) if q!=o)
|
| 137 |
+
return bool(footprint and (support or not require_support) and b[2]+.015<p[2]<b[2]+.065 and not self.sk.holding(o))
|
| 138 |
+
def in_bin(self):return self.in_cargo('card_1')
|
| 139 |
+
def monitor_step(self):
|
| 140 |
+
if self.mon is None:return
|
| 141 |
+
CardEdge.monitor_step(self)
|
| 142 |
+
if self.sk.n_steps%5:return
|
| 143 |
+
states={o:self.in_cargo(o) for o in CARGO}
|
| 144 |
+
for o,v in states.items():
|
| 145 |
+
if v!=self.mon['states'][o]:self.mon['events'].append(dict(step=self.sk.n_steps,item=o,event='achieved' if v else 'lost'))
|
| 146 |
+
self.mon['states']=states
|
| 147 |
+
box=envs.obj_pos(self.env,'box_1');yaw=_yaw(envs.obj_quat(self.env,'box_1'))
|
| 148 |
+
footprint=box_corners(box[:2],yaw)-np.asarray(self.inst['box_xy'])
|
| 149 |
+
at_start=bool(np.all(np.abs(footprint[:,0])<.10) and np.all(np.abs(footprint[:,1])<.15))
|
| 150 |
+
if self.mon['loaded'] and at_start and not all(self.in_cargo(o,require_support=False) for o in CARGO):
|
| 151 |
+
self.mon['loaded']=False
|
| 152 |
+
self.mon['load_step']=None
|
| 153 |
+
if all(states.values()) and at_start:
|
| 154 |
+
if self.mon['load_step'] is None:self.mon['load_step']=self.sk.n_steps
|
| 155 |
+
self.mon['loaded']=True
|
| 156 |
+
if not at_start and not self.mon['loaded']:self.mon['departed_unloaded']=True
|
| 157 |
+
def grasp_and_bin(self,xy,yaw,z_site,lift=.12):
|
| 158 |
+
sk=self.sk;sk.set_gripper(False,8)
|
| 159 |
+
sk.move_to([*xy,z_site+.08],yaw=yaw);sk.move_to([*xy,z_site],tol=.003,max_steps=120)
|
| 160 |
+
sk.set_gripper(True,15);sk.move_to([*xy,z_site+lift],speed=.2)
|
| 161 |
+
if not sk.holding('card_1'):sk.set_gripper(False,8);return False
|
| 162 |
+
b=envs.obj_pos(self.env,'box_1');sk.move_to([b[0],b[1],envs.TABLE_Z+.23],yaw=np.pi/2)
|
| 163 |
+
sk.hold(5)
|
| 164 |
+
offset=envs.obj_pos(self.env,'card_1')[:2]-sk.eef_pos()[:2]
|
| 165 |
+
goal=b[:2]-offset
|
| 166 |
+
sk.move_to([*goal,envs.TABLE_Z+.20])
|
| 167 |
+
sk.move_to([*goal,envs.TABLE_Z+.055],speed=.1)
|
| 168 |
+
sk.set_gripper(False,12);sk.move_to([b[0],b[1],envs.TABLE_Z+.22]);return True
|
| 169 |
+
def repair_card(self):
|
| 170 |
+
"""Recover a card overhanging the shipping tray, with real finger motions."""
|
| 171 |
+
if self.in_cargo('card_1'):return True
|
| 172 |
+
p=self.card_pose();b=envs.obj_pos(self.env,'box_1')
|
| 173 |
+
axis=np.array([np.cos(p['yaw']),np.sin(p['yaw'])])
|
| 174 |
+
sign=1. if (p['xy']-b[:2])@axis>=0 else -1.
|
| 175 |
+
grasp=p['xy']+sign*.034*axis
|
| 176 |
+
floor=b[2]+HALF[2]
|
| 177 |
+
return self.grasp_and_bin(grasp,p['yaw'],floor-.003)
|
| 178 |
+
def load_product(self,o,k):
|
| 179 |
+
sk=self.sk;p=envs.obj_pos(self.env,o).copy();sk.set_gripper(False,8)
|
| 180 |
+
sk.move_to([p[0],p[1],envs.TABLE_Z+.18],yaw=0)
|
| 181 |
+
approach_offset=(sk.eef_pos()[:2]-p[:2]).tolist()
|
| 182 |
+
sk.move_to([p[0],p[1],p[2]+.003],tol=.002,max_steps=120)
|
| 183 |
+
offset=(sk.eef_pos()[:2]-p[:2]).tolist()
|
| 184 |
+
sk.set_gripper(True,15);sk.move_to([p[0],p[1],envs.TABLE_Z+.19])
|
| 185 |
+
held=sk.holding(o)
|
| 186 |
+
self.mon['l1_attempts'].append(dict(item=o,offset=offset,approach_offset=approach_offset,correction=self.sk.correction.tolist(),held=bool(held),step=sk.n_steps))
|
| 187 |
+
if not held:sk.set_gripper(False,8);return False
|
| 188 |
+
b=envs.obj_pos(self.env,'box_1');xy=[b[0],b[1]+(-.075 if k==0 else .075)]
|
| 189 |
+
sk.move_to([*xy,envs.TABLE_Z+.20]);sk.move_to([*xy,envs.TABLE_Z+.058],speed=.1)
|
| 190 |
+
sk.set_gripper(False,12);sk.move_to([*xy,envs.TABLE_Z+.22]);return self.in_cargo(o)
|
| 191 |
+
def execute(self,inst,params):
|
| 192 |
+
if 'mode' not in params:
|
| 193 |
+
return OffcenterPush.execute(self,inst,params)
|
| 194 |
+
mode=params['mode'];self.sk.correction=np.asarray(params.get('correction',[0,0,0]),dtype=float)
|
| 195 |
+
for k,o in enumerate(PRODUCTS):
|
| 196 |
+
if not self.load_product(o,k):return
|
| 197 |
+
if mode=='adaptive':
|
| 198 |
+
self.sk.correction+=np.array([*self.mon['l1_attempts'][-1]['approach_offset'],0.])
|
| 199 |
+
if mode=='naive':
|
| 200 |
+
CardEdge.execute(self,inst,dict(mode='grasp'))
|
| 201 |
+
else:
|
| 202 |
+
CardEdge.execute(self,inst,dict(mode='edge',overhang=.03))
|
| 203 |
+
self.sk.hold(10)
|
| 204 |
+
if not all(self.in_cargo(o) for o in CARGO):return
|
| 205 |
+
if mode=='adaptive':
|
| 206 |
+
OffcenterPush.adaptive_attempt(self,inst,params.get('c',0.))
|
| 207 |
+
if not self.in_cargo('card_1'):self.repair_card()
|
| 208 |
+
else:OffcenterPush.execute(self,inst,dict(c=params.get('c',0.)))
|
| 209 |
+
p=self.sk.eef_pos();self.sk.move_to([p[0],p[1],envs.TABLE_Z+.23]);self.sk.set_gripper(False,8)
|
| 210 |
+
def outcome(self,inst):
|
| 211 |
+
self.sk.hold(30)
|
| 212 |
+
p=envs.obj_pos(self.env,'box_1');yaw=_yaw(envs.obj_quat(self.env,'box_1'));fit=box_fit(p[:2],yaw,self.target_xy(inst))
|
| 213 |
+
cargo={o:self.in_cargo(o) for o in CARGO}
|
| 214 |
+
velocities=[]
|
| 215 |
+
for o in CARGO+('box_1',):
|
| 216 |
+
adr=self.env.sim.model.jnt_dofadr[self.env.sim.model.joint_name2id(self.env.objects_dict[o].joints[0])]
|
| 217 |
+
velocities.append(self.env.sim.data.qvel[adr:adr+6].copy())
|
| 218 |
+
static=all(np.linalg.norm(v[:3])<.01 and np.linalg.norm(v[3:])<.15 for v in velocities)
|
| 219 |
+
m=self.env.sim.model
|
| 220 |
+
robot=[g for g in range(m.ngeom) if (m.geom_id2name(g) or '').startswith(('robot0_','gripper0_'))]
|
| 221 |
+
touching=any(envs.contacts_between(self.env,robot,envs.obj_geom_ids(self.env,o)) for o in CARGO+('box_1',))
|
| 222 |
+
upright=envs.obj_upright_cos(self.env,'box_1')>.95
|
| 223 |
+
success=bool(all(cargo.values()) and self.mon['loaded'] and not self.mon['departed_unloaded'] and fit['inside'] and static and upright and not touching and self.sk.grip<0)
|
| 224 |
+
bad=[m for m in self.sk.box_moves if m.get('bad') and not m.get('gripper_open') and self.mon['load_step'] is not None and m['step']>=self.mon['load_step']]
|
| 225 |
+
return copy.deepcopy(dict(success=success,cargo=cargo,loaded_in_start=bool(self.mon['loaded']),load_step=self.mon['load_step'],departed_unloaded=self.mon['departed_unloaded'],inside=fit['inside'],static=bool(static),
|
| 226 |
+
failure=None if success else 'cargo' if not all(cargo.values()) else 'loading_order' if not self.mon['loaded'] else 'delivery',
|
| 227 |
+
stages={**cargo,'loaded_in_start':self.mon['loaded'],'delivery':fit['inside']},events=self.mon['events'],
|
| 228 |
+
l1_attempts=self.mon['l1_attempts'],card_closes=self.sk.closes,card_lift=self.mon['max_lift'],
|
| 229 |
+
box_moves=self.sk.box_moves,l5_triggered=bool(bad),yaw_deg=float(np.degrees(yaw)),
|
| 230 |
+
sim_s=self.sk.n_steps*.05,commands=self.sk.n_commands,touching=bool(touching),upright=bool(upright),
|
| 231 |
+
detail='Cargo in tray: '+str(cargo)+'; tray inside delivery rectangle: '+str(fit['inside'])+'.'))
|
| 232 |
+
def default_params(self,inst):return dict(mode='naive')
|
| 233 |
+
def oracle_params(self,inst):return dict(mode='oracle',correction=(inst['bias'] if inst['mechanisms']['L1'] else [0,0,0]),c=inst['com_offset'] if inst['mechanisms']['L5'] else 0.)
|
| 234 |
+
def adapt_params(self,inst,history):
|
| 235 |
+
# Calibration estimate from the measured failed grasp, not hidden bias.
|
| 236 |
+
offsets=[x['offset'] for h in history for x in h['outcome']['l1_attempts']]
|
| 237 |
+
calibrations=[np.array(x.get('correction',h['params'].get('correction',[0,0,0])))+np.array([*x.get('approach_offset',x['offset']),0.]) for h in history for x in h['outcome']['l1_attempts']]
|
| 238 |
+
corr=np.mean(calibrations[-2:],axis=0).tolist() if calibrations else history[-1]['params'].get('correction',[0,0,0])
|
| 239 |
+
moves=[m for h in history for m in h['outcome']['box_moves']]
|
| 240 |
+
return dict(mode='adaptive',correction=corr,c=self.bracket(moves))
|
| 241 |
+
def blind_params(self,inst,attempt,rng):return dict(mode='naive',correction=[*rng.normal(0,.005,2),0.])
|
| 242 |
+
def run_scripted(self,*args,**kwargs):return LFFTask.run_scripted(self,*args,**kwargs)
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/lh_wobbly_table.py
ADDED
|
@@ -0,0 +1,1177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LH lh_wobbly_table (2026-10-16): stand four bottles on the four coloured spots of a small side table -- one of its
|
| 2 |
+
legs is 1.5 cm short. Set the heavy bottle down on the corner over that leg while other bottles already stand on the
|
| 3 |
+
table and the table rocks down onto the short leg with a knock that throws the tall light bottles over.
|
| 4 |
+
|
| 5 |
+
Family: long-horizon self-disturbance ("state_restoration"): four plain pick-and-place stages, but a later stage (the heavy
|
| 6 |
+
bottle on the wobbly corner) physically undoes the earlier ones without the robot touching them. The agent has to
|
| 7 |
+
notice the fallen bottles and stand them up again (the rocked table is stable, so they stay up), or learn across
|
| 8 |
+
attempts to put that bottle down first (the table then rocks while nothing stands on it).
|
| 9 |
+
|
| 10 |
+
Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y):
|
| 11 |
+
* a small wooden side table (free body, 1.1 kg): 28 x 28 x 1.6 cm top, 8.5 cm high, four 1.6 cm square legs at
|
| 12 |
+
+-12.5 cm; centre 53-57 cm in front of the robot base, +-4 cm left/right; four coloured spots (7.2 x 6.4 cm,
|
| 13 |
+
painted, colours permuted) centred 8 cm from the middle on both axes (one per corner);
|
| 14 |
+
* four square glass bottles (red / blue / green / yellow; 3.2 x 3.2 x 10 cm body, 2.4 cm flat foot, shoulder, 1.4 cm
|
| 15 |
+
square neck, a thin stem and a 1.2 cm white ball stopper; 14.7 cm tall) standing in a row on the main table in
|
| 16 |
+
front of the side table or beside it (random). Three are empty and light (75-90 g, centre of mass 7.2-8.0 cm up:
|
| 17 |
+
they tip over beyond ~9 deg); the fourth looks the same but is heavy (0.34-0.38 kg, sand in the bottom, centre of
|
| 18 |
+
mass 3.0-3.6 cm up).
|
| 19 |
+
|
| 20 |
+
Hidden variables: which leg is short (its collision capsule is 14-16 mm shorter; the visual leg is drawn full length,
|
| 21 |
+
so all legs look alike and touch the table) and which bottle is heavy. Coupled by construction: the heavy bottle's spot
|
| 22 |
+
is the corner over the short leg. Balanced over seeds: in the scripted naive order (spots farthest from the supply
|
| 23 |
+
first, then left first) the heavy bottle's spot comes 1st / 2nd / 3rd / 4th for exactly 5 of every 20 consecutive seeds
|
| 24 |
+
(1st = benign for that order: the table rocks while it is empty).
|
| 25 |
+
|
| 26 |
+
Physics (measured, scratch scripts t2-t24, see the task card and results/lh_wobbly_table/physics.json):
|
| 27 |
+
* The legs' collision geoms are capsules (rounded feet). With flat 1.6 cm box feet the rocking axis moved 1.1 cm
|
| 28 |
+
towards the loaded corner and the table's own weight stopped the rock half way (0.5 deg, balanced on two legs).
|
| 29 |
+
* The empty table rests level on its three long legs: its centre of mass is 5 mm towards the corner opposite the
|
| 30 |
+
short leg (1.1 kg x 5 mm). The light bottles on their own spots (the other three corners) never tip it, also let go
|
| 31 |
+
4 cm above the top with a 2.6 cm error towards the short corner (4/4 seeds); the heavy bottle on the short corner
|
| 32 |
+
does (0.36 kg x 11.3 cm), also against a light bottle on the opposite corner. (A light bottle put on the short
|
| 33 |
+
corner's spot -- a wrong spot -- also tips the empty table: 85 g x 11.3 cm > 1.1 kg x 5 mm.) Rocked onto the short
|
| 34 |
+
leg the table tilts 4.5-5.1 deg and stays there with the heavy bottle on it, also when the light ones are added;
|
| 35 |
+
lifting the heavy bottle off, or pressing 1.25 N down near the raised corner, rocks it back (measured).
|
| 36 |
+
* The knock topples the light bottles standing on the table: 18/18 with teleported (zero-velocity) placements at gaps
|
| 37 |
+
13-18 mm (12 mm: 8-10/18, 10 mm: 0/18); they fall towards the low corner, some off the table edge. The heavy bottle
|
| 38 |
+
stays up. The robot does not touch the bottles that fall (logged per rock).
|
| 39 |
+
* Bottle and table-top contacts are overdamped (solref 0.01, damping ratio 3): with stiff critically damped contacts
|
| 40 |
+
a light bottle let go 1-4 cm above the ROCKED table landed on its uphill edge and fell over (21/27 at 3.4 deg);
|
| 41 |
+
damped, 0/54 at every gap 13-18 mm, so the cross-attempt fix (heavy bottle first) works with the agent's usual
|
| 42 |
+
release 1-4 cm above the surface.
|
| 43 |
+
* A 22 x 22 cm draft table (spots 15.6 cm apart diagonally, 15.7 cm draft bottles) let the bottle on the opposite corner
|
| 44 |
+
fall onto the heavy one and lean on it; its stopper could not be grasped without knocking the heavy bottle over
|
| 45 |
+
(after which the table rocks back and forth on every repair step). At 28 cm nothing leans on it.
|
| 46 |
+
* Grasps: the Panda hand's collision hull starts 3 cm above the grasp point and the finger pads reach 1.2 cm above
|
| 47 |
+
it. Everything above the square neck is narrower than the neck: fingers that overlap the neck (grasp point 0.4-0.9
|
| 48 |
+
cm below its top) close on its flat faces and hold the bottle rigidly (the heavy one stayed in the fingers through
|
| 49 |
+
three moves at the controller's top speed 12/12, a light one 11/12); fingers on the ball alone (grasp point at or
|
| 50 |
+
above the neck's top) touch it at one point each and the bottle pivots (top-speed carries lost it 6/6). Drafts: a
|
| 51 |
+
1.8 cm ball on a 1.3 cm round neck (the fingers always closed on the ball; the heavy bottle swung out in 5/6 fast
|
| 52 |
+
carries and once in the first smoke test), a 1.2 x 2.2 cm cylinder stopper (line contacts: a lying bottle lifted by
|
| 53 |
+
it stuck at ~26 deg and fell over when set down). The instruction states which grip is rigid and which swings (as
|
| 54 |
+
lh_bystander states its cap).
|
| 55 |
+
* Restoring (yaw-only top-down gripper): grasp the ball stopper of a lying bottle from above with the fingers across
|
| 56 |
+
its axis (torsional friction 0.0005), lift: it swings down and hangs straight (0.1 deg); lower it onto its spot and
|
| 57 |
+
let go. A bottle that fell off onto the main table right beside the small table often cannot be reached this way:
|
| 58 |
+
the hand (20 cm wide along the finger axis, 3 cm above the grasp point) would hit the table top. Where the hand,
|
| 59 |
+
the open fingers or the forearm would touch a standing bottle, the scripted repair first lifts the fallen bottle by
|
| 60 |
+
its body and lays it down in free space.
|
| 61 |
+
* Reach: the arm stalls 2-3 cm short of low targets beyond ~0.72 m from the base; every scripted grasp point stays
|
| 62 |
+
within 0.70 m.
|
| 63 |
+
|
| 64 |
+
Success predicates (evaluated every other control step by a monitor, debounced over 0.5 s): each bottle stands upright
|
| 65 |
+
(tilt <= 10 deg from vertical; on the rocked table they stand at ~5.5 deg) on the small table's top with the centre of
|
| 66 |
+
its bottom inside its spot shrunk by 6 mm (3.0 cm forward-back, 2.6 cm left-right of the spot's centre), not held.
|
| 67 |
+
Success = all four at the end, gripper open and not touching a bottle, scene static, and the small table within 3 cm /
|
| 68 |
+
10 deg of where it stood and standing on its legs (tilt <= 8 deg; the rocked tilt counts as standing). The monitor logs
|
| 69 |
+
achieved / lost / restored per bottle and table_rocked / table_rocked_back events (the bottle released just before,
|
| 70 |
+
the bottles standing at that moment, which of them fell, whether the robot touched them before / while they fell) for
|
| 71 |
+
the server log only (F1 gives the agent only success / failure).
|
| 72 |
+
|
| 73 |
+
Protocol: cross (reset to the same instance before every attempt), k = 3.
|
| 74 |
+
"""
|
| 75 |
+
import numpy as np
|
| 76 |
+
|
| 77 |
+
from .. import envs
|
| 78 |
+
from ..bddl import write_bddl
|
| 79 |
+
from ..objects import _fmt, _wrap, register_generated
|
| 80 |
+
from ..skills import Skills
|
| 81 |
+
from ..task_base import LFFTask, register_task
|
| 82 |
+
|
| 83 |
+
TZ = envs.TABLE_Z
|
| 84 |
+
COLOURS = ["red", "blue", "green", "yellow"]
|
| 85 |
+
BOTTLES = [f"bottle_{c}_1" for c in COLOURS]
|
| 86 |
+
TABLE = "side_table_1"
|
| 87 |
+
RGBA = {"red": (0.80, 0.14, 0.12, 1.0), "blue": (0.15, 0.33, 0.80, 1.0), "green": (0.14, 0.58, 0.24, 1.0),
|
| 88 |
+
"yellow": (0.90, 0.74, 0.12, 1.0)}
|
| 89 |
+
SPOT_RGBA = {"red": (0.62, 0.12, 0.11, 1.0), "blue": (0.12, 0.22, 0.58, 1.0), "green": (0.10, 0.42, 0.17, 1.0),
|
| 90 |
+
"yellow": (0.70, 0.56, 0.08, 1.0)}
|
| 91 |
+
CAP_RGBA = (0.93, 0.93, 0.91, 1.0) # white round stopper
|
| 92 |
+
WOOD = (0.52, 0.36, 0.22, 1.0)
|
| 93 |
+
LEG_RGBA = (0.40, 0.27, 0.16, 1.0)
|
| 94 |
+
|
| 95 |
+
# ---------------------------------------------------------------- side table (free body)
|
| 96 |
+
TOP_HW = 0.140 # 28 x 28 cm top
|
| 97 |
+
TOP_T = 0.016
|
| 98 |
+
TABLE_H = 0.085 # top surface above the main table
|
| 99 |
+
LEG_HW = 0.008 # 1.6 x 1.6 cm legs (visual); collision: capsules of radius 8 mm (rounded feet)
|
| 100 |
+
LEG_O = 0.125 # leg centre offset from the table centre (x and y)
|
| 101 |
+
LEG_L = TABLE_H - TOP_T
|
| 102 |
+
TBL_MASS = 1.1
|
| 103 |
+
TBL_SOLREF = 'solimp="0.95 0.99 0.001" solref="0.004 1"' # legs: stiff (a sharp knock when the short leg lands)
|
| 104 |
+
TOP_SOLREF = 'solimp="0.95 0.99 0.001" solref="0.01 3"' # top: overdamped like the bottles
|
| 105 |
+
LEG_MU = 1.0
|
| 106 |
+
TOP_MU = 0.8
|
| 107 |
+
# corners in the table frame (= world axes; +x forward, +y left): index -> (sx, sy); k and k + 2 are diagonal
|
| 108 |
+
CORNERS = [(1, 1), (1, -1), (-1, -1), (-1, 1)]
|
| 109 |
+
CORNER_NAME = {(1, 1): "far-left", (1, -1): "far-right", (-1, -1): "near-right", (-1, 1): "near-left"}
|
| 110 |
+
SPOT_O = 0.080 # spot centre offset from the table centre (x and y)
|
| 111 |
+
SPOT_HX, SPOT_HY = 0.036, 0.032 # spot half sizes (forward-back, left-right): 7.2 x 6.4 cm
|
| 112 |
+
SHORT_H = (0.014, 0.016) # hidden: one leg this much shorter (collision only; the visual leg reaches the table)
|
| 113 |
+
COM_BIAS = 0.005 # table centre of mass this far towards the leg opposite the short one: the empty table rests level
|
| 114 |
+
|
| 115 |
+
# ---------------------------------------------------------------- bottles (square glass bottles with a round stopper)
|
| 116 |
+
RB, HB = 0.016, 0.100 # body half width, height (3.2 x 3.2 x 10 cm)
|
| 117 |
+
RF, HF = 0.012, 0.005 # foot: flat contact 2.4 x 2.4 cm (rounded glass base)
|
| 118 |
+
RS, HS = 0.011, 0.010 # shoulder
|
| 119 |
+
RN, HN = 0.007, 0.016 # square neck: 1.4 cm wide, 1.6 cm long (11.0-12.6 cm above the bottom)
|
| 120 |
+
RT, HT = 0.0035, 0.010 # thin round stem above it: 0.7 cm wide, 1.0 cm long
|
| 121 |
+
RK, CAP_SINK = 0.006, 0.001 # ball stopper: 1.2 cm wide, on the stem (top 14.7 cm above the bottom)
|
| 122 |
+
# Why this top (measured, t8_hand.py / t19_slip.py / t22_restand.py): the Panda hand's collision hull starts ~3 cm above
|
| 123 |
+
# the grasp point and the finger pads reach 1.2 cm above it. Everything above the square neck is narrower than the
|
| 124 |
+
# neck, so fingers that overlap the neck close on its flat faces (several contact points: the bottle is held rigidly),
|
| 125 |
+
# and fingers on the ball alone touch it at one point each (low torsional friction: a lying bottle swings down and
|
| 126 |
+
# hangs straight). Drafts: a 1.8 cm ball on a 1.3 cm round neck -- the fingers always closed on the ball, the heavy
|
| 127 |
+
# bottle pivoted and swung out in 5/6 fast carries; a 1.2 x 2.2 cm cylinder stopper -- line contacts, a lifted lying
|
| 128 |
+
# bottle stuck at ~26 deg and fell over when set down (in-attempt repair 6/15).
|
| 129 |
+
H_TOT = HB + HS + HN + HT + 2 * RK - CAP_SINK # 14.7 cm
|
| 130 |
+
CAP_Z = H_TOT - RK # stopper centre above the bottle's bottom
|
| 131 |
+
NECK_Z = (HB + HS, HB + HS + HN) # square neck span above the bottom
|
| 132 |
+
BOT_MU = 0.7
|
| 133 |
+
CAP_MU_T = 0.0005 # torsional friction of the stopper (condim 4): held by it, a lying bottle swings down and hangs
|
| 134 |
+
BOT_DAMP = 0.003 # free-joint damping of the bottles (damps the swing of a bottle hanging from its stopper)
|
| 135 |
+
# overdamped contacts (damping ratio 3): with critically damped stiff contacts a light bottle set down 1-4 cm above a
|
| 136 |
+
# table top tilted 3.4 deg landed on its uphill edge and fell over (measured 21/27); damped: 0/54 at tilts up to 5 deg
|
| 137 |
+
BOT_SOLREF = 'solimp="0.95 0.99 0.001" solref="0.01 3"'
|
| 138 |
+
LIGHT_MASS = (0.075, 0.090)
|
| 139 |
+
LIGHT_COM = (0.072, 0.080) # above the bottom (empty glass bottle, thick shoulder)
|
| 140 |
+
HEAVY_MASS = (0.34, 0.38)
|
| 141 |
+
HEAVY_COM = (0.030, 0.036) # sand in the bottom
|
| 142 |
+
|
| 143 |
+
# ---------------------------------------------------------------- predicates / monitor
|
| 144 |
+
TILT_OK = np.radians(10.0) # a bottle stands upright (world vertical; the rocked table itself tilts ~4.3 deg)
|
| 145 |
+
TOL_X = SPOT_HX - 0.006 # bottle centre within the spot shrunk by 6 mm (3.0 cm forward-back, 2.6 cm left-right)
|
| 146 |
+
TOL_Y = SPOT_HY - 0.006
|
| 147 |
+
ON_TOP = 0.006 # the bottle's bottom within this of the table top
|
| 148 |
+
HYST = 0.003
|
| 149 |
+
DEBOUNCE = 10 # control steps (0.5 s)
|
| 150 |
+
ROCK_ON, ROCK_OFF = np.radians(1.5), np.radians(0.8) # table tilt thresholds of the rock detector
|
| 151 |
+
FELL_WINDOW = 40 # control steps after a rock in which lost stages are attributed to it (2 s)
|
| 152 |
+
TABLE_MOVE_TOL = 0.03 # success: the table centre within 3 cm of where it stood
|
| 153 |
+
TABLE_YAW_TOL = np.radians(10.0)
|
| 154 |
+
TABLE_TILT_MAX = np.radians(8.0)
|
| 155 |
+
|
| 156 |
+
# ---------------------------------------------------------------- scripted motion
|
| 157 |
+
Z_CARRY = 0.40 # grasp point above the main table while carrying (bottle bottom ~27 cm up: clears standing bottles)
|
| 158 |
+
Z_HANG = 0.42 # ... carrying a bottle that hangs from its stopper (its bottom 27 cm up)
|
| 159 |
+
GRASP_NECK = 0.006 # scripted transport grasp point: this far below the neck's top (pads 1.1 cm on the neck, the hand
|
| 160 |
+
# 3 mm above the stopper; measured: 4-9 mm below the top hold rigidly, 4 mm above it close on the ball)
|
| 161 |
+
NAIVE_GAP = (0.010, 0.040) # Sonnet releases 1-4 cm above the surface
|
| 162 |
+
NAIVE_BIAS = (0.008, 0.020) # systematic forward placement error (lh_nudge_row pilot), per instance
|
| 163 |
+
NAIVE_RAND = 0.006
|
| 164 |
+
CAREFUL_GAP = 0.004
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def bottle_xml(name, rgba):
|
| 168 |
+
"""square glass bottle: rounded foot (smaller flat contact), body, shoulder, square neck, round stopper. Collision and
|
| 169 |
+
visual geoms separate; the inertial (mass, COM) is replaced per instance."""
|
| 170 |
+
h = H_TOT / 2
|
| 171 |
+
zf, zb = -h + HF / 2, -h + HF + (HB - HF) / 2
|
| 172 |
+
zs, zn = -h + HB + HS / 2, -h + HB + HS + HN / 2
|
| 173 |
+
zt = -h + HB + HS + HN + HT / 2
|
| 174 |
+
zk = -h + HB + HS + HN + HT + RK - CAP_SINK
|
| 175 |
+
parts = [("foot", "box", (0, 0, zf), (RF, RF, HF / 2), rgba, f'friction="{BOT_MU} 0.005 0.0001"'),
|
| 176 |
+
("body", "box", (0, 0, zb), (RB, RB, (HB - HF) / 2), rgba, f'friction="{BOT_MU} 0.005 0.0001"'),
|
| 177 |
+
("shoulder", "box", (0, 0, zs), (RS, RS, HS / 2), rgba, f'friction="{BOT_MU} 0.005 0.0001"'),
|
| 178 |
+
("neck", "box", (0, 0, zn), (RN, RN, HN / 2), rgba, f'friction="{BOT_MU} 0.005 0.0001"'),
|
| 179 |
+
("stem", "cylinder", (0, 0, zt), (RT, HT / 2), CAP_RGBA, f'friction="{BOT_MU} 0.005 0.0001"'),
|
| 180 |
+
("cap", "sphere", (0, 0, zk), (RK,), CAP_RGBA, f'friction="1 {CAP_MU_T} 0.0001" condim="4" priority="2"')]
|
| 181 |
+
s = [f' <inertial pos="0 0 {-h + 0.05:.4f}" mass="0.08" diaginertia="1.5e-4 1.5e-4 2.0e-5" />']
|
| 182 |
+
for nm, typ, pos, size, c, extra in parts:
|
| 183 |
+
s.append(f' <geom name="{name}_{nm}" type="{typ}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(c)}" '
|
| 184 |
+
f'{extra} {BOT_SOLREF} group="0" />')
|
| 185 |
+
s.append(f' <geom type="{typ}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(c)}" contype="0" '
|
| 186 |
+
f'conaffinity="0" group="1" />')
|
| 187 |
+
# a pale label (visual) so the bottles read as bottles
|
| 188 |
+
s.append(f' <geom type="box" pos="0 0 {zb + 0.008:.4f}" size="{RB + 0.0006:.4f} {RB + 0.0006:.4f} 0.016" '
|
| 189 |
+
f'rgba="0.94 0.92 0.84 1" contype="0" conaffinity="0" group="1" />')
|
| 190 |
+
return _wrap(name, "\n".join(s), h, RB * 1.42)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def table_xml(name):
|
| 194 |
+
"""side table, origin at the centre of the footprint at mid height. Leg k sits under corner CORNERS[k]."""
|
| 195 |
+
h = TABLE_H / 2
|
| 196 |
+
zt = h - TOP_T / 2
|
| 197 |
+
zl = -h + LEG_L / 2
|
| 198 |
+
s = [f' <inertial pos="0 0 {0.02:.4f}" mass="{TBL_MASS}" diaginertia="0.004 0.004 0.007" />',
|
| 199 |
+
f' <geom name="{name}_top" type="box" pos="0 0 {zt:.5f}" size="{TOP_HW:.5f} {TOP_HW:.5f} {TOP_T / 2:.5f}" '
|
| 200 |
+
f'rgba="{_fmt(WOOD)}" friction="{TOP_MU} 0.005 0.0001" {TOP_SOLREF} group="0" />',
|
| 201 |
+
f' <geom type="box" pos="0 0 {zt:.5f}" size="{TOP_HW:.5f} {TOP_HW:.5f} {TOP_T / 2:.5f}" '
|
| 202 |
+
f'rgba="{_fmt(WOOD)}" contype="0" conaffinity="0" group="1" />']
|
| 203 |
+
for k, (sx, sy) in enumerate(CORNERS):
|
| 204 |
+
p = (sx * LEG_O, sy * LEG_O, zl)
|
| 205 |
+
# collision: a capsule inscribed in the square leg -> a rounded, point-like foot (a flat 1.6 cm foot moves the
|
| 206 |
+
# rocking axis 1.1 cm towards the loaded corner, and the table's own weight then stops the rock; measured)
|
| 207 |
+
s.append(f' <geom name="{name}_leg{k}" type="capsule" pos="{_fmt(p)}" '
|
| 208 |
+
f'size="{LEG_HW:.5f} {LEG_L / 2 - LEG_HW:.5f}" rgba="{_fmt(LEG_RGBA)}" '
|
| 209 |
+
f'friction="{LEG_MU} 0.005 0.0001" {TBL_SOLREF} group="0" />')
|
| 210 |
+
s.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt((LEG_HW, LEG_HW, LEG_L / 2))}" '
|
| 211 |
+
f'rgba="{_fmt(LEG_RGBA)}" contype="0" conaffinity="0" group="1" />')
|
| 212 |
+
for k, (sx, sy) in enumerate(CORNERS): # coloured spots (visual); colours are set per instance
|
| 213 |
+
s.append(f' <geom name="{name}_spot{k}" type="box" pos="{sx * SPOT_O:.5f} {sy * SPOT_O:.5f} {h + 0.0004:.5f}" '
|
| 214 |
+
f'size="{SPOT_HX:.5f} {SPOT_HY:.5f} 0.0004" rgba="0.5 0.5 0.5 1" contype="0" conaffinity="0" '
|
| 215 |
+
f'group="1" />')
|
| 216 |
+
return _wrap(name, "\n".join(s), h, TOP_HW * 1.42)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def _fb(d):
|
| 220 |
+
return f"{100 * abs(d):.1f} cm {'forward' if d > 0 else 'back'}"
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def _lr(d):
|
| 224 |
+
return f"{100 * abs(d):.1f} cm to the {'left' if d > 0 else 'right'}"
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def _ang(a):
|
| 228 |
+
return float((a + np.pi) % (2 * np.pi) - np.pi)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
class WobblySkills(Skills):
|
| 232 |
+
"""Skills that feed the task's per-step monitor."""
|
| 233 |
+
|
| 234 |
+
def __init__(self, env, task, recorder=None):
|
| 235 |
+
super().__init__(env, recorder=recorder)
|
| 236 |
+
self.task = task
|
| 237 |
+
|
| 238 |
+
def _act(self, dpos, drot, grip):
|
| 239 |
+
super()._act(dpos, drot, grip)
|
| 240 |
+
self.task.monitor_step()
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
@register_task
|
| 244 |
+
class WobblyTable(LFFTask):
|
| 245 |
+
name = "lh_wobbly_table"
|
| 246 |
+
level = "L2"
|
| 247 |
+
category = "state_restoration"
|
| 248 |
+
capabilities = ("Perceive", "Reason", "Restore", "Plan")
|
| 249 |
+
protocol = "cross"
|
| 250 |
+
max_attempts = 3
|
| 251 |
+
# careful: 4 bottles x ~7 commands + standing up to three fallen bottles again x ~9 + looking / corrections
|
| 252 |
+
agent_max_steps = 120
|
| 253 |
+
instruction = ("Put each of the four bottles on the spot of its own colour on the small wooden table. At the end "
|
| 254 |
+
"every bottle must stand upright on its spot, the gripper must be open and clear of the bottles, and "
|
| 255 |
+
"the small table must still stand where it is now. (Each bottle has a square neck with a small round "
|
| 256 |
+
"white stopper on top. Gripped on the neck, a bottle stays rigid in the fingers; gripped by the "
|
| 257 |
+
"stopper alone, it swings freely and hangs straight down.)")
|
| 258 |
+
instruction_indirect = ("Set the four coloured bottles out on the little wooden side table, each on the patch that "
|
| 259 |
+
"matches its colour. When you finish, all four have to be standing upright on their patches, "
|
| 260 |
+
"the gripper open and away from them, and the side table left where it stands. (Gripped "
|
| 261 |
+
"on its square neck a bottle stays rigid; gripped by the round white stopper alone it swings "
|
| 262 |
+
"freely and hangs straight down.)")
|
| 263 |
+
agent_object_names = ["bottles (red, blue, green, yellow; each with a square neck and a small round white stopper)",
|
| 264 |
+
"small wooden side table with four coloured spots (red, blue, green, yellow)"]
|
| 265 |
+
|
| 266 |
+
# ------------------------------------------------------------ scene
|
| 267 |
+
def make_bddl(self):
|
| 268 |
+
objs = []
|
| 269 |
+
for i, (c, b) in enumerate(zip(COLOURS, BOTTLES)):
|
| 270 |
+
cat = register_generated(f"LffLhwBottle{c.capitalize()}", bottle_xml(f"lff_lhw_bottle_{c}", RGBA[c]))
|
| 271 |
+
objs.append((b, cat, f"bottle{i}_region", (-0.30 + 0.13 * i, 0.30, -0.29 + 0.13 * i, 0.31)))
|
| 272 |
+
cat = register_generated("LffLhwSideTable", table_xml("lff_lhw_table"))
|
| 273 |
+
objs.append((TABLE, cat, "table_region", (-0.05, -0.30, -0.04, -0.29)))
|
| 274 |
+
return write_bddl(self.name, "Stand each bottle on the spot of its colour on the small table", objs, [])
|
| 275 |
+
|
| 276 |
+
def __init__(self, cam_res=None):
|
| 277 |
+
super().__init__(cam_res)
|
| 278 |
+
m = self.env.sim.model
|
| 279 |
+
self.tbid = envs.body_id(self.env, TABLE)
|
| 280 |
+
pre = f"{TABLE}_lff_lhw_table"
|
| 281 |
+
self.leg_gid = [m.geom_name2id(f"{pre}_leg{k}") for k in range(4)]
|
| 282 |
+
self.top_gid = m.geom_name2id(f"{pre}_top")
|
| 283 |
+
self.leg_size0 = [m.geom_size[g].copy() for g in self.leg_gid]
|
| 284 |
+
self.leg_pos0 = [m.geom_pos[g].copy() for g in self.leg_gid]
|
| 285 |
+
self.tbl_ipos0 = m.body_ipos[self.tbid].copy()
|
| 286 |
+
self.spot_gid = [m.geom_name2id(f"{pre}_spot{k}") for k in range(4)]
|
| 287 |
+
self.bbid = {b: envs.body_id(self.env, b) for b in BOTTLES}
|
| 288 |
+
self.cap_gid = {b: m.geom_name2id(f"{b}_lff_lhw_bottle_{c}_cap") for c, b in zip(COLOURS, BOTTLES)}
|
| 289 |
+
self.dof = {b: envs.free_joint_addr(self.env, b)[1] for b in BOTTLES}
|
| 290 |
+
self.tbl_dof = envs.free_joint_addr(self.env, TABLE)[1]
|
| 291 |
+
self.bgeoms = {b: envs.obj_geom_ids(self.env, b) for b in BOTTLES}
|
| 292 |
+
self.finger_geoms, self.hand_geoms, self.arm_geoms = [], [], []
|
| 293 |
+
for g in envs.robot_geom_ids(self.env):
|
| 294 |
+
n = m.geom_id2name(g) or ""
|
| 295 |
+
(self.finger_geoms if "finger" in n else self.hand_geoms if n.startswith("gripper0_")
|
| 296 |
+
else self.arm_geoms).append(g)
|
| 297 |
+
# per-geom lookup tables for the substep contact check: bottle index (-1 none), robot part (1 finger, 2 hand,
|
| 298 |
+
# 3 arm), table geom
|
| 299 |
+
self.owner = np.full(m.ngeom, -1, int)
|
| 300 |
+
for i, b in enumerate(BOTTLES):
|
| 301 |
+
self.owner[self.bgeoms[b]] = i
|
| 302 |
+
self.part = np.zeros(m.ngeom, int)
|
| 303 |
+
self.part[self.finger_geoms] = 1
|
| 304 |
+
self.part[self.hand_geoms] = 2
|
| 305 |
+
self.part[self.arm_geoms] = 3
|
| 306 |
+
self.is_table = np.zeros(m.ngeom, bool)
|
| 307 |
+
self.is_table[envs.obj_geom_ids(self.env, TABLE)] = True
|
| 308 |
+
self._sub_rob, self._sub_obj, self._sub_tbl = {}, {}, 0
|
| 309 |
+
# contacts are collected after every MuJoCo substep (same technique as lh_nudge_row; wrappers chain)
|
| 310 |
+
sim = self.env.sim
|
| 311 |
+
if not getattr(sim, "_lhw_wrapped", False):
|
| 312 |
+
orig = sim.step
|
| 313 |
+
|
| 314 |
+
def step(*a, **k):
|
| 315 |
+
orig(*a, **k)
|
| 316 |
+
t = getattr(sim, "_lhw_task", None)
|
| 317 |
+
if t is not None and t.mon is not None:
|
| 318 |
+
t._substep()
|
| 319 |
+
sim.step = step
|
| 320 |
+
sim._lhw_wrapped = True
|
| 321 |
+
sim._lhw_task = self
|
| 322 |
+
self.inst = None
|
| 323 |
+
self.mon = None
|
| 324 |
+
self.sk = None
|
| 325 |
+
self._held_prev = None
|
| 326 |
+
|
| 327 |
+
def _substep(self):
|
| 328 |
+
d = self.env.sim.data
|
| 329 |
+
n = d.ncon
|
| 330 |
+
if not n:
|
| 331 |
+
return
|
| 332 |
+
g1 = np.asarray(d.contact.geom1)[:n]
|
| 333 |
+
g2 = np.asarray(d.contact.geom2)[:n]
|
| 334 |
+
o1, o2 = self.owner[g1], self.owner[g2]
|
| 335 |
+
for a, b, pa, pb in zip(g1, g2, o1, o2):
|
| 336 |
+
if pa < 0 and pb < 0:
|
| 337 |
+
if (self.is_table[a] and self.part[b]) or (self.is_table[b] and self.part[a]):
|
| 338 |
+
self._sub_tbl = 1
|
| 339 |
+
continue
|
| 340 |
+
if pa >= 0 and pb >= 0:
|
| 341 |
+
if pa != pb:
|
| 342 |
+
self._sub_obj[int(pa)] = int(pb)
|
| 343 |
+
self._sub_obj[int(pb)] = int(pa)
|
| 344 |
+
continue
|
| 345 |
+
p, o = (pa, b) if pa >= 0 else (pb, a)
|
| 346 |
+
part = int(self.part[o])
|
| 347 |
+
if part:
|
| 348 |
+
self._sub_rob[int(p)] = min(self._sub_rob.get(int(p), 9), part)
|
| 349 |
+
|
| 350 |
+
# ------------------------------------------------------------ instances
|
| 351 |
+
@staticmethod
|
| 352 |
+
def _supply(side, tx, ty, j):
|
| 353 |
+
"""slot j (0-3) of the row of bottles on the main table: in front of the side table (robot side) or beside it;
|
| 354 |
+
every grasp point stays within 0.70 m (horizontal) of the robot base (the arm stalled 2-3 cm short of low
|
| 355 |
+
targets beyond ~0.72 m, measured)"""
|
| 356 |
+
if side == "front":
|
| 357 |
+
return [tx - 0.215, ty + (j - 1.5) * 0.085]
|
| 358 |
+
sg = 1.0 if side == "left" else -1.0
|
| 359 |
+
return [tx - 0.05 + (j - 1.5) * 0.075, ty + sg * 0.22]
|
| 360 |
+
|
| 361 |
+
@staticmethod
|
| 362 |
+
def _far_first(spot_of, side, tx, ty):
|
| 363 |
+
"""colours in the order of the scripted naive policy: the spots farthest from the supply first (a careful agent
|
| 364 |
+
does not reach over bottles it has already put down), ties broken to the left, then far"""
|
| 365 |
+
sup = np.mean([WobblyTable._supply(side, tx, ty, j) for j in range(4)], axis=0)
|
| 366 |
+
sc = []
|
| 367 |
+
for c, k in spot_of.items():
|
| 368 |
+
sx, sy = CORNERS[k]
|
| 369 |
+
p = np.array([tx + sx * SPOT_O, ty + sy * SPOT_O])
|
| 370 |
+
sc.append((-round(float(np.linalg.norm(p - sup)), 3), -sy, -sx, c))
|
| 371 |
+
return [t[-1] for t in sorted(sc)]
|
| 372 |
+
|
| 373 |
+
def sample_instance(self, seed):
|
| 374 |
+
rng = np.random.default_rng(seed)
|
| 375 |
+
tx = float(rng.uniform(-0.13, -0.09)) # side table centre: 53-57 cm in front of the robot base
|
| 376 |
+
ty = float(rng.uniform(-0.04, 0.04))
|
| 377 |
+
side = str(rng.choice(["left", "right", "front"]))
|
| 378 |
+
perm = [int(v) for v in rng.permutation(4)] # perm[corner] = colour index on that corner's spot
|
| 379 |
+
spot_of = {COLOURS[perm[k]]: k for k in range(4)}
|
| 380 |
+
# the heavy bottle and the short leg under its spot: balanced over seeds against the scripted naive order (far
|
| 381 |
+
# spots first): its spot comes 1st / 2nd / 3rd / 4th in that order for exactly 5 of every 20 consecutive seeds
|
| 382 |
+
order = self._far_first(spot_of, side, tx, ty)
|
| 383 |
+
pos = int((int(seed) * 7) % 20 // 5)
|
| 384 |
+
heavy = order[pos]
|
| 385 |
+
short = spot_of[heavy]
|
| 386 |
+
slots = [int(v) for v in rng.permutation(4)]
|
| 387 |
+
start = {}
|
| 388 |
+
for i in range(4):
|
| 389 |
+
x, y = self._supply(side, tx, ty, slots[i])
|
| 390 |
+
start[COLOURS[i]] = [x + float(rng.uniform(-0.006, 0.006)), y + float(rng.uniform(-0.006, 0.006))]
|
| 391 |
+
mass = {c: float(rng.uniform(*LIGHT_MASS)) for c in COLOURS}
|
| 392 |
+
com = {c: float(rng.uniform(*LIGHT_COM)) for c in COLOURS}
|
| 393 |
+
mass[heavy] = float(rng.uniform(*HEAVY_MASS))
|
| 394 |
+
com[heavy] = float(rng.uniform(*HEAVY_COM))
|
| 395 |
+
return dict(seed=int(seed), table_xy=[tx, ty], short_leg=int(short), short_corner=CORNER_NAME[CORNERS[short]],
|
| 396 |
+
heavy=heavy, heavy_rank_naive=pos + 1, spot_of=spot_of, supply_side=side, start=start, mass=mass,
|
| 397 |
+
com=com, short_h=float(rng.uniform(*SHORT_H)), com_bias=COM_BIAS,
|
| 398 |
+
yaw0={c: float(rng.uniform(-0.3, 0.3)) for c in COLOURS},
|
| 399 |
+
naive_bias_x=float(rng.uniform(*NAIVE_BIAS)))
|
| 400 |
+
|
| 401 |
+
def apply_instance(self, inst):
|
| 402 |
+
self.inst = inst
|
| 403 |
+
m = self.env.sim.model
|
| 404 |
+
k = inst["short_leg"]
|
| 405 |
+
h = float(inst["short_h"])
|
| 406 |
+
for j, g in enumerate(self.leg_gid):
|
| 407 |
+
m.geom_size[g] = self.leg_size0[j]
|
| 408 |
+
m.geom_pos[g] = self.leg_pos0[j]
|
| 409 |
+
g = self.leg_gid[k]
|
| 410 |
+
m.geom_size[g][1] = self.leg_size0[k][1] - h / 2 # capsule half length
|
| 411 |
+
m.geom_pos[g][2] = self.leg_pos0[k][2] + h / 2
|
| 412 |
+
opp = CORNERS[(k + 2) % 4]
|
| 413 |
+
b = float(inst.get("com_bias", COM_BIAS)) / np.sqrt(2)
|
| 414 |
+
m.body_ipos[self.tbid] = [opp[0] * b, opp[1] * b, self.tbl_ipos0[2]]
|
| 415 |
+
envs.refit_bounds(m, self.tbid)
|
| 416 |
+
for c in COLOURS:
|
| 417 |
+
m.geom_rgba[self.spot_gid[inst["spot_of"][c]]] = SPOT_RGBA[c]
|
| 418 |
+
for c, bot in zip(COLOURS, BOTTLES):
|
| 419 |
+
bid = self.bbid[bot]
|
| 420 |
+
M, zc = inst["mass"][c], inst["com"][c]
|
| 421 |
+
m.body_mass[bid] = M
|
| 422 |
+
m.body_ipos[bid] = [0.0, 0.0, -H_TOT / 2 + zc]
|
| 423 |
+
# glass shell + internal weight, roughly: radius of gyration ~ 0.35 x height about horizontal axes
|
| 424 |
+
ixx = M * ((2 * RB) ** 2 / 12 + (0.35 * H_TOT) ** 2)
|
| 425 |
+
m.body_inertia[bid] = [ixx, ixx, M * (2 * RB) ** 2 / 6]
|
| 426 |
+
envs.refit_bounds(m, bid)
|
| 427 |
+
m.dof_damping[self.dof[bot]:self.dof[bot] + 6] = BOT_DAMP
|
| 428 |
+
self.env.sim.forward()
|
| 429 |
+
tx, ty = inst["table_xy"]
|
| 430 |
+
# yaw pi: the canonical quaternion LIBERO gives generated objects is a 180 deg yaw (envs.canonical_quat); with
|
| 431 |
+
# it the table frame is the world frame
|
| 432 |
+
envs.place_upright(self.env, TABLE, [tx, ty], yaw=np.pi, clearance=0.0003)
|
| 433 |
+
for c, bot in zip(COLOURS, BOTTLES):
|
| 434 |
+
envs.place_upright(self.env, bot, inst["start"][c], yaw=inst["yaw0"][c], clearance=0.0005)
|
| 435 |
+
self.env.sim.data.qvel[self.tbl_dof:self.tbl_dof + 6] = 0.0
|
| 436 |
+
|
| 437 |
+
def reset_instance(self, inst, recorder=None):
|
| 438 |
+
self.mon = None
|
| 439 |
+
self.env.reset()
|
| 440 |
+
self.apply_instance(inst)
|
| 441 |
+
self.env.sim.forward()
|
| 442 |
+
envs.settle(self.env, 15)
|
| 443 |
+
self.sk = WobblySkills(self.env, self, recorder=recorder)
|
| 444 |
+
self._sub_rob, self._sub_obj, self._sub_tbl = {}, {}, 0
|
| 445 |
+
self._held_prev = None
|
| 446 |
+
self.table0 = dict(pos=self.table_pos().tolist(), yaw=self.table_yaw())
|
| 447 |
+
n = len(BOTTLES)
|
| 448 |
+
self.mon = dict(state=[False] * n, raw_since=[0] * n, ever=[False] * n, lost=[False] * n, events=[],
|
| 449 |
+
lost_cause=[None] * n, last_robot=[None] * n, last_obj=[None] * n, last_release=None,
|
| 450 |
+
last_table_touch=-10 ** 6, rocked=False, rock_since=0, rocks=[], n_steps=0,
|
| 451 |
+
max_table_tilt_deg=0.0)
|
| 452 |
+
return self.sk
|
| 453 |
+
|
| 454 |
+
# ------------------------------------------------------------ geometry / predicates
|
| 455 |
+
def table_R(self):
|
| 456 |
+
return self.env.sim.data.body_xmat[self.tbid].reshape(3, 3).copy()
|
| 457 |
+
|
| 458 |
+
def table_pos(self):
|
| 459 |
+
return self.env.sim.data.body_xpos[self.tbid].copy()
|
| 460 |
+
|
| 461 |
+
def table_yaw(self):
|
| 462 |
+
R = self.table_R()
|
| 463 |
+
return float(np.arctan2(R[1, 0], R[0, 0]))
|
| 464 |
+
|
| 465 |
+
def table_tilt(self):
|
| 466 |
+
return float(np.arccos(np.clip(self.table_R()[2, 2], -1, 1)))
|
| 467 |
+
|
| 468 |
+
def top_point(self, local_xy):
|
| 469 |
+
"""world position of a point on the table's top surface (table frame xy)"""
|
| 470 |
+
return self.table_pos() + self.table_R() @ np.array([local_xy[0], local_xy[1], TABLE_H / 2])
|
| 471 |
+
|
| 472 |
+
def spot_local(self, colour):
|
| 473 |
+
sx, sy = CORNERS[self.inst["spot_of"][colour]]
|
| 474 |
+
return np.array([sx * SPOT_O, sy * SPOT_O])
|
| 475 |
+
|
| 476 |
+
def spot_world(self, colour):
|
| 477 |
+
return self.top_point(self.spot_local(colour))
|
| 478 |
+
|
| 479 |
+
def top_z_at(self, xy):
|
| 480 |
+
"""z of the table's top plane above world point xy"""
|
| 481 |
+
R, p = self.table_R(), self.table_pos()
|
| 482 |
+
n = R[:, 2]
|
| 483 |
+
c = p + n * TABLE_H / 2
|
| 484 |
+
return float(c[2] - (n[0] * (xy[0] - c[0]) + n[1] * (xy[1] - c[1])) / max(n[2], 1e-6))
|
| 485 |
+
|
| 486 |
+
def over_table(self, xy):
|
| 487 |
+
loc = self.table_R().T @ (np.array([xy[0], xy[1], self.table_pos()[2]]) - self.table_pos())
|
| 488 |
+
return abs(loc[0]) < TOP_HW and abs(loc[1]) < TOP_HW
|
| 489 |
+
|
| 490 |
+
def bR(self, b):
|
| 491 |
+
return self.env.sim.data.body_xmat[self.bbid[b]].reshape(3, 3).copy()
|
| 492 |
+
|
| 493 |
+
def bpos(self, b):
|
| 494 |
+
return self.env.sim.data.body_xpos[self.bbid[b]].copy()
|
| 495 |
+
|
| 496 |
+
def foot(self, b):
|
| 497 |
+
"""world position of the centre of the bottle's bottom face"""
|
| 498 |
+
return self.bpos(b) - self.bR(b)[:, 2] * H_TOT / 2
|
| 499 |
+
|
| 500 |
+
def tilt(self, b):
|
| 501 |
+
return float(np.arccos(np.clip(self.bR(b)[2, 2], -1.0, 1.0)))
|
| 502 |
+
|
| 503 |
+
def cap_xyz(self, b):
|
| 504 |
+
return self.env.sim.data.geom_xpos[self.cap_gid[b]].copy()
|
| 505 |
+
|
| 506 |
+
def held(self, b):
|
| 507 |
+
return self.sk is not None and self.sk.holding(b)
|
| 508 |
+
|
| 509 |
+
def offset(self, i):
|
| 510 |
+
"""bottle i's foot centre relative to its spot centre, in the table frame (x forward-back, y left-right), and
|
| 511 |
+
the height of its bottom above the table top"""
|
| 512 |
+
b, c = BOTTLES[i], COLOURS[i]
|
| 513 |
+
loc = self.table_R().T @ (self.foot(b) - self.table_pos())
|
| 514 |
+
return loc[:2] - self.spot_local(c), float(loc[2] - TABLE_H / 2)
|
| 515 |
+
|
| 516 |
+
def on_spot(self, i, extra=0.0):
|
| 517 |
+
b = BOTTLES[i]
|
| 518 |
+
if self.tilt(b) > TILT_OK + (np.radians(2.0) if extra else 0.0):
|
| 519 |
+
return False
|
| 520 |
+
off, dz = self.offset(i)
|
| 521 |
+
if abs(off[0]) > TOL_X + extra or abs(off[1]) > TOL_Y + extra or abs(dz) > ON_TOP:
|
| 522 |
+
return False
|
| 523 |
+
return not self.held(b)
|
| 524 |
+
|
| 525 |
+
def stages(self):
|
| 526 |
+
return [self.on_spot(i) for i in range(len(BOTTLES))]
|
| 527 |
+
|
| 528 |
+
def table_ok(self):
|
| 529 |
+
p0 = np.asarray(self.table0["pos"])
|
| 530 |
+
moved = float(np.linalg.norm(self.table_pos()[:2] - p0[:2]))
|
| 531 |
+
dyaw = abs(_ang(self.table_yaw() - self.table0["yaw"]))
|
| 532 |
+
return bool(moved <= TABLE_MOVE_TOL and dyaw <= TABLE_YAW_TOL and self.table_tilt() <= TABLE_TILT_MAX), moved, dyaw
|
| 533 |
+
|
| 534 |
+
def low_corner(self):
|
| 535 |
+
"""robot-centric name of the table corner that is lowest (after a rock: the corner over the short leg)"""
|
| 536 |
+
zs = {k: self.top_point([sx * TOP_HW, sy * TOP_HW])[2] for k, (sx, sy) in enumerate(CORNERS)}
|
| 537 |
+
return CORNER_NAME[CORNERS[min(zs, key=zs.get)]]
|
| 538 |
+
|
| 539 |
+
# ------------------------------------------------------------ monitor
|
| 540 |
+
def monitor_step(self):
|
| 541 |
+
mon = self.mon
|
| 542 |
+
if mon is None or self.sk is None:
|
| 543 |
+
return
|
| 544 |
+
mon["n_steps"] += 1
|
| 545 |
+
t = int(self.sk.n_steps)
|
| 546 |
+
rob, obj, tbl = dict(self._sub_rob), dict(self._sub_obj), self._sub_tbl
|
| 547 |
+
self._sub_rob, self._sub_obj, self._sub_tbl = {}, {}, 0
|
| 548 |
+
gstate = "open" if self.sk.grip < 0 else "closed"
|
| 549 |
+
held_now = None
|
| 550 |
+
for c, b in zip(COLOURS, BOTTLES):
|
| 551 |
+
if gstate == "closed" and self.held(b):
|
| 552 |
+
held_now = c
|
| 553 |
+
for i, part in rob.items():
|
| 554 |
+
if COLOURS[i] != held_now:
|
| 555 |
+
mon["last_robot"][i] = [{1: "finger", 2: "hand", 3: "arm"}[part], t, gstate]
|
| 556 |
+
for i, j in obj.items():
|
| 557 |
+
mon["last_obj"][i] = [COLOURS[j], t]
|
| 558 |
+
if tbl:
|
| 559 |
+
mon["last_table_touch"] = t
|
| 560 |
+
if held_now is None and self._held_prev is not None: # the gripper has just let go of a bottle
|
| 561 |
+
mon["last_release"] = [self._held_prev, t]
|
| 562 |
+
self._held_prev = held_now
|
| 563 |
+
tl = self.table_tilt()
|
| 564 |
+
mon["max_table_tilt_deg"] = max(mon["max_table_tilt_deg"], round(float(np.degrees(tl)), 2))
|
| 565 |
+
if mon["n_steps"] % 2:
|
| 566 |
+
return
|
| 567 |
+
# ---- table rock detector (debounced)
|
| 568 |
+
want = tl > ROCK_ON if not mon["rocked"] else tl > ROCK_OFF
|
| 569 |
+
if want != mon["rocked"]:
|
| 570 |
+
mon["rock_since"] += 2
|
| 571 |
+
if mon["rock_since"] >= 4:
|
| 572 |
+
mon["rocked"] = want
|
| 573 |
+
mon["rock_since"] = 0
|
| 574 |
+
self._rock_event(want, t - 3)
|
| 575 |
+
else:
|
| 576 |
+
mon["rock_since"] = 0
|
| 577 |
+
for r in mon["rocks"]:
|
| 578 |
+
if not r.get("closed") and t - r["step"] > FELL_WINDOW:
|
| 579 |
+
self._close_rock(r)
|
| 580 |
+
# ---- stage predicates
|
| 581 |
+
for i in range(len(BOTTLES)):
|
| 582 |
+
b = BOTTLES[i]
|
| 583 |
+
raw = self.on_spot(i, HYST if mon["state"][i] else 0.0)
|
| 584 |
+
if raw == mon["state"][i]:
|
| 585 |
+
mon["raw_since"][i] = 0
|
| 586 |
+
continue
|
| 587 |
+
mon["raw_since"][i] += 2
|
| 588 |
+
if mon["raw_since"][i] < DEBOUNCE:
|
| 589 |
+
continue
|
| 590 |
+
mon["state"][i] = raw
|
| 591 |
+
mon["raw_since"][i] = 0
|
| 592 |
+
t0 = int(t - DEBOUNCE + 1)
|
| 593 |
+
if raw:
|
| 594 |
+
restored = mon["lost"][i]
|
| 595 |
+
e = dict(stage=COLOURS[i], event="restored" if restored else "achieved", step=t0)
|
| 596 |
+
if restored:
|
| 597 |
+
e["after"] = mon["lost_cause"][i]
|
| 598 |
+
mon["events"].append(e)
|
| 599 |
+
mon["ever"][i] = True
|
| 600 |
+
else:
|
| 601 |
+
mon["lost"][i] = True
|
| 602 |
+
cause = self._cause(i, t0)
|
| 603 |
+
mon["lost_cause"][i] = cause
|
| 604 |
+
off, dz = self.offset(i)
|
| 605 |
+
mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t0, cause=cause,
|
| 606 |
+
tilt_deg=round(float(np.degrees(self.tilt(b))), 1),
|
| 607 |
+
offset_cm=[round(100 * float(v), 1) for v in off]))
|
| 608 |
+
|
| 609 |
+
def _rock_event(self, down, t):
|
| 610 |
+
mon = self.mon
|
| 611 |
+
rel = mon["last_release"]
|
| 612 |
+
e = dict(event="table_rocked" if down else "table_rocked_back", step=int(t),
|
| 613 |
+
table_tilt_deg=round(float(np.degrees(self.table_tilt())), 2), low_corner=self.low_corner(),
|
| 614 |
+
released=rel[0] if rel is not None and t - rel[1] <= 40 else None,
|
| 615 |
+
robot_touched_table=bool(t - mon["last_table_touch"] <= 20),
|
| 616 |
+
standing=[COLOURS[i] for i in range(len(BOTTLES)) if mon["state"][i]])
|
| 617 |
+
# the cheap explanation would be "my hand bumped them": which of the standing bottles did the robot touch in
|
| 618 |
+
# the 2 s before the rock (should be none)
|
| 619 |
+
e["robot_touched_before"] = [COLOURS[i] for i in range(len(BOTTLES)) if mon["state"][i] and
|
| 620 |
+
mon["last_robot"][i] is not None and t - mon["last_robot"][i][1] <= 40]
|
| 621 |
+
mon["events"].append(e)
|
| 622 |
+
mon["rocks"].append(dict(step=int(t), down=bool(down), standing=list(e["standing"]), event=e))
|
| 623 |
+
|
| 624 |
+
def _close_rock(self, r):
|
| 625 |
+
"""FELL_WINDOW after a rock: which of the bottles that stood on their spots fell, and did the robot touch any
|
| 626 |
+
of them after the rock began (a falling bottle hitting the open fingers)"""
|
| 627 |
+
r["closed"] = True
|
| 628 |
+
mon = self.mon
|
| 629 |
+
fell, touched = [], []
|
| 630 |
+
for c in r["standing"]:
|
| 631 |
+
i = COLOURS.index(c)
|
| 632 |
+
if self.tilt(BOTTLES[i]) > np.radians(30) or not mon["state"][i]:
|
| 633 |
+
fell.append(c)
|
| 634 |
+
lr = mon["last_robot"][i]
|
| 635 |
+
if lr is not None and lr[1] >= r["step"]:
|
| 636 |
+
touched.append(c)
|
| 637 |
+
r["event"]["fell"] = fell
|
| 638 |
+
r["event"]["robot_touched_while_falling"] = touched
|
| 639 |
+
r["fell"] = fell
|
| 640 |
+
|
| 641 |
+
def _cause(self, i, t, window=60):
|
| 642 |
+
if self.held(BOTTLES[i]):
|
| 643 |
+
return "picked_up"
|
| 644 |
+
mon = self.mon
|
| 645 |
+
for r in reversed(mon["rocks"]):
|
| 646 |
+
if 0 <= t - r["step"] <= FELL_WINDOW + 10 and COLOURS[i] in r["standing"]:
|
| 647 |
+
return "table_rocked" if r["down"] else "table_rocked_back"
|
| 648 |
+
lr, lo = mon["last_robot"][i], mon["last_obj"][i]
|
| 649 |
+
cands = []
|
| 650 |
+
if lr is not None and t - lr[1] <= window:
|
| 651 |
+
cands.append((lr[1], f"robot_{lr[0]}"))
|
| 652 |
+
if lo is not None and t - lo[1] <= window:
|
| 653 |
+
cands.append((lo[1] - 30, "bottle:" + lo[0]))
|
| 654 |
+
return max(cands)[1] if cands else "other"
|
| 655 |
+
|
| 656 |
+
def _finalize_monitor(self, raw):
|
| 657 |
+
mon = self.mon
|
| 658 |
+
if mon is None:
|
| 659 |
+
return
|
| 660 |
+
for r in mon["rocks"]:
|
| 661 |
+
if not r.get("closed"):
|
| 662 |
+
self._close_rock(r)
|
| 663 |
+
t = int(self.sk.n_steps)
|
| 664 |
+
for i in range(len(BOTTLES)):
|
| 665 |
+
if raw[i] == mon["state"][i]:
|
| 666 |
+
continue
|
| 667 |
+
mon["state"][i] = raw[i]
|
| 668 |
+
if raw[i]:
|
| 669 |
+
restored = mon["lost"][i]
|
| 670 |
+
e = dict(stage=COLOURS[i], event="restored" if restored else "achieved", step=t, final=True)
|
| 671 |
+
if restored:
|
| 672 |
+
e["after"] = mon["lost_cause"][i]
|
| 673 |
+
mon["events"].append(e)
|
| 674 |
+
mon["ever"][i] = True
|
| 675 |
+
else:
|
| 676 |
+
mon["lost"][i] = True
|
| 677 |
+
cause = self._cause(i, t, window=10 ** 6)
|
| 678 |
+
mon["lost_cause"][i] = cause
|
| 679 |
+
mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t, cause=cause, final=True))
|
| 680 |
+
|
| 681 |
+
# ------------------------------------------------------------ outcome
|
| 682 |
+
def _touching(self):
|
| 683 |
+
d = self.env.sim.data
|
| 684 |
+
for j in range(d.ncon):
|
| 685 |
+
c = d.contact[j]
|
| 686 |
+
if (self.owner[c.geom1] >= 0 and self.part[c.geom2]) or (self.owner[c.geom2] >= 0 and self.part[c.geom1]):
|
| 687 |
+
return True
|
| 688 |
+
return False
|
| 689 |
+
|
| 690 |
+
def outcome(self, inst):
|
| 691 |
+
sk = self.sk
|
| 692 |
+
sk.hold(10)
|
| 693 |
+
p0 = {b: self.bpos(b) for b in BOTTLES}
|
| 694 |
+
t0 = self.table_pos()
|
| 695 |
+
touching = False
|
| 696 |
+
for _ in range(20):
|
| 697 |
+
sk.hold(1)
|
| 698 |
+
touching = touching or self._touching()
|
| 699 |
+
moved = max([float(np.linalg.norm(self.bpos(b) - p0[b])) for b in BOTTLES] +
|
| 700 |
+
[float(np.linalg.norm(self.table_pos() - t0))])
|
| 701 |
+
static = moved < 0.003
|
| 702 |
+
raw = self.stages()
|
| 703 |
+
self._finalize_monitor(raw)
|
| 704 |
+
held = [COLOURS[i] for i, b in enumerate(BOTTLES) if self.held(b)]
|
| 705 |
+
tok, tmoved, tyaw = self.table_ok()
|
| 706 |
+
mon = self.mon
|
| 707 |
+
ev = list(mon["events"])
|
| 708 |
+
rocks = [r for r in mon["rocks"] if r["down"]]
|
| 709 |
+
damaging = [r for r in mon["rocks"] if r.get("fell")]
|
| 710 |
+
n_reg = sum(e.get("event") == "lost" and e.get("cause") != "picked_up" for e in ev)
|
| 711 |
+
n_lost = sum(e.get("event") == "lost" for e in ev)
|
| 712 |
+
n_res = sum(e.get("event") == "restored" and e.get("after") != "picked_up" for e in ev)
|
| 713 |
+
success = bool(all(raw) and static and not held and not touching and tok)
|
| 714 |
+
tilted = [i for i in range(len(BOTTLES)) if self.tilt(BOTTLES[i]) > TILT_OK and COLOURS[i] not in held]
|
| 715 |
+
ever = mon["ever"]
|
| 716 |
+
fell_by_rock = sorted({c for r in damaging for c in r["fell"]})
|
| 717 |
+
if success:
|
| 718 |
+
failure = "none"
|
| 719 |
+
elif not tok:
|
| 720 |
+
failure = "table_moved"
|
| 721 |
+
elif held:
|
| 722 |
+
failure = "held"
|
| 723 |
+
elif tilted:
|
| 724 |
+
failure = "toppled_by_rock" if any(COLOURS[i] in fell_by_rock for i in tilted) else "toppled"
|
| 725 |
+
elif not all(raw):
|
| 726 |
+
failure = "not_on_spot"
|
| 727 |
+
elif touching:
|
| 728 |
+
failure = "touching"
|
| 729 |
+
else:
|
| 730 |
+
failure = "not_static"
|
| 731 |
+
parts = []
|
| 732 |
+
if success:
|
| 733 |
+
parts.append("Every bottle stands upright on the spot of its colour.")
|
| 734 |
+
for i in range(len(BOTTLES)):
|
| 735 |
+
if raw[i]:
|
| 736 |
+
continue
|
| 737 |
+
c, b = COLOURS[i], BOTTLES[i]
|
| 738 |
+
if c in held:
|
| 739 |
+
parts.append(f"The {c} bottle is still held by the gripper.")
|
| 740 |
+
continue
|
| 741 |
+
off, dz = self.offset(i)
|
| 742 |
+
tl = float(np.degrees(self.tilt(b)))
|
| 743 |
+
on_small = abs(dz) < 0.05 and max(abs(off + self.spot_local(c))) < TOP_HW + 0.02
|
| 744 |
+
if tl > np.degrees(TILT_OK):
|
| 745 |
+
txt = (f"The {c} bottle lies on its side on the {'small' if on_small else 'big'} table" if tl > 45 else
|
| 746 |
+
f"The {c} bottle leans {tl:.0f} degrees") + "."
|
| 747 |
+
elif abs(dz) > ON_TOP:
|
| 748 |
+
txt = f"The {c} bottle is not on the small table."
|
| 749 |
+
else:
|
| 750 |
+
txt = f"The {c} bottle stands {_fb(off[0])} and {_lr(off[1])} of its spot's centre, not on its spot."
|
| 751 |
+
if ever[i] and c in fell_by_rock:
|
| 752 |
+
txt += " It had stood on its spot and fell when the small table rocked."
|
| 753 |
+
elif ever[i]:
|
| 754 |
+
txt += " It had stood on its spot earlier."
|
| 755 |
+
parts.append(txt)
|
| 756 |
+
if not tok:
|
| 757 |
+
parts.append(f"The small table was moved ({100 * tmoved:.1f} cm, {np.degrees(tyaw):.0f} degrees).")
|
| 758 |
+
elif not success and all(raw):
|
| 759 |
+
if touching:
|
| 760 |
+
parts.append("The gripper is still touching a bottle.")
|
| 761 |
+
elif not static:
|
| 762 |
+
parts.append("Something was still moving.")
|
| 763 |
+
if rocks:
|
| 764 |
+
r = rocks[0]["event"]
|
| 765 |
+
txt = (f"When the {r['released']} bottle was set down, the small table rocked down onto its "
|
| 766 |
+
f"{r['low_corner']} leg" if r.get("released") else
|
| 767 |
+
f"The small table rocked down onto its {r['low_corner']} leg")
|
| 768 |
+
fl = r.get("fell", [])
|
| 769 |
+
txt += (" and the " + " and ".join(fl) + f" bottle{'s' if len(fl) > 1 else ''} standing on it fell over."
|
| 770 |
+
if fl else ".")
|
| 771 |
+
txt += f" That leg is {100 * float(inst['short_h']):.1f} cm shorter than the other three."
|
| 772 |
+
parts.append(txt)
|
| 773 |
+
trap = bool(damaging)
|
| 774 |
+
return dict(success=success, stages={COLOURS[i]: bool(raw[i]) for i in range(len(BOTTLES))}, events=ev,
|
| 775 |
+
n_regressions=int(n_reg), n_lost=int(n_lost), n_restored=int(n_res), n_rocks=len(rocks),
|
| 776 |
+
rocked=bool(rocks), trap_fired=trap, recovered_in_attempt=bool(trap and success),
|
| 777 |
+
fell_by_rock=fell_by_rock, failure=failure, held=held, touching=bool(touching),
|
| 778 |
+
static=bool(static), table_ok=bool(tok), table_moved_cm=round(100 * tmoved, 2),
|
| 779 |
+
table_tilt_deg=round(float(np.degrees(self.table_tilt())), 2),
|
| 780 |
+
max_table_tilt_deg=mon["max_table_tilt_deg"],
|
| 781 |
+
offsets_cm={COLOURS[i]: [round(100 * float(v), 2) for v in self.offset(i)[0]] for i in range(4)},
|
| 782 |
+
tilts_deg={COLOURS[i]: round(float(np.degrees(self.tilt(BOTTLES[i]))), 1) for i in range(4)},
|
| 783 |
+
heavy=inst["heavy"], short_corner=inst["short_corner"], detail=" ".join(parts))
|
| 784 |
+
|
| 785 |
+
# ------------------------------------------------------------ scripted primitives (move_to + gripper only)
|
| 786 |
+
def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300):
|
| 787 |
+
return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
|
| 788 |
+
|
| 789 |
+
def _lift_to(self, z, speed=0.2):
|
| 790 |
+
cur = self.sk.eef_pos()
|
| 791 |
+
if cur[2] < TZ + z - 0.005:
|
| 792 |
+
self._go([cur[0], cur[1], TZ + z], speed=speed)
|
| 793 |
+
|
| 794 |
+
def _settle(self, b, max_checks=25):
|
| 795 |
+
d = self.env.sim.data
|
| 796 |
+
da = self.dof[b]
|
| 797 |
+
for _ in range(max_checks):
|
| 798 |
+
if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2:
|
| 799 |
+
return
|
| 800 |
+
self.sk.hold(2)
|
| 801 |
+
|
| 802 |
+
def upright(self, b):
|
| 803 |
+
return self.tilt(b) < np.radians(20)
|
| 804 |
+
|
| 805 |
+
def pick_neck(self, b, z_carry=Z_CARRY, yaw=0.0, v=0.2):
|
| 806 |
+
"""Sonnet-like top-down pick of a standing bottle: open, over it at carry height, straight down to the upper
|
| 807 |
+
neck, close, lift to carry height. Returns True if held."""
|
| 808 |
+
sk = self.sk
|
| 809 |
+
self._settle(b)
|
| 810 |
+
p = self.foot(b)
|
| 811 |
+
zg = p[2] + NECK_Z[1] - GRASP_NECK
|
| 812 |
+
sk.set_gripper(False, steps=8)
|
| 813 |
+
self._lift_to(z_carry)
|
| 814 |
+
self._go([p[0], p[1], TZ + z_carry], yaw=yaw, speed=v)
|
| 815 |
+
self._go([p[0], p[1], zg + 0.02], speed=0.12)
|
| 816 |
+
self._go([p[0], p[1], zg], speed=0.04, tol=0.003, max_steps=150)
|
| 817 |
+
sk.set_gripper(True, steps=15)
|
| 818 |
+
self._go([p[0], p[1], TZ + z_carry], speed=0.12)
|
| 819 |
+
sk.hold(5)
|
| 820 |
+
if not self.held(b):
|
| 821 |
+
sk.set_gripper(False, steps=8)
|
| 822 |
+
return False
|
| 823 |
+
return True
|
| 824 |
+
|
| 825 |
+
def put_held(self, b, xy, gap, z_carry=Z_CARRY, yaw=None, v=0.2):
|
| 826 |
+
"""carry the held bottle so that its foot is over world xy, straight down until its bottom is `gap` above the
|
| 827 |
+
surface below, let go, lift"""
|
| 828 |
+
sk = self.sk
|
| 829 |
+
rel = self.foot(b)[:2] - sk.eef_pos()[:2]
|
| 830 |
+
q = np.asarray(xy, float) - rel
|
| 831 |
+
self._go([q[0], q[1], TZ + z_carry], yaw=yaw, speed=v)
|
| 832 |
+
sk.hold(10)
|
| 833 |
+
rel = self.foot(b)[:2] - sk.eef_pos()[:2] # a bottle hanging from its stopper swings while carried
|
| 834 |
+
q = np.asarray(xy, float) - rel
|
| 835 |
+
surf = self.top_z_at(xy) if self.over_table(xy) else TZ
|
| 836 |
+
dz = sk.eef_pos()[2] - self.foot(b)[2]
|
| 837 |
+
zr = surf + dz + gap
|
| 838 |
+
self._go([q[0], q[1], zr + 0.02], speed=0.10)
|
| 839 |
+
self._go([q[0], q[1], zr], speed=0.03, tol=0.003, max_steps=150)
|
| 840 |
+
sk.hold(4)
|
| 841 |
+
sk.set_gripper(False, steps=12)
|
| 842 |
+
cur = sk.eef_pos()
|
| 843 |
+
self._go([cur[0], cur[1], cur[2] + 0.06], speed=0.10)
|
| 844 |
+
self._go([cur[0], cur[1], TZ + z_carry], speed=0.2)
|
| 845 |
+
sk.hold(3)
|
| 846 |
+
|
| 847 |
+
def surface_z(self, xy):
|
| 848 |
+
return self.top_z_at(xy) if self.over_table(xy) else TZ
|
| 849 |
+
|
| 850 |
+
def pick_stopper(self, b, v=0.15):
|
| 851 |
+
"""grasp a lying (or leaning) bottle by its round stopper from above, fingers across the bottle's axis, lift it
|
| 852 |
+
until it hangs free. The fingertips stay >= 4 mm above the surface under the stopper: pressing the raised half
|
| 853 |
+
of the rocked table rocks it back (measured), and the knock when it comes down again topples standing bottles.
|
| 854 |
+
Returns True if held."""
|
| 855 |
+
sk = self.sk
|
| 856 |
+
self._settle(b)
|
| 857 |
+
for _ in range(2):
|
| 858 |
+
k, zg, yaw = self.stopper_grasp(b) # fingers across the bottle's axis
|
| 859 |
+
sk.set_gripper(False, steps=8)
|
| 860 |
+
self._lift_to(Z_HANG)
|
| 861 |
+
self._go([k[0], k[1], TZ + Z_HANG], yaw=yaw, speed=v)
|
| 862 |
+
sk.hold(5)
|
| 863 |
+
k, zg, _ = self.stopper_grasp(b)
|
| 864 |
+
self._go([k[0], k[1], zg + 0.03], speed=0.10)
|
| 865 |
+
self._go([k[0], k[1], zg], speed=0.03, tol=0.003, max_steps=120)
|
| 866 |
+
sk.set_gripper(True, steps=15)
|
| 867 |
+
if not self.held(b):
|
| 868 |
+
sk.set_gripper(False, steps=8)
|
| 869 |
+
self._go([k[0], k[1], zg + 0.08], speed=0.1)
|
| 870 |
+
continue
|
| 871 |
+
self._go([k[0], k[1], zg + 0.05], speed=0.05)
|
| 872 |
+
self._go([k[0], k[1], TZ + Z_HANG], speed=0.10)
|
| 873 |
+
sk.hold(20)
|
| 874 |
+
return True
|
| 875 |
+
return False
|
| 876 |
+
|
| 877 |
+
# gripper footprint (measured, t8_hand): the hand's collision hull is a slab 20 cm along the finger axis and ~4 cm
|
| 878 |
+
# across, from 3 cm above the grasp point up; open fingers 3.9-6.6 cm out along the finger axis, from 1 cm below
|
| 879 |
+
# the grasp point to 4.5 cm above it
|
| 880 |
+
HAND_U, HAND_V, HAND_Z0 = 0.100, (-0.018, 0.024), 0.03
|
| 881 |
+
FING_U, FING_V, FING_Z = (0.039, 0.066), (-0.009, 0.013), (-0.010, 0.045)
|
| 882 |
+
# wrist and forearm (t16_arm, measured at low grasps): lowest point above the grasp point vs the distance from the
|
| 883 |
+
# grasp point towards the robot base; they span ~13 cm to either side of that line
|
| 884 |
+
ARM_D = (-0.05, 0.05, 0.10, 0.15, 0.20)
|
| 885 |
+
ARM_Z = (0.097, 0.100, 0.155, 0.185, 0.31)
|
| 886 |
+
ARM_LAT = 0.13
|
| 887 |
+
|
| 888 |
+
def _footprint(self, q, yaw):
|
| 889 |
+
"""sample points (xy) of the hand slab and of the open fingers for a grasp at q with gripper yaw `yaw`"""
|
| 890 |
+
a = np.array([-np.sin(yaw), np.cos(yaw)]) # finger axis
|
| 891 |
+
c = np.array([np.cos(yaw), np.sin(yaw)])
|
| 892 |
+
hand = [q + u * a + v * c for u in np.linspace(-self.HAND_U, self.HAND_U, 21)
|
| 893 |
+
for v in np.linspace(*self.HAND_V, 5)]
|
| 894 |
+
fing = [q + sg * u * a + v * c for sg in (-1, 1) for u in np.linspace(*self.FING_U, 4)
|
| 895 |
+
for v in np.linspace(*self.FING_V, 3)]
|
| 896 |
+
return np.array(hand), np.array(fing)
|
| 897 |
+
|
| 898 |
+
def grasp_clearance(self, q, zg, yaw, ignore=()):
|
| 899 |
+
"""smallest horizontal clearance (m) between the hand / open fingers of a grasp at (q, zg) and any standing
|
| 900 |
+
bottle (other than `ignore`) or the small table; negative = collision"""
|
| 901 |
+
q = np.asarray(q, float)[:2]
|
| 902 |
+
hand, fing = self._footprint(q, yaw)
|
| 903 |
+
best = 1.0
|
| 904 |
+
for b in BOTTLES:
|
| 905 |
+
if b in ignore or self.held(b) or self.tilt(b) > np.radians(30):
|
| 906 |
+
continue
|
| 907 |
+
p = self.foot(b)[:2]
|
| 908 |
+
top = self.foot(b)[2] + H_TOT
|
| 909 |
+
r = RB * 1.42
|
| 910 |
+
if top > zg + self.HAND_Z0:
|
| 911 |
+
best = min(best, float(np.min(np.linalg.norm(hand - p, axis=1))) - r)
|
| 912 |
+
best = min(best, float(np.min(np.linalg.norm(fing - p, axis=1))) - r)
|
| 913 |
+
# the wrist / forearm sloping back towards the robot base over a tall standing bottle
|
| 914 |
+
ub = np.array([-0.66, 0.0]) - q
|
| 915 |
+
ub /= max(float(np.linalg.norm(ub)), 1e-6)
|
| 916 |
+
along, lat = float((p - q) @ ub), float((p - q) @ np.array([-ub[1], ub[0]]))
|
| 917 |
+
if self.ARM_D[0] <= along <= self.ARM_D[-1] and abs(lat) < self.ARM_LAT + r:
|
| 918 |
+
if top > zg + float(np.interp(along, self.ARM_D, self.ARM_Z)) - 0.01:
|
| 919 |
+
best = min(best, -0.01)
|
| 920 |
+
# the small table's top plate (and legs) when the grasp is below its top surface
|
| 921 |
+
R, P = self.table_R(), self.table_pos()
|
| 922 |
+
ztop = P[2] + TABLE_H / 2
|
| 923 |
+
for pts, z0, z1 in ((hand, zg + self.HAND_Z0, zg + 0.13), (fing, zg + self.FING_Z[0], zg + self.FING_Z[1])):
|
| 924 |
+
if z0 > ztop + 0.003:
|
| 925 |
+
continue
|
| 926 |
+
loc = (pts - P[:2]) @ R[:2, :2]
|
| 927 |
+
if z1 > ztop - TOP_T: # the plate's height band
|
| 928 |
+
d = np.maximum(np.abs(loc) - TOP_HW, 0.0)
|
| 929 |
+
inside = np.all(np.abs(loc) < TOP_HW, axis=1)
|
| 930 |
+
dist = np.where(inside, -0.01, np.linalg.norm(d, axis=1))
|
| 931 |
+
best = min(best, float(np.min(dist)))
|
| 932 |
+
return best
|
| 933 |
+
|
| 934 |
+
def stopper_grasp(self, b):
|
| 935 |
+
"""(xy, z, yaw) of the stopper grasp of a lying bottle: fingers across its axis, fingertips >= 4 mm above the
|
| 936 |
+
surface below"""
|
| 937 |
+
k = self.cap_xyz(b)
|
| 938 |
+
ax = self.bR(b)[:2, 2]
|
| 939 |
+
yaw = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else self.sk.yaw
|
| 940 |
+
zg = max(float(k[2]), self.surface_z(k[:2]) + envs.FINGERTIP_BELOW_SITE + 0.004)
|
| 941 |
+
return k[:2], zg, yaw
|
| 942 |
+
|
| 943 |
+
def body_grasp(self, b, along=None):
|
| 944 |
+
"""(xy, z, yaw) of a grasp across a lying bottle's body, `along` m from its bottom (default: the middle)"""
|
| 945 |
+
R = self.bR(b)
|
| 946 |
+
a = HF + (HB - HF) / 2 if along is None else float(along)
|
| 947 |
+
c = self.foot(b) + R[:, 2] * a
|
| 948 |
+
ax = R[:2, 2]
|
| 949 |
+
yaw = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else self.sk.yaw
|
| 950 |
+
zg = max(float(c[2]), self.surface_z(c[:2]) + envs.FINGERTIP_BELOW_SITE + 0.004)
|
| 951 |
+
return c[:2], zg, yaw
|
| 952 |
+
|
| 953 |
+
def staging_spot(self, b):
|
| 954 |
+
"""a free place on the main table to lay a fallen bottle down: far from the small table and the other bottles,
|
| 955 |
+
within the arm's comfortable reach"""
|
| 956 |
+
tx, ty = self.table_pos()[:2]
|
| 957 |
+
best, bq = -1.0, None
|
| 958 |
+
for x in np.arange(tx - 0.30, tx + 0.06, 0.03):
|
| 959 |
+
for y in np.arange(ty - 0.30, ty + 0.31, 0.03):
|
| 960 |
+
# within reach, and >= 14 cm inside the main table's edges (it spans x, y = +-0.5, +-0.6): a bottle laid
|
| 961 |
+
# down too close to the near edge rolled off onto the floor (measured)
|
| 962 |
+
if np.hypot(x + 0.66, y) > 0.66 or np.hypot(x + 0.66, y) < 0.33 or x < -0.36 or abs(y) > 0.46:
|
| 963 |
+
continue
|
| 964 |
+
loc = self.table_R()[:2, :2].T @ (np.array([x, y]) - np.array([tx, ty]))
|
| 965 |
+
dt = float(np.linalg.norm(np.maximum(np.abs(loc) - TOP_HW, 0.0)))
|
| 966 |
+
if np.all(np.abs(loc) < TOP_HW):
|
| 967 |
+
continue
|
| 968 |
+
do = min([float(np.linalg.norm(self.foot(o)[:2] - [x, y])) for o in BOTTLES if o != b] +
|
| 969 |
+
[float(np.linalg.norm(self.cap_xyz(o)[:2] - [x, y])) for o in BOTTLES if o != b])
|
| 970 |
+
sc = min(dt - 0.10, do - 0.14) # the bottle lies ~16 cm long around the point
|
| 971 |
+
if sc > best and min(self.grasp_clearance([x, y], TZ + 0.016, yw, ignore=(b,))
|
| 972 |
+
for yw in (0.0, np.pi / 2)) > 0.01:
|
| 973 |
+
best, bq = sc, np.array([x, y])
|
| 974 |
+
return bq
|
| 975 |
+
|
| 976 |
+
def stage(self, b, v=0.12):
|
| 977 |
+
"""the stopper of a fallen bottle cannot be reached: grasp its body at a point where the hand is clear (the
|
| 978 |
+
bottle then hangs from the grasp), carry it to free space on the main table, let it down there so that it falls
|
| 979 |
+
over away from everything. Returns True if it was moved."""
|
| 980 |
+
sk = self.sk
|
| 981 |
+
for along in (0.055, 0.035, 0.075, 0.015, 0.095):
|
| 982 |
+
q, zg, yaw = self.body_grasp(b, along)
|
| 983 |
+
if self.grasp_clearance(q, zg, yaw, ignore=(b,)) >= 0.004:
|
| 984 |
+
break
|
| 985 |
+
else:
|
| 986 |
+
return False
|
| 987 |
+
dst = self.staging_spot(b)
|
| 988 |
+
if dst is None:
|
| 989 |
+
return False
|
| 990 |
+
sk.set_gripper(False, steps=8)
|
| 991 |
+
self._lift_to(Z_CARRY)
|
| 992 |
+
self._go([q[0], q[1], TZ + Z_CARRY], yaw=yaw, speed=v)
|
| 993 |
+
self._go([q[0], q[1], zg + 0.03], speed=0.10)
|
| 994 |
+
self._go([q[0], q[1], zg], speed=0.03, tol=0.003, max_steps=120)
|
| 995 |
+
sk.set_gripper(True, steps=15)
|
| 996 |
+
if not self.held(b):
|
| 997 |
+
sk.set_gripper(False, steps=8)
|
| 998 |
+
self._go([q[0], q[1], TZ + Z_CARRY], speed=0.1)
|
| 999 |
+
return False
|
| 1000 |
+
self._go([q[0], q[1], zg + 0.04], speed=0.05)
|
| 1001 |
+
self._go([q[0], q[1], TZ + Z_HANG], speed=0.10)
|
| 1002 |
+
sk.hold(15)
|
| 1003 |
+
self._go([dst[0], dst[1], TZ + Z_HANG], speed=0.10)
|
| 1004 |
+
sk.hold(15)
|
| 1005 |
+
drop = envs.obj_min_z(self.env, b) - (TZ + 0.012)
|
| 1006 |
+
cur = sk.eef_pos()
|
| 1007 |
+
self._go([cur[0], cur[1], cur[2] - drop], speed=0.08)
|
| 1008 |
+
sk.set_gripper(False, steps=12)
|
| 1009 |
+
cur = sk.eef_pos()
|
| 1010 |
+
self._go([cur[0], cur[1], TZ + Z_HANG], speed=0.15)
|
| 1011 |
+
self._settle(b, 40)
|
| 1012 |
+
return True
|
| 1013 |
+
|
| 1014 |
+
def restand(self, i, gap=CAREFUL_GAP, err=None):
|
| 1015 |
+
"""stand bottle i up again on its spot: if the stopper cannot be grasped without the hand touching a standing
|
| 1016 |
+
bottle or the small table, first lay the bottle down in free space; grasp the stopper, let the bottle hang,
|
| 1017 |
+
carry it over the spot, lower it until its bottom is `gap` above the table top, let go"""
|
| 1018 |
+
b, c = BOTTLES[i], COLOURS[i]
|
| 1019 |
+
q, zg, yaw = self.stopper_grasp(b)
|
| 1020 |
+
if self.grasp_clearance(q, zg, yaw, ignore=(b,)) < 0.005:
|
| 1021 |
+
self.stage(b)
|
| 1022 |
+
if not self.pick_stopper(b):
|
| 1023 |
+
return False
|
| 1024 |
+
tgt = self.spot_world(c)[:2] + (np.asarray(err, float) if err is not None else 0.0)
|
| 1025 |
+
self.put_held(b, tgt, gap, z_carry=Z_HANG, v=0.10)
|
| 1026 |
+
self._settle(b)
|
| 1027 |
+
return self.on_spot(i)
|
| 1028 |
+
|
| 1029 |
+
def place(self, i, gap, err=None, z_carry=Z_CARRY, yaw=0.0, v=0.2):
|
| 1030 |
+
"""one stage: pick bottle i (by the neck if it stands, by the stopper if it lies) and put it on its spot"""
|
| 1031 |
+
b, c = BOTTLES[i], COLOURS[i]
|
| 1032 |
+
tgt = self.spot_world(c)[:2] + (np.asarray(err, float) if err is not None else 0.0)
|
| 1033 |
+
if self.upright(b):
|
| 1034 |
+
if not self.pick_neck(b, z_carry=z_carry, yaw=yaw, v=v) and not self.pick_neck(b, z_carry=z_carry,
|
| 1035 |
+
yaw=yaw, v=v):
|
| 1036 |
+
return False
|
| 1037 |
+
self.put_held(b, tgt, gap, z_carry=z_carry, yaw=yaw, v=v)
|
| 1038 |
+
else:
|
| 1039 |
+
if not self.pick_stopper(b):
|
| 1040 |
+
return False
|
| 1041 |
+
self.put_held(b, tgt, gap, z_carry=Z_HANG, v=0.10)
|
| 1042 |
+
self._settle(b)
|
| 1043 |
+
return True
|
| 1044 |
+
|
| 1045 |
+
def repair_order(self, idx):
|
| 1046 |
+
"""bottles to fix: one standing upright off its spot first (it may be the heavy one: re-placing it rocks the
|
| 1047 |
+
table), then lying ones whose stopper is easiest to reach"""
|
| 1048 |
+
def key(j):
|
| 1049 |
+
b = BOTTLES[j]
|
| 1050 |
+
if self.upright(b):
|
| 1051 |
+
return (0, 0.0)
|
| 1052 |
+
q, zg, yaw = self.stopper_grasp(b)
|
| 1053 |
+
return (1, -self.grasp_clearance(q, zg, yaw, ignore=(b,)))
|
| 1054 |
+
return sorted(idx, key=key)
|
| 1055 |
+
|
| 1056 |
+
def fix(self, i, gap=CAREFUL_GAP):
|
| 1057 |
+
if self.upright(BOTTLES[i]):
|
| 1058 |
+
self.place(i, gap)
|
| 1059 |
+
else:
|
| 1060 |
+
self.restand(i, gap)
|
| 1061 |
+
|
| 1062 |
+
def check_and_repair(self, rounds=3, gap=CAREFUL_GAP):
|
| 1063 |
+
"""look at every bottle; stand up / re-place every one that is not on its spot"""
|
| 1064 |
+
for _ in range(rounds):
|
| 1065 |
+
bad = [i for i in range(4) if not self.on_spot(i)]
|
| 1066 |
+
if not bad:
|
| 1067 |
+
return True
|
| 1068 |
+
for i in self.repair_order(bad):
|
| 1069 |
+
if not self.on_spot(i):
|
| 1070 |
+
self.fix(i, gap)
|
| 1071 |
+
return all(self.stages())
|
| 1072 |
+
|
| 1073 |
+
def order(self, mode, rng=None, first=None):
|
| 1074 |
+
o = self._far_first(self.inst["spot_of"], self.inst["supply_side"], *self.inst["table_xy"])
|
| 1075 |
+
if mode == "near_first":
|
| 1076 |
+
o = o[::-1]
|
| 1077 |
+
elif mode == "random":
|
| 1078 |
+
o = [o[j] for j in rng.permutation(4)]
|
| 1079 |
+
if first is not None:
|
| 1080 |
+
o = [first] + [c for c in o if c != first]
|
| 1081 |
+
return [COLOURS.index(c) for c in o]
|
| 1082 |
+
|
| 1083 |
+
def execute(self, inst, params):
|
| 1084 |
+
rng = np.random.default_rng(params.get("noise_seed", 0))
|
| 1085 |
+
order = self.order(params.get("order", "far_first"), rng, params.get("first"))
|
| 1086 |
+
gap = params.get("gap") # None: random in NAIVE_GAP per placement
|
| 1087 |
+
bias = np.array([float(params.get("bias_x", 0.0)), 0.0])
|
| 1088 |
+
rand = float(params.get("rand", 0.0))
|
| 1089 |
+
for i in order:
|
| 1090 |
+
g = float(rng.uniform(*NAIVE_GAP)) if gap is None else float(gap)
|
| 1091 |
+
e = bias + (rng.uniform(-rand, rand, 2) if rand else 0.0)
|
| 1092 |
+
self.place(i, g, err=e, z_carry=params.get("z_carry", Z_CARRY), v=params.get("v", 0.2))
|
| 1093 |
+
if params.get("repair") == "each": # looks at all bottles after every step and stands fallen ones up
|
| 1094 |
+
for _ in range(2):
|
| 1095 |
+
bad = [j for j in range(4) if self.mon["ever"][j] and not self.on_spot(j)]
|
| 1096 |
+
for j in self.repair_order(bad):
|
| 1097 |
+
if not self.on_spot(j):
|
| 1098 |
+
self.fix(j)
|
| 1099 |
+
if params.get("check"):
|
| 1100 |
+
self.check_and_repair()
|
| 1101 |
+
self._lift_to(Z_CARRY)
|
| 1102 |
+
self.sk.hold(10)
|
| 1103 |
+
|
| 1104 |
+
# naive = Sonnet-like habits (lh_nudge_row / lh_bystander pilots): careful, far spots first, carries high, vertical
|
| 1105 |
+
# descent, releases 1-4 cm above the surface, places ~1-2 cm too far forward +- 0.6 cm, no special plan for the
|
| 1106 |
+
# table, does not look back at the bottles it has already put down
|
| 1107 |
+
def default_params(self, inst):
|
| 1108 |
+
return dict(order="far_first", gap=None, bias_x=float(inst["naive_bias_x"]), rand=NAIVE_RAND,
|
| 1109 |
+
noise_seed=int(inst["seed"]) * 13, repair=None, check=False)
|
| 1110 |
+
|
| 1111 |
+
def oracle_params(self, inst):
|
| 1112 |
+
"""knows the short leg: puts the heavy bottle on its corner first (the table rocks while nothing stands on it),
|
| 1113 |
+
sets the others down gently, checks at the end"""
|
| 1114 |
+
return dict(order="far_first", first=inst["heavy"], gap=CAREFUL_GAP, bias_x=0.0, rand=0.0, repair="each",
|
| 1115 |
+
check=True)
|
| 1116 |
+
|
| 1117 |
+
def adapt_params(self, inst, history):
|
| 1118 |
+
"""attempt >= 2: the bottle whose placement rocked the table (from the event of the failed attempt) first; the
|
| 1119 |
+
same imprecise habits otherwise; stands fallen bottles up and checks at the end"""
|
| 1120 |
+
first = None
|
| 1121 |
+
for h in history:
|
| 1122 |
+
for e in h["outcome"].get("events", []):
|
| 1123 |
+
if e.get("event") == "table_rocked" and e.get("released"):
|
| 1124 |
+
first = e["released"]
|
| 1125 |
+
break
|
| 1126 |
+
if first:
|
| 1127 |
+
break
|
| 1128 |
+
return dict(self.default_params(inst), first=first, repair="each", check=True)
|
| 1129 |
+
|
| 1130 |
+
def blind_params(self, inst, attempt, rng):
|
| 1131 |
+
"""the naive behaviour with a random order and random variation, no history, no look back"""
|
| 1132 |
+
return dict(self.default_params(inst), order="random", noise_seed=int(rng.integers(1 << 30)),
|
| 1133 |
+
z_carry=float(rng.uniform(0.40, 0.45)), v=float(rng.uniform(0.12, 0.25)),
|
| 1134 |
+
bias_x=float(rng.uniform(*NAIVE_BIAS)))
|
| 1135 |
+
|
| 1136 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 1137 |
+
"""oracle / naive: one attempt. adaptive: attempt 1 = naive + stands fallen bottles up after every step and checks
|
| 1138 |
+
at the end; attempts >= 2: the rocking bottle first. blind: naive with a random order.
|
| 1139 |
+
Extra kinds (controls): naive_heavy_first (naive habits, 1-4 cm drops, but the heavy bottle first),
|
| 1140 |
+
naive_repair (= adaptive's first attempt), naive_near_first, switch (order change only, no repair),
|
| 1141 |
+
oracle_noise (+-5 mm)."""
|
| 1142 |
+
k = k or self.max_attempts
|
| 1143 |
+
rng = np.random.default_rng(seed)
|
| 1144 |
+
history = []
|
| 1145 |
+
single = ("oracle", "naive", "naive_heavy_first", "naive_repair", "oracle_noise", "naive_near_first")
|
| 1146 |
+
for a in range(k):
|
| 1147 |
+
self.reset_instance(inst)
|
| 1148 |
+
if kind == "oracle":
|
| 1149 |
+
params = self.oracle_params(inst)
|
| 1150 |
+
elif kind == "naive":
|
| 1151 |
+
params = self.default_params(inst)
|
| 1152 |
+
elif kind == "adaptive":
|
| 1153 |
+
params = (dict(self.default_params(inst), repair="each", check=True) if a == 0 else
|
| 1154 |
+
self.adapt_params(inst, history))
|
| 1155 |
+
elif kind == "blind":
|
| 1156 |
+
params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
|
| 1157 |
+
elif kind == "switch":
|
| 1158 |
+
params = (self.default_params(inst) if a == 0 else
|
| 1159 |
+
dict(self.adapt_params(inst, history), repair=None, check=False))
|
| 1160 |
+
elif kind == "naive_heavy_first":
|
| 1161 |
+
params = dict(self.default_params(inst), first=inst["heavy"])
|
| 1162 |
+
elif kind == "naive_repair":
|
| 1163 |
+
params = dict(self.default_params(inst), repair="each", check=True)
|
| 1164 |
+
elif kind == "naive_near_first":
|
| 1165 |
+
params = dict(self.default_params(inst), order="near_first")
|
| 1166 |
+
elif kind == "oracle_noise":
|
| 1167 |
+
params = dict(self.oracle_params(inst), rand=0.005, noise_seed=int(seed) * 7 + a)
|
| 1168 |
+
else:
|
| 1169 |
+
raise ValueError(kind)
|
| 1170 |
+
self.execute(inst, params)
|
| 1171 |
+
out = self.outcome(inst)
|
| 1172 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 1173 |
+
if on_attempt:
|
| 1174 |
+
on_attempt(a, params, out)
|
| 1175 |
+
if out["success"] or kind in single:
|
| 1176 |
+
break
|
| 1177 |
+
return history
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/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/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/agent_cost.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Project GPT-6 cost / latency of a protocol from a run directory.
|
| 2 |
+
|
| 3 |
+
Works on (a) a real OpenAI run (uses the logged usage and latencies) or (b) a dry run of another backend made
|
| 4 |
+
with --dry-run-payload (uses the logged request sizes of every call). For (b) all numbers are ESTIMATES:
|
| 5 |
+
input tokens per call = text_chars / 4 + n_images * 256 (512 px images; image accounting is an assumption)
|
| 6 |
+
cached tokens per call = input tokens of the previous call in the same attempt (append-only prefix) --
|
| 7 |
+
the first call of an attempt is counted as uncached (conservative)
|
| 8 |
+
output tokens per call = --out-tokens (reasoning + visible; unknown for GPT-6 Astra, default 1500)
|
| 9 |
+
latency per call = --latency (seconds; RoboICL measured ~30-50 s per GPT-6 Astra call at 50-90K input
|
| 10 |
+
tokens and high/xhigh effort -- treat as an upper-range planning number)
|
| 11 |
+
The number of model calls of a scripted run is a LOWER bound for an LLM agent (no perception / checking calls).
|
| 12 |
+
|
| 13 |
+
python scripts/agent_cost.py runs/agent/l5_slide_to_target/<run> --out-tokens 1500 --latency 20 --calls-scale 2
|
| 14 |
+
"""
|
| 15 |
+
import argparse
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
import sys
|
| 19 |
+
from collections import defaultdict
|
| 20 |
+
|
| 21 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 22 |
+
|
| 23 |
+
from lffbench.agent.cost import PRICES, call_cost # noqa: E402
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def main():
|
| 27 |
+
ap = argparse.ArgumentParser()
|
| 28 |
+
ap.add_argument("run_dir")
|
| 29 |
+
ap.add_argument("--model", default="gpt-6-astra")
|
| 30 |
+
ap.add_argument("--out-tokens", type=float, default=1500)
|
| 31 |
+
ap.add_argument("--latency", type=float, default=20.0)
|
| 32 |
+
ap.add_argument("--calls-scale", type=float, default=1.0, help="multiply the call count (LLM vs scripted)")
|
| 33 |
+
a = ap.parse_args()
|
| 34 |
+
ev = [json.loads(l) for l in open(os.path.join(a.run_dir, "events.jsonl"))]
|
| 35 |
+
calls = [e for e in ev if e["type"] == "llm_call"]
|
| 36 |
+
runs = {e["seed"] for e in ev if e["type"] == "run_start"}
|
| 37 |
+
real = [c for c in calls if c.get("usage")]
|
| 38 |
+
if real and not any("dry_run_request" in c for c in calls):
|
| 39 |
+
cost = sum(call_cost(c["usage"], a.model) or 0 for c in real)
|
| 40 |
+
lat = [c["latency_s"] for c in real]
|
| 41 |
+
u = defaultdict(int)
|
| 42 |
+
for c in real:
|
| 43 |
+
for kk, v in c["usage"].items():
|
| 44 |
+
u[kk] += v
|
| 45 |
+
out = dict(mode="measured", runs=len(runs), calls=len(real), calls_per_run=len(real) / max(len(runs), 1),
|
| 46 |
+
usage=dict(u), cost_usd=cost, cost_per_run=cost / max(len(runs), 1),
|
| 47 |
+
latency_mean_s=sum(lat) / len(lat), api_time_per_run_s=sum(lat) / max(len(runs), 1))
|
| 48 |
+
else:
|
| 49 |
+
prev = {}
|
| 50 |
+
tot_in = tot_cached = 0
|
| 51 |
+
cost1 = 0.0 # priced per call (the long-context surcharge applies per request)
|
| 52 |
+
for c in calls:
|
| 53 |
+
d = c.get("dry_run_request")
|
| 54 |
+
if not d:
|
| 55 |
+
continue
|
| 56 |
+
key = (c["seed"], c["attempt"])
|
| 57 |
+
tin = d["est_input_tokens"]
|
| 58 |
+
cached = min(prev.get(key, 0), tin)
|
| 59 |
+
prev[key] = tin
|
| 60 |
+
tot_in += tin
|
| 61 |
+
tot_cached += cached
|
| 62 |
+
cost1 += call_cost(dict(input_tokens=tin, cached_tokens=cached, output_tokens=a.out_tokens), a.model)
|
| 63 |
+
n = len(calls) * a.calls_scale
|
| 64 |
+
scale = a.calls_scale
|
| 65 |
+
usage = dict(input_tokens=tot_in * scale, cached_tokens=tot_cached * scale, output_tokens=n * a.out_tokens)
|
| 66 |
+
cost = cost1 * scale
|
| 67 |
+
out = dict(mode="estimate (dry run)", runs=len(runs), calls=n, calls_per_run=n / max(len(runs), 1),
|
| 68 |
+
input_tokens_per_call=tot_in / max(len(calls), 1), cached_fraction=tot_cached / max(tot_in, 1),
|
| 69 |
+
usage=usage, cost_usd=cost, cost_per_run=cost / max(len(runs), 1),
|
| 70 |
+
api_time_per_run_s=n * a.latency / max(len(runs), 1), prices=PRICES.get(a.model),
|
| 71 |
+
assumptions=dict(out_tokens_per_call=a.out_tokens, latency_s_per_call=a.latency,
|
| 72 |
+
calls_scale=a.calls_scale, image_tokens_512px=256))
|
| 73 |
+
print(json.dumps(out, indent=1, default=str))
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
if __name__ == "__main__":
|
| 77 |
+
main()
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/cs_ir_report.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reproduce the CS/IR audit tables from read-only manifests and hash-bound evidence."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import api_batch
|
| 7 |
+
import outcomes
|
| 8 |
+
from outcome_audit import load_audit, sha256
|
| 9 |
+
|
| 10 |
+
GROUPS = {"GPT": ["cx_main1"], "Sonnet": ["cc_main1"], "Opus": ["cc_opus1"],
|
| 11 |
+
"DeepSeek": ["ds_cx1", "ds_cx1b"]}
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def main():
|
| 15 |
+
parser = argparse.ArgumentParser()
|
| 16 |
+
parser.add_argument("--runs-root", required=True)
|
| 17 |
+
parser.add_argument("--audit", required=True)
|
| 18 |
+
parser.add_argument("--out", required=True)
|
| 19 |
+
args = parser.parse_args()
|
| 20 |
+
api_batch.RUNS = str(Path(args.runs_root).resolve())
|
| 21 |
+
audit = load_audit(args.audit)
|
| 22 |
+
output = Path(args.out)
|
| 23 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 24 |
+
all_rows, models, manifests, coverage = [], {}, {}, {}
|
| 25 |
+
for model, batches in GROUPS.items():
|
| 26 |
+
old, new = [], []
|
| 27 |
+
for batch in batches:
|
| 28 |
+
manifest = api_batch.load(batch)
|
| 29 |
+
manifests[batch] = sha256(api_batch.mpath(batch))
|
| 30 |
+
old += outcomes.instance_rows(manifest, batch=batch)
|
| 31 |
+
new += outcomes.instance_rows(manifest, audit=audit, batch=batch)
|
| 32 |
+
for run in manifest["runs"]:
|
| 33 |
+
if not (run["cond"] == "harness" and run.get("followup") and run["status"] == "done"):
|
| 34 |
+
continue
|
| 35 |
+
attempts = outcomes.attempts(run["log"])
|
| 36 |
+
if attempts:
|
| 37 |
+
coverage.setdefault(run["task"], set()).update(
|
| 38 |
+
k for k in outcomes.ERROR_FLAGS + outcomes.ERROR_COUNTS if k in attempts[0][2])
|
| 39 |
+
before, after = outcomes.summary(old), outcomes.summary(new)
|
| 40 |
+
for key in ("n", "A1", "A3", "XR", "F", "n_paired", "A3_paired", "passk_paired", "delta_paired"):
|
| 41 |
+
assert before[key] == after[key], f"Audit unexpectedly changed {model} {key}"
|
| 42 |
+
assert len({(r["task"], r["seed"]) for r in new}) == len(new), "duplicate model/task/seed"
|
| 43 |
+
models[model] = dict(before=before, after=after)
|
| 44 |
+
all_rows += [dict(r, model=model) for r in new]
|
| 45 |
+
payload = dict(schema="lff-cs-ir-report-1", source_manifests_sha256=manifests,
|
| 46 |
+
audit_sha256=sha256(args.audit), models=models, rows=all_rows,
|
| 47 |
+
legacy_counter_coverage={k: sorted(v) for k, v in coverage.items()})
|
| 48 |
+
(output / "summary.json").write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
|
| 49 |
+
lines = ["# CS / IR 证据审计表(2026-10-24)", "",
|
| 50 |
+
"本表由 `scripts/cs_ir_report.py` 生成;定义、局限、合并说明见同目录 `README.md`。",
|
| 51 |
+
"旧口径是 task counter heuristic;新口径是逐 run 的物理失败 + 主动修复证据审计。",
|
| 52 |
+
"A1、A3、XR、F、配对样本及 Δ_hist 均逐项断言保持不变。", "",
|
| 53 |
+
"| 模型 | 旧 CS / IR / S? | 审计 CS / IR / S? | 原 S? 已补 | A1 | A3 |",
|
| 54 |
+
"|---|---|---|---|---|---|"]
|
| 55 |
+
for model, pair in models.items():
|
| 56 |
+
b, a = pair["before"], pair["after"]
|
| 57 |
+
resolved = sum(r["model"] == model and r["legacy_cls"] == "S?" and r["cls"] != "S?" for r in all_rows)
|
| 58 |
+
lines.append(f"| {model} | {b['CS']} / {b['IR']} / {b['S?']} | {a['CS']} / {a['IR']} / {a['S?']} | "
|
| 59 |
+
f"{resolved}/{b['S?']} | {a['A1']}/{a['n']} | {a['A3']}/{a['n']} |")
|
| 60 |
+
lines += ["", "## 每任务新旧分类与原统一字段覆盖", "",
|
| 61 |
+
"`旧→新`;只有一个标签表示未变。`缺失` 不是没有错误;有字段也不代表覆盖抓空/掉落等全部失败。", "",
|
| 62 |
+
"| 任务 | GPT | Sonnet | Opus | DeepSeek | 原统一错误字段 |", "|---|---|---|---|---|---|"]
|
| 63 |
+
for task, counters in coverage.items():
|
| 64 |
+
cells = []
|
| 65 |
+
for model in GROUPS:
|
| 66 |
+
row = next(r for r in all_rows if r["model"] == model and r["task"] == task)
|
| 67 |
+
cells.append(row["cls"] if row["cls"] == row["legacy_cls"] else f"{row['legacy_cls']}→{row['cls']}")
|
| 68 |
+
lines.append("| " + " | ".join([task] + cells + [", ".join(sorted(counters)) or "缺失"]) + " |")
|
| 69 |
+
lines += ["", "## 首次成功的证据链", "", "行号均指原 run 文件,E 为 events.jsonl,T 为 trajectory.jsonl;s 为机器人命令序号。", ""]
|
| 70 |
+
for row in all_rows:
|
| 71 |
+
if not row["a1"]:
|
| 72 |
+
continue
|
| 73 |
+
entry = audit.get((row["batch"], row["run_id"]))
|
| 74 |
+
manifest = api_batch.load(row["batch"])
|
| 75 |
+
run = next(r for r in manifest["runs"] if r["id"] == row["run_id"])
|
| 76 |
+
lines += [f"### {row['model']} · {row['task']} · {row['legacy_cls']} → {row['cls']}", "",
|
| 77 |
+
row["audit_basis"], "", f"[原 events.jsonl]({run['log']}/events.jsonl) · "
|
| 78 |
+
f"[原 trajectory.jsonl]({run['log']}/trajectory.jsonl)", ""]
|
| 79 |
+
if entry:
|
| 80 |
+
lines += [f"证据索引:{entry.get('evidence', '')}", "",
|
| 81 |
+
f"归因范围:`{entry.get('failure_scope', 'not_adjudicated')}`。", ""]
|
| 82 |
+
(output / "TABLES.md").write_text("\n".join(lines) + "\n")
|
| 83 |
+
print(json.dumps(models, ensure_ascii=False, indent=2))
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
if __name__ == "__main__":
|
| 87 |
+
main()
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/ladder_plan.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Layer-3 feedback ladder (user 2026-10-27; design docs/20). Same instances and records as the mismatched-history
|
| 2 |
+
control (scripts/mismatch_plan.py): the main-table attempt 1 of every Claude instance in the 9 twin tasks whose
|
| 3 |
+
attempt 1 failed. Fresh single-attempt agents (Claude Code B', jail, high, F1), README byte-identical to the Do arm;
|
| 4 |
+
only the Result section of history/README.md grows, one rung at a time:
|
| 5 |
+
|
| 6 |
+
F1 "The environment judged that attempt: failed." = the Do arm (do_<m>), not re-run
|
| 7 |
+
F2 + the measured error of that attempt (outcome.detail, axis labels stripped) batch lf2_<m>
|
| 8 |
+
hplus + "Cause: " the hidden variable (arm_specs reveal, as --arm hplus states it) batch lhp_<m>
|
| 9 |
+
fix + how to succeed (arm_specs fix, from the oracle parameters; results/_ladder/fix_validate.json) lfx_<m>
|
| 10 |
+
|
| 11 |
+
python scripts/ladder_plan.py build records -> runs/api/ladder_20261027/<m>/<rung>.json (+ tasks_<m>.txt)
|
| 12 |
+
python scripts/ladder_plan.py report per instance F1 / F2 / H+ / Fix, totals, adjacent paired counts
|
| 13 |
+
-> runs/api/ladder_20261027/report.json + markdown on stdout
|
| 14 |
+
"""
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
import subprocess
|
| 18 |
+
import sys
|
| 19 |
+
|
| 20 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 21 |
+
sys.path.insert(0, ROOT)
|
| 22 |
+
API = os.path.join(ROOT, "runs", "api")
|
| 23 |
+
SRC = os.path.join(API, "mismatch_20261027")
|
| 24 |
+
OUT = os.path.join(API, "ladder_20261027")
|
| 25 |
+
FIXV = os.path.join(ROOT, "results", "_ladder", "fix_validate.json")
|
| 26 |
+
MODELS = ("opus", "sonnet")
|
| 27 |
+
RUNGS = ("F2", "hplus", "fix")
|
| 28 |
+
BATCH = {"F1": "do", "F2": "lf2", "hplus": "lhp", "fix": "lfx"}
|
| 29 |
+
WITHIN = {"l2_turntable_restore"} # reported separately (docs/20 §2)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def events(log):
|
| 33 |
+
return [json.loads(line) for line in open(os.path.join(log, "events.jsonl")) if line.strip()]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def texts(src, fixes):
|
| 37 |
+
"""rung -> result_extra for one record source (the logged attempt 1)"""
|
| 38 |
+
from lffbench import arm_specs
|
| 39 |
+
from lffbench.agent.robot_server import strip_axes
|
| 40 |
+
ev = events(src["log"])
|
| 41 |
+
start = next(e for e in ev if e["ev"] == "session_start")
|
| 42 |
+
done = next(e for e in ev if e["ev"] == "done" and e.get("attempt") == 1)
|
| 43 |
+
detail = strip_axes((done.get("outcome") or {}).get("detail") or "").strip()
|
| 44 |
+
if not detail:
|
| 45 |
+
raise SystemExit(f"{src['task']}:{src['seed']}: attempt 1 has no outcome detail for F2")
|
| 46 |
+
cause = "Cause: " + strip_axes(arm_specs.reveal(start["task"], start["inst"]).strip())
|
| 47 |
+
fx = fixes.get(f"{start['task']}:{start['seed']}")
|
| 48 |
+
if fx is None or not fx["ok"]:
|
| 49 |
+
raise SystemExit(f"{start['task']}:{start['seed']}: no validated fix text in {FIXV}")
|
| 50 |
+
return {"F2": detail, "hplus": detail + "\n\n" + cause, "fix": detail + "\n\n" + cause + "\n\n" + fx["fix"]}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def cmd_build():
|
| 54 |
+
fixes = {r["key"]: r for r in json.load(open(FIXV))["rows"]}
|
| 55 |
+
for m in MODELS:
|
| 56 |
+
own = json.load(open(os.path.join(SRC, m, "own.json")))
|
| 57 |
+
os.makedirs(os.path.join(OUT, m), exist_ok=True)
|
| 58 |
+
open(os.path.join(OUT, m, f"tasks_{m}.txt"), "w").write("\n".join(own) + "\n")
|
| 59 |
+
out = {r: {} for r in RUNGS}
|
| 60 |
+
for key, d in own.items():
|
| 61 |
+
src = json.load(open(d + ".source.json"))
|
| 62 |
+
tx = texts(src, fixes)
|
| 63 |
+
for r in RUNGS:
|
| 64 |
+
dst = os.path.join(OUT, m, r, f"{src['task']}_s{src['seed']}")
|
| 65 |
+
if not os.path.isdir(dst):
|
| 66 |
+
subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "make_dossier.py"), src["log"],
|
| 67 |
+
dst, "--result-extra", tx[r]], check=True, capture_output=True)
|
| 68 |
+
out[r][key] = dst
|
| 69 |
+
for r in RUNGS:
|
| 70 |
+
json.dump(out[r], open(os.path.join(OUT, m, f"{r}.json"), "w"), indent=1)
|
| 71 |
+
print(m, len(own), "instances x", len(RUNGS), "rungs")
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def single(batch):
|
| 75 |
+
"""task:seed -> True / False (attempt 1 of the batch's done run)"""
|
| 76 |
+
out = {}
|
| 77 |
+
p = os.path.join(API, batch, "manifest.json")
|
| 78 |
+
if not os.path.exists(p):
|
| 79 |
+
return out
|
| 80 |
+
for r in json.load(open(p))["runs"]:
|
| 81 |
+
if r["status"] != "done":
|
| 82 |
+
continue
|
| 83 |
+
d = next((e for e in events(r["log"]) if e["ev"] == "done" and e.get("attempt") == 1), None)
|
| 84 |
+
out[f"{r['task']}:{r['seed']}"] = None if d is None else bool(d["success"])
|
| 85 |
+
return out
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def cmd_report():
|
| 89 |
+
rep, md = {}, []
|
| 90 |
+
order = ("F1", "F2", "hplus", "fix")
|
| 91 |
+
f = lambda v: "-" if v is None else ("S" if v else "F")
|
| 92 |
+
for m in MODELS:
|
| 93 |
+
want = [l.strip() for l in open(os.path.join(OUT, m, f"tasks_{m}.txt")) if l.strip()]
|
| 94 |
+
res = {r: single(f"{BATCH[r]}_{m}") for r in order}
|
| 95 |
+
rows = [dict(inst=k, within=k.split(":")[0] in WITHIN, **{r: res[r].get(k) for r in order}) for k in want]
|
| 96 |
+
tot = {}
|
| 97 |
+
for part, sub in (("all", rows), ("cross", [r for r in rows if not r["within"]]),
|
| 98 |
+
("within", [r for r in rows if r["within"]])):
|
| 99 |
+
tot[part] = {r: [sum(x[r] for x in sub if x[r] is not None), sum(x[r] is not None for x in sub)] for r in order}
|
| 100 |
+
steps = {}
|
| 101 |
+
cross = [r for r in rows if not r["within"]]
|
| 102 |
+
for lo, hi in zip(order, order[1:]):
|
| 103 |
+
both = [r for r in cross if r[lo] is not None and r[hi] is not None]
|
| 104 |
+
steps[f"{lo}->{hi}"] = dict(n=len(both), up=sum(r[hi] and not r[lo] for r in both),
|
| 105 |
+
down=sum(r[lo] and not r[hi] for r in both))
|
| 106 |
+
rep[m] = dict(rows=rows, totals=tot, steps=steps)
|
| 107 |
+
md += [f"### {m}", "", "| instance | F1 | F2 | H+ | Fix |", "|---|---|---|---|---|"]
|
| 108 |
+
md += [f"| {r['inst']}{' (within)' if r['within'] else ''} | " + " | ".join(f(r[x]) for x in order) + " |"
|
| 109 |
+
for r in rows]
|
| 110 |
+
for part in ("cross", "within"):
|
| 111 |
+
md.append(f"{part}: " + ", ".join(f"{x} {tot[part][x][0]}/{tot[part][x][1]}" for x in order))
|
| 112 |
+
md.append("adjacent (cross, paired): " + "; ".join(f"{k} n={v['n']} up {v['up']} down {v['down']}"
|
| 113 |
+
for k, v in steps.items()))
|
| 114 |
+
md.append("")
|
| 115 |
+
json.dump(rep, open(os.path.join(OUT, "report.json"), "w"), indent=1)
|
| 116 |
+
print("\n".join(md))
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
if __name__ == "__main__":
|
| 120 |
+
{"build": cmd_build, "report": cmd_report}[sys.argv[1]]()
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/lerobot_replay.py
ADDED
|
@@ -0,0 +1,744 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/lerobot_sft_dataset.py
ADDED
|
@@ -0,0 +1,473 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Build the training set for supervised fine-tuning (SFT) a VLA from the published agent replays.
|
| 3 |
+
|
| 4 |
+
Input: the unified LeRobot v3 release named by /mnt/cpfs/shared/datasets/lffbench_agent_replays/CURRENT.json, plus any
|
| 5 |
+
package it does not hold yet (--extra-source). Output: one LeRobot v2.1 dataset with the feature names of openpi's LIBERO
|
| 6 |
+
config (image, wrist_image, state, actions), one episode per successful attempt:
|
| 7 |
+
|
| 8 |
+
- only frames of attempts judged successful, without the evaluator's outcome check (annotation.phase == 2);
|
| 9 |
+
- a multi-attempt `within` episode gives one clip per successful attempt, so action chunks never cross attempts;
|
| 10 |
+
- the safety routine of l6_sequence_resume's emergency stop drives the arm without the agent, so it is cut out;
|
| 11 |
+
- one instance per task is held out by (task, seed) and written to a separate dataset, never to the training one;
|
| 12 |
+
- videos are remuxed packet by packet from the published files: the pixels are the validated ones, nothing is re-encoded.
|
| 13 |
+
|
| 14 |
+
python scripts/lerobot_sft_dataset.py build --out DIR --repo-id lff_sft_vX --holdout sets/main_v2_3inst.txt [--holdout-seed task:seed ...]
|
| 15 |
+
python scripts/lerobot_sft_dataset.py verify DIR/<repo-id> # in the OpenPI environment: reads through its LeRobot
|
| 16 |
+
python scripts/lerobot_sft_dataset.py norm DIR/<repo-id> --assets <assets_base_dir>/pi05_lff/<repo-id>
|
| 17 |
+
|
| 18 |
+
Run with an environment that has av and pyarrow (shared/envs/openpi-ppu20).
|
| 19 |
+
"""
|
| 20 |
+
import argparse
|
| 21 |
+
import collections
|
| 22 |
+
import functools
|
| 23 |
+
import glob
|
| 24 |
+
import json
|
| 25 |
+
import multiprocessing
|
| 26 |
+
import os
|
| 27 |
+
import random
|
| 28 |
+
import time
|
| 29 |
+
from concurrent.futures import ProcessPoolExecutor
|
| 30 |
+
|
| 31 |
+
import av
|
| 32 |
+
import numpy as np
|
| 33 |
+
import pyarrow as pa
|
| 34 |
+
import pyarrow.parquet as pq
|
| 35 |
+
|
| 36 |
+
DATA = "/mnt/cpfs/shared/datasets/lffbench_agent_replays"
|
| 37 |
+
FPS = 20
|
| 38 |
+
CAMERAS = {"image": "observation.images.image", "wrist_image": "observation.images.wrist_image"}
|
| 39 |
+
CHUNK = 1000
|
| 40 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def sources(extra):
|
| 44 |
+
"""The canonical release, which already merges the earlier packages, and what it does not hold yet."""
|
| 45 |
+
return [json.load(open(os.path.join(DATA, "CURRENT.json")))["dataset"]] + list(extra or [])
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def read_holdout(path, extra):
|
| 49 |
+
out = {}
|
| 50 |
+
if path:
|
| 51 |
+
for line in open(path):
|
| 52 |
+
if line.strip() and not line.startswith("#"):
|
| 53 |
+
t, s = line.strip().split(":")
|
| 54 |
+
out[t] = {int(x) for x in s.split(",")}
|
| 55 |
+
for item in extra or []:
|
| 56 |
+
t, s = item.split(":")
|
| 57 |
+
out[t] = {int(x) for x in s.split(",")}
|
| 58 |
+
return out
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def plan_source(name, only_task=None):
|
| 62 |
+
"""Successful attempts of one published dataset, as frame ranges inside its episodes."""
|
| 63 |
+
p = os.path.join(DATA, name)
|
| 64 |
+
rows = {}
|
| 65 |
+
for line in open(os.path.join(p, "lff/episodes.jsonl")):
|
| 66 |
+
r = json.loads(line)
|
| 67 |
+
if any(r["success"]) and (not only_task or r["task"] in only_task):
|
| 68 |
+
rows[r["episode_index"]] = r
|
| 69 |
+
if not rows:
|
| 70 |
+
return [], collections.Counter()
|
| 71 |
+
meta = []
|
| 72 |
+
for f in sorted(glob.glob(os.path.join(p, "meta/episodes/chunk-*/file-*.parquet"))):
|
| 73 |
+
keep = ["episode_index", "length", "dataset_from_index"]
|
| 74 |
+
for key in CAMERAS.values():
|
| 75 |
+
keep += [f"videos/{key}/chunk_index", f"videos/{key}/file_index", f"videos/{key}/from_timestamp"]
|
| 76 |
+
meta += pq.read_table(f, columns=keep).to_pylist()
|
| 77 |
+
meta = {m["episode_index"]: m for m in meta}
|
| 78 |
+
cols = ["index", "episode_index", "frame_index", "annotation.attempt_index", "annotation.phase", "annotation.attempt_success",
|
| 79 |
+
"annotation.command_index", "action"]
|
| 80 |
+
keep, located, stops = {}, {}, {}
|
| 81 |
+
for f in sorted(glob.glob(os.path.join(p, "data/chunk-*/file-*.parquet"))):
|
| 82 |
+
t = pq.read_table(f, columns=cols)
|
| 83 |
+
ep = t["episode_index"].to_numpy().reshape(-1)
|
| 84 |
+
fr = t["frame_index"].to_numpy().reshape(-1)
|
| 85 |
+
att = t["annotation.attempt_index"].to_numpy().reshape(-1)
|
| 86 |
+
ph = t["annotation.phase"].to_numpy().reshape(-1)
|
| 87 |
+
su = t["annotation.attempt_success"].to_numpy().reshape(-1)
|
| 88 |
+
cmd = t["annotation.command_index"].to_numpy().reshape(-1)
|
| 89 |
+
grip = np.stack(t["action"].to_numpy(zero_copy_only=False))[:, 6]
|
| 90 |
+
first_index = int(t["index"][0].as_py())
|
| 91 |
+
for e in np.unique(ep):
|
| 92 |
+
if int(e) not in rows:
|
| 93 |
+
continue
|
| 94 |
+
located[int(e)] = (f, first_index)
|
| 95 |
+
m = (ep == e) & (su == 1) & (ph != 2)
|
| 96 |
+
for a in np.unique(att[m]):
|
| 97 |
+
ix = np.sort(fr[m & (att == a)])
|
| 98 |
+
keep[(int(e), int(a))] = ix
|
| 99 |
+
if rows[int(e)]["task"] == "l6_sequence_resume":
|
| 100 |
+
o = np.flatnonzero(ep == e)
|
| 101 |
+
o = o[np.argsort(fr[o])]
|
| 102 |
+
stops[int(e)] = emergency_stops(fr[o], att[o], cmd[o], ph[o], grip[o])
|
| 103 |
+
clips, stats = [], collections.Counter()
|
| 104 |
+
for (e, a), ix in sorted(keep.items()):
|
| 105 |
+
r = rows[e]
|
| 106 |
+
spans = [(int(ix[0]), int(ix[-1]) + 1)]
|
| 107 |
+
if not (np.diff(ix) == 1).all():
|
| 108 |
+
raise ValueError(f"{name} episode {e} attempt {a}: frames are not contiguous")
|
| 109 |
+
for s_att, cut0, cut1 in stops.get(e, []):
|
| 110 |
+
if s_att == a:
|
| 111 |
+
stats["emergency_frames_cut"] += cut1 - cut0
|
| 112 |
+
spans = [x for x in ((spans[0][0], cut0), (cut1, spans[0][1])) if x[1] > x[0]]
|
| 113 |
+
for s0, s1 in spans:
|
| 114 |
+
clips.append(dict(source=name, episode=e, attempt=a, start=s0, stop=s1, task=r["task"], seed=r["seed"], run=r["run"], batch=r["batch"],
|
| 115 |
+
model=r["model"], condition=r["condition"], protocol=r["protocol"], instruction=r["instruction"], cause=r["paper_cause"],
|
| 116 |
+
first_attempt=a == 1, run_outcome_class=r.get("run_outcome_class"),
|
| 117 |
+
videos={cam: dict(chunk=meta[e][f"videos/{key}/chunk_index"], file=meta[e][f"videos/{key}/file_index"],
|
| 118 |
+
t0=meta[e][f"videos/{key}/from_timestamp"]) for cam, key in CAMERAS.items()},
|
| 119 |
+
ep_from=meta[e]["dataset_from_index"], data_file=located[e][0], data_first_index=located[e][1]))
|
| 120 |
+
return clips, stats
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def emergency_stops(frame, attempt, command, phase, grip):
|
| 124 |
+
"""l6_sequence_resume's emergency stop opens the jaws in the middle of a move and then drives the arm home until that
|
| 125 |
+
command returns; an agent's move never changes the gripper while it moves. So the stop is where the gripper action
|
| 126 |
+
turns from close to open inside one motion command, and the routine is the rest of that command.
|
| 127 |
+
Returns [(attempt, first frame of the routine, end of the command)]."""
|
| 128 |
+
out = []
|
| 129 |
+
for i in range(1, len(frame)):
|
| 130 |
+
if phase[i] == 0 == phase[i - 1] and command[i] == command[i - 1] and attempt[i] == attempt[i - 1] \
|
| 131 |
+
and grip[i - 1] > 0 > grip[i]:
|
| 132 |
+
end = i
|
| 133 |
+
while end < len(frame) and command[end] == command[i] and attempt[end] == attempt[i]:
|
| 134 |
+
end += 1
|
| 135 |
+
out.append((int(attempt[i]), int(frame[i]), int(frame[end - 1]) + 1))
|
| 136 |
+
return out
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def remux(src, dst, f0, n, t0):
|
| 140 |
+
"""Copy n frames starting at file time t0 + f0/FPS without re-encoding. Returns (frames written, first frame kept):
|
| 141 |
+
a clip must start on a key frame, so a start between key frames moves to the next one."""
|
| 142 |
+
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
| 143 |
+
tmp = dst + ".tmp.mp4"
|
| 144 |
+
with av.open(src) as ic:
|
| 145 |
+
s = ic.streams.video[0]
|
| 146 |
+
tb = s.time_base
|
| 147 |
+
first = int(round((t0 + f0 / FPS) / tb))
|
| 148 |
+
frame_pts = int(round(1 / (FPS * tb)))
|
| 149 |
+
ic.seek(first, stream=s, backward=True, any_frame=False)
|
| 150 |
+
with av.open(tmp, "w", format="mp4") as oc:
|
| 151 |
+
o = oc.add_stream_from_template(s, opaque=True) # packets are copied, so no encoder is involved
|
| 152 |
+
base, written = None, 0
|
| 153 |
+
for pkt in ic.demux(s):
|
| 154 |
+
if pkt.pts is None or pkt.pts < first:
|
| 155 |
+
continue
|
| 156 |
+
idx = int(round((pkt.pts - first) / frame_pts))
|
| 157 |
+
if idx >= n:
|
| 158 |
+
break
|
| 159 |
+
if base is None:
|
| 160 |
+
if not pkt.is_keyframe:
|
| 161 |
+
continue
|
| 162 |
+
base, kept = pkt.pts, idx
|
| 163 |
+
pkt.pts = pkt.pts - base
|
| 164 |
+
pkt.dts = pkt.dts - base
|
| 165 |
+
pkt.stream = o
|
| 166 |
+
oc.mux(pkt)
|
| 167 |
+
written += 1
|
| 168 |
+
os.replace(tmp, dst)
|
| 169 |
+
return written, kept
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
@functools.lru_cache(maxsize=2)
|
| 173 |
+
def read_data_file(path):
|
| 174 |
+
return pq.read_table(path, columns=["observation.state", "action", "index", "episode_index", "annotation.attempt_success", "annotation.phase"])
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def write_clip(job):
|
| 178 |
+
"""One output episode: both videos, then the parquet of exactly the frames they hold."""
|
| 179 |
+
clip, ep, out = job
|
| 180 |
+
n = clip["stop"] - clip["start"]
|
| 181 |
+
chunk = ep // CHUNK
|
| 182 |
+
src = os.path.join(DATA, clip["source"])
|
| 183 |
+
results = {}
|
| 184 |
+
for cam, v in clip["videos"].items():
|
| 185 |
+
path = os.path.join(src, f"videos/{CAMERAS[cam]}/chunk-{v['chunk']:03d}/file-{v['file']:03d}.mp4")
|
| 186 |
+
results[cam] = remux(path, os.path.join(out, f"videos/chunk-{chunk:03d}/{cam}/episode_{ep:06d}.mp4"), clip["start"], n, v["t0"])
|
| 187 |
+
kept = {r[1] for r in results.values()}
|
| 188 |
+
if len(kept) != 1:
|
| 189 |
+
raise ValueError(f"cameras disagree on the first key frame: {results} ({clip['source']} {clip['episode']})")
|
| 190 |
+
skip = kept.pop()
|
| 191 |
+
length = results["image"][0]
|
| 192 |
+
if results["wrist_image"][0] != length or length != n - skip:
|
| 193 |
+
raise ValueError(f"frame count {results} != {n - skip} ({clip['source']} {clip['episode']})")
|
| 194 |
+
i0 = clip["ep_from"] + clip["start"] + skip
|
| 195 |
+
t = read_data_file(clip["data_file"]).slice(i0 - clip["data_first_index"], length)
|
| 196 |
+
if t.num_rows != length or int(t["index"][0].as_py()) != i0 or set(t["episode_index"].to_pylist()) != {clip["episode"]}:
|
| 197 |
+
raise ValueError(f"parquet slice mismatch ({clip['source']} {clip['episode']})")
|
| 198 |
+
if set(t["annotation.attempt_success"].to_pylist()) != {1} or 2 in set(t["annotation.phase"].to_pylist()):
|
| 199 |
+
raise ValueError(f"unexpected frame labels ({clip['source']} {clip['episode']})")
|
| 200 |
+
state = np.stack(t["observation.state"].to_numpy(zero_copy_only=False)).astype(np.float32)
|
| 201 |
+
action = np.stack(t["action"].to_numpy(zero_copy_only=False)).astype(np.float32)
|
| 202 |
+
chunk_dir = os.path.join(out, f"videos/chunk-{chunk:03d}")
|
| 203 |
+
images = {cam: image_stats(os.path.join(chunk_dir, f"{cam}/episode_{ep:06d}.mp4"), length) for cam in CAMERAS}
|
| 204 |
+
return dict(ep=ep, length=length, skip=skip, state=state, action=action, image_stats=images)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def stats_of(a):
|
| 208 |
+
return dict(min=a.min(0).tolist(), max=a.max(0).tolist(), mean=a.mean(0).tolist(), std=a.std(0).tolist(), count=[len(a)])
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def image_stats(path, length, n=5):
|
| 212 |
+
"""Sampled image statistics for meta/episodes_stats.jsonl (LeRobot requires them, openpi does not use them)."""
|
| 213 |
+
frames = []
|
| 214 |
+
with av.open(path) as c:
|
| 215 |
+
s = c.streams.video[0]
|
| 216 |
+
for i in np.linspace(0, length - 1, min(n, length)).astype(int):
|
| 217 |
+
pts = int(round(i / FPS / s.time_base))
|
| 218 |
+
c.seek(pts, stream=s, backward=True)
|
| 219 |
+
for fr in c.decode(s):
|
| 220 |
+
if fr.pts >= pts:
|
| 221 |
+
frames.append(fr.to_ndarray(format="rgb24").astype(np.float32) / 255.0)
|
| 222 |
+
break
|
| 223 |
+
x = np.stack(frames).transpose(0, 3, 1, 2)
|
| 224 |
+
fmt = lambda v: [[[float(q)]] for q in v]
|
| 225 |
+
return dict(min=fmt(x.min((0, 2, 3))), max=fmt(x.max((0, 2, 3))), mean=fmt(x.mean((0, 2, 3))), std=fmt(x.std((0, 2, 3))), count=[len(frames)])
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def pool(workers):
|
| 229 |
+
"""Fresh interpreters: a forked worker inherits FFmpeg's state from a parent that decoded video and can deadlock."""
|
| 230 |
+
return ProcessPoolExecutor(workers, mp_context=multiprocessing.get_context("spawn"))
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def write_dataset(out, clips, workers):
|
| 234 |
+
os.makedirs(os.path.join(out, "meta"), exist_ok=True)
|
| 235 |
+
os.makedirs(os.path.join(out, "lff"), exist_ok=True)
|
| 236 |
+
tasks = sorted({c["instruction"] for c in clips})
|
| 237 |
+
task_index = {t: i for i, t in enumerate(tasks)}
|
| 238 |
+
clips = sorted(clips, key=lambda c: (c["task"], c["seed"], c["source"], c["episode"], c["start"]))
|
| 239 |
+
with pool(workers) as ex:
|
| 240 |
+
results = list(ex.map(write_clip, [(c, i, out) for i, c in enumerate(clips)], chunksize=4))
|
| 241 |
+
index, eps, ep_stats, prov = 0, [], [], []
|
| 242 |
+
for c, r in zip(clips, results):
|
| 243 |
+
ep, n = r["ep"], r["length"]
|
| 244 |
+
chunk = ep // CHUNK
|
| 245 |
+
ts = np.arange(n, dtype=np.float32) / FPS
|
| 246 |
+
table = pa.table({"state": list(r["state"]), "actions": list(r["action"]), "timestamp": ts, "frame_index": np.arange(n),
|
| 247 |
+
"episode_index": np.full(n, ep), "index": np.arange(index, index + n),
|
| 248 |
+
"task_index": np.full(n, task_index[c["instruction"]])})
|
| 249 |
+
p = os.path.join(out, f"data/chunk-{chunk:03d}/episode_{ep:06d}.parquet")
|
| 250 |
+
os.makedirs(os.path.dirname(p), exist_ok=True)
|
| 251 |
+
pq.write_table(table, p)
|
| 252 |
+
eps.append(dict(episode_index=ep, tasks=[c["instruction"]], length=n))
|
| 253 |
+
st = dict(state=stats_of(r["state"]), actions=stats_of(r["action"]),
|
| 254 |
+
timestamp=stats_of(ts[:, None]), frame_index=stats_of(np.arange(n)[:, None]),
|
| 255 |
+
episode_index=stats_of(np.full((n, 1), ep)), index=stats_of(np.arange(index, index + n)[:, None]),
|
| 256 |
+
task_index=stats_of(np.full((n, 1), task_index[c["instruction"]])))
|
| 257 |
+
st.update(r["image_stats"])
|
| 258 |
+
ep_stats.append(dict(episode_index=ep, stats=st))
|
| 259 |
+
prov.append(dict(episode_index=ep, index_from=index, length=n, source=c["source"], source_episode=c["episode"], attempt=c["attempt"],
|
| 260 |
+
source_frame_start=c["start"] + r["skip"], task=c["task"], seed=c["seed"], cause=c["cause"], model=c["model"],
|
| 261 |
+
run=c["run"], batch=c["batch"], condition=c["condition"], protocol=c["protocol"], first_attempt=c["first_attempt"],
|
| 262 |
+
run_outcome_class=c["run_outcome_class"]))
|
| 263 |
+
index += n
|
| 264 |
+
feat = lambda dtype, shape, names=None: dict(dtype=dtype, shape=shape, names=names)
|
| 265 |
+
video = dict(dtype="video", shape=[256, 256, 3], names=["height", "width", "channels"],
|
| 266 |
+
info={"video.height": 256, "video.width": 256, "video.codec": "av1", "video.pix_fmt": "yuv420p", "video.is_depth_map": False,
|
| 267 |
+
"video.fps": FPS, "video.channels": 3, "has_audio": False})
|
| 268 |
+
info = dict(codebase_version="v2.1", robot_type="franka_panda", total_episodes=len(clips), total_frames=index, total_tasks=len(tasks),
|
| 269 |
+
total_videos=2 * len(clips), total_chunks=(len(clips) - 1) // CHUNK + 1, chunks_size=CHUNK, fps=FPS, splits={"train": f"0:{len(clips)}"},
|
| 270 |
+
data_path="data/chunk-{episode_chunk:03d}/episode_{episode_index:06d}.parquet",
|
| 271 |
+
video_path="videos/chunk-{episode_chunk:03d}/{video_key}/episode_{episode_index:06d}.mp4",
|
| 272 |
+
features=dict(image=video, wrist_image=video,
|
| 273 |
+
state=feat("float32", [8], ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z", "finger_qpos_left", "finger_qpos_right"]),
|
| 274 |
+
actions=feat("float32", [7], ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y", "eef_delta_rot_aa_z", "gripper_close"]),
|
| 275 |
+
timestamp=feat("float32", [1]), frame_index=feat("int64", [1]), episode_index=feat("int64", [1]), index=feat("int64", [1]),
|
| 276 |
+
task_index=feat("int64", [1])))
|
| 277 |
+
json.dump(info, open(os.path.join(out, "meta/info.json"), "w"), indent=1)
|
| 278 |
+
jsonl = lambda name, rows: open(os.path.join(out, name), "w").write("".join(json.dumps(r) + "\n" for r in rows))
|
| 279 |
+
jsonl("meta/tasks.jsonl", [dict(task_index=i, task=t) for i, t in enumerate(tasks)])
|
| 280 |
+
jsonl("meta/episodes.jsonl", eps)
|
| 281 |
+
jsonl("meta/episodes_stats.jsonl", ep_stats)
|
| 282 |
+
jsonl("lff/provenance.jsonl", prov)
|
| 283 |
+
return prov
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def summarize(prov):
|
| 287 |
+
per = collections.defaultdict(lambda: dict(episodes=0, frames=0, seeds=set()))
|
| 288 |
+
for p in prov:
|
| 289 |
+
d = per[p["task"]]
|
| 290 |
+
d["episodes"] += 1
|
| 291 |
+
d["frames"] += p["length"]
|
| 292 |
+
d["seeds"].add(p["seed"])
|
| 293 |
+
return {t: dict(episodes=d["episodes"], frames=d["frames"], seeds=sorted(d["seeds"])) for t, d in sorted(per.items())}
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def cmd_build(a):
|
| 297 |
+
holdout = read_holdout(a.holdout, a.holdout_seed)
|
| 298 |
+
names = sources(a.extra_source)
|
| 299 |
+
clips, stats = [], collections.Counter()
|
| 300 |
+
with pool(a.workers) as ex:
|
| 301 |
+
for c, s in ex.map(functools.partial(plan_source, only_task=a.only_task), names):
|
| 302 |
+
clips += c
|
| 303 |
+
stats.update(s)
|
| 304 |
+
seen =collections.Counter((c["run"], c["attempt"], c["start"]) for c in clips)
|
| 305 |
+
dups = [k for k, v in seen.items() if v > 1]
|
| 306 |
+
if dups:
|
| 307 |
+
raise SystemExit(f"{len(dups)} duplicate clips, e.g. {dups[:3]}")
|
| 308 |
+
no_holdout = sorted({c["task"] for c in clips} - set(holdout))
|
| 309 |
+
if no_holdout:
|
| 310 |
+
raise SystemExit(f"tasks without a held-out instance: {no_holdout}")
|
| 311 |
+
train = [c for c in clips if c["seed"] not in holdout[c["task"]]]
|
| 312 |
+
test = [c for c in clips if c["seed"] in holdout[c["task"]]]
|
| 313 |
+
report = dict(built_utc=time.strftime("%FT%TZ", time.gmtime()), sources=names, holdout={t: sorted(s) for t, s in holdout.items()},
|
| 314 |
+
emergency_frames_cut=stats["emergency_frames_cut"])
|
| 315 |
+
for split, group, repo in (("train", train, a.repo_id), ("heldout", test, a.repo_id + "_heldout")):
|
| 316 |
+
if split not in a.splits:
|
| 317 |
+
continue
|
| 318 |
+
out = os.path.join(a.out, repo)
|
| 319 |
+
if os.path.exists(os.path.join(out, "meta/info.json")):
|
| 320 |
+
raise SystemExit(f"{out} exists: datasets are not rewritten in place")
|
| 321 |
+
prov = write_dataset(out, group, a.workers)
|
| 322 |
+
report[split] = dict(repo_id=repo, episodes=len(prov), frames=sum(p["length"] for p in prov), tasks=len({p["task"] for p in prov}),
|
| 323 |
+
first_attempt=sum(p["first_attempt"] for p in prov), per_task=summarize(prov))
|
| 324 |
+
json.dump(report, open(os.path.join(out, "lff/build_report.json"), "w"), indent=1)
|
| 325 |
+
print(split, report[split]["episodes"], "episodes", report[split]["frames"], "frames", report[split]["tasks"], "tasks", flush=True)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
@functools.lru_cache(maxsize=64)
|
| 329 |
+
def source_meta(src):
|
| 330 |
+
"""Per episode metadata of one release, and (first index, path) of each of its data files."""
|
| 331 |
+
meta = {}
|
| 332 |
+
for mf in sorted(glob.glob(os.path.join(src, "meta/episodes/chunk-*/file-*.parquet"))):
|
| 333 |
+
keep = [c for c in pq.read_schema(mf).names if not c.startswith("stats/")]
|
| 334 |
+
for m in pq.read_table(mf, columns=keep).to_pylist():
|
| 335 |
+
meta[m["episode_index"]] = m
|
| 336 |
+
files = []
|
| 337 |
+
for df in sorted(glob.glob(os.path.join(src, "data/chunk-*/file-*.parquet"))):
|
| 338 |
+
files.append((int(pq.read_table(df, columns=["index"])["index"][0].as_py()), df))
|
| 339 |
+
return meta, files
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def source_frame(prov, t):
|
| 343 |
+
"""State, action and both camera frames of one output frame, read directly from the published release."""
|
| 344 |
+
src = os.path.join(DATA, prov["source"])
|
| 345 |
+
f = prov["source_frame_start"] + t
|
| 346 |
+
metas, files = source_meta(src)
|
| 347 |
+
meta = metas[prov["source_episode"]]
|
| 348 |
+
i = meta["dataset_from_index"] + f
|
| 349 |
+
first, df = [x for x in files if x[0] <= i][-1]
|
| 350 |
+
row = read_data_file(df).slice(i - first, 1).to_pylist()[0]
|
| 351 |
+
if row["index"] != i:
|
| 352 |
+
raise SystemExit(f"source row lookup failed: {prov['source']} {i}")
|
| 353 |
+
imgs = {}
|
| 354 |
+
for cam, key in CAMERAS.items():
|
| 355 |
+
path = os.path.join(src, f"videos/{key}/chunk-{meta[f'videos/{key}/chunk_index']:03d}/file-{meta[f'videos/{key}/file_index']:03d}.mp4")
|
| 356 |
+
ts = meta[f"videos/{key}/from_timestamp"] + f / FPS
|
| 357 |
+
with av.open(path) as c:
|
| 358 |
+
s = c.streams.video[0]
|
| 359 |
+
c.seek(int(ts / s.time_base), stream=s, backward=True)
|
| 360 |
+
for fr in c.decode(s):
|
| 361 |
+
if abs(float(fr.pts * s.time_base) - ts) < 1e-3:
|
| 362 |
+
imgs[cam] = fr.to_ndarray(format="rgb24")
|
| 363 |
+
break
|
| 364 |
+
return row, imgs
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def cmd_verify(a):
|
| 368 |
+
"""Reads the dataset through openpi's LeRobot exactly as training does and compares it with the published releases."""
|
| 369 |
+
import lerobot.common.datasets.lerobot_dataset as ld
|
| 370 |
+
out = a.dir.rstrip("/")
|
| 371 |
+
root, repo = os.path.dirname(out), os.path.basename(out)
|
| 372 |
+
prov = [json.loads(x) for x in open(os.path.join(out, "lff/provenance.jsonl"))]
|
| 373 |
+
report = json.load(open(os.path.join(out, "lff/build_report.json")))
|
| 374 |
+
meta = ld.LeRobotDatasetMetadata(repo, root=out)
|
| 375 |
+
H = 10
|
| 376 |
+
ds = ld.LeRobotDataset(repo, root=out, delta_timestamps={"actions": [t / meta.fps for t in range(H)]}, video_backend="pyav")
|
| 377 |
+
checks = dict(n_frames=len(ds), n_episodes=meta.total_episodes, fps=meta.fps)
|
| 378 |
+
if len(ds) != sum(p["length"] for p in prov):
|
| 379 |
+
raise SystemExit("frame count differs from the provenance")
|
| 380 |
+
holdout = {t: set(s) for t, s in report["holdout"].items()}
|
| 381 |
+
leaked = [p for p in prov if (p["seed"] in holdout.get(p["task"], ())) != repo.endswith("_heldout")]
|
| 382 |
+
checks["instances_in_wrong_split"] = len(leaked)
|
| 383 |
+
rng = random.Random(0)
|
| 384 |
+
by_task = collections.defaultdict(list)
|
| 385 |
+
for p in prov:
|
| 386 |
+
by_task[p["task"]].append(p)
|
| 387 |
+
samples = []
|
| 388 |
+
for t, ps in sorted(by_task.items()):
|
| 389 |
+
for j in range(a.per_task):
|
| 390 |
+
p = rng.choice(ps)
|
| 391 |
+
near_end = j % 2 == 1 and p["length"] > H # half of the samples test the chunks that reach the clip's end
|
| 392 |
+
samples.append((p, p["length"] - rng.randint(1, H - 1) if near_end else rng.randrange(p["length"])))
|
| 393 |
+
state_err, act_err, img_err, chunk_err, pad_bad, prompts = [], [], [], [], 0, set()
|
| 394 |
+
tasks = {t["task_index"]: t["task"] for t in (json.loads(x) for x in open(os.path.join(out, "meta/tasks.jsonl")))}
|
| 395 |
+
for p, t in samples:
|
| 396 |
+
item = ds[p["index_from"] + t]
|
| 397 |
+
row, imgs = source_frame(p, t)
|
| 398 |
+
state_err.append(float(np.abs(item["state"].numpy() - np.asarray(row["observation.state"])).max()))
|
| 399 |
+
chunk = item["actions"].numpy()
|
| 400 |
+
act_err.append(float(np.abs(chunk[0] - np.asarray(row["action"])).max()))
|
| 401 |
+
if row["annotation.attempt_success"] != 1 or row["annotation.phase"] == 2:
|
| 402 |
+
raise SystemExit(f"frame with the wrong label in the dataset: {p['source']} {p['source_episode']} {t}")
|
| 403 |
+
for j in range(1, H):
|
| 404 |
+
if t + j >= p["length"]: # past the clip's end the loader must repeat the last action, not read the next clip
|
| 405 |
+
last = ds.hf_dataset[p["index_from"] + p["length"] - 1]["actions"].numpy()
|
| 406 |
+
chunk_err.append(float(np.abs(chunk[j] - last).max()))
|
| 407 |
+
pad_bad += int(not item["actions_is_pad"][j])
|
| 408 |
+
for cam in CAMERAS:
|
| 409 |
+
got = (item[cam].numpy().transpose(1, 2, 0) * 255).round()
|
| 410 |
+
img_err.append(float(np.abs(got - imgs[cam].astype(float)).mean()))
|
| 411 |
+
prompts.add(tasks[int(item["task_index"])] == item["task"])
|
| 412 |
+
checks.update(samples=len(samples), max_state_err=max(state_err), max_action_err=max(act_err), max_image_mae=max(img_err),
|
| 413 |
+
chunk_end_checks=len(chunk_err), max_chunk_end_err=max(chunk_err or [0.0]), chunk_end_not_padded=pad_bad, prompts_ok=prompts == {True})
|
| 414 |
+
actions = np.concatenate([np.asarray(ds.hf_dataset[p["index_from"]]["actions"])[None] for p in prov[:50]])
|
| 415 |
+
checks["first_actions_range"] = [float(actions.min()), float(actions.max())]
|
| 416 |
+
checks["pass"] = bool(not leaked and max(state_err) < 1e-6 and max(act_err) < 1e-6 and max(img_err) < 1.0 and max(chunk_err or [0.0]) < 1e-6
|
| 417 |
+
and not pad_bad and prompts == {True})
|
| 418 |
+
json.dump(checks, open(os.path.join(out, "lff/verify_report.json"), "w"), indent=1)
|
| 419 |
+
print(json.dumps(checks, indent=1))
|
| 420 |
+
if not checks["pass"]:
|
| 421 |
+
raise SystemExit("VERIFY FAILED")
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
def cmd_norm(a):
|
| 425 |
+
"""openpi's scripts/compute_norm_stats.py computes state and action-chunk statistics, decoding every video frame on
|
| 426 |
+
the way. This feeds the same RunningStats the same arrays from the parquet files, so it takes seconds."""
|
| 427 |
+
from openpi.shared import normalize
|
| 428 |
+
out = a.dir.rstrip("/")
|
| 429 |
+
stats = {key: normalize.RunningStats() for key in ("state", "actions")}
|
| 430 |
+
eps = [json.loads(x) for x in open(os.path.join(out, "meta/episodes.jsonl"))]
|
| 431 |
+
for e in eps:
|
| 432 |
+
i = e["episode_index"]
|
| 433 |
+
t = pq.read_table(os.path.join(out, f"data/chunk-{i // CHUNK:03d}/episode_{i:06d}.parquet"), columns=["state", "actions"])
|
| 434 |
+
state = np.stack(t["state"].to_numpy(zero_copy_only=False))
|
| 435 |
+
act = np.stack(t["actions"].to_numpy(zero_copy_only=False))
|
| 436 |
+
idx = np.minimum(np.arange(len(act))[:, None] + np.arange(a.horizon)[None, :], len(act) - 1) # the loader's clamping
|
| 437 |
+
stats["state"].update(state)
|
| 438 |
+
stats["actions"].update(act[idx])
|
| 439 |
+
norm = {key: s.get_statistics() for key, s in stats.items()}
|
| 440 |
+
normalize.save(a.assets, norm)
|
| 441 |
+
print(f"wrote {a.assets}/norm_stats.json from {len(eps)} episodes")
|
| 442 |
+
for key, n in norm.items():
|
| 443 |
+
print(key, "q01", np.round(n.q01, 4).tolist(), "q99", np.round(n.q99, 4).tolist())
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def main():
|
| 447 |
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 448 |
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
| 449 |
+
n = sub.add_parser("norm")
|
| 450 |
+
n.add_argument("dir")
|
| 451 |
+
n.add_argument("--assets", required=True, help="<assets_base_dir>/<config name>/<repo id>")
|
| 452 |
+
n.add_argument("--horizon", type=int, default=10)
|
| 453 |
+
n.set_defaults(fn=cmd_norm)
|
| 454 |
+
b = sub.add_parser("build")
|
| 455 |
+
b.add_argument("--out", required=True)
|
| 456 |
+
b.add_argument("--repo-id", required=True)
|
| 457 |
+
b.add_argument("--holdout", help="sets/ file naming the held-out instance of each task")
|
| 458 |
+
b.add_argument("--holdout-seed", nargs="*", help="task:seed items for tasks not in that file")
|
| 459 |
+
b.add_argument("--extra-source", nargs="*", help="packages not in the canonical release yet")
|
| 460 |
+
b.add_argument("--splits", nargs="*", default=["train", "heldout"])
|
| 461 |
+
b.add_argument("--only-task", nargs="*", help="keep only these tasks (development datasets)")
|
| 462 |
+
b.add_argument("--workers", type=int, default=6)
|
| 463 |
+
b.set_defaults(fn=cmd_build)
|
| 464 |
+
v = sub.add_parser("verify")
|
| 465 |
+
v.add_argument("dir")
|
| 466 |
+
v.add_argument("--per-task", type=int, default=3)
|
| 467 |
+
v.set_defaults(fn=cmd_verify)
|
| 468 |
+
a = ap.parse_args()
|
| 469 |
+
a.fn(a)
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
if __name__ == "__main__":
|
| 473 |
+
main()
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/start_robot_session.sh
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Start a robot server + isolated sandbox for one task instance.
|
| 3 |
+
# usage: scripts/start_robot_session.sh <task> <seed> <memory full|none> <feedback F0|F1|F2> <port> [instruction direct|indirect] [k] [tag] [perception depth|rgb] [video 0|1]
|
| 4 |
+
# The sandbox gets an opaque random name (no task / condition in the path); the readable run name is only in LOG.
|
| 5 |
+
set -e
|
| 6 |
+
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
| 7 |
+
TASK=$1; SEED=$2; MEM=$3; FB=$4; PORT=$5; INSTR=${6:-direct}; K=${7:-}; TAG=${8:-}; PERC=${9:-depth}; VID=${10:-0}
|
| 8 |
+
RUN=${TAG:+${TAG}_}${TASK}_s${SEED}_${MEM}_${FB}_${INSTR}_k${K:-d}_$(date +%m%d-%H%M%S)_p${PORT}
|
| 9 |
+
SANDBOX=${LFF_SANDBOX_ROOT:-/tmp/robotlab}/$(python3 -c 'import secrets;print(secrets.token_hex(6))')
|
| 10 |
+
LOG=${LFF_RUNS_DIR:-$ROOT/runs/claude}/$RUN
|
| 11 |
+
mkdir -p "$SANDBOX" "$LOG"
|
| 12 |
+
cd "$ROOT" && source run_env.sh && export OMP_NUM_THREADS=1
|
| 13 |
+
KARG=""; [ -n "$K" ] && KARG="--k $K"
|
| 14 |
+
VARG=""; [ "$VID" = "1" ] && VARG="--video $LOG/rollout.mp4"
|
| 15 |
+
nohup python -m lffbench.agent.robot_server --task "$TASK" --seed "$SEED" --memory "$MEM" --feedback "$FB" \
|
| 16 |
+
--instruction "$INSTR" --port "$PORT" --sandbox "$SANDBOX" --log-dir "$LOG" --perception "$PERC" --style "${LFF_STYLE:-v1}" ${LFF_EXTRA_ARGS:-} $KARG $VARG > "$LOG/server.log" 2>&1 &
|
| 17 |
+
echo $! > "$LOG/server.pid"
|
| 18 |
+
# wait for the scene (long-horizon scenes on a loaded machine took > 2 min, 2026-10-20); on failure stop the server
|
| 19 |
+
# so that it does not keep the port
|
| 20 |
+
for i in $(seq 1 "${LFF_SERVER_WAIT_S:-600}"); do [ -f "$LOG/READY" ] && break; sleep 1; done
|
| 21 |
+
[ -f "$LOG/READY" ] || { echo "server failed"; tail -20 "$LOG/server.log"; kill "$(cat "$LOG/server.pid")" 2>/dev/null; exit 1; }
|
| 22 |
+
echo "{\"run\": \"$RUN\", \"sandbox\": \"$SANDBOX\", \"port\": $PORT}" > "$LOG/session.json"
|
| 23 |
+
echo "SANDBOX=$SANDBOX"
|
| 24 |
+
echo "LOG=$LOG"
|
leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-fable-5-1_high.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "claude_code_full-oauth|2.1.299|2d894a4b1bfaaa9a|claude-fable-5-1|high",
|
| 3 |
+
"fingerprint_sha256": "f44d5ded7b8b847b934c86d8f7b51fa90ae396a1f33bca51e1c946f09da1031b",
|
| 4 |
+
"written": "2026-10-21 05:19:35",
|
| 5 |
+
"summary": {
|
| 6 |
+
"system_chars": 11701,
|
| 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-fable-5-1"
|
| 14 |
+
}
|
| 15 |
+
}
|
leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "claude_code_full|2.1.267|0399c793ff571d59|claude-sonnet-5-5|high",
|
| 3 |
+
"fingerprint_sha256": "0f8972223c9bdc90da28633f367aa577ae839f887c2f3f015f8128bb34a7f5b4",
|
| 4 |
+
"written": "2026-10-13 04:12:38",
|
| 5 |
+
"summary": {
|
| 6 |
+
"system_chars": 26736,
|
| 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-sonnet-5-5"
|
| 14 |
+
}
|
| 15 |
+
}
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/client/pyproject.toml
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["setuptools>=61"]
|
| 3 |
+
build-backend = "setuptools.build_meta"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "lffbench-client"
|
| 7 |
+
version = "0.1.0"
|
| 8 |
+
description = "LFF-Bench agent tools (robot / shell / view_images) for robot harness frameworks, via the episode's tool gateway"
|
| 9 |
+
requires-python = ">=3.8"
|
| 10 |
+
dependencies = []
|
| 11 |
+
|
| 12 |
+
[tool.setuptools]
|
| 13 |
+
packages = ["lffbench_client"]
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/real/DRIVER.md
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LFF-Bench 真机驱动说明(给负责机械臂的同学)
|
| 2 |
+
|
| 3 |
+
> 协议版本 1(`protocol.py` 的 `PROTOCOL_VERSION`)。2026-10-19 起草;参考实现是仿真版假驱动 `fake_driver.py`,
|
| 4 |
+
> 它通过了本文 §7 的自检和 `tests/real_selfcheck.py` 的全部对照。
|
| 5 |
+
|
| 6 |
+
## 0. 一句话
|
| 7 |
+
|
| 8 |
+
你只需要在机器人电脑上跑一个**驱动进程**:收到 HTTP 请求就动臂、动夹爪、拍两张照片,或者在终端里问操作员。
|
| 9 |
+
模型、harness、命令预算、尝试次数、日志都在跑评测的那台机器上,你那边不用装。
|
| 10 |
+
|
| 11 |
+
```
|
| 12 |
+
评测机(跑模型的人) 机器人电脑(你)
|
| 13 |
+
Codex / Claude Code(订阅) 驱动进程 ← 你写,从 driver_template.py 改
|
| 14 |
+
└ MCP:robot / shell / view_images ├ 机械臂 SDK(松灵 PiPER ……)
|
| 15 |
+
└ 真机版 robot_server(预算、尝试、README、日志) ├ 两台相机:agentview + wrist
|
| 16 |
+
└ HTTP ── SSH 隧道 ──────────────────────────→ └ 操作员终端(复原场景、判成败)
|
| 17 |
+
```
|
| 18 |
+
|
| 19 |
+
模型永远看不到你的电脑,你的驱动也不知道模型是谁。所有运动只走 `/move`、`/gripper`、`/home` 三个接口。
|
| 20 |
+
|
| 21 |
+
## 1. 你要交付的东西
|
| 22 |
+
|
| 23 |
+
1. 驱动进程:`driver_template.py` 里 5 个 TODO(连臂、笛卡尔直线运动、读位姿、夹爪、取图),`/ik` 可选。
|
| 24 |
+
2. 两台相机:`agentview`(固定,能看到整个工作区)和 `wrist`(装在夹爪上)。
|
| 25 |
+
3. 场景道具,见 §6。
|
| 26 |
+
4. `scripts/real_check_driver.py` 全部 PASS(§7)。
|
| 27 |
+
5. 一位操作员,按 §8 的规程操作。可以就是你。
|
| 28 |
+
|
| 29 |
+
需要的文件只有三个:`lffbench/real/protocol.py`、`lffbench/real/driver_template.py`、`scripts/real_check_driver.py`。
|
| 30 |
+
放在同一个目录即可。依赖:Python 3、numpy、Pillow;录像另需 imageio + imageio-ffmpeg;再加上你的臂和相机 SDK。
|
| 31 |
+
|
| 32 |
+
## 2. 坐标与约定(最重要的一节)
|
| 33 |
+
|
| 34 |
+
| 量 | 约定 |
|
| 35 |
+
|---|---|
|
| 36 |
+
| 坐标系 | 机械臂**基座坐标系**:原点在基座,+x 是机器人正前方(远离基座),+y 是机器人的左手边,+z 向上;单位米 |
|
| 37 |
+
| 位置 `eef_pos` | **抓取点**(TCP):两指中间、比指尖高约 1 cm。在 SDK 里把 TCP 设到这里,或者自己做固定偏移 |
|
| 38 |
+
| 姿态 | 夹爪始终**竖直朝下**,只有一个自由度 yaw(绕基座 z 轴)。`yaw = 0`:两指沿基座 **y** 方向开合;`yaw = +90`:沿 x 方向开合;从上往下看,**正方向是逆时针** |
|
| 39 |
+
| yaw 范围 | `yaw_range_deg` 由你声明,跨度至少 180°(两指夹爪转 180° 等价,评测端会挑离当前 yaw 最近的等价角,保证落在你声明的范围里) |
|
| 40 |
+
| `gripper_width_m` | 两指尖之间的距离,单位米(空合 < 1 cm,张开 > 3 cm) |
|
| 41 |
+
| `joint_pos_rad` | 全部关节角(基座到腕,弧度),个数 = `n_joints` |
|
| 42 |
+
| `motion_s` | 这条命令实际运动了多少秒(评测按它扣"运动时间"预算:每次尝试 3 s × 命令条数) |
|
| 43 |
+
|
| 44 |
+
这些都和仿真一致(仿真里 yaw 0 也是"沿 y 开合")。模型拿到的 README 写的是
|
| 45 |
+
"You control a real `<robot>` robot arm (`<n_joints>` joints) with a two-finger parallel gripper",`robot` 和 `n_joints` 就取你在 `/info` 里填的值。
|
| 46 |
+
|
| 47 |
+
## 3. 接口
|
| 48 |
+
|
| 49 |
+
所有请求都是 `POST http://127.0.0.1:<port>/<endpoint>`,带 JSON body,请求头 `X-Driver-Token: <token>`。
|
| 50 |
+
所有回复都是 JSON,含 `"ok": true|false`。**`"fault": true` 表示机器人不可信了**(保护性停止、急停、通信断开……),评测端会立刻结束这个 run 并标为无效。
|
| 51 |
+
模板里任何未捕获的异常都会自动变成 fault。
|
| 52 |
+
|
| 53 |
+
| 接口 | 请求 | 回复(`ok` 之外) | 说明 |
|
| 54 |
+
|---|---|---|---|
|
| 55 |
+
| `info` | `{}` | `protocol` = 1,`robot`,`n_joints`,`cameras` = `["agentview","wrist"]`,`workspace` = `{lo:[x,y,z], hi:[x,y,z]}`,`yaw_range_deg` = `[lo,hi]`,`max_speed`(m/s),`ik`(bool),`driver_version` | 启动时调一次,内容写进每个 run 的契约 |
|
| 56 |
+
| `home` | `{}` | `state` | 回到初始位姿、张开夹爪。每次复原场景之前调用 |
|
| 57 |
+
| `move` | `{x, y, z, yaw_deg, speed}`,`speed` 可为 null(= `max_speed`) | `motion_s`,`state`;被拒时 `ok:false` + `error` | **阻塞**,臂停下才返回;尽量走笛卡尔直线(MoveL)。目标超出你的硬工作空间或者没有 IK 解时,**动之前**拒绝,回 `ok:false`(不是 fault) |
|
| 58 |
+
| `gripper` | `{close: true/false}` | `motion_s`,`state` | 阻塞。合爪要限力,夹到东西或合到底就停 |
|
| 59 |
+
| `state` | `{}` | `state` = `{eef_pos, eef_yaw_deg, gripper_width_m, joint_pos_rad}` | 报**真实**位姿。标定偏差由评测端在软件里加,驱动不要加 |
|
| 60 |
+
| `observe` | `{}` | `images` = `{agentview: {format, data}, wrist: {...}}`(base64 的 jpeg 或 png),`state` | 取**最新**一帧(先清相机缓冲)。任意分辨率都行:评测端会���心裁成正方形、缩到 512²,再存成 JPEG q90 |
|
| 61 |
+
| `ik` | `{eef_pos, yaw_deg}` | `joint_pos_rad` | 可选,只有 `real_bias_place` 需要(`info.ik = true`)。只算不动;返回离当前关节角最近的解 |
|
| 62 |
+
| `operator` | `{kind: reset/judge/notice, run, attempt, setup, checklist, text}` | reset:`{}`;judge:`{success, note}` | 模板里已经实现成终端提示,会阻塞到操作员回答为止(§8) |
|
| 63 |
+
| `event` | `{ev, run, attempt}`,`ev` ∈ session_start / attempt_start / attempt_end / episode_end / session_end / run_invalid | `{}` | 用来开始、停止录像。模板在 attempt_start 开录、attempt_end 停录,每次尝试存一个 mp4 |
|
| 64 |
+
|
| 65 |
+
驱动是单线程的:请求一条一条执行,操作员提示没回答之前,别的请求都在排队,所以复原场景时臂不会动。
|
| 66 |
+
|
| 67 |
+
## 4. 安全(必须做)
|
| 68 |
+
|
| 69 |
+
- **硬工作空间**:驱动自己检查(模板的 `_inside` 已经写好)。z 下限要保证指尖离桌面至少 5 mm;盒子任务要用指尖贴近桌面推,所以 z 下限别留太高。
|
| 70 |
+
- **速度上限**:`max_speed` 建议不超过 0.25 m/s。模型可以要求更慢,但不能更快。
|
| 71 |
+
- **力保护**:推盒子本来就要接触物体,但模型也可能让夹爪压桌面、撞东西。打开臂自带的碰撞检测或电流保护;保护停止触发时回 fault。
|
| 72 |
+
- **急停**放在操作员手边。急停之后这个 run 作废,在 judge 提示里选 `x`,或者驱动自己回 fault。
|
| 73 |
+
- `/move` 里**不要做任何"聪明"的补偿**,比如自动抬高、自动避障、自动纠偏。那样会改变任务本身。超范围就拒绝,其他情况照命令执行。
|
| 74 |
+
|
| 75 |
+
## 5. 模型那边看到的和你有关的东西
|
| 76 |
+
|
| 77 |
+
- 每条命令之后的两张图(agentview、wrist)和末端状态。所以 agentview 必须拍到整个工作区:盒子、目标框、起点。
|
| 78 |
+
光照要稳定;模型运行时,画面里不要有人和多余的东西。
|
| 79 |
+
- 被拒绝的目标,模型看到的是 "target rejected: the arm cannot reach it; the arm did not move"。
|
| 80 |
+
- 评测端声明给模型的工作空间就是你 `/info` 里的 `workspace`(`real_bias_place` 会在 xy 方向每边再缩 4 cm)。模型不知道具体数值,只会在越界时被拒。
|
| 81 |
+
|
| 82 |
+
## 6. 两个任务的场景
|
| 83 |
+
|
| 84 |
+
实例(配重放哪、布局用哪组)由种子决定,每次复原前会显示在你的终端里,照做就行。正式 run 用 5000 以后的种子。
|
| 85 |
+
|
| 86 |
+
### 6.1 `real_offcenter_push`:重心偏的长盒子推进绿框(对应仿真 `l7_offcenter_push`)
|
| 87 |
+
|
| 88 |
+
模型看到的指令(与仿真相同):*Slowly push the long brown box with the closed gripper so that it ends up completely inside the green rectangle ahead of it (farther from the robot).*
|
| 89 |
+
|
| 90 |
+
- **盒子**:不透明的棕色长盒(纸盒或 3D 打印都行),带盖。仿真尺寸是 9 × 22 × 4 cm(沿推的方向 × 长 × 高)。
|
| 91 |
+
可以按 PiPER 的可达范围缩小,但沿推的方向的尺寸要比夹爪最大开口宽至少 2 cm,保证夹不起来。长边横放(沿 y)。
|
| 92 |
+
- **配重**:盒内每端隔两格(最外一格、往里一格),共 4 格。配重块(钢块、铅块)放在实例指定的那一格;空格可以塞泡沫,免得配重滑动。
|
| 93 |
+
合上盖子,两端外观一模一样,贴同样的胶带。
|
| 94 |
+
- **起点**:桌上贴定位角标,盒子每次都按角标摆,长边横放。
|
| 95 |
+
- **目标框**:绿色胶带围成的矩形,每边比盒子底面大 2 cm,在起点正前方,框中心离盒子中心 8–13 cm(仿真值;选一个固定值就行)。
|
| 96 |
+
- **桌面**:摩擦要均匀,盒子不能一推就滑出去很远。
|
| 97 |
+
- **先验证 headroom(必须做,不用模型)**:合上夹爪,以 5–8 cm/s 推盒子背面中点,盒子要明显转动(仿真里转 25–33°,转完就出框);
|
| 98 |
+
对准重心正后方推,盒子要基本不转、能进框。转得不明显就加重配重、把配重往外移,或者换更滑的桌垫。左右两种配重位置各试几次,记下来。
|
| 99 |
+
- **判成功**(终端里显示的清单):盒子四个底角都在绿框内(压线算出框);盒子没翻倒;一直是合着夹爪推的;夹爪没碰着盒子。
|
| 100 |
+
|
| 101 |
+
### 6.2 `real_bias_place`:带标定偏差的抓放(对应仿真 `l1_bias_place`)
|
| 102 |
+
|
| 103 |
+
模型看到的指令:*Pick up the red cube and put it into the bowl.*
|
| 104 |
+
|
| 105 |
+
- 红色方块(约 4 cm,能稳稳夹起),一个浅碗(内径 ≥ 12 cm)。
|
| 106 |
+
- 桌上贴 4 组标记 A–D:`A1` 放方块、`A2` 放碗,B、C、D 同理。各组之间、方块和碗之间都相距 ≥ 20 cm,全部在工作空间内,离工作空间边界 ≥ 5 cm。
|
| 107 |
+
- **偏差不用你管**:评测端给每条命令加一个隐藏的 2.5–4 cm 水平偏移,回报位姿时再减掉,臂本身不变。
|
| 108 |
+
但你需要实现 `/ik`(并把 `info()` 里的 `ik` 改成 True),否则回报的关节角会泄露偏差,评测端会拒绝启动这个任务。
|
| 109 |
+
- **判成功**:方块在碗里(落在碗底,不在碗沿上);夹爪张开,没夹着方��。
|
| 110 |
+
|
| 111 |
+
## 7. 联调步骤
|
| 112 |
+
|
| 113 |
+
1. 把 §1 的三个文件拷到机器人电脑上,填好 `driver_template.py` 的 TODO 和顶部的配置(`ROBOT`、`N_JOINTS`、`WORKSPACE_*`、`YAW_RANGE_DEG`、`HOME`)。
|
| 114 |
+
2. 启动驱动(token 自己定,私下发给跑评测的人):
|
| 115 |
+
```bash
|
| 116 |
+
python driver_template.py --port 9900 --token <token> --log driver_logs
|
| 117 |
+
```
|
| 118 |
+
3. 在机器人电脑上自检。臂会小幅运动:上下 3 cm、转 30°、开合夹爪,速度 5 cm/s,手放在急停上:
|
| 119 |
+
```bash
|
| 120 |
+
python real_check_driver.py --driver http://127.0.0.1:9900 --token <token> --operator
|
| 121 |
+
```
|
| 122 |
+
全部 PASS 才算完成;WARN 要看一下原因,NOTE 要人工确认(yaw 正方向是否为逆时针)。
|
| 123 |
+
4. 建 SSH 隧道,让评测机能访问 `127.0.0.1:9900`。二选一:
|
| 124 |
+
- 评测机能 ssh 到机器人电脑:在评测机上执行 `ssh -N -L 9900:127.0.0.1:9900 <user>@<机器人电脑>`
|
| 125 |
+
- 只能反过来连:在机器人电脑上执行 `ssh -N -R 9900:127.0.0.1:9900 <user>@<评测机>`
|
| 126 |
+
5. 跑评测的人在评测机上经隧道再跑一次 `real_check_driver.py`(加 `--yes`)。
|
| 127 |
+
6. 正式 run:评测机启动 session 后,你的终端会先出现 **RESET** 提示:按 setup 摆好场景,人离开画面,回车,模型开始操作。
|
| 128 |
+
一次尝试结束时出现 **JUDGE** 提示:按清单判 y / n / x。还有下一次尝试的话,臂会先回 home,再出现 RESET 提示。
|
| 129 |
+
|
| 130 |
+
## 8. 操作员规程
|
| 131 |
+
|
| 132 |
+
- 只照终端提示做;setup 要严格照做,每次复原都一样(角标对齐、配重格子对、盖子合好)。
|
| 133 |
+
- 模型运行期间,人不进相机画面,不碰场景,也不对任何人说配重在哪(除非要急停)。
|
| 134 |
+
- 判 y / n 只看清单本身,不看模型"努力了没有"。
|
| 135 |
+
- `x` = 这个 run 作废:机器人报错、相机掉线、有人碰了场景、配重摆错了。note 里写一句原因。
|
| 136 |
+
- 时间:模型每步要几秒到几十秒,一个 run 大约 15–60 分钟(估计,没实测),最长一次尝试约 40 条命令。
|
| 137 |
+
|
| 138 |
+
## 9. 常见问题
|
| 139 |
+
|
| 140 |
+
- **相机不是正方形**:可以。评测端会中心裁成正方形,两边各裁掉 (宽−高)/2 像素,所以工作区要在画面中间。
|
| 141 |
+
- **被物体挡住、没到目标**:位置控制会继续顶。设好电流或力矩保护;保护停止就回 fault,没触发就照常返回,模型会从位姿和图里看出没到。
|
| 142 |
+
- **到不了的目标**:`/move` 回 `ok:false` + `error`,并且不能动。不要回 fault。
|
| 143 |
+
- **延迟**:每个请求 1 秒内回完就行(取图建议 < 0.5 s)。瓶颈在模型。
|
| 144 |
+
- **PiPER 的 SDK 细节**:模板里只写了提示,没有在真机上验证过,以 SDK 文档为准。
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/real/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Real-robot backend of LFF-Bench (docs/17): the same agent interface as simulation, with a robot driver underneath.
|
| 2 |
+
|
| 3 |
+
protocol.py driver protocol v1 (both sides; stdlib + numpy + Pillow only)
|
| 4 |
+
executor.py RealToolExecutor: robot_server's executor on top of a driver (calibration bias injected here)
|
| 5 |
+
session.py RealRobotSession: robot_server's LA session without the simulator; python -m lffbench.real.session
|
| 6 |
+
tasks.py real-robot tasks (setup sheet, operator checklist, hidden variable from the seed)
|
| 7 |
+
fake_driver.py a driver backed by the simulator (no hardware)
|
| 8 |
+
driver_template.py skeleton for a hardware driver (copy to the robot PC with protocol.py)
|
| 9 |
+
DRIVER.md spec for the driver author and the operator
|
| 10 |
+
"""
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/real/driver_template.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Skeleton of a hardware driver for LFF-Bench (spec: DRIVER.md). Copy this file and protocol.py to the robot PC,
|
| 2 |
+
fill in the five methods marked TODO, run scripts/real_check_driver.py until every check passes.
|
| 3 |
+
|
| 4 |
+
python driver_template.py --port 9900 [--token <t>] [--log <dir>]
|
| 5 |
+
|
| 6 |
+
Only Python 3 + numpy + Pillow are needed here (plus your robot / camera SDKs). Keep the server on 127.0.0.1; the
|
| 7 |
+
benchmark machine reaches it through an SSH tunnel (DRIVER.md §7).
|
| 8 |
+
|
| 9 |
+
What is already done for you: the HTTP protocol, the token, the operator's terminal prompts, the safety checks that
|
| 10 |
+
must run before every motion (hard workspace box, speed limit), the motion timing, and an optional recorder that saves
|
| 11 |
+
both cameras to an mp4 per attempt. Everything robot-specific is in the TODO methods.
|
| 12 |
+
"""
|
| 13 |
+
import argparse
|
| 14 |
+
import os
|
| 15 |
+
import threading
|
| 16 |
+
import time
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
try: # copied next to protocol.py on the robot PC
|
| 21 |
+
from protocol import CAMERAS, PROTOCOL_VERSION, DriverServer, square_resize
|
| 22 |
+
except ImportError: # inside the repo (python -m lffbench.real.driver_template)
|
| 23 |
+
from .protocol import CAMERAS, PROTOCOL_VERSION, DriverServer, square_resize
|
| 24 |
+
|
| 25 |
+
# ---------------------------------------------------------------------------------------------- your setup (edit)
|
| 26 |
+
ROBOT = "AgileX PiPER" # TODO: the arm's name as the agent will read it ("You control a real <ROBOT> robot arm")
|
| 27 |
+
N_JOINTS = 6 # TODO
|
| 28 |
+
# Hard workspace of the GRASP POINT in the robot-base frame (metres). Rejected targets never move the arm. Choose it so
|
| 29 |
+
# that every point inside is reachable with the gripper pointing straight down at any yaw in YAW_RANGE_DEG, and the
|
| 30 |
+
# lower z bound keeps the fingertips >= 5 mm above the table (the boxes are pushed with the fingertips ~1 cm up).
|
| 31 |
+
WORKSPACE_LO = [0.15, -0.25, 0.00] # TODO: measure on your table
|
| 32 |
+
WORKSPACE_HI = [0.45, 0.25, 0.30] # TODO
|
| 33 |
+
YAW_RANGE_DEG = [-120.0, 120.0] # TODO: gripper yaw your wrist reaches (span >= 180)
|
| 34 |
+
MAX_SPEED = 0.25 # m/s, the fastest straight-line speed you allow (the agent may ask for less)
|
| 35 |
+
HOME = dict(x=0.25, y=0.0, z=0.20, yaw_deg=0.0) # TODO: above the table centre, out of the agentview's way if possible
|
| 36 |
+
REACH_TOL = 0.004 # m: a move counts as finished when within this of the target and stopped
|
| 37 |
+
MOVE_TIMEOUT = 30.0 # s
|
| 38 |
+
DRIVER_VERSION = "template-0" # TODO: your git commit / date
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class MyDriver(DriverServer):
|
| 42 |
+
image_format = "jpeg" # "png" is lossless but ~5x larger; jpeg q95 is fine over a LAN / SSH tunnel
|
| 43 |
+
|
| 44 |
+
def __init__(self, record_dir=""):
|
| 45 |
+
self.lock = threading.RLock() # hardware access from the recorder thread and from requests
|
| 46 |
+
self.record_dir = record_dir
|
| 47 |
+
self.recorder = None
|
| 48 |
+
# TODO: connect to the arm, enable it, set the TCP (grasp point = midway between the fingertips, about 1 cm
|
| 49 |
+
# above their tips), open the cameras. Example for PiPER (piper_sdk; check the SDK docs, not verified here):
|
| 50 |
+
# from piper_sdk import C_PiperInterface_V2
|
| 51 |
+
# self.arm = C_PiperInterface_V2("can0"); self.arm.ConnectPort(); ... enable ...
|
| 52 |
+
# Cameras: "agentview" = fixed camera looking at the table from the front/side (sees the whole work area);
|
| 53 |
+
# "wrist" = camera on the gripper. E.g. cv2.VideoCapture / pyrealsense2 colour stream.
|
| 54 |
+
raise NotImplementedError("connect the arm and the cameras")
|
| 55 |
+
|
| 56 |
+
# ------------------------------------------------------------------ TODO 1: low-level hardware
|
| 57 |
+
def _send_cartesian(self, x, y, z, yaw_deg, speed):
|
| 58 |
+
"""Start a straight-line (MoveL) motion of the grasp point to (x, y, z) with the gripper pointing straight down
|
| 59 |
+
and rotated by yaw_deg about the base z axis (0 = fingers close along the base y axis, +90 = along the base x
|
| 60 |
+
axis, counter-clockwise seen from above). Return False if the controller refuses (no IK)."""
|
| 61 |
+
raise NotImplementedError
|
| 62 |
+
|
| 63 |
+
def _read_pose(self):
|
| 64 |
+
"""-> (xyz of the grasp point in the base frame [m], yaw_deg, joint angles [rad], is_moving: bool)."""
|
| 65 |
+
raise NotImplementedError
|
| 66 |
+
|
| 67 |
+
def _set_gripper(self, close):
|
| 68 |
+
"""Close (force-limited, stop when blocked) or open fully; return when the fingers have stopped."""
|
| 69 |
+
raise NotImplementedError
|
| 70 |
+
|
| 71 |
+
def _gripper_width(self):
|
| 72 |
+
"""Opening between the fingertips, metres."""
|
| 73 |
+
raise NotImplementedError
|
| 74 |
+
|
| 75 |
+
def _grab(self):
|
| 76 |
+
"""-> {"agentview": HxWx3 uint8 RGB, "wrist": ...}: the newest frames (flush camera buffers first)."""
|
| 77 |
+
raise NotImplementedError
|
| 78 |
+
|
| 79 |
+
def ik(self, eef_pos, yaw_deg):
|
| 80 |
+
"""Optional (set info()["ik"] = True), needed only for real_bias_place: joint angles that put the grasp point
|
| 81 |
+
at eef_pos / yaw_deg (pointing down), the solution closest to the current joints. Do NOT move the arm."""
|
| 82 |
+
raise NotImplementedError
|
| 83 |
+
|
| 84 |
+
# ------------------------------------------------------------------ protocol (normally no need to edit)
|
| 85 |
+
def info(self):
|
| 86 |
+
return dict(protocol=PROTOCOL_VERSION, robot=ROBOT, n_joints=N_JOINTS, cameras=list(CAMERAS),
|
| 87 |
+
workspace=dict(lo=WORKSPACE_LO, hi=WORKSPACE_HI), yaw_range_deg=YAW_RANGE_DEG, max_speed=MAX_SPEED,
|
| 88 |
+
ik=False, driver_version=DRIVER_VERSION)
|
| 89 |
+
|
| 90 |
+
def state(self):
|
| 91 |
+
with self.lock:
|
| 92 |
+
xyz, yaw, q, _ = self._read_pose()
|
| 93 |
+
return dict(eef_pos=[float(v) for v in xyz], eef_yaw_deg=float(yaw), gripper_width_m=float(self._gripper_width()),
|
| 94 |
+
joint_pos_rad=[float(v) for v in q])
|
| 95 |
+
|
| 96 |
+
def _inside(self, x, y, z, yaw_deg):
|
| 97 |
+
p = np.array([x, y, z])
|
| 98 |
+
return (bool(np.all(p >= WORKSPACE_LO) and np.all(p <= WORKSPACE_HI))
|
| 99 |
+
and YAW_RANGE_DEG[0] <= yaw_deg <= YAW_RANGE_DEG[1])
|
| 100 |
+
|
| 101 |
+
def move(self, x, y, z, yaw_deg, speed):
|
| 102 |
+
if not self._inside(x, y, z, yaw_deg):
|
| 103 |
+
return False, "outside the hard workspace", 0.0
|
| 104 |
+
speed = MAX_SPEED if speed is None else float(np.clip(speed, 0.005, MAX_SPEED))
|
| 105 |
+
with self.lock:
|
| 106 |
+
t0 = time.time()
|
| 107 |
+
if not self._send_cartesian(x, y, z, yaw_deg, speed):
|
| 108 |
+
return False, "no IK solution", 0.0
|
| 109 |
+
tgt = np.array([x, y, z])
|
| 110 |
+
while True: # blocking: return only once the arm has stopped
|
| 111 |
+
xyz, _, _, moving = self._read_pose()
|
| 112 |
+
if not moving and np.linalg.norm(np.asarray(xyz) - tgt) < REACH_TOL:
|
| 113 |
+
break
|
| 114 |
+
if time.time() - t0 > MOVE_TIMEOUT:
|
| 115 |
+
if not moving:
|
| 116 |
+
break # stopped short (blocked by an object): a normal outcome, the agent sees the pose
|
| 117 |
+
raise RuntimeError("move timed out while still moving") # -> fault: the run stops
|
| 118 |
+
time.sleep(0.02)
|
| 119 |
+
return True, None, time.time() - t0
|
| 120 |
+
|
| 121 |
+
def gripper(self, close):
|
| 122 |
+
with self.lock:
|
| 123 |
+
t0 = time.time()
|
| 124 |
+
self._set_gripper(close)
|
| 125 |
+
return time.time() - t0
|
| 126 |
+
|
| 127 |
+
def home(self):
|
| 128 |
+
ok, err, _ = self.move(HOME["x"], HOME["y"], HOME["z"], HOME["yaw_deg"], 0.15)
|
| 129 |
+
if not ok:
|
| 130 |
+
raise RuntimeError(f"cannot reach the home pose: {err}")
|
| 131 |
+
self.gripper(False)
|
| 132 |
+
return self.state()
|
| 133 |
+
|
| 134 |
+
def images(self):
|
| 135 |
+
with self.lock:
|
| 136 |
+
return self._grab()
|
| 137 |
+
|
| 138 |
+
def event(self, ev, run="", attempt=None, **kw):
|
| 139 |
+
if not self.record_dir:
|
| 140 |
+
return
|
| 141 |
+
if ev == "attempt_start":
|
| 142 |
+
self._stop_recording()
|
| 143 |
+
try:
|
| 144 |
+
self.recorder = Recorder(self, os.path.join(self.record_dir, f"{run}_a{attempt}.mp4"))
|
| 145 |
+
except Exception as e: # the video is only for the record: a missing imageio must not end a run as a fault
|
| 146 |
+
print(f"WARNING: recorder not started ({type(e).__name__}: {e}); "
|
| 147 |
+
"pip install imageio imageio-ffmpeg", flush=True)
|
| 148 |
+
elif ev in ("attempt_end", "episode_end", "session_end", "run_invalid"):
|
| 149 |
+
self._stop_recording()
|
| 150 |
+
|
| 151 |
+
def _stop_recording(self):
|
| 152 |
+
if self.recorder is not None:
|
| 153 |
+
self.recorder.stop()
|
| 154 |
+
self.recorder = None
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
class Recorder(threading.Thread):
|
| 158 |
+
"""agentview | wrist side by side at ~5 fps while an attempt runs (needs imageio + imageio-ffmpeg)."""
|
| 159 |
+
|
| 160 |
+
def __init__(self, drv, path, fps=5, res=360):
|
| 161 |
+
super().__init__(daemon=True)
|
| 162 |
+
import imageio
|
| 163 |
+
self.drv, self.fps, self.res, self.halt = drv, fps, res, threading.Event()
|
| 164 |
+
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
| 165 |
+
self.w = imageio.get_writer(path, fps=fps, macro_block_size=8)
|
| 166 |
+
self.start()
|
| 167 |
+
|
| 168 |
+
def run(self):
|
| 169 |
+
while not self.halt.is_set():
|
| 170 |
+
t0 = time.time()
|
| 171 |
+
try:
|
| 172 |
+
with self.drv.lock:
|
| 173 |
+
f = self.drv._grab()
|
| 174 |
+
self.w.append_data(np.concatenate([square_resize(f[c], self.res) for c in CAMERAS], axis=1))
|
| 175 |
+
except Exception as e: # never let the recorder break a run
|
| 176 |
+
print("recorder:", e)
|
| 177 |
+
self.halt.wait(max(0.0, 1.0 / self.fps - (time.time() - t0)))
|
| 178 |
+
|
| 179 |
+
def stop(self):
|
| 180 |
+
self.halt.set()
|
| 181 |
+
self.join(timeout=5)
|
| 182 |
+
self.w.close()
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def main():
|
| 186 |
+
ap = argparse.ArgumentParser()
|
| 187 |
+
ap.add_argument("--port", type=int, default=9900)
|
| 188 |
+
ap.add_argument("--token", default=os.environ.get("LFF_DRIVER_TOKEN", ""))
|
| 189 |
+
ap.add_argument("--log", default="driver_logs", help="operator answers (operator.jsonl) and attempt videos")
|
| 190 |
+
a = ap.parse_args()
|
| 191 |
+
os.makedirs(a.log, exist_ok=True)
|
| 192 |
+
MyDriver(record_dir=a.log).serve(a.port, token=a.token or None, operator_log=os.path.join(a.log, "operator.jsonl"))
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
if __name__ == "__main__":
|
| 196 |
+
main()
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/real/protocol.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Robot-driver protocol v1: what a real arm (or a fake one) must answer so that LFF-Bench can run on it.
|
| 2 |
+
|
| 3 |
+
The benchmark side (lffbench/real/session.py, on the machine that runs the agent harness) talks to one *driver*
|
| 4 |
+
process (on the robot PC) over HTTP. The driver only moves the arm, reads its state, grabs camera frames and talks
|
| 5 |
+
to the human operator; budgets, attempts, README, logs and the agent interface stay on the benchmark side, so the
|
| 6 |
+
agent sees exactly the same tools as in simulation. Spec for driver authors: lffbench/real/DRIVER.md.
|
| 7 |
+
|
| 8 |
+
This file is shared by both sides and needs only the Python standard library + numpy + Pillow (no simulator):
|
| 9 |
+
DriverClient benchmark side: typed calls to a driver
|
| 10 |
+
DriverServer driver side: HTTP plumbing; subclass it and implement the hardware methods (driver_template.py)
|
| 11 |
+
ConsoleOperator driver side: the operator's terminal (blocking prompts for reset / judging)
|
| 12 |
+
|
| 13 |
+
Every request is POST <url>/<endpoint> with a JSON body and header X-Driver-Token: <token>.
|
| 14 |
+
Every reply is JSON with "ok": true|false. A reply with "fault": true means the robot can no longer be trusted
|
| 15 |
+
(protective stop, e-stop, lost connection, ...): the benchmark ends the run and marks it invalid.
|
| 16 |
+
"""
|
| 17 |
+
import base64
|
| 18 |
+
import io
|
| 19 |
+
import json
|
| 20 |
+
import math
|
| 21 |
+
import os
|
| 22 |
+
import secrets
|
| 23 |
+
import sys
|
| 24 |
+
import time
|
| 25 |
+
import traceback
|
| 26 |
+
import urllib.error
|
| 27 |
+
import urllib.request
|
| 28 |
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
| 29 |
+
|
| 30 |
+
import numpy as np
|
| 31 |
+
|
| 32 |
+
PROTOCOL_VERSION = 1
|
| 33 |
+
CAMERAS = ("agentview", "wrist")
|
| 34 |
+
TOKEN_HEADER = "X-Driver-Token"
|
| 35 |
+
ENDPOINTS = ("info", "home", "move", "gripper", "state", "observe", "ik", "operator", "event")
|
| 36 |
+
OPERATOR_KINDS = ("reset", "judge", "notice")
|
| 37 |
+
EVENTS = ("session_start", "attempt_start", "attempt_end", "episode_end", "session_end", "run_invalid")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class DriverError(RuntimeError):
|
| 41 |
+
"""The driver answered something that breaks the protocol (or did not answer)."""
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class DriverFault(DriverError):
|
| 45 |
+
"""The driver reports a robot fault: the run must stop and is invalid."""
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# ------------------------------------------------------------------------------------------------ images
|
| 49 |
+
def encode_image(arr, fmt="png", quality=95):
|
| 50 |
+
"""uint8 HxWx3 -> {"format": "png"|"jpeg", "data": base64}. PNG is lossless (the benchmark re-encodes every frame
|
| 51 |
+
as 512x512 JPEG q90 itself, so a JPEG from the driver is compressed twice); JPEG is smaller over a slow link."""
|
| 52 |
+
from PIL import Image
|
| 53 |
+
buf = io.BytesIO()
|
| 54 |
+
im = Image.fromarray(np.asarray(arr, dtype=np.uint8))
|
| 55 |
+
if fmt == "jpeg":
|
| 56 |
+
im.save(buf, format="JPEG", quality=int(quality))
|
| 57 |
+
else:
|
| 58 |
+
im.save(buf, format="PNG")
|
| 59 |
+
return dict(format=fmt, data=base64.b64encode(buf.getvalue()).decode("ascii"))
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def decode_image(obj):
|
| 63 |
+
"""{"format", "data"} -> uint8 HxWx3 (RGB)."""
|
| 64 |
+
from PIL import Image
|
| 65 |
+
if not isinstance(obj, dict) or "data" not in obj:
|
| 66 |
+
raise DriverError("image must be {\"format\": \"png\"|\"jpeg\", \"data\": <base64>}")
|
| 67 |
+
im = Image.open(io.BytesIO(base64.b64decode(obj["data"])))
|
| 68 |
+
return np.asarray(im.convert("RGB"), dtype=np.uint8)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def square_resize(arr, res):
|
| 72 |
+
"""Centre-crop to a square, then resize to res x res. A frame that is already res x res is returned unchanged
|
| 73 |
+
(bit for bit), so a simulator-backed driver gives exactly the simulator's pixels."""
|
| 74 |
+
from PIL import Image
|
| 75 |
+
arr = np.asarray(arr, dtype=np.uint8)
|
| 76 |
+
h, w = arr.shape[:2]
|
| 77 |
+
if h == res and w == res:
|
| 78 |
+
return arr
|
| 79 |
+
s = min(h, w)
|
| 80 |
+
y0, x0 = (h - s) // 2, (w - s) // 2
|
| 81 |
+
arr = arr[y0:y0 + s, x0:x0 + s]
|
| 82 |
+
if s == res:
|
| 83 |
+
return np.ascontiguousarray(arr)
|
| 84 |
+
return np.asarray(Image.fromarray(arr).resize((res, res), Image.BICUBIC))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
# ------------------------------------------------------------------------------------------------ validation
|
| 88 |
+
def _vec(v, n):
|
| 89 |
+
return isinstance(v, (list, tuple)) and len(v) == n and all(isinstance(x, (int, float)) and math.isfinite(x) for x in v)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def info_problems(info):
|
| 93 |
+
"""-> list of problems with an /info reply (empty = fine)."""
|
| 94 |
+
p = []
|
| 95 |
+
if info.get("protocol") != PROTOCOL_VERSION:
|
| 96 |
+
p.append(f"protocol must be {PROTOCOL_VERSION}, got {info.get('protocol')!r}")
|
| 97 |
+
if not isinstance(info.get("robot"), str) or not info["robot"].strip():
|
| 98 |
+
p.append("robot: non-empty string (e.g. \"AgileX PiPER\")")
|
| 99 |
+
if not isinstance(info.get("n_joints"), int) or not 4 <= info["n_joints"] <= 8:
|
| 100 |
+
p.append("n_joints: integer 4..8")
|
| 101 |
+
if sorted(info.get("cameras") or []) != sorted(CAMERAS):
|
| 102 |
+
p.append(f"cameras must be exactly {list(CAMERAS)}")
|
| 103 |
+
ws = info.get("workspace") or {}
|
| 104 |
+
if not (_vec(ws.get("lo"), 3) and _vec(ws.get("hi"), 3) and all(a < b for a, b in zip(ws["lo"], ws["hi"]))):
|
| 105 |
+
p.append("workspace: {lo: [x, y, z], hi: [x, y, z]} with lo < hi (robot-base frame, metres)")
|
| 106 |
+
yr = info.get("yaw_range_deg")
|
| 107 |
+
if not (_vec(yr, 2) and yr[0] < yr[1] and yr[1] - yr[0] >= 180.0):
|
| 108 |
+
p.append("yaw_range_deg: [lo, hi] with hi - lo >= 180 (the gripper is symmetric, every yaw must be reachable)")
|
| 109 |
+
if not (isinstance(info.get("max_speed"), (int, float)) and 0.01 <= info["max_speed"] <= 1.0):
|
| 110 |
+
p.append("max_speed: m/s, 0.01..1.0")
|
| 111 |
+
if not isinstance(info.get("ik"), bool):
|
| 112 |
+
p.append("ik: true|false (whether /ik is implemented; needed only for tasks with a calibration bias)")
|
| 113 |
+
if not isinstance(info.get("driver_version"), str):
|
| 114 |
+
p.append("driver_version: string (your git commit or a date; it is written into every run's log)")
|
| 115 |
+
return p
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def state_problems(st, n_joints):
|
| 119 |
+
p = []
|
| 120 |
+
if not _vec(st.get("eef_pos"), 3):
|
| 121 |
+
p.append("state.eef_pos: [x, y, z] metres")
|
| 122 |
+
if not (isinstance(st.get("eef_yaw_deg"), (int, float)) and math.isfinite(st["eef_yaw_deg"])):
|
| 123 |
+
p.append("state.eef_yaw_deg: number")
|
| 124 |
+
if not (isinstance(st.get("gripper_width_m"), (int, float)) and 0.0 <= st["gripper_width_m"] <= 0.2):
|
| 125 |
+
p.append("state.gripper_width_m: number 0..0.2")
|
| 126 |
+
if not _vec(st.get("joint_pos_rad"), n_joints):
|
| 127 |
+
p.append(f"state.joint_pos_rad: {n_joints} numbers (radians)")
|
| 128 |
+
return p
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# ------------------------------------------------------------------------------------------------ benchmark side
|
| 132 |
+
class DriverClient:
|
| 133 |
+
"""Typed calls to a driver. `url` like http://127.0.0.1:9900 (an SSH tunnel to the robot PC)."""
|
| 134 |
+
|
| 135 |
+
def __init__(self, url, token, timeout=120.0):
|
| 136 |
+
self.url, self.token, self.timeout = url.rstrip("/"), token, float(timeout)
|
| 137 |
+
self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) # never through a web proxy
|
| 138 |
+
|
| 139 |
+
def call(self, endpoint, payload=None, timeout=None, allow_not_ok=False):
|
| 140 |
+
req = urllib.request.Request(f"{self.url}/{endpoint}", data=json.dumps(payload or {}).encode(),
|
| 141 |
+
headers={"Content-Type": "application/json", TOKEN_HEADER: self.token})
|
| 142 |
+
try:
|
| 143 |
+
with self.opener.open(req, timeout=timeout if timeout is not None else self.timeout) as r:
|
| 144 |
+
rep = json.loads(r.read().decode())
|
| 145 |
+
except (urllib.error.URLError, OSError, ValueError) as e:
|
| 146 |
+
raise DriverError(f"/{endpoint}: no valid reply from the driver ({type(e).__name__}: {e})") from e
|
| 147 |
+
if not isinstance(rep, dict) or "ok" not in rep:
|
| 148 |
+
raise DriverError(f"/{endpoint}: reply is not a JSON object with \"ok\"")
|
| 149 |
+
if rep.get("fault"):
|
| 150 |
+
raise DriverFault(f"/{endpoint}: robot fault: {rep.get('error', '')}")
|
| 151 |
+
if not rep["ok"] and not allow_not_ok:
|
| 152 |
+
raise DriverError(f"/{endpoint}: {rep.get('error', 'not ok')}")
|
| 153 |
+
return rep
|
| 154 |
+
|
| 155 |
+
def info(self):
|
| 156 |
+
rep = self.call("info")
|
| 157 |
+
prob = info_problems(rep)
|
| 158 |
+
if prob:
|
| 159 |
+
raise DriverError("/info: " + "; ".join(prob))
|
| 160 |
+
return rep
|
| 161 |
+
|
| 162 |
+
def home(self):
|
| 163 |
+
return self.call("home", timeout=max(self.timeout, 300))
|
| 164 |
+
|
| 165 |
+
def move(self, x, y, z, yaw_deg, speed=None):
|
| 166 |
+
"""-> reply; ok=false (not a fault) means the target was rejected and the arm did not move."""
|
| 167 |
+
return self.call("move", dict(x=float(x), y=float(y), z=float(z), yaw_deg=float(yaw_deg),
|
| 168 |
+
speed=None if speed is None else float(speed)), allow_not_ok=True)
|
| 169 |
+
|
| 170 |
+
def gripper(self, close):
|
| 171 |
+
return self.call("gripper", dict(close=bool(close)))
|
| 172 |
+
|
| 173 |
+
def state(self):
|
| 174 |
+
return self.call("state")["state"]
|
| 175 |
+
|
| 176 |
+
def observe(self):
|
| 177 |
+
rep = self.call("observe")
|
| 178 |
+
imgs = rep.get("images") or {}
|
| 179 |
+
missing = [c for c in CAMERAS if c not in imgs]
|
| 180 |
+
if missing:
|
| 181 |
+
raise DriverError(f"/observe: missing camera(s) {missing}")
|
| 182 |
+
return {c: decode_image(imgs[c]) for c in CAMERAS}, rep["state"]
|
| 183 |
+
|
| 184 |
+
def ik(self, eef_pos, yaw_deg):
|
| 185 |
+
return self.call("ik", dict(eef_pos=[float(v) for v in eef_pos], yaw_deg=float(yaw_deg)))["joint_pos_rad"]
|
| 186 |
+
|
| 187 |
+
def operator(self, kind, **kw):
|
| 188 |
+
"""Blocks until the operator has answered (no timeout)."""
|
| 189 |
+
assert kind in OPERATOR_KINDS, kind
|
| 190 |
+
return self.call("operator", dict(kind=kind, **kw), timeout=24 * 3600)
|
| 191 |
+
|
| 192 |
+
def event(self, ev, **kw):
|
| 193 |
+
assert ev in EVENTS, ev
|
| 194 |
+
return self.call("event", dict(ev=ev, **kw))
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
# ------------------------------------------------------------------------------------------------ driver side
|
| 198 |
+
class ConsoleOperator:
|
| 199 |
+
"""The operator's terminal on the robot PC. Prompts block the driver (the robot must not move while the operator
|
| 200 |
+
resets the scene). Answers are appended to `log_path` (JSON lines)."""
|
| 201 |
+
|
| 202 |
+
def __init__(self, log_path=None, stream_in=None, stream_out=None):
|
| 203 |
+
self.log_path = log_path
|
| 204 |
+
self.inp = stream_in or sys.stdin
|
| 205 |
+
self.out = stream_out or sys.stdout
|
| 206 |
+
|
| 207 |
+
def _say(self, s=""):
|
| 208 |
+
self.out.write(s + "\n")
|
| 209 |
+
self.out.flush()
|
| 210 |
+
|
| 211 |
+
def _ask(self, prompt):
|
| 212 |
+
self.out.write(prompt)
|
| 213 |
+
self.out.flush()
|
| 214 |
+
line = self.inp.readline()
|
| 215 |
+
if not line:
|
| 216 |
+
raise EOFError("operator input closed")
|
| 217 |
+
return line.strip()
|
| 218 |
+
|
| 219 |
+
def _log(self, d):
|
| 220 |
+
if self.log_path:
|
| 221 |
+
os.makedirs(os.path.dirname(os.path.abspath(self.log_path)), exist_ok=True)
|
| 222 |
+
with open(self.log_path, "a") as f:
|
| 223 |
+
f.write(json.dumps(dict(d, t=time.time()), ensure_ascii=False) + "\n")
|
| 224 |
+
|
| 225 |
+
def __call__(self, kind, run="", attempt=None, text="", setup="", checklist=None, **_):
|
| 226 |
+
bar = "=" * 72
|
| 227 |
+
self._say("\n" + bar)
|
| 228 |
+
self._say(f"[{time.strftime('%H:%M:%S')}] run {run} attempt {attempt} -- {kind.upper()}")
|
| 229 |
+
if text:
|
| 230 |
+
self._say(text)
|
| 231 |
+
if kind == "reset":
|
| 232 |
+
if setup:
|
| 233 |
+
self._say("\nScene for this attempt (do it exactly; do not talk to anyone about it):\n" + setup)
|
| 234 |
+
self._ask("\nArm is at home. Put the scene back as described, step out of the cameras, press Enter... ")
|
| 235 |
+
self._log(dict(kind=kind, run=run, attempt=attempt))
|
| 236 |
+
return dict(ok=True)
|
| 237 |
+
if kind == "judge":
|
| 238 |
+
for i, c in enumerate(checklist or [], 1):
|
| 239 |
+
self._say(f" {i}. {c}")
|
| 240 |
+
while True:
|
| 241 |
+
a = self._ask("\nAll conditions met? y = success, n = failure, x = run invalid (robot / camera "
|
| 242 |
+
"problem): ").lower()
|
| 243 |
+
if a in ("y", "n", "x"):
|
| 244 |
+
break
|
| 245 |
+
note = self._ask("Note (one line, optional): ")
|
| 246 |
+
self._log(dict(kind=kind, run=run, attempt=attempt, answer=a, note=note))
|
| 247 |
+
if a == "x":
|
| 248 |
+
return dict(ok=False, fault=True, error=f"operator marked the run invalid: {note}")
|
| 249 |
+
return dict(ok=True, success=a == "y", note=note)
|
| 250 |
+
self._log(dict(kind=kind, run=run, attempt=attempt, text=text))
|
| 251 |
+
return dict(ok=True)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
class DriverServer:
|
| 255 |
+
"""HTTP plumbing for a driver. Subclass and implement the hardware methods below; see driver_template.py.
|
| 256 |
+
The server is single-threaded on purpose: requests are executed one at a time, and an operator prompt blocks
|
| 257 |
+
every other request until it is answered."""
|
| 258 |
+
|
| 259 |
+
# ---- implement these ------------------------------------------------------------------------------
|
| 260 |
+
def info(self):
|
| 261 |
+
"""-> dict (see DRIVER.md §3): protocol, robot, n_joints, cameras, workspace, yaw_range_deg, max_speed, ik,
|
| 262 |
+
driver_version."""
|
| 263 |
+
raise NotImplementedError
|
| 264 |
+
|
| 265 |
+
def home(self):
|
| 266 |
+
"""Move to the home pose (gripper open, pointing down). -> state dict."""
|
| 267 |
+
raise NotImplementedError
|
| 268 |
+
|
| 269 |
+
def move(self, x, y, z, yaw_deg, speed):
|
| 270 |
+
"""Blocking straight-line move of the grasp point; speed m/s or None (= max_speed).
|
| 271 |
+
-> (ok, error_or_None, motion_s). ok=False: rejected BEFORE moving (outside the hard limits / no IK)."""
|
| 272 |
+
raise NotImplementedError
|
| 273 |
+
|
| 274 |
+
def gripper(self, close):
|
| 275 |
+
"""Blocking open / close (force-limited close). -> motion_s."""
|
| 276 |
+
raise NotImplementedError
|
| 277 |
+
|
| 278 |
+
def state(self):
|
| 279 |
+
"""-> dict eef_pos, eef_yaw_deg, gripper_width_m, joint_pos_rad."""
|
| 280 |
+
raise NotImplementedError
|
| 281 |
+
|
| 282 |
+
def images(self):
|
| 283 |
+
"""-> {"agentview": uint8 HxWx3 RGB, "wrist": ...}, taken now (after the arm has stopped)."""
|
| 284 |
+
raise NotImplementedError
|
| 285 |
+
|
| 286 |
+
def ik(self, eef_pos, yaw_deg):
|
| 287 |
+
"""Optional (info()["ik"] = True): joint angles that put the grasp point at eef_pos / yaw_deg (pointing
|
| 288 |
+
down), close to the current joint angles. -> list of n_joints floats."""
|
| 289 |
+
raise NotImplementedError
|
| 290 |
+
|
| 291 |
+
def operator(self, kind, **kw):
|
| 292 |
+
"""Default: the terminal. -> dict (reset: {ok}; judge: {ok, success, note}; notice: {ok})."""
|
| 293 |
+
return self.console(kind, **kw)
|
| 294 |
+
|
| 295 |
+
def event(self, ev, **kw):
|
| 296 |
+
"""Start / stop your own recordings here (attempt_start / attempt_end / episode_end ...)."""
|
| 297 |
+
return None
|
| 298 |
+
|
| 299 |
+
image_format = "png"
|
| 300 |
+
|
| 301 |
+
# ---- plumbing -------------------------------------------------------------------------------------
|
| 302 |
+
def dispatch(self, endpoint, a):
|
| 303 |
+
if endpoint == "info":
|
| 304 |
+
return dict(ok=True, **self.info())
|
| 305 |
+
if endpoint == "home":
|
| 306 |
+
return dict(ok=True, state=self.home())
|
| 307 |
+
if endpoint == "move":
|
| 308 |
+
ok, err, motion_s = self.move(float(a["x"]), float(a["y"]), float(a["z"]), float(a["yaw_deg"]),
|
| 309 |
+
None if a.get("speed") is None else float(a["speed"]))
|
| 310 |
+
rep = dict(ok=bool(ok), motion_s=float(motion_s or 0.0), state=self.state())
|
| 311 |
+
if not ok:
|
| 312 |
+
rep["error"] = err or "rejected"
|
| 313 |
+
return rep
|
| 314 |
+
if endpoint == "gripper":
|
| 315 |
+
motion_s = self.gripper(bool(a["close"]))
|
| 316 |
+
return dict(ok=True, motion_s=float(motion_s or 0.0), state=self.state())
|
| 317 |
+
if endpoint == "state":
|
| 318 |
+
return dict(ok=True, state=self.state())
|
| 319 |
+
if endpoint == "observe":
|
| 320 |
+
imgs = self.images()
|
| 321 |
+
return dict(ok=True, images={c: encode_image(imgs[c], self.image_format) for c in CAMERAS},
|
| 322 |
+
state=self.state())
|
| 323 |
+
if endpoint == "ik":
|
| 324 |
+
return dict(ok=True, joint_pos_rad=[float(v) for v in self.ik(a["eef_pos"], float(a["yaw_deg"]))])
|
| 325 |
+
if endpoint == "operator":
|
| 326 |
+
kw = {k: v for k, v in a.items() if k != "kind"}
|
| 327 |
+
return self.operator(a["kind"], **kw)
|
| 328 |
+
if endpoint == "event":
|
| 329 |
+
self.event(a.get("ev", ""), **{k: v for k, v in a.items() if k != "ev"})
|
| 330 |
+
return dict(ok=True)
|
| 331 |
+
return dict(ok=False, error=f"unknown endpoint {endpoint!r}")
|
| 332 |
+
|
| 333 |
+
def serve(self, port, token=None, host="127.0.0.1", operator_log=None):
|
| 334 |
+
"""Serve forever on host:port (keep 127.0.0.1 and reach it through an SSH tunnel)."""
|
| 335 |
+
self.token = token or os.environ.get("LFF_DRIVER_TOKEN") or secrets.token_hex(12)
|
| 336 |
+
self.console = ConsoleOperator(operator_log)
|
| 337 |
+
drv = self
|
| 338 |
+
|
| 339 |
+
class H(BaseHTTPRequestHandler):
|
| 340 |
+
def log_message(self, *x):
|
| 341 |
+
pass
|
| 342 |
+
|
| 343 |
+
def do_POST(self):
|
| 344 |
+
try:
|
| 345 |
+
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)) or b"{}")
|
| 346 |
+
if self.headers.get(TOKEN_HEADER) != drv.token:
|
| 347 |
+
rep = dict(ok=False, error="unauthorised")
|
| 348 |
+
else:
|
| 349 |
+
rep = drv.dispatch(self.path.strip("/"), body)
|
| 350 |
+
except NotImplementedError as e:
|
| 351 |
+
rep = dict(ok=False, error=f"not implemented: {self.path} {e}")
|
| 352 |
+
except Exception as e: # anything unexpected on the robot side is a fault: stop the run
|
| 353 |
+
traceback.print_exc()
|
| 354 |
+
rep = dict(ok=False, fault=True, error=f"{type(e).__name__}: {e}")
|
| 355 |
+
data = json.dumps(rep).encode()
|
| 356 |
+
self.send_response(200)
|
| 357 |
+
self.send_header("Content-Type", "application/json")
|
| 358 |
+
self.send_header("Content-Length", str(len(data)))
|
| 359 |
+
self.end_headers()
|
| 360 |
+
self.wfile.write(data)
|
| 361 |
+
|
| 362 |
+
srv = HTTPServer((host, int(port)), H)
|
| 363 |
+
print(f"driver ready on http://{host}:{port} token={self.token}", flush=True)
|
| 364 |
+
srv.serve_forever()
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/real/tasks.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Real-robot tasks. Same idea as lffbench/tasks/ (an instruction, a hidden variable the agent cannot see before it acts,
|
| 2 |
+
a success rule), but the scene is physical: the instance is a setup sheet the operator follows, and the operator
|
| 3 |
+
judges the end state. The hidden variable is drawn from the seed, so the instance list of a run is reproducible and
|
| 4 |
+
nobody has to choose it by hand.
|
| 5 |
+
|
| 6 |
+
Seeds: 5000+ for real-robot runs (same convention as simulation: 1000-1999 development, 3000 pilots, 5000+ test).
|
| 7 |
+
"""
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
REAL_TASKS = {}
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def register_real(cls):
|
| 14 |
+
REAL_TASKS[cls.name] = cls
|
| 15 |
+
return cls
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class RealTask:
|
| 19 |
+
name = "real_base"
|
| 20 |
+
sim_counterpart = "" # the simulated task with the same hidden variable (for the paper's mapping only)
|
| 21 |
+
protocol = "cross"
|
| 22 |
+
max_attempts = 3
|
| 23 |
+
agent_max_steps = 40
|
| 24 |
+
instruction = ""
|
| 25 |
+
instruction_indirect = ""
|
| 26 |
+
needs_ik = False # True if the instance carries a calibration bias (believed joint angles need the driver's /ik)
|
| 27 |
+
bias_margin = 0.0 # largest possible |bias| (m): the agent-facing workspace is shrunk by it, so a rejected target
|
| 28 |
+
# never depends on the hidden bias
|
| 29 |
+
judge = None # set by RealRobotSession: inst -> outcome dict, asks the operator
|
| 30 |
+
|
| 31 |
+
def outcome(self, inst):
|
| 32 |
+
"""Same role as LFFTask.outcome: called by robot_server's _done when an attempt ends."""
|
| 33 |
+
return self.judge(inst)
|
| 34 |
+
|
| 35 |
+
def sample_instance(self, seed):
|
| 36 |
+
raise NotImplementedError
|
| 37 |
+
|
| 38 |
+
def setup_text(self, inst):
|
| 39 |
+
"""What the operator builds before every attempt (shown on the robot PC only, never to the agent)."""
|
| 40 |
+
raise NotImplementedError
|
| 41 |
+
|
| 42 |
+
def checklist(self, inst):
|
| 43 |
+
"""Conditions the operator checks when an attempt ends; success = all of them."""
|
| 44 |
+
raise NotImplementedError
|
| 45 |
+
|
| 46 |
+
def bias(self, inst):
|
| 47 |
+
"""Hidden calibration error added to every commanded position (robot-base frame, metres)."""
|
| 48 |
+
return np.zeros(3)
|
| 49 |
+
|
| 50 |
+
def feedback(self, inst, out, level="F1"):
|
| 51 |
+
# same text as LFFTask.feedback (F0 / F1); F2 needs simulator measurements and is refused at session start
|
| 52 |
+
if level == "F0":
|
| 53 |
+
return ""
|
| 54 |
+
return "Attempt succeeded." if out["success"] else "Attempt failed."
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@register_real
|
| 58 |
+
class RealOffcenterPush(RealTask):
|
| 59 |
+
"""L7 l7_offcenter_push on a real arm: a long opaque box with a hidden weight at one end. Pushing the middle of
|
| 60 |
+
its back face turns it (visible in the agentview); the fix is to push nearer the heavy end or to straighten it
|
| 61 |
+
afterwards. Physical build and scene layout: DRIVER.md §6.1."""
|
| 62 |
+
name = "real_offcenter_push"
|
| 63 |
+
sim_counterpart = "l7_offcenter_push"
|
| 64 |
+
# same wording as the simulated task (2026-10-19): end state only, no hint about the weight or where to push
|
| 65 |
+
instruction = ("Slowly push the long brown box with the closed gripper so that it ends up completely inside the "
|
| 66 |
+
"green rectangle ahead of it (farther from the robot).")
|
| 67 |
+
instruction_indirect = ("Slowly push the long cardboard-coloured block with the closed gripper so that it ends up "
|
| 68 |
+
"completely inside the marked green area ahead of it (farther from the robot).")
|
| 69 |
+
SLOTS = ("end", "inner") # weight compartments per side: at the very end, or one compartment further in
|
| 70 |
+
|
| 71 |
+
def sample_instance(self, seed):
|
| 72 |
+
rng = np.random.default_rng(seed)
|
| 73 |
+
return dict(seed=int(seed), weight_side=str(rng.choice(["left", "right"])), weight_slot=str(rng.choice(self.SLOTS)))
|
| 74 |
+
|
| 75 |
+
def setup_text(self, inst):
|
| 76 |
+
side = {"left": "LEFT (the robot's left, +y)", "right": "RIGHT (the robot's right, -y)"}[inst["weight_side"]]
|
| 77 |
+
slot = {"end": "the outermost compartment", "inner": "the second compartment from that end"}[inst["weight_slot"]]
|
| 78 |
+
return "\n".join([
|
| 79 |
+
f"- weight block inside the box: {side} end, in {slot};",
|
| 80 |
+
"- the other compartments stay empty; close the lid; both ends look the same from outside;",
|
| 81 |
+
"- box on the START tape marks: long side across the robot (left-right), back face on the back mark;",
|
| 82 |
+
"- nothing else on the table; the green target rectangle tape unchanged.",
|
| 83 |
+
])
|
| 84 |
+
|
| 85 |
+
def checklist(self, inst):
|
| 86 |
+
return ["all four bottom corners of the box are inside the green rectangle (a corner on the tape = outside)",
|
| 87 |
+
"the box is standing on its bottom face (not tipped over)",
|
| 88 |
+
"the box was only pushed with the closed gripper (no pushes with the fingers open)",
|
| 89 |
+
"the gripper is not touching the box"]
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@register_real
|
| 93 |
+
class RealBiasPlace(RealTask):
|
| 94 |
+
"""L1 l1_bias_place on a real arm: pick-and-place with a calibration error injected in software (the benchmark
|
| 95 |
+
adds `bias` to every commanded position and subtracts it from every reported one, exactly as in simulation).
|
| 96 |
+
The arm itself is unchanged; the cameras show where the gripper really is. Physical build: DRIVER.md §6.2."""
|
| 97 |
+
name = "real_bias_place"
|
| 98 |
+
sim_counterpart = "l1_bias_place"
|
| 99 |
+
instruction = "Pick up the red cube and put it into the bowl."
|
| 100 |
+
instruction_indirect = "Pick up the small red block and put it into the round bowl."
|
| 101 |
+
needs_ik = True
|
| 102 |
+
R_MIN, R_MAX = 0.025, 0.040 # bias magnitude (m), as l1_bias_place
|
| 103 |
+
bias_margin = R_MAX
|
| 104 |
+
LAYOUTS = ("A", "B", "C", "D") # taped (cube mark, bowl mark) pairs; DRIVER.md §6.2
|
| 105 |
+
|
| 106 |
+
def sample_instance(self, seed):
|
| 107 |
+
rng = np.random.default_rng(seed)
|
| 108 |
+
r, th = float(rng.uniform(self.R_MIN, self.R_MAX)), float(rng.uniform(-np.pi, np.pi))
|
| 109 |
+
return dict(seed=int(seed), layout=str(rng.choice(self.LAYOUTS)),
|
| 110 |
+
bias=[round(r * np.cos(th), 4), round(r * np.sin(th), 4), 0.0], bias_r=round(r, 4),
|
| 111 |
+
bias_theta=round(th, 4))
|
| 112 |
+
|
| 113 |
+
def bias(self, inst):
|
| 114 |
+
return np.asarray(inst["bias"], float)
|
| 115 |
+
|
| 116 |
+
def setup_text(self, inst):
|
| 117 |
+
L = inst["layout"]
|
| 118 |
+
return "\n".join([f"- red cube on mark {L}1, bowl on mark {L}2 (layout {L});",
|
| 119 |
+
"- nothing else on the table."])
|
| 120 |
+
|
| 121 |
+
def checklist(self, inst):
|
| 122 |
+
return ["the red cube is inside the bowl (resting in it, not on the rim)",
|
| 123 |
+
"the gripper is open and not holding the cube"]
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/tasks/l2_turntable.py
ADDED
|
@@ -0,0 +1,469 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L2-C turntable_restore: take the butter off a turntable that stands half under a shelf, then turn the
|
| 2 |
+
turntable back exactly the way it was.
|
| 3 |
+
|
| 4 |
+
Replaces the planned l2_drawer_reclosed (feasibility test 2026-10-07, see the task card): with the gripper
|
| 5 |
+
always pointing straight down, the handle of LIBERO's wooden_cabinet top drawer (3.8 cm below the cabinet
|
| 6 |
+
top) cannot be reached -- the descent stops 1.5-4.5 cm above it, closing grasps nothing (4/4 cabinet
|
| 7 |
+
placements) and a pull opened the drawer only 1/4 times, by accident. The turntable keeps the idea (an
|
| 8 |
+
articulated fixture the agent *has to* change to get the object and has to put back afterwards) and is
|
| 9 |
+
operable with move_to + open/close only.
|
| 10 |
+
|
| 11 |
+
Scene: a turntable (lazy susan; disc radius 17 cm on a damped hinge about z) on the robot's right; a fixed
|
| 12 |
+
shelf board 10 cm above the disc covers its -y half (robot's right), so nothing under the board can be
|
| 13 |
+
grasped from above (measured, 20 seeds x 2 grasp yaws: the hand stops on the board 10-14 cm above the grasp
|
| 14 |
+
height, 0/40 lifts). Four red pegs stand near the rim; grasping a peg and moving the gripper along the rim
|
| 15 |
+
turns the disc. The butter lies on the disc under the board; painted marks (yellow stripe, blue square,
|
| 16 |
+
green dot; visual only) make the disc's angle readable. The basket stands on the robot's left.
|
| 17 |
+
|
| 18 |
+
Why the first attempt fails (the L2 event is the agent's own, necessary change): to reach the butter the
|
| 19 |
+
agent must turn the disc by 136-179 deg (start angle random; measured on seeds 1000-1019). An agent that puts the butter into the basket
|
| 20 |
+
and stops leaves the turntable turned -> failure. To repair it the agent has to turn it back to its start
|
| 21 |
+
angle (+-15 deg); after the main turn the marks are elsewhere and nothing in the scene shows the start angle:
|
| 22 |
+
it is only in the first frame (or in the agent's memory of how far it turned). The F2 text says *that* the
|
| 23 |
+
turntable is not turned the way it was, never by how much or which way.
|
| 24 |
+
|
| 25 |
+
Protocol: within (one episode, no reset). Attempt 1 = the main task, every later attempt = one corrective
|
| 26 |
+
round; the outcome (success + F2 text) is computed after each round.
|
| 27 |
+
|
| 28 |
+
Scripted references (perception stand-in: simulator poses; motions: Skills.move_to / set_gripper only)
|
| 29 |
+
oracle turns, takes the butter, then immediately turns the disc back to the saved start angle.
|
| 30 |
+
naive turns, takes the butter, done.
|
| 31 |
+
adaptive saves the start angle (Save); after F2 "not turned the way it was" turns back to it (Retrieve +
|
| 32 |
+
Utilize); redoes the main task if the butter is not in the basket.
|
| 33 |
+
blind no history, no feedback: every later round redoes the main task (lifts the butter out of the
|
| 34 |
+
basket and drops it back, grasp jittered by 5 mm).
|
| 35 |
+
nomem (extra control, not in the acceptance table) gets F2 but has no start frame: turns the disc by a
|
| 36 |
+
random angle in (-180, 180] deg each round.
|
| 37 |
+
|
| 38 |
+
Physics notes (all measured while building the task, 2026-10-07): the HOPE butter weighs 5 g -> set to 0.2 kg;
|
| 39 |
+
a box on a cylinder gets a single contact point and no torsional friction, so the butter span on the disc at
|
| 40 |
+
~4 deg/s even at rest -> the disc's collision surface is the inscribed square plate (visual disc stays round).
|
| 41 |
+
"""
|
| 42 |
+
import numpy as np
|
| 43 |
+
|
| 44 |
+
from .. import envs
|
| 45 |
+
from ..bddl import write_bddl
|
| 46 |
+
from ..objects import _fmt, register_generated
|
| 47 |
+
from ..task_base import LFFTask, register_task
|
| 48 |
+
|
| 49 |
+
TT = "turntable_1"
|
| 50 |
+
TARGET = "butter_1"
|
| 51 |
+
ITEMS = (TARGET,)
|
| 52 |
+
BASKET = "basket_1"
|
| 53 |
+
MASS = {"butter_1": 0.20} # real-world order (the HOPE box weighs 5 g)
|
| 54 |
+
|
| 55 |
+
# turntable geometry (fixture frame: origin on the table top at the disc axis)
|
| 56 |
+
R = 0.17 # disc radius
|
| 57 |
+
DISC_T = 0.012 # disc thickness
|
| 58 |
+
BASE_H = 0.012 # pedestal height
|
| 59 |
+
DISC_TOP = BASE_H + DISC_T # disc top above the table
|
| 60 |
+
PEG_R, PEG_RAD, PEG_H = 0.009, 0.155, 0.035 # radius, distance from the axis, height above the disc
|
| 61 |
+
# (low enough that the hand clears the pegs by 1 cm when it grasps the butter between them)
|
| 62 |
+
PEG_ANG = tuple(np.pi / 4 + k * np.pi / 2 for k in range(4)) # disc frame
|
| 63 |
+
STRIPE_ANG = np.pi # disc frame
|
| 64 |
+
BOARD_Z = DISC_TOP + 0.10 # underside of the shelf board above the table
|
| 65 |
+
BOARD_EDGE = 0.01 # the board covers fixture y < +1 cm (the -y half of the disc)
|
| 66 |
+
HINGE = dict(damping=1.0, armature=0.3, frictionloss=0.01) # the disc stops within ~1 deg when released
|
| 67 |
+
ITEM_R = 0.07 # butter's distance from the axis (disc frame); open fingers at a held peg clear it by >= 1.2 cm
|
| 68 |
+
|
| 69 |
+
ANG_TOL = np.radians(15.0) # success: disc within 15 deg of its start angle (4 cm at the pegs, 2.6 cm at the stripe end)
|
| 70 |
+
BASKET_IN = 0.060 # LIBERO basket: half size of the inner floor
|
| 71 |
+
BASKET_RIM = 0.150
|
| 72 |
+
BASKET_FLOOR = 0.017
|
| 73 |
+
SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"'
|
| 74 |
+
|
| 75 |
+
NAMES = {TARGET: "butter"}
|
| 76 |
+
DESCR = {TARGET: "small orange box"}
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _wrap(a):
|
| 80 |
+
return float((a + np.pi) % (2 * np.pi) - np.pi)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _wrap_half(a):
|
| 84 |
+
return float((a + np.pi / 2) % np.pi - np.pi / 2)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _rot(a):
|
| 88 |
+
c, s = np.cos(a), np.sin(a)
|
| 89 |
+
return np.array([[c, -s], [s, c]])
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def turntable_xml(model_name):
|
| 93 |
+
"""Static pedestal + shelf board + side wall; a hinged disc (child body) with 4 pegs and painted marks."""
|
| 94 |
+
def geoms(kind, pos, size, rgba, coll=True, vis=True):
|
| 95 |
+
s = f'type="{kind}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(rgba)}"'
|
| 96 |
+
out = [f'<geom {s} conaffinity="0" contype="0" group="1" />'] if vis else []
|
| 97 |
+
if coll:
|
| 98 |
+
out.insert(0, f'<geom {s} friction="1.0 0.005 0.0001" {SOLID} density="400" group="0" />')
|
| 99 |
+
return out
|
| 100 |
+
|
| 101 |
+
shelf = (0.82, 0.82, 0.80, 1.0)
|
| 102 |
+
fixed = geoms("cylinder", (0, 0, BASE_H / 2), (0.06, BASE_H / 2), (0.3, 0.3, 0.3, 1.0))
|
| 103 |
+
by0, by1, bx = -(R + 0.04), BOARD_EDGE, R + 0.04
|
| 104 |
+
fixed += geoms("box", (0, (by0 + by1) / 2, BOARD_Z + 0.004), (bx, (by1 - by0) / 2, 0.004), shelf)
|
| 105 |
+
fixed += geoms("box", (0, by0 + 0.005, BOARD_Z / 2), (bx, 0.005, BOARD_Z / 2), shelf)
|
| 106 |
+
# the round disc is visual only; its collision surface is the inscribed square plate: a box on a cylinder gets a
|
| 107 |
+
# single contact point and no torsional friction, and the butter span on the disc at ~4 deg/s even at rest (measured)
|
| 108 |
+
disc = geoms("cylinder", (0, 0, 0), (R, DISC_T / 2), (0.62, 0.42, 0.24, 1.0), coll=False)
|
| 109 |
+
disc += geoms("box", (0, 0, 0), (R / np.sqrt(2), R / np.sqrt(2), DISC_T / 2), (0.62, 0.42, 0.24, 1.0), vis=False)
|
| 110 |
+
for a in PEG_ANG:
|
| 111 |
+
disc += geoms("cylinder", (PEG_RAD * np.cos(a), PEG_RAD * np.sin(a), DISC_T / 2 + PEG_H / 2),
|
| 112 |
+
(PEG_R, PEG_H / 2), (0.75, 0.08, 0.08, 1.0))
|
| 113 |
+
# painted marks (visual only) that make the disc's angle readable: yellow stripe, blue square, green dot
|
| 114 |
+
disc += geoms("box", (0.085 * np.cos(STRIPE_ANG), 0.085 * np.sin(STRIPE_ANG), DISC_T / 2 + 0.0006),
|
| 115 |
+
(0.055, 0.007, 0.0006), (0.95, 0.85, 0.10, 1.0), coll=False)
|
| 116 |
+
disc += geoms("box", (0.10 * np.cos(np.pi / 2), 0.10 * np.sin(np.pi / 2), DISC_T / 2 + 0.0006),
|
| 117 |
+
(0.016, 0.016, 0.0006), (0.15, 0.35, 0.85, 1.0), coll=False)
|
| 118 |
+
disc += geoms("cylinder", (0.10 * np.cos(-np.pi / 2), 0.10 * np.sin(-np.pi / 2), DISC_T / 2 + 0.0006),
|
| 119 |
+
(0.016, 0.0006), (0.15, 0.65, 0.25, 1.0), coll=False)
|
| 120 |
+
nl = "\n "
|
| 121 |
+
return f"""<mujoco model="{model_name}">
|
| 122 |
+
<worldbody>
|
| 123 |
+
<body>
|
| 124 |
+
<body name="object">
|
| 125 |
+
{nl.join(fixed)}
|
| 126 |
+
<body name="disc" pos="0 0 {BASE_H + DISC_T / 2:.5f}">
|
| 127 |
+
<joint name="spin" type="hinge" axis="0 0 1" pos="0 0 0" limited="false" damping="{HINGE['damping']}" armature="{HINGE['armature']}" frictionloss="{HINGE['frictionloss']}" />
|
| 128 |
+
{nl.join(disc)}
|
| 129 |
+
</body>
|
| 130 |
+
</body>
|
| 131 |
+
<site rgba="0 0 0 0" size="0.005" pos="0 0 0" name="bottom_site" />
|
| 132 |
+
<site rgba="0 0 0 0" size="0.005" pos="0 0 {BOARD_Z + 0.008:.5f}" name="top_site" />
|
| 133 |
+
<site rgba="0 0 0 0" size="0.005" pos="{R:.5f} {R:.5f} 0" name="horizontal_radius_site" />
|
| 134 |
+
</body>
|
| 135 |
+
</worldbody>
|
| 136 |
+
</mujoco>
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
@register_task
|
| 141 |
+
class TurntableRestore(LFFTask):
|
| 142 |
+
name = "l2_turntable_restore"
|
| 143 |
+
level = "L2"
|
| 144 |
+
category = "state_restoration"
|
| 145 |
+
capabilities = ("Perceive", "Save", "Retrieve", "Utilize")
|
| 146 |
+
protocol = "within"
|
| 147 |
+
max_attempts = 5
|
| 148 |
+
instruction = ("Put the butter into the basket. The butter is on the turntable, under the shelf. You can turn the "
|
| 149 |
+
"turntable by its red pegs. When you are done, the turntable must be turned exactly the way it is now.")
|
| 150 |
+
instruction_indirect = ("Put the small orange box into the wicker basket. It is on the round turntable, under the "
|
| 151 |
+
"shelf. You can turn the turntable by its red pegs. When you are done, the turntable must be "
|
| 152 |
+
"turned exactly the way it is now.")
|
| 153 |
+
|
| 154 |
+
def __init__(self, cam_res=None):
|
| 155 |
+
super().__init__(cam_res)
|
| 156 |
+
m = self.env.sim.model
|
| 157 |
+
self._tt_bid = m.body_name2id(self.env.fixtures_dict[TT].root_body)
|
| 158 |
+
jid = m.joint_name2id(f"{TT}_spin")
|
| 159 |
+
self._qa, self._qv = m.jnt_qposadr[jid], m.jnt_dofadr[jid]
|
| 160 |
+
self.start = {}
|
| 161 |
+
self.turn_log = [] # per peg grasp: commanded sweep vs measured disc rotation (diagnostics)
|
| 162 |
+
self._home = None
|
| 163 |
+
self._c = np.zeros(2)
|
| 164 |
+
|
| 165 |
+
# ------------------------------------------------------------ scene
|
| 166 |
+
def make_bddl(self):
|
| 167 |
+
tt = register_generated("LffTurntableShelf", turntable_xml("lff_turntable_shelf"), free=False)
|
| 168 |
+
objs = [(n, n[:-2], f"r_{i}", (0.20, -0.25 + 0.15 * i, 0.22, -0.23 + 0.15 * i)) for i, n in enumerate(ITEMS)]
|
| 169 |
+
objs.append((BASKET, "basket", "r_basket", (-0.10, 0.24, -0.08, 0.26)))
|
| 170 |
+
fx = [(TT, tt, "tt_region", (0.25, 0.30, 0.27, 0.32))] # moved in apply_instance
|
| 171 |
+
return write_bddl(self.name, self.instruction.replace(";", ","), objs, fixtures=fx)
|
| 172 |
+
|
| 173 |
+
def sample_instance(self, seed):
|
| 174 |
+
rng = np.random.default_rng(seed)
|
| 175 |
+
c = np.array([rng.uniform(-0.08, -0.02), rng.uniform(-0.12, -0.08)])
|
| 176 |
+
th = {TARGET: float(rng.uniform(-0.14, 0.14))} # disc-frame angle of the butter (stripe at 180 deg)
|
| 177 |
+
rad = {n: float(ITEM_R + rng.uniform(-0.005, 0.005)) for n in ITEMS}
|
| 178 |
+
tilt = {n: float(rng.uniform(-0.17, 0.17)) for n in ITEMS} # box yaw relative to radial
|
| 179 |
+
# start angle: the butter sits under the board (world azimuth -90 +- 40 deg about the axis)
|
| 180 |
+
q0 = float(_wrap(-np.pi / 2 - th[TARGET] + rng.uniform(-np.radians(40), np.radians(40))))
|
| 181 |
+
return dict(seed=int(seed), center=c.round(4).tolist(), q0=q0, theta=th, rad=rad, tilt=tilt,
|
| 182 |
+
basket_xy=[float(rng.uniform(-0.12, -0.06)), float(rng.uniform(0.25, 0.28))])
|
| 183 |
+
|
| 184 |
+
def disc_angle(self):
|
| 185 |
+
return float(self.env.sim.data.qpos[self._qa])
|
| 186 |
+
|
| 187 |
+
def to_world(self, r, th, q=None):
|
| 188 |
+
q = self.disc_angle() if q is None else q
|
| 189 |
+
return self._c + r * np.array([np.cos(th + q), np.sin(th + q)])
|
| 190 |
+
|
| 191 |
+
def to_disc(self, xy, q=None):
|
| 192 |
+
q = self.disc_angle() if q is None else q
|
| 193 |
+
return _rot(-q) @ (np.asarray(xy, float)[:2] - self._c)
|
| 194 |
+
|
| 195 |
+
def place(self, name, xy, yaw, surface_z):
|
| 196 |
+
"""Teleport a box flat (its mesh frame is flat) with yaw about world z, lowest point 2 mm above surface_z."""
|
| 197 |
+
envs.set_obj_pose(self.env, name, [xy[0], xy[1], surface_z + 0.3],
|
| 198 |
+
quat_wxyz=np.array([np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)]))
|
| 199 |
+
self.env.sim.forward()
|
| 200 |
+
dz = envs.obj_min_z(self.env, name) - (surface_z + 0.002)
|
| 201 |
+
qa, _ = envs.free_joint_addr(self.env, name)
|
| 202 |
+
self.env.sim.data.qpos[qa + 2] -= dz
|
| 203 |
+
self.env.sim.forward()
|
| 204 |
+
|
| 205 |
+
def apply_instance(self, inst):
|
| 206 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 207 |
+
self._c = np.array(inst["center"], float)
|
| 208 |
+
m.body_pos[self._tt_bid] = [self._c[0], self._c[1], envs.TABLE_Z]
|
| 209 |
+
m.body_quat[self._tt_bid] = [1, 0, 0, 0]
|
| 210 |
+
d.qpos[self._qa] = inst["q0"]
|
| 211 |
+
d.qvel[self._qv] = 0.0
|
| 212 |
+
self.env.sim.forward()
|
| 213 |
+
for n in ITEMS:
|
| 214 |
+
envs.scale_mass(self.env, n, MASS[n])
|
| 215 |
+
th = inst["theta"][n]
|
| 216 |
+
# long axis radial (+ tilt): the gripper then closes tangentially and keeps clear of the board
|
| 217 |
+
self.place(n, self.to_world(inst["rad"][n], th, inst["q0"]), th + inst["q0"] + inst["tilt"][n],
|
| 218 |
+
envs.TABLE_Z + DISC_TOP)
|
| 219 |
+
envs.scale_mass(self.env, BASKET, 2.0)
|
| 220 |
+
self.place(BASKET, inst["basket_xy"], 0.0, envs.TABLE_Z)
|
| 221 |
+
self.env.sim.forward()
|
| 222 |
+
|
| 223 |
+
def reset_instance(self, inst, recorder=None):
|
| 224 |
+
sk = super().reset_instance(inst, recorder)
|
| 225 |
+
self.start = dict(q=self.disc_angle())
|
| 226 |
+
self._home = sk.eef_pos()
|
| 227 |
+
return sk
|
| 228 |
+
|
| 229 |
+
# ------------------------------------------------------------ measurements
|
| 230 |
+
def footprint(self, name):
|
| 231 |
+
"""AABB centre, yaw of the long horizontal axis, z range (scripted 'perception')."""
|
| 232 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 233 |
+
lo, hi = np.full(3, np.inf), np.full(3, -np.inf)
|
| 234 |
+
best = None
|
| 235 |
+
for g in envs.obj_geom_ids(self.env, name):
|
| 236 |
+
Rg = d.geom_xmat[g].reshape(3, 3)
|
| 237 |
+
c = d.geom_xpos[g] + Rg @ m.geom_aabb[g, :3]
|
| 238 |
+
e = np.abs(Rg) @ m.geom_aabb[g, 3:]
|
| 239 |
+
lo, hi = np.minimum(lo, c - e), np.maximum(hi, c + e)
|
| 240 |
+
vol = float(np.prod(m.geom_aabb[g, 3:]))
|
| 241 |
+
if best is None or vol > best[0]:
|
| 242 |
+
best = (vol, Rg, m.geom_aabb[g, 3:])
|
| 243 |
+
_, Rg, half = best
|
| 244 |
+
horiz = sorted([(half[k], Rg[:, k]) for k in range(3) if abs(Rg[2, k]) < 0.5], key=lambda t: -t[0])
|
| 245 |
+
ax = horiz[0][1] if horiz else np.array([1.0, 0.0, 0.0])
|
| 246 |
+
return dict(center=[float(v) for v in (lo + hi) / 2], yaw=float(np.arctan2(ax[1], ax[0])),
|
| 247 |
+
zmin=float(lo[2]), zmax=float(hi[2]))
|
| 248 |
+
|
| 249 |
+
def item_loc(self, name):
|
| 250 |
+
f = self.footprint(name)
|
| 251 |
+
c = np.array(f["center"])
|
| 252 |
+
held = self.sk is not None and self.sk.holding(name)
|
| 253 |
+
if held and f["zmin"] > envs.TABLE_Z + DISC_TOP + 0.01:
|
| 254 |
+
return "gripper", f
|
| 255 |
+
bp = envs.obj_pos(self.env, BASKET)
|
| 256 |
+
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 \
|
| 257 |
+
and f["zmin"] > envs.TABLE_Z + 0.005:
|
| 258 |
+
return "basket", f
|
| 259 |
+
on_disc = np.linalg.norm(c[:2] - self._c) < R and abs(f["zmin"] - (envs.TABLE_Z + DISC_TOP)) < 0.012
|
| 260 |
+
if on_disc:
|
| 261 |
+
return "turntable", f
|
| 262 |
+
if f["zmin"] < envs.TABLE_Z + 0.01:
|
| 263 |
+
return "table", f
|
| 264 |
+
return "other", f
|
| 265 |
+
|
| 266 |
+
def outcome(self, inst):
|
| 267 |
+
envs.settle(self.env, 30)
|
| 268 |
+
tloc, _ = self.item_loc(TARGET)
|
| 269 |
+
dq = _wrap(self.disc_angle() - self.start["q"])
|
| 270 |
+
turned_ok = abs(dq) <= ANG_TOL
|
| 271 |
+
success = bool(tloc == "basket" and turned_ok)
|
| 272 |
+
return dict(success=success, target_loc=tloc, angle_err_deg=round(float(np.degrees(dq)), 1),
|
| 273 |
+
turned_ok=bool(turned_ok),
|
| 274 |
+
detail=self._describe(tloc, turned_ok, dq, NAMES),
|
| 275 |
+
detail_indirect=self._describe(tloc, turned_ok, dq, DESCR),
|
| 276 |
+
detail_offset=self._describe(tloc, turned_ok, dq, NAMES, offset=True))
|
| 277 |
+
|
| 278 |
+
@staticmethod
|
| 279 |
+
def _describe(tloc, turned_ok, dq, names, offset=False):
|
| 280 |
+
tn = names[TARGET]
|
| 281 |
+
msgs = []
|
| 282 |
+
if tloc != "basket":
|
| 283 |
+
msgs.append({"gripper": f"The {tn} is still in the gripper, not in the basket.",
|
| 284 |
+
"turntable": f"The {tn} is still on the turntable, not in the basket.",
|
| 285 |
+
"table": f"The {tn} is on the table, not in the basket."}
|
| 286 |
+
.get(tloc, f"The {tn} is not in the basket."))
|
| 287 |
+
if not turned_ok:
|
| 288 |
+
m = "The turntable is not turned the way it was at the start."
|
| 289 |
+
if offset: # ablation tier: relative measurement, externalises the memory
|
| 290 |
+
m += (f" It is turned {abs(np.degrees(dq)):.0f} deg "
|
| 291 |
+
f"{'counter-clockwise' if dq > 0 else 'clockwise'} (seen from above) from its starting angle.")
|
| 292 |
+
msgs.append(m)
|
| 293 |
+
if not msgs:
|
| 294 |
+
msgs.append(f"The {tn} is in the basket and the turntable is turned the way it was at the start.")
|
| 295 |
+
return " ".join(msgs)
|
| 296 |
+
|
| 297 |
+
def feedback(self, inst, out, level="F2", indirect=False, offset=False):
|
| 298 |
+
"""F0: nothing, F1: success flag, F2: what is wrong (never by how much the turntable is off).
|
| 299 |
+
offset=True (ablation tier 'F2+offset'): also the relative turn from the start angle."""
|
| 300 |
+
if level == "F2":
|
| 301 |
+
key = "detail_offset" if offset else ("detail_indirect" if indirect else "detail")
|
| 302 |
+
out = dict(out, detail=out.get(key, out["detail"]))
|
| 303 |
+
return super().feedback(inst, out, level)
|
| 304 |
+
|
| 305 |
+
# ------------------------------------------------------------ scripted motions (Skills.move_to / set_gripper)
|
| 306 |
+
SAFE_Z = envs.TABLE_Z + 0.22 # travel height between pegs / items
|
| 307 |
+
PICK_AZ = np.pi / 2 # where the butter is brought: middle of the open side (at 135 deg the open finger lands on
|
| 308 |
+
# the board edge -- measured); grasp yaw ~ +-90 deg, so the wrist is turned back to 0 while
|
| 309 |
+
# carrying (arriving at the basket with yaw -103 deg left the arm stalled near a joint limit)
|
| 310 |
+
WIN = (np.radians(30), np.radians(150)) # world azimuths where a peg can be held (open side, clear of the board)
|
| 311 |
+
|
| 312 |
+
def go_home(self):
|
| 313 |
+
sk = self.sk
|
| 314 |
+
p = sk.eef_pos()
|
| 315 |
+
sk.move_to([p[0], p[1], max(p[2], self._home[2])])
|
| 316 |
+
sk.move_to(self._home, yaw=0.0)
|
| 317 |
+
|
| 318 |
+
def _settle_yaw(self, tol=np.radians(3), max_steps=40):
|
| 319 |
+
"""move_to stops on position only; after a large wrist rotation hold until the yaw has converged (a descent
|
| 320 |
+
that starts mid-rotation swipes the open fingers across the pegs -- measured)."""
|
| 321 |
+
sk = self.sk
|
| 322 |
+
for _ in range(max_steps // 5):
|
| 323 |
+
R = sk.eef_mat() @ sk.R0.T
|
| 324 |
+
if abs(_wrap(np.arctan2(R[1, 0], R[0, 0]) - sk.yaw)) < tol:
|
| 325 |
+
return
|
| 326 |
+
sk.hold(5)
|
| 327 |
+
|
| 328 |
+
def peg_azimuths(self):
|
| 329 |
+
return [_wrap(self.disc_angle() + a) for a in PEG_ANG]
|
| 330 |
+
|
| 331 |
+
def turn(self, delta, step=np.radians(10)):
|
| 332 |
+
"""Turn the disc by `delta` rad (+ = counter-clockwise seen from above): grasp a peg on the open side,
|
| 333 |
+
move the gripper along the rim in short straight segments, release, repeat."""
|
| 334 |
+
sk = self.sk
|
| 335 |
+
zg = envs.TABLE_Z + DISC_TOP + PEG_H - 0.012
|
| 336 |
+
rem = float(delta)
|
| 337 |
+
for _ in range(6):
|
| 338 |
+
if abs(rem) < np.radians(1.0):
|
| 339 |
+
break
|
| 340 |
+
az = self.peg_azimuths()
|
| 341 |
+
if rem > 0:
|
| 342 |
+
cands = [a for a in az if self.WIN[0] - 1e-6 <= a <= self.WIN[1] - np.radians(10)]
|
| 343 |
+
a0 = min(cands)
|
| 344 |
+
sweep = min(rem, self.WIN[1] - a0)
|
| 345 |
+
else:
|
| 346 |
+
cands = [a for a in az if self.WIN[0] + np.radians(10) <= a <= self.WIN[1] + 1e-6]
|
| 347 |
+
a0 = max(cands)
|
| 348 |
+
sweep = max(rem, self.WIN[0] - a0)
|
| 349 |
+
q_before = self.disc_angle()
|
| 350 |
+
p = self._c + PEG_RAD * np.array([np.cos(a0), np.sin(a0)])
|
| 351 |
+
sk.set_gripper(False, steps=6)
|
| 352 |
+
# up, across, straight down: a long diagonal move at full speed sags ~5 cm below its line and the open
|
| 353 |
+
# fingers sweep the disc (measured: turned it 38 deg the wrong way)
|
| 354 |
+
cur = sk.eef_pos()
|
| 355 |
+
if cur[2] < self.SAFE_Z - 0.02:
|
| 356 |
+
sk.move_to([cur[0], cur[1], self.SAFE_Z])
|
| 357 |
+
sk.move_to([p[0], p[1], self.SAFE_Z], yaw=np.pi / 2) # fingers close along world x
|
| 358 |
+
self._settle_yaw()
|
| 359 |
+
sk.move_to([p[0], p[1], zg + 0.03], speed=0.4)
|
| 360 |
+
sk.move_to([p[0], p[1], zg], tol=0.003, max_steps=80)
|
| 361 |
+
sk.set_gripper(True, steps=12)
|
| 362 |
+
dbg = dict(off=np.round((sk.eef_pos() - np.r_[self._c + PEG_RAD * np.array([np.cos(a0), np.sin(a0)]), zg]) * 100, 1).tolist(),
|
| 363 |
+
w=round(sk.gripper_width() * 100, 1), q_close=round(float(np.degrees(_wrap(self.disc_angle() - q_before))), 1),
|
| 364 |
+
yaw=round(float(np.degrees(sk.yaw)), 0))
|
| 365 |
+
k = max(1, int(np.ceil(abs(sweep) / step)))
|
| 366 |
+
for i in range(1, k + 1):
|
| 367 |
+
w = self._c + PEG_RAD * np.array([np.cos(a0 + sweep * i / k), np.sin(a0 + sweep * i / k)])
|
| 368 |
+
sk.move_to([w[0], w[1], zg], tol=0.003, max_steps=40)
|
| 369 |
+
sk.set_gripper(False, steps=8)
|
| 370 |
+
pe = sk.eef_pos()
|
| 371 |
+
sk.move_to([pe[0], pe[1], zg + 0.10])
|
| 372 |
+
got = _wrap(self.disc_angle() - q_before)
|
| 373 |
+
self.turn_log.append(dict(peg_az=round(float(np.degrees(a0)), 1), sweep=round(float(np.degrees(sweep)), 1),
|
| 374 |
+
got=round(float(np.degrees(got)), 1), **dbg))
|
| 375 |
+
rem -= got
|
| 376 |
+
|
| 377 |
+
def pick_place(self, name, dest_xy, support_z, fp=None, carry_z=1.20, travel_z=1.15, carry_yaw=0.0):
|
| 378 |
+
"""Top-down pick across the short side, carry, release just above support_z at dest_xy."""
|
| 379 |
+
sk = self.sk
|
| 380 |
+
f = fp or self.footprint(name)
|
| 381 |
+
c = np.array(f["center"])
|
| 382 |
+
gyaw = _wrap_half(f["yaw"])
|
| 383 |
+
zg = max(f["zmin"] + 0.5 * (f["zmax"] - f["zmin"]), f["zmin"] + 0.0145)
|
| 384 |
+
sk.set_gripper(False, steps=6)
|
| 385 |
+
p = sk.eef_pos()
|
| 386 |
+
if p[2] < travel_z - 0.02:
|
| 387 |
+
sk.move_to([p[0], p[1], travel_z])
|
| 388 |
+
sk.move_to([c[0], c[1], travel_z], yaw=gyaw)
|
| 389 |
+
self._settle_yaw()
|
| 390 |
+
sk.move_to([c[0], c[1], f["zmax"] + 0.03], speed=0.4)
|
| 391 |
+
sk.move_to([c[0], c[1], zg], tol=0.003, max_steps=80)
|
| 392 |
+
sk.set_gripper(True, steps=12)
|
| 393 |
+
sk.move_to([c[0], c[1], carry_z], speed=0.3)
|
| 394 |
+
sk.move_to([dest_xy[0], dest_xy[1], carry_z], yaw=carry_yaw)
|
| 395 |
+
sk.move_to([dest_xy[0], dest_xy[1], support_z + (zg - f["zmin"]) + 0.006], tol=0.003, speed=0.2, max_steps=150)
|
| 396 |
+
sk.hold(4)
|
| 397 |
+
sk.set_gripper(False, steps=10)
|
| 398 |
+
sk.move_to([dest_xy[0], dest_xy[1], travel_z], speed=0.4)
|
| 399 |
+
|
| 400 |
+
def butter_to_basket(self, fp=None):
|
| 401 |
+
"""The main task: if the butter is on the turntable, turn it to the open side first."""
|
| 402 |
+
loc, f = self.item_loc(TARGET)
|
| 403 |
+
if loc == "turntable":
|
| 404 |
+
az = np.arctan2(f["center"][1] - self._c[1], f["center"][0] - self._c[0])
|
| 405 |
+
# bring the butter's long axis parallel to world y (then the hand lies along x, away from the board edge;
|
| 406 |
+
# a hand turned 26 deg off caught the board -- measured); its centre ends within ~30 deg of PICK_AZ
|
| 407 |
+
delta = _wrap_half(f["yaw"] - az)
|
| 408 |
+
self.turn(_wrap(self.PICK_AZ - delta - az))
|
| 409 |
+
b = envs.obj_pos(self.env, BASKET)
|
| 410 |
+
# release with the hand above the rim and let the box drop in: lowering it to the floor puts the 20 cm long
|
| 411 |
+
# hand below the rim of the 12 cm basket and the contact flips the wrist (joint 5 at its limit -- measured)
|
| 412 |
+
self.pick_place(TARGET, b[:2], envs.obj_min_z(self.env, BASKET) + BASKET_RIM + 0.02, fp=fp)
|
| 413 |
+
|
| 414 |
+
def do(self, actions):
|
| 415 |
+
for act in actions:
|
| 416 |
+
if act[0] == "butter_to_basket":
|
| 417 |
+
self.butter_to_basket(fp=act[1] if len(act) > 1 else None)
|
| 418 |
+
elif act[0] == "turn_to": # ["turn_to", absolute disc angle (the agent's remembered start angle)]
|
| 419 |
+
self.turn(_wrap(act[1] - self.disc_angle()))
|
| 420 |
+
elif act[0] == "turn_by":
|
| 421 |
+
self.turn(act[1])
|
| 422 |
+
else:
|
| 423 |
+
raise ValueError(act)
|
| 424 |
+
|
| 425 |
+
# ------------------------------------------------------------ scripted reference policies
|
| 426 |
+
def _plan(self, kind, inst, a, history, rng, memory):
|
| 427 |
+
if kind == "naive" or (a == 0 and kind in ("adaptive", "blind", "nomem")):
|
| 428 |
+
return [["butter_to_basket"]]
|
| 429 |
+
if kind == "oracle":
|
| 430 |
+
return [["butter_to_basket"], ["turn_to", memory["q"]]]
|
| 431 |
+
last = history[-1]["outcome"]
|
| 432 |
+
acts = [] if last["target_loc"] == "basket" else [["butter_to_basket"]]
|
| 433 |
+
if kind == "adaptive":
|
| 434 |
+
return acts + ([] if last["turned_ok"] else [["turn_to", memory["q"]]])
|
| 435 |
+
if kind == "nomem":
|
| 436 |
+
return acts + ([] if last["turned_ok"] else [["turn_by", float(rng.uniform(-np.pi, np.pi))]])
|
| 437 |
+
if kind == "blind":
|
| 438 |
+
fp = self.footprint(TARGET)
|
| 439 |
+
fp["center"] = (np.array(fp["center"]) + np.r_[rng.normal(0, 0.005, 2), 0.0]).tolist()
|
| 440 |
+
return [["butter_to_basket", fp]]
|
| 441 |
+
raise ValueError(kind)
|
| 442 |
+
|
| 443 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 444 |
+
"""Within-episode protocol: one reset, attempt 1 = main task, attempts 2..k = corrective rounds."""
|
| 445 |
+
k = k or self.max_attempts
|
| 446 |
+
rng = np.random.default_rng(seed)
|
| 447 |
+
history = []
|
| 448 |
+
self.reset_instance(inst)
|
| 449 |
+
memory = dict(q=self.disc_angle()) # Save: the start angle (an agent reads it off the first frame)
|
| 450 |
+
for a in range(k):
|
| 451 |
+
actions = self._plan(kind, inst, a, history, rng, memory)
|
| 452 |
+
self.do(actions)
|
| 453 |
+
self.go_home()
|
| 454 |
+
out = self.outcome(inst)
|
| 455 |
+
params = dict(actions=[[x[0]] + ([round(float(np.degrees(x[1])), 1)] if x[0] != "butter_to_basket" else [])
|
| 456 |
+
for x in actions])
|
| 457 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 458 |
+
if on_attempt:
|
| 459 |
+
on_attempt(a, params, out)
|
| 460 |
+
if out["success"] or kind in ("oracle", "naive"):
|
| 461 |
+
break
|
| 462 |
+
return history
|
| 463 |
+
|
| 464 |
+
# cross-protocol hooks are not used by this task
|
| 465 |
+
def default_params(self, inst):
|
| 466 |
+
return dict(policy="naive")
|
| 467 |
+
|
| 468 |
+
def oracle_params(self, inst):
|
| 469 |
+
return dict(policy="oracle")
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/tasks/l3_card_shelf.py
ADDED
|
@@ -0,0 +1,587 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L3 card_shelf (2026-10-12): a deepened l3_card_edge. The thin card lies on a raised SHELF (thin top on four legs)
|
| 2 |
+
and hides a weight in one end; sliding the heavy end over the edge far enough to grasp it tips the card off the shelf
|
| 3 |
+
onto the table, where it lies flat and cannot be picked up: the attempt is lost.
|
| 4 |
+
|
| 5 |
+
Why (../research_notes/P1P2_加深与常识任务设计.md sec. 1, 3.2): l3_card_edge saturated. Sonnet 5.5 (cla4) failed one
|
| 6 |
+
flat grasp, then in the same attempt slid the card 2-3 cm over the board's edge and grasped the overhang (both runs
|
| 7 |
+
succeeded on attempt 1): the failed grasp costs one command and changes nothing. Here the first common-sense
|
| 8 |
+
interaction (slide the nearest end out ~3 cm) has an irreversible cost whenever that end is the heavy one.
|
| 9 |
+
|
| 10 |
+
Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): a wooden shelf
|
| 11 |
+
(top 22 x 26 x 1 cm on four 2 x 2 cm legs, top surface 10 cm above the table) with a thin red card (9.0 x 5.6 x 0.2 cm)
|
| 12 |
+
lying flat on it, long side along x or along y (+-8 deg). Its near end is 2.5-4 cm from the shelf edge it points to (an
|
| 13 |
+
x-card's near end is always the FORWARD one: a card that tips off the backward edge lands behind the shelf, hidden from
|
| 14 |
+
the front camera), the far end 9-14 cm from the opposite edge, both long sides >= 5 cm inside; a grey bin (16 x 16 cm
|
| 15 |
+
inside, 5 cm high) stands on the table beside the shelf (left or right, 6 cm gap). Same card size, mass (10 g),
|
| 16 |
+
friction and bin as l3_card_edge.
|
| 17 |
+
|
| 18 |
+
Hidden variable (instance level, the same in every attempt, invisible): 8 of the card's 10 g are a weight hidden in one
|
| 19 |
+
end; its centre of mass sits COM_E = 2.8 cm from the middle towards that end. Both ends look identical. In 14 of every
|
| 20 |
+
20 consecutive seeds the heavy end is the NEAR end (the end a Sonnet-like agent slides out), else the far end.
|
| 21 |
+
|
| 22 |
+
Mechanism (physics, no teleport): an end slid out by h tips over the edge once the centre of mass passes it. Measured
|
| 23 |
+
(card teleported with overhang h, 2 s): heavy end stays for h <= 1.7 cm, tips for h >= 1.8 cm; light end stays up to
|
| 24 |
+
7.0 cm; a uniform card up to ~4.5 cm. The grasp of an overhang needs the fingers past the edge: light end 1.8-3.8 cm
|
| 25 |
+
out -> 11/12 grasped; the heavy end only in a narrow window (1.3-1.5 cm out, grasp 0.8-1.2 cm beyond the edge: 12/36).
|
| 26 |
+
A tipped card is flat on the table within 0.4 s (56/56 tilt 0), where it cannot be gripped (0/56 regrasps) and no edge
|
| 27 |
+
is in reach. The fix is to slide the OTHER end out (a longer slide across the shelf), learnable from the failure: "only
|
| 28 |
+
~2 cm out and it already tipped -> that end is heavy" (the cheaper explanation "I pushed too far" leads to pushing
|
| 29 |
+
less, which leaves too little overhang to grasp). Validation (seeds 1000-1019): Sonnet-like naive tips 14/14 heavy-near
|
| 30 |
+
instances and succeeds on 6/6 light-near ones; the same habit succeeds 20/20 on l3_card_edge and 20/20 here with a
|
| 31 |
+
uniform card.
|
| 32 |
+
|
| 33 |
+
Implementation notes: the centre of mass is fixed in the generated MJCF (explicit <inertial pos="COM_E 0 0">) and the
|
| 34 |
+
heavy end is chosen by the card's yaw (the card is symmetric), so the body's inertial frame is never changed at runtime
|
| 35 |
+
(no bounding-volume refit needed; see lh_fence / envs.refit_bounds for that MuJoCo pitfall). The inertia is written in
|
| 36 |
+
scientific notation: objects._fmt (5 decimals) rounds a 10-30 g card's inertia to ~0 (a 10 g card does not compile; a
|
| 37 |
+
30 g card with rounded inertia got pinched and lifted by the flat grasp 4/16). Mass 10 g as in l3_card_edge: the flat
|
| 38 |
+
grasp then fails 20/20 (fingers slide over the card). The shelf is a static multi-geom fixture; its legs stand inside
|
| 39 |
+
its top's footprint (robot-leg contacts: 0 in all scripted runs).
|
| 40 |
+
|
| 41 |
+
Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: success = the card lies in the bin,
|
| 42 |
+
not held; plus a per-step event log (end / side slid over an edge, tipped_off, lifted, released, in_bin, hand_hit_leg)
|
| 43 |
+
and R6 fields (tipped_off, trap_fired, grasp_tries) for the server log; F1 gives the agent only success / failure.
|
| 44 |
+
"""
|
| 45 |
+
import numpy as np
|
| 46 |
+
|
| 47 |
+
from .. import envs
|
| 48 |
+
from ..bddl import write_bddl
|
| 49 |
+
from ..objects import _SOLID, _fmt, _wrap, bin_xml, register_generated
|
| 50 |
+
from ..skills import Skills
|
| 51 |
+
from ..task_base import LFFTask, register_task
|
| 52 |
+
|
| 53 |
+
TZ = envs.TABLE_Z
|
| 54 |
+
CARD_HALF = (0.045, 0.028, 0.001) # 9.0 x 5.6 x 0.2 cm (as l3_card_edge)
|
| 55 |
+
CARD_MASS = 0.010 # as l3_card_edge (flat grasp fails 20/20; a 30 g card was pinched and lifted 4/16)
|
| 56 |
+
SLUG_MASS = 0.008 # hidden weight (+ 2 g of card); slug centre 3.5 cm from the middle
|
| 57 |
+
COM_E = 0.028 # centre of mass this far from the card's middle, towards the heavy end (the card's local +x)
|
| 58 |
+
MU = 0.3 # card and shelf sliding friction (as l3_card_edge)
|
| 59 |
+
SHELF_HALF = (0.11, 0.13) # top half extents (as l3_card_edge's board)
|
| 60 |
+
SHELF_H = 0.10 # top surface above the table
|
| 61 |
+
TOP_T = 0.01 # top thickness
|
| 62 |
+
LEG = 0.01 # leg half width (2 x 2 cm legs)
|
| 63 |
+
LEG_IN = 0.012 # leg centre to the top's edges
|
| 64 |
+
SHELF_TOP = TZ + SHELF_H
|
| 65 |
+
CARD_REST_Z = SHELF_TOP + CARD_HALF[2]
|
| 66 |
+
BIN_IN = 0.08 # inner half width
|
| 67 |
+
BIN_WALL_H = 0.05
|
| 68 |
+
BIN_GAP = 0.06 # shelf edge to bin outer wall
|
| 69 |
+
BIN_T = 0.006
|
| 70 |
+
BIN_HALF_OUT = BIN_IN + BIN_T
|
| 71 |
+
TIP_BELOW_SITE = envs.FINGERTIP_BELOW_SITE
|
| 72 |
+
LOW_CLOSE = 0.02 # a close counts as a grasp try when the fingertips are at most this far above the card
|
| 73 |
+
|
| 74 |
+
# instance ranges
|
| 75 |
+
P_HEAVY_NEAR = 0.7 # 14 of every 20 consecutive seeds
|
| 76 |
+
NEAR_GAP = (0.025, 0.040) # near end to its shelf edge
|
| 77 |
+
SIDE_CLEAR = 0.05 # long sides to the shelf's side edges, at least
|
| 78 |
+
YAW_JIT = np.radians(8.0)
|
| 79 |
+
|
| 80 |
+
# scripted policies
|
| 81 |
+
GRASP_OUT = 0.022 # grasp point this far beyond the edge (fingers must clear the edge)
|
| 82 |
+
DRAG_SPEED = 0.08
|
| 83 |
+
NAIVE_STEPS = (0.0, 0.01, 0.02, 0.03) # Sonnet-like: slide the end to the edge, then out in 1 cm steps, lift & look
|
| 84 |
+
ORACLE_STEPS = (0.02, 0.03) # l3_card_edge oracle: to 1 cm short, look, the rest
|
| 85 |
+
|
| 86 |
+
EDGES = ("forward", "backward", "left", "right") # shelf edges in robot-centric words (+x, -x, +y, -y)
|
| 87 |
+
EDGE_U = {"forward": (1.0, 0.0), "backward": (-1.0, 0.0), "left": (0.0, 1.0), "right": (0.0, -1.0)}
|
| 88 |
+
OPPOSITE = {"forward": "backward", "backward": "forward", "left": "right", "right": "left"}
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def card_xml(name, rgba=(0.85, 0.15, 0.12, 1.0)):
|
| 92 |
+
"""Uniform-looking card; the inertial (10 g, centre of mass COM_E along local +x) models an 8 g weight hidden in
|
| 93 |
+
the +x end. Explicit inertial pos != 0, so MuJoCo keeps a separate inertial frame (see module doc)."""
|
| 94 |
+
h = CARD_HALF
|
| 95 |
+
ms = CARD_MASS - SLUG_MASS
|
| 96 |
+
xs = COM_E * CARD_MASS / SLUG_MASS # slug centre
|
| 97 |
+
sl = (0.0075, 0.021, h[2]) # slug half extents (1.5 x 4.2 x 0.2 cm)
|
| 98 |
+
box_i = lambda mm, a: mm / 3 * np.array([a[1] ** 2 + a[2] ** 2, a[0] ** 2 + a[2] ** 2, a[0] ** 2 + a[1] ** 2])
|
| 99 |
+
par = lambda mm, r: mm * np.array([r[1] ** 2 + r[2] ** 2, r[0] ** 2 + r[2] ** 2, r[0] ** 2 + r[1] ** 2])
|
| 100 |
+
c = np.array([COM_E, 0.0, 0.0])
|
| 101 |
+
inertia = box_i(ms, h) + par(ms, -c) + box_i(SLUG_MASS, sl) + par(SLUG_MASS, np.array([xs, 0.0, 0.0]) - c)
|
| 102 |
+
g = (f' <inertial pos="{_fmt(c)}" mass="{CARD_MASS}" diaginertia="{" ".join(f"{v:.6e}" for v in inertia)}" />\n'
|
| 103 |
+
f' <geom name="{name}_g0" type="box" size="{_fmt(h)}" rgba="{_fmt(rgba)}" '
|
| 104 |
+
f'friction="{MU} 0.005 0.0001" {_SOLID} group="0" condim="4"/>\n'
|
| 105 |
+
f' <geom type="box" size="{_fmt(h)}" rgba="{_fmt(rgba)}" contype="0" conaffinity="0" group="1"/>')
|
| 106 |
+
return _wrap(name, g, h[2], float(np.hypot(h[0], h[1])))
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def shelf_xml(name, rgba=(0.62, 0.45, 0.27, 1.0), leg_rgba=(0.50, 0.36, 0.21, 1.0)):
|
| 110 |
+
"""Static shelf: top plate on four legs; body origin at mid height (top surface at +SHELF_H / 2)."""
|
| 111 |
+
hx, hy = SHELF_HALF
|
| 112 |
+
H = SHELF_H / 2
|
| 113 |
+
parts = [((0.0, 0.0, H - TOP_T / 2), (hx, hy, TOP_T / 2), rgba)]
|
| 114 |
+
for sx in (-1, 1):
|
| 115 |
+
for sy in (-1, 1):
|
| 116 |
+
parts.append(((sx * (hx - LEG_IN), sy * (hy - LEG_IN), -TOP_T / 2), (LEG, LEG, H - TOP_T / 2), leg_rgba))
|
| 117 |
+
g = []
|
| 118 |
+
for k, (p, s, c) in enumerate(parts):
|
| 119 |
+
g.append(f' <geom name="{name}_g{k}" type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" '
|
| 120 |
+
f'density="500" friction="{MU} 0.005 0.0001" {_SOLID} group="0" />')
|
| 121 |
+
g.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" contype="0" '
|
| 122 |
+
f'conaffinity="0" group="1" />')
|
| 123 |
+
return _wrap(name, "\n".join(g), H, float(np.hypot(hx, hy)))
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _yaw_of(quat_wxyz):
|
| 127 |
+
w, x, y, z = quat_wxyz
|
| 128 |
+
return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)))
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class ShelfSkills(Skills):
|
| 132 |
+
"""Skills that feed the task's per-step monitor and log every close of the gripper."""
|
| 133 |
+
|
| 134 |
+
def __init__(self, env, task, recorder=None):
|
| 135 |
+
super().__init__(env, recorder=recorder)
|
| 136 |
+
self.task = task
|
| 137 |
+
self.closes = []
|
| 138 |
+
|
| 139 |
+
def _act(self, dpos, drot, grip):
|
| 140 |
+
super()._act(dpos, drot, grip)
|
| 141 |
+
self.task.monitor_step()
|
| 142 |
+
|
| 143 |
+
def set_gripper(self, close, steps=15):
|
| 144 |
+
was_open = self.grip < 0
|
| 145 |
+
before = self.task.close_context() if (close and was_open) else None
|
| 146 |
+
rep = super().set_gripper(close, steps)
|
| 147 |
+
if before is not None:
|
| 148 |
+
before.update(held=self.holding("card_1"), width=round(self.gripper_width(), 4))
|
| 149 |
+
self.closes.append(before)
|
| 150 |
+
return rep
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
@register_task
|
| 154 |
+
class CardShelf(LFFTask):
|
| 155 |
+
name = "l3_card_shelf"
|
| 156 |
+
level = "L3"
|
| 157 |
+
category = "strategy_switching"
|
| 158 |
+
capabilities = ("Perceive", "Reason", "Plan")
|
| 159 |
+
protocol = "cross"
|
| 160 |
+
max_attempts = 3
|
| 161 |
+
agent_max_steps = 40
|
| 162 |
+
instruction = "Pick up the thin red card lying on the wooden shelf and put it into the grey bin."
|
| 163 |
+
instruction_indirect = "Put the flat red rectangle that lies on the raised wooden platform into the grey container."
|
| 164 |
+
|
| 165 |
+
# ------------------------------------------------------------ scene
|
| 166 |
+
def make_bddl(self):
|
| 167 |
+
card = register_generated("LffShelfCard", card_xml("lff_shelf_card"))
|
| 168 |
+
shelf = register_generated("LffCardShelf", shelf_xml("lff_card_shelf"), free=False)
|
| 169 |
+
bin_ = register_generated("LffShelfBin", bin_xml("lff_shelf_bin", (BIN_IN, BIN_IN), BIN_WALL_H, wall_t=BIN_T,
|
| 170 |
+
rgba=(0.55, 0.56, 0.60, 1.0)), free=False)
|
| 171 |
+
objs = [("card_1", card, "card_region", (0.10, 0.20, 0.12, 0.22))]
|
| 172 |
+
fx = [("shelf_1", shelf, "shelf_region", (-0.11, -0.01, -0.09, 0.01)),
|
| 173 |
+
("bin_1", bin_, "bin_region", (-0.11, -0.31, -0.09, -0.29))]
|
| 174 |
+
return write_bddl(self.name, self.instruction, objs, fx)
|
| 175 |
+
|
| 176 |
+
def __init__(self, cam_res=None):
|
| 177 |
+
super().__init__(cam_res)
|
| 178 |
+
m = self.env.sim.model
|
| 179 |
+
self.shelf_bid = m.body_name2id(self.env.fixtures_dict["shelf_1"].root_body)
|
| 180 |
+
self.bin_bid = m.body_name2id(self.env.fixtures_dict["bin_1"].root_body)
|
| 181 |
+
g0 = int(m.body_geomadr[self.shelf_bid])
|
| 182 |
+
self.leg_geoms = {g for g in range(g0, g0 + int(m.body_geomnum[self.shelf_bid]))
|
| 183 |
+
if (m.geom_id2name(g) or "").endswith(("_g1", "_g2", "_g3", "_g4"))}
|
| 184 |
+
self.robot_geoms = set(envs.robot_geom_ids(self.env))
|
| 185 |
+
self.inst = None
|
| 186 |
+
self.mon = None
|
| 187 |
+
|
| 188 |
+
def sample_instance(self, seed):
|
| 189 |
+
rng = np.random.default_rng(seed)
|
| 190 |
+
bx, by = float(rng.uniform(-0.14, -0.06)), float(rng.uniform(-0.08, 0.08))
|
| 191 |
+
along = str(rng.choice(["x", "y"]))
|
| 192 |
+
near_sign = 1.0 if rng.random() < 0.5 else -1.0
|
| 193 |
+
if along == "x": # the near end of an x-card is the forward one: a card that tips off the backward edge lands
|
| 194 |
+
near_sign = 1.0 # behind the shelf, hidden from the front camera (measured); forward = nearest = away from the robot
|
| 195 |
+
jit = float(rng.uniform(-YAW_JIT, YAW_JIT))
|
| 196 |
+
gap = float(rng.uniform(*NEAR_GAP))
|
| 197 |
+
heavy_near = bool((int(seed) * 7) % 20 < round(20 * P_HEAVY_NEAR)) # balanced per 20 consecutive seeds
|
| 198 |
+
a_long, a_side = (0, 1) if along == "x" else (1, 0) # world axis of the card's long / short side
|
| 199 |
+
ext_long = CARD_HALF[0] * abs(np.cos(jit)) + CARD_HALF[1] * abs(np.sin(jit)) # half extents incl. the jitter
|
| 200 |
+
ext_side = CARD_HALF[0] * abs(np.sin(jit)) + CARD_HALF[1] * abs(np.cos(jit))
|
| 201 |
+
c = [bx, by]
|
| 202 |
+
c[a_long] += near_sign * (SHELF_HALF[a_long] - gap - ext_long)
|
| 203 |
+
room = SHELF_HALF[a_side] - ext_side - SIDE_CLEAR
|
| 204 |
+
c[a_side] += float(rng.uniform(-room, room))
|
| 205 |
+
u_near = np.zeros(2)
|
| 206 |
+
u_near[a_long] = near_sign
|
| 207 |
+
near_edge = {(1.0, 0.0): "forward", (-1.0, 0.0): "backward", (0.0, 1.0): "left", (0.0, -1.0): "right"}[
|
| 208 |
+
(float(u_near[0]), float(u_near[1]))]
|
| 209 |
+
heavy_dir = u_near if heavy_near else -u_near # the card's local +x (heavy end) points this way (+- jitter)
|
| 210 |
+
yaw = float(np.arctan2(heavy_dir[1], heavy_dir[0]) + jit)
|
| 211 |
+
side = 1.0 if rng.random() < 0.5 else -1.0
|
| 212 |
+
bin_xy = [bx + float(rng.uniform(-0.04, 0.04)), by + side * (SHELF_HALF[1] + BIN_GAP + BIN_HALF_OUT)]
|
| 213 |
+
return dict(seed=int(seed), shelf_xy=[bx, by], card_xy=[float(c[0]), float(c[1])], card_yaw=yaw,
|
| 214 |
+
card_along=along, near_edge=near_edge, far_edge=OPPOSITE[near_edge], near_gap=gap,
|
| 215 |
+
heavy_near=heavy_near, heavy_edge=near_edge if heavy_near else OPPOSITE[near_edge],
|
| 216 |
+
com_offset=COM_E, bin_xy=bin_xy, bin_side="left" if side > 0 else "right")
|
| 217 |
+
|
| 218 |
+
def apply_instance(self, inst):
|
| 219 |
+
self.inst = inst
|
| 220 |
+
m = self.env.sim.model
|
| 221 |
+
bx, by = inst["shelf_xy"]
|
| 222 |
+
m.body_pos[self.shelf_bid] = [bx, by, TZ + SHELF_H / 2]
|
| 223 |
+
m.body_quat[self.shelf_bid] = [1.0, 0.0, 0.0, 0.0]
|
| 224 |
+
cx, cy = inst["bin_xy"]
|
| 225 |
+
m.body_pos[self.bin_bid] = [cx, cy, TZ + (BIN_WALL_H + BIN_T) / 2]
|
| 226 |
+
m.body_quat[self.bin_bid] = [1.0, 0.0, 0.0, 0.0]
|
| 227 |
+
x, y = inst["card_xy"]
|
| 228 |
+
envs.set_obj_pose(self.env, "card_1", [x, y, CARD_REST_Z + 0.0003], yaw=inst["card_yaw"])
|
| 229 |
+
|
| 230 |
+
def reset_instance(self, inst, recorder=None):
|
| 231 |
+
self.env.reset()
|
| 232 |
+
self.apply_instance(inst)
|
| 233 |
+
self.env.sim.forward()
|
| 234 |
+
envs.settle(self.env, 15)
|
| 235 |
+
self.sk = ShelfSkills(self.env, self, recorder=recorder)
|
| 236 |
+
p = self.card_pose()
|
| 237 |
+
self.mon = dict(start_xy=p["xy"].copy(), max_lift=0.0, max_overhang=0.0, fell=False, lifted=False,
|
| 238 |
+
out=dict(heavy=0.0, light=0.0, side=0.0), out_edge=dict(heavy=None, light=None, side=None),
|
| 239 |
+
flagged=set(), events=[], in_bin=False, tip=None, leg_hits=0, edge_used=None)
|
| 240 |
+
return self.sk
|
| 241 |
+
|
| 242 |
+
# ------------------------------------------------------------ geometry
|
| 243 |
+
def card_pose(self):
|
| 244 |
+
p = envs.obj_pos(self.env, "card_1")
|
| 245 |
+
return dict(xy=p[:2].copy(), z=float(p[2]), yaw=_yaw_of(envs.obj_quat(self.env, "card_1")))
|
| 246 |
+
|
| 247 |
+
def _card_frame(self):
|
| 248 |
+
d = self.env.sim.data
|
| 249 |
+
bid = envs.body_id(self.env, "card_1")
|
| 250 |
+
return d.body_xpos[bid].copy(), d.body_xmat[bid].reshape(3, 3).copy()
|
| 251 |
+
|
| 252 |
+
def card_corners(self):
|
| 253 |
+
p, R = self._card_frame()
|
| 254 |
+
h = np.array(CARD_HALF)
|
| 255 |
+
return np.array([p + R @ (h * [sx, sy, 0.0]) for sx in (-1, 1) for sy in (-1, 1)])
|
| 256 |
+
|
| 257 |
+
def _beyond(self, xy):
|
| 258 |
+
"""{edge: how far the point lies beyond that edge of the shelf top (m, negative = inside)}"""
|
| 259 |
+
b = np.asarray(xy, float) - np.asarray(self.inst["shelf_xy"])
|
| 260 |
+
return {"forward": b[0] - SHELF_HALF[0], "backward": -b[0] - SHELF_HALF[0],
|
| 261 |
+
"left": b[1] - SHELF_HALF[1], "right": -b[1] - SHELF_HALF[1]}
|
| 262 |
+
|
| 263 |
+
def overhang(self):
|
| 264 |
+
"""(how far the card sticks out beyond the shelf's edges (m, max over its corners), edge word)"""
|
| 265 |
+
best = (-1.0, None)
|
| 266 |
+
for c in self.card_corners():
|
| 267 |
+
for e, v in self._beyond(c[:2]).items():
|
| 268 |
+
if v > best[0]:
|
| 269 |
+
best = (float(v), e)
|
| 270 |
+
return best
|
| 271 |
+
|
| 272 |
+
def part_overhangs(self):
|
| 273 |
+
"""{'heavy' | 'light' | 'side': (overhang m, edge)}: the heavy end (local +x), light end and long sides,
|
| 274 |
+
each measured at its two corners."""
|
| 275 |
+
p, R = self._card_frame()
|
| 276 |
+
h = np.array(CARD_HALF)
|
| 277 |
+
groups = {"heavy": [(1, -1), (1, 1)], "light": [(-1, -1), (-1, 1)]}
|
| 278 |
+
out = {}
|
| 279 |
+
for k, cs in groups.items():
|
| 280 |
+
best = (-1.0, None)
|
| 281 |
+
for sx, sy in cs:
|
| 282 |
+
c = p + R @ (h * [sx, sy, 0.0])
|
| 283 |
+
for e, v in self._beyond(c[:2]).items():
|
| 284 |
+
if v > best[0]:
|
| 285 |
+
best = (float(v), e)
|
| 286 |
+
out[k] = best
|
| 287 |
+
best = (-1.0, None) # a long side: its middle point (an end pushed out also moves two corners out)
|
| 288 |
+
for sy in (-1, 1):
|
| 289 |
+
c = p + R @ (h * [0.0, sy, 0.0])
|
| 290 |
+
for e, v in self._beyond(c[:2]).items():
|
| 291 |
+
if v > best[0]:
|
| 292 |
+
best = (float(v), e)
|
| 293 |
+
out["side"] = best
|
| 294 |
+
return out
|
| 295 |
+
|
| 296 |
+
def end_edge(self, which):
|
| 297 |
+
"""shelf edge that the card's `which` end ('heavy' | 'light' | 'near' | 'far') points to, from the live pose"""
|
| 298 |
+
p = self.card_pose()
|
| 299 |
+
d = np.array([np.cos(p["yaw"]), np.sin(p["yaw"])]) # heavy end direction
|
| 300 |
+
if which == "near" or which == "far":
|
| 301 |
+
gaps = {}
|
| 302 |
+
for s in (1.0, -1.0):
|
| 303 |
+
u = d * s
|
| 304 |
+
e = max(EDGE_U, key=lambda k: float(np.asarray(EDGE_U[k]) @ u))
|
| 305 |
+
tip = p["xy"] + u * CARD_HALF[0]
|
| 306 |
+
gaps[e] = -self._beyond(tip)[e]
|
| 307 |
+
near = min(gaps, key=gaps.get)
|
| 308 |
+
return near if which == "near" else OPPOSITE[near]
|
| 309 |
+
u = d if which == "heavy" else -d
|
| 310 |
+
return max(EDGE_U, key=lambda k: float(np.asarray(EDGE_U[k]) @ u))
|
| 311 |
+
|
| 312 |
+
def on_shelf(self):
|
| 313 |
+
p = self.card_pose()
|
| 314 |
+
rel = np.abs(p["xy"] - np.asarray(self.inst["shelf_xy"]))
|
| 315 |
+
return bool(rel[0] <= SHELF_HALF[0] and rel[1] <= SHELF_HALF[1] and abs(p["z"] - CARD_REST_Z) < 0.012)
|
| 316 |
+
|
| 317 |
+
def on_table(self):
|
| 318 |
+
return bool(self.card_pose()["z"] < TZ + 0.03 and not self.in_bin())
|
| 319 |
+
|
| 320 |
+
def tilt_deg(self):
|
| 321 |
+
_, R = self._card_frame()
|
| 322 |
+
return float(np.degrees(np.arccos(np.clip(abs(R[2, 2]), 0.0, 1.0))))
|
| 323 |
+
|
| 324 |
+
def in_bin(self):
|
| 325 |
+
p = self.card_pose()
|
| 326 |
+
rel = np.abs(p["xy"] - np.asarray(self.inst["bin_xy"]))
|
| 327 |
+
return bool(rel[0] <= BIN_IN and rel[1] <= BIN_IN and p["z"] < TZ + BIN_T + BIN_WALL_H)
|
| 328 |
+
|
| 329 |
+
# ------------------------------------------------------------ monitor
|
| 330 |
+
def _event(self, ev, **kw):
|
| 331 |
+
self.mon["events"].append(dict(event=ev, step=int(self.sk.n_steps), **kw))
|
| 332 |
+
|
| 333 |
+
def monitor_step(self):
|
| 334 |
+
mon = self.mon
|
| 335 |
+
if mon is None or self.sk is None:
|
| 336 |
+
return
|
| 337 |
+
p = self.card_pose()
|
| 338 |
+
held = self.sk.holding("card_1")
|
| 339 |
+
zmin = float(self.card_corners()[:, 2].min())
|
| 340 |
+
mon["max_lift"] = max(mon["max_lift"], zmin - SHELF_TOP)
|
| 341 |
+
if held and zmin - SHELF_TOP > 0.02 and not mon["lifted"]:
|
| 342 |
+
mon["lifted"] = True
|
| 343 |
+
self._event("lifted")
|
| 344 |
+
rel = np.abs(p["xy"] - np.asarray(self.inst["shelf_xy"]))
|
| 345 |
+
if (not held and abs(p["z"] - CARD_REST_Z) < 0.004 and self.tilt_deg() < 5.0 and rel[0] <= SHELF_HALF[0]
|
| 346 |
+
and rel[1] <= SHELF_HALF[1]): # lying flat on the shelf
|
| 347 |
+
mon["max_overhang"] = max(mon["max_overhang"], self.overhang()[0])
|
| 348 |
+
for k, (v, e) in self.part_overhangs().items():
|
| 349 |
+
if v > mon["out"][k]:
|
| 350 |
+
mon["out"][k], mon["out_edge"][k] = v, e
|
| 351 |
+
if v >= 0.005 and k not in mon["flagged"]:
|
| 352 |
+
mon["flagged"].add(k)
|
| 353 |
+
self._event("side_over_edge" if k == "side" else "end_over_edge", part=k, edge=e)
|
| 354 |
+
if p["z"] < SHELF_TOP - 0.02 and not held and not mon["fell"]:
|
| 355 |
+
mon["fell"] = True
|
| 356 |
+
if not mon["lifted"]: # never lifted: it tipped (or was pushed) off the shelf
|
| 357 |
+
part = max(("heavy", "light", "side"), key=lambda k: mon["out"][k])
|
| 358 |
+
mon["tip"] = dict(part=part, edge=mon["out_edge"][part], overhang=round(mon["out"][part], 4))
|
| 359 |
+
self._event("tipped_off", **mon["tip"])
|
| 360 |
+
else:
|
| 361 |
+
self._event("released")
|
| 362 |
+
d = self.env.sim.data
|
| 363 |
+
for i in range(d.ncon): # the hand / arm touching a shelf leg (should not happen in normal grasps)
|
| 364 |
+
c = d.contact[i]
|
| 365 |
+
if (c.geom1 in self.leg_geoms and c.geom2 in self.robot_geoms) or (c.geom2 in self.leg_geoms and
|
| 366 |
+
c.geom1 in self.robot_geoms):
|
| 367 |
+
if mon["leg_hits"] == 0:
|
| 368 |
+
self._event("hand_hit_leg")
|
| 369 |
+
mon["leg_hits"] += 1
|
| 370 |
+
break
|
| 371 |
+
if not mon["in_bin"] and self.in_bin() and not held:
|
| 372 |
+
mon["in_bin"] = True
|
| 373 |
+
self._event("in_bin")
|
| 374 |
+
|
| 375 |
+
def close_context(self):
|
| 376 |
+
"""Where the gripper is relative to the card and the shelf just before it closes."""
|
| 377 |
+
sk, p = self.sk, self.card_pose()
|
| 378 |
+
e = sk.eef_pos()
|
| 379 |
+
c, s = np.cos(p["yaw"]), np.sin(p["yaw"])
|
| 380 |
+
rel = e[:2] - p["xy"]
|
| 381 |
+
local = [float(rel @ [c, s]), float(rel @ [-s, c])] # along the card's long / short side (+ = heavy end)
|
| 382 |
+
beyond = self._beyond(e[:2])
|
| 383 |
+
edge = max(beyond, key=beyond.get)
|
| 384 |
+
ov, ov_edge = self.overhang()
|
| 385 |
+
return dict(step=sk.n_steps, local=[round(v, 4) for v in local],
|
| 386 |
+
tips_above_card=round(float(e[2] - TIP_BELOW_SITE - (p["z"] + CARD_HALF[2])), 4),
|
| 387 |
+
beyond_edge=round(float(beyond[edge]), 4), beyond_edge_name=edge,
|
| 388 |
+
card_on_shelf=self.on_shelf(), overhang=round(ov, 4), overhang_edge=ov_edge,
|
| 389 |
+
width_before=round(sk.gripper_width(), 4))
|
| 390 |
+
|
| 391 |
+
# ------------------------------------------------------------ outcome / F2
|
| 392 |
+
def outcome(self, inst):
|
| 393 |
+
envs.settle(self.env, 30)
|
| 394 |
+
self.monitor_step()
|
| 395 |
+
sk, mon = self.sk, self.mon
|
| 396 |
+
p = self.card_pose()
|
| 397 |
+
held = bool(sk.holding("card_1"))
|
| 398 |
+
in_bin = self.in_bin() and not held
|
| 399 |
+
success = bool(in_bin)
|
| 400 |
+
moved = float(np.linalg.norm(p["xy"] - mon["start_xy"]))
|
| 401 |
+
lifted = mon["max_lift"] > 0.02
|
| 402 |
+
tries = [c for c in sk.closes if c["tips_above_card"] <= LOW_CLOSE and c["width_before"] > 0.02]
|
| 403 |
+
parts, mode = [], "success"
|
| 404 |
+
rel = p["xy"] - np.asarray(inst["bin_xy"])
|
| 405 |
+
where = (f"{100 * abs(rel[0]):.1f} cm {'forward' if rel[0] > 0 else 'backward'} and "
|
| 406 |
+
f"{100 * abs(rel[1]):.1f} cm {'left' if rel[1] > 0 else 'right'} of the bin's centre")
|
| 407 |
+
tip = mon["tip"]
|
| 408 |
+
if success:
|
| 409 |
+
parts.append("The card is in the bin.")
|
| 410 |
+
elif held:
|
| 411 |
+
mode = "held"
|
| 412 |
+
parts.append(f"The card is still held by the gripper, {where}.")
|
| 413 |
+
elif lifted:
|
| 414 |
+
mode = "dropped"
|
| 415 |
+
loc = ("on the shelf" if self.on_shelf() else "on the table" if self.on_table() else
|
| 416 |
+
"partly on the shelf" if p["z"] > SHELF_TOP - 0.02 else "off the shelf")
|
| 417 |
+
parts.append(f"The card was lifted {100 * mon['max_lift']:.1f} cm above the shelf but is not in the "
|
| 418 |
+
f"bin: it lies {loc}, its centre {where}.")
|
| 419 |
+
elif mon["fell"]:
|
| 420 |
+
mode = "fell_off"
|
| 421 |
+
what = "a long side" if tip["part"] == "side" else "one end"
|
| 422 |
+
parts.append(f"The card was never lifted: after {what} of it had been slid {100 * max(tip['overhang'], 0):.1f}"
|
| 423 |
+
f" cm beyond the shelf's {tip['edge']} edge, it tipped over that edge and fell off the shelf; "
|
| 424 |
+
+ ("it lies flat on the table." if self.on_table() and self.tilt_deg() < 10 else
|
| 425 |
+
f"it rests off the shelf, tilted {self.tilt_deg():.0f} degrees."))
|
| 426 |
+
else:
|
| 427 |
+
mode = "not_lifted"
|
| 428 |
+
parts.append("The card was never lifted; it still lies flat on the shelf"
|
| 429 |
+
+ (f" (it was slid {100 * moved:.1f} cm" + (f" and stuck out up to "
|
| 430 |
+
f"{100 * mon['max_overhang']:.1f} cm beyond the shelf's edge)" if mon["max_overhang"] > 0.003
|
| 431 |
+
else ")") if moved > 0.005 else "") + ".")
|
| 432 |
+
if not success and not lifted and tries:
|
| 433 |
+
c = tries[-1]
|
| 434 |
+
n = f"{len(tries)} grasp tries; in the last one, " if len(tries) > 1 else ""
|
| 435 |
+
if c["card_on_shelf"] and c["overhang"] <= 0.0 and c["beyond_edge"] < 0.0:
|
| 436 |
+
txt = ("when the gripper closed on the card lying flat on the shelf, its fingertips were on either side "
|
| 437 |
+
"of the card, at shelf level")
|
| 438 |
+
else:
|
| 439 |
+
pos = (f"{100 * c['beyond_edge']:.1f} cm beyond the shelf's {c['beyond_edge_name']} edge"
|
| 440 |
+
if c["beyond_edge"] >= 0.0 else
|
| 441 |
+
f"over the shelf, {100 * -c['beyond_edge']:.1f} cm inside its {c['beyond_edge_name']} edge")
|
| 442 |
+
txt = (f"when the gripper closed, the card stuck out {100 * max(c['overhang'], 0.0):.1f} cm beyond the "
|
| 443 |
+
f"shelf's {c['overhang_edge']} edge and the gripper's centre was {pos}")
|
| 444 |
+
txt += f" ({100 * c['tips_above_card']:+.1f} cm from the fingertips to the top of the card); the fingers closed "
|
| 445 |
+
txt += ("fully, sliding over the top of the card instead of gripping its edges."
|
| 446 |
+
if c["width"] < 2 * CARD_HALF[1] - 0.01 and not c["held"] else
|
| 447 |
+
("on the card." if c["held"] else f"to {100 * c['width']:.1f} cm without holding the card."))
|
| 448 |
+
parts.append(n + txt if n else txt[0].upper() + txt[1:])
|
| 449 |
+
elif not success and not lifted and not mon["fell"]:
|
| 450 |
+
parts.append("The gripper never closed with its fingertips down at the card.")
|
| 451 |
+
failure = "none" if success else mode
|
| 452 |
+
out = dict(success=success, mode=mode, failure=failure, held=held, lifted=bool(lifted),
|
| 453 |
+
max_lift=round(mon["max_lift"], 4), max_overhang=round(mon["max_overhang"], 4), moved=round(moved, 4),
|
| 454 |
+
fell=bool(mon["fell"]), tipped_off=tip is not None, trap_fired=bool(tip is not None and
|
| 455 |
+
tip["part"] == "heavy"),
|
| 456 |
+
tip=tip, end_out={k: round(v, 4) for k, v in mon["out"].items()},
|
| 457 |
+
end_out_edge=dict(mon["out_edge"]), card_final=dict(xy=[round(float(v), 4) for v in p["xy"]],
|
| 458 |
+
z_above_table=round(p["z"] - TZ, 4),
|
| 459 |
+
tilt_deg=round(self.tilt_deg(), 1)),
|
| 460 |
+
leg_hits=int(mon["leg_hits"]), slid_edge=mon["edge_used"],
|
| 461 |
+
events=list(mon["events"]), grasp_tries=tries, closes=sk.closes, detail=" ".join(parts))
|
| 462 |
+
return out
|
| 463 |
+
|
| 464 |
+
# ------------------------------------------------------------ scripted policies (move_to + gripper only)
|
| 465 |
+
def grasp_and_bin(self, xy, yaw, z_site, lift=0.12):
|
| 466 |
+
sk = self.sk
|
| 467 |
+
sk.set_gripper(False, steps=8)
|
| 468 |
+
sk.move_to([xy[0], xy[1], z_site + 0.08], yaw=yaw)
|
| 469 |
+
sk.move_to([xy[0], xy[1], z_site], tol=0.003, max_steps=120)
|
| 470 |
+
sk.set_gripper(True, steps=15)
|
| 471 |
+
sk.move_to([xy[0], xy[1], z_site + lift], speed=0.2)
|
| 472 |
+
if not sk.holding("card_1"):
|
| 473 |
+
sk.set_gripper(False, steps=8)
|
| 474 |
+
return False
|
| 475 |
+
bx, by = self.inst["bin_xy"]
|
| 476 |
+
hi = SHELF_TOP + 0.10
|
| 477 |
+
sk.move_to([bx, by, hi])
|
| 478 |
+
sk.move_to([bx, by, TZ + BIN_WALL_H + 0.05], speed=0.2)
|
| 479 |
+
sk.set_gripper(False, steps=12)
|
| 480 |
+
sk.move_to([bx, by, hi])
|
| 481 |
+
return True
|
| 482 |
+
|
| 483 |
+
def slide_card(self, delta, press=0.004, at=(0.0, 0.0)):
|
| 484 |
+
"""closed fingertips pressed on the card (at its centre + `at`), straight move by `delta` (xy), lift"""
|
| 485 |
+
sk, p = self.sk, self.card_pose()
|
| 486 |
+
z = p["z"] + CARD_HALF[2] + TIP_BELOW_SITE - press
|
| 487 |
+
s = p["xy"] + np.asarray(at, float)
|
| 488 |
+
sk.set_gripper(True, steps=8)
|
| 489 |
+
sk.move_to([s[0], s[1], z + 0.06], yaw=p["yaw"])
|
| 490 |
+
sk.move_to([s[0], s[1], z], tol=0.003, max_steps=100)
|
| 491 |
+
e = s + np.asarray(delta, float)
|
| 492 |
+
sk.move_to([e[0], e[1], z], speed=DRAG_SPEED, tol=0.004, max_steps=300)
|
| 493 |
+
sk.move_to([e[0], e[1], z + 0.06], speed=0.2)
|
| 494 |
+
sk.hold(10) # look
|
| 495 |
+
|
| 496 |
+
def push_end(self, u, dist, behind=0.015):
|
| 497 |
+
"""closed fingers at shelf level `behind` m behind the card's trailing end, push it `dist` along u, lift"""
|
| 498 |
+
sk, p = self.sk, self.card_pose()
|
| 499 |
+
d = np.array([np.cos(p["yaw"]), np.sin(p["yaw"])])
|
| 500 |
+
la = d * np.sign(d @ u) if abs(d @ u) > 0.5 else d
|
| 501 |
+
tail = p["xy"] - la * CARD_HALF[0]
|
| 502 |
+
s = tail - u * behind
|
| 503 |
+
z = SHELF_TOP + TIP_BELOW_SITE - 0.001 # fingertips on the shelf top (2 mm above: they pass over the card)
|
| 504 |
+
yaw = float(np.arctan2(u[1], u[0]) - np.pi / 2) # finger axis across the push direction
|
| 505 |
+
sk.set_gripper(True, steps=8)
|
| 506 |
+
sk.move_to([s[0], s[1], z + 0.05], yaw=yaw)
|
| 507 |
+
sk.move_to([s[0], s[1], z], tol=0.003, max_steps=100)
|
| 508 |
+
e = s + u * (behind + dist)
|
| 509 |
+
sk.move_to([e[0], e[1], z], speed=0.04, tol=0.004, max_steps=300)
|
| 510 |
+
sk.move_to([e[0], e[1], z + 0.05], speed=0.2)
|
| 511 |
+
sk.hold(10)
|
| 512 |
+
|
| 513 |
+
def execute(self, inst, params):
|
| 514 |
+
p = self.card_pose()
|
| 515 |
+
rng = np.random.default_rng(params.get("noise_seed")) if params.get("noise_seed") is not None else None
|
| 516 |
+
if params.get("probe_grasp", False) or params["mode"] == "grasp": # flat grasp at the card's middle
|
| 517 |
+
dxy = np.asarray(params.get("probe_dxy", (0.0, 0.0)))
|
| 518 |
+
self.grasp_and_bin(p["xy"] + dxy, p["yaw"], SHELF_TOP + params.get("probe_dz", 0.0))
|
| 519 |
+
if params["mode"] == "grasp" or self.sk.holding("card_1") or self.mon["lifted"]:
|
| 520 |
+
return
|
| 521 |
+
# slide one end of the card along its long side out over the edge it points to, in strokes
|
| 522 |
+
edge = params.get("edge") or self.end_edge(params.get("end", "near"))
|
| 523 |
+
self.mon["edge_used"] = edge
|
| 524 |
+
u = np.asarray(EDGE_U[edge], float)
|
| 525 |
+
b = np.asarray(inst["shelf_xy"])
|
| 526 |
+
half = SHELF_HALF[0] if edge in ("forward", "backward") else SHELF_HALF[1]
|
| 527 |
+
edge_pos = float(b @ u) + half
|
| 528 |
+
for k, target in enumerate(params.get("steps", ORACLE_STEPS)):
|
| 529 |
+
if not self.on_shelf():
|
| 530 |
+
return # tipped off: nothing left to grasp (the attempt is lost)
|
| 531 |
+
p = self.card_pose()
|
| 532 |
+
d = np.array([np.cos(p["yaw"]), np.sin(p["yaw"])])
|
| 533 |
+
la = d * np.sign(d @ u) if abs(d @ u) >= 0.5 else np.array([-d[1], d[0]]) * np.sign(np.array([-d[1], d[0]]) @ u)
|
| 534 |
+
ext = max(float(c[:2] @ u) for c in self.card_corners()) - float(p["xy"] @ u)
|
| 535 |
+
tgt = float(target) + (float(rng.uniform(-1, 1)) * params.get("step_noise", 0.0) if rng is not None else 0.0)
|
| 536 |
+
need = edge_pos + tgt - (float(p["xy"] @ u) + ext) # travel still needed along u
|
| 537 |
+
if need > 0.003:
|
| 538 |
+
if params.get("style", "press") == "endpush":
|
| 539 |
+
self.push_end(u, need)
|
| 540 |
+
else:
|
| 541 |
+
at = (np.asarray(params.get("press_at", (0.0, 0.0))) if rng is None else
|
| 542 |
+
rng.normal(0.0, params.get("press_noise", 0.0), 2))
|
| 543 |
+
self.slide_card(la * need / max(float(la @ u), 1e-6), at=at)
|
| 544 |
+
self.sk.hold(10)
|
| 545 |
+
if not self.on_shelf():
|
| 546 |
+
return
|
| 547 |
+
q = self.card_pose()
|
| 548 |
+
d = np.array([np.cos(q["yaw"]), np.sin(q["yaw"])])
|
| 549 |
+
la = d * np.sign(d @ u) if abs(d @ u) >= 0.5 else np.array([-d[1], d[0]]) * np.sign(np.array([-d[1], d[0]]) @ u)
|
| 550 |
+
cu = float(q["xy"] @ u)
|
| 551 |
+
tip_u = max(float(c[:2] @ u) for c in self.card_corners()) # outermost point of the card along u
|
| 552 |
+
target_u = min(tip_u - 0.008, edge_pos + params.get("grasp_out", GRASP_OUT))
|
| 553 |
+
g = q["xy"] + la * (target_u - cu) / max(float(la @ u), 1e-6)
|
| 554 |
+
g = g + np.asarray(params.get("grasp_dxy", (0.0, 0.0)))
|
| 555 |
+
self.grasp_and_bin(g, q["yaw"], SHELF_TOP - 0.003 + params.get("grasp_dz", 0.0))
|
| 556 |
+
|
| 557 |
+
def default_params(self, inst):
|
| 558 |
+
"""Sonnet-like (cla4 l3_card_edge): one flat grasp, then the nearest end out to the edge and 1 cm at a time
|
| 559 |
+
to ~3 cm, lifting the finger and looking after each stroke; grasp the overhang."""
|
| 560 |
+
return dict(mode="edge", probe_grasp=True, end="near", steps=list(NAIVE_STEPS))
|
| 561 |
+
|
| 562 |
+
def oracle_params(self, inst):
|
| 563 |
+
"""Knows the hidden weight: slides the light end out 3 cm (two strokes, as the l3_card_edge oracle)."""
|
| 564 |
+
return dict(mode="edge", end="light", steps=list(ORACLE_STEPS))
|
| 565 |
+
|
| 566 |
+
def blind_params(self, inst, attempt, rng):
|
| 567 |
+
"""naive with small random variations, no history: nearest end, 2.5-3.5 cm, pressing point / grasp jitter"""
|
| 568 |
+
return dict(mode="edge", probe_grasp=True, end="near", steps=[0.0, 0.01, 0.02, float(rng.uniform(0.025, 0.035))],
|
| 569 |
+
noise_seed=int(rng.integers(1 << 30)), press_noise=0.005,
|
| 570 |
+
grasp_dxy=rng.uniform(-0.005, 0.005, 2).tolist(), grasp_dz=float(rng.uniform(-0.004, 0.003)))
|
| 571 |
+
|
| 572 |
+
def adapt_params(self, inst, history):
|
| 573 |
+
"""Tipped off the shelf (never lifted) -> slide the OTHER end next time (it tipped although only ~2 cm stuck
|
| 574 |
+
out: that end must be heavy). Slid out but not gripped -> 1 cm more overhang. Otherwise repeat."""
|
| 575 |
+
out, prm = history[-1]["outcome"], history[-1]["params"]
|
| 576 |
+
used = out.get("slid_edge") or prm.get("edge")
|
| 577 |
+
nxt = dict(mode="edge", probe_grasp=False, edge=used, steps=list(ORACLE_STEPS))
|
| 578 |
+
if out["mode"] == "fell_off":
|
| 579 |
+
e = (out.get("tip") or {}).get("edge") or used
|
| 580 |
+
nxt["edge"] = OPPOSITE.get(e)
|
| 581 |
+
elif out["mode"] == "not_lifted" and used is not None:
|
| 582 |
+
last = float((prm.get("steps") or ORACLE_STEPS)[-1])
|
| 583 |
+
nxt["steps"] = [s + 0.01 for s in ORACLE_STEPS] if last < 0.035 else list(ORACLE_STEPS)
|
| 584 |
+
if nxt["edge"] is None:
|
| 585 |
+
nxt.pop("edge")
|
| 586 |
+
nxt["end"] = "near"
|
| 587 |
+
return nxt
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/scripts/cs_ir_report.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reproduce the CS/IR audit tables from read-only manifests and hash-bound evidence."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import api_batch
|
| 7 |
+
import outcomes
|
| 8 |
+
from outcome_audit import load_audit, sha256
|
| 9 |
+
|
| 10 |
+
GROUPS = {"GPT": ["cx_main1"], "Sonnet": ["cc_main1"], "Opus": ["cc_opus1"],
|
| 11 |
+
"DeepSeek": ["ds_cx1", "ds_cx1b"]}
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def main():
|
| 15 |
+
parser = argparse.ArgumentParser()
|
| 16 |
+
parser.add_argument("--runs-root", required=True)
|
| 17 |
+
parser.add_argument("--audit", required=True)
|
| 18 |
+
parser.add_argument("--out", required=True)
|
| 19 |
+
args = parser.parse_args()
|
| 20 |
+
api_batch.RUNS = str(Path(args.runs_root).resolve())
|
| 21 |
+
audit = load_audit(args.audit)
|
| 22 |
+
output = Path(args.out)
|
| 23 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 24 |
+
all_rows, models, manifests, coverage = [], {}, {}, {}
|
| 25 |
+
for model, batches in GROUPS.items():
|
| 26 |
+
old, new = [], []
|
| 27 |
+
for batch in batches:
|
| 28 |
+
manifest = api_batch.load(batch)
|
| 29 |
+
manifests[batch] = sha256(api_batch.mpath(batch))
|
| 30 |
+
old += outcomes.instance_rows(manifest, batch=batch)
|
| 31 |
+
new += outcomes.instance_rows(manifest, audit=audit, batch=batch)
|
| 32 |
+
for run in manifest["runs"]:
|
| 33 |
+
if not (run["cond"] == "harness" and run.get("followup") and run["status"] == "done"):
|
| 34 |
+
continue
|
| 35 |
+
attempts = outcomes.attempts(run["log"])
|
| 36 |
+
if attempts:
|
| 37 |
+
coverage.setdefault(run["task"], set()).update(
|
| 38 |
+
k for k in outcomes.ERROR_FLAGS + outcomes.ERROR_COUNTS if k in attempts[0][2])
|
| 39 |
+
before, after = outcomes.summary(old), outcomes.summary(new)
|
| 40 |
+
for key in ("n", "A1", "A3", "XR", "F", "n_paired", "A3_paired", "passk_paired", "delta_paired"):
|
| 41 |
+
assert before[key] == after[key], f"Audit unexpectedly changed {model} {key}"
|
| 42 |
+
assert len({(r["task"], r["seed"]) for r in new}) == len(new), "duplicate model/task/seed"
|
| 43 |
+
models[model] = dict(before=before, after=after)
|
| 44 |
+
all_rows += [dict(r, model=model) for r in new]
|
| 45 |
+
payload = dict(schema="lff-cs-ir-report-1", source_manifests_sha256=manifests,
|
| 46 |
+
audit_sha256=sha256(args.audit), models=models, rows=all_rows,
|
| 47 |
+
legacy_counter_coverage={k: sorted(v) for k, v in coverage.items()})
|
| 48 |
+
(output / "summary.json").write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
|
| 49 |
+
lines = ["# CS / IR 证据审计表(2026-10-24)", "",
|
| 50 |
+
"本表由 `scripts/cs_ir_report.py` 生成;定义、局限、合并说明见同目录 `README.md`。",
|
| 51 |
+
"旧口径是 task counter heuristic;新口径是逐 run 的物理失败 + 主动修复证据审计。",
|
| 52 |
+
"A1、A3、XR、F、配对样本及 Δ_hist 均逐项断言保持不变。", "",
|
| 53 |
+
"| 模型 | 旧 CS / IR / S? | 审计 CS / IR / S? | 原 S? 已补 | A1 | A3 |",
|
| 54 |
+
"|---|---|---|---|---|---|"]
|
| 55 |
+
for model, pair in models.items():
|
| 56 |
+
b, a = pair["before"], pair["after"]
|
| 57 |
+
resolved = sum(r["model"] == model and r["legacy_cls"] == "S?" and r["cls"] != "S?" for r in all_rows)
|
| 58 |
+
lines.append(f"| {model} | {b['CS']} / {b['IR']} / {b['S?']} | {a['CS']} / {a['IR']} / {a['S?']} | "
|
| 59 |
+
f"{resolved}/{b['S?']} | {a['A1']}/{a['n']} | {a['A3']}/{a['n']} |")
|
| 60 |
+
lines += ["", "## 每任务新旧分类与原统一字段覆盖", "",
|
| 61 |
+
"`旧→新`;只有一个标签表示未变。`缺失` 不是没有错误;有字段也不代表覆盖抓空/掉落等全部失败。", "",
|
| 62 |
+
"| 任务 | GPT | Sonnet | Opus | DeepSeek | 原统一错误字段 |", "|---|---|---|---|---|---|"]
|
| 63 |
+
for task, counters in coverage.items():
|
| 64 |
+
cells = []
|
| 65 |
+
for model in GROUPS:
|
| 66 |
+
row = next(r for r in all_rows if r["model"] == model and r["task"] == task)
|
| 67 |
+
cells.append(row["cls"] if row["cls"] == row["legacy_cls"] else f"{row['legacy_cls']}→{row['cls']}")
|
| 68 |
+
lines.append("| " + " | ".join([task] + cells + [", ".join(sorted(counters)) or "缺失"]) + " |")
|
| 69 |
+
lines += ["", "## 首次成功的证据链", "", "行号均指原 run 文件,E 为 events.jsonl,T 为 trajectory.jsonl;s 为机器人命令序号。", ""]
|
| 70 |
+
for row in all_rows:
|
| 71 |
+
if not row["a1"]:
|
| 72 |
+
continue
|
| 73 |
+
entry = audit.get((row["batch"], row["run_id"]))
|
| 74 |
+
manifest = api_batch.load(row["batch"])
|
| 75 |
+
run = next(r for r in manifest["runs"] if r["id"] == row["run_id"])
|
| 76 |
+
lines += [f"### {row['model']} · {row['task']} · {row['legacy_cls']} → {row['cls']}", "",
|
| 77 |
+
row["audit_basis"], "", f"[原 events.jsonl]({run['log']}/events.jsonl) · "
|
| 78 |
+
f"[原 trajectory.jsonl]({run['log']}/trajectory.jsonl)", ""]
|
| 79 |
+
if entry:
|
| 80 |
+
lines += [f"证据索引:{entry.get('evidence', '')}", "",
|
| 81 |
+
f"归因范围:`{entry.get('failure_scope', 'not_adjudicated')}`。", ""]
|
| 82 |
+
(output / "TABLES.md").write_text("\n".join(lines) + "\n")
|
| 83 |
+
print(json.dumps(models, ensure_ascii=False, indent=2))
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
if __name__ == "__main__":
|
| 87 |
+
main()
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/scripts/l6_controls.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""python scripts/l6_controls.py <l6_count_into_box|l6_sequence_resume> [n]
|
| 2 |
+
|
| 3 |
+
Extra controls for the two L6 tasks: thumbnails right after the interruption, extra scripted policies,
|
| 4 |
+
no-injection sanity check, analytic memoryless baselines. Writes results/<task>/controls.json."""
|
| 5 |
+
import sys, json, os, time
|
| 6 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 7 |
+
sys.path.insert(0, ROOT)
|
| 8 |
+
import numpy as np, imageio
|
| 9 |
+
from lffbench import envs
|
| 10 |
+
import lffbench.tasks.l6_count, lffbench.tasks.l6_sequence # noqa
|
| 11 |
+
from lffbench.task_base import TASKS
|
| 12 |
+
name = sys.argv[1]
|
| 13 |
+
n = int(sys.argv[2]) if len(sys.argv) > 2 else 20
|
| 14 |
+
out_dir = os.path.join(ROOT, "results", name)
|
| 15 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 16 |
+
task = TASKS[name](cam_res=384)
|
| 17 |
+
extra = ["skip", "inc1"] if name == "l6_count_into_box" else ["skip"]
|
| 18 |
+
res = dict(task=name, n=n, seeds=list(range(1000, 1000 + n)), extra={}, no_inject={}, analytic={})
|
| 19 |
+
t0 = time.time()
|
| 20 |
+
|
| 21 |
+
# 1) frames right after the interruption (what the agent sees next), seeds 1000-1002, adaptive policy
|
| 22 |
+
def interrupted():
|
| 23 |
+
return (task.slip if name == "l6_count_into_box" else task.stop) is not None
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
for seed in range(1000, 1003):
|
| 27 |
+
inst = task.sample_instance(seed)
|
| 28 |
+
shot = {}
|
| 29 |
+
orig_step = task.env.step
|
| 30 |
+
|
| 31 |
+
def step(a, _o=orig_step):
|
| 32 |
+
r = _o(a)
|
| 33 |
+
if "f" not in shot and interrupted():
|
| 34 |
+
shot["cnt"] = shot.get("cnt", 0) + 1
|
| 35 |
+
if shot["cnt"] >= (4 if name == "l6_count_into_box" else 60): # count: 0.2 s; sequence: arm back home
|
| 36 |
+
shot["f"] = np.concatenate([envs.render(task.env, "agentview", 384),
|
| 37 |
+
envs.render(task.env, "robot0_eye_in_hand", 384)], 1)
|
| 38 |
+
return r
|
| 39 |
+
task.env.step = step
|
| 40 |
+
task.run_scripted("adaptive", inst, k=5, seed=seed)
|
| 41 |
+
task.env.step = orig_step
|
| 42 |
+
if "f" in shot:
|
| 43 |
+
imageio.imwrite(os.path.join(out_dir, f"interrupt_{seed}.png"), shot["f"])
|
| 44 |
+
print("thumbs", f"{time.time()-t0:.0f}s", flush=True)
|
| 45 |
+
|
| 46 |
+
# 2) extra scripted policies
|
| 47 |
+
for kind in extra:
|
| 48 |
+
fs = []
|
| 49 |
+
for i in range(n):
|
| 50 |
+
seed = 1000 + i
|
| 51 |
+
inst = task.sample_instance(seed)
|
| 52 |
+
h = task.run_scripted(kind, inst, k=5, seed=seed)
|
| 53 |
+
s = next((x["attempt"] for x in h if x["outcome"]["success"]), None)
|
| 54 |
+
fs.append(s)
|
| 55 |
+
res["extra"][kind] = dict(first_success=fs, succ_at_k=[float(np.mean([s is not None and s <= j for s in fs])) for j in range(1, 6)])
|
| 56 |
+
print(kind, res["extra"][kind]["succ_at_k"], f"{time.time()-t0:.0f}s", flush=True)
|
| 57 |
+
|
| 58 |
+
# 3) no-injection sanity (oracle + naive, first 10 seeds)
|
| 59 |
+
task.inject = False
|
| 60 |
+
for kind in ("adaptive", "naive"):
|
| 61 |
+
fs = []
|
| 62 |
+
for i in range(10):
|
| 63 |
+
seed = 1000 + i
|
| 64 |
+
inst = task.sample_instance(seed)
|
| 65 |
+
h = task.run_scripted(kind, inst, k=1, seed=seed)
|
| 66 |
+
fs.append(bool(h[0]["outcome"]["success"]))
|
| 67 |
+
res["no_inject"][kind] = float(np.mean(fs))
|
| 68 |
+
print("no inject", kind, res["no_inject"][kind], flush=True)
|
| 69 |
+
task.inject = True
|
| 70 |
+
|
| 71 |
+
# 4) analytic memoryless baselines over the same seeds (perfect execution assumed)
|
| 72 |
+
if name == "l6_count_into_box":
|
| 73 |
+
insts = [task.sample_instance(1000 + i) for i in range(n)]
|
| 74 |
+
res["analytic"]["uniform_guess_0..N-1@1"] = float(np.mean([1 / x["n_target"] for x in insts]))
|
| 75 |
+
best = max(range(0, 6), key=lambda g: np.mean([x["n_target"] - x["p"] == g for x in insts]))
|
| 76 |
+
res["analytic"]["best_fixed_number_to_add@1"] = dict(add=best, rate=float(np.mean([x["n_target"] - x["p"] == best for x in insts])))
|
| 77 |
+
res["analytic"]["p_hist"] = {str(v): int(sum(x["p"] == v for x in insts)) for v in range(1, 6)}
|
| 78 |
+
res["analytic"]["N_hist"] = {str(v): int(sum(x["n_target"] == v for x in insts)) for v in (4, 5)}
|
| 79 |
+
big = [task.sample_instance(5000 + i) for i in range(2000)]
|
| 80 |
+
res["analytic"]["uniform_guess@1_2000inst"] = float(np.mean([1 / x["n_target"] for x in big]))
|
| 81 |
+
res["analytic"]["best_fixed_add@1_2000inst"] = float(max(np.mean([x["n_target"] - x["p"] == g for x in big]) for g in range(1, 5)))
|
| 82 |
+
else:
|
| 83 |
+
insts = [task.sample_instance(1000 + i) for i in range(n)]
|
| 84 |
+
res["analytic"]["w_hist"] = {str(v): int(sum(x["stop_w"] == v for x in insts)) for v in range(1, 5)}
|
| 85 |
+
res["analytic"]["phase_hist"] = {p: int(sum(x["stop_phase"] == p for x in insts)) for p in "AB"}
|
| 86 |
+
res["analytic"]["uniform_guess_0..4@1"] = 0.2
|
| 87 |
+
big = [task.sample_instance(5000 + i) for i in range(2000)]
|
| 88 |
+
res["analytic"]["best_fixed_guess@1_2000inst"] = float(max(np.mean([x["stop_w"] == g for x in big]) for g in range(0, 5)))
|
| 89 |
+
res["analytic"]["skip_expected"] = float(np.mean([x["stop_phase"] == "B" or x["stop_w"] == 3 for x in big]))
|
| 90 |
+
res["seconds"] = time.time() - t0
|
| 91 |
+
json.dump(res, open(os.path.join(out_dir, "controls.json"), "w"), indent=1)
|
| 92 |
+
print(json.dumps(res["analytic"]))
|