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/final/episode_000118_wrist_image.png +3 -0
- leaf/final/episode_000188.npz +3 -0
- leaf/final/episode_000682.npz +3 -0
- leaf/final/episode_001434_image.png +3 -0
- leaf/final/episode_001473.npz +3 -0
- leaf/final/episode_003014_image.png +3 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/arm_specs/l3_card_shelf.py +65 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/arm_specs/l3_wall_flush.py +61 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/arm_specs/l7_key_turn.py +34 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/pins/claude_code_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json +15 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-sonnet-5-5_high.json +15 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/__init__.py +1 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/camera.py +100 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/context.py +377 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/images.py +47 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/replay.py +59 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/robot_server.py +966 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/runlog.py +62 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/tools.py +392 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/agent_compare.py +40 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/agent_cost.py +77 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/api_batch.py +704 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/api_player.py +446 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/audit_subagent.py +130 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_breakfast_geometry.py +41 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_breakfast_mechanisms.py +79 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_breakfast_service.py +48 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_breakfast_tool_interface.py +57 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_lh_order_dispatch.py +73 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_lh_pantry_relatch.py +138 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_setup.py +175 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/claude_batch.py +309 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/cs_ir_report.py +87 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/feedback_ladder.py +428 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/full_report.py +89 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/full_waves.sh +38 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/gpt_batch.py +192 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/gpt_player.py +20 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/gptpolicy_player.sh +37 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/harness_run.py +431 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/headroom_parts_cart.py +19 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/l6_controls.py +92 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/la_report.py +93 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/ladder_gpt_plan.py +95 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/ladder_plan.py +120 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/layer4_plan.py +174 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/lerobot_export.py +431 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/lerobot_replay.py +744 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/lerobot_sft_dataset.py +473 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/make_dossier.py +103 -0
leaf/final/episode_000118_wrist_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_000188.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a6c21041fe7e870dfb64e9066fdb8b1e88f1ea426a171630499c0c7676b940bd
|
| 3 |
+
size 3958
|
leaf/final/episode_000682.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fa2bd914ca89f9b5a5472fafa69a4dc79fd040d45cba70164aab2383b9757e7a
|
| 3 |
+
size 3734
|
leaf/final/episode_001434_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_001473.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bffcee52ba7d49087c639ec2354a58b1e4f8b538f39107daea320e497af7de06
|
| 3 |
+
size 3838
|
leaf/final/episode_003014_image.png
ADDED
|
Git LFS Details
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/arm_specs/l3_card_shelf.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controlled arms for l3_card_shelf (2026-10-12, docs/14 sec. 6).
|
| 2 |
+
|
| 3 |
+
Hidden variable: which end of the (symmetric-looking) card holds the 8 g weight. The centre of mass is compiled into
|
| 4 |
+
the card's MJCF along its local +x, so the heavy end is chosen purely by `card_yaw` (heavy end direction = yaw);
|
| 5 |
+
`heavy_near` / `heavy_edge` are bookkeeping only (nothing in reset / outcome / policies reads them), kept consistent.
|
| 6 |
+
No override changes geometry, mass or inertia, so no bounding-volume refit is involved.
|
| 7 |
+
|
| 8 |
+
h0 : the same card turned end for end (yaw + 180 deg): identical pose and footprint, the weight now in the FAR end,
|
| 9 |
+
so the common-sense "slide the nearest end out" slides the light end and succeeds.
|
| 10 |
+
twin : the trap stays (the heavy end is the nearest end) but it points to the OPPOSITE shelf edge: the card is mirrored
|
| 11 |
+
through the shelf centre along its long axis (near gap, side offset, jitter mirrored) and keeps its weight in
|
| 12 |
+
the end that is now nearest. The right correction (slide the other, light end) is then over the opposite
|
| 13 |
+
edge. For an x-card this makes the near end the BACKWARD one, which the task's own sampler avoids because a
|
| 14 |
+
card tipping off the backward edge lands behind the shelf (agentview shows the shelf empty, not the card);
|
| 15 |
+
see the arm validation (results/l3_card_shelf/arms/). For an instance whose heavy end is already the far end
|
| 16 |
+
(naive succeeds there) the twin keeps the pose and turns the card end for end, so the weight is in the near
|
| 17 |
+
end and the heavy edge is again the opposite one.
|
| 18 |
+
reveal: which shelf edge the heavy end points to, in the F2 feedback's edge words.
|
| 19 |
+
"""
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
HIDDEN_KEYS = ("card_yaw", "heavy_near", "heavy_edge")
|
| 23 |
+
|
| 24 |
+
OPPOSITE = {"forward": "backward", "backward": "forward", "left": "right", "right": "left"}
|
| 25 |
+
GLOSS = {"forward": "away from the robot", "backward": "towards the robot", "left": "on the robot's left",
|
| 26 |
+
"right": "on the robot's right"}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _wrap(a):
|
| 30 |
+
return float((a + np.pi) % (2 * np.pi) - np.pi)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def h0(inst):
|
| 34 |
+
if not inst["heavy_near"]:
|
| 35 |
+
return {} # already the ordinary case for the naive habit (weight away from the end that gets slid out)
|
| 36 |
+
return dict(card_yaw=_wrap(inst["card_yaw"] + np.pi), heavy_near=False, heavy_edge=inst["far_edge"])
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def twin(inst):
|
| 40 |
+
if not inst["heavy_near"]:
|
| 41 |
+
return dict(card_yaw=_wrap(inst["card_yaw"] + np.pi), heavy_near=True, heavy_edge=inst["near_edge"])
|
| 42 |
+
a = 0 if inst["card_along"] == "x" else 1 # world axis of the card's long side
|
| 43 |
+
c = list(inst["card_xy"])
|
| 44 |
+
c[a] = 2.0 * inst["shelf_xy"][a] - c[a]
|
| 45 |
+
yaw = inst["card_yaw"]
|
| 46 |
+
yaw = np.pi - yaw if a == 0 else -yaw # reflection x -> -x (resp. y -> -y) of the card's heading
|
| 47 |
+
return dict(card_xy=[float(c[0]), float(c[1])], card_yaw=_wrap(yaw), near_edge=OPPOSITE[inst["near_edge"]],
|
| 48 |
+
far_edge=OPPOSITE[inst["far_edge"]], heavy_edge=OPPOSITE[inst["heavy_edge"]])
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def reveal(inst):
|
| 52 |
+
e = inst["heavy_edge"]
|
| 53 |
+
return (f"The card is not uniform: 8 g of its 10 g are a weight hidden in the end that points towards the shelf's "
|
| 54 |
+
f"{e} edge ({GLOSS[e]}), so its centre of mass is 2.8 cm from the card's middle towards that end.")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def fix(inst, params):
|
| 58 |
+
"""Ladder Fix rung (docs/20): slide the light end out (two strokes to 2 and 3 cm), grasp the overhang, bin."""
|
| 59 |
+
light = OPPOSITE[inst["heavy_edge"]]
|
| 60 |
+
return (f"A way to succeed: slide the light end out, not the heavy one. The light end is the one pointing towards "
|
| 61 |
+
f"the shelf's {light} edge ({GLOSS[light]}). With the gripper closed, press the fingertips lightly on the "
|
| 62 |
+
f"middle of the card and drag it slowly (speed about 0.08) along its long side towards that edge, in two "
|
| 63 |
+
f"strokes: first until that end sticks out about 2 cm beyond the edge, look, then until it sticks out "
|
| 64 |
+
f"about 3 cm. Then open the gripper, grasp the part that sticks out about 2 cm beyond the edge, at the "
|
| 65 |
+
f"card's height, lift it and drop the card into the bin.")
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/arm_specs/l3_wall_flush.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controlled arms for l3_wall_flush (2026-10-12).
|
| 2 |
+
|
| 3 |
+
Hidden variable: inst["gap"] -- the box-wall gap, 0-3 mm (below camera resolution), far less than the ~1.2 cm a
|
| 4 |
+
finger needs, so the wall-side finger lands on the wall top. sample_instance caches the wall position derived from it
|
| 5 |
+
(wall_x = box_x + side * (wall half thickness + box half width + gap)) and apply_instance reads only inst["wall_xy"],
|
| 6 |
+
so every override below sets wall_xy as well.
|
| 7 |
+
|
| 8 |
+
h0 gap = 5 cm: box, plate, wall length and wall y unchanged, the wall moved 4.7-5 cm away from the box (on the
|
| 9 |
+
same side). There is room for the whole finger and the prior (grasp across the width where the box lies) works.
|
| 10 |
+
(2.5 cm was not enough: the open fingers reach 6.6 cm from the grasp centre, so with the wall on the far side
|
| 11 |
+
the outer edge of the finger still caught the wall top and the box slipped out on the way, seeds 3000 / 3003.)
|
| 12 |
+
twin Gap unchanged (box still flush, trap active), box / plate / wall length / wall x unchanged, but the wall slid
|
| 13 |
+
along y so that the box sits near the OTHER end of the wall, 2 cm of wall beyond the box's end (the sampler's
|
| 14 |
+
extreme). The original's nearer wall end is +y (or -y); the twin's is -y (or +y): the push that clears the
|
| 15 |
+
wall goes the opposite way, and is the shortest possible push (about 10 + 4.5 cm).
|
| 16 |
+
Note: pushing the original's box towards its FAR end also clears the wall (just a longer push), so the cross
|
| 17 |
+
check "twin oracle on the original" succeeds (measured 5/5, seeds 3000-3004; results/l3_wall_flush/arms/
|
| 18 |
+
validate.json). The twin changes which way to push, not whether pushing works.
|
| 19 |
+
reveal The gap, and on which side of the box the wall is, in the task's F2 frame words.
|
| 20 |
+
"""
|
| 21 |
+
BOX_HALF_X, BOX_HALF_Y, WALL_HALF_T = 0.03, 0.08, 0.015
|
| 22 |
+
H0_GAP = 0.05
|
| 23 |
+
|
| 24 |
+
HIDDEN_KEYS = ("gap",)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _wall_x(inst, gap):
|
| 28 |
+
return inst["box_xy"][0] + inst["side"] * (WALL_HALF_T + BOX_HALF_X + gap)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def h0(inst):
|
| 32 |
+
return {"gap": H0_GAP, "wall_xy": [_wall_x(inst, H0_GAP), inst["wall_xy"][1]]}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def twin(inst):
|
| 36 |
+
wy, by = inst["wall_xy"][1], inst["box_xy"][1]
|
| 37 |
+
u_max = inst["wall_hl"] - BOX_HALF_Y - 0.02
|
| 38 |
+
nearer = 1 if by - wy > 0 else -1 # same rule as WallFlush._nearer_end
|
| 39 |
+
u_twin = -nearer * u_max # box offset from the wall centre in the twin: near the other end
|
| 40 |
+
return {"wall_xy": [inst["wall_xy"][0], by - u_twin]}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def reveal(inst):
|
| 44 |
+
side = "far side (away from the robot)" if inst["side"] > 0 else "near side (toward the robot)"
|
| 45 |
+
return (f"The long box is pressed against the wall on its {side} along its whole length: the gap between box "
|
| 46 |
+
f"and wall is only about {max(100 * inst['gap'], 0.1):.1f} cm.")
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def fix(inst, params):
|
| 50 |
+
"""Ladder Fix rung (docs/20): push the box along the wall past its nearer end (oracle end, margin 4.5 cm), then
|
| 51 |
+
grasp across the width and place."""
|
| 52 |
+
end, margin = int(params["end"]), float(params["margin"])
|
| 53 |
+
wy, hl, by = float(inst["wall_xy"][1]), float(inst["wall_hl"]), float(inst["box_xy"][1])
|
| 54 |
+
wall_end = wy + hl if end > 0 else wy - hl
|
| 55 |
+
dist = max(0.0, end * (wall_end + end * margin - by))
|
| 56 |
+
side, other = ("left", "right") if end > 0 else ("right", "left")
|
| 57 |
+
return (f"A way to succeed: first get the box away from the wall, then grasp it. With the gripper closed and the "
|
| 58 |
+
f"fingertips about 1 cm above the table, push on the box's end face on the robot's {other} side and slide "
|
| 59 |
+
f"the box slowly (speed about 0.08) along the wall towards the robot's {side}, about {100 * dist:.0f} cm, "
|
| 60 |
+
f"until the whole box is past the end of the wall (its centre about {100 * margin:.1f} cm beyond the "
|
| 61 |
+
f"wall's end). Then lift, open the gripper, grasp the box across its 6 cm width and put it on the plate.")
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/arm_specs/l7_key_turn.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controlled-arm spec for l7_key_turn (2026-10-12).
|
| 2 |
+
|
| 3 |
+
Hidden variable: inst["direction"], the way the key opens the lock ("CCW" or "CW", seen from above). apply_instance()
|
| 4 |
+
derives the joint range and outcome()/check_unlock()/oracle_params() derive the open sign from it on every reset, so
|
| 5 |
+
overriding "direction" alone is enough (nothing is cached at sampling time).
|
| 6 |
+
|
| 7 |
+
The scripted prior (naive) turns counterclockwise, so the trap exists only on CW locks -- all full5 instances are CW.
|
| 8 |
+
|
| 9 |
+
h0 -> direction = "CCW": same lock position / yaw, the key opens the common-sense way, naive succeeds.
|
| 10 |
+
twin -> {} (no valid twin). The task has a single binary hidden variable and the trap exists only for one of its two
|
| 11 |
+
values: a twin with the trap still active must be CW again, i.e. need exactly the same correction ("turn
|
| 12 |
+
clockwise"), and the sign-flipped twin (CCW) is the H0 twin, where naive succeeds. There is no second hidden
|
| 13 |
+
constraint (the required angle is the fixed quarter turn named in the instruction). The mismatched-history
|
| 14 |
+
arm therefore has to take another instance's history -- note that every trap instance's history teaches the
|
| 15 |
+
same correction, so for this task a mismatched history is not misleading about the direction.
|
| 16 |
+
reveal -> states which way the key turns and that the other way stops after ~3 deg (the words "clockwise",
|
| 17 |
+
"counterclockwise", "seen from above" are those of the task's F2 feedback).
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
HIDDEN_KEYS = ("direction",)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def h0(inst):
|
| 24 |
+
return {"direction": "CCW"}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def twin(inst):
|
| 28 |
+
return {}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def reveal(inst):
|
| 32 |
+
ok, other = (("counterclockwise", "clockwise") if inst["direction"] == "CCW" else ("clockwise", "counterclockwise"))
|
| 33 |
+
return (f"Note: this lock opens only when the key is turned {ok} (seen from above); turned {other} the key moves "
|
| 34 |
+
f"about 3 degrees and then hits a hard stop.")
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/pins/claude_code_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "claude_code|2.1.267|0399c793ff571d59|claude-sonnet-5-5|high",
|
| 3 |
+
"fingerprint_sha256": "fbf323682711d7010fa8cd2c9036b1082dab2a6cd4cf80983be1adf64e037d7c",
|
| 4 |
+
"written": "2026-10-20 02:16:00",
|
| 5 |
+
"summary": {
|
| 6 |
+
"system_chars": 182,
|
| 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/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-sonnet-5-5_high.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "claude_code_full-oauth|2.1.299|2d894a4b1bfaaa9a|claude-sonnet-5-5|high",
|
| 3 |
+
"fingerprint_sha256": "a8c04b0dca902885e52e7e5680c1cf8b782469e79c518f83b72249342285bfb0",
|
| 4 |
+
"written": "2026-10-21 05:19:29",
|
| 5 |
+
"summary": {
|
| 6 |
+
"system_chars": 5629,
|
| 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_breakfast1_20261114/lff/source_closure/lffbench/agent/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""LFF-Bench agent harness: tool interface, context packing, model backends, protocol runner."""
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/camera.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Camera geometry for the agent tools: pixel -> world back-projection with the rendered depth map.
|
| 2 |
+
|
| 3 |
+
Conventions (match the images the agent receives, i.e. `envs.render`, which flips MuJoCo's
|
| 4 |
+
bottom-up buffer to an upright image):
|
| 5 |
+
u = column index (0 = left edge), v = row index (0 = top edge), both in pixels of a res x res image.
|
| 6 |
+
Intrinsics / extrinsics / depth linearisation come from robosuite.utils.camera_utils.
|
| 7 |
+
"""
|
| 8 |
+
import numpy as np
|
| 9 |
+
from robosuite.utils import camera_utils as CU
|
| 10 |
+
|
| 11 |
+
from .. import envs
|
| 12 |
+
|
| 13 |
+
# agent-facing camera name -> MuJoCo camera name
|
| 14 |
+
CAMERAS = {"agentview": "agentview", "wrist": "robot0_eye_in_hand"}
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def mj_cam(name):
|
| 18 |
+
if name in CAMERAS:
|
| 19 |
+
return CAMERAS[name]
|
| 20 |
+
if name in CAMERAS.values():
|
| 21 |
+
return name
|
| 22 |
+
raise KeyError(f"unknown camera {name!r}; use one of {sorted(CAMERAS)}")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def intrinsics(env, cam, res):
|
| 26 |
+
return CU.get_camera_intrinsic_matrix(env.sim, mj_cam(cam), res, res)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def cam_to_world(env, cam):
|
| 30 |
+
"""4x4 pose of the camera in the world, OpenCV axes (x right, y down, z forward)."""
|
| 31 |
+
return CU.get_camera_extrinsic_matrix(env.sim, mj_cam(cam))
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def render_depth(env, cam, res):
|
| 35 |
+
"""Metric depth (distance along the optical axis, metres), upright (res, res)."""
|
| 36 |
+
_, d = envs.render(env, mj_cam(cam), res, depth=True)
|
| 37 |
+
return CU.get_real_depth_map(env.sim, np.clip(d, 0.0, 1.0))
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def world_to_pixel(env, cam, xyz, res):
|
| 41 |
+
"""Project a world point; returns (u, v) floats (u = column, v = row) and the depth."""
|
| 42 |
+
K = intrinsics(env, cam, res)
|
| 43 |
+
T = np.linalg.inv(cam_to_world(env, cam))
|
| 44 |
+
p = T @ np.append(np.asarray(xyz, float), 1.0)
|
| 45 |
+
uvw = K @ p[:3]
|
| 46 |
+
return float(uvw[0] / uvw[2]), float(uvw[1] / uvw[2]), float(p[2])
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def pixel_ray(env, cam, u, v, res):
|
| 50 |
+
"""Unit ray direction (world) through pixel (u, v) and the camera origin."""
|
| 51 |
+
K = intrinsics(env, cam, res)
|
| 52 |
+
E = cam_to_world(env, cam)
|
| 53 |
+
d_cam = np.array([(u - K[0, 2]) / K[0, 0], (v - K[1, 2]) / K[1, 1], 1.0])
|
| 54 |
+
d = E[:3, :3] @ d_cam
|
| 55 |
+
return E[:3, 3].copy(), d / np.linalg.norm(d)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def pixel_to_world(env, cam, u, v, res, depth=None):
|
| 59 |
+
"""Back-project pixel (u, v) of a res x res image using the depth map. Returns a dict."""
|
| 60 |
+
if depth is None:
|
| 61 |
+
depth = render_depth(env, cam, res)
|
| 62 |
+
iu, iv = int(round(u)), int(round(v))
|
| 63 |
+
if not (0 <= iu < res and 0 <= iv < res):
|
| 64 |
+
raise ValueError(f"pixel ({u}, {v}) outside the {res}x{res} image")
|
| 65 |
+
z = float(depth[iv, iu])
|
| 66 |
+
K = intrinsics(env, cam, res)
|
| 67 |
+
E = cam_to_world(env, cam)
|
| 68 |
+
p_cam = np.array([(u - K[0, 2]) * z / K[0, 0], (v - K[1, 2]) * z / K[1, 1], z, 1.0])
|
| 69 |
+
p = E @ p_cam
|
| 70 |
+
far = env.sim.model.vis.map.zfar * env.sim.model.stat.extent
|
| 71 |
+
return dict(xyz=p[:3], depth=z, valid=bool(z < 0.98 * far))
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def image_axes(env, cam, res, plane_z=envs.TABLE_Z):
|
| 75 |
+
"""World directions of image-right and image-down at the image centre, projected onto the table
|
| 76 |
+
plane (for describing the camera to the agent). Returns two unit 2-vectors (x, y)."""
|
| 77 |
+
o, d = pixel_ray(env, cam, res / 2, res / 2, res)
|
| 78 |
+
if abs(d[2]) < 1e-6:
|
| 79 |
+
return None
|
| 80 |
+
t = (plane_z - o[2]) / d[2]
|
| 81 |
+
c = o + t * d
|
| 82 |
+
out = []
|
| 83 |
+
for du, dv in ((8, 0), (0, 8)):
|
| 84 |
+
o2, d2 = pixel_ray(env, cam, res / 2 + du, res / 2 + dv, res)
|
| 85 |
+
t2 = (plane_z - o2[2]) / d2[2]
|
| 86 |
+
w = (o2 + t2 * d2 - c)[:2]
|
| 87 |
+
out.append(w / max(np.linalg.norm(w), 1e-9))
|
| 88 |
+
return out
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def describe_axes(env, cam, res):
|
| 92 |
+
"""Human-readable mapping 'image right ~ +y, image down ~ +x' (dominant axis, sign)."""
|
| 93 |
+
ax = image_axes(env, cam, res)
|
| 94 |
+
if ax is None:
|
| 95 |
+
return None
|
| 96 |
+
names = []
|
| 97 |
+
for w in ax:
|
| 98 |
+
i = int(np.argmax(np.abs(w)))
|
| 99 |
+
names.append(("+" if w[i] > 0 else "-") + "xy"[i])
|
| 100 |
+
return dict(right=names[0], down=names[1])
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/context.py
ADDED
|
@@ -0,0 +1,377 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Backend-neutral conversation, attempt records, memory selection and prompt text.
|
| 2 |
+
|
| 3 |
+
A conversation is a list of items (plain dicts):
|
| 4 |
+
{"kind": "user", "parts": [{"type": "text", "text": str} | {"type": "image", "image": ImageRef}], "live": bool}
|
| 5 |
+
{"kind": "assistant", "text": str|None, "tool_calls": [ToolCall], "raw": list|None, "backend": str}
|
| 6 |
+
{"kind": "tool_output", "call_id": str, "name": str, "text": str}
|
| 7 |
+
The system prompt is kept separately (Conversation.system). Backends convert this into their own wire
|
| 8 |
+
format (OpenAI Responses input items, Chat Completions messages, ...).
|
| 9 |
+
|
| 10 |
+
"live" user items are the current attempt's observations; old live images can be dropped to bound the
|
| 11 |
+
request size. History (earlier attempts) is packed into the attempt's first user item and never pruned,
|
| 12 |
+
so the request prefix stays byte-stable within an attempt and grows append-only across attempts
|
| 13 |
+
(prompt-cache friendly).
|
| 14 |
+
"""
|
| 15 |
+
import copy
|
| 16 |
+
import json
|
| 17 |
+
import math
|
| 18 |
+
from dataclasses import dataclass, field
|
| 19 |
+
from typing import Optional
|
| 20 |
+
|
| 21 |
+
from ..envs import TABLE_Z
|
| 22 |
+
|
| 23 |
+
MEMORY_MODES = ("none", "full", "last", "mismatched")
|
| 24 |
+
FEEDBACK_LEVELS = ("F0", "F1", "F2")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@dataclass
|
| 28 |
+
class ToolCall:
|
| 29 |
+
id: str
|
| 30 |
+
name: str
|
| 31 |
+
arguments: dict
|
| 32 |
+
raw_arguments: str = ""
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@dataclass
|
| 36 |
+
class StepRecord:
|
| 37 |
+
step: int
|
| 38 |
+
name: str
|
| 39 |
+
args: dict
|
| 40 |
+
report: dict
|
| 41 |
+
ok: bool
|
| 42 |
+
wall_s: float = 0.0
|
| 43 |
+
sim_steps: int = 0
|
| 44 |
+
frame: object = None # ImageRef of the agentview after this step (for keyframes)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@dataclass
|
| 48 |
+
class AttemptRecord:
|
| 49 |
+
seed: int
|
| 50 |
+
attempt: int
|
| 51 |
+
steps: list = field(default_factory=list)
|
| 52 |
+
keyframes: list = field(default_factory=list) # [(caption, ImageRef)]
|
| 53 |
+
outcome: dict = field(default_factory=dict)
|
| 54 |
+
success: bool = False
|
| 55 |
+
feedback: str = ""
|
| 56 |
+
done_reason: Optional[str] = None
|
| 57 |
+
diagnosis: Optional[str] = None
|
| 58 |
+
ended_by: str = ""
|
| 59 |
+
backend_meta: dict = field(default_factory=dict)
|
| 60 |
+
|
| 61 |
+
def action_signature(self, nd=2):
|
| 62 |
+
"""Rounded action sequence (to compare consecutive attempts: 'same mistake again')."""
|
| 63 |
+
sig = []
|
| 64 |
+
for s in self.steps:
|
| 65 |
+
if s.name in ("get_observation", "pixel_to_world", "locate", "done"):
|
| 66 |
+
continue
|
| 67 |
+
sig.append((s.name, tuple(sorted((k, round(v, nd) if isinstance(v, (int, float)) and v is not None else v)
|
| 68 |
+
for k, v in s.args.items()))))
|
| 69 |
+
return tuple(sig)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def select_history(mode, own, donor=None):
|
| 73 |
+
"""Which earlier attempts the agent sees at the start of the next attempt."""
|
| 74 |
+
if mode == "none":
|
| 75 |
+
return []
|
| 76 |
+
if mode == "full":
|
| 77 |
+
return list(own)
|
| 78 |
+
if mode == "last":
|
| 79 |
+
return list(own[-1:])
|
| 80 |
+
if mode == "mismatched":
|
| 81 |
+
if donor is None:
|
| 82 |
+
raise ValueError("mismatched memory needs donor attempts from another instance")
|
| 83 |
+
return list(donor[:len(own)])
|
| 84 |
+
raise ValueError(mode)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class Conversation:
|
| 88 |
+
def __init__(self, system):
|
| 89 |
+
self.system = system
|
| 90 |
+
self.items = []
|
| 91 |
+
|
| 92 |
+
def add_user(self, parts, live=True):
|
| 93 |
+
self.items.append(dict(kind="user", parts=list(parts), live=live))
|
| 94 |
+
|
| 95 |
+
def add_assistant(self, text, tool_calls, raw=None, backend=""):
|
| 96 |
+
self.items.append(dict(kind="assistant", text=text, tool_calls=list(tool_calls), raw=raw, backend=backend))
|
| 97 |
+
|
| 98 |
+
def add_tool_output(self, call_id, name, text):
|
| 99 |
+
self.items.append(dict(kind="tool_output", call_id=call_id, name=name, text=text))
|
| 100 |
+
|
| 101 |
+
def n_images(self):
|
| 102 |
+
return sum(1 for it in self.items if it["kind"] == "user" for p in it["parts"] if p["type"] == "image")
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def prune_live_images(items, max_live):
|
| 106 |
+
"""Copy of `items` keeping only the newest `max_live` live images. Hysteresis: when the budget is
|
| 107 |
+
exceeded, prune down to half of it so the request prefix stays stable for several steps."""
|
| 108 |
+
if max_live is None or max_live < 0:
|
| 109 |
+
return items
|
| 110 |
+
live = [(i, j) for i, it in enumerate(items) if it["kind"] == "user" and it.get("live")
|
| 111 |
+
for j, p in enumerate(it["parts"]) if p["type"] == "image"]
|
| 112 |
+
if len(live) <= max_live:
|
| 113 |
+
return items
|
| 114 |
+
keep_n = max(max_live // 2, 1)
|
| 115 |
+
drop = set(live[:len(live) - keep_n])
|
| 116 |
+
out = []
|
| 117 |
+
for i, it in enumerate(items):
|
| 118 |
+
if it["kind"] == "user" and any((i, j) in drop for j in range(len(it["parts"]))):
|
| 119 |
+
it = dict(it)
|
| 120 |
+
parts = []
|
| 121 |
+
for j, p in enumerate(it["parts"]):
|
| 122 |
+
if (i, j) in drop:
|
| 123 |
+
parts.append(dict(type="text", text=f"[{p['image'].camera} image omitted to save context]"))
|
| 124 |
+
else:
|
| 125 |
+
parts.append(p)
|
| 126 |
+
it["parts"] = parts
|
| 127 |
+
out.append(it)
|
| 128 |
+
return out
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# ---------------------------------------------------------------------------------------------- text
|
| 132 |
+
|
| 133 |
+
def fmt_num(v):
|
| 134 |
+
if v is None:
|
| 135 |
+
return "null"
|
| 136 |
+
if isinstance(v, bool):
|
| 137 |
+
return str(v).lower()
|
| 138 |
+
if isinstance(v, float):
|
| 139 |
+
return f"{v:.3f}".rstrip("0").rstrip(".") if abs(v) < 1e4 else f"{v:.4g}"
|
| 140 |
+
return json.dumps(v)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def fmt_call(name, args):
|
| 144 |
+
return f"{name}(" + ", ".join(f"{k}={fmt_num(v)}" for k, v in args.items()) + ")"
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def fmt_report(name, rep):
|
| 148 |
+
if not rep.get("ok", False):
|
| 149 |
+
return "ERROR: " + str(rep.get("error"))
|
| 150 |
+
bits = []
|
| 151 |
+
if "reached" in rep:
|
| 152 |
+
bits.append("reached" if rep["reached"] else "NOT reached")
|
| 153 |
+
if "sweep_reached" in rep:
|
| 154 |
+
bits.append("sweep completed" if rep["sweep_reached"] else "sweep NOT completed")
|
| 155 |
+
if "eef_pos" in rep and name in ("move_to", "push", "open_gripper", "close_gripper"):
|
| 156 |
+
bits.append("eef (" + ", ".join(f"{x:.3f}" for x in rep["eef_pos"]) + ")")
|
| 157 |
+
if name in ("open_gripper", "close_gripper"):
|
| 158 |
+
bits.append(f"width {rep.get('gripper_width_m', 0):.3f} m")
|
| 159 |
+
if rep.get("holding_object") not in (None, False):
|
| 160 |
+
bits.append(f"holding {rep['holding_object']}" if isinstance(rep["holding_object"], str) else "holding an object")
|
| 161 |
+
if rep.get("touched_object") or rep.get("touched_objects"):
|
| 162 |
+
t = rep.get("touched_objects")
|
| 163 |
+
bits.append("touched " + ", ".join(t) if t else "touched an object")
|
| 164 |
+
if name == "pixel_to_world":
|
| 165 |
+
bits.append("world (" + ", ".join(f"{x:.3f}" for x in rep["world_xyz"]) + ")")
|
| 166 |
+
if name == "locate":
|
| 167 |
+
bits.append("pos (" + ", ".join(f"{x:.3f}" for x in rep["position"]) + ")")
|
| 168 |
+
if "target_clipped_to" in rep or "start_clipped_to" in rep:
|
| 169 |
+
bits.append("target clipped to workspace")
|
| 170 |
+
if rep.get("events"):
|
| 171 |
+
bits.append("EVENT: " + " ".join(rep["events"]))
|
| 172 |
+
return "; ".join(bits) if bits else "ok"
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def summarize_actions(steps):
|
| 176 |
+
lines = []
|
| 177 |
+
for s in steps:
|
| 178 |
+
if s.name == "done":
|
| 179 |
+
lines.append(f"{s.step}. done(reason={json.dumps(s.args.get('reason', ''))})")
|
| 180 |
+
else:
|
| 181 |
+
lines.append(f"{s.step}. {fmt_call(s.name, s.args)} -> {fmt_report(s.name, s.report)}")
|
| 182 |
+
return "\n".join(lines) if lines else "(no actions)"
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def _text(t):
|
| 186 |
+
return dict(type="text", text=t)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _img(ref):
|
| 190 |
+
return dict(type="image", image=ref)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class PromptBuilder:
|
| 194 |
+
"""All text the agent sees. One instance per (task, config)."""
|
| 195 |
+
|
| 196 |
+
def __init__(self, task, protocol, k, memory, feedback, image_res, cam_axes, privileged_locate=False,
|
| 197 |
+
object_names=(), grasp_report="bool", cams=("agentview", "wrist"), depth_tool=True):
|
| 198 |
+
self.task, self.protocol, self.k = task, protocol, k
|
| 199 |
+
self.depth_tool = depth_tool
|
| 200 |
+
self.memory, self.feedback = memory, feedback
|
| 201 |
+
self.image_res, self.cam_axes = image_res, cam_axes
|
| 202 |
+
self.privileged_locate, self.object_names = privileged_locate, list(object_names)
|
| 203 |
+
self.grasp_report, self.cams = grasp_report, tuple(cams)
|
| 204 |
+
|
| 205 |
+
# ----------------------------------------------------------------------------- system prompt
|
| 206 |
+
def system_prompt(self):
|
| 207 |
+
ax = self.cam_axes.get("agentview") or {}
|
| 208 |
+
wx = self.cam_axes.get("wrist") or {}
|
| 209 |
+
lines = [
|
| 210 |
+
"You control a Franka Panda robot arm with a parallel-jaw gripper in a tabletop physics simulation. "
|
| 211 |
+
"You act only by calling the provided tools, exactly one tool call per turn. Every action tool returns an "
|
| 212 |
+
"execution report; after each action you also receive new camera images and the robot's proprioceptive "
|
| 213 |
+
"state.",
|
| 214 |
+
"",
|
| 215 |
+
"Coordinates (world frame, metres): the table top is at z = %.2f; the robot base is at x = -0.66, y = 0; "
|
| 216 |
+
"+x points away from the robot, +y to the robot's left, +z up. Positions given to move_to / push are for "
|
| 217 |
+
"the gripper's grasp point (midway between the fingertips). The gripper always points straight down; yaw "
|
| 218 |
+
"(degrees) turns it about the vertical axis: at yaw 0 the fingers close along the world y axis, at yaw 90 "
|
| 219 |
+
"along the world x axis; yaw is taken modulo 180 degrees because the gripper is symmetric." % TABLE_Z,
|
| 220 |
+
"",
|
| 221 |
+
"Direction words in every text you receive (task, reports, feedback) are robot-centric: forward = +x (away "
|
| 222 |
+
"from the robot), backward = -x (toward the robot), left = +y (the robot's left), right = -y (the robot's "
|
| 223 |
+
"right), up = +z. They never mean left/right in an image.",
|
| 224 |
+
"",
|
| 225 |
+
"Cameras (%dx%d images): 'agentview' looks at the table from the side opposite the robot, so the robot "
|
| 226 |
+
"appears at the top of that image; image-right is %s and image-down is %s in world coordinates (so the "
|
| 227 |
+
"robot's left appears on the right side of that image). 'wrist' is "
|
| 228 |
+
"mounted on the gripper and looks down between the fingers (at yaw 0, image-right is %s and image-down is "
|
| 229 |
+
"%s).%s"
|
| 230 |
+
% (self.image_res, self.image_res, ax.get("right", "?"), ax.get("down", "?"), wx.get("right", "?"),
|
| 231 |
+
wx.get("down", "?"),
|
| 232 |
+
" For pixel_to_world, u is the column counted from the left edge and v the row counted from the top "
|
| 233 |
+
"edge of the image as you received it." if self.depth_tool else ""),
|
| 234 |
+
"",
|
| 235 |
+
"Proprioception (end-effector position, yaw, gripper width%s) comes from the robot's own sensors."
|
| 236 |
+
% (", whether an object is held" if self.grasp_report != "none" else ""),
|
| 237 |
+
]
|
| 238 |
+
if self.privileged_locate:
|
| 239 |
+
lines += ["", "The locate tool is available and returns exact object positions. Objects: "
|
| 240 |
+
+ ", ".join(self.object_names) + "."]
|
| 241 |
+
else:
|
| 242 |
+
lines += ["", "Object positions are not given to you: localise objects from the images, e.g. by calling "
|
| 243 |
+
"pixel_to_world on the pixel where you see them." if self.depth_tool else
|
| 244 |
+
"Object positions are not given to you and there is no depth sensor: the cameras give colour "
|
| 245 |
+
"images only. Localise objects from the images."]
|
| 246 |
+
lines += ["", self._protocol_text(), "", self._feedback_text()]
|
| 247 |
+
if self.memory != "none":
|
| 248 |
+
lines += ["", "At the start of every attempt after the first, before your first tool call, write one to "
|
| 249 |
+
"three sentences assessing the earlier attempt(s): what happened and what you will keep or "
|
| 250 |
+
"change."]
|
| 251 |
+
lines += ["", "Finish by calling done(reason) when you believe the task is complete. Be precise: small errors "
|
| 252 |
+
"in position or speed matter."]
|
| 253 |
+
return "\n".join(lines)
|
| 254 |
+
|
| 255 |
+
def _protocol_text(self):
|
| 256 |
+
if self.memory == "none":
|
| 257 |
+
if self.protocol == "within":
|
| 258 |
+
return "Work on the task until you believe it is complete, then call done."
|
| 259 |
+
return "You have one attempt at the task; it ends when you call done."
|
| 260 |
+
if self.protocol == "within":
|
| 261 |
+
if self.feedback == "F0":
|
| 262 |
+
return (f"Everything happens in one continuous episode. After you call done you may be asked to "
|
| 263 |
+
f"continue from the current state; you may call done at most {self.k} times.")
|
| 264 |
+
return (f"Everything happens in one continuous episode. When you call done, the task is checked; if it is "
|
| 265 |
+
f"not complete you are told so and continue from the current state. You may call done at most "
|
| 266 |
+
f"{self.k} times.")
|
| 267 |
+
return (f"You get up to {self.k} attempts at the same task. Before every attempt the scene is reset to exactly "
|
| 268 |
+
f"the same initial state, with the same objects and the same physical properties. Each attempt ends "
|
| 269 |
+
f"when you call done; you will then see a summary of the attempt (key images, the actions you "
|
| 270 |
+
f"executed{'' if self.feedback == 'F0' else ' and outcome feedback'}).")
|
| 271 |
+
|
| 272 |
+
def _feedback_text(self):
|
| 273 |
+
if self.memory == "none":
|
| 274 |
+
return ""
|
| 275 |
+
if self.feedback == "F0":
|
| 276 |
+
return ("You will not be told whether an attempt succeeded; judge it from the images. "
|
| 277 |
+
+ ("Attempts continue until the budget is used up." if self.protocol == "cross" else ""))
|
| 278 |
+
if self.feedback == "F1":
|
| 279 |
+
return "After each attempt you are told only whether it succeeded."
|
| 280 |
+
return "After each attempt you are told whether it succeeded and, if not, a measurement of what went wrong."
|
| 281 |
+
|
| 282 |
+
# ----------------------------------------------------------------------------- per attempt
|
| 283 |
+
def history_parts(self, instruction, history):
|
| 284 |
+
"""First user item of an attempt (not pruned): task + packed earlier attempts. The header carries no
|
| 285 |
+
count so that the item grows append-only from one attempt to the next (prompt-cache friendly)."""
|
| 286 |
+
parts = [_text("TASK: " + instruction)]
|
| 287 |
+
if history:
|
| 288 |
+
parts.append(_text("\n=== Your earlier attempts ==="))
|
| 289 |
+
for i, rec in enumerate(history, 1):
|
| 290 |
+
parts += self.history_block(rec, i)
|
| 291 |
+
parts.append(_text("=== End of earlier attempts ==="))
|
| 292 |
+
return parts
|
| 293 |
+
|
| 294 |
+
def current_parts(self, attempt, obs_images, proprio, continuing=False):
|
| 295 |
+
"""Second user item of an attempt (live): attempt counter + current observation."""
|
| 296 |
+
parts = []
|
| 297 |
+
if self.memory != "none":
|
| 298 |
+
if self.protocol == "within" and continuing:
|
| 299 |
+
if self.feedback == "F0":
|
| 300 |
+
parts.append(_text(f"You called done. Continue from the current state (this is segment "
|
| 301 |
+
f"{attempt}; you may call done at most {self.k} times in total)."))
|
| 302 |
+
else:
|
| 303 |
+
parts.append(_text(f"You called done, but the task is not complete. Continue from the current "
|
| 304 |
+
f"state (this is segment {attempt}; you may call done at most {self.k} times "
|
| 305 |
+
f"in total)."))
|
| 306 |
+
elif self.protocol == "cross":
|
| 307 |
+
parts.append(_text(f"This is attempt {attempt} of at most {self.k}. The scene has been reset."))
|
| 308 |
+
parts += self.observation_parts("Current observation", obs_images, proprio)
|
| 309 |
+
return parts
|
| 310 |
+
|
| 311 |
+
def history_block(self, rec, idx):
|
| 312 |
+
head = f"\n--- Attempt {idx} ---" if self.protocol == "cross" else f"\n--- Segment {idx} (until done call {idx}) ---"
|
| 313 |
+
parts = [_text(head + "\nActions executed:\n" + summarize_actions(rec.steps))]
|
| 314 |
+
fb = (rec.feedback or "").strip()
|
| 315 |
+
if self.feedback != "F0" and fb:
|
| 316 |
+
parts.append(_text("Outcome feedback: " + fb))
|
| 317 |
+
if rec.keyframes:
|
| 318 |
+
parts.append(_text("Key images (" + ", ".join(c for c, _ in rec.keyframes) + "):"))
|
| 319 |
+
for cap, ref in rec.keyframes:
|
| 320 |
+
parts.append(_text(f"[{cap}]"))
|
| 321 |
+
parts.append(_img(ref))
|
| 322 |
+
return parts
|
| 323 |
+
|
| 324 |
+
def observation_parts(self, title, images, proprio):
|
| 325 |
+
parts = [_text(f"\n{title}:")]
|
| 326 |
+
for ref in images:
|
| 327 |
+
parts.append(_text(f"{ref.camera} camera:"))
|
| 328 |
+
parts.append(_img(ref))
|
| 329 |
+
parts.append(_text("Proprioception: " + json.dumps(proprio)))
|
| 330 |
+
return parts
|
| 331 |
+
|
| 332 |
+
def step_observation(self, step, tool_name, images, proprio):
|
| 333 |
+
return self.observation_parts(f"Observation after step {step} ({tool_name})", images, proprio)
|
| 334 |
+
|
| 335 |
+
@staticmethod
|
| 336 |
+
def nudge():
|
| 337 |
+
return [_text("Please continue by calling exactly one tool (call done if you are finished).")]
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def pick_keyframes(steps, initial, final, n=4):
|
| 341 |
+
"""<= n agentview keyframes: start, up to n-2 informative intermediate frames, end (after settling)."""
|
| 342 |
+
out = [("start of attempt", initial)] if initial is not None and n >= 2 else []
|
| 343 |
+
budget = n - len(out) - (1 if final is not None else 0)
|
| 344 |
+
cands = [s for s in steps if s.frame is not None]
|
| 345 |
+
if budget > 0 and cands:
|
| 346 |
+
events = [s for s in cands if s.name in ("push", "close_gripper", "open_gripper")
|
| 347 |
+
or s.report.get("touched_object") or s.report.get("touched_objects")]
|
| 348 |
+
pool = events if len(events) >= budget else cands
|
| 349 |
+
if len(pool) > budget:
|
| 350 |
+
idx = [round(i * (len(pool) - 1) / max(budget - 1, 1)) for i in range(budget)] if budget > 1 \
|
| 351 |
+
else [len(pool) - 1]
|
| 352 |
+
pool = [pool[i] for i in sorted(set(idx))]
|
| 353 |
+
for s in sorted(pool, key=lambda s: s.step)[:budget]:
|
| 354 |
+
out.append((f"after step {s.step} ({s.name})", s.frame))
|
| 355 |
+
if final is not None:
|
| 356 |
+
out.append(("end of attempt, after objects settled", final))
|
| 357 |
+
return out[:n]
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def wilson(k, n, z=1.96):
|
| 361 |
+
if n == 0:
|
| 362 |
+
return (float("nan"), float("nan"))
|
| 363 |
+
p = k / n
|
| 364 |
+
d = 1 + z * z / n
|
| 365 |
+
c = (p + z * z / (2 * n)) / d
|
| 366 |
+
h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
|
| 367 |
+
return (max(0.0, c - h), min(1.0, c + h))
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def deep_strip_images(obj):
|
| 371 |
+
"""JSON-friendly copy of conversation items (images -> paths)."""
|
| 372 |
+
obj = copy.copy(obj)
|
| 373 |
+
if isinstance(obj, dict):
|
| 374 |
+
return {k: (v.path if k == "image" else deep_strip_images(v)) for k, v in obj.items()}
|
| 375 |
+
if isinstance(obj, list):
|
| 376 |
+
return [deep_strip_images(v) for v in obj]
|
| 377 |
+
return obj
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/images.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Image references and encoding (JPEG bytes are what the model sees and what is saved to disk)."""
|
| 2 |
+
import base64
|
| 3 |
+
import io
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from typing import Any, Optional
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@dataclass
|
| 11 |
+
class ImageRef:
|
| 12 |
+
camera: str # agent-facing camera name ("agentview" / "wrist")
|
| 13 |
+
array: Any = None # uint8 HxWx3
|
| 14 |
+
label: str = ""
|
| 15 |
+
path: Optional[str] = None # where the encoded image was saved
|
| 16 |
+
jpeg: Optional[bytes] = None # encoded bytes actually sent to the model
|
| 17 |
+
|
| 18 |
+
def encoded(self, quality=90):
|
| 19 |
+
if self.jpeg is None:
|
| 20 |
+
if self.array is None and self.path:
|
| 21 |
+
with open(self.path, "rb") as f:
|
| 22 |
+
self.jpeg = f.read()
|
| 23 |
+
else:
|
| 24 |
+
self.jpeg = encode_jpeg(self.array, quality)
|
| 25 |
+
return self.jpeg
|
| 26 |
+
|
| 27 |
+
def data_url(self, quality=90):
|
| 28 |
+
return "data:image/jpeg;base64," + base64.b64encode(self.encoded(quality)).decode("ascii")
|
| 29 |
+
|
| 30 |
+
@property
|
| 31 |
+
def size(self):
|
| 32 |
+
return None if self.array is None else tuple(np.asarray(self.array).shape[:2])
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def encode_jpeg(arr, quality=90):
|
| 36 |
+
from PIL import Image
|
| 37 |
+
buf = io.BytesIO()
|
| 38 |
+
Image.fromarray(np.asarray(arr, dtype=np.uint8)).save(buf, format="JPEG", quality=int(quality))
|
| 39 |
+
return buf.getvalue()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def resize(arr, res):
|
| 43 |
+
from PIL import Image
|
| 44 |
+
arr = np.asarray(arr, dtype=np.uint8)
|
| 45 |
+
if arr.shape[0] == res and arr.shape[1] == res:
|
| 46 |
+
return arr
|
| 47 |
+
return np.asarray(Image.fromarray(arr).resize((res, res), Image.BILINEAR))
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/replay.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Rebuild AttemptRecords from a finished run directory (events.jsonl + images/), e.g. to use a full-memory
|
| 2 |
+
run as the donor pool of a mismatched-memory run without re-running (and re-paying for) it."""
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
from .context import AttemptRecord, StepRecord
|
| 7 |
+
from .images import ImageRef
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def load_events(run_dir):
|
| 11 |
+
with open(os.path.join(run_dir, "events.jsonl")) as f:
|
| 12 |
+
return [json.loads(line) for line in f if line.strip()]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def load_records(run_dir, task=None, feedback="F2"):
|
| 16 |
+
"""{seed: [AttemptRecord]} with keyframes loaded from disk. Feedback text is re-rendered at the
|
| 17 |
+
requested level with task.feedback() when a task is given (else the logged F2 text / '')."""
|
| 18 |
+
ev = load_events(run_dir)
|
| 19 |
+
insts, steps, out = {}, {}, {}
|
| 20 |
+
for e in ev:
|
| 21 |
+
t = e["type"]
|
| 22 |
+
if t == "run_start":
|
| 23 |
+
insts[e["seed"]] = e["inst"]
|
| 24 |
+
out[e["seed"]] = []
|
| 25 |
+
elif t == "tool_call":
|
| 26 |
+
steps.setdefault((e["seed"], e["attempt"]), []).append(
|
| 27 |
+
StepRecord(step=e["step"], name=e["name"], args=e["args"], report=e["report"], ok=e["ok"]))
|
| 28 |
+
elif t == "attempt_end":
|
| 29 |
+
seed, a = e["seed"], e["attempt"]
|
| 30 |
+
kfs = []
|
| 31 |
+
for cap, rel in e.get("keyframes") or []:
|
| 32 |
+
p = os.path.join(run_dir, rel)
|
| 33 |
+
with open(p, "rb") as f:
|
| 34 |
+
kfs.append((cap, ImageRef(camera="agentview", path=p, jpeg=f.read())))
|
| 35 |
+
o = e["outcome"]
|
| 36 |
+
if task is not None:
|
| 37 |
+
fb = task.feedback(insts.get(seed, {}), o, feedback)
|
| 38 |
+
else:
|
| 39 |
+
fb = {"F0": "", "F1": "Attempt succeeded." if e["success"] else "Attempt failed."}.get(
|
| 40 |
+
feedback, e.get("feedback_f2", ""))
|
| 41 |
+
out.setdefault(seed, []).append(AttemptRecord(
|
| 42 |
+
seed=seed, attempt=a, steps=steps.get((seed, a), []), keyframes=kfs, outcome=o,
|
| 43 |
+
success=bool(e["success"]), feedback=fb, done_reason=e.get("done_reason"),
|
| 44 |
+
diagnosis=e.get("diagnosis"), ended_by=e.get("ended_by", ""), backend_meta=e.get("backend_meta") or {}))
|
| 45 |
+
return out
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def derange(target_seeds, donor_seeds):
|
| 49 |
+
"""Map each target seed to a donor seed != itself (cyclic shift over the sorted donor pool)."""
|
| 50 |
+
pool = sorted(donor_seeds)
|
| 51 |
+
if not pool:
|
| 52 |
+
raise ValueError("empty donor pool")
|
| 53 |
+
m = {}
|
| 54 |
+
for i, s in enumerate(sorted(target_seeds)):
|
| 55 |
+
j = (pool.index(s) + 1) % len(pool) if s in pool else i % len(pool)
|
| 56 |
+
if pool[j] == s:
|
| 57 |
+
raise ValueError(f"cannot find a donor different from seed {s} (pool {pool})")
|
| 58 |
+
m[s] = pool[j]
|
| 59 |
+
return m
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/robot_server.py
ADDED
|
@@ -0,0 +1,966 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Robot server for driving an LFF-Bench task from an isolated agent (e.g. a Claude Code subagent).
|
| 2 |
+
|
| 3 |
+
The server owns the simulator, the task instance and its hidden variables. The agent only gets a
|
| 4 |
+
sandbox directory containing a tiny `robot` CLI (talks to this server over localhost HTTP), a README
|
| 5 |
+
with the instructions, and the observation images the server writes into `<sandbox>/obs/`.
|
| 6 |
+
Nothing about the benchmark (code paths, hidden variables, success rule, scripted policies) is ever
|
| 7 |
+
written into the sandbox.
|
| 8 |
+
|
| 9 |
+
Attempt protocol (same semantics as harness.py):
|
| 10 |
+
cross `done` -> outcome is measured; if failed and attempts remain, the scene is reset to the same
|
| 11 |
+
initial state + hidden variables and the next attempt starts.
|
| 12 |
+
within `done` -> outcome is measured; if failed and done-calls remain, continue from the current state.
|
| 13 |
+
memory=none: every attempt is meant for a fresh agent; after `done` the server tells the agent to stop
|
| 14 |
+
(no feedback) and waits for the orchestrator to start a new agent (`./robot status` shows the state).
|
| 15 |
+
|
| 16 |
+
Run: python -m lffbench.agent.robot_server --task l5_slide_to_target --seed 1001 --sandbox <dir> --port 8765
|
| 17 |
+
"""
|
| 18 |
+
import argparse
|
| 19 |
+
import importlib
|
| 20 |
+
import json
|
| 21 |
+
import os
|
| 22 |
+
import pkgutil
|
| 23 |
+
import shutil
|
| 24 |
+
import sys
|
| 25 |
+
import time
|
| 26 |
+
import traceback
|
| 27 |
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
| 28 |
+
import signal
|
| 29 |
+
import textwrap
|
| 30 |
+
|
| 31 |
+
import numpy as np
|
| 32 |
+
|
| 33 |
+
from .. import tasks as task_pkg
|
| 34 |
+
from ..task_base import TASKS
|
| 35 |
+
from . import camera as C
|
| 36 |
+
from .context import PromptBuilder
|
| 37 |
+
from .tools import ACTION_TOOLS, WS_HI, WS_LO, ToolExecutor, _json_default
|
| 38 |
+
|
| 39 |
+
for _m in pkgutil.iter_modules(task_pkg.__path__):
|
| 40 |
+
importlib.import_module(f"lffbench.tasks.{_m.name}")
|
| 41 |
+
|
| 42 |
+
LFF_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 43 |
+
|
| 44 |
+
SHELL_TEMPLATE = r'''#!/bin/bash
|
| 45 |
+
# Run a shell command inside this workspace, in the episode jail (no network, host data hidden):
|
| 46 |
+
# ./shell '<command>' or ./shell <<'EOF' ... EOF (command read from stdin)
|
| 47 |
+
WS="$(cd "$(dirname "$0")" && pwd)"
|
| 48 |
+
if [ $# -gt 0 ]; then CMD="$*"; else CMD="$(cat)"; fi
|
| 49 |
+
exec unshare --user --map-root-user --mount --net -- /opt/lffjail/jail_inner.sh "$WS" timeout -k 5 60 bash -c "$CMD"
|
| 50 |
+
'''
|
| 51 |
+
|
| 52 |
+
CLI_TEMPLATE = r'''#!/usr/bin/env python3
|
| 53 |
+
"""Robot command-line interface. Usage: ./robot <command> [key=value ...] (./robot help)"""
|
| 54 |
+
import json, sys, urllib.request
|
| 55 |
+
PORT = __PORT__
|
| 56 |
+
TOKEN = "__TOKEN__"
|
| 57 |
+
def main():
|
| 58 |
+
if len(sys.argv) < 2:
|
| 59 |
+
sys.argv.append("help")
|
| 60 |
+
cmd, args = sys.argv[1], {}
|
| 61 |
+
for a in sys.argv[2:]:
|
| 62 |
+
if "=" not in a:
|
| 63 |
+
print(f"bad argument {a!r}: use key=value"); sys.exit(2)
|
| 64 |
+
k, v = a.split("=", 1)
|
| 65 |
+
try:
|
| 66 |
+
args[k] = json.loads(v)
|
| 67 |
+
except ValueError:
|
| 68 |
+
args[k] = v
|
| 69 |
+
req = urllib.request.Request(f"http://127.0.0.1:{PORT}/call", data=json.dumps({"cmd": cmd, "args": args}).encode(),
|
| 70 |
+
headers={"Content-Type": "application/json", "X-Token": TOKEN})
|
| 71 |
+
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
| 72 |
+
with opener.open(req, timeout=600) as r:
|
| 73 |
+
print(r.read().decode())
|
| 74 |
+
main()
|
| 75 |
+
'''
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def strip_axes(text):
|
| 79 |
+
"""v2: keep the robot-centric words of the F2 feedback ("to the robot's left", "forward") but drop the explicit
|
| 80 |
+
coordinate-axis labels ("(+y)", "+x, ", "+yaw"), so the feedback does not hand over the axis convention that the
|
| 81 |
+
v2 instructions deliberately leave out."""
|
| 82 |
+
import re
|
| 83 |
+
t = re.sub(r"\s?\((?:[+-]?[xyz]|[+-]yaw)\)", "", text) # " (+y)", " (x)", " (-yaw)"
|
| 84 |
+
t = re.sub(r"\(([+-][xyz]|[+-]yaw), ", "(", t) # "(+x, away from the robot)"
|
| 85 |
+
t = re.sub(r", [+-](?:[xyz]|yaw)\)", ")", t) # "(... robot's left, +yaw)"
|
| 86 |
+
t = re.sub(r"\s{2,}", " ", t)
|
| 87 |
+
return t
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class VideoRec:
|
| 91 |
+
"""Records agentview | wrist while the simulator steps (one frame every `every` control steps, played at
|
| 92 |
+
`fps`, i.e. sped up by every * fps / 20). A header shows the attempt, the current robot command and the
|
| 93 |
+
report of the previous one; gripper commands and attempt outcomes get short freeze frames."""
|
| 94 |
+
|
| 95 |
+
BAND = 56
|
| 96 |
+
|
| 97 |
+
def __init__(self, path, env, res=320, every=3, fps=20, title=""):
|
| 98 |
+
import imageio
|
| 99 |
+
from . import camera as _C
|
| 100 |
+
self.env, self.res, self.every, self.fps, self.title = env, res, every, fps, title
|
| 101 |
+
self.cams = [_C.mj_cam("agentview"), _C.mj_cam("wrist")]
|
| 102 |
+
self.w = imageio.get_writer(path, fps=fps, quality=7, macro_block_size=8)
|
| 103 |
+
self.n = 0
|
| 104 |
+
self.lines = ["", "", ""]
|
| 105 |
+
self.last = None
|
| 106 |
+
orig = env.step
|
| 107 |
+
|
| 108 |
+
def step(a):
|
| 109 |
+
out = orig(a)
|
| 110 |
+
self.n += 1
|
| 111 |
+
if self.w is not None and self.n % self.every == 0:
|
| 112 |
+
self.grab()
|
| 113 |
+
return out
|
| 114 |
+
|
| 115 |
+
env.step = step
|
| 116 |
+
|
| 117 |
+
def _font(self, size):
|
| 118 |
+
from PIL import ImageFont
|
| 119 |
+
try:
|
| 120 |
+
return ImageFont.load_default(size=size)
|
| 121 |
+
except TypeError:
|
| 122 |
+
return ImageFont.load_default()
|
| 123 |
+
|
| 124 |
+
def grab(self):
|
| 125 |
+
from PIL import Image, ImageDraw
|
| 126 |
+
from .. import envs as _E
|
| 127 |
+
img = np.concatenate([_E.render(self.env, c, self.res) for c in self.cams], axis=1)
|
| 128 |
+
im = Image.new("RGB", (2 * self.res, self.res + self.BAND), (0, 0, 0))
|
| 129 |
+
im.paste(Image.fromarray(img), (0, self.BAND))
|
| 130 |
+
d = ImageDraw.Draw(im)
|
| 131 |
+
hdr = [self.title] + self.lines[:2]
|
| 132 |
+
for i, s_ in enumerate(hdr):
|
| 133 |
+
d.text((5, 3 + 17 * i), s_[:120], fill=(255, 255, 255) if i else (255, 220, 120), font=self._font(13))
|
| 134 |
+
self.last = np.asarray(im)
|
| 135 |
+
self.w.append_data(self.last)
|
| 136 |
+
|
| 137 |
+
def hold(self, secs):
|
| 138 |
+
if self.w is None:
|
| 139 |
+
return
|
| 140 |
+
self.grab()
|
| 141 |
+
for _ in range(int(secs * self.fps)):
|
| 142 |
+
self.w.append_data(self.last)
|
| 143 |
+
|
| 144 |
+
def card(self, lines, secs=3.0, color=(20, 20, 20)):
|
| 145 |
+
if self.w is None:
|
| 146 |
+
return
|
| 147 |
+
from PIL import Image, ImageDraw
|
| 148 |
+
im = Image.new("RGB", (2 * self.res, self.res + self.BAND), color)
|
| 149 |
+
d = ImageDraw.Draw(im)
|
| 150 |
+
y = 14
|
| 151 |
+
for s_ in lines:
|
| 152 |
+
for part in textwrap.wrap(s_, 62) or [""]:
|
| 153 |
+
d.text((14, y), part, fill=(255, 255, 255), font=self._font(15))
|
| 154 |
+
y += 19
|
| 155 |
+
y += 5
|
| 156 |
+
fr = np.asarray(im)
|
| 157 |
+
for _ in range(int(secs * self.fps)):
|
| 158 |
+
self.w.append_data(fr)
|
| 159 |
+
|
| 160 |
+
def close(self):
|
| 161 |
+
if self.w is not None:
|
| 162 |
+
self.w.close()
|
| 163 |
+
self.w = None
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def _short(rep):
|
| 167 |
+
keys = ("touched_object", "holding_object", "gripper_width_m", "eef_pos", "eef_yaw_deg", "error")
|
| 168 |
+
return ", ".join(f"{k}={rep[k]}" for k in keys if k in rep)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class RobotSession:
|
| 172 |
+
def __init__(self, a):
|
| 173 |
+
self.a = a
|
| 174 |
+
self.task = TASKS[a.task](cam_res=a.image_res)
|
| 175 |
+
if a.max_steps is None: # long procedural tasks declare a larger per-attempt budget
|
| 176 |
+
a.max_steps = int(getattr(self.task, "agent_max_steps", 40))
|
| 177 |
+
self.inst = self.task.sample_instance(a.seed)
|
| 178 |
+
if getattr(a, "nominal", False):
|
| 179 |
+
# control condition: same scene, hidden calibration error removed (L1 tasks only) -> plain pick-and-place
|
| 180 |
+
hidden = [k for k in ("bias", "yaw_bias") if k in self.inst]
|
| 181 |
+
if not hidden:
|
| 182 |
+
raise SystemExit(f"--nominal is not supported for {a.task} (no bias / yaw_bias in the instance)")
|
| 183 |
+
for k in [k for k in self.inst if "bias" in k]: # bias, bias_r, yaw_bias, yaw_bias_deg, ...
|
| 184 |
+
v = self.inst[k]
|
| 185 |
+
if isinstance(v, (list, tuple)):
|
| 186 |
+
self.inst[k] = [0.0] * len(v)
|
| 187 |
+
elif isinstance(v, (int, float)):
|
| 188 |
+
self.inst[k] = 0.0
|
| 189 |
+
self.inst["nominal"] = True
|
| 190 |
+
# full5 controlled arms (docs/14 §6): h0 / twin override the hidden variable, hplus states it in the instruction
|
| 191 |
+
self.arm, self.arm_overrides, self.reveal_text = getattr(a, "arm", "none") or "none", {}, ""
|
| 192 |
+
if self.arm in ("h0", "twin"):
|
| 193 |
+
from .. import arm_specs
|
| 194 |
+
self.arm_overrides = arm_specs.overrides(a.task, self.arm, self.inst)
|
| 195 |
+
self.inst.update(self.arm_overrides)
|
| 196 |
+
elif self.arm == "hplus":
|
| 197 |
+
from .. import arm_specs
|
| 198 |
+
self.reveal_text = arm_specs.reveal(a.task, self.inst).strip()
|
| 199 |
+
if a.style in ("v2", "la"): # same rule as the F2 feedback: no axis labels such as "(+y)"
|
| 200 |
+
self.reveal_text = strip_axes(self.reveal_text)
|
| 201 |
+
self.n_mon_events = 0 # regression snapshots: monitor events already inspected
|
| 202 |
+
self.protocol = getattr(self.task, "protocol", "cross")
|
| 203 |
+
self.k = a.k or self.task.max_attempts
|
| 204 |
+
# --hide-k (memory=full): README and status say 1 attempt, exactly like an independent k=1 run, and the other
|
| 205 |
+
# attempts are announced only after a failure, so attempt 1 sees the same thing as the independent run.
|
| 206 |
+
self.k_shown = 1 if getattr(a, "hide_k", False) and a.memory == "full" else self.k
|
| 207 |
+
assert self.k_shown == self.k or a.style in ("v2", "la"), "--hide-k needs --style v2 or la"
|
| 208 |
+
self.sandbox = os.path.abspath(a.sandbox)
|
| 209 |
+
self.obs_dir = os.path.join(self.sandbox, "obs")
|
| 210 |
+
self.log_dir = os.path.abspath(a.log_dir)
|
| 211 |
+
os.makedirs(self.obs_dir, exist_ok=True)
|
| 212 |
+
os.makedirs(os.path.join(self.log_dir, "images"), exist_ok=True)
|
| 213 |
+
self.events = open(os.path.join(self.log_dir, "events.jsonl"), "a")
|
| 214 |
+
import secrets
|
| 215 |
+
self.token = secrets.token_hex(8)
|
| 216 |
+
self.n_actions = 0 # robot commands in the current attempt (step budget)
|
| 217 |
+
self.attempt = 1
|
| 218 |
+
self.step = 0
|
| 219 |
+
self.finished = False
|
| 220 |
+
self.waiting_new_agent = False
|
| 221 |
+
self.history = []
|
| 222 |
+
self.last_send = None
|
| 223 |
+
cam_axes = {c: C.describe_axes(self.task.env, c, a.image_res) for c in C.CAMERAS}
|
| 224 |
+
names = getattr(self.task, "agent_object_names", None) or list(self.task.env.objects_dict)
|
| 225 |
+
memory = "none" if a.memory == "none" else "full"
|
| 226 |
+
self.pb = PromptBuilder(self.task, self.protocol, self.k, memory, a.feedback, a.image_res, cam_axes,
|
| 227 |
+
object_names=names, cams=("agentview", "wrist"), depth_tool=a.perception == "depth")
|
| 228 |
+
self.video = None
|
| 229 |
+
if a.video:
|
| 230 |
+
self.video = VideoRec(a.video, self.task.env, every=a.video_every, fps=a.video_fps,
|
| 231 |
+
title=f"{a.task} seed={a.seed} perception={a.perception} (sped up x{a.video_every * a.video_fps // 20})")
|
| 232 |
+
self.video.card([f"Task: {a.task} seed {a.seed} memory={a.memory} feedback={a.feedback} k={self.k}",
|
| 233 |
+
"Instruction: " + self.instruction(),
|
| 234 |
+
"Left: agentview Right: wrist camera. Header: current robot command and the report of "
|
| 235 |
+
"the previous one."], 3)
|
| 236 |
+
self._start_attempt(reset=True)
|
| 237 |
+
# la: agent-facing positions are in the robot-base frame (LIBERO-Agent: "Coordinates are expressed in the
|
| 238 |
+
# robot-base frame and measured in metres"); the LIBERO base is axis-aligned with the world, so a translation
|
| 239 |
+
self.base_off = np.zeros(3)
|
| 240 |
+
if a.style == "la":
|
| 241 |
+
sim = self.task.env.sim
|
| 242 |
+
bid = sim.model.body_name2id("robot0_base")
|
| 243 |
+
assert np.allclose(sim.data.body_xmat[bid].reshape(3, 3), np.eye(3), atol=1e-6), "robot base is rotated"
|
| 244 |
+
self.base_off = np.array(sim.data.body_xpos[bid], float).copy()
|
| 245 |
+
self._write_sandbox()
|
| 246 |
+
self.log(dict(ev="session_start", task=a.task, seed=a.seed, k=self.k, k_shown=self.k_shown, protocol=self.protocol,
|
| 247 |
+
memory=a.memory, feedback=a.feedback, instruction=a.instruction, perception=a.perception,
|
| 248 |
+
inst={k: v for k, v in self.inst.items() if not k.startswith("_")}, arm=self.arm,
|
| 249 |
+
arm_overrides=self.arm_overrides, reveal=self.reveal_text, dossier=getattr(a, "dossier", "") or ""))
|
| 250 |
+
|
| 251 |
+
# ------------------------------------------------------------------ helpers
|
| 252 |
+
def log(self, d):
|
| 253 |
+
d["t"] = time.time()
|
| 254 |
+
self.events.write(json.dumps(d, default=_json_default) + "\n")
|
| 255 |
+
self.events.flush()
|
| 256 |
+
|
| 257 |
+
def instruction(self):
|
| 258 |
+
hook = getattr(self.task, "agent_instruction", None)
|
| 259 |
+
if hook is not None:
|
| 260 |
+
text = hook(self.inst, self.a.instruction)
|
| 261 |
+
elif self.a.instruction == "indirect" and getattr(self.task, "instruction_indirect", ""):
|
| 262 |
+
text = self.task.instruction_indirect
|
| 263 |
+
else:
|
| 264 |
+
text = self.task.instruction
|
| 265 |
+
return text + (" " + self.reveal_text if getattr(self, "reveal_text", "") else "")
|
| 266 |
+
|
| 267 |
+
def feedback_text(self, out):
|
| 268 |
+
import inspect
|
| 269 |
+
fn = self.task.feedback
|
| 270 |
+
if "indirect" in inspect.signature(fn).parameters:
|
| 271 |
+
fb = fn(self.inst, out, self.a.feedback, indirect=self.a.instruction == "indirect")
|
| 272 |
+
else:
|
| 273 |
+
fb = fn(self.inst, out, self.a.feedback)
|
| 274 |
+
return strip_axes(fb) if self.a.style in ("v2", "la") else fb
|
| 275 |
+
|
| 276 |
+
def _start_attempt(self, reset):
|
| 277 |
+
self.n_actions = 0
|
| 278 |
+
if reset:
|
| 279 |
+
self.task.reset_instance(self.inst)
|
| 280 |
+
self.ex = ToolExecutor(self.task, self.inst, image_res=self.a.image_res, cams=("agentview", "wrist"))
|
| 281 |
+
self.step = 0
|
| 282 |
+
self.sim0 = self.task.sk.n_steps # v2: simulated-time budget is counted per attempt
|
| 283 |
+
|
| 284 |
+
def _save_obs(self, tag):
|
| 285 |
+
"""Same bytes as the GPT harness sends (JPEG q90). Under memory=none the file names carry no
|
| 286 |
+
attempt number, so a fresh agent cannot tell it is a retry; --hide-k names attempt 1 the same way."""
|
| 287 |
+
from PIL import Image
|
| 288 |
+
paths = []
|
| 289 |
+
for ref in self.ex.observe(label=tag):
|
| 290 |
+
name = (f"s{self.step:03d}_{ref.camera}.jpg" if self.a.memory == "none" or (self.k_shown < self.k and self.attempt == 1)
|
| 291 |
+
else f"a{self.attempt}_s{self.step:03d}_{ref.camera}.jpg")
|
| 292 |
+
Image.fromarray(ref.array).save(os.path.join(self.obs_dir, name), quality=90)
|
| 293 |
+
shutil.copy(os.path.join(self.obs_dir, name), os.path.join(self.log_dir, "images", f"a{self.attempt}_{name}"))
|
| 294 |
+
paths.append(f"obs/{name}")
|
| 295 |
+
if self.a.style == "la":
|
| 296 |
+
self.last_files = self._write_la_files(f"a{self.attempt}_s{self.step:03d}")
|
| 297 |
+
return paths
|
| 298 |
+
|
| 299 |
+
def readme(self):
|
| 300 |
+
if self.a.style == "la":
|
| 301 |
+
return self.readme_la()
|
| 302 |
+
if self.a.style == "v2":
|
| 303 |
+
return self.readme_v2()
|
| 304 |
+
sp = self.pb.system_prompt()
|
| 305 |
+
sp = sp.replace("You act only by calling the provided tools, exactly one tool call per turn. Every action tool "
|
| 306 |
+
"returns an execution report; after each action you also receive new camera images and the "
|
| 307 |
+
"robot's proprioceptive state.",
|
| 308 |
+
"You act only through the `./robot` command in this directory (one robot command at a time). "
|
| 309 |
+
"Every action command prints an execution report and the paths of new camera images taken "
|
| 310 |
+
"after the action; look at them with your file-reading tool.")
|
| 311 |
+
sp = sp.replace("Finish by calling done(reason)", "Finish by running `./robot done reason=\"...\"`")
|
| 312 |
+
sp = sp.replace("Each attempt ends when you call done; you will then see a summary of the attempt (key images, the "
|
| 313 |
+
"actions you executed and outcome feedback).",
|
| 314 |
+
"Each attempt ends when you run `./robot done`; that command prints the outcome feedback (if any) "
|
| 315 |
+
"and the images of the reset scene for the next attempt.")
|
| 316 |
+
sp = sp.replace("Each attempt ends when you call done; you will then see a summary of the attempt (key images, the "
|
| 317 |
+
"actions you executed).",
|
| 318 |
+
"Each attempt ends when you run `./robot done`; that command prints the images of the reset "
|
| 319 |
+
"scene for the next attempt.")
|
| 320 |
+
sp = sp.replace("before your first tool call", "before your first robot command")
|
| 321 |
+
tools = "\n".join([
|
| 322 |
+
" ./robot help this text",
|
| 323 |
+
" ./robot status task, current images and proprioception",
|
| 324 |
+
" ./robot observe take new images (agentview + wrist) + proprioception",
|
| 325 |
+
" ./robot move_to x=.. y=.. z=.. yaw=.. [speed=..] yaw in degrees; speed m/s (omit = fastest)",
|
| 326 |
+
" ./robot open_gripper | ./robot close_gripper",
|
| 327 |
+
" ./robot pixel_to_world camera=agentview|wrist u=.. v=.. (pixel -> 3-D point via depth)",
|
| 328 |
+
" ./robot done reason=\"...\" end the attempt / segment",
|
| 329 |
+
] if self.a.perception == "depth" else [
|
| 330 |
+
" ./robot help this text",
|
| 331 |
+
" ./robot status task, current images and proprioception",
|
| 332 |
+
" ./robot observe take new images (agentview + wrist) + proprioception",
|
| 333 |
+
" ./robot move_to x=.. y=.. z=.. yaw=.. [speed=..] yaw in degrees; speed m/s (omit = fastest)",
|
| 334 |
+
" ./robot open_gripper | ./robot close_gripper",
|
| 335 |
+
" ./robot done reason=\"...\" end the attempt / segment",
|
| 336 |
+
])
|
| 337 |
+
return ("# Robot task\n\n" + sp + "\n\n## Commands\n" + tools +
|
| 338 |
+
"\n\nArguments are key=value; numbers are plain (e.g. x=0.12). Quote strings with spaces.\n"
|
| 339 |
+
"Images are written to obs/ inside this directory. After every action, look at the new images "
|
| 340 |
+
"before deciding on the next command.\n"
|
| 341 |
+
f"Each attempt allows at most {self.a.max_steps} robot commands (help/status not counted); after that "
|
| 342 |
+
"the attempt ends automatically.\n\n## TASK\n" + self.instruction() + "\n")
|
| 343 |
+
|
| 344 |
+
def _write_sandbox(self):
|
| 345 |
+
os.makedirs(self.sandbox, exist_ok=True)
|
| 346 |
+
if self.a.style == "la":
|
| 347 |
+
with open(os.path.join(self.log_dir, "agent_iface.json"), "w") as f:
|
| 348 |
+
json.dump(dict(token=self.token, port=self.a.port, workspace=self.sandbox, agent_iface=self.a.agent_iface,
|
| 349 |
+
max_tool_calls=self.a.max_tool_calls, perception=self.a.perception), f)
|
| 350 |
+
with open(os.path.join(self.sandbox, "README.md"), "w") as f:
|
| 351 |
+
f.write(self.readme())
|
| 352 |
+
if getattr(self.a, "dossier", ""):
|
| 353 |
+
shutil.copytree(self.a.dossier, os.path.join(self.sandbox, "history"))
|
| 354 |
+
if self.a.agent_iface == "cli": # coding-agent harness (Claude Code): ./robot + ./shell in the workspace
|
| 355 |
+
for name, body in (("robot", CLI_TEMPLATE.replace("__PORT__", str(self.a.port)).replace("__TOKEN__", self.token)),
|
| 356 |
+
("shell", SHELL_TEMPLATE)):
|
| 357 |
+
with open(os.path.join(self.sandbox, name), "w") as f:
|
| 358 |
+
f.write(body)
|
| 359 |
+
os.chmod(os.path.join(self.sandbox, name), 0o755)
|
| 360 |
+
return
|
| 361 |
+
cli = os.path.join(self.sandbox, "robot")
|
| 362 |
+
with open(cli, "w") as f:
|
| 363 |
+
f.write(CLI_TEMPLATE.replace("__PORT__", str(self.a.port)).replace("__TOKEN__", self.token))
|
| 364 |
+
os.chmod(cli, 0o755)
|
| 365 |
+
with open(os.path.join(self.sandbox, "README.md"), "w") as f:
|
| 366 |
+
f.write(self.readme())
|
| 367 |
+
|
| 368 |
+
def status(self):
|
| 369 |
+
if self.a.memory == "none":
|
| 370 |
+
return dict(task=self.instruction(), finished=self.finished)
|
| 371 |
+
st = dict(task=self.instruction(), protocol=self.protocol, attempt=self.attempt, max_attempts=self.k,
|
| 372 |
+
finished=self.finished)
|
| 373 |
+
if self.waiting_new_agent:
|
| 374 |
+
st["note"] = "The previous agent finished its attempt. A new attempt is ready; the scene has been reset."
|
| 375 |
+
return st
|
| 376 |
+
|
| 377 |
+
# ------------------------------------------------------------------ dispatch
|
| 378 |
+
def handle(self, cmd, args):
|
| 379 |
+
if self.a.style in ("v2", "la"):
|
| 380 |
+
return self.handle_v2(cmd, args)
|
| 381 |
+
if cmd == "help":
|
| 382 |
+
return dict(text=self.readme())
|
| 383 |
+
if cmd == "status":
|
| 384 |
+
st = self.status()
|
| 385 |
+
st["images"] = self._save_obs("status")
|
| 386 |
+
st.update(self.ex.proprio())
|
| 387 |
+
self.waiting_new_agent = False
|
| 388 |
+
return st
|
| 389 |
+
if self.finished:
|
| 390 |
+
return dict(ok=False, error="The episode is over. Stop now.")
|
| 391 |
+
if self.waiting_new_agent:
|
| 392 |
+
return dict(ok=False, error="This attempt has ended. Stop now.")
|
| 393 |
+
if cmd in ("observe", "pixel_to_world", "move_to", "open_gripper", "close_gripper", "push"):
|
| 394 |
+
self.n_actions += 1
|
| 395 |
+
if self.n_actions > self.a.max_steps:
|
| 396 |
+
rep = self._done("step budget exhausted (automatic)")
|
| 397 |
+
rep["note"] = f"The step budget of {self.a.max_steps} commands for this attempt was used up."
|
| 398 |
+
return rep
|
| 399 |
+
if cmd == "observe":
|
| 400 |
+
self.step += 1
|
| 401 |
+
rep = dict(ok=True, images=self._save_obs("observe"))
|
| 402 |
+
rep.update(self.ex.proprio())
|
| 403 |
+
self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
|
| 404 |
+
return rep
|
| 405 |
+
if cmd == "done":
|
| 406 |
+
return self._done(args.get("reason", ""))
|
| 407 |
+
allowed = tuple(t for t in ACTION_TOOLS if t != "push" or self.a.allow_push)
|
| 408 |
+
if self.a.perception == "depth":
|
| 409 |
+
allowed += ("pixel_to_world",)
|
| 410 |
+
if cmd not in allowed:
|
| 411 |
+
return dict(ok=False, error=f"unknown command {cmd!r}; run ./robot help")
|
| 412 |
+
self.step += 1
|
| 413 |
+
if self.video is not None:
|
| 414 |
+
argtxt = " ".join(f"{k}={v}" for k, v in args.items())
|
| 415 |
+
self.video.lines[0] = f"attempt {self.attempt}/{self.k} command #{self.n_actions}: {cmd} {argtxt}"
|
| 416 |
+
res = self.ex.call(cmd, args)
|
| 417 |
+
rep = dict(res.report)
|
| 418 |
+
if self.video is not None:
|
| 419 |
+
self.video.lines[1] = f" -> {_short(rep)}"
|
| 420 |
+
if cmd in ("close_gripper", "open_gripper"):
|
| 421 |
+
self.video.hold(1.2)
|
| 422 |
+
if res.ok and cmd in ACTION_TOOLS:
|
| 423 |
+
rep["images"] = self._save_obs(cmd)
|
| 424 |
+
self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep,
|
| 425 |
+
wall_s=res.wall_s, sim_steps=res.sim_steps))
|
| 426 |
+
return rep
|
| 427 |
+
|
| 428 |
+
def _done(self, reason):
|
| 429 |
+
out = self.task.outcome(self.inst)
|
| 430 |
+
succ = bool(out["success"])
|
| 431 |
+
fb = self.feedback_text(out)
|
| 432 |
+
self.history.append(dict(attempt=self.attempt, success=succ, feedback=fb, reason=reason))
|
| 433 |
+
self.log(dict(ev="done", attempt=self.attempt, step=self.step, reason=reason, success=succ, feedback=fb,
|
| 434 |
+
outcome={k: v for k, v in out.items() if k != "feedback"}))
|
| 435 |
+
last = self.attempt >= self.k or succ or bool(out.get("terminal"))
|
| 436 |
+
if self.video is not None:
|
| 437 |
+
self.video.lines = [f"attempt {self.attempt}/{self.k}: done", f" reason: {reason}", ""]
|
| 438 |
+
self.video.hold(1.0)
|
| 439 |
+
self.video.card([f"Attempt {self.attempt}: {'SUCCESS' if succ else 'FAILED'}",
|
| 440 |
+
f"Commands used in this attempt: {self.n_actions}", "Agent's reason: " + str(reason)[:300],
|
| 441 |
+
"Feedback: " + (fb if self.a.memory != "none" and self.a.feedback != "F0" else "(not shown)")],
|
| 442 |
+
3.5, (20, 50, 20) if succ else (60, 20, 20))
|
| 443 |
+
if last:
|
| 444 |
+
self.video.close()
|
| 445 |
+
else:
|
| 446 |
+
self.video.lines = ["", "", ""]
|
| 447 |
+
if self.a.memory == "none":
|
| 448 |
+
# independent attempts: no feedback to the agent; orchestrator starts a fresh agent
|
| 449 |
+
if last:
|
| 450 |
+
self.finished = True
|
| 451 |
+
else:
|
| 452 |
+
self.attempt += 1
|
| 453 |
+
self._start_attempt(reset=self.protocol == "cross")
|
| 454 |
+
self.waiting_new_agent = True
|
| 455 |
+
return dict(ok=True, ended=True, message="Attempt recorded. Stop now and report what you did.")
|
| 456 |
+
rep = dict(ok=True, ended=True)
|
| 457 |
+
if self.a.feedback != "F0":
|
| 458 |
+
rep["feedback"] = fb
|
| 459 |
+
if last and (succ or self.a.feedback != "F0"):
|
| 460 |
+
self.finished = True
|
| 461 |
+
rep["message"] = "The episode is over. Stop now and report."
|
| 462 |
+
return rep
|
| 463 |
+
if self.attempt >= self.k or out.get("terminal"):
|
| 464 |
+
self.finished = True
|
| 465 |
+
rep["message"] = ("The failure cannot be undone, so the episode is over. Stop now and report."
|
| 466 |
+
if out.get("terminal") else "No attempts left. The episode is over. Stop now and report.")
|
| 467 |
+
return rep
|
| 468 |
+
self.attempt += 1
|
| 469 |
+
reveal = ""
|
| 470 |
+
if self.k_shown < self.k: # --hide-k: first failure, announce the extra attempts now
|
| 471 |
+
self.k_shown = self.k
|
| 472 |
+
reveal = f"You get more attempts than README.md says: up to {self.k} in total. "
|
| 473 |
+
if self.protocol == "cross":
|
| 474 |
+
self._start_attempt(reset=True)
|
| 475 |
+
rep["message"] = reveal + (f"Attempt {self.attempt} of {self.k} starts now. The scene has been reset to exactly the "
|
| 476 |
+
f"same initial state.")
|
| 477 |
+
else:
|
| 478 |
+
self._start_attempt(reset=False)
|
| 479 |
+
rep["message"] = reveal + (f"Continue from the current state (segment {self.attempt}; you may call done at most "
|
| 480 |
+
f"{self.k} times in total).")
|
| 481 |
+
self.step += 1
|
| 482 |
+
rep["images"] = self._save_obs("attempt_start")
|
| 483 |
+
rep.update(self._la_files())
|
| 484 |
+
if self.a.style in ("v2", "la"):
|
| 485 |
+
rep.update(self._state_v2())
|
| 486 |
+
else:
|
| 487 |
+
rep.update(self.ex.proprio())
|
| 488 |
+
return rep
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
V2_DROP = ("holding", "touched", "events", "sim_time_s", "tool", "reached", "yaw_used_deg", "target_clipped_to")
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
class _V2:
|
| 495 |
+
"""Interface v2 (2026-10-07, aligned with LIBERO-Agent / RoboDojo-L3 at the user's request):
|
| 496 |
+
- priors: only the task instruction, the attempt rules, the budgets and the command definitions (no axes,
|
| 497 |
+
table height, camera orientation or robot geometry);
|
| 498 |
+
- observations: two RGB images published as files after every command + end-effector state (position,
|
| 499 |
+
yaw, gripper width) + how far the arm stopped from the commanded target + budget left; no
|
| 500 |
+
held/touched flags and no per-step task events;
|
| 501 |
+
- action: move_eef = absolute target (omitted coordinates keep their value; gripper after the motion;
|
| 502 |
+
optional speed); unreachable targets are rejected and the arm does not move;
|
| 503 |
+
- an attempt ends with `finish` (alias `done`) or when a budget runs out; the environment judges it."""
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
def _readme_v2(self):
|
| 507 |
+
sec = self.sim_budget()
|
| 508 |
+
proto = (f"You have up to {self.k_shown} attempts at this task. Before every attempt the scene is reset to exactly the "
|
| 509 |
+
f"same initial state." if self.protocol == "cross" else
|
| 510 |
+
f"Everything happens in one continuous scene. You may end an attempt up to {self.k_shown} times; after a "
|
| 511 |
+
f"failed attempt you continue from the current state.")
|
| 512 |
+
return "\n".join([
|
| 513 |
+
"# Robot task", "",
|
| 514 |
+
"You control a robot arm with a two-finger gripper in a physics simulation, only through the `./robot` "
|
| 515 |
+
"command in this directory (one command at a time).", "",
|
| 516 |
+
"## Task", self.instruction(), "",
|
| 517 |
+
"## Attempts", proto + " An attempt ends when you run `./robot finish reason=\"...\"` or when its budget "
|
| 518 |
+
"is used up. " + _fb_sentence(self.a.feedback) + " The episode ends at the first success or after the last "
|
| 519 |
+
"attempt.", "",
|
| 520 |
+
"## Budget (per attempt)",
|
| 521 |
+
f"- at most {self.a.max_steps} robot commands (status and help are free);",
|
| 522 |
+
f"- at most {sec:.0f} s of simulated robot motion.",
|
| 523 |
+
"Every reply shows what is left.", "",
|
| 524 |
+
"## Observations",
|
| 525 |
+
"Every command writes two new camera images into obs/ and prints their paths: 'agentview' (a fixed camera "
|
| 526 |
+
"looking at the table) and 'wrist' (a camera on the gripper). It also reports the end-effector state: "
|
| 527 |
+
"eef_pos = [x, y, z] of the gripper's grasp point in metres, eef_yaw_deg = rotation of the gripper about "
|
| 528 |
+
"the vertical axis in degrees, gripper_width_m = opening of the fingers in metres, and after a motion how "
|
| 529 |
+
"far the gripper stopped from your target.", "",
|
| 530 |
+
"## Commands",
|
| 531 |
+
" ./robot status task, attempt, budget, current state and images",
|
| 532 |
+
" ./robot observe new images and state without moving",
|
| 533 |
+
" ./robot move_eef [x=..] [y=..] [z=..] [yaw=..] [gripper=open|close] [speed=..]",
|
| 534 |
+
" move the grasp point to an absolute target in the same frame as eef_pos (metres; yaw in degrees);",
|
| 535 |
+
" omitted coordinates keep their current value; the gripper command is executed after the motion;",
|
| 536 |
+
" speed in m/s (omit = fastest); a target the arm cannot reach is rejected and the arm does not move.",
|
| 537 |
+
" ./robot finish reason=\"...\" end the current attempt",
|
| 538 |
+
"",
|
| 539 |
+
"Arguments are key=value; numbers are plain (e.g. x=0.12). Quote strings with spaces.", ""])
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def _sim_budget(self):
|
| 543 |
+
return 3.0 * self.a.max_steps # seconds of simulated motion per attempt
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
def _budget_left(self):
|
| 547 |
+
used = (self.task.sk.n_steps - self.sim0) * 0.05
|
| 548 |
+
return dict(commands=max(self.a.max_steps - self.n_actions, 0), sim_seconds=round(max(self.sim_budget() - used, 0.0), 1))
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
def _state_v2(self):
|
| 552 |
+
p = self.ex.proprio()
|
| 553 |
+
pos = p["eef_pos"]
|
| 554 |
+
if self.a.style == "la":
|
| 555 |
+
pos = [round(float(v), 4) for v in np.asarray(pos, float) - self.base_off]
|
| 556 |
+
st = dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"])
|
| 557 |
+
if self.a.style == "la": # read-only joint angles, as LIBERO-Agent (all levels) and RoboDojo give them
|
| 558 |
+
st["joint_pos_rad"] = [round(float(v), 4) for v in self._believed_joints()]
|
| 559 |
+
st["budget_left"] = self._budget_left()
|
| 560 |
+
return st
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
def _clean_v2(rep):
|
| 564 |
+
return {k: v for k, v in rep.items() if not k.startswith(V2_DROP)}
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
def _handle_v2(self, cmd, args):
|
| 568 |
+
if cmd == "help":
|
| 569 |
+
return dict(text=self.readme())
|
| 570 |
+
if cmd == "status":
|
| 571 |
+
st = dict(task=self.instruction(), attempt=self.attempt, max_attempts=self.k_shown, finished=self.finished)
|
| 572 |
+
st["images"] = self._save_obs("status")
|
| 573 |
+
st.update(self._la_files())
|
| 574 |
+
st.update(self._state_v2())
|
| 575 |
+
return st
|
| 576 |
+
if self.finished:
|
| 577 |
+
return dict(ok=False, error="The episode is over. Stop now.")
|
| 578 |
+
if cmd in ("finish", "done"):
|
| 579 |
+
return self._done(args.get("reason", ""))
|
| 580 |
+
if cmd not in ("observe", "move_eef"):
|
| 581 |
+
return dict(ok=False, error=f"unknown command {cmd!r}; run ./robot help")
|
| 582 |
+
self.n_actions += 1
|
| 583 |
+
if self.n_actions > self.a.max_steps:
|
| 584 |
+
rep = self._done("command budget used up (automatic)")
|
| 585 |
+
rep["note"] = f"The budget of {self.a.max_steps} commands for this attempt was used up."
|
| 586 |
+
return rep
|
| 587 |
+
self.step += 1
|
| 588 |
+
if cmd == "observe":
|
| 589 |
+
rep = dict(ok=True, images=self._save_obs("observe"))
|
| 590 |
+
rep.update(self._la_files())
|
| 591 |
+
rep.update(self._state_v2())
|
| 592 |
+
self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
|
| 593 |
+
return rep
|
| 594 |
+
# ---------------- move_eef
|
| 595 |
+
p = self.ex.proprio()
|
| 596 |
+
unknown = set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}
|
| 597 |
+
if unknown:
|
| 598 |
+
rep = dict(ok=False, error=f"unknown argument(s) {sorted(unknown)}; use x, y, z, yaw, gripper, speed")
|
| 599 |
+
self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
|
| 600 |
+
return rep
|
| 601 |
+
off = self.base_off # zero except la (robot-base frame)
|
| 602 |
+
try:
|
| 603 |
+
cur = np.asarray(p["eef_pos"], float) - off
|
| 604 |
+
tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
|
| 605 |
+
yaw = float(args.get("yaw", p["eef_yaw_deg"]))
|
| 606 |
+
speed = None if args.get("speed") in (None, "") else float(args["speed"])
|
| 607 |
+
except (TypeError, ValueError):
|
| 608 |
+
rep = dict(ok=False, error="x, y, z, yaw and speed must be numbers")
|
| 609 |
+
self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
|
| 610 |
+
return rep
|
| 611 |
+
grip = args.get("gripper")
|
| 612 |
+
if grip not in (None, "open", "close"):
|
| 613 |
+
rep = dict(ok=False, error="gripper must be open or close")
|
| 614 |
+
self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
|
| 615 |
+
return rep
|
| 616 |
+
moving = any(k in args for k in ("x", "y", "z", "yaw"))
|
| 617 |
+
tgt_w = np.asarray(tgt) + off # simulator (world) frame
|
| 618 |
+
if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)):
|
| 619 |
+
rep = dict(ok=False, error="target rejected: the arm cannot reach it; the arm did not move")
|
| 620 |
+
rep.update(self._state_v2())
|
| 621 |
+
self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
|
| 622 |
+
return rep
|
| 623 |
+
if self.video is not None:
|
| 624 |
+
argtxt = " ".join(f"{k}={v}" for k, v in args.items())
|
| 625 |
+
self.video.lines[0] = f"attempt {self.attempt}/{self.k} command #{self.n_actions}: {cmd} {argtxt}"
|
| 626 |
+
left = self._budget_left()["sim_seconds"]
|
| 627 |
+
raw = {}
|
| 628 |
+
if moving:
|
| 629 |
+
mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw)
|
| 630 |
+
if speed is not None:
|
| 631 |
+
mv["speed"] = speed
|
| 632 |
+
res = self.ex.call("move_to", mv)
|
| 633 |
+
raw.update(res.report)
|
| 634 |
+
if grip is not None:
|
| 635 |
+
res = self.ex.call("open_gripper" if grip == "open" else "close_gripper", {})
|
| 636 |
+
raw.update(res.report)
|
| 637 |
+
rep = dict(ok=bool(raw.get("ok", True)))
|
| 638 |
+
if raw.get("error"):
|
| 639 |
+
rep["error"] = raw["error"]
|
| 640 |
+
rep.update(self._state_v2())
|
| 641 |
+
if moving:
|
| 642 |
+
err = np.asarray(tgt) - np.asarray(rep["eef_pos"])
|
| 643 |
+
dyaw = (yaw - rep["eef_yaw_deg"] + 90.0) % 180.0 - 90.0
|
| 644 |
+
rep["stopped_from_target"] = dict(cm=round(100 * float(np.linalg.norm(err)), 1), deg=round(abs(dyaw), 1))
|
| 645 |
+
if self.video is not None:
|
| 646 |
+
self.video.lines[1] = f" -> eef={rep['eef_pos']} width={rep['gripper_width_m']} {rep.get('stopped_from_target', '')}"
|
| 647 |
+
if grip is not None:
|
| 648 |
+
self.video.hold(1.2)
|
| 649 |
+
rep["images"] = self._save_obs(cmd)
|
| 650 |
+
rep.update(self._la_files())
|
| 651 |
+
self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep, raw=raw))
|
| 652 |
+
self._snap_regressions()
|
| 653 |
+
if rep["budget_left"]["sim_seconds"] <= 0 and left > 0:
|
| 654 |
+
fin = self._done("motion budget used up (automatic)")
|
| 655 |
+
fin["note"] = f"The {self.sim_budget():.0f} s motion budget for this attempt was used up."
|
| 656 |
+
rep["attempt_ended"] = fin
|
| 657 |
+
return rep
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
LOSS_EVENTS = ("lost", "toppled", "tipped", "load_fell", "load_displaced")
|
| 661 |
+
|
| 662 |
+
|
| 663 |
+
def _snap_regressions(self):
|
| 664 |
+
"""Save the simulator state right after a command during which the task monitor registered a loss of earlier
|
| 665 |
+
progress (lost / toppled / tipped / load_fell ...), for the "self-inflicted vs handed-over" experiment (docs/14 §6).
|
| 666 |
+
Server-side only: snapshots go to <log>/snapshots/, never to the agent's workspace."""
|
| 667 |
+
try: # bookkeeping only: it must never change what the agent gets back
|
| 668 |
+
self._snap_regressions_inner()
|
| 669 |
+
except Exception:
|
| 670 |
+
self.log(dict(ev="snapshot_error", error=traceback.format_exc()[-1500:]))
|
| 671 |
+
|
| 672 |
+
|
| 673 |
+
def _snap_regressions_inner(self):
|
| 674 |
+
mon = getattr(self.task, "mon", None)
|
| 675 |
+
evs = mon.get("events") if isinstance(mon, dict) else None
|
| 676 |
+
if not isinstance(evs, list):
|
| 677 |
+
return
|
| 678 |
+
new = evs[self.n_mon_events:]
|
| 679 |
+
self.n_mon_events = len(evs)
|
| 680 |
+
loss = [e for e in new if isinstance(e, dict) and str(e.get("ev", e.get("event", ""))) in LOSS_EVENTS]
|
| 681 |
+
if not loss:
|
| 682 |
+
return
|
| 683 |
+
import copy
|
| 684 |
+
d = os.path.join(self.log_dir, "snapshots")
|
| 685 |
+
os.makedirs(d, exist_ok=True)
|
| 686 |
+
name = f"a{self.attempt}_s{self.step:03d}"
|
| 687 |
+
try:
|
| 688 |
+
flat = np.asarray(self.task.env.sim.get_state().flatten(), float)
|
| 689 |
+
except Exception: # keep the run going even if a simulator binding lacks get_state
|
| 690 |
+
flat = np.concatenate([self.task.env.sim.data.qpos, self.task.env.sim.data.qvel]).astype(float)
|
| 691 |
+
np.save(os.path.join(d, name + "_sim.npy"), flat)
|
| 692 |
+
meta = dict(attempt=self.attempt, step=self.step, n_actions=self.n_actions, sim_steps=int(self.task.sk.n_steps - self.sim0),
|
| 693 |
+
loss_events=loss, mon=copy.deepcopy(mon))
|
| 694 |
+
def _dflt(o): # task monitors keep sets (ever / lost / lid_hits ...)
|
| 695 |
+
return sorted(o, key=str) if isinstance(o, (set, frozenset)) else _json_default(o)
|
| 696 |
+
with open(os.path.join(d, name + "_meta.json"), "w") as f:
|
| 697 |
+
json.dump(meta, f, default=_dflt)
|
| 698 |
+
self.log(dict(ev="regression_snapshot", attempt=self.attempt, step=self.step, file=f"snapshots/{name}", n_loss=len(loss)))
|
| 699 |
+
|
| 700 |
+
|
| 701 |
+
def _la_files(self):
|
| 702 |
+
"""la: paths of the non-image observation files written with the last images (empty for other styles)."""
|
| 703 |
+
return dict(self.last_files) if self.a.style == "la" and getattr(self, "last_files", None) else {}
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
def _believed_pose(self):
|
| 707 |
+
"""4x4 pose of the grasp point as the ROBOT believes it (the frame of eef_pos / move_eef): the true pose shifted by
|
| 708 |
+
the task's hidden calibration errors (Skills.bias, and YawSkills.yaw_bias about the vertical axis). A real robot
|
| 709 |
+
computes its wrist-camera pose from its own (miscalibrated) kinematics, so the wrist calibration uses this pose."""
|
| 710 |
+
sk = self.task.sk
|
| 711 |
+
beta = float(getattr(sk, "yaw_bias", 0.0))
|
| 712 |
+
c, s_ = np.cos(-beta), np.sin(-beta)
|
| 713 |
+
Rz = np.array([[c, -s_, 0.0], [s_, c, 0.0], [0.0, 0.0, 1.0]])
|
| 714 |
+
T_true = np.eye(4)
|
| 715 |
+
T_true[:3, :3], T_true[:3, 3] = sk.eef_mat(), sk.eef_pos()
|
| 716 |
+
T_b = np.eye(4)
|
| 717 |
+
T_b[:3, :3], T_b[:3, 3] = Rz @ sk.eef_mat(), sk.eef_pos() - np.asarray(sk.bias, float)
|
| 718 |
+
return T_b, T_true
|
| 719 |
+
|
| 720 |
+
|
| 721 |
+
def _believed_joints(self, iters=30):
|
| 722 |
+
"""The 7 arm joint angles as the robot's encoders report them. For tasks with a hidden calibration error (L1) these
|
| 723 |
+
are the angles consistent with the robot's own belief: standard forward kinematics of them gives exactly the
|
| 724 |
+
reported (believed) grasp pose, as on a real arm whose encoder offsets are miscalibrated; true joint angles would
|
| 725 |
+
hand the hidden error to anyone who runs the public Franka kinematics. Without a calibration error they are the true
|
| 726 |
+
angles. Solved by damped least squares on a scratch copy of the simulator state (2-3 iterations)."""
|
| 727 |
+
import mujoco
|
| 728 |
+
env, sk = self.task.env, self.task.sk
|
| 729 |
+
rob = env.robots[0]
|
| 730 |
+
idx, dof, site = np.array(rob._ref_joint_pos_indexes), np.array(rob._ref_joint_vel_indexes), rob.eef_site_id
|
| 731 |
+
m, d0 = env.sim.model._model, env.sim.data._data
|
| 732 |
+
T_b, _ = self._believed_pose()
|
| 733 |
+
if np.allclose(T_b[:3, 3], d0.site_xpos[site]) and np.allclose(T_b[:3, :3], d0.site_xmat[site].reshape(3, 3)):
|
| 734 |
+
return d0.qpos[idx].copy()
|
| 735 |
+
d = mujoco.MjData(m)
|
| 736 |
+
d.qpos[:] = d0.qpos
|
| 737 |
+
jp, jr = np.zeros((3, m.nv)), np.zeros((3, m.nv))
|
| 738 |
+
for _ in range(iters):
|
| 739 |
+
mujoco.mj_kinematics(m, d)
|
| 740 |
+
mujoco.mj_comPos(m, d)
|
| 741 |
+
ep = T_b[:3, 3] - d.site_xpos[site]
|
| 742 |
+
Re = T_b[:3, :3] @ d.site_xmat[site].reshape(3, 3).T
|
| 743 |
+
er = 0.5 * np.array([Re[2, 1] - Re[1, 2], Re[0, 2] - Re[2, 0], Re[1, 0] - Re[0, 1]])
|
| 744 |
+
if np.linalg.norm(ep) < 1e-7 and np.linalg.norm(er) < 1e-7:
|
| 745 |
+
break
|
| 746 |
+
mujoco.mj_jacSite(m, d, jp, jr, site)
|
| 747 |
+
J = np.vstack([jp[:, dof], jr[:, dof]])
|
| 748 |
+
d.qpos[idx] += J.T @ np.linalg.solve(J @ J.T + 1e-6 * np.eye(6), np.concatenate([ep, er]))
|
| 749 |
+
return d.qpos[idx].copy()
|
| 750 |
+
|
| 751 |
+
|
| 752 |
+
def _write_la_files(self, prefix):
|
| 753 |
+
"""la observation files besides the two JPEGs: <prefix>_state.json always; with --perception rgbd also metric
|
| 754 |
+
depth for both cameras (<prefix>_<cam>_depth.npy, float32 metres along the optical axis, same upright pixels as
|
| 755 |
+
the JPEG) and <prefix>_camera.json (K and cam_to_world in the eef_pos frame, OpenCV camera axes).
|
| 756 |
+
The fixed agentview camera is calibrated in the true frame; the wrist camera pose is computed from the robot's
|
| 757 |
+
believed gripper pose (so neither file reveals the hidden calibration error of the L1 tasks)."""
|
| 758 |
+
out = {}
|
| 759 |
+
st = self._state_v2()
|
| 760 |
+
st = dict(eef_pos=st["eef_pos"], eef_yaw_deg=st["eef_yaw_deg"], gripper_width_m=st["gripper_width_m"],
|
| 761 |
+
joint_pos_rad=st["joint_pos_rad"], attempt=self.attempt, step=self.step)
|
| 762 |
+
with open(os.path.join(self.obs_dir, f"{prefix}_state.json"), "w") as f:
|
| 763 |
+
json.dump(st, f, default=_json_default)
|
| 764 |
+
out["state_file"] = f"obs/{prefix}_state.json"
|
| 765 |
+
if self.a.perception == "rgbd":
|
| 766 |
+
res = self.a.image_res
|
| 767 |
+
cams, depth_files = {}, []
|
| 768 |
+
T_b, T_true = self._believed_pose()
|
| 769 |
+
for cam in ("agentview", "wrist"):
|
| 770 |
+
d = C.render_depth(self.task.env, cam, res).astype(np.float32)
|
| 771 |
+
np.save(os.path.join(self.obs_dir, f"{prefix}_{cam}_depth.npy"), d)
|
| 772 |
+
depth_files.append(f"obs/{prefix}_{cam}_depth.npy")
|
| 773 |
+
E = C.cam_to_world(self.task.env, cam)
|
| 774 |
+
if cam == "wrist":
|
| 775 |
+
E = T_b @ np.linalg.inv(T_true) @ E
|
| 776 |
+
E = E.copy()
|
| 777 |
+
E[:3, 3] -= self.base_off # robot-base frame
|
| 778 |
+
cams[cam] = dict(K=np.round(C.intrinsics(self.task.env, cam, res), 6).tolist(),
|
| 779 |
+
cam_to_base=np.round(E, 6).tolist(), width=res, height=res)
|
| 780 |
+
with open(os.path.join(self.obs_dir, f"{prefix}_camera.json"), "w") as f:
|
| 781 |
+
json.dump(cams, f)
|
| 782 |
+
out["depth_files"] = depth_files
|
| 783 |
+
out["camera_file"] = f"obs/{prefix}_camera.json"
|
| 784 |
+
return out
|
| 785 |
+
|
| 786 |
+
|
| 787 |
+
|
| 788 |
+
def _fb_sentence(level):
|
| 789 |
+
"""README sentence for the feedback level. F1 (default since 2026-10-08): success / failure only, like
|
| 790 |
+
LIBERO-Agent's finish_episode outcome; F2 (measured error, e.g. "2.5 cm past the centre") is privileged
|
| 791 |
+
simulator information that neither LIBERO-Agent nor RoboDojo gives, kept only as an ablation."""
|
| 792 |
+
return {"F0": "The environment then checks the result.",
|
| 793 |
+
"F1": "The environment then checks the result and tells you only whether the attempt succeeded.",
|
| 794 |
+
"F2": "The environment then checks the result and tells you whether the attempt succeeded and, if not, "
|
| 795 |
+
"what went wrong."}[level]
|
| 796 |
+
|
| 797 |
+
def _readme_la(self):
|
| 798 |
+
"""LIBERO-Agent-style instructions: the agent works in an episode workspace (observations are files, it can run
|
| 799 |
+
programs on them); the robot itself is driven only through the harness's `robot` tool."""
|
| 800 |
+
sec = self.sim_budget()
|
| 801 |
+
rgbd = self.a.perception == "rgbd"
|
| 802 |
+
cli = self.a.agent_iface == "cli"
|
| 803 |
+
pre = "./robot " if cli else ""
|
| 804 |
+
proto = (f"You have up to {self.k_shown} attempts at this task. Before every attempt the scene is reset to exactly the "
|
| 805 |
+
f"same initial state." if self.protocol == "cross" else
|
| 806 |
+
f"Everything happens in one continuous scene. You may end an attempt up to {self.k_shown} times; after a "
|
| 807 |
+
f"failed attempt you continue from the current state.")
|
| 808 |
+
files = [
|
| 809 |
+
"- obs/a<attempt>_s<step>_agentview.jpg and obs/a<attempt>_s<step>_wrist.jpg: 512x512 RGB images from "
|
| 810 |
+
"'agentview' (a fixed camera looking at the table) and 'wrist' (a camera on the gripper);",
|
| 811 |
+
"- obs/a<attempt>_s<step>_state.json: the end-effector state: eef_pos = [x, y, z] of the gripper's grasp "
|
| 812 |
+
"point (midway between the two fingers, about 1 cm above the fingertips), eef_yaw_deg = rotation of the gripper about the vertical axis in degrees, gripper_width_m = opening "
|
| 813 |
+
"of the fingers in metres, joint_pos_rad = the 7 arm joint angles (radians, base to wrist; read-only).",
|
| 814 |
+
]
|
| 815 |
+
if rgbd:
|
| 816 |
+
files += [
|
| 817 |
+
"- obs/a<attempt>_s<step>_agentview_depth.npy and obs/a<attempt>_s<step>_wrist_depth.npy: metric depth "
|
| 818 |
+
"(numpy float32 array, 512x512, metres along each camera's optical axis), pixel-aligned with the images "
|
| 819 |
+
"(row 0 = top of the image);",
|
| 820 |
+
"- obs/a<attempt>_s<step>_camera.json: for each camera, K (3x3 intrinsics of the 512x512 image) and "
|
| 821 |
+
"cam_to_base (4x4 pose of the camera in the robot-base frame; camera axes: x right, y down, z forward).",
|
| 822 |
+
]
|
| 823 |
+
return "\n".join([
|
| 824 |
+
"# Robot task", "",
|
| 825 |
+
"You control a Franka Emika Panda robot arm (7 joints) with a two-finger parallel gripper in a physics "
|
| 826 |
+
"simulation.", "",
|
| 827 |
+
"## Task", self.instruction(), "",
|
| 828 |
+
"## Attempts", proto + f" An attempt ends when you run the robot command `{pre}finish reason=\"...\"` or when its "
|
| 829 |
+
"budget is used up. " + _fb_sentence(self.a.feedback) + " The episode ends at the first success or after the "
|
| 830 |
+
"last attempt.", "",
|
| 831 |
+
*(["## Earlier attempt",
|
| 832 |
+
"Before this episode, an earlier attempt at this task, starting from a scene that looked the same as yours, "
|
| 833 |
+
"failed. Its record is in history/: history/README.md lists every robot command of that attempt with the "
|
| 834 |
+
"robot's reply and its closing remark, and history/obs/ holds the camera images it produced.", ""]
|
| 835 |
+
if getattr(self.a, "dossier", "") else []),
|
| 836 |
+
"## Budget (per attempt)",
|
| 837 |
+
f"- at most {self.a.max_steps} robot commands (status and help are free);",
|
| 838 |
+
f"- at most {sec:.0f} s of simulated robot motion;",
|
| 839 |
+
*([] if cli else [f"- at most {self.a.max_tool_calls} tool calls in total (robot, shell and view_image together)."]),
|
| 840 |
+
"Every robot reply shows the robot budgets that are left.", "",
|
| 841 |
+
"## Coordinates",
|
| 842 |
+
"Coordinates are expressed in the robot-base frame and measured in metres; angles are in degrees.", "",
|
| 843 |
+
"## Workspace and observations",
|
| 844 |
+
"This directory is your workspace for the whole episode. Every robot command writes its observation into "
|
| 845 |
+
"obs/ and prints the paths of the new files:",
|
| 846 |
+
*files,
|
| 847 |
+
"Robot replies also include the end-effector state and, after a motion, how far the gripper stopped from your "
|
| 848 |
+
"target. " + ("You can look at any image with your file-reading tool, run shell commands and programs in this "
|
| 849 |
+
"workspace with `./shell '<command>'` (python3 with numpy, scipy, Pillow and OpenCV; no network; "
|
| 850 |
+
"programs cannot control the robot), and keep your own files and notes in this directory; they "
|
| 851 |
+
"persist across attempts." if cli else
|
| 852 |
+
"You can look at any image with view_image, run shell commands and programs here (python3 with "
|
| 853 |
+
"numpy, scipy, Pillow and OpenCV; no network; programs cannot control the robot), and keep your "
|
| 854 |
+
"own files and notes in this directory; they persist across attempts."), "",
|
| 855 |
+
"## Robot commands " + ("(run from this directory as `./robot <command>`, one command at a time)" if cli
|
| 856 |
+
else "(argument of the `robot` tool)"),
|
| 857 |
+
f" {pre}status task, attempt, budget, current state and observation files",
|
| 858 |
+
f" {pre}observe new observation without moving",
|
| 859 |
+
f" {pre}move_eef [x=..] [y=..] [z=..] [yaw=..] [gripper=open|close] [speed=..]",
|
| 860 |
+
" move the grasp point to an absolute target (robot-base frame, metres; yaw in degrees);",
|
| 861 |
+
" omitted coordinates keep their current value; the gripper command is executed after the motion;",
|
| 862 |
+
" speed in m/s (omit = fastest); a target the arm cannot reach is rejected and the arm does not move.",
|
| 863 |
+
f" {pre}finish reason=\"...\" end the current attempt",
|
| 864 |
+
"",
|
| 865 |
+
"Arguments are key=value; numbers are plain (e.g. x=0.12). Quote strings with spaces.", ""])
|
| 866 |
+
|
| 867 |
+
|
| 868 |
+
for _n, _f in (("_believed_joints", _believed_joints), ("readme_la", _readme_la), ("_la_files", _la_files), ("_believed_pose", _believed_pose),
|
| 869 |
+
("_write_la_files", _write_la_files), ("readme_v2", _readme_v2), ("sim_budget", _sim_budget), ("_budget_left", _budget_left),
|
| 870 |
+
("_state_v2", _state_v2), ("handle_v2", _handle_v2), ("_snap_regressions", _snap_regressions),
|
| 871 |
+
("_snap_regressions_inner", _snap_regressions_inner)):
|
| 872 |
+
setattr(RobotSession, _n, _f)
|
| 873 |
+
RobotSession._clean_v2 = staticmethod(_clean_v2)
|
| 874 |
+
|
| 875 |
+
|
| 876 |
+
def serve(a):
|
| 877 |
+
sess = RobotSession(a)
|
| 878 |
+
|
| 879 |
+
class H(BaseHTTPRequestHandler):
|
| 880 |
+
def log_message(self, *x):
|
| 881 |
+
pass
|
| 882 |
+
|
| 883 |
+
def do_POST(self):
|
| 884 |
+
t_recv = time.time()
|
| 885 |
+
cmd = ""
|
| 886 |
+
try:
|
| 887 |
+
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
|
| 888 |
+
cmd = body.get("cmd", "")
|
| 889 |
+
if self.headers.get("X-Token") != sess.token:
|
| 890 |
+
rep = dict(ok=False, error="unauthorised")
|
| 891 |
+
else:
|
| 892 |
+
rep = sess.handle(cmd, body.get("args", {}) or {})
|
| 893 |
+
except Exception as e: # never leak a traceback (it contains benchmark paths) to the agent
|
| 894 |
+
sess.log(dict(ev="error", error=traceback.format_exc()))
|
| 895 |
+
rep = dict(ok=False, error=f"internal error: {type(e).__name__}")
|
| 896 |
+
data = json.dumps(rep, default=_json_default, indent=None).encode()
|
| 897 |
+
if "text" in rep:
|
| 898 |
+
data = rep["text"].encode()
|
| 899 |
+
self.send_response(200)
|
| 900 |
+
self.send_header("Content-Type", "application/json")
|
| 901 |
+
self.end_headers()
|
| 902 |
+
self.wfile.write(data)
|
| 903 |
+
t_send = time.time()
|
| 904 |
+
# think time = gap between the previous reply and this request (model inference + its own tool overhead)
|
| 905 |
+
sess.log(dict(ev="http", cmd=cmd, attempt=sess.attempt, t_recv=t_recv, t_send=t_send,
|
| 906 |
+
server_s=t_send - t_recv, think_s=(t_recv - sess.last_send) if sess.last_send else None))
|
| 907 |
+
sess.last_send = t_send
|
| 908 |
+
|
| 909 |
+
def _term(*_):
|
| 910 |
+
if sess.video is not None:
|
| 911 |
+
sess.video.close()
|
| 912 |
+
os._exit(0)
|
| 913 |
+
|
| 914 |
+
signal.signal(signal.SIGTERM, _term)
|
| 915 |
+
srv = HTTPServer(("127.0.0.1", a.port), H)
|
| 916 |
+
print(f"robot server ready on 127.0.0.1:{a.port} sandbox={sess.sandbox} log={sess.log_dir}", flush=True)
|
| 917 |
+
with open(os.path.join(sess.log_dir, "READY"), "w") as f:
|
| 918 |
+
f.write(str(os.getpid()))
|
| 919 |
+
srv.serve_forever()
|
| 920 |
+
|
| 921 |
+
|
| 922 |
+
def main():
|
| 923 |
+
ap = argparse.ArgumentParser()
|
| 924 |
+
ap.add_argument("--task", required=True)
|
| 925 |
+
ap.add_argument("--seed", type=int, required=True)
|
| 926 |
+
ap.add_argument("--k", type=int, default=None)
|
| 927 |
+
ap.add_argument("--memory", default="full", choices=["full", "none"])
|
| 928 |
+
ap.add_argument("--hide-k", action="store_true",
|
| 929 |
+
help="memory=full: README/status say 1 attempt (same as an independent k=1 run); the remaining "
|
| 930 |
+
"attempts are announced only after a failed attempt")
|
| 931 |
+
ap.add_argument("--feedback", default="F1", choices=["F0", "F1", "F2"])
|
| 932 |
+
ap.add_argument("--instruction", default="direct", choices=["direct", "indirect"])
|
| 933 |
+
ap.add_argument("--image-res", type=int, default=512)
|
| 934 |
+
ap.add_argument("--port", type=int, default=8765)
|
| 935 |
+
ap.add_argument("--sandbox", required=True)
|
| 936 |
+
ap.add_argument("--log-dir", required=True)
|
| 937 |
+
ap.add_argument("--max-steps", type=int, default=None,
|
| 938 |
+
help="robot commands per attempt (default: the task's agent_max_steps, else 40)")
|
| 939 |
+
ap.add_argument("--allow-push", action="store_true", help="expose the composite push primitive (off by default)")
|
| 940 |
+
ap.add_argument("--perception", default="depth", choices=["depth", "rgb", "rgbd"],
|
| 941 |
+
help="rgb: images only (no pixel_to_world / depth); depth: adds the depth back-projection tool "
|
| 942 |
+
"(v1); rgbd (la): also writes metric depth and camera calibration files")
|
| 943 |
+
ap.add_argument("--style", default="v1", choices=["v1", "v2", "la"],
|
| 944 |
+
help="v2: LIBERO-Agent / RoboDojo-aligned interface (see _V2); la: v2 + LIBERO-Agent workspace "
|
| 945 |
+
"(observation files, programs in the workspace, robot only through the harness tool)")
|
| 946 |
+
ap.add_argument("--nominal", action="store_true",
|
| 947 |
+
help="control: remove the hidden calibration error of an L1 task (bias / yaw_bias = 0)")
|
| 948 |
+
ap.add_argument("--agent-iface", default="tools", choices=["tools", "cli"],
|
| 949 |
+
help="la: tools = harness tools (robot / shell / view_images, our GPT driver); cli = ./robot and "
|
| 950 |
+
"./shell in the workspace for a coding agent such as Claude Code")
|
| 951 |
+
ap.add_argument("--max-tool-calls", type=int, default=100,
|
| 952 |
+
help="la: tool calls per attempt (robot + shell + view_image), enforced by the harness")
|
| 953 |
+
ap.add_argument("--arm", default="none", choices=["none", "h0", "hplus", "twin"],
|
| 954 |
+
help="full5 controlled arms (lffbench/arm_specs/<task>.py): h0 = hidden variable at its ordinary value; "
|
| 955 |
+
"hplus = hidden variable stated in the instruction; twin = mismatched-history source instance")
|
| 956 |
+
ap.add_argument("--dossier", default="",
|
| 957 |
+
help="la: copy this directory into the workspace as history/ (record of an earlier failed attempt, "
|
| 958 |
+
"made by scripts/make_dossier.py) and say so in README.md")
|
| 959 |
+
ap.add_argument("--video", default="", help="record agentview|wrist mp4 to this path")
|
| 960 |
+
ap.add_argument("--video-every", type=int, default=3, help="one frame every N control steps (20 Hz)")
|
| 961 |
+
ap.add_argument("--video-fps", type=int, default=20)
|
| 962 |
+
serve(ap.parse_args())
|
| 963 |
+
|
| 964 |
+
|
| 965 |
+
if __name__ == "__main__":
|
| 966 |
+
main()
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_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_breakfast1_20261114/lff/source_closure/lffbench/agent/tools.py
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Agent-facing tool interface on top of `Skills`.
|
| 2 |
+
|
| 3 |
+
Every action tool calls the task's `Skills` object, so the task's hidden calibration `bias` keeps
|
| 4 |
+
acting on every commanded position. Proprioception is reported in the robot's own (possibly
|
| 5 |
+
miscalibrated) frame: reported eef = true eef - bias, i.e. the robot "believes" it reached the
|
| 6 |
+
commanded point; only the cameras show the truth. Camera-derived quantities (pixel_to_world) and
|
| 7 |
+
the privileged `locate` tool are in the true world frame.
|
| 8 |
+
|
| 9 |
+
Tool schemas are plain JSON schema (OpenAI strict-mode compatible: every property listed in
|
| 10 |
+
`required`, optional ones nullable, no additional properties).
|
| 11 |
+
"""
|
| 12 |
+
import json
|
| 13 |
+
import math
|
| 14 |
+
import time
|
| 15 |
+
from dataclasses import dataclass, field
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
|
| 19 |
+
from .. import envs
|
| 20 |
+
from . import camera as C
|
| 21 |
+
from .images import ImageRef
|
| 22 |
+
|
| 23 |
+
TABLE_Z = envs.TABLE_Z
|
| 24 |
+
# Workspace limits for commanded grasp-point positions (world frame, metres). Targets outside are
|
| 25 |
+
# clipped and the report says so.
|
| 26 |
+
WS_LO = np.array([-0.55, -0.45, TABLE_Z + 0.005])
|
| 27 |
+
WS_HI = np.array([0.35, 0.45, TABLE_Z + 0.50])
|
| 28 |
+
SPEED_RANGE = (0.02, 1.0)
|
| 29 |
+
PUSH_DIST_RANGE = (0.0, 0.40)
|
| 30 |
+
RUNUP_RANGE = (0.02, 0.30)
|
| 31 |
+
|
| 32 |
+
ACTION_TOOLS = ("move_to", "open_gripper", "close_gripper", "push")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _num(desc):
|
| 36 |
+
return {"type": "number", "description": desc}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _opt_num(desc):
|
| 40 |
+
return {"type": ["number", "null"], "description": desc}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _fn(name, desc, props=None):
|
| 44 |
+
props = props or {}
|
| 45 |
+
return dict(name=name, description=desc,
|
| 46 |
+
parameters={"type": "object", "properties": props, "required": list(props),
|
| 47 |
+
"additionalProperties": False})
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def tool_specs(privileged_locate=False, object_names=None, image_res=512):
|
| 51 |
+
"""Backend-neutral tool list: [{name, description, parameters}]."""
|
| 52 |
+
specs = [
|
| 53 |
+
_fn("move_to",
|
| 54 |
+
"Move the gripper's grasp point (midway between the fingertips) in a straight line to the world "
|
| 55 |
+
"position (x, y, z) with the gripper pointing straight down and rotated to `yaw`. The gripper "
|
| 56 |
+
"opening is not changed. Returns whether the target was reached, the end-effector position, gripper "
|
| 57 |
+
"width, whether an object is held and whether the arm touched an object during the motion.",
|
| 58 |
+
{"x": _num("target x, metres (world frame; +x away from the robot)"),
|
| 59 |
+
"y": _num("target y, metres (world frame; +y to the robot's left)"),
|
| 60 |
+
"z": _num(f"target z, metres (table top is z = {TABLE_Z:.2f})"),
|
| 61 |
+
"yaw": _num("gripper rotation about the vertical axis in DEGREES; 0 = fingers close along the world "
|
| 62 |
+
"y axis, 90 = fingers close along the world x axis. Taken modulo 180 (the two-finger "
|
| 63 |
+
"gripper is symmetric): the controller uses the equivalent angle closest to the current "
|
| 64 |
+
"yaw within +-113 deg; the report gives the yaw actually used"),
|
| 65 |
+
"speed": _opt_num("straight-line speed in m/s (0.02-1.0); null = as fast as the controller allows "
|
| 66 |
+
"(about 0.6 m/s)")}),
|
| 67 |
+
_fn("open_gripper", "Open the gripper fully (the arm holds its position)."),
|
| 68 |
+
_fn("close_gripper", "Close the gripper (the arm holds its position). Closing on an object grasps it."),
|
| 69 |
+
_fn("push",
|
| 70 |
+
"Straight-line push with the closed gripper. The gripper closes, moves above the point `runup` metres "
|
| 71 |
+
"behind (x, y) (opposite to the push direction), descends to height z, sweeps along (dir_x, dir_y) "
|
| 72 |
+
"through (x, y) and stops `distance` metres past (x, y), moving at `speed` m/s, then lifts 12 cm. The "
|
| 73 |
+
"gripper is rotated automatically to a fixed orientation relative to the push direction.",
|
| 74 |
+
{"x": _num("x of the point where the push should start acting (e.g. the near face of the object), m"),
|
| 75 |
+
"y": _num("y of that point, m"),
|
| 76 |
+
"dir_x": _num("x component of the push direction (normalised internally)"),
|
| 77 |
+
"dir_y": _num("y component of the push direction"),
|
| 78 |
+
"distance": _num("how far past (x, y) the gripper travels, metres (0-0.40)"),
|
| 79 |
+
"speed": _num("sweep speed, m/s (0.02-1.0; the controller saturates near 0.6)"),
|
| 80 |
+
"z": _opt_num(f"height of the grasp point during the sweep, m; null = {TABLE_Z + 0.02:.2f} "
|
| 81 |
+
"(2 cm above the table)"),
|
| 82 |
+
"runup": _opt_num("distance behind (x, y) where the sweep starts, m (0.02-0.30); null = 0.06. A longer "
|
| 83 |
+
"run-up lets the gripper reach the commanded speed before contact.")}),
|
| 84 |
+
_fn("get_observation",
|
| 85 |
+
"Return the current camera images (agentview and wrist) and the robot's proprioceptive state."),
|
| 86 |
+
_fn("pixel_to_world",
|
| 87 |
+
f"Back-project an image pixel to a 3-D world point using the camera's depth map. (u, v) are pixel "
|
| 88 |
+
f"coordinates in the {image_res}x{image_res} image exactly as you received it: u = column from the "
|
| 89 |
+
f"left edge, v = row from the top edge. Returns the world point (x, y, z) of the surface seen at that "
|
| 90 |
+
f"pixel and its height above the table.",
|
| 91 |
+
{"camera": {"type": "string", "enum": ["agentview", "wrist"], "description": "which image"},
|
| 92 |
+
"u": _num("column (0 = left edge)"), "v": _num("row (0 = top edge)")}),
|
| 93 |
+
_fn("done",
|
| 94 |
+
"Finish the current attempt. Call this when you believe the task is complete (or you want to stop). "
|
| 95 |
+
"Give a short reason: what you did and whether you think it worked.",
|
| 96 |
+
{"reason": {"type": "string", "description": "short explanation"}}),
|
| 97 |
+
]
|
| 98 |
+
if privileged_locate:
|
| 99 |
+
names = list(object_names or [])
|
| 100 |
+
prop = {"type": "string", "description": "object name"}
|
| 101 |
+
if names:
|
| 102 |
+
prop["enum"] = names
|
| 103 |
+
specs.insert(-1, _fn("locate",
|
| 104 |
+
"PRIVILEGED (ablation): return the true world position of an object's origin and its "
|
| 105 |
+
"axis-aligned bounding box.", {"object_name": prop}))
|
| 106 |
+
return specs
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
@dataclass
|
| 110 |
+
class ToolResult:
|
| 111 |
+
name: str
|
| 112 |
+
args: dict
|
| 113 |
+
ok: bool
|
| 114 |
+
report: dict
|
| 115 |
+
images: list = field(default_factory=list)
|
| 116 |
+
ended: bool = False
|
| 117 |
+
wall_s: float = 0.0
|
| 118 |
+
sim_steps: int = 0
|
| 119 |
+
|
| 120 |
+
def text(self):
|
| 121 |
+
return json.dumps(self.report, separators=(", ", ": "), default=_json_default)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _json_default(o):
|
| 125 |
+
if isinstance(o, (np.floating,)):
|
| 126 |
+
return float(o)
|
| 127 |
+
if isinstance(o, (np.integer,)):
|
| 128 |
+
return int(o)
|
| 129 |
+
if isinstance(o, np.ndarray):
|
| 130 |
+
return o.tolist()
|
| 131 |
+
if isinstance(o, (np.bool_,)):
|
| 132 |
+
return bool(o)
|
| 133 |
+
raise TypeError(type(o))
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _r(v, nd=4):
|
| 137 |
+
return [round(float(x), nd) for x in v]
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class ContactTracker:
|
| 141 |
+
"""Collects the objects the robot touches. Contacts are checked after every MuJoCo substep (a control
|
| 142 |
+
step is 25 substeps; a fast push touches the object for less than one control step, so checking only at
|
| 143 |
+
control-step boundaries misses it -- measured). Implemented by wrapping `env.sim.step` once per env; the
|
| 144 |
+
wrapper only reads contacts and dispatches to the currently active tracker."""
|
| 145 |
+
|
| 146 |
+
def __init__(self, env):
|
| 147 |
+
self.env = env
|
| 148 |
+
m = env.sim.model
|
| 149 |
+
self.is_robot = np.zeros(m.ngeom, bool)
|
| 150 |
+
self.is_robot[envs.robot_geom_ids(env)] = True
|
| 151 |
+
self.names = []
|
| 152 |
+
self.obj_of = np.full(m.ngeom, -1, int)
|
| 153 |
+
for name in list(env.objects_dict) + list(getattr(env, "fixtures_dict", {}) or {}):
|
| 154 |
+
try:
|
| 155 |
+
ids = envs.obj_geom_ids(env, name)
|
| 156 |
+
except Exception: # fixtures without contact geoms
|
| 157 |
+
continue
|
| 158 |
+
self.obj_of[ids] = len(self.names)
|
| 159 |
+
self.names.append(name)
|
| 160 |
+
self.touched = set()
|
| 161 |
+
sim = env.sim
|
| 162 |
+
if not getattr(sim, "_lff_step_wrapped", False):
|
| 163 |
+
orig = sim.step
|
| 164 |
+
|
| 165 |
+
def step(*a, **k):
|
| 166 |
+
orig(*a, **k)
|
| 167 |
+
t = getattr(sim, "_lff_tracker", None)
|
| 168 |
+
if t is not None:
|
| 169 |
+
t.check()
|
| 170 |
+
sim.step = step
|
| 171 |
+
sim._lff_step_wrapped = True
|
| 172 |
+
sim._lff_tracker = self
|
| 173 |
+
|
| 174 |
+
def reset(self):
|
| 175 |
+
self.touched = set()
|
| 176 |
+
|
| 177 |
+
def check(self):
|
| 178 |
+
d = self.env.sim.data
|
| 179 |
+
n = d.ncon
|
| 180 |
+
if not n:
|
| 181 |
+
return
|
| 182 |
+
g1 = np.asarray(d.contact.geom1)[:n]
|
| 183 |
+
g2 = np.asarray(d.contact.geom2)[:n]
|
| 184 |
+
hit = np.concatenate([self.obj_of[g2[self.is_robot[g1]]], self.obj_of[g1[self.is_robot[g2]]]])
|
| 185 |
+
for i in set(hit[hit >= 0].tolist()):
|
| 186 |
+
self.touched.add(self.names[i])
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def parse_args(raw):
|
| 190 |
+
if raw is None:
|
| 191 |
+
return {}
|
| 192 |
+
if isinstance(raw, dict):
|
| 193 |
+
return dict(raw)
|
| 194 |
+
raw = raw.strip()
|
| 195 |
+
return json.loads(raw) if raw else {}
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
class ToolExecutor:
|
| 199 |
+
"""Executes agent tool calls on a task whose instance has just been reset (task.sk is live)."""
|
| 200 |
+
|
| 201 |
+
def __init__(self, task, inst, image_res=512, cams=("agentview", "wrist"), privileged_locate=False,
|
| 202 |
+
grasp_report="bool", jpeg_quality=90, image_sink=None):
|
| 203 |
+
self.task = task
|
| 204 |
+
self.inst = inst
|
| 205 |
+
self.env = task.env
|
| 206 |
+
self.sk = task.sk # keep our own reference: the scripted backend may swap task.sk for a proxy
|
| 207 |
+
self.image_res = int(image_res)
|
| 208 |
+
self.cams = tuple(cams)
|
| 209 |
+
self.privileged_locate = privileged_locate
|
| 210 |
+
self.grasp_report = grasp_report # "bool" | "name" | "none"
|
| 211 |
+
self.jpeg_quality = jpeg_quality
|
| 212 |
+
self.image_sink = image_sink # callable(ImageRef) -> path (saves the image)
|
| 213 |
+
self.objects = list(self.env.objects_dict)
|
| 214 |
+
self.tracker = ContactTracker(self.env) # task recorders / hooks on Skills are left untouched
|
| 215 |
+
self._depth_cache = {}
|
| 216 |
+
self.n_calls = 0
|
| 217 |
+
|
| 218 |
+
# ------------------------------------------------------------------ state
|
| 219 |
+
def eef_yaw_deg(self):
|
| 220 |
+
R = self.sk.eef_mat() @ self.sk.R0.T
|
| 221 |
+
return math.degrees(math.atan2(R[1, 0], R[0, 0]))
|
| 222 |
+
|
| 223 |
+
def held(self):
|
| 224 |
+
names = [o for o in self.objects if self.sk.holding(o)]
|
| 225 |
+
return names
|
| 226 |
+
|
| 227 |
+
def _holding_field(self, names):
|
| 228 |
+
if self.grasp_report == "name":
|
| 229 |
+
return names[0] if names else None
|
| 230 |
+
if self.grasp_report == "none":
|
| 231 |
+
return None
|
| 232 |
+
return bool(names)
|
| 233 |
+
|
| 234 |
+
def proprio(self):
|
| 235 |
+
believed = self.sk.eef_pos() - self.sk.bias
|
| 236 |
+
p = dict(eef_pos=_r(believed), eef_yaw_deg=round(self.eef_yaw_deg(), 1),
|
| 237 |
+
gripper="closed" if self.sk.grip > 0 else "open",
|
| 238 |
+
gripper_width_m=round(self.sk.gripper_width(), 4))
|
| 239 |
+
if self.grasp_report != "none":
|
| 240 |
+
p["holding_object"] = self._holding_field(self.held())
|
| 241 |
+
return p
|
| 242 |
+
|
| 243 |
+
def render(self, cam, res=None):
|
| 244 |
+
res = res or self.image_res
|
| 245 |
+
return envs.render(self.env, C.mj_cam(cam), res)
|
| 246 |
+
|
| 247 |
+
def observe(self, label=""):
|
| 248 |
+
imgs = []
|
| 249 |
+
for cam in self.cams:
|
| 250 |
+
ref = ImageRef(camera=cam, array=self.render(cam), label=f"{label} {cam}".strip())
|
| 251 |
+
if self.image_sink is not None:
|
| 252 |
+
self.image_sink(ref)
|
| 253 |
+
imgs.append(ref)
|
| 254 |
+
self._depth_cache = {}
|
| 255 |
+
return imgs
|
| 256 |
+
|
| 257 |
+
# ------------------------------------------------------------------ dispatch
|
| 258 |
+
def call(self, name, raw_args):
|
| 259 |
+
t0 = time.time()
|
| 260 |
+
n0 = self.sk.n_steps
|
| 261 |
+
self.n_calls += 1
|
| 262 |
+
try:
|
| 263 |
+
args = parse_args(raw_args)
|
| 264 |
+
except Exception as e:
|
| 265 |
+
return ToolResult(name, {"_raw": str(raw_args)}, False, dict(ok=False, error=f"arguments are not valid JSON: {e}"),
|
| 266 |
+
wall_s=time.time() - t0)
|
| 267 |
+
fn = getattr(self, f"_t_{name}", None)
|
| 268 |
+
if fn is None or (name == "locate" and not self.privileged_locate):
|
| 269 |
+
return ToolResult(name, args, False, dict(ok=False, error=f"unknown tool {name!r}"), wall_s=time.time() - t0)
|
| 270 |
+
try:
|
| 271 |
+
res = fn(**args)
|
| 272 |
+
except TypeError as e:
|
| 273 |
+
res = ToolResult(name, args, False, dict(ok=False, error=f"bad arguments: {e}"))
|
| 274 |
+
except ValueError as e:
|
| 275 |
+
res = ToolResult(name, args, False, dict(ok=False, error=str(e)))
|
| 276 |
+
res.args = args
|
| 277 |
+
res.wall_s = time.time() - t0
|
| 278 |
+
res.sim_steps = self.sk.n_steps - n0
|
| 279 |
+
if res.sim_steps:
|
| 280 |
+
self._depth_cache = {}
|
| 281 |
+
hook = getattr(self.task, "on_agent_tool", None)
|
| 282 |
+
if hook is not None:
|
| 283 |
+
hook(self.inst, name, args, res.report)
|
| 284 |
+
drain = getattr(self.task, "drain_events", None) # task-side events (e.g. L6: an item slipped)
|
| 285 |
+
if drain is not None:
|
| 286 |
+
ev = drain()
|
| 287 |
+
if ev:
|
| 288 |
+
res.report["events"] = list(ev)
|
| 289 |
+
return res
|
| 290 |
+
|
| 291 |
+
# ------------------------------------------------------------------ helpers
|
| 292 |
+
def _clip_xyz(self, xyz):
|
| 293 |
+
xyz = np.asarray(xyz, float)
|
| 294 |
+
if not np.all(np.isfinite(xyz)):
|
| 295 |
+
raise ValueError("non-finite coordinates")
|
| 296 |
+
c = np.clip(xyz, WS_LO, WS_HI)
|
| 297 |
+
return c, (None if np.allclose(c, xyz) else _r(c))
|
| 298 |
+
|
| 299 |
+
@staticmethod
|
| 300 |
+
def _clip(v, lo_hi, what):
|
| 301 |
+
v = float(v)
|
| 302 |
+
if not math.isfinite(v):
|
| 303 |
+
raise ValueError(f"{what} must be finite")
|
| 304 |
+
return float(np.clip(v, *lo_hi))
|
| 305 |
+
|
| 306 |
+
def _action_report(self, name, extra=None):
|
| 307 |
+
names = self.held()
|
| 308 |
+
rep = dict(ok=True, tool=name)
|
| 309 |
+
if extra:
|
| 310 |
+
rep.update(extra)
|
| 311 |
+
rep.update(self.proprio())
|
| 312 |
+
if self.grasp_report == "name":
|
| 313 |
+
rep["touched_objects"] = sorted(self.tracker.touched)
|
| 314 |
+
elif self.grasp_report == "bool":
|
| 315 |
+
rep["touched_object"] = bool(self.tracker.touched)
|
| 316 |
+
rep["sim_time_s"] = round(self.sk.n_steps * 0.05, 2)
|
| 317 |
+
return rep
|
| 318 |
+
|
| 319 |
+
# ------------------------------------------------------------------ tools
|
| 320 |
+
def _t_move_to(self, x, y, z, yaw, speed=None):
|
| 321 |
+
tgt, clipped = self._clip_xyz([x, y, z])
|
| 322 |
+
spd = None if speed is None else self._clip(speed, SPEED_RANGE, "speed")
|
| 323 |
+
self.tracker.reset()
|
| 324 |
+
rep = self.sk.move_to(tgt, yaw=math.radians(float(yaw)), speed=spd) # Skills wraps yaw mod pi
|
| 325 |
+
extra = dict(reached=bool(rep["reached"]), yaw_used_deg=round(math.degrees(self.sk.yaw), 1))
|
| 326 |
+
if clipped:
|
| 327 |
+
extra["target_clipped_to"] = clipped
|
| 328 |
+
return ToolResult("move_to", {}, True, self._action_report("move_to", extra))
|
| 329 |
+
|
| 330 |
+
def _t_open_gripper(self):
|
| 331 |
+
self.tracker.reset()
|
| 332 |
+
self.sk.set_gripper(False)
|
| 333 |
+
return ToolResult("open_gripper", {}, True, self._action_report("open_gripper"))
|
| 334 |
+
|
| 335 |
+
def _t_close_gripper(self):
|
| 336 |
+
self.tracker.reset()
|
| 337 |
+
self.sk.set_gripper(True)
|
| 338 |
+
return ToolResult("close_gripper", {}, True, self._action_report("close_gripper"))
|
| 339 |
+
|
| 340 |
+
def _t_push(self, x, y, dir_x, dir_y, distance, speed, z=None, runup=None):
|
| 341 |
+
d = np.array([float(dir_x), float(dir_y)])
|
| 342 |
+
if not np.all(np.isfinite(d)) or np.linalg.norm(d) < 1e-6:
|
| 343 |
+
raise ValueError("push direction must be a non-zero vector")
|
| 344 |
+
start, clipped = self._clip_xyz([x, y, TABLE_Z + 0.02 if z is None else z])
|
| 345 |
+
dist = self._clip(distance, PUSH_DIST_RANGE, "distance")
|
| 346 |
+
spd = self._clip(speed, SPEED_RANGE, "speed")
|
| 347 |
+
pre = 0.06 if runup is None else self._clip(runup, RUNUP_RANGE, "runup")
|
| 348 |
+
self.tracker.reset()
|
| 349 |
+
rep = self.sk.push(start[:2], d, dist, spd, z=float(start[2]), pre=pre)
|
| 350 |
+
extra = dict(sweep_reached=bool(rep["reached"]))
|
| 351 |
+
if clipped:
|
| 352 |
+
extra["start_clipped_to"] = clipped
|
| 353 |
+
return ToolResult("push", {}, True, self._action_report("push", extra))
|
| 354 |
+
|
| 355 |
+
def _t_get_observation(self):
|
| 356 |
+
imgs = self.observe(label="requested")
|
| 357 |
+
return ToolResult("get_observation", {}, True, dict(ok=True, images=[i.camera for i in imgs], **self.proprio()),
|
| 358 |
+
images=imgs)
|
| 359 |
+
|
| 360 |
+
def _t_pixel_to_world(self, camera, u, v):
|
| 361 |
+
cam = str(camera)
|
| 362 |
+
if cam not in C.CAMERAS:
|
| 363 |
+
raise ValueError(f"camera must be one of {sorted(C.CAMERAS)}")
|
| 364 |
+
if cam not in self._depth_cache:
|
| 365 |
+
self._depth_cache[cam] = C.render_depth(self.env, cam, self.image_res)
|
| 366 |
+
r = C.pixel_to_world(self.env, cam, float(u), float(v), self.image_res, depth=self._depth_cache[cam])
|
| 367 |
+
rep = dict(ok=True, camera=cam, u=float(u), v=float(v), world_xyz=_r(r["xyz"]),
|
| 368 |
+
height_above_table_m=round(float(r["xyz"][2] - TABLE_Z), 4), depth_m=round(r["depth"], 4))
|
| 369 |
+
if not r["valid"]:
|
| 370 |
+
rep["warning"] = "pixel shows the far background; the point is unreliable"
|
| 371 |
+
return ToolResult("pixel_to_world", {}, True, rep)
|
| 372 |
+
|
| 373 |
+
def _t_locate(self, object_name):
|
| 374 |
+
if object_name not in self.env.objects_dict:
|
| 375 |
+
raise ValueError(f"unknown object {object_name!r}; known: {self.objects}")
|
| 376 |
+
lo, hi = self._aabb(object_name)
|
| 377 |
+
p = envs.obj_pos(self.env, object_name)
|
| 378 |
+
return ToolResult("locate", {}, True, dict(ok=True, object=object_name, position=_r(p), bbox_min=_r(lo),
|
| 379 |
+
bbox_max=_r(hi)))
|
| 380 |
+
|
| 381 |
+
def _aabb(self, name):
|
| 382 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 383 |
+
lo, hi = np.full(3, np.inf), np.full(3, -np.inf)
|
| 384 |
+
for g in envs.obj_geom_ids(self.env, name):
|
| 385 |
+
R = d.geom_xmat[g].reshape(3, 3)
|
| 386 |
+
c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3]
|
| 387 |
+
h = np.abs(R) @ m.geom_aabb[g, 3:]
|
| 388 |
+
lo, hi = np.minimum(lo, c - h), np.maximum(hi, c + h)
|
| 389 |
+
return lo, hi
|
| 390 |
+
|
| 391 |
+
def _t_done(self, reason=""):
|
| 392 |
+
return ToolResult("done", {}, True, dict(ok=True, ended=True), ended=True)
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_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_breakfast1_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_breakfast1_20261114/lff/source_closure/scripts/api_batch.py
ADDED
|
@@ -0,0 +1,704 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Batch of runs with a concurrency limit: the runner for the paper's main table (reference driver scripts/api_player.py)
|
| 2 |
+
and, with --harness, for native agent harnesses (side table, docs/15).
|
| 3 |
+
|
| 4 |
+
start python scripts/api_batch.py start --batch m1_opus --provider anthropic --model claude-opus-5-5 --effort high \
|
| 5 |
+
--tasks l1_height_bias:3000,3001 lh_bridge:3000 --k 3 --concurrency 6 --video
|
| 6 |
+
-> writes runs/api/<batch>/manifest.json (one entry per run, status "pending") and starts a background
|
| 7 |
+
runner that keeps at most --concurrency runs going (robot server + api_player each) and stops each
|
| 8 |
+
server when its player exits.
|
| 9 |
+
status python scripts/api_batch.py status --batch m1_opus
|
| 10 |
+
table python scripts/api_batch.py table --batch m1_opus [--batch ...] (same table as claude_batch + tokens)
|
| 11 |
+
stop python scripts/api_batch.py stop --batch m1_opus (runner, players, servers; runs -> "stopped")
|
| 12 |
+
retry python scripts/api_batch.py retry --batch m1_opus [--runs <run> ...] (default: every failed / stopped / timeout run;
|
| 13 |
+
old logs stay, listed under "superseded"; starts the runner again)
|
| 14 |
+
followup python scripts/api_batch.py followup --batch m1_opus (switch a batch started before 2026-10-19 to
|
| 15 |
+
--memfree followup: plans the memory-free retries due for its finished history runs; then `retry` starts them)
|
| 16 |
+
contract python scripts/api_batch.py contract --batch b1 [--batch b2 ...] (contract_sha256 per instance and condition;
|
| 17 |
+
flags instances whose hash differs between batches: those cells must not share a table)
|
| 18 |
+
pause touch runs/api/<batch>/PAUSE: the runner launches no new run while the file exists; the runs going on finish
|
| 19 |
+
and are recorded as usual (rm the file to go on). Used by quota watchers to stay below a usage window.
|
| 20 |
+
|
| 21 |
+
--harness (default ours): which agent harness drives each run, through scripts/harness_run.py (lffbench/harnesses):
|
| 22 |
+
ours scripts/api_player.py, unchanged (--provider as before)
|
| 23 |
+
claude_code Claude Code CLI --bare, only our MCP tools, one-time config dirs (arm B; provider anthropic)
|
| 24 |
+
claude_code_full Claude Code CLI without --bare (full system prompt), otherwise the same (arm B');
|
| 25 |
+
--claude-auth oauth (default): the subscription token of `claude setup-token` (LFF_CLAUDE_OAUTH_FILE),
|
| 26 |
+
apikey: ANTHROPIC_API_KEY (claude_code takes only apikey)
|
| 27 |
+
codex Codex CLI exec --ephemeral, empty CODEX_HOME, only our MCP tools reachable (arm F; provider openai);
|
| 28 |
+
--codex-auth chatgpt (default): the ChatGPT subscription login, apikey: OPENAI_API_KEY
|
| 29 |
+
dsh DeepSeek Harness headless, only our MCP tools, one-time dirs (lffbench/harnesses/dsh.py; provider
|
| 30 |
+
deepseek, key LFF_DEEPSEEK_API_KEY / DEEPSEEK_API_KEY)
|
| 31 |
+
Native harnesses are refused at launch (status "refused") unless their preset prompt / tool list matches the pin
|
| 32 |
+
written by tests/harness_selfcheck (--allow-unpinned to launch anyway; the preflight still runs). Every run gets
|
| 33 |
+
harness.json, contract.json, trajectory.jsonl and harness_audit.json in its log dir.
|
| 34 |
+
|
| 35 |
+
Conditions (same as claude_batch): harness = memory full, k attempts in one agent; noharness = independent single-attempt
|
| 36 |
+
agents (memory none, k=1). History runs use --hide-k (README and status say 1 attempt, byte-identical to an independent
|
| 37 |
+
run; more attempts are announced only after a failure; --no-hide-k to show k).
|
| 38 |
+
--memfree, how the memory-free retries (pass@k without history) are run:
|
| 39 |
+
followup (default, 2026-10-19): one history run per instance. Its attempt 1 is also the first memory-free attempt,
|
| 40 |
+
since under --hide-k it sees exactly what a fresh agent sees. Only if attempt 1 fails does the runner add a
|
| 41 |
+
fresh single-attempt agent (noharness rep 1, "chain" = the history run's id); if that one fails too, the
|
| 42 |
+
next (rep 2), up to k-1 of them; the first success ends the chain. An instance solved on attempt 1 thus
|
| 43 |
+
costs one attempt in all. Not for tasks whose scene persists between attempts (task protocol "within"):
|
| 44 |
+
a fresh agent would start from the initial scene, the history run's attempt 2 from the failed one, so the
|
| 45 |
+
two conditions would differ; these tasks are reported without memory-free retries (user 2026-10-20).
|
| 46 |
+
upfront the 2026-10-11 protocol: --indep-reps independent runs per instance (default k, all of them run), all
|
| 47 |
+
before the history runs (--conds order; --no-barrier to mix the phases).
|
| 48 |
+
none history runs only.
|
| 49 |
+
--seeds-per-task N keeps the first N seeds of each task:seeds (e.g. 1 = one instance per task).
|
| 50 |
+
API keys come from LFF_ENV_FILE (default <repo>/.env, KEY=value lines) or the environment.
|
| 51 |
+
"""
|
| 52 |
+
import argparse
|
| 53 |
+
import json
|
| 54 |
+
import os
|
| 55 |
+
import re
|
| 56 |
+
import shlex
|
| 57 |
+
import signal
|
| 58 |
+
import subprocess
|
| 59 |
+
import sys
|
| 60 |
+
import threading
|
| 61 |
+
import time
|
| 62 |
+
|
| 63 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 64 |
+
sys.path.insert(0, os.path.join(ROOT, "scripts"))
|
| 65 |
+
import claude_batch # noqa: E402
|
| 66 |
+
|
| 67 |
+
RUNS = os.path.join(ROOT, "runs", "api")
|
| 68 |
+
ENV_FILE = os.environ.get("LFF_ENV_FILE") or os.path.join(ROOT, ".env")
|
| 69 |
+
ACTIVE = ("starting", "running")
|
| 70 |
+
RETRYABLE = ("failed", "stopped", "timeout", "server_failed")
|
| 71 |
+
sys.path.insert(0, ROOT)
|
| 72 |
+
from lffbench.harnesses import NAMES, ROBOT_HARNESSES, PROVIDER as HARNESS_PROVIDER
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def bdir(batch):
|
| 77 |
+
return os.path.join(RUNS, batch)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def mpath(batch):
|
| 81 |
+
return os.path.join(bdir(batch), "manifest.json")
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def load(batch):
|
| 85 |
+
with open(mpath(batch)) as f:
|
| 86 |
+
return json.load(f)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def save(batch, m):
|
| 90 |
+
os.makedirs(bdir(batch), exist_ok=True)
|
| 91 |
+
tmp = mpath(batch) + ".tmp"
|
| 92 |
+
with open(tmp, "w") as f:
|
| 93 |
+
json.dump(m, f, indent=1)
|
| 94 |
+
os.replace(tmp, mpath(batch))
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def alive(pid):
|
| 98 |
+
try:
|
| 99 |
+
os.kill(int(pid), 0)
|
| 100 |
+
return True
|
| 101 |
+
except (ProcessLookupError, PermissionError, TypeError, ValueError):
|
| 102 |
+
return False
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def runner_alive(batch):
|
| 106 |
+
p = os.path.join(bdir(batch), "runner.pid")
|
| 107 |
+
return os.path.exists(p) and alive(open(p).read().strip())
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def launch_runner(batch):
|
| 111 |
+
log = open(os.path.join(bdir(batch), "runner.log"), "a")
|
| 112 |
+
p = subprocess.Popen([sys.executable, os.path.abspath(__file__), "_runner", "--batch", batch], cwd=ROOT,
|
| 113 |
+
start_new_session=True, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)
|
| 114 |
+
with open(os.path.join(bdir(batch), "runner.pid"), "w") as f:
|
| 115 |
+
f.write(str(p.pid))
|
| 116 |
+
return p.pid
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def next_id(m):
|
| 120 |
+
return f"{max((int(r['id']) for r in m['runs']), default=-1) + 1:04d}"
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
# ------------------------------------------------------------------------------------------------- memory-free chains
|
| 124 |
+
# --memfree followup: per instance, history run (cond harness, followup=True) -> noharness rep 1 -> ... -> rep k-1,
|
| 125 |
+
# each link planned only after the previous attempts all failed. Attempt 1 of the history run is the chain's first
|
| 126 |
+
# attempt (--hide-k makes it identical to a fresh agent's), so the memory-free pass@k of an instance is: attempt 1 of
|
| 127 |
+
# the history run, or any of its chain runs, succeeded.
|
| 128 |
+
PLAN_KEYS = ("task", "seed", "provider", "agent_harness", "api_base_url", "max_budget_usd", "allow_unpinned", "jail",
|
| 129 |
+
"codex_auth", "claude_auth", "codex_catalog", "codex_provider",
|
| 130 |
+
"rpent_sessions", "rpent_attempts_per_session", "rpent_max_turns",
|
| 131 |
+
"model", "effort", "perception", "video", "style", "feedback", "phase", "nominal", "red_team")
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def attempt_results(log):
|
| 135 |
+
"""[success of attempt 1, of attempt 2, ...] from the robot server log ([] if there is none)."""
|
| 136 |
+
p = os.path.join(log or "", "events.jsonl")
|
| 137 |
+
if not os.path.exists(p):
|
| 138 |
+
return []
|
| 139 |
+
res = {}
|
| 140 |
+
for line in open(p):
|
| 141 |
+
e = json.loads(line)
|
| 142 |
+
if e.get("ev") == "done":
|
| 143 |
+
res[e["attempt"]] = bool(e["success"])
|
| 144 |
+
return [res[i] for i in sorted(res)]
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def episode_protocol(log):
|
| 148 |
+
"""The task's attempt protocol ("cross": reset between attempts, "within": the scene persists) from the robot
|
| 149 |
+
server log's session_start line; None if unknown."""
|
| 150 |
+
p = os.path.join(log or "", "events.jsonl")
|
| 151 |
+
if os.path.exists(p):
|
| 152 |
+
for line in open(p):
|
| 153 |
+
e = json.loads(line)
|
| 154 |
+
if e.get("ev") == "session_start":
|
| 155 |
+
return e.get("protocol")
|
| 156 |
+
return None
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def plan_followup(m, r):
|
| 160 |
+
"""Run r has finished: append the next memory-free retry of its instance if one is due; returns it or None."""
|
| 161 |
+
if r["status"] != "done":
|
| 162 |
+
return None
|
| 163 |
+
if r["cond"] == "harness" and r.get("followup"):
|
| 164 |
+
if episode_protocol(r.get("log")) == "within": # no like-for-like fresh agent (module docstring)
|
| 165 |
+
return None
|
| 166 |
+
root, nxt, res = r, 1, attempt_results(r.get("log"))[:1]
|
| 167 |
+
elif r.get("chain"):
|
| 168 |
+
root = next((x for x in m["runs"] if x["id"] == r["chain"]), None)
|
| 169 |
+
nxt, res = r["rep"] + 1, attempt_results(r.get("log"))
|
| 170 |
+
else:
|
| 171 |
+
return None
|
| 172 |
+
if root is None or not res or any(res) or nxt >= root["k"]:
|
| 173 |
+
return None
|
| 174 |
+
if any(x.get("chain") == root["id"] and x["rep"] == nxt for x in m["runs"]):
|
| 175 |
+
return None
|
| 176 |
+
new = {k: root.get(k) for k in PLAN_KEYS}
|
| 177 |
+
new.update(id=next_id(m), cond="noharness", rep=nxt, k=1, mem="none", hide_k=False, chain=root["id"],
|
| 178 |
+
status="pending")
|
| 179 |
+
m["runs"].append(new)
|
| 180 |
+
return new
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def memfree_chain(m, root):
|
| 184 |
+
"""Table rows for the memory-free retries of root's instance: its attempt 1 (rep 0, only_attempt=1) and the chain
|
| 185 |
+
runs after it. [] while the chain has not ended (a success, or k attempts)."""
|
| 186 |
+
first = attempt_results(root.get("log"))[:1]
|
| 187 |
+
if not first:
|
| 188 |
+
return []
|
| 189 |
+
rows = [dict(root, cond="noharness", rep=0, k=1, only_attempt=1)]
|
| 190 |
+
if first[0]:
|
| 191 |
+
return rows
|
| 192 |
+
chain = {x["rep"]: x for x in m["runs"] if x.get("chain") == root["id"] and x["status"] == "done" and x.get("log")}
|
| 193 |
+
for rep in range(1, root["k"]):
|
| 194 |
+
if rep not in chain:
|
| 195 |
+
return []
|
| 196 |
+
rows.append(dict(chain[rep]))
|
| 197 |
+
if any(attempt_results(chain[rep]["log"])):
|
| 198 |
+
break
|
| 199 |
+
return rows
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# ------------------------------------------------------------------------------------------------------------ start
|
| 203 |
+
def cmd_start(a):
|
| 204 |
+
a.codex_auth = a.codex_auth or ("apikey" if a.harness in ROBOT_HARNESSES else "chatgpt")
|
| 205 |
+
if a.harness == "rpent_codex" and a.codex_auth != "apikey":
|
| 206 |
+
sys.exit("Historical RPent adapter supports apikey only")
|
| 207 |
+
if runner_alive(a.batch):
|
| 208 |
+
sys.exit(f"batch {a.batch}: runner already running; stop it first or use another batch name")
|
| 209 |
+
m = load(a.batch) if os.path.exists(mpath(a.batch)) else dict(batch=a.batch, runs=[], superseded=[])
|
| 210 |
+
m.update(concurrency=a.concurrency, barrier=not a.no_barrier, port0=a.port0, run_timeout_s=a.run_timeout)
|
| 211 |
+
reps = a.k if a.indep_reps is None else a.indep_reps
|
| 212 |
+
if a.harness != "ours":
|
| 213 |
+
need = HARNESS_PROVIDER[a.harness]
|
| 214 |
+
if a.provider and a.provider != need:
|
| 215 |
+
sys.exit(f"--harness {a.harness} drives {need} models only (got --provider {a.provider})")
|
| 216 |
+
a.provider = need
|
| 217 |
+
elif not a.provider:
|
| 218 |
+
sys.exit("--provider is required with --harness ours")
|
| 219 |
+
claude_auth = None
|
| 220 |
+
if a.harness.startswith("claude_code"):
|
| 221 |
+
claude_auth = a.claude_auth or ("apikey" if a.harness == "claude_code" else "oauth")
|
| 222 |
+
if claude_auth == "oauth" and a.harness == "claude_code":
|
| 223 |
+
sys.exit("--harness claude_code (--bare) takes only an API key; use claude_code_full for a subscription")
|
| 224 |
+
elif a.claude_auth:
|
| 225 |
+
sys.exit("--claude-auth is for --harness claude_code / claude_code_full")
|
| 226 |
+
if a.jail and a.harness == "ours":
|
| 227 |
+
sys.exit("--jail is for native harnesses (the reference driver runs our own code)")
|
| 228 |
+
if a.red_team and a.harness == "ours":
|
| 229 |
+
sys.exit("--red-team is for native harnesses (lffbench/harnesses/redteam.py)")
|
| 230 |
+
if a.memfree == "upfront":
|
| 231 |
+
conds = [c.strip() for c in (a.conds or "noharness,harness").split(",") if c.strip()]
|
| 232 |
+
else:
|
| 233 |
+
if a.conds and a.conds.replace(" ", "") != "harness":
|
| 234 |
+
sys.exit(f"--conds is for --memfree upfront (--memfree {a.memfree} plans history runs only)")
|
| 235 |
+
if a.memfree == "followup" and a.no_hide_k:
|
| 236 |
+
sys.exit("--memfree followup shares attempt 1 of the history run with the memory-free retries: needs --hide-k")
|
| 237 |
+
conds = ["harness"]
|
| 238 |
+
dossiers = json.load(open(a.dossiers)) if a.dossiers else None
|
| 239 |
+
if dossiers is not None: # task:seed -> record dir (scripts/make_dossier.py); every planned instance needs one
|
| 240 |
+
miss = [f"{spec.split(':')[0]}:{sd}" for spec in a.tasks for sd in spec.split(":")[1].split(",")[:a.seeds_per_task]
|
| 241 |
+
if f"{spec.split(':')[0]}:{sd}" not in dossiers]
|
| 242 |
+
if miss:
|
| 243 |
+
sys.exit(f"--dossiers has no record for {miss}")
|
| 244 |
+
bad = [d for d in dossiers.values() if not os.path.isfile(os.path.join(d, "README.md")) or any(c.isspace() for c in d)]
|
| 245 |
+
if bad:
|
| 246 |
+
sys.exit(f"--dossiers: not a record dir (or path with spaces): {bad}")
|
| 247 |
+
n0 = len(m["runs"])
|
| 248 |
+
for cond in conds: # the order of --conds is the order of the phases
|
| 249 |
+
for spec in a.tasks:
|
| 250 |
+
task, seeds = spec.split(":")
|
| 251 |
+
for seed in seeds.split(",")[:a.seeds_per_task]:
|
| 252 |
+
plan = [("harness", "full", a.k, 0)] if cond == "harness" else \
|
| 253 |
+
[("noharness", "none", 1, i) for i in range(reps)]
|
| 254 |
+
for c, mem, k, rep in plan:
|
| 255 |
+
m["runs"].append(dict(id=next_id(m), task=task, seed=int(seed), provider=a.provider,
|
| 256 |
+
agent_harness=a.harness, api_base_url=a.api_base_url,
|
| 257 |
+
max_budget_usd=a.max_budget_usd, allow_unpinned=a.allow_unpinned,
|
| 258 |
+
jail=a.jail, codex_auth=(("apikey" if a.codex_provider in ("deepseek", "opencode") else a.codex_auth)
|
| 259 |
+
if a.harness in ("codex", *ROBOT_HARNESSES) else None),
|
| 260 |
+
claude_auth=claude_auth,
|
| 261 |
+
codex_catalog=(a.codex_catalog if a.harness in ("codex", *ROBOT_HARNESSES)
|
| 262 |
+
else None),
|
| 263 |
+
**(dict(rpent_sessions=a.rpent_sessions,
|
| 264 |
+
rpent_attempts_per_session=a.rpent_attempts_per_session,
|
| 265 |
+
rpent_max_turns=a.rpent_max_turns)
|
| 266 |
+
if a.harness == "rpent_codex" else {}),
|
| 267 |
+
codex_provider=(a.codex_provider if a.harness == "codex" else None),
|
| 268 |
+
model=a.model, effort=a.effort, cond=c, rep=rep, k=k, mem=mem,
|
| 269 |
+
hide_k=(c == "harness" and not a.no_hide_k), perception=a.perception,
|
| 270 |
+
video=a.video, style="la", feedback=a.feedback, phase=conds.index(cond),
|
| 271 |
+
nominal=a.nominal, followup=(c == "harness" and a.memfree == "followup"),
|
| 272 |
+
arm=a.arm, red_team=a.red_team, dossier=(os.path.abspath(dossiers[f"{task}:{seed}"]) if dossiers else None),
|
| 273 |
+
status="pending"))
|
| 274 |
+
save(a.batch, m)
|
| 275 |
+
print(f"{len(m['runs']) - n0} runs planned ({', '.join(conds)}, --memfree {a.memfree}); manifest {mpath(a.batch)}")
|
| 276 |
+
if a.memfree == "followup":
|
| 277 |
+
print("memory-free retries are added while the batch runs, for instances whose attempt 1 failed")
|
| 278 |
+
print("runner pid", launch_runner(a.batch))
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
# ------------------------------------------------------------------------------------------------------------ runner
|
| 282 |
+
class Runner:
|
| 283 |
+
def __init__(self, batch):
|
| 284 |
+
self.batch = batch
|
| 285 |
+
self.lock = threading.Lock()
|
| 286 |
+
self.m = load(batch)
|
| 287 |
+
self.used_ports = set()
|
| 288 |
+
self.stop = False
|
| 289 |
+
|
| 290 |
+
def update(self, r, **kw):
|
| 291 |
+
with self.lock:
|
| 292 |
+
r.update(kw)
|
| 293 |
+
save(self.batch, self.m)
|
| 294 |
+
|
| 295 |
+
def next_run(self):
|
| 296 |
+
with self.lock:
|
| 297 |
+
runs = self.m["runs"]
|
| 298 |
+
pending = [r for r in runs if r["status"] == "pending"]
|
| 299 |
+
if not pending:
|
| 300 |
+
# a run still going may yet add a memory-free retry (--memfree followup)
|
| 301 |
+
if any(r["status"] in ACTIVE and (r.get("followup") or r.get("chain")) for r in runs):
|
| 302 |
+
return "wait"
|
| 303 |
+
return None
|
| 304 |
+
if self.m.get("barrier", True):
|
| 305 |
+
phase = min(r["phase"] for r in pending)
|
| 306 |
+
if any(r["status"] in ACTIVE and r["phase"] < phase for r in runs):
|
| 307 |
+
return "wait"
|
| 308 |
+
pending = [r for r in pending if r["phase"] == phase]
|
| 309 |
+
if os.path.exists(os.path.join(bdir(self.batch), "PAUSE")):
|
| 310 |
+
return "wait"
|
| 311 |
+
r = pending[0]
|
| 312 |
+
r["status"] = "starting"
|
| 313 |
+
save(self.batch, self.m)
|
| 314 |
+
return r
|
| 315 |
+
|
| 316 |
+
def port(self):
|
| 317 |
+
with self.lock:
|
| 318 |
+
p = int(self.m.get("port0", 14000))
|
| 319 |
+
while p in self.used_ports or not claude_batch.port_free(p):
|
| 320 |
+
p += 1
|
| 321 |
+
self.used_ports.add(p)
|
| 322 |
+
return p
|
| 323 |
+
|
| 324 |
+
def run_one(self, r):
|
| 325 |
+
port = self.port()
|
| 326 |
+
model_tag = re.sub(r"[^A-Za-z0-9.-]+", "-", r["model"])[:40]
|
| 327 |
+
ah = r.get("agent_harness", "ours")
|
| 328 |
+
if ah != "ours":
|
| 329 |
+
model_tag += "-" + ah.replace("_", "")
|
| 330 |
+
tag = (f"{self.batch}-{model_tag}-{r['cond']}{r['rep'] if r['cond'] == 'noharness' else ''}"
|
| 331 |
+
+ ("-hidek" if r["hide_k"] else "") + ("-nominal" if r.get("nominal") else "")
|
| 332 |
+
+ (f"-{r['arm']}" if r.get("arm", "none") != "none" else "") + ("-dossier" if r.get("dossier") else "")
|
| 333 |
+
+ ("-redteam" if r.get("red_team") else ""))
|
| 334 |
+
extra = (" --hide-k" if r["hide_k"] else "") + (" --nominal" if r.get("nominal") else "")
|
| 335 |
+
# docs/14 §6 arms (robot_server --arm / --dossier); LFF_EXTRA_ARGS is word-split, so no spaces in the path
|
| 336 |
+
extra += (f" --arm {r['arm']}" if r.get("arm", "none") != "none" else "") + (f" --dossier {r['dossier']}" if r.get("dossier") else "")
|
| 337 |
+
t0 = time.time()
|
| 338 |
+
try:
|
| 339 |
+
sb, log = claude_batch.start_one(r["task"], r["seed"], r["mem"], r["k"], port, tag, r["perception"],
|
| 340 |
+
r["video"], r["style"], extra.strip(), r["feedback"])
|
| 341 |
+
except Exception as e: # server did not come up
|
| 342 |
+
self.update(r, status="server_failed", error=str(e)[-500:], port=port)
|
| 343 |
+
with self.lock:
|
| 344 |
+
self.used_ports.discard(port)
|
| 345 |
+
return
|
| 346 |
+
self.update(r, status="running", port=port, sandbox=sb, log=log, run=os.path.basename(log), t_start=t0)
|
| 347 |
+
opts = ""
|
| 348 |
+
if r.get("api_base_url"):
|
| 349 |
+
opts += f" --api-base-url {shlex.quote(r['api_base_url'])}"
|
| 350 |
+
if r.get("max_budget_usd"):
|
| 351 |
+
opts += f" --max-budget-usd {r['max_budget_usd']}"
|
| 352 |
+
if r.get("allow_unpinned"):
|
| 353 |
+
opts += " --allow-unpinned"
|
| 354 |
+
if r.get("jail"):
|
| 355 |
+
opts += " --jail"
|
| 356 |
+
if r.get("red_team"):
|
| 357 |
+
opts += " --red-team"
|
| 358 |
+
if r.get("codex_auth"):
|
| 359 |
+
opts += f" --codex-auth {r['codex_auth']}"
|
| 360 |
+
if r.get("claude_auth"):
|
| 361 |
+
opts += f" --claude-auth {r['claude_auth']}"
|
| 362 |
+
if r.get("agent_harness") in ("codex", *ROBOT_HARNESSES) and r.get("agent_harness") != "rpent_codex": # runs planned before 10-20 have no catalog: Codex's native one
|
| 363 |
+
opts += f" --codex-catalog {r.get('codex_catalog') or 'native'}"
|
| 364 |
+
if r.get("codex_provider") in ("deepseek", "opencode"):
|
| 365 |
+
opts += f" --codex-provider {r['codex_provider']}"
|
| 366 |
+
if r.get("agent_harness") == "rpent_codex":
|
| 367 |
+
opts += (f" --codex-catalog {r.get('codex_catalog') or 'generic'}"
|
| 368 |
+
f" --rpent-sessions {r.get('rpent_sessions') or 5}"
|
| 369 |
+
f" --rpent-attempts-per-session {r.get('rpent_attempts_per_session', 1)}"
|
| 370 |
+
f" --rpent-max-turns {r.get('rpent_max_turns') or 100}")
|
| 371 |
+
# every harness (also ours: api_player.py with the same arguments as before, its output still in
|
| 372 |
+
# api_player.log) goes through the adapter layer, which adds harness.json / contract.json / trajectory.jsonl
|
| 373 |
+
player = (f"cd {ROOT} && source run_env.sh >/dev/null 2>&1 && "
|
| 374 |
+
f"{{ [ ! -f {ENV_FILE} ] || {{ set -a && source {ENV_FILE} && set +a; }}; }} && "
|
| 375 |
+
f"exec python scripts/harness_run.py --harness {ah} --session {log}/session.json "
|
| 376 |
+
f"--provider {r['provider']} --model {shlex.quote(r['model'])} --effort {r['effort']} "
|
| 377 |
+
f"--timeout {int(self.m.get('run_timeout_s', 28800))}{opts} > {log}/harness_run.log 2>&1")
|
| 378 |
+
p = subprocess.Popen(["bash", "-c", player], start_new_session=True, stdin=subprocess.DEVNULL,
|
| 379 |
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
| 380 |
+
self.update(r, player_pid=p.pid)
|
| 381 |
+
status = None
|
| 382 |
+
try:
|
| 383 |
+
code = p.wait(timeout=self.m.get("run_timeout_s", 28800))
|
| 384 |
+
except subprocess.TimeoutExpired:
|
| 385 |
+
os.killpg(p.pid, signal.SIGTERM)
|
| 386 |
+
code, status = p.wait(), "timeout"
|
| 387 |
+
self.stop_server(log)
|
| 388 |
+
if status is None:
|
| 389 |
+
status = "stopped" if self.stop else ("done" if code == 0 else "refused" if code == 2 else "failed")
|
| 390 |
+
self.update(r, status=status, exit_code=code, t_end=time.time(), wall_s=round(time.time() - t0, 1))
|
| 391 |
+
with self.lock:
|
| 392 |
+
self.used_ports.discard(port)
|
| 393 |
+
if plan_followup(self.m, r):
|
| 394 |
+
save(self.batch, self.m)
|
| 395 |
+
|
| 396 |
+
@staticmethod
|
| 397 |
+
def stop_server(log):
|
| 398 |
+
pf = os.path.join(log, "server.pid")
|
| 399 |
+
if not os.path.exists(pf):
|
| 400 |
+
return
|
| 401 |
+
pid = int(open(pf).read())
|
| 402 |
+
try:
|
| 403 |
+
os.kill(pid, signal.SIGTERM) # the server closes rollout.mp4 first
|
| 404 |
+
except ProcessLookupError:
|
| 405 |
+
return
|
| 406 |
+
for _ in range(120):
|
| 407 |
+
if not alive(pid):
|
| 408 |
+
return
|
| 409 |
+
time.sleep(0.5)
|
| 410 |
+
|
| 411 |
+
def worker(self):
|
| 412 |
+
while not self.stop:
|
| 413 |
+
r = self.next_run()
|
| 414 |
+
if r is None:
|
| 415 |
+
return
|
| 416 |
+
if r == "wait":
|
| 417 |
+
time.sleep(5)
|
| 418 |
+
continue
|
| 419 |
+
try:
|
| 420 |
+
self.run_one(r)
|
| 421 |
+
except Exception as e: # keep the other workers going
|
| 422 |
+
self.update(r, status="failed", error=f"runner: {type(e).__name__}: {e}"[:500])
|
| 423 |
+
|
| 424 |
+
def main(self):
|
| 425 |
+
os.environ["LFF_RUNS_DIR"] = bdir(self.batch) # claude_batch.start_one puts the run logs here
|
| 426 |
+
for r in self.m["runs"]: # a previous runner died: its half-started runs go back to pending
|
| 427 |
+
if r["status"] in ACTIVE:
|
| 428 |
+
r["status"] = "pending"
|
| 429 |
+
for r in list(self.m["runs"]): # memory-free retries due but not yet planned (runner died, `followup`)
|
| 430 |
+
plan_followup(self.m, r)
|
| 431 |
+
save(self.batch, self.m)
|
| 432 |
+
|
| 433 |
+
def on_term(*_):
|
| 434 |
+
self.stop = True
|
| 435 |
+
with self.lock:
|
| 436 |
+
for r in self.m["runs"]:
|
| 437 |
+
if r["status"] == "running" and r.get("player_pid"):
|
| 438 |
+
try:
|
| 439 |
+
os.killpg(r["player_pid"], signal.SIGTERM)
|
| 440 |
+
except ProcessLookupError:
|
| 441 |
+
pass
|
| 442 |
+
signal.signal(signal.SIGTERM, on_term)
|
| 443 |
+
ths = [threading.Thread(target=self.worker, daemon=True) for _ in range(int(self.m.get("concurrency", 4)))]
|
| 444 |
+
for t in ths:
|
| 445 |
+
t.start()
|
| 446 |
+
time.sleep(2) # stagger server start-ups
|
| 447 |
+
for t in ths:
|
| 448 |
+
t.join()
|
| 449 |
+
print(time.strftime("%F %T"), "runner finished", flush=True)
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
def cmd_runner(a):
|
| 453 |
+
Runner(a.batch).main()
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
# ------------------------------------------------------------------------------------------------------------ views
|
| 457 |
+
def transcript_usage(log):
|
| 458 |
+
tot = dict(calls=0, input_tokens=0, cached_tokens=0, output_tokens=0, api_errors=0, end=None)
|
| 459 |
+
p = os.path.join(log or "", "transcript.jsonl")
|
| 460 |
+
if not os.path.exists(p): # native harness: totals from the unified trajectory
|
| 461 |
+
sys.path.insert(0, ROOT)
|
| 462 |
+
from lffbench.harnesses.trajectory import usage_summary
|
| 463 |
+
u = usage_summary(log)
|
| 464 |
+
if u:
|
| 465 |
+
tot.update(calls=u.get("calls", 0), input_tokens=u.get("total_prompt_tokens") or 0,
|
| 466 |
+
cached_tokens=u.get("total_cached_tokens") or 0,
|
| 467 |
+
output_tokens=u.get("total_completion_tokens") or 0, end=u.get("exit_reason"),
|
| 468 |
+
cost_usd=u.get("total_cost_usd"))
|
| 469 |
+
return tot
|
| 470 |
+
for line in open(p):
|
| 471 |
+
d = json.loads(line)
|
| 472 |
+
if d["ev"] == "assistant":
|
| 473 |
+
tot["calls"] += 1
|
| 474 |
+
for k in ("input_tokens", "cached_tokens", "output_tokens"):
|
| 475 |
+
tot[k] += (d.get("usage") or {}).get(k, 0)
|
| 476 |
+
elif d["ev"] == "api_error":
|
| 477 |
+
tot["api_errors"] += 1
|
| 478 |
+
elif d["ev"] in ("end", "abort"):
|
| 479 |
+
tot["end"] = d["ev"] if d["ev"] == "end" else "abort: " + d.get("reason", "")
|
| 480 |
+
return tot
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
def cmd_status(a):
|
| 484 |
+
m = load(a.batch)
|
| 485 |
+
counts = {}
|
| 486 |
+
for r in m["runs"]:
|
| 487 |
+
counts[r["status"]] = counts.get(r["status"], 0) + 1
|
| 488 |
+
att = ""
|
| 489 |
+
if r.get("log") and os.path.exists(os.path.join(r["log"], "events.jsonl")):
|
| 490 |
+
ev = [json.loads(line) for line in open(os.path.join(r["log"], "events.jsonl"))]
|
| 491 |
+
att = "".join("S" if e["success"] else "F" for e in ev if e["ev"] == "done")
|
| 492 |
+
u = transcript_usage(r.get("log"))
|
| 493 |
+
print(f"{r['id']} {r['status']:13s} {r.get('agent_harness', 'ours'):16s} "
|
| 494 |
+
f"{r['cond']:9s}{r['rep'] if r['cond'] == 'noharness' else '':1} "
|
| 495 |
+
f"{r['task']:24s} s{r['seed']} {att:4s} calls={u['calls']:3d} api_err={u['api_errors']} "
|
| 496 |
+
f"in={u['input_tokens'] / 1e6:.2f}M out={u['output_tokens'] / 1e3:.0f}k {u['end'] or ''}"
|
| 497 |
+
+ (f" (memory-free attempt {r['rep'] + 1} after {r['chain']})" if r.get("chain") else ""))
|
| 498 |
+
print("runner", "alive" if runner_alive(a.batch) else "not running", "|", counts)
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
def cmd_table(a):
|
| 502 |
+
def done_runs(b):
|
| 503 |
+
m = load(b)
|
| 504 |
+
runs = []
|
| 505 |
+
for r in m["runs"]:
|
| 506 |
+
if not (r.get("log") and r["status"] == "done") or r.get("chain"):
|
| 507 |
+
continue
|
| 508 |
+
runs.append(dict(r))
|
| 509 |
+
if r["cond"] == "harness" and r.get("followup"): # its memory-free chain, once finished
|
| 510 |
+
runs += memfree_chain(m, r)
|
| 511 |
+
for r in runs: # the harness is part of the table's "model" column (claude_batch groups by task, model)
|
| 512 |
+
if r.get("agent_harness", "ours") != "ours":
|
| 513 |
+
r["model"] = f"{r['model']} @ {r['agent_harness']}"
|
| 514 |
+
return dict(m, runs=runs)
|
| 515 |
+
claude_batch.load = done_runs # same manifest fields (task, seed, model, cond, rep, k, log): reuse its table
|
| 516 |
+
# token totals: every run once (the rep-0 row of a chain is attempt 1 of a history run, already counted)
|
| 517 |
+
rows = [r for b in a.batch for r in done_runs(b)["runs"] if not r.get("only_attempt")]
|
| 518 |
+
claude_batch.cmd_table(argparse.Namespace(batch=a.batch))
|
| 519 |
+
by = {}
|
| 520 |
+
for r in rows:
|
| 521 |
+
u = transcript_usage(r["log"])
|
| 522 |
+
t = by.setdefault((r.get("agent_harness", "ours"), r["provider"], r["model"], r["effort"]), [0, 0, 0, 0, 0])
|
| 523 |
+
t[0] += 1
|
| 524 |
+
t[1] += u["calls"]
|
| 525 |
+
t[2] += u["input_tokens"]
|
| 526 |
+
t[3] += u["cached_tokens"]
|
| 527 |
+
t[4] += u["output_tokens"]
|
| 528 |
+
print("\n| harness | provider | model | effort | runs done | model calls | input tokens (M) | of which cached (M) | output tokens (M) |")
|
| 529 |
+
print("|---|---|---|---|---|---|---|---|---|")
|
| 530 |
+
for (h, p, mo, e), t in sorted(by.items()):
|
| 531 |
+
print(f"| {h} | {p} | {mo} | {e} | {t[0]} | {t[1]} | {t[2] / 1e6:.1f} | {t[3] / 1e6:.1f} | {t[4] / 1e6:.2f} |")
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
def cmd_contract(a):
|
| 535 |
+
"""contract_sha256 per (task, seed, cond) and batch; an instance whose hash differs between batches is flagged."""
|
| 536 |
+
import collections
|
| 537 |
+
seen = collections.defaultdict(dict)
|
| 538 |
+
for b in a.batch:
|
| 539 |
+
for r in load(b)["runs"]:
|
| 540 |
+
p = os.path.join(r.get("log") or "", "contract.json")
|
| 541 |
+
if r.get("log") and os.path.exists(p):
|
| 542 |
+
sha = json.load(open(p))["contract_sha256"]
|
| 543 |
+
seen[(r["task"], r["seed"], r["cond"])].setdefault(b, set()).add(sha)
|
| 544 |
+
bad = 0
|
| 545 |
+
print("| task | seed | cond | " + " | ".join(a.batch) + " | same |")
|
| 546 |
+
print("|---|---|---|" + "---|" * len(a.batch) + "---|")
|
| 547 |
+
for (task, seed, cond), per in sorted(seen.items()):
|
| 548 |
+
shas = set().union(*per.values())
|
| 549 |
+
same = len(shas) == 1
|
| 550 |
+
bad += not same
|
| 551 |
+
cells = [",".join(sorted(x[:12] for x in per.get(b, []))) or "-" for b in a.batch]
|
| 552 |
+
print(f"| {task} | {seed} | {cond} | " + " | ".join(cells) + f" | {'yes' if same else '**NO**'} |")
|
| 553 |
+
print(f"\n{len(seen)} instance/condition rows, {bad} with differing contracts")
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
def cmd_stop(a):
|
| 557 |
+
pf = os.path.join(bdir(a.batch), "runner.pid")
|
| 558 |
+
if os.path.exists(pf) and alive(open(pf).read().strip()):
|
| 559 |
+
os.kill(int(open(pf).read().strip()), signal.SIGTERM) # the runner stops its players and servers
|
| 560 |
+
for _ in range(240):
|
| 561 |
+
if not runner_alive(a.batch):
|
| 562 |
+
break
|
| 563 |
+
time.sleep(0.5)
|
| 564 |
+
m = load(a.batch)
|
| 565 |
+
for r in m["runs"]: # anything left over (runner killed hard)
|
| 566 |
+
if r["status"] in ACTIVE:
|
| 567 |
+
if r.get("player_pid"):
|
| 568 |
+
try:
|
| 569 |
+
os.killpg(r["player_pid"], signal.SIGTERM)
|
| 570 |
+
except ProcessLookupError:
|
| 571 |
+
pass
|
| 572 |
+
if r.get("log"):
|
| 573 |
+
Runner.stop_server(r["log"])
|
| 574 |
+
r["status"] = "stopped"
|
| 575 |
+
save(a.batch, m)
|
| 576 |
+
print("stopped")
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
def cmd_retry(a):
|
| 580 |
+
if runner_alive(a.batch):
|
| 581 |
+
sys.exit("runner still running: stop it first")
|
| 582 |
+
m = load(a.batch)
|
| 583 |
+
reset = []
|
| 584 |
+
for r in m["runs"]:
|
| 585 |
+
if (a.runs and (r.get("run") in a.runs or r["id"] in a.runs)) or (not a.runs and r["status"] in RETRYABLE):
|
| 586 |
+
if r.get("log"):
|
| 587 |
+
m.setdefault("superseded", []).append(dict(r))
|
| 588 |
+
for k in ("port", "sandbox", "log", "run", "player_pid", "exit_code", "t_start", "t_end", "wall_s", "error"):
|
| 589 |
+
r.pop(k, None)
|
| 590 |
+
r["status"] = "pending"
|
| 591 |
+
reset.append(r)
|
| 592 |
+
# memory-free retries planned after a run that is now re-run were based on attempts that no longer count
|
| 593 |
+
stale = [x for x in m["runs"] if x.get("chain") and all(x is not y for y in reset) and any(
|
| 594 |
+
x["chain"] == y["id"] or (x["chain"] == y.get("chain") and x["rep"] > y["rep"]) for y in reset)]
|
| 595 |
+
for x in stale:
|
| 596 |
+
m["runs"].remove(x)
|
| 597 |
+
if x.get("log"):
|
| 598 |
+
m.setdefault("superseded", []).append(dict(x, superseded_because="earlier attempt of its chain re-run"))
|
| 599 |
+
save(a.batch, m)
|
| 600 |
+
print(len(reset), "runs reset to pending" + (f", {len(stale)} memory-free retries after them dropped" if stale else "")
|
| 601 |
+
+ "; runner pid", launch_runner(a.batch))
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
def cmd_followup(a):
|
| 605 |
+
"""Switch a batch to --memfree followup: mark its --hide-k history runs and plan the memory-free retries due for
|
| 606 |
+
those already done. `retry` then starts the runner (and re-runs failed / stopped runs)."""
|
| 607 |
+
if runner_alive(a.batch):
|
| 608 |
+
sys.exit("runner still running: stop it first")
|
| 609 |
+
m = load(a.batch)
|
| 610 |
+
marked = left = 0
|
| 611 |
+
for r in m["runs"]:
|
| 612 |
+
if r["cond"] == "harness" and not r.get("followup"):
|
| 613 |
+
if r.get("hide_k"):
|
| 614 |
+
r["followup"] = True
|
| 615 |
+
marked += 1
|
| 616 |
+
else:
|
| 617 |
+
left += 1
|
| 618 |
+
new = [x for r in list(m["runs"]) for x in [plan_followup(m, r)] if x]
|
| 619 |
+
save(a.batch, m)
|
| 620 |
+
print(f"{marked} history runs switched to --memfree followup"
|
| 621 |
+
+ (f" ({left} without --hide-k left out: their attempt 1 is not a fresh agent's)" if left else "")
|
| 622 |
+
+ f"; {len(new)} memory-free retries planned")
|
| 623 |
+
print(f"start the runner with: python scripts/api_batch.py retry --batch {a.batch}")
|
| 624 |
+
|
| 625 |
+
|
| 626 |
+
def main():
|
| 627 |
+
ap = argparse.ArgumentParser()
|
| 628 |
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
| 629 |
+
s = sub.add_parser("start")
|
| 630 |
+
s.add_argument("--batch", required=True)
|
| 631 |
+
s.add_argument("--harness", default="ours", choices=NAMES,
|
| 632 |
+
help="agent harness (docs/15); native harnesses imply the provider; rpent_codex = RPent on Codex "
|
| 633 |
+
"(docs/18), OpenAI API key only (LFF_OPENAI_API_KEY)")
|
| 634 |
+
s.add_argument("--provider", default=None, choices=["openai", "anthropic", "gemini", "chat"],
|
| 635 |
+
help="required for --harness ours")
|
| 636 |
+
s.add_argument("--api-base-url", default=None, help="native harnesses: model API endpoint (see harness_run.py)")
|
| 637 |
+
s.add_argument("--max-budget-usd", type=float, default=None, help="claude_code*: per-run dollar cap")
|
| 638 |
+
s.add_argument("--allow-unpinned", action="store_true", help="native harnesses: launch without a pin")
|
| 639 |
+
s.add_argument("--codex-auth", default=None, choices=["chatgpt", "apikey"],
|
| 640 |
+
help="Codex authentication: chatgpt defaults for codex; apikey defaults for Robot Harnesses. "
|
| 641 |
+
"SenseNova/EmbodiedEvo also support chatgpt; historical RPent is apikey only")
|
| 642 |
+
s.add_argument("--claude-auth", default=None, choices=["oauth", "apikey"],
|
| 643 |
+
help="claude_code*: subscription token (default for claude_code_full) or ANTHROPIC_API_KEY "
|
| 644 |
+
"(claude_code, --bare: apikey only)")
|
| 645 |
+
s.add_argument("--codex-provider", default="openai", choices=["openai", "deepseek", "opencode"],
|
| 646 |
+
help="codex: model provider; deepseek / opencode (OpenCode Go) imply --codex-auth apikey "
|
| 647 |
+
"(see harness_run.py)")
|
| 648 |
+
s.add_argument("--codex-catalog", default="generic", choices=["generic", "native"],
|
| 649 |
+
help="codex: model configuration, the main table's shared one (default) or Codex's native one "
|
| 650 |
+
"(control; see lffbench/harnesses/codex.py)")
|
| 651 |
+
s.add_argument("--rpent-sessions", type=int, default=5, help="rpent_codex: planner sessions per episode")
|
| 652 |
+
s.add_argument("--rpent-attempts-per-session", type=int, default=1,
|
| 653 |
+
help="rpent_codex: attempts one session may use (1 = variant H, default; 0 = no limit)")
|
| 654 |
+
s.add_argument("--rpent-max-turns", type=int, default=100, help="rpent_codex: model responses per session")
|
| 655 |
+
s.add_argument("--jail", action="store_true",
|
| 656 |
+
help="native harnesses: run the CLI in the native-harness jail (docs/15 §3.4, lffbench/harnesses/jail.py)")
|
| 657 |
+
s.add_argument("--model", required=True)
|
| 658 |
+
s.add_argument("--effort", default="high")
|
| 659 |
+
s.add_argument("--tasks", nargs="+", required=True, help="task:seed,seed ...")
|
| 660 |
+
s.add_argument("--k", type=int, default=3)
|
| 661 |
+
s.add_argument("--seeds-per-task", type=int, default=None, help="only the first N seeds of each task:seeds")
|
| 662 |
+
s.add_argument("--memfree", default="followup", choices=["followup", "upfront", "none"],
|
| 663 |
+
help="memory-free retries: followup (default) = fresh single-attempt agents only after the history "
|
| 664 |
+
"run's attempt 1 failed, one at a time, up to k attempts in all, stop at the first success; "
|
| 665 |
+
"upfront = --indep-reps independent runs per instance before the history runs; none = no "
|
| 666 |
+
"memory-free retries (see the module docstring)")
|
| 667 |
+
s.add_argument("--indep-reps", type=int, default=None, help="--memfree upfront: independent runs per instance (default k)")
|
| 668 |
+
s.add_argument("--conds", default=None, help="--memfree upfront: conditions in phase order (default noharness,harness)")
|
| 669 |
+
s.add_argument("--no-barrier", action="store_true", help="do not wait for one phase to finish before the next")
|
| 670 |
+
s.add_argument("--no-hide-k", action="store_true", help="history runs: README / status show all k attempts")
|
| 671 |
+
s.add_argument("--concurrency", type=int, default=4)
|
| 672 |
+
s.add_argument("--port0", type=int, default=14000)
|
| 673 |
+
s.add_argument("--run-timeout", type=int, default=28800,
|
| 674 |
+
help="seconds per run before the player is killed (default 8 h: a long-horizon history run can need 300+ model calls)")
|
| 675 |
+
s.add_argument("--perception", default="rgb", choices=["rgb", "rgbd"])
|
| 676 |
+
s.add_argument("--video", action="store_true")
|
| 677 |
+
s.add_argument("--feedback", default="F1", choices=["F0", "F1", "F2"])
|
| 678 |
+
s.add_argument("--nominal", action="store_true", help="L1 control: hidden calibration error removed")
|
| 679 |
+
s.add_argument("--arm", default="none", choices=["none", "h0", "hplus", "twin"],
|
| 680 |
+
help="docs/14 §6 controlled arm for every run: twin = same layout, other value of the hidden variable")
|
| 681 |
+
s.add_argument("--red-team", action="store_true",
|
| 682 |
+
help="adversarial acceptance runs (lffbench/harnesses/redteam.py): the agent is told to get a success "
|
| 683 |
+
"without doing the task; own contract; read with scripts/redteam_report.py")
|
| 684 |
+
s.add_argument("--dossiers", default=None,
|
| 685 |
+
help="JSON {\"task:seed\": record dir from scripts/make_dossier.py}: each run gets that record in "
|
| 686 |
+
"history/ and a README section saying an earlier attempt failed (own vs mismatched history)")
|
| 687 |
+
r = sub.add_parser("_runner")
|
| 688 |
+
r.add_argument("--batch", required=True)
|
| 689 |
+
for name in ("status", "stop", "followup"):
|
| 690 |
+
sub.add_parser(name).add_argument("--batch", required=True)
|
| 691 |
+
t = sub.add_parser("table")
|
| 692 |
+
t.add_argument("--batch", nargs="+", required=True)
|
| 693 |
+
ct = sub.add_parser("contract")
|
| 694 |
+
ct.add_argument("--batch", nargs="+", required=True)
|
| 695 |
+
rt = sub.add_parser("retry")
|
| 696 |
+
rt.add_argument("--batch", required=True)
|
| 697 |
+
rt.add_argument("--runs", nargs="*", default=[])
|
| 698 |
+
a = ap.parse_args()
|
| 699 |
+
dict(start=cmd_start, _runner=cmd_runner, status=cmd_status, table=cmd_table, stop=cmd_stop, retry=cmd_retry,
|
| 700 |
+
contract=cmd_contract, followup=cmd_followup)[a.cmd](a)
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
if __name__ == "__main__":
|
| 704 |
+
main()
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/api_player.py
ADDED
|
@@ -0,0 +1,446 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Drive one robot_server session with a model through its provider's official API (the unified harness).
|
| 2 |
+
|
| 3 |
+
Every provider gets exactly the same input: the sandbox README as its instructions and the same tools; only the
|
| 4 |
+
wire format differs (lffbench/agent/backends/). After every command the JSON report is returned as the tool output.
|
| 5 |
+
Nothing else is sent: no files, no memory, no paths outside the sandbox.
|
| 6 |
+
|
| 7 |
+
python scripts/api_player.py --session runs/<...>/session.json --provider anthropic --model claude-opus-5-5 --effort high --style la
|
| 8 |
+
|
| 9 |
+
Providers (key / endpoint from the environment, e.g. `set -a; source .env; set +a`):
|
| 10 |
+
openai OpenAI Responses API OPENAI_API_KEY [OPENAI_BASE_URL]
|
| 11 |
+
anthropic Anthropic Messages API ANTHROPIC_API_KEY
|
| 12 |
+
gemini Gemini API (google-genai) GEMINI_API_KEY
|
| 13 |
+
chat any OpenAI-compatible Chat Completions endpoint (vLLM / SGLang for open models, xAI, ...)
|
| 14 |
+
LFF_CHAT_BASE_URL, LFF_CHAT_API_KEY
|
| 15 |
+
`--effort` is the provider's reasoning knob: OpenAI reasoning.effort, Anthropic output_config.effort, Gemini
|
| 16 |
+
thinking_level, chat: reasoning_effort (omitted when "none").
|
| 17 |
+
|
| 18 |
+
--style la (LIBERO-Agent-style workspace, the paper's interface): the sandbox is the agent's episode workspace. Besides
|
| 19 |
+
`robot` the model gets `shell` (a command run in the workspace inside a jail: no network, robot server unreachable,
|
| 20 |
+
host data hidden, see /opt/lffjail/jail_inner.sh) and `view_images` (any image file in the workspace, including ones
|
| 21 |
+
it made itself). Tool calls per attempt are capped (agent_iface.json: max_tool_calls); at the cap the attempt is
|
| 22 |
+
finished for it.
|
| 23 |
+
Logs in the run's log dir: transcript.jsonl (every request / reply / tool call), final_report.md.
|
| 24 |
+
"""
|
| 25 |
+
import argparse
|
| 26 |
+
import base64
|
| 27 |
+
import json
|
| 28 |
+
import os
|
| 29 |
+
import shlex
|
| 30 |
+
import subprocess
|
| 31 |
+
import sys
|
| 32 |
+
import time
|
| 33 |
+
import traceback
|
| 34 |
+
import urllib.request
|
| 35 |
+
|
| 36 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 37 |
+
sys.path.insert(0, ROOT)
|
| 38 |
+
if not os.environ.get("SSL_CERT_FILE") and os.path.exists("/etc/ssl/certs/ca-certificates.crt"):
|
| 39 |
+
os.environ["SSL_CERT_FILE"] = "/etc/ssl/certs/ca-certificates.crt" # the venv's own CA bundle lacks the proxy's issuer
|
| 40 |
+
|
| 41 |
+
from lffbench.agent.backends import make_backend # noqa: E402
|
| 42 |
+
from lffbench.agent.context import Conversation # noqa: E402
|
| 43 |
+
|
| 44 |
+
PROVIDERS = ("openai", "anthropic", "gemini", "chat")
|
| 45 |
+
|
| 46 |
+
TOOL = dict(
|
| 47 |
+
name="robot",
|
| 48 |
+
description=("Run one robot command. `command` is exactly what you would type after `./robot` in the "
|
| 49 |
+
"instructions (e.g. `observe`). Returns the command's JSON report."),
|
| 50 |
+
parameters=dict(type="object", properties=dict(command=dict(type="string", description="the robot command")),
|
| 51 |
+
required=["command"], additionalProperties=False),
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
VIEW_TOOL = dict(
|
| 55 |
+
name="view_images",
|
| 56 |
+
description=("Look at camera images the robot has written. `paths` are image paths exactly as printed by robot "
|
| 57 |
+
"commands (e.g. obs/a1_s003_wrist.jpg); any image of this episode can be viewed again. The images "
|
| 58 |
+
"are attached right after this call."),
|
| 59 |
+
parameters=dict(type="object", properties=dict(paths=dict(type="array", items=dict(type="string"),
|
| 60 |
+
description="image paths to view")),
|
| 61 |
+
required=["paths"], additionalProperties=False),
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
TOOL_LA = dict(
|
| 65 |
+
name="robot",
|
| 66 |
+
description=("Run one robot command. `command` is exactly one of the robot commands in the instructions, e.g. "
|
| 67 |
+
"`status` or `move_eef z=1.0 gripper=open`. Returns the command's JSON report, including the paths "
|
| 68 |
+
"of the new observation files."),
|
| 69 |
+
parameters=TOOL["parameters"],
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
SHELL_TOOL = dict(
|
| 73 |
+
name="shell",
|
| 74 |
+
description=("Run a shell command (bash) in your workspace directory, e.g. `ls obs` or `python3 analyse.py`. "
|
| 75 |
+
"python3 has numpy, scipy, Pillow and OpenCV. No network; programs cannot control the robot. "
|
| 76 |
+
"Time limit 60 s per call. Returns the exit code and the combined stdout/stderr (long output is "
|
| 77 |
+
"truncated in the middle)."),
|
| 78 |
+
parameters=dict(type="object", properties=dict(command=dict(type="string", description="the bash command")),
|
| 79 |
+
required=["command"], additionalProperties=False),
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
VIEW_TOOL_LA = dict(
|
| 83 |
+
name="view_images",
|
| 84 |
+
description=("Look at image files in your workspace (.jpg / .jpeg / .png), e.g. obs/a1_s003_wrist.jpg or an image "
|
| 85 |
+
"you made yourself; paths are relative to the workspace. At most 8 per call. The images are attached "
|
| 86 |
+
"right after this call."),
|
| 87 |
+
parameters=dict(type="object", properties=dict(paths=dict(type="array", items=dict(type="string"),
|
| 88 |
+
description="image paths to view")),
|
| 89 |
+
required=["paths"], additionalProperties=False),
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
PREAMBLE_LA = ("You control the robot described below and work in the workspace described below. Tools: `robot` runs "
|
| 93 |
+
"one robot command per call (the argument is exactly a command from the instructions, e.g. `status`); "
|
| 94 |
+
"`shell` runs a shell command in your workspace; `view_images` shows you image files from the "
|
| 95 |
+
"workspace. When a robot command tells you to stop or that the episode is over, stop calling tools and "
|
| 96 |
+
"reply with a short report: what you did (key commands and parameter values), what you observed, any "
|
| 97 |
+
"feedback you got, and how you changed your approach.\n\n")
|
| 98 |
+
|
| 99 |
+
PREAMBLE = ("You control the robot described below. You act only through the `robot` tool, one command per call. "
|
| 100 |
+
"When a command tells you to stop or that the episode is over, stop calling the tool and reply with a "
|
| 101 |
+
"short report: what you did (key commands and parameter values), what you observed, any feedback you "
|
| 102 |
+
"got, and how you changed your approach.\n\n")
|
| 103 |
+
|
| 104 |
+
JAIL = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "jail", "jail_inner.sh")
|
| 105 |
+
SHELL_TIMEOUT = 60
|
| 106 |
+
SHELL_MAX_CHARS = 12000
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def run_shell(workspace, command):
|
| 110 |
+
"""Run `command` in the jailed workspace; returns (exit code, output text, seconds)."""
|
| 111 |
+
t0 = time.time()
|
| 112 |
+
argv = ["unshare", "--user", "--map-root-user", "--mount", "--net", "--", JAIL, workspace,
|
| 113 |
+
"timeout", "-k", "5", str(SHELL_TIMEOUT), "bash", "-c", command]
|
| 114 |
+
try:
|
| 115 |
+
r = subprocess.run(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
| 116 |
+
timeout=SHELL_TIMEOUT + 30)
|
| 117 |
+
code, out = r.returncode, r.stdout.decode("utf-8", "replace")
|
| 118 |
+
except subprocess.TimeoutExpired as e:
|
| 119 |
+
code, out = 124, (e.stdout or b"").decode("utf-8", "replace")
|
| 120 |
+
if code == 124:
|
| 121 |
+
out += f"\n[killed: time limit of {SHELL_TIMEOUT} s]"
|
| 122 |
+
if len(out) > SHELL_MAX_CHARS:
|
| 123 |
+
h = SHELL_MAX_CHARS // 2
|
| 124 |
+
out = out[:h] + f"\n[... {len(out) - SHELL_MAX_CHARS} characters truncated ...]\n" + out[-h:]
|
| 125 |
+
return code, out, time.time() - t0
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def workspace_image(workspace, rel):
|
| 129 |
+
"""Resolve a model-given image path inside the workspace (no escaping via .. or symlinks); None if not allowed."""
|
| 130 |
+
if not isinstance(rel, str) or not rel or rel.startswith("/"):
|
| 131 |
+
return None
|
| 132 |
+
root = os.path.realpath(workspace)
|
| 133 |
+
full = os.path.realpath(os.path.join(root, rel))
|
| 134 |
+
if not full.startswith(root + os.sep) or not os.path.isfile(full):
|
| 135 |
+
return None
|
| 136 |
+
if os.path.splitext(full)[1].lower() not in (".jpg", ".jpeg", ".png") or os.path.getsize(full) > 8 * 2 ** 20:
|
| 137 |
+
return None
|
| 138 |
+
return full
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
class FileImage:
|
| 142 |
+
"""The exact JPEG bytes the server wrote (same bytes a Claude Code player reads)."""
|
| 143 |
+
|
| 144 |
+
def __init__(self, path):
|
| 145 |
+
self.path = path
|
| 146 |
+
base = os.path.basename(path)
|
| 147 |
+
self.camera = "wrist" if "wrist" in base else ("agentview" if "agentview" in base else "camera")
|
| 148 |
+
self.label = base
|
| 149 |
+
|
| 150 |
+
def data_url(self, quality=None):
|
| 151 |
+
mime = "image/png" if self.path.lower().endswith(".png") else "image/jpeg"
|
| 152 |
+
with open(self.path, "rb") as f:
|
| 153 |
+
return f"data:{mime};base64," + base64.b64encode(f.read()).decode()
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def parse_command(s):
|
| 157 |
+
s = s.strip()
|
| 158 |
+
s = s.removeprefix("./robot").strip() if s.startswith("./robot") else (s[len("robot "):] if s.startswith("robot ") else s)
|
| 159 |
+
toks = shlex.split(s.strip())
|
| 160 |
+
if not toks:
|
| 161 |
+
return "help", {}
|
| 162 |
+
cmd, args = toks[0], {}
|
| 163 |
+
for a in toks[1:]:
|
| 164 |
+
if "=" not in a:
|
| 165 |
+
return None, f"bad argument {a!r}: use key=value"
|
| 166 |
+
k, v = a.split("=", 1)
|
| 167 |
+
try:
|
| 168 |
+
args[k] = json.loads(v)
|
| 169 |
+
except ValueError:
|
| 170 |
+
args[k] = v
|
| 171 |
+
return cmd, args
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def call_server(port, token, cmd, args):
|
| 175 |
+
req = urllib.request.Request(f"http://127.0.0.1:{port}/call", data=json.dumps({"cmd": cmd, "args": args}).encode(),
|
| 176 |
+
headers={"Content-Type": "application/json", "X-Token": token})
|
| 177 |
+
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
| 178 |
+
with opener.open(req, timeout=900) as r:
|
| 179 |
+
return r.read().decode()
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
MAX_NO_TOOL = 3 # nudges in a row for replies without a tool call; the next such reply ends the run
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def continue_nudge(port, token, stx=None):
|
| 186 |
+
"""The user message sent when the model replies without a tool call before the episode is over. Native harnesses
|
| 187 |
+
send the same text when their CLI exits early (scripts/harness_run.py). stx: a status reply already fetched."""
|
| 188 |
+
try: # tell it where it is: models sometimes believe the episode ended after a failed attempt
|
| 189 |
+
if stx is None:
|
| 190 |
+
stx = json.loads(call_server(port, token, "status", {}))
|
| 191 |
+
where = (f" You are in attempt {stx.get('attempt')} of {stx.get('max_attempts')}; the episode is NOT over."
|
| 192 |
+
if stx.get("attempt") else "")
|
| 193 |
+
except Exception:
|
| 194 |
+
where = ""
|
| 195 |
+
return "Continue: issue the next robot command with the `robot` tool." + where
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def build_backend(a, v2):
|
| 199 |
+
"""The model backend for --provider; image pruning only where the provider allows editing earlier turns."""
|
| 200 |
+
if a.provider == "openai":
|
| 201 |
+
return make_backend("openai", model=a.model, reasoning_effort=a.effort, reasoning_summary="auto",
|
| 202 |
+
max_live_images=None if v2 else a.max_live_images, cache_breakpoints="none", max_retries=1)
|
| 203 |
+
if a.provider == "anthropic": # append-only history (thinking blocks are bound to it): never prune
|
| 204 |
+
return make_backend("anthropic", model=a.model, effort=a.effort, max_live_images=None)
|
| 205 |
+
if a.provider == "gemini":
|
| 206 |
+
return make_backend("gemini", model=a.model, thinking_level=a.effort,
|
| 207 |
+
max_live_images=None if v2 else a.max_live_images)
|
| 208 |
+
extra = None if a.effort in ("", "none", None) else dict(reasoning_effort=a.effort)
|
| 209 |
+
return make_backend("chat", model=a.model, max_tokens=a.max_output_tokens, temperature=None, extra_body=extra,
|
| 210 |
+
max_live_images=None if v2 else a.max_live_images)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def context_overflow(err):
|
| 214 |
+
"""The request no longer fits: token limit (OpenAI / Anthropic / Gemini / Kimi wordings) or too many images."""
|
| 215 |
+
e = err.lower()
|
| 216 |
+
return (("context" in e and ("length" in e or "window" in e or "too long" in e)) or "prompt is too long" in e
|
| 217 |
+
or ("exceed" in e and "token" in e) or "too many images" in e or "maximum number of images" in e)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def live_images(conv):
|
| 221 |
+
return sum(1 for it in conv.items if it["kind"] == "user" and it.get("live") for p in it["parts"]
|
| 222 |
+
if p["type"] == "image")
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def main(argv=None, default_provider=None, transcript_name="transcript.jsonl"):
|
| 226 |
+
ap = argparse.ArgumentParser()
|
| 227 |
+
ap.add_argument("--session", required=True, help="session.json written by start_robot_session.sh")
|
| 228 |
+
ap.add_argument("--provider", default=default_provider, choices=PROVIDERS, required=default_provider is None)
|
| 229 |
+
ap.add_argument("--model", default="gpt-6-astra" if default_provider == "openai" else None,
|
| 230 |
+
required=default_provider is None)
|
| 231 |
+
ap.add_argument("--effort", default="medium")
|
| 232 |
+
ap.add_argument("--max-turns", type=int, default=400)
|
| 233 |
+
ap.add_argument("--max-live-images", type=int, default=16)
|
| 234 |
+
ap.add_argument("--max-output-tokens", type=int, default=32768, help="chat provider only")
|
| 235 |
+
ap.add_argument("--api-retries", type=int, default=8,
|
| 236 |
+
help="retries of a failed API call before giving up (back-off 5 s doubling to 120 s: ~9 min)")
|
| 237 |
+
ap.add_argument("--max-request-images", type=int, default=500,
|
| 238 |
+
help="when the conversation holds more viewed images than this, switch to the context-full "
|
| 239 |
+
"policy (Claude through a gateway failed at 601 images, 2026-10-15)")
|
| 240 |
+
ap.add_argument("--style", default="v1", choices=["v1", "v2", "la"],
|
| 241 |
+
help="v2: images are not attached automatically; the model views them on demand with "
|
| 242 |
+
"view_images, and no history is pruned (the agent manages its own context)")
|
| 243 |
+
a = ap.parse_args(argv)
|
| 244 |
+
|
| 245 |
+
sess = json.load(open(a.session))
|
| 246 |
+
sb, port = sess["sandbox"], sess["port"]
|
| 247 |
+
log_dir = os.path.dirname(os.path.abspath(a.session))
|
| 248 |
+
la = a.style == "la"
|
| 249 |
+
if la: # no robot CLI in a la workspace: the token is only in the log dir
|
| 250 |
+
iface = json.load(open(os.path.join(log_dir, "agent_iface.json")))
|
| 251 |
+
token, max_tool_calls = iface["token"], int(iface["max_tool_calls"])
|
| 252 |
+
else:
|
| 253 |
+
token = open(os.path.join(sb, "robot")).read().split('TOKEN = "', 1)[1].split('"', 1)[0]
|
| 254 |
+
readme = open(os.path.join(sb, "README.md")).read()
|
| 255 |
+
tlog = open(os.path.join(log_dir, transcript_name), "a")
|
| 256 |
+
|
| 257 |
+
def log(d):
|
| 258 |
+
d["t"] = time.time()
|
| 259 |
+
tlog.write(json.dumps(d, ensure_ascii=False) + "\n")
|
| 260 |
+
tlog.flush()
|
| 261 |
+
|
| 262 |
+
v2 = a.style in ("v2", "la") # la = v2 robot interface + workspace tools
|
| 263 |
+
tools = [TOOL_LA, SHELL_TOOL, VIEW_TOOL_LA] if la else ([TOOL, VIEW_TOOL] if v2 else [TOOL])
|
| 264 |
+
backend = build_backend(a, v2)
|
| 265 |
+
conv = Conversation((PREAMBLE_LA if la else PREAMBLE) + readme)
|
| 266 |
+
log(dict(ev="start", provider=a.provider, model=a.model, effort=a.effort, style=a.style, backend=backend.config(),
|
| 267 |
+
instructions=conv.system, tools=tools))
|
| 268 |
+
|
| 269 |
+
def images_part(paths, title):
|
| 270 |
+
parts = [dict(type="text", text=title)]
|
| 271 |
+
for p in paths:
|
| 272 |
+
parts.append(dict(type="image", image=FileImage(os.path.join(sb, p))))
|
| 273 |
+
return parts
|
| 274 |
+
|
| 275 |
+
st = json.loads(call_server(port, token, "status", {}))
|
| 276 |
+
if v2: # images stay files; the model decides what to look at
|
| 277 |
+
first = [dict(type="text", text=("Begin. Current status (robot command `status`):\n" if la else
|
| 278 |
+
"Begin. Current status (`./robot status`):\n") + json.dumps(st))]
|
| 279 |
+
else:
|
| 280 |
+
first = [dict(type="text", text="Begin. Current status (`./robot status`):\n" +
|
| 281 |
+
json.dumps({k: v for k, v in st.items() if k != "images"}))]
|
| 282 |
+
first += images_part(st.get("images", []), "Current camera images (agentview, wrist):")[1:]
|
| 283 |
+
conv.add_user(first, live=True)
|
| 284 |
+
log(dict(ev="user", text=first[0]["text"], images=st.get("images", [])))
|
| 285 |
+
|
| 286 |
+
finished, no_tool, report = False, 0, None
|
| 287 |
+
calls_in_attempt = 0 # la: tool calls (robot + shell + view_images) in the current attempt
|
| 288 |
+
usage_tot = dict(input_tokens=0, cached_tokens=0, cache_write_tokens=0, output_tokens=0, reasoning_tokens=0)
|
| 289 |
+
for turn in range(a.max_turns):
|
| 290 |
+
resp, err = None, None
|
| 291 |
+
if v2 and backend.max_live_images is None and live_images(conv) > a.max_request_images:
|
| 292 |
+
backend.max_live_images = 32 # same context-full policy as below, before the request limit is hit
|
| 293 |
+
log(dict(ev="context_overflow", reason="image count", n_images=live_images(conv), keep_images=32))
|
| 294 |
+
for r in range(a.api_retries + 1):
|
| 295 |
+
t0 = time.time()
|
| 296 |
+
try:
|
| 297 |
+
out = backend.act(conv, tools)
|
| 298 |
+
except Exception as e: # flaky endpoint: back off and retry the identical request
|
| 299 |
+
err = f"{type(e).__name__}: {str(e)[:300]}"
|
| 300 |
+
if v2 and context_overflow(err):
|
| 301 |
+
# the context is full (every provider): from now on keep only the newest viewed images
|
| 302 |
+
backend.max_live_images = 32 if backend.max_live_images is None else max(backend.max_live_images // 2, 4)
|
| 303 |
+
log(dict(ev="context_overflow", reason=err[:120], keep_images=backend.max_live_images))
|
| 304 |
+
log(dict(ev="api_error", turn=turn, retry=r, error=err, dt=time.time() - t0))
|
| 305 |
+
time.sleep(min(120, 5 * 2 ** r))
|
| 306 |
+
continue
|
| 307 |
+
if out.status == "refusal": # the provider declined: no fallback model (it would change the model under test)
|
| 308 |
+
resp, err = out, out.error
|
| 309 |
+
break
|
| 310 |
+
if out.status == "incomplete": # truncated / malformed turn: not appended, ask again
|
| 311 |
+
err = out.error
|
| 312 |
+
log(dict(ev="api_error", turn=turn, retry=r, error=err, dt=time.time() - t0, usage=out.usage))
|
| 313 |
+
continue
|
| 314 |
+
resp = out
|
| 315 |
+
break
|
| 316 |
+
if resp is None:
|
| 317 |
+
log(dict(ev="abort", reason="api failed", error=err))
|
| 318 |
+
print("ABORT api failed:", err, flush=True)
|
| 319 |
+
sys.exit(3)
|
| 320 |
+
for k in usage_tot:
|
| 321 |
+
usage_tot[k] += resp.usage.get(k, 0)
|
| 322 |
+
if resp.status == "refusal":
|
| 323 |
+
log(dict(ev="refusal", turn=turn, latency_s=resp.latency_s, usage=resp.usage, error=resp.error,
|
| 324 |
+
text=resp.text))
|
| 325 |
+
log(dict(ev="abort", reason="refusal", error=resp.error))
|
| 326 |
+
print("ABORT refusal:", resp.error, flush=True)
|
| 327 |
+
break
|
| 328 |
+
conv.add_assistant(resp.text, resp.tool_calls, raw=resp.raw, backend=backend.name)
|
| 329 |
+
log(dict(ev="assistant", turn=turn, latency_s=resp.latency_s, usage=resp.usage, text=resp.text,
|
| 330 |
+
reasoning_summary=resp.reasoning_summary,
|
| 331 |
+
reasoning_summary_status="recorded" if resp.reasoning_summary else "not_returned",
|
| 332 |
+
status=resp.status, error=resp.error,
|
| 333 |
+
tool_calls=[dict(id=c.id, name=c.name, arguments=c.arguments) for c in resp.tool_calls],
|
| 334 |
+
request_stats=resp.request_stats))
|
| 335 |
+
if finished:
|
| 336 |
+
report = resp.text
|
| 337 |
+
break
|
| 338 |
+
if not resp.tool_calls:
|
| 339 |
+
no_tool += 1
|
| 340 |
+
nudge = continue_nudge(port, token)
|
| 341 |
+
if no_tool > MAX_NO_TOOL:
|
| 342 |
+
log(dict(ev="abort", reason="no tool call 4 times"))
|
| 343 |
+
break
|
| 344 |
+
conv.add_user([dict(type="text", text=nudge)], live=False)
|
| 345 |
+
log(dict(ev="user", text=nudge))
|
| 346 |
+
continue
|
| 347 |
+
no_tool = 0
|
| 348 |
+
for c in resp.tool_calls:
|
| 349 |
+
if la and not finished:
|
| 350 |
+
calls_in_attempt += 1
|
| 351 |
+
if la and c.name == "shell":
|
| 352 |
+
code, out, dt = run_shell(sb, str(c.arguments.get("command", "")))
|
| 353 |
+
out_text = json.dumps(dict(exit_code=code, output=out))
|
| 354 |
+
conv.add_tool_output(c.id, c.name, out_text)
|
| 355 |
+
log(dict(ev="tool", turn=turn, command="shell: " + str(c.arguments.get("command", "")), output=out_text,
|
| 356 |
+
shell_s=round(dt, 2)))
|
| 357 |
+
continue
|
| 358 |
+
if la and c.name == "view_images":
|
| 359 |
+
paths = [str(x) for x in (c.arguments.get("paths") or [])][:8]
|
| 360 |
+
full = [(x, workspace_image(sb, x)) for x in paths]
|
| 361 |
+
ok_paths = [x for x, f in full if f]
|
| 362 |
+
out = dict(ok=bool(ok_paths), attached=ok_paths)
|
| 363 |
+
if len(ok_paths) < len(paths):
|
| 364 |
+
out["not_viewable"] = [x for x, f in full if not f]
|
| 365 |
+
conv.add_tool_output(c.id, c.name, json.dumps(out))
|
| 366 |
+
log(dict(ev="tool", turn=turn, command="view_images " + " ".join(paths), output=json.dumps(out), images=ok_paths))
|
| 367 |
+
if ok_paths:
|
| 368 |
+
parts = [dict(type="text", text="Requested images:")]
|
| 369 |
+
for x, f in full:
|
| 370 |
+
if f:
|
| 371 |
+
parts.append(dict(type="image", image=FileImage(f)))
|
| 372 |
+
conv.add_user(parts, live=True)
|
| 373 |
+
continue
|
| 374 |
+
if c.name == "view_images":
|
| 375 |
+
paths = [str(x) for x in (c.arguments.get("paths") or [])][:8]
|
| 376 |
+
ok_paths = [x for x in paths if x.startswith("obs/") and "/.." not in x and ".." not in x
|
| 377 |
+
and os.path.exists(os.path.join(sb, x))]
|
| 378 |
+
bad = [x for x in paths if x not in ok_paths]
|
| 379 |
+
out = dict(ok=bool(ok_paths), attached=ok_paths)
|
| 380 |
+
if bad:
|
| 381 |
+
out["not_found"] = bad
|
| 382 |
+
conv.add_tool_output(c.id, c.name, json.dumps(out))
|
| 383 |
+
log(dict(ev="tool", turn=turn, command="view_images " + " ".join(paths), output=json.dumps(out), images=ok_paths))
|
| 384 |
+
if ok_paths:
|
| 385 |
+
conv.add_user(images_part(ok_paths, "Requested images:"), live=True)
|
| 386 |
+
continue
|
| 387 |
+
cmdline = str(c.arguments.get("command", ""))
|
| 388 |
+
cmd, args = parse_command(cmdline)
|
| 389 |
+
if cmd is None:
|
| 390 |
+
out_text, paths = json.dumps(dict(ok=False, error=args)), []
|
| 391 |
+
else:
|
| 392 |
+
raw = call_server(port, token, cmd, args)
|
| 393 |
+
try:
|
| 394 |
+
rep = json.loads(raw)
|
| 395 |
+
if v2: # keep the image paths in the reply: the model views them itself if it wants
|
| 396 |
+
paths = []
|
| 397 |
+
out_text = json.dumps(rep)
|
| 398 |
+
else:
|
| 399 |
+
paths = rep.pop("images", []) if isinstance(rep, dict) else []
|
| 400 |
+
out_text = json.dumps(rep)
|
| 401 |
+
except ValueError: # help text
|
| 402 |
+
rep, paths, out_text = {}, [], raw
|
| 403 |
+
msg = (rep.get("message", "") + " " + rep.get("error", "")) if isinstance(rep, dict) else ""
|
| 404 |
+
if isinstance(rep, dict) and isinstance(rep.get("attempt_ended"), dict):
|
| 405 |
+
msg += " " + rep["attempt_ended"].get("message", "")
|
| 406 |
+
if "episode is over" in msg or "No attempts left" in msg or "Stop now" in msg:
|
| 407 |
+
finished = True
|
| 408 |
+
if isinstance(rep, dict) and (rep.get("ended") or isinstance(rep.get("attempt_ended"), dict)):
|
| 409 |
+
calls_in_attempt = 0
|
| 410 |
+
conv.add_tool_output(c.id, c.name, out_text)
|
| 411 |
+
log(dict(ev="tool", turn=turn, command=cmdline, output=out_text, images=paths))
|
| 412 |
+
if paths and not v2:
|
| 413 |
+
conv.add_user(images_part(paths, f"Camera images after `{cmdline}` (agentview, wrist):"), live=True)
|
| 414 |
+
if la and not finished and calls_in_attempt >= max_tool_calls:
|
| 415 |
+
raw = call_server(port, token, "finish", dict(reason="tool-call budget used up (automatic)"))
|
| 416 |
+
try:
|
| 417 |
+
rep = json.loads(raw)
|
| 418 |
+
except ValueError:
|
| 419 |
+
rep = dict(raw=raw)
|
| 420 |
+
msg = rep.get("message", "") + " " + rep.get("error", "")
|
| 421 |
+
if "episode is over" in msg or "No attempts left" in msg or "Stop now" in msg:
|
| 422 |
+
finished = True
|
| 423 |
+
calls_in_attempt = 0
|
| 424 |
+
note = (f"The budget of {max_tool_calls} tool calls for this attempt was used up, so the attempt was "
|
| 425 |
+
f"finished automatically. Result: " + json.dumps(rep))
|
| 426 |
+
conv.add_user([dict(type="text", text=note)], live=False)
|
| 427 |
+
log(dict(ev="user", text=note, auto_finish=True))
|
| 428 |
+
if finished:
|
| 429 |
+
ask = "Stop now and reply with your short report (no more tool calls)."
|
| 430 |
+
conv.add_user([dict(type="text", text=ask)], live=False)
|
| 431 |
+
log(dict(ev="user", text=ask))
|
| 432 |
+
if report:
|
| 433 |
+
with open(os.path.join(log_dir, "final_report.md"), "w") as f:
|
| 434 |
+
f.write(report)
|
| 435 |
+
log(dict(ev="end", finished=finished, usage_total=usage_tot))
|
| 436 |
+
print(json.dumps(dict(finished=finished, usage=usage_tot, report=(report or "")[:200])), flush=True)
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
if __name__ == "__main__":
|
| 440 |
+
try:
|
| 441 |
+
main()
|
| 442 |
+
except SystemExit:
|
| 443 |
+
raise
|
| 444 |
+
except Exception:
|
| 445 |
+
traceback.print_exc()
|
| 446 |
+
sys.exit(1)
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/audit_subagent.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Audit an isolated policy subagent: every tool call it made must stay inside its sandbox.
|
| 2 |
+
|
| 3 |
+
python scripts/audit_subagent.py <transcript.jsonl> <sandbox_dir> [--out audit.json]
|
| 4 |
+
Allowed: Bash `cd <sandbox> && ./robot ...` (or `<sandbox>/robot ...`); Read of <sandbox>/README.md or <sandbox>/obs/*.
|
| 5 |
+
With --la (LIBERO-Agent-style workspace): also Bash `cd <sandbox> && ./shell '<cmd>'` / `./shell <<'TAG' ... TAG` (the
|
| 6 |
+
command runs inside the jail; anything the OUTER shell would execute or expand is a violation), and Read / Write / Edit
|
| 7 |
+
of any file inside <sandbox>.
|
| 8 |
+
Everything else is reported as a violation. Prints counts + violations only (the transcript itself is large).
|
| 9 |
+
"""
|
| 10 |
+
import argparse
|
| 11 |
+
import json
|
| 12 |
+
import re
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def tool_uses(obj):
|
| 16 |
+
if isinstance(obj, dict):
|
| 17 |
+
if obj.get("type") == "tool_use" and "name" in obj:
|
| 18 |
+
yield obj
|
| 19 |
+
for v in obj.values():
|
| 20 |
+
yield from tool_uses(v)
|
| 21 |
+
elif isinstance(obj, list):
|
| 22 |
+
for v in obj:
|
| 23 |
+
yield from tool_uses(v)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def extra_shell_ops(cmd, sb):
|
| 27 |
+
"""True if the command contains shell operators / substitutions outside quotes, apart from the
|
| 28 |
+
allowed leading `cd <sandbox> &&`."""
|
| 29 |
+
import shlex
|
| 30 |
+
body = re.sub(r"^\s*cd\s+%s\s*&&\s*" % re.escape(sb), "", cmd)
|
| 31 |
+
if "`" in body or "$(" in body:
|
| 32 |
+
return True
|
| 33 |
+
try:
|
| 34 |
+
lex = shlex.shlex(body, posix=True, punctuation_chars=True)
|
| 35 |
+
toks = list(lex)
|
| 36 |
+
except ValueError:
|
| 37 |
+
return True
|
| 38 |
+
return any(t in (";", "&&", "||", "|", "&", ">", ">>", "<") for t in toks)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def shell_call_ok(cmd, sb):
|
| 42 |
+
"""la: `cd <sb> && ./shell ...` where nothing runs outside the jail: either one heredoc with a QUOTED tag (no outer
|
| 43 |
+
expansion) and nothing after it, or plain arguments without outer operators / substitutions."""
|
| 44 |
+
m = re.match(r"^\s*cd\s+%s\s*&&\s*(\./shell|%s/shell)(.*)$" % (re.escape(sb), re.escape(sb)), cmd, re.S)
|
| 45 |
+
if not m:
|
| 46 |
+
return False
|
| 47 |
+
rest = m.group(2)
|
| 48 |
+
s = rest.strip()
|
| 49 |
+
if rest[:1].isspace() and len(s) >= 2 and s[0] == "'" and s[-1] == "'" and "'" not in s[1:-1]:
|
| 50 |
+
return True # one single-quoted argument: the outer shell expands nothing (an inner `<<EOF` runs in the jail)
|
| 51 |
+
if "<<" in rest:
|
| 52 |
+
first, _, body = rest.partition("\n")
|
| 53 |
+
hm = re.match(r"^\s*<<-?\s*(['\"])(\w+)\1\s*$", first)
|
| 54 |
+
if not hm:
|
| 55 |
+
return False # unquoted tag: the outer shell would expand $(...) inside the heredoc
|
| 56 |
+
tag = hm.group(2)
|
| 57 |
+
lines = body.rstrip("\n").split("\n")
|
| 58 |
+
return bool(lines) and lines[-1].strip() == tag and tag not in [l.strip() for l in lines[:-1]]
|
| 59 |
+
if "`" in rest or "$(" in rest.replace("'", "\x00").split("\x00")[0::2].__str__():
|
| 60 |
+
return False
|
| 61 |
+
import shlex
|
| 62 |
+
try:
|
| 63 |
+
toks = list(shlex.shlex(rest, posix=True, punctuation_chars=True))
|
| 64 |
+
except ValueError:
|
| 65 |
+
return False
|
| 66 |
+
return not any(t in (";", "&&", "||", "|", "&", ">", ">>", "<") for t in toks)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def main():
|
| 70 |
+
ap = argparse.ArgumentParser()
|
| 71 |
+
ap.add_argument("transcript")
|
| 72 |
+
ap.add_argument("sandbox")
|
| 73 |
+
ap.add_argument("--out")
|
| 74 |
+
ap.add_argument("--la", action="store_true", help="LIBERO-Agent-style workspace: ./shell and workspace files allowed")
|
| 75 |
+
a = ap.parse_args()
|
| 76 |
+
sb = a.sandbox.rstrip("/")
|
| 77 |
+
ok_bash = re.compile(r"^\s*(cd\s+%s\s*&&\s*)?(\./robot|%s/robot)(\s|$)" % (re.escape(sb), re.escape(sb)))
|
| 78 |
+
seen, calls, viol = set(), [], []
|
| 79 |
+
injected = [] # context Claude Code attached on its own: the user's memory index / identity
|
| 80 |
+
with open(a.transcript) as f:
|
| 81 |
+
for line in f:
|
| 82 |
+
try:
|
| 83 |
+
rec = json.loads(line)
|
| 84 |
+
except ValueError:
|
| 85 |
+
continue
|
| 86 |
+
if rec.get("type") == "attachment":
|
| 87 |
+
at = rec.get("attachment", {})
|
| 88 |
+
if at.get("type") == "instructions":
|
| 89 |
+
for fi in at.get("files", []):
|
| 90 |
+
if "memory" in (fi.get("path") or "").lower() or fi.get("type") == "AutoMem":
|
| 91 |
+
injected.append(dict(kind="memory_index", path=fi.get("path"), chars=len(fi.get("content", ""))))
|
| 92 |
+
elif at.get("type") == "session_context":
|
| 93 |
+
injected.append(dict(kind="session_context", keys=sorted((at.get("context") or {}).keys())))
|
| 94 |
+
for tu in tool_uses(rec):
|
| 95 |
+
if tu.get("id") in seen:
|
| 96 |
+
continue
|
| 97 |
+
seen.add(tu.get("id"))
|
| 98 |
+
name, inp = tu["name"], tu.get("input", {})
|
| 99 |
+
calls.append(name)
|
| 100 |
+
if name == "SubagentHandback": # the final report back to the orchestrator
|
| 101 |
+
continue
|
| 102 |
+
if name == "Bash":
|
| 103 |
+
cmd = inp.get("command", "")
|
| 104 |
+
bad = (not ok_bash.match(cmd)) or extra_shell_ops(cmd, sb)
|
| 105 |
+
if bad and a.la and shell_call_ok(cmd, sb):
|
| 106 |
+
bad = False
|
| 107 |
+
if bad:
|
| 108 |
+
viol.append(dict(tool=name, command=cmd))
|
| 109 |
+
elif name in ("Read", "Write", "Edit") and a.la:
|
| 110 |
+
import os
|
| 111 |
+
p = os.path.normpath(inp.get("file_path", ""))
|
| 112 |
+
if not p.startswith(sb + "/"):
|
| 113 |
+
viol.append(dict(tool=name, path=inp.get("file_path", "")))
|
| 114 |
+
elif name == "Read":
|
| 115 |
+
p = inp.get("file_path", "")
|
| 116 |
+
if not (p == f"{sb}/README.md" or p.startswith(f"{sb}/obs/")):
|
| 117 |
+
viol.append(dict(tool=name, path=p))
|
| 118 |
+
else:
|
| 119 |
+
viol.append(dict(tool=name, input=json.dumps(inp)[:300]))
|
| 120 |
+
from collections import Counter
|
| 121 |
+
res = dict(n_calls=len(calls), by_tool=dict(Counter(calls)), n_violations=len(viol), violations=viol,
|
| 122 |
+
memory_injected=any(i["kind"] == "memory_index" for i in injected), injected=injected)
|
| 123 |
+
print(json.dumps(res, indent=1, ensure_ascii=False))
|
| 124 |
+
if a.out:
|
| 125 |
+
with open(a.out, "w") as f:
|
| 126 |
+
json.dump(res, f, indent=1, ensure_ascii=False)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
if __name__ == "__main__":
|
| 130 |
+
main()
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_breakfast_geometry.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""V2 physical height/orientation controls. Initialization interventions are diagnostics only."""
|
| 2 |
+
import json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from PIL import Image
|
| 5 |
+
from lffbench import envs
|
| 6 |
+
from lffbench.tasks.lh_breakfast_service import BreakfastService
|
| 7 |
+
|
| 8 |
+
def main():
|
| 9 |
+
out=Path(__file__).resolve().parents[1]/'results/lh_breakfast_service/geometry_v2/geometry_controls'
|
| 10 |
+
out.mkdir(parents=True,exist_ok=True);rows=[];t=BreakfastService()
|
| 11 |
+
for seed in range(1000,1003):
|
| 12 |
+
inst=t.sample_instance(seed);t.reset_instance(inst);t.sk.correction=t.sk.bias.copy()
|
| 13 |
+
# Move bread clear only at diagnostic initialization, so the obstacle is unambiguous.
|
| 14 |
+
envs.set_obj_pose(t.env,'bread_1',[-.09,-.32,.94]);t.env.sim.forward()
|
| 15 |
+
def state(stage):
|
| 16 |
+
r=dict(seed=seed,stage=stage,lid_deg=t.lid_deg(),butter_height_cm=100*t.butter_height(),
|
| 17 |
+
butter_lid_contact=bool(t.butter_lid_contact()),butter_fits=t.butter_in_box(),
|
| 18 |
+
applied_torque=float(t.env.sim.data.qfrc_applied[t.dof]))
|
| 19 |
+
assert r['applied_torque']==0.,r
|
| 20 |
+
rows.append(r);print(json.dumps(r),flush=True)
|
| 21 |
+
Image.fromarray(envs.render(t.env,res=512)).save(out/f'{seed}_{stage}.png')
|
| 22 |
+
(out/'progress.json').write_text(json.dumps(rows,indent=2))
|
| 23 |
+
return r
|
| 24 |
+
# Two empty-box closes prove that the removed closure-count mechanism does not reappear.
|
| 25 |
+
for cycle in range(2):
|
| 26 |
+
# Let the freely swinging open lid settle before targeting its knob again.
|
| 27 |
+
t.open_lid();t.sk.hold(100);t.close_lid(False);t.sk.hold(80)
|
| 28 |
+
r=state('empty_close_'+str(cycle+1));assert r['lid_deg']<4
|
| 29 |
+
t.open_lid();assert t.put_butter();t.close_lid(False);t.sk.hold(100)
|
| 30 |
+
r=state('upright_blocked')
|
| 31 |
+
assert r['lid_deg']>10 and r['butter_lid_contact'] and r['butter_height_cm']>7 and not r['butter_fits'],r
|
| 32 |
+
# Remove precisely that obstacle, leaving all geometry, forces and joint limits unchanged.
|
| 33 |
+
t.open_lid();assert t.pick_place('butter_1',inst['butter_xy'],t.butter_height()/2+.003)
|
| 34 |
+
t.close_lid(False);t.sk.hold(80);r=state('obstacle_removed');assert r['lid_deg']<4
|
| 35 |
+
assert t.lay_butter_flat();r=state('laid_flat');assert r['butter_height_cm']<2.9
|
| 36 |
+
t.open_lid();assert t.put_butter();t.close_lid(False);t.sk.hold(100)
|
| 37 |
+
r=state('flat_inside_closed');assert r['lid_deg']<4 and r['butter_fits'] and not r['butter_lid_contact'],r
|
| 38 |
+
(out/'result.json').write_text(json.dumps(dict(passed=True,rows=rows),indent=2))
|
| 39 |
+
t.env.close()
|
| 40 |
+
|
| 41 |
+
if __name__=='__main__':main()
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_breakfast_mechanisms.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Mechanism-on/off controls and negative judge fixtures, separate from rollouts."""
|
| 2 |
+
import argparse, copy, json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
from lffbench.tasks.lh_breakfast_service import BreakfastService
|
| 6 |
+
from lffbench import envs
|
| 7 |
+
|
| 8 |
+
def main():
|
| 9 |
+
p=argparse.ArgumentParser();p.add_argument('--liquid-only',action='store_true')
|
| 10 |
+
p.add_argument('--judge-only',action='store_true');args=p.parse_args()
|
| 11 |
+
out=Path(__file__).resolve().parents[1]/'results/lh_breakfast_service/mechanisms'
|
| 12 |
+
out.mkdir(parents=True,exist_ok=True);t=BreakfastService();rows=[]
|
| 13 |
+
if args.judge_only:rows=json.loads((out/'controls_progress.json').read_text())
|
| 14 |
+
for seed in ([] if args.liquid_only or args.judge_only else range(1000,1003)):
|
| 15 |
+
for enabled in (True,False):
|
| 16 |
+
inst=t.sample_instance(seed);inst['mechanisms']['L1']=enabled;t.reset_instance(inst)
|
| 17 |
+
t.calibration_probe();row=dict(seed=seed,mechanism='L1',enabled=enabled,triggered=t.traps['L1'])
|
| 18 |
+
rows.append(row);print(json.dumps(row),flush=True)
|
| 19 |
+
assert row['triggered']==enabled,row
|
| 20 |
+
inst=t.sample_instance(seed);inst['mechanisms']['L3']=enabled;t.reset_instance(inst);t.sk.correction=t.sk.bias.copy()
|
| 21 |
+
t.direct_carton_lift();row=dict(seed=seed,mechanism='L3',enabled=enabled,**t.pull_probe)
|
| 22 |
+
rows.append(row);print(json.dumps(row),flush=True)
|
| 23 |
+
assert row['held_before'] and ((row['displacement_m']<.01) if enabled else (row['displacement_m']>.04)),row
|
| 24 |
+
inst=t.sample_instance(seed);inst['mechanisms']['L2']=enabled;t.reset_instance(inst);t.sk.correction=t.sk.bias.copy()
|
| 25 |
+
for _ in range(2):t.open_lid();t.close_lid(False)
|
| 26 |
+
t.sk.hold(300);failure=t.lid_deg()
|
| 27 |
+
if enabled:t.open_lid();t.close_lid(True);t.sk.hold(300)
|
| 28 |
+
row=dict(seed=seed,mechanism='L2',enabled=enabled,lid_after_quick_closes=failure,final_lid=t.lid_deg())
|
| 29 |
+
rows.append(row);print(json.dumps(row),flush=True)
|
| 30 |
+
assert (failure>10 if enabled else failure<4) and row['final_lid']<4,row
|
| 31 |
+
(out/'controls_progress.json').write_text(json.dumps(rows,indent=2))
|
| 32 |
+
liquid_controls=json.loads((out/'liquid_controls.json').read_text()) if args.judge_only else []
|
| 33 |
+
for case in ([] if args.judge_only else ('upright','tilted_aligned','tilted_misaligned')):
|
| 34 |
+
inst=t.sample_instance(1000);t.reset_instance(inst)
|
| 35 |
+
if case!='upright':t.env.sim.data.qpos[t.pour_qa]=1.35
|
| 36 |
+
if case=='tilted_misaligned':t.env.sim.model.body_pos[t.cup_bid,0]+=.20
|
| 37 |
+
t.env.sim.forward();t.sk.hold(160)
|
| 38 |
+
q=t.liquid;inflight=sum(p['ml'] for p in q['parcels'])
|
| 39 |
+
row=dict(case=case,cup_ml=q['cup'],spill_ml=q['spill'],reservoir_ml=q['reservoir'],
|
| 40 |
+
conservation_error_ml=abs(300-q['cup']-q['spill']-q['reservoir']-inflight))
|
| 41 |
+
liquid_controls.append(row);print(json.dumps(row),flush=True)
|
| 42 |
+
assert row['conservation_error_ml']<1e-8,row
|
| 43 |
+
if case=='upright':assert q['cup']==q['spill']==0,row
|
| 44 |
+
elif case=='tilted_aligned':assert q['cup']>=179 and q['spill']>50,row
|
| 45 |
+
else:assert q['cup']==0 and q['spill']>200,row
|
| 46 |
+
if args.liquid_only:
|
| 47 |
+
(out/'liquid_controls.json').write_text(json.dumps(liquid_controls,indent=2))
|
| 48 |
+
t.env.close();return
|
| 49 |
+
# Obtain a successful physical endpoint before mutating diagnostic scoring fixtures.
|
| 50 |
+
inst=t.sample_instance(1000);t.reset_instance(inst);t.execute(inst,{'mode':'oracle'});baseline=t.outcome(inst)
|
| 51 |
+
assert baseline['success'],baseline
|
| 52 |
+
state=copy.deepcopy(t.env.sim.get_state());liquid=copy.deepcopy(t.liquid)
|
| 53 |
+
mon=copy.deepcopy(t.mon);closes=t.closes_done;latch=t.active_latch
|
| 54 |
+
negatives=[]
|
| 55 |
+
for case in ('no_milk','too_much_milk','spill','bread_off_plate','butter_outside','lid_open','carton_tilted','gripper_closed'):
|
| 56 |
+
t.env.sim.set_state(state);t.env.sim.forward();t.liquid=copy.deepcopy(liquid);t.sk.grip=-1.;t.drift_active=False
|
| 57 |
+
t.mon=copy.deepcopy(mon);t.closes_done=closes;t.active_latch=latch
|
| 58 |
+
if case=='no_milk':t.liquid['reservoir']+=t.liquid['cup'];t.liquid['cup']=0
|
| 59 |
+
elif case=='too_much_milk':
|
| 60 |
+
t.liquid['reservoir']-=175-t.liquid['cup'];t.liquid['cup']=175
|
| 61 |
+
elif case=='spill':t.liquid['reservoir']-=25;t.liquid['spill']=25;t.liquid['spill_xy']=[.2,0]
|
| 62 |
+
elif case=='bread_off_plate':envs.set_obj_pose(t.env,'bread_1',[-.30,.03,.912])
|
| 63 |
+
elif case=='butter_outside':envs.set_obj_pose(t.env,'butter_1',[-.35,-.32,.914])
|
| 64 |
+
elif case=='lid_open':t.env.sim.data.qpos[t.qa]=1.0
|
| 65 |
+
elif case=='carton_tilted':t.env.sim.data.qpos[t.pour_qa]=1.35
|
| 66 |
+
elif case=='gripper_closed':t.sk.grip=1.
|
| 67 |
+
t.env.sim.forward();result=t.outcome(inst)
|
| 68 |
+
negatives.append(dict(case=case,accepted=result['success'],failure=result['failure'],stages=result['stages']))
|
| 69 |
+
print(json.dumps(negatives[-1],default=lambda v:v.item()),flush=True)
|
| 70 |
+
predicate={'no_milk':'milk_served','too_much_milk':'milk_served','spill':'spill_ok',
|
| 71 |
+
'bread_off_plate':'bread_on_plate','butter_outside':'butter_in_box','lid_open':'lid_closed',
|
| 72 |
+
'carton_tilted':'carton_upright','gripper_closed':'gripper_open'}[case]
|
| 73 |
+
assert not result['success'] and not result['stages'][predicate],case
|
| 74 |
+
data=dict(controls=rows,liquid_controls=liquid_controls,negative_fixtures=negatives,
|
| 75 |
+
scope='Controlled interventions are diagnostics, not agent rollouts')
|
| 76 |
+
(out/'result.json').write_text(json.dumps(data,indent=2,default=lambda v:v.item()))
|
| 77 |
+
t.env.close()
|
| 78 |
+
|
| 79 |
+
if __name__=='__main__':main()
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_breakfast_service.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Development physical/reference-policy validation. Never starts model evaluation."""
|
| 2 |
+
import argparse, concurrent.futures, hashlib, json, os, time
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
TASK=None
|
| 6 |
+
def init_worker():
|
| 7 |
+
global TASK
|
| 8 |
+
from lffbench.tasks.lh_breakfast_service import BreakfastService
|
| 9 |
+
TASK=BreakfastService()
|
| 10 |
+
|
| 11 |
+
def plain(v):
|
| 12 |
+
return v.item() if hasattr(v,'item') else v.tolist()
|
| 13 |
+
|
| 14 |
+
def run_one(job):
|
| 15 |
+
kind,seed,outdir=job;t=TASK;start=time.time();inst=t.sample_instance(seed)
|
| 16 |
+
hist=t.run_scripted(kind,inst,k=5,seed=seed+42)
|
| 17 |
+
row=dict(kind=kind,seed=seed,instance=inst,history=hist,trace=t.trace,
|
| 18 |
+
control_steps=t.sk.n_steps,primitive_count=len(t.sk.log),wall_s=time.time()-start,
|
| 19 |
+
pull_probe=getattr(t,'pull_probe',None))
|
| 20 |
+
dest=Path(outdir)/f'{kind}_{seed}.json';dest.write_text(json.dumps(row,indent=2,default=plain)+'\n')
|
| 21 |
+
return dict(kind=kind,seed=seed,success=hist[-1]['outcome']['success'],
|
| 22 |
+
traps=hist[-1]['outcome']['traps'],recovered=hist[-1]['outcome']['recovered'],
|
| 23 |
+
cup_ml=hist[-1]['outcome']['cup_ml'],spill_ml=hist[-1]['outcome']['spill_ml'],
|
| 24 |
+
file=str(dest),wall_s=row['wall_s'])
|
| 25 |
+
|
| 26 |
+
def main():
|
| 27 |
+
p=argparse.ArgumentParser();p.add_argument('--n',type=int,default=20)
|
| 28 |
+
p.add_argument('--policies',default='adaptive,oracle,naive,blind');p.add_argument('--workers',type=int,default=2)
|
| 29 |
+
p.add_argument('--out',required=True);args=p.parse_args();out=Path(args.out);out.mkdir(parents=True,exist_ok=True)
|
| 30 |
+
root=Path(__file__).resolve().parents[1]
|
| 31 |
+
files=[root/'lffbench/tasks'/n for n in ('lh_breakfast_service.py','lh_pantry_relatch.py','lh_lid_box.py')]
|
| 32 |
+
hashes={str(f):hashlib.sha256(f.read_bytes()).hexdigest() for f in files}
|
| 33 |
+
(out/'source_hashes.json').write_text(json.dumps(hashes,indent=2))
|
| 34 |
+
jobs=[(kind,seed,str(out)) for seed in range(1000,1000+args.n) for kind in args.policies.split(',')]
|
| 35 |
+
rows=[]
|
| 36 |
+
with concurrent.futures.ProcessPoolExecutor(max_workers=args.workers,initializer=init_worker) as pool:
|
| 37 |
+
for row in pool.map(run_one,jobs):
|
| 38 |
+
rows.append(row);print(json.dumps(row),flush=True)
|
| 39 |
+
(out/'progress.json').write_text(json.dumps(rows,indent=2))
|
| 40 |
+
final_hashes={str(f):hashlib.sha256(f.read_bytes()).hexdigest() for f in files}
|
| 41 |
+
summary=dict(n=args.n,source_unchanged=hashes==final_hashes,policies={},rows=rows)
|
| 42 |
+
for kind in args.policies.split(','):
|
| 43 |
+
r=[x for x in rows if x['kind']==kind]
|
| 44 |
+
summary['policies'][kind]=dict(success=sum(x['success'] for x in r),total=len(r),
|
| 45 |
+
all_traps_and_recovery=sum(x['success'] and all(x['traps'].values()) and all(x['recovered'].values()) for x in r))
|
| 46 |
+
(out/'summary.json').write_text(json.dumps(summary,indent=2));print(json.dumps(summary['policies']),flush=True)
|
| 47 |
+
|
| 48 |
+
if __name__=='__main__':main()
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_breakfast_tool_interface.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Execute the reference through the real public ToolExecutor, including default motion limits.
|
| 2 |
+
Privileged reference observations remain allowed; all actuation goes through public tools.
|
| 3 |
+
"""
|
| 4 |
+
import argparse, json, math
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from lffbench.tasks.lh_breakfast_service import BreakfastService
|
| 7 |
+
from lffbench.agent.tools import ToolExecutor
|
| 8 |
+
|
| 9 |
+
class PublicSkills:
|
| 10 |
+
def __init__(self,base,executor):
|
| 11 |
+
object.__setattr__(self,'base',base);object.__setattr__(self,'executor',executor)
|
| 12 |
+
object.__setattr__(self,'calls',[])
|
| 13 |
+
# Learned compensation belongs in the caller's command coordinates, not the environment.
|
| 14 |
+
object.__setattr__(self,'correction',base.correction.copy());base.correction[:]=0
|
| 15 |
+
def __getattr__(self,name):return getattr(self.base,name)
|
| 16 |
+
def __setattr__(self,name,value):
|
| 17 |
+
if name=='correction':object.__setattr__(self,name,value)
|
| 18 |
+
else:setattr(self.base,name,value)
|
| 19 |
+
def call(self,name,args):
|
| 20 |
+
result=self.executor.call(name,args)
|
| 21 |
+
self.calls.append(dict(name=name,args=args,ok=result.ok,report=result.report))
|
| 22 |
+
if not result.ok:raise RuntimeError(result.report)
|
| 23 |
+
return result.report
|
| 24 |
+
def move_to(self,target,yaw=None,speed=None,**kwargs):
|
| 25 |
+
target=target-self.correction
|
| 26 |
+
return self.call('move_to',dict(x=float(target[0]),y=float(target[1]),z=float(target[2]),
|
| 27 |
+
yaw=math.degrees(self.base.yaw if yaw is None else yaw),speed=speed))
|
| 28 |
+
def set_gripper(self,close,steps=15):
|
| 29 |
+
result=self.call('close_gripper' if close else 'open_gripper',{})
|
| 30 |
+
if steps>15:self.hold(steps-15)
|
| 31 |
+
return result
|
| 32 |
+
def hold(self,steps=10):
|
| 33 |
+
for _ in range(steps//15):self.call('close_gripper' if self.base.grip>0 else 'open_gripper',{})
|
| 34 |
+
for _ in range(steps%15):
|
| 35 |
+
self.move_to(self.base.eef_pos()-self.base.bias+self.correction)
|
| 36 |
+
|
| 37 |
+
def main():
|
| 38 |
+
p=argparse.ArgumentParser();p.add_argument('--out');p.add_argument('--seed',type=int,default=1000);args=p.parse_args()
|
| 39 |
+
root=Path(__file__).resolve().parents[1]
|
| 40 |
+
out=Path(args.out) if args.out else root/'results/lh_breakfast_service/geometry_v2/tool_interface'
|
| 41 |
+
out.mkdir(parents=True,exist_ok=True)
|
| 42 |
+
t=BreakfastService();inst=t.sample_instance(args.seed);t.reset_instance(inst)
|
| 43 |
+
executor=ToolExecutor(t,inst,image_res=128)
|
| 44 |
+
proxy=PublicSkills(t.sk,executor);t.sk=proxy
|
| 45 |
+
t.phase_hook=lambda text,state:print(json.dumps(state),flush=True)
|
| 46 |
+
t.execute(inst,{'mode':'adaptive'})
|
| 47 |
+
# The final judge's mandatory settle is environment work, not additional agent tool calls.
|
| 48 |
+
t.sk=proxy.base
|
| 49 |
+
result=t.outcome(inst)
|
| 50 |
+
data=dict(outcome=result,calls=proxy.calls,call_count=len(proxy.calls),trace=t.trace,
|
| 51 |
+
environment_correction=proxy.base.correction.tolist(),compensation_in_tool_arguments=True,
|
| 52 |
+
scope='Reference with privileged observations; actual public ToolExecutor actuation, not an LLM evaluation')
|
| 53 |
+
(out/'result.json').write_text(json.dumps(data,indent=2,default=lambda v:v.item()))
|
| 54 |
+
print('OUTCOME',result,flush=True)
|
| 55 |
+
assert result['success'] and all(result['traps'].values()) and len(proxy.calls)<=t.agent_max_steps,dict(outcome=result,call_count=len(proxy.calls))
|
| 56 |
+
|
| 57 |
+
if __name__=='__main__':main()
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_lh_order_dispatch.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small physical development check; no agent/API calls. Every case starts from a reset.
|
| 2 |
+
Oracle recovery is explicitly diagnostic, not learned behaviour.
|
| 3 |
+
"""
|
| 4 |
+
import argparse,copy,json,sys,time
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from PIL import Image
|
| 7 |
+
import hashlib
|
| 8 |
+
from lffbench import envs
|
| 9 |
+
import numpy as np
|
| 10 |
+
from lffbench.tasks.lh_order_dispatch import OrderDispatch,PRODUCTS
|
| 11 |
+
from lffbench.tasks.l3_card_edge import CardEdge
|
| 12 |
+
from lffbench.tasks.l7_offcenter_push import OffcenterPush
|
| 13 |
+
p=argparse.ArgumentParser();p.add_argument('--seeds',default='1000,1001,1002');p.add_argument('--cases',default='baseline,oracle_all,L1,L3,L5,combined_recovery');p.add_argument('--out',required=True);a=p.parse_args()
|
| 14 |
+
source=Path('lffbench/tasks/lh_order_dispatch.py').read_bytes()
|
| 15 |
+
code_sha256=hashlib.sha256(source).hexdigest()
|
| 16 |
+
Path(a.out).parent.mkdir(exist_ok=True,parents=True)
|
| 17 |
+
Path(a.out).with_suffix('.source.py').write_bytes(source)
|
| 18 |
+
task=OrderDispatch(cam_res=512);rows=[]
|
| 19 |
+
def capture(label):
|
| 20 |
+
dest=Path(a.out).parent/(Path(a.out).stem+'_frames')/f'{seed}_{case}_{label}.png';dest.parent.mkdir(exist_ok=True)
|
| 21 |
+
Image.fromarray(envs.render(task.env,res=512)).save(dest)
|
| 22 |
+
return dict(path=str(dest.resolve()),sim_step=task.sk.n_steps)
|
| 23 |
+
|
| 24 |
+
for seed in map(int,a.seeds.split(',')):
|
| 25 |
+
for case in a.cases.split(','):
|
| 26 |
+
inst=task.sample_instance(seed);inst['mechanisms']={x:case in ('oracle_all','combined_recovery') or x==case for x in ['L1','L3','L5']};task.reset_instance(inst)
|
| 27 |
+
frames=[capture('initial')]
|
| 28 |
+
base_move=task.sk.move_to
|
| 29 |
+
captured_l5=[False]
|
| 30 |
+
def observed_move(*args,**kwargs):
|
| 31 |
+
result=base_move(*args,**kwargs)
|
| 32 |
+
if task.sk.box_moves and task.sk.box_moves[-1].get('bad') and task.mon['loaded'] and not task.sk.box_moves[-1].get('gripper_open') and not captured_l5[0]:
|
| 33 |
+
frames.append(capture('L5_failure'));captured_l5[0]=True
|
| 34 |
+
return result
|
| 35 |
+
task.sk.move_to=observed_move
|
| 36 |
+
try:
|
| 37 |
+
failure=None
|
| 38 |
+
if case in ('baseline','oracle_all'):
|
| 39 |
+
task.execute(inst,task.oracle_params(inst))
|
| 40 |
+
elif case=='L1':
|
| 41 |
+
task.load_product(PRODUCTS[0],0);failure=copy.deepcopy(task.outcome(inst))
|
| 42 |
+
frames.append(capture('L1_failure'));measured=failure['l1_attempts'][0]['approach_offset'];task.execute(inst,dict(mode='oracle',correction=[*measured,0],c=0.))
|
| 43 |
+
elif case=='L3':
|
| 44 |
+
for k,o in enumerate(PRODUCTS):task.load_product(o,k)
|
| 45 |
+
CardEdge.execute(task,inst,dict(mode='grasp'));frames.append(capture('L3_failure'));failure=copy.deepcopy(task.outcome(inst))
|
| 46 |
+
CardEdge.execute(task,inst,dict(mode='edge',overhang=.03));task.sk.hold(10)
|
| 47 |
+
if all(task.in_cargo(o) for o in task.mon['states']):OffcenterPush.execute(task,inst,dict(c=0.))
|
| 48 |
+
pos=task.sk.eef_pos();task.sk.move_to([pos[0],pos[1],1.15]);task.sk.set_gripper(False,8)
|
| 49 |
+
elif case=='combined_recovery':
|
| 50 |
+
task.load_product(PRODUCTS[0],0);frames.append(capture('L1_failure'));failure=copy.deepcopy(task.outcome(inst))
|
| 51 |
+
estimate=np.array([*failure['l1_attempts'][0]['approach_offset'],0.]);task.sk.correction=estimate
|
| 52 |
+
for k,o in enumerate(PRODUCTS):
|
| 53 |
+
task.load_product(o,k)
|
| 54 |
+
estimate+=np.array([*task.mon['l1_attempts'][-1]['approach_offset'],0.]);task.sk.correction=estimate.copy()
|
| 55 |
+
CardEdge.execute(task,inst,dict(mode='grasp'));frames.append(capture('L3_failure'))
|
| 56 |
+
CardEdge.execute(task,inst,dict(mode='edge',overhang=.03));task.sk.hold(10)
|
| 57 |
+
if all(task.in_cargo(o) for o in task.mon['states']):
|
| 58 |
+
OffcenterPush.adaptive_attempt(task,inst,0.)
|
| 59 |
+
if not task.in_cargo('card_1'):task.repair_card()
|
| 60 |
+
pos=task.sk.eef_pos();task.sk.move_to([pos[0],pos[1],1.15]);task.sk.set_gripper(False,8)
|
| 61 |
+
else:
|
| 62 |
+
# Original corrector takes its estimate only from observed pushes, not hidden com_offset.
|
| 63 |
+
task.execute(inst,dict(mode='adaptive',c=0.))
|
| 64 |
+
out=task.outcome(inst);frames.append(capture('final'))
|
| 65 |
+
trigger=(not failure['l1_attempts'][0]['held'] if case=='L1' else
|
| 66 |
+
not any(c['held'] for c in failure['card_closes'] if c['card_on_board'] and c['overhang']<=0) if case=='L3' else
|
| 67 |
+
out['l5_triggered'] if case=='L5' else None)
|
| 68 |
+
diagnostics=dict(L1=bool(out['l1_attempts'] and not out['l1_attempts'][0]['held']),L3=any(c['card_on_board'] and c['overhang']<=.001 and abs(c['local'][0])<.05 and abs(c['local'][1])<.05 and c['tips_above_card']<.02 and not c['held'] for c in out['card_closes']),L5=out['l5_triggered'])
|
| 69 |
+
row=dict(seed=seed,case=case,diagnostics=diagnostics,mechanisms=inst['mechanisms'],triggered=trigger,recovered=out['success'],before_recovery=failure,outcome=out,frames=frames)
|
| 70 |
+
except Exception as e:
|
| 71 |
+
row=dict(seed=seed,case=case,error=repr(e))
|
| 72 |
+
assert hashlib.sha256(Path('lffbench/tasks/lh_order_dispatch.py').read_bytes()).hexdigest()==code_sha256,'source changed during run'
|
| 73 |
+
rows.append(row);Path(a.out).write_text(json.dumps(dict(code_sha256=code_sha256,rows=rows),indent=2));print(seed,case,{k:row.get(k) for k in ('triggered','recovered','error')},flush=True)
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_lh_pantry_relatch.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Physical checks for lh_pantry_relatch: confirm the latch-fatigue mechanism actually behaves as designed before
|
| 2 |
+
any acceptance validation. Not the formal n>=20 k=5 headroom run (see scripts/validate.py for that).
|
| 3 |
+
|
| 4 |
+
Usage:
|
| 5 |
+
cd lffbench && source run_env.sh && OMP_NUM_THREADS=1 python scripts/check_lh_pantry_relatch.py mechanism
|
| 6 |
+
OMP_NUM_THREADS=1 python scripts/check_lh_pantry_relatch.py seeds --seeds 1000,1001,1002 --out <path>
|
| 7 |
+
"""
|
| 8 |
+
import argparse
|
| 9 |
+
import copy
|
| 10 |
+
import hashlib
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
import sys
|
| 14 |
+
|
| 15 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
|
| 19 |
+
from lffbench import envs
|
| 20 |
+
from lffbench.tasks.lh_pantry_relatch import PantryRelatch
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def source_hash():
|
| 24 |
+
path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "lffbench", "tasks",
|
| 25 |
+
"lh_pantry_relatch.py")
|
| 26 |
+
return hashlib.sha256(open(path, "rb").read()).hexdigest()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def mechanism_check(seed=1000, out=None):
|
| 30 |
+
"""Isolate the latch mechanism: close 1 (quick) should hold; close 2 (quick) should drift open on its own
|
| 31 |
+
during the settle window; close 2 (dwell) should hold. No bread/butter picking involved -- just the lid."""
|
| 32 |
+
task = PantryRelatch()
|
| 33 |
+
rows = []
|
| 34 |
+
for label, dwell1, dwell2 in [("quick_quick", False, False), ("quick_dwell", False, True)]:
|
| 35 |
+
inst = task.sample_instance(seed)
|
| 36 |
+
task.reset_instance(inst)
|
| 37 |
+
task.open_lid()
|
| 38 |
+
task.close_lid(dwell=dwell1)
|
| 39 |
+
after_close1 = task.lid_deg()
|
| 40 |
+
n = 0
|
| 41 |
+
while n < 300:
|
| 42 |
+
task.sk.hold(10)
|
| 43 |
+
n += 10
|
| 44 |
+
settled1 = task.lid_deg()
|
| 45 |
+
task.open_lid()
|
| 46 |
+
task.close_lid(dwell=dwell2)
|
| 47 |
+
after_close2 = task.lid_deg()
|
| 48 |
+
n = 0
|
| 49 |
+
while n < 500:
|
| 50 |
+
task.sk.hold(10)
|
| 51 |
+
n += 10
|
| 52 |
+
settled2 = task.lid_deg()
|
| 53 |
+
row = dict(label=label, dwell1=dwell1, dwell2=dwell2, after_close1_deg=round(after_close1, 2),
|
| 54 |
+
settled1_deg=round(settled1, 2), after_close2_deg=round(after_close2, 2),
|
| 55 |
+
settled2_deg=round(settled2, 2), closes_done=task.closes_done,
|
| 56 |
+
active_latch_final=round(task.active_latch, 4))
|
| 57 |
+
rows.append(row)
|
| 58 |
+
print(row, flush=True)
|
| 59 |
+
print("expect: quick_quick settled2_deg clearly > quick_dwell settled2_deg (fatigue visible without dwell)")
|
| 60 |
+
if out:
|
| 61 |
+
with open(out, "w") as f:
|
| 62 |
+
json.dump(dict(rows=rows, source_sha256=source_hash()), f, indent=1)
|
| 63 |
+
return rows
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def ablation_no_decay(seed=1000, out=None):
|
| 67 |
+
"""Ablation: force DECAY=1.0 (no fatigue). Quick-release close 2 should then also hold."""
|
| 68 |
+
import lffbench.tasks.lh_pantry_relatch as mod
|
| 69 |
+
orig = mod.DECAY
|
| 70 |
+
mod.DECAY = 1.0
|
| 71 |
+
try:
|
| 72 |
+
task = PantryRelatch()
|
| 73 |
+
inst = task.sample_instance(seed)
|
| 74 |
+
task.reset_instance(inst)
|
| 75 |
+
task.open_lid()
|
| 76 |
+
task.close_lid(dwell=False)
|
| 77 |
+
task.open_lid()
|
| 78 |
+
task.close_lid(dwell=False)
|
| 79 |
+
n = 0
|
| 80 |
+
while n < 500:
|
| 81 |
+
task.sk.hold(10)
|
| 82 |
+
n += 10
|
| 83 |
+
settled2 = task.lid_deg()
|
| 84 |
+
row = dict(decay_forced=1.0, settled2_deg=round(settled2, 2), closes_done=task.closes_done)
|
| 85 |
+
print(row, flush=True)
|
| 86 |
+
finally:
|
| 87 |
+
mod.DECAY = orig
|
| 88 |
+
if out:
|
| 89 |
+
with open(out, "w") as f:
|
| 90 |
+
json.dump(row, f, indent=1)
|
| 91 |
+
return row
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def full_episode(seed, kind, out_dir=None):
|
| 95 |
+
"""Full pick-bread / put-butter episode with a given scripted policy kind."""
|
| 96 |
+
task = PantryRelatch()
|
| 97 |
+
inst = task.sample_instance(seed)
|
| 98 |
+
hist = task.run_scripted(kind, inst, k=task.max_attempts, seed=seed)
|
| 99 |
+
for h in hist:
|
| 100 |
+
o = h["outcome"]
|
| 101 |
+
print(f"seed={seed} kind={kind} attempt={h['attempt']} success={o['success']} failure={o['failure']} "
|
| 102 |
+
f"closes_done={o['closes_done']} lid_final={o['lid_final_deg']} detail={o['detail']}", flush=True)
|
| 103 |
+
return hist
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def seeds_check(seeds, out=None):
|
| 107 |
+
task_rows = {}
|
| 108 |
+
for seed in seeds:
|
| 109 |
+
rows = {}
|
| 110 |
+
for kind in ("oracle", "naive", "adaptive"):
|
| 111 |
+
hist = full_episode(seed, kind)
|
| 112 |
+
rows[kind] = [dict(attempt=h["attempt"], success=h["outcome"]["success"],
|
| 113 |
+
failure=h["outcome"]["failure"], closes_done=h["outcome"]["closes_done"],
|
| 114 |
+
lid_final_deg=h["outcome"]["lid_final_deg"]) for h in hist]
|
| 115 |
+
task_rows[seed] = rows
|
| 116 |
+
result = dict(seeds=seeds, rows=task_rows, source_sha256=source_hash())
|
| 117 |
+
if out:
|
| 118 |
+
with open(out, "w") as f:
|
| 119 |
+
json.dump(result, f, indent=1)
|
| 120 |
+
return result
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
if __name__ == "__main__":
|
| 124 |
+
ap = argparse.ArgumentParser()
|
| 125 |
+
ap.add_argument("mode", choices=["mechanism", "ablation", "seeds", "episode"])
|
| 126 |
+
ap.add_argument("--seed", type=int, default=1000)
|
| 127 |
+
ap.add_argument("--seeds", type=str, default="1000,1001,1002")
|
| 128 |
+
ap.add_argument("--kind", type=str, default="oracle")
|
| 129 |
+
ap.add_argument("--out", type=str, default=None)
|
| 130 |
+
args = ap.parse_args()
|
| 131 |
+
if args.mode == "mechanism":
|
| 132 |
+
mechanism_check(args.seed, args.out)
|
| 133 |
+
elif args.mode == "ablation":
|
| 134 |
+
ablation_no_decay(args.seed, args.out)
|
| 135 |
+
elif args.mode == "episode":
|
| 136 |
+
full_episode(args.seed, args.kind)
|
| 137 |
+
elif args.mode == "seeds":
|
| 138 |
+
seeds_check([int(s) for s in args.seeds.split(",")], args.out)
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_setup.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Check that this machine can run LFF-Bench. Run after `source run_env.sh`:
|
| 2 |
+
|
| 3 |
+
python scripts/check_setup.py # Python packages, LIBERO config, simulation + rendering, the agent's shell jail
|
| 4 |
+
python scripts/check_setup.py --api # ... plus one tiny text-only request to the model endpoint (OPENAI_API_KEY /
|
| 5 |
+
# OPENAI_BASE_URL from the environment or from .env); costs a few tokens
|
| 6 |
+
python scripts/check_setup.py --api --model gpt-5.5 --skip-sim --skip-jail
|
| 7 |
+
|
| 8 |
+
Exit code 0 when every check that ran passed.
|
| 9 |
+
"""
|
| 10 |
+
import argparse
|
| 11 |
+
import os
|
| 12 |
+
import subprocess
|
| 13 |
+
import sys
|
| 14 |
+
import tempfile
|
| 15 |
+
import time
|
| 16 |
+
|
| 17 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 18 |
+
sys.path.insert(0, ROOT)
|
| 19 |
+
JAIL = "/opt/lffjail/jail_inner.sh" # same path as lffbench/agent/robot_server.py and scripts/gpt_player.py
|
| 20 |
+
|
| 21 |
+
results = []
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def report(name, ok, detail=""):
|
| 25 |
+
results.append(ok)
|
| 26 |
+
print(f"[{'ok' if ok else 'FAIL'}] {name}" + (f": {detail}" if detail else ""), flush=True)
|
| 27 |
+
return ok
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def check_packages():
|
| 31 |
+
report("python 3.10", sys.version_info[:2] == (3, 10), sys.version.split()[0])
|
| 32 |
+
from lffbench.agent.backends.base import import_openai
|
| 33 |
+
for mod in ("numpy", "mujoco", "robosuite", "libero.libero", "openai", "imageio", "cv2"):
|
| 34 |
+
try:
|
| 35 |
+
m = import_openai() if mod == "openai" else __import__(mod, fromlist=["_"])
|
| 36 |
+
report(f"import {mod}", True, getattr(m, "__version__", ""))
|
| 37 |
+
except Exception as e: # noqa: BLE001
|
| 38 |
+
report(f"import {mod}", False, f"{type(e).__name__}: {e}")
|
| 39 |
+
cfg = os.path.join(os.environ.get("LIBERO_CONFIG_PATH", ""), "config.yaml")
|
| 40 |
+
if report("LIBERO config", os.path.isfile(cfg), cfg + ("" if os.path.isfile(cfg) else " missing: run setup/install.sh")):
|
| 41 |
+
import yaml
|
| 42 |
+
assets = yaml.safe_load(open(cfg)).get("assets", "")
|
| 43 |
+
report("LIBERO assets", os.path.isdir(assets), assets)
|
| 44 |
+
report("rendering backend", bool(os.environ.get("MUJOCO_GL")), f"MUJOCO_GL={os.environ.get('MUJOCO_GL')}")
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def check_sim(task_name, seed):
|
| 48 |
+
import importlib
|
| 49 |
+
import pkgutil
|
| 50 |
+
|
| 51 |
+
try:
|
| 52 |
+
import lffbench.tasks as task_pkg
|
| 53 |
+
from lffbench.task_base import TASKS
|
| 54 |
+
except Exception as e: # noqa: BLE001
|
| 55 |
+
report("import lffbench", False, f"{type(e).__name__}: {e}")
|
| 56 |
+
return
|
| 57 |
+
try:
|
| 58 |
+
for m in pkgutil.iter_modules(task_pkg.__path__):
|
| 59 |
+
importlib.import_module(f"lffbench.tasks.{m.name}")
|
| 60 |
+
except Exception as e: # noqa: BLE001
|
| 61 |
+
report("import tasks", False, f"{type(e).__name__}: {e}")
|
| 62 |
+
return
|
| 63 |
+
report("tasks registered", len(TASKS) >= 20, f"{len(TASKS)} tasks")
|
| 64 |
+
t0 = time.time()
|
| 65 |
+
try:
|
| 66 |
+
task = TASKS[task_name]()
|
| 67 |
+
inst = task.sample_instance(seed)
|
| 68 |
+
task.reset_instance(inst)
|
| 69 |
+
img = task.snapshot()
|
| 70 |
+
out = task.outcome(inst)
|
| 71 |
+
except Exception as e: # noqa: BLE001
|
| 72 |
+
report(f"simulate + render {task_name}", False, f"{type(e).__name__}: {e}")
|
| 73 |
+
return
|
| 74 |
+
ok = img.ndim == 3 and img.shape[2] == 3 and float(img.std()) > 1.0
|
| 75 |
+
report(f"simulate + render {task_name}", ok,
|
| 76 |
+
f"image {img.shape}, pixel std {img.std():.1f}, untouched scene success={out['success']}, {time.time() - t0:.1f} s")
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def check_jail():
|
| 80 |
+
if not report("jail installed", os.access(JAIL, os.X_OK) and os.path.isdir("/opt/lffjail/py"),
|
| 81 |
+
JAIL if os.path.exists(JAIL) else "missing: sudo bash jail/setup_jail.sh"):
|
| 82 |
+
return
|
| 83 |
+
probe = r'''
|
| 84 |
+
echo "pwd=$(pwd)"
|
| 85 |
+
python3 -c "import numpy, scipy, PIL, cv2; print('py=ok')" 2>&1 | tail -1
|
| 86 |
+
echo "mnt_entries=$(ls -A /mnt 2>/dev/null | wc -l) home_entries=$(ls -A /home 2>/dev/null | wc -l)"
|
| 87 |
+
python3 -c "
|
| 88 |
+
import socket
|
| 89 |
+
s = socket.socket(); s.settimeout(3)
|
| 90 |
+
try:
|
| 91 |
+
s.connect(('1.1.1.1', 443)); print('net=open')
|
| 92 |
+
except OSError as e:
|
| 93 |
+
print('net=blocked')
|
| 94 |
+
"
|
| 95 |
+
touch made_in_jail && echo "write=ok"
|
| 96 |
+
'''
|
| 97 |
+
with tempfile.TemporaryDirectory(prefix="lffjail_check_") as ws:
|
| 98 |
+
argv = ["unshare", "--user", "--map-root-user", "--mount", "--net", "--", JAIL, ws,
|
| 99 |
+
"timeout", "-k", "5", "60", "bash", "-c", probe]
|
| 100 |
+
r = subprocess.run(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=120)
|
| 101 |
+
kv = dict(l.split("=", 1) for l in r.stdout.split() if "=" in l)
|
| 102 |
+
if r.returncode != 0 and not kv:
|
| 103 |
+
hint = ""
|
| 104 |
+
if "Operation not permitted" in r.stdout or "uid_map" in r.stdout:
|
| 105 |
+
hint = (" | unprivileged user namespaces are blocked; on Ubuntu >= 23.10: "
|
| 106 |
+
"sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0")
|
| 107 |
+
report("jail runs", False, r.stdout.strip()[-400:] + hint)
|
| 108 |
+
return
|
| 109 |
+
report("jail runs", True, f"workdir {kv.get('pwd')}")
|
| 110 |
+
report("jail python (numpy/scipy/Pillow/OpenCV)", kv.get("py") == "ok", kv.get("py", r.stdout[-300:]))
|
| 111 |
+
report("jail hides host data", kv.get("mnt_entries") == "0" and kv.get("home_entries") == "0",
|
| 112 |
+
f"/mnt entries {kv.get('mnt_entries')}, /home entries {kv.get('home_entries')}")
|
| 113 |
+
report("jail has no network", kv.get("net") == "blocked", kv.get("net", "?"))
|
| 114 |
+
report("jail writes the workspace", kv.get("write") == "ok" and os.path.exists(os.path.join(ws, "made_in_jail")))
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def load_env_file():
|
| 118 |
+
path = os.environ.get("LFF_ENV_FILE") or os.path.join(ROOT, ".env")
|
| 119 |
+
if not os.path.isfile(path):
|
| 120 |
+
return None
|
| 121 |
+
for line in open(path):
|
| 122 |
+
line = line.strip()
|
| 123 |
+
if line and not line.startswith("#") and "=" in line:
|
| 124 |
+
k, v = line.split("=", 1)
|
| 125 |
+
os.environ.setdefault(k.removeprefix("export ").strip(), v.strip().strip("'\""))
|
| 126 |
+
return path
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def check_api(model, effort):
|
| 130 |
+
src = load_env_file()
|
| 131 |
+
if not os.environ.get("SSL_CERT_FILE") and os.path.exists("/etc/ssl/certs/ca-certificates.crt"):
|
| 132 |
+
os.environ["SSL_CERT_FILE"] = "/etc/ssl/certs/ca-certificates.crt" # same as scripts/gpt_player.py
|
| 133 |
+
if not report("OPENAI_API_KEY set", bool(os.environ.get("OPENAI_API_KEY")),
|
| 134 |
+
f"from {src}" if src else "from the environment (no .env)"):
|
| 135 |
+
return
|
| 136 |
+
base = os.environ.get("OPENAI_BASE_URL") or "https://api.openai.com/v1 (default)"
|
| 137 |
+
from lffbench.agent.backends.openai_responses import OpenAIResponsesBackend
|
| 138 |
+
t0 = time.time()
|
| 139 |
+
try:
|
| 140 |
+
client = OpenAIResponsesBackend(model=model, reasoning_effort=effort, timeout=120.0, max_retries=1).client()
|
| 141 |
+
resp = client.responses.create(model=model, instructions="Reply with exactly the word OK.", input="ping",
|
| 142 |
+
reasoning=dict(effort=effort), store=False, max_output_tokens=256)
|
| 143 |
+
text = (resp.output_text or "").strip()
|
| 144 |
+
u = resp.usage
|
| 145 |
+
report(f"API {model} @ {base}", bool(text), f"reply {text[:40]!r}, {time.time() - t0:.1f} s, "
|
| 146 |
+
f"tokens in {u.input_tokens} / out {u.output_tokens}")
|
| 147 |
+
except Exception as e: # noqa: BLE001
|
| 148 |
+
report(f"API {model} @ {base}", False, f"{type(e).__name__}: {str(e)[:300]}")
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def main():
|
| 152 |
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 153 |
+
ap.add_argument("--api", action="store_true", help="also send one tiny request to the model endpoint")
|
| 154 |
+
ap.add_argument("--model", default="gpt-6-astra")
|
| 155 |
+
ap.add_argument("--effort", default="low")
|
| 156 |
+
ap.add_argument("--task", default="l5_slide_to_target")
|
| 157 |
+
ap.add_argument("--seed", type=int, default=1000)
|
| 158 |
+
ap.add_argument("--skip-sim", action="store_true")
|
| 159 |
+
ap.add_argument("--skip-jail", action="store_true")
|
| 160 |
+
a = ap.parse_args()
|
| 161 |
+
os.environ.setdefault("OMP_NUM_THREADS", "1")
|
| 162 |
+
check_packages()
|
| 163 |
+
if not a.skip_sim:
|
| 164 |
+
check_sim(a.task, a.seed)
|
| 165 |
+
if not a.skip_jail:
|
| 166 |
+
check_jail()
|
| 167 |
+
if a.api:
|
| 168 |
+
check_api(a.model, a.effort)
|
| 169 |
+
n_bad = results.count(False)
|
| 170 |
+
print(f"\n{len(results) - n_bad}/{len(results)} checks passed")
|
| 171 |
+
sys.exit(1 if n_bad else 0)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
if __name__ == "__main__":
|
| 175 |
+
main()
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/claude_batch.py
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Batch bookkeeping for Claude-subagent policy runs.
|
| 2 |
+
|
| 3 |
+
start python scripts/claude_batch.py start --batch exp1 --model sonnet --tasks t1:s1,s2 t2:s1 --k 3 --port0 9000
|
| 4 |
+
-> starts one server per (task, seed, condition) run and writes runs/claude/<batch>/manifest.json
|
| 5 |
+
conditions: harness = memory full + feedback (default F1) + k attempts in one agent;
|
| 6 |
+
noharness = k independent single-attempt agents (memory none, k=1)
|
| 7 |
+
usage python scripts/claude_batch.py usage --batch exp1 --run <run> --agent <agentId> --tokens N --ms N --tools N
|
| 8 |
+
audit python scripts/claude_batch.py audit --batch exp1 (runs audit_subagent on every recorded agent)
|
| 9 |
+
table python scripts/claude_batch.py table --batch exp1 [--batch exp2 ...]
|
| 10 |
+
stop python scripts/claude_batch.py stop --batch exp1
|
| 11 |
+
"""
|
| 12 |
+
import argparse
|
| 13 |
+
import glob
|
| 14 |
+
import json
|
| 15 |
+
import os
|
| 16 |
+
import subprocess
|
| 17 |
+
import sys
|
| 18 |
+
|
| 19 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 20 |
+
RUNS = os.path.join(ROOT, "runs", "claude")
|
| 21 |
+
RUNS_DIR_DEFAULT = RUNS
|
| 22 |
+
TRANSCRIPTS = os.environ.get("CLAUDE_TASKS_DIR", "") # the Claude Code session's tasks/ dir (<agentId>.output files)
|
| 23 |
+
|
| 24 |
+
PLAYER_PROMPT = """You are controlling a simulated robot arm. Everything you need is in the directory {sb}
|
| 25 |
+
|
| 26 |
+
Rules (strict):
|
| 27 |
+
- First read {sb}/README.md — it explains the robot, the coordinate frames, the cameras, the commands and your task.
|
| 28 |
+
- Control the robot only by running shell commands of the form:
|
| 29 |
+
cd {sb} && ./robot <command> key=value ...
|
| 30 |
+
Run one robot command per shell call.
|
| 31 |
+
- Look at camera images only with your file-reading tool on the image paths the robot prints (they are inside that directory's obs/ folder).
|
| 32 |
+
- Do not read, list, search or execute anything else on this machine: no other files or directories, no other programs, no scripts of your own, no web access. Only README.md, the obs/ images and ./robot.
|
| 33 |
+
- Keep going until a robot command tells you to stop or that the episode is over.
|
| 34 |
+
|
| 35 |
+
When you are told to stop, reply with a short report: what you did (key commands and parameter values), what you observed, any feedback you got, and how you changed your approach."""
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
PLAYER_PROMPT_LA = """You are controlling a simulated robot arm. Your workspace is the directory {sb}
|
| 39 |
+
|
| 40 |
+
Rules (strict):
|
| 41 |
+
- First read {sb}/README.md: it explains the robot, the commands, the observation files and your task.
|
| 42 |
+
- Every shell call must be exactly one of these forms, with nothing chained before or after it:
|
| 43 |
+
cd {sb} && ./robot <command> key=value ...
|
| 44 |
+
cd {sb} && ./shell '<bash command>'
|
| 45 |
+
cd {sb} && ./shell <<'EOF'
|
| 46 |
+
<multi-line bash command, e.g. a python3 heredoc>
|
| 47 |
+
EOF
|
| 48 |
+
./robot runs one robot command. ./shell runs your command inside the workspace (ls, python3 with numpy / scipy /
|
| 49 |
+
Pillow / OpenCV, writing your own notes or scripts, ...); it has no network and cannot control the robot.
|
| 50 |
+
- Use your file-reading tool to look at images and other files, and your file-writing tools if you want, but only on
|
| 51 |
+
files inside {sb}.
|
| 52 |
+
- Do not read, list, search or execute anything else on this machine, do not use any other tool, no web access.
|
| 53 |
+
- Keep going until a robot command tells you to stop or that the episode is over.
|
| 54 |
+
|
| 55 |
+
When you are told to stop, reply with a short report: what you did (key commands and parameter values), what you
|
| 56 |
+
observed, any feedback you got, and how you changed your approach."""
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
THINK_ALOUD = """
|
| 60 |
+
|
| 61 |
+
Think aloud (for the experiment log): before every ./robot command, first write one to three plain sentences as
|
| 62 |
+
normal text (not inside a tool call): what you currently see or know, what you conclude from it, and what the next
|
| 63 |
+
command is meant to achieve. After each attempt ends, also write what you think went wrong (or right) and what you
|
| 64 |
+
will change. Keep these notes short and factual."""
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def manifest_path(batch):
|
| 68 |
+
return os.path.join(RUNS, batch, "manifest.json")
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def load(batch):
|
| 72 |
+
with open(manifest_path(batch)) as f:
|
| 73 |
+
return json.load(f)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def save(batch, m):
|
| 77 |
+
os.makedirs(os.path.dirname(manifest_path(batch)), exist_ok=True)
|
| 78 |
+
with open(manifest_path(batch), "w") as f:
|
| 79 |
+
json.dump(m, f, indent=1)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def port_free(port):
|
| 83 |
+
import socket
|
| 84 |
+
with socket.socket() as so:
|
| 85 |
+
try:
|
| 86 |
+
so.bind(("127.0.0.1", port))
|
| 87 |
+
return True
|
| 88 |
+
except OSError:
|
| 89 |
+
return False
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def start_one(task, seed, mem, k, port, tag, perception="depth", video=False, style="v1", extra="", feedback="F1"):
|
| 93 |
+
env = dict(os.environ, LFF_RUNS_DIR=os.environ.get("LFF_RUNS_DIR", RUNS_DIR_DEFAULT), LFF_STYLE=style, LFF_EXTRA_ARGS=extra)
|
| 94 |
+
out = subprocess.run(["bash", os.path.join(ROOT, "scripts", "start_robot_session.sh"), task, str(seed), mem, feedback,
|
| 95 |
+
str(port), "direct", str(k), tag, perception, "1" if video else "0"], capture_output=True, text=True,
|
| 96 |
+
env=env)
|
| 97 |
+
kv = dict(line.split("=", 1) for line in out.stdout.strip().splitlines() if "=" in line and line.split("=")[0] in ("SANDBOX", "LOG"))
|
| 98 |
+
if "SANDBOX" not in kv:
|
| 99 |
+
raise RuntimeError(out.stdout + out.stderr)
|
| 100 |
+
return kv["SANDBOX"], kv["LOG"]
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def cmd_start(a):
|
| 104 |
+
m = load(a.batch) if os.path.exists(manifest_path(a.batch)) else dict(batch=a.batch, runs=[])
|
| 105 |
+
port = a.port0
|
| 106 |
+
used = {r["port"] for r in m["runs"]}
|
| 107 |
+
for spec in a.tasks:
|
| 108 |
+
task, seeds = spec.split(":")
|
| 109 |
+
for seed in seeds.split(","):
|
| 110 |
+
conds = [("harness", "full", a.k, 0)] + [("noharness", "none", 1, i) for i in range(a.k)]
|
| 111 |
+
for cond, mem, k, rep in conds:
|
| 112 |
+
if a.only and cond != a.only:
|
| 113 |
+
continue
|
| 114 |
+
while port in used or not port_free(port):
|
| 115 |
+
port += 1
|
| 116 |
+
hide_k = bool(a.hide_k and cond == "harness")
|
| 117 |
+
tag = (f"{a.batch}-{a.model}-{cond}{rep if cond == 'noharness' else ''}" + ("-nominal" if a.nominal else "")
|
| 118 |
+
+ ("-hidek" if hide_k else "") + (f"-arm{a.arm}" if a.arm != "none" else "")
|
| 119 |
+
+ ("-dossier" if a.dossier else ""))
|
| 120 |
+
extra = (("--agent-iface cli" if a.style == "la" else "") + (" --nominal" if a.nominal else "")
|
| 121 |
+
+ (" --hide-k" if hide_k else "") + (f" --arm {a.arm}" if a.arm != "none" else "")
|
| 122 |
+
+ (f" --dossier {os.path.abspath(a.dossier)}" if a.dossier else ""))
|
| 123 |
+
os.environ["LFF_RUNS_DIR"] = os.path.join(RUNS, a.batch)
|
| 124 |
+
sb, log = start_one(task, int(seed), mem, k, port, tag, a.perception, a.video, a.style, extra.strip(), a.feedback)
|
| 125 |
+
used.add(port)
|
| 126 |
+
r = dict(run=os.path.basename(log), task=task, seed=int(seed), model=a.model, cond=cond, rep=rep, k=k,
|
| 127 |
+
port=port, sandbox=sb, log=log, perception=a.perception, video=a.video, style=a.style,
|
| 128 |
+
nominal=a.nominal, feedback=a.feedback, think_aloud=a.think_aloud, hide_k=hide_k,
|
| 129 |
+
arm=a.arm, dossier=os.path.abspath(a.dossier) if a.dossier else "",
|
| 130 |
+
prompt=(PLAYER_PROMPT_LA if a.style == "la" else PLAYER_PROMPT).format(sb=sb)
|
| 131 |
+
+ (THINK_ALOUD if a.think_aloud else ""))
|
| 132 |
+
m["runs"].append(r)
|
| 133 |
+
print(json.dumps({k_: r[k_] for k_ in ("run", "sandbox")}), flush=True)
|
| 134 |
+
save(a.batch, m)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def cmd_usage(a):
|
| 138 |
+
m = load(a.batch)
|
| 139 |
+
for r in m["runs"]:
|
| 140 |
+
if r["run"] == a.run or r["sandbox"] == a.run:
|
| 141 |
+
r.update(agent=a.agent, tokens=a.tokens, ms=a.ms, tool_uses=a.tools)
|
| 142 |
+
save(a.batch, m)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def cmd_audit(a):
|
| 146 |
+
m = load(a.batch)
|
| 147 |
+
for r in m["runs"]:
|
| 148 |
+
if not r.get("agent"):
|
| 149 |
+
continue
|
| 150 |
+
tr = os.path.join(TRANSCRIPTS, f"{r['agent']}.output")
|
| 151 |
+
if not os.path.exists(tr):
|
| 152 |
+
r["audit"] = "transcript missing"
|
| 153 |
+
continue
|
| 154 |
+
out = subprocess.run([sys.executable, os.path.join(ROOT, "scripts", "audit_subagent.py"), tr, r["sandbox"],
|
| 155 |
+
"--out", os.path.join(r["log"], "audit.json")] + (["--la"] if r.get("style") == "la" else []),
|
| 156 |
+
capture_output=True, text=True)
|
| 157 |
+
res = json.loads(out.stdout)
|
| 158 |
+
r["audit"] = dict(n_calls=res["n_calls"], n_violations=res["n_violations"])
|
| 159 |
+
if res["n_violations"]:
|
| 160 |
+
print(r["run"], res["violations"][:3])
|
| 161 |
+
save(a.batch, m)
|
| 162 |
+
print("audited", sum(1 for r in m["runs"] if r.get("audit")))
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def run_stats(r):
|
| 166 |
+
ev = [json.loads(l) for l in open(os.path.join(r["log"], "events.jsonl"))]
|
| 167 |
+
if r.get("only_attempt"): # one attempt of a run (api_batch --memfree followup: attempt 1 of a history run)
|
| 168 |
+
ev = [e for e in ev if e.get("attempt") == r["only_attempt"]]
|
| 169 |
+
dones = [e for e in ev if e["ev"] == "done"]
|
| 170 |
+
http = [e for e in ev if e["ev"] == "http"]
|
| 171 |
+
calls = [e for e in ev if e["ev"] == "call"]
|
| 172 |
+
first = next((d["attempt"] for d in dones if d["success"]), None)
|
| 173 |
+
think = [h["think_s"] for h in http if h.get("think_s") is not None]
|
| 174 |
+
srv = [h["server_s"] for h in http]
|
| 175 |
+
t0 = http[0]["t_recv"] if http else None
|
| 176 |
+
t1 = http[-1]["t_send"] if http else None
|
| 177 |
+
return dict(attempts=len(dones), first_success=first, n_calls=len(calls), n_http=len(http),
|
| 178 |
+
think_s=sum(think), server_s=sum(srv), wall_s=(t1 - t0) if t0 else None,
|
| 179 |
+
think_per_cmd=(sum(think) / len(think)) if think else None,
|
| 180 |
+
outcomes=[(d["attempt"], d["success"], d.get("feedback", "")) for d in dones])
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def cmd_table(a):
|
| 184 |
+
rows = []
|
| 185 |
+
for b in a.batch:
|
| 186 |
+
for r in load(b)["runs"]:
|
| 187 |
+
try:
|
| 188 |
+
st = run_stats(r)
|
| 189 |
+
except FileNotFoundError:
|
| 190 |
+
continue
|
| 191 |
+
rows.append(dict(r, **st))
|
| 192 |
+
import collections
|
| 193 |
+
# group: (task, model) -> harness runs / noharness groups by seed
|
| 194 |
+
g = collections.defaultdict(lambda: dict(h=[], n=collections.defaultdict(list)))
|
| 195 |
+
for x in rows:
|
| 196 |
+
key = (x["task"], x["model"])
|
| 197 |
+
if x["cond"] == "harness":
|
| 198 |
+
g[key]["h"].append(x)
|
| 199 |
+
else:
|
| 200 |
+
g[key]["n"][x["seed"]].append(x)
|
| 201 |
+
lines = ["| task | model | n | harness @1 | harness @k | no-harness @1 | no-harness @k (k indep.) | think s/cmd | cmds/attempt | wall min/run (harness) |",
|
| 202 |
+
"|---|---|---|---|---|---|---|---|---|---|"]
|
| 203 |
+
tot = collections.defaultdict(lambda: [0, 0, 0, 0, 0])
|
| 204 |
+
for (task, model), d in sorted(g.items()):
|
| 205 |
+
H = [x for x in d["h"] if x["attempts"] > 0]
|
| 206 |
+
K = max([x["k"] for x in H] or [3])
|
| 207 |
+
h1 = sum(1 for x in H if x["first_success"] == 1)
|
| 208 |
+
hk = sum(1 for x in H if x["first_success"] is not None)
|
| 209 |
+
seeds = [s for s, xs in d["n"].items() if all(x["attempts"] > 0 for x in xs)]
|
| 210 |
+
n1 = sum(1 for s in seeds if sorted(d["n"][s], key=lambda x: x["rep"])[0]["first_success"])
|
| 211 |
+
nk = sum(1 for s in seeds if any(x["first_success"] for x in d["n"][s]))
|
| 212 |
+
allx = H + [x for s in seeds for x in d["n"][s] if not x.get("only_attempt")] # attempt 1 counted in H
|
| 213 |
+
th = [x["think_per_cmd"] for x in allx if x["think_per_cmd"]]
|
| 214 |
+
cpa = [x["n_calls"] / max(x["attempts"], 1) for x in allx]
|
| 215 |
+
wall = [x["wall_s"] / 60 for x in H if x["wall_s"]]
|
| 216 |
+
f = lambda v: f"{sum(v) / len(v):.1f}" if v else "—"
|
| 217 |
+
lines.append(f"| {task} | {model} | {len(H)}/{len(seeds)} | {h1}/{len(H)} | {hk}/{len(H)} | {n1}/{len(seeds)} | "
|
| 218 |
+
f"{nk}/{len(seeds)} | {f(th)} | {f(cpa)} | {f(wall)} |")
|
| 219 |
+
t = tot[model]
|
| 220 |
+
t[0] += h1; t[1] += hk; t[2] += len(H); t[3] += nk; t[4] += len(seeds)
|
| 221 |
+
for model, t in tot.items():
|
| 222 |
+
lines.append(f"| **all** | {model} | | {t[0]}/{t[2]} | {t[1]}/{t[2]} | | {t[3]}/{t[4]} | | | |")
|
| 223 |
+
print("\n".join(lines))
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def cmd_restart(a):
|
| 227 |
+
"""Re-run interrupted runs from scratch: stop the old server, start a fresh one (new sandbox, new port),
|
| 228 |
+
keep the old entry under 'superseded'."""
|
| 229 |
+
m = load(a.batch)
|
| 230 |
+
used = {r["port"] for r in m["runs"]}
|
| 231 |
+
port = a.port0
|
| 232 |
+
for i, r in enumerate(list(m["runs"])):
|
| 233 |
+
if r["run"] not in a.runs:
|
| 234 |
+
continue
|
| 235 |
+
try:
|
| 236 |
+
os.kill(int(open(os.path.join(r["log"], "server.pid")).read()), 15)
|
| 237 |
+
except (ProcessLookupError, FileNotFoundError):
|
| 238 |
+
pass
|
| 239 |
+
while port in used or not port_free(port):
|
| 240 |
+
port += 1
|
| 241 |
+
mem = "full" if r["cond"] == "harness" else "none"
|
| 242 |
+
tag = f"{a.batch}-{r['model']}-{r['cond']}{r['rep'] if r['cond'] == 'noharness' else ''}"
|
| 243 |
+
if r.get("style") == "la":
|
| 244 |
+
os.environ["LFF_RUNS_DIR"] = os.path.dirname(r["log"])
|
| 245 |
+
extra = (("--agent-iface cli" if r.get("style") == "la" else "") + (" --nominal" if r.get("nominal") else "")
|
| 246 |
+
+ (" --hide-k" if r.get("hide_k") else "")
|
| 247 |
+
+ (f" --arm {r['arm']}" if r.get("arm", "none") != "none" else "")
|
| 248 |
+
+ (f" --dossier {r['dossier']}" if r.get("dossier") else ""))
|
| 249 |
+
tag += ("-hidek" if r.get("hide_k") else "") + (f"-arm{r['arm']}" if r.get("arm", "none") != "none" else "") \
|
| 250 |
+
+ ("-dossier" if r.get("dossier") else "")
|
| 251 |
+
sb, log = start_one(r["task"], r["seed"], mem, r["k"], port, tag, r.get("perception", "depth"), r.get("video", False),
|
| 252 |
+
r.get("style", "v1"), extra.strip(), r.get("feedback", "F2"))
|
| 253 |
+
used.add(port)
|
| 254 |
+
new = {k: v for k, v in r.items() if k not in ("agent", "tokens", "ms", "tool_uses", "audit")}
|
| 255 |
+
new.update(run=os.path.basename(log), port=port, sandbox=sb, log=log,
|
| 256 |
+
prompt=(PLAYER_PROMPT_LA if r.get("style") == "la" else PLAYER_PROMPT).format(sb=sb))
|
| 257 |
+
m.setdefault("superseded", []).append(dict(r, reason=a.reason))
|
| 258 |
+
m["runs"][i] = new
|
| 259 |
+
print(json.dumps(dict(run=new["run"], sandbox=sb)))
|
| 260 |
+
save(a.batch, m)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def cmd_stop(a):
|
| 264 |
+
for r in load(a.batch)["runs"]:
|
| 265 |
+
pid = os.path.join(r["log"], "server.pid")
|
| 266 |
+
if os.path.exists(pid):
|
| 267 |
+
try:
|
| 268 |
+
os.kill(int(open(pid).read()), 15)
|
| 269 |
+
except ProcessLookupError:
|
| 270 |
+
pass
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def main():
|
| 274 |
+
ap = argparse.ArgumentParser()
|
| 275 |
+
sub = ap.add_subparsers(dest="cmd")
|
| 276 |
+
s = sub.add_parser("start"); s.add_argument("--batch", required=True); s.add_argument("--model", required=True)
|
| 277 |
+
s.add_argument("--tasks", nargs="+", required=True); s.add_argument("--k", type=int, default=3)
|
| 278 |
+
s.add_argument("--port0", type=int, default=9000); s.add_argument("--only", choices=["harness", "noharness"])
|
| 279 |
+
s.add_argument("--perception", default="depth", choices=["depth", "rgb", "rgbd"]); s.add_argument("--video", action="store_true")
|
| 280 |
+
s.add_argument("--style", default="v1", choices=["v1", "v2", "la"])
|
| 281 |
+
s.add_argument("--nominal", action="store_true", help="L1 control: hidden calibration error removed")
|
| 282 |
+
s.add_argument("--arm", default="none", choices=["none", "h0", "hplus", "twin"],
|
| 283 |
+
help="full5 controlled arm (lffbench/arm_specs/<task>.py), passed to every run of this call")
|
| 284 |
+
s.add_argument("--dossier", default="",
|
| 285 |
+
help="la, single task:seed per call: earlier-attempt record (scripts/make_dossier.py) copied to history/")
|
| 286 |
+
s.add_argument("--hide-k", action="store_true",
|
| 287 |
+
help="harness runs: README says 1 attempt (same as the independent run); the other k-1 attempts are "
|
| 288 |
+
"announced only after a failure")
|
| 289 |
+
s.add_argument("--think-aloud", action="store_true",
|
| 290 |
+
help="append a request to write 1-3 plain sentences before every robot command (the transcript keeps no "
|
| 291 |
+
"thinking text, so this is the only way to record the agent's reasoning); changes the prompt")
|
| 292 |
+
s.add_argument("--feedback", default="F1", choices=["F0", "F1", "F2"],
|
| 293 |
+
help="after a failed attempt: F1 = success/failure only (default since 2026-10-08); F2 = measured error "
|
| 294 |
+
"(privileged; neither LIBERO-Agent nor RoboDojo gives it), ablation only")
|
| 295 |
+
u = sub.add_parser("usage"); u.add_argument("--batch", required=True); u.add_argument("--run", required=True)
|
| 296 |
+
u.add_argument("--agent", required=True); u.add_argument("--tokens", type=int); u.add_argument("--ms", type=int)
|
| 297 |
+
u.add_argument("--tools", type=int)
|
| 298 |
+
au = sub.add_parser("audit"); au.add_argument("--batch", required=True)
|
| 299 |
+
t = sub.add_parser("table"); t.add_argument("--batch", nargs="+", required=True)
|
| 300 |
+
st = sub.add_parser("stop"); st.add_argument("--batch", required=True)
|
| 301 |
+
rs = sub.add_parser("restart"); rs.add_argument("--batch", required=True); rs.add_argument("--runs", nargs="+", required=True)
|
| 302 |
+
rs.add_argument("--port0", type=int, default=9300)
|
| 303 |
+
rs.add_argument("--reason", default="interrupted (rate limit)")
|
| 304 |
+
a = ap.parse_args()
|
| 305 |
+
dict(start=cmd_start, usage=cmd_usage, audit=cmd_audit, table=cmd_table, stop=cmd_stop, restart=cmd_restart)[a.cmd](a)
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
if __name__ == "__main__":
|
| 309 |
+
main()
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_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_breakfast1_20261114/lff/source_closure/scripts/feedback_ladder.py
ADDED
|
@@ -0,0 +1,428 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Frozen first-failure record experiment. No native-session-continuation claim.
|
| 2 |
+
|
| 3 |
+
prepare creates a host-only manifest plus agent-visible, identical history records.
|
| 4 |
+
run starts the serial, resumable controller; player wraps the unchanged native harness.
|
| 5 |
+
"""
|
| 6 |
+
import argparse
|
| 7 |
+
import collections
|
| 8 |
+
import datetime as dt
|
| 9 |
+
import hashlib
|
| 10 |
+
import json
|
| 11 |
+
import os
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
import random
|
| 14 |
+
import shutil
|
| 15 |
+
import signal
|
| 16 |
+
import socket
|
| 17 |
+
import subprocess
|
| 18 |
+
import sys
|
| 19 |
+
import time
|
| 20 |
+
|
| 21 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 22 |
+
sys.path.insert(0, str(ROOT))
|
| 23 |
+
sys.path.insert(0, str(ROOT / 'scripts'))
|
| 24 |
+
SOURCE = ROOT.parents[1] / 'lffbench'
|
| 25 |
+
REPORT = ROOT.parents[1] / 'reports/feedback_ladder_20261027'
|
| 26 |
+
BATCHES = ('cc_opus1', 'cc_opus_s2', 'cc_opus_s3')
|
| 27 |
+
TASKS = ('l7_offcenter_push','l5_slide_to_target','l5_tablecloth_pull','l3_wall_flush',
|
| 28 |
+
'l3_under_table_tool','l4_fit_container','l7_key_turn','l2_turntable_restore','l3_card_shelf','l5_loaded_beam')
|
| 29 |
+
ARMS = ('F1', 'F2', 'cause', 'fix')
|
| 30 |
+
ENV_FILE = Path('/mnt/cpfs/workspace/env/claude-releases/cc_opus_s3.env')
|
| 31 |
+
PILOT = ('cc_opus1__l3_card_shelf__3003', 'cc_opus_s2__l4_fit_container__3001')
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def now():
|
| 35 |
+
return dt.datetime.now(dt.timezone.utc).isoformat()
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def sha(p):
|
| 39 |
+
return hashlib.sha256(Path(p).read_bytes()).hexdigest()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def digest(d):
|
| 43 |
+
return hashlib.sha256(json.dumps(d,sort_keys=True,ensure_ascii=False,separators=(',',':')).encode()).hexdigest()
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def read(p):
|
| 47 |
+
return json.loads(Path(p).read_text())
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def write(p,d):
|
| 51 |
+
p=Path(p);p.parent.mkdir(parents=True,exist_ok=True)
|
| 52 |
+
tmp=p.with_name(p.name+'.tmp');tmp.write_text(json.dumps(d,indent=2,ensure_ascii=False)+'\n');tmp.replace(p)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def jsonl(p):
|
| 56 |
+
return [json.loads(s) for s in Path(p).read_text().splitlines() if s.strip()]
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def tree_hash(p):
|
| 60 |
+
return digest({str(f.relative_to(p)):sha(f) for f in sorted(Path(p).rglob('*')) if f.is_file()})
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def intervention(a,arm):
|
| 64 |
+
parts=['The earlier attempt failed.']
|
| 65 |
+
if arm not in ARMS:raise ValueError(arm)
|
| 66 |
+
for level,key in [('F2','phenomenon'),('cause','cause'),('fix','fix')]:
|
| 67 |
+
if ARMS.index(arm)>=ARMS.index(level):parts.append(a[key])
|
| 68 |
+
return '\n'.join(parts)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def annotations(task,seed,out,inst):
|
| 72 |
+
"""Manual mechanism families, checked against each observed first-attempt outcome.
|
| 73 |
+
F2 contains observations only; privileged mechanism and strategy are separate.
|
| 74 |
+
Unknown/mixed mechanisms are explicitly excluded, not assigned a task-name cause.
|
| 75 |
+
"""
|
| 76 |
+
if task=='l3_wall_flush' and out.get('mode')=='placed_off':
|
| 77 |
+
return dict(eligible=False,reason='Placement missed after successful extraction; exact localization/control cause unverified.')
|
| 78 |
+
if task=='l3_under_table_tool':
|
| 79 |
+
return dict(eligible=False,reason='Cube never moved and agent reported wrist limits; transparent-pane mechanism not triggered. Needs separate operational audit.')
|
| 80 |
+
if task=='l5_slide_to_target':
|
| 81 |
+
assert out['failure']=='position' and out['along_err']>0 and out['at_rest']
|
| 82 |
+
return dict(eligible=True,phenomenon='The cube came to rest beyond the far edge of the target square.',
|
| 83 |
+
cause='The cube keeps moving after release: its surface friction is low, so the launch imparted more sliding distance than the remaining distance to the target.',
|
| 84 |
+
fix='Use the previous strike and observed travel as a calibration. Align a short strike toward the square, launch more gently for the remaining distance, withdraw the gripper, and wait for the cube to stop before checking both edges. Preserve a free slide; do not carry or continuously push it into place.',
|
| 85 |
+
basis=['failure=position','along_err>0','at_rest=true','mu in sampled instance','strikes/free_slide_cm'],mechanism='overshoot_after_release')
|
| 86 |
+
if task=='l5_tablecloth_pull':
|
| 87 |
+
assert out['failure']=='missed_band' and out['upright'] and not out['on_board'] and out['band_offset_x']>0
|
| 88 |
+
return dict(eligible=True,phenomenon='The board came out and the cube stayed upright, but the cube stopped short of the green band in the direction of the pull.',
|
| 89 |
+
cause='Friction transfers motion from the board to the cube while they remain in contact. The pull was too fast to move the cube far enough toward the band before the board escaped.',
|
| 90 |
+
fix='On the reset scene, grasp only the handle and use one straight, somewhat slower pull than before, then release. A slower pull carries the cube farther before the board escapes; avoid making it so slow that the cube rides on the board. Check the whole cube against the band after it settles.',
|
| 91 |
+
basis=['failure=missed_band','upright=true','on_board=false','band_offset_x>0','tasks/l5_tablecloth_pull.py adaptive_params'],mechanism='insufficient_frictional_displacement')
|
| 92 |
+
if task=='l3_wall_flush':
|
| 93 |
+
assert out['mode']=='wall_blocked' and not out['lifted']
|
| 94 |
+
return dict(eligible=True,phenomenon='The box was not lifted. During grasp attempts, the wall-side finger came down on the top of the wall.',
|
| 95 |
+
cause='The clearance between box and wall is too small for that finger, and the wall is higher than the box. At the attempted grasp locations the finger still overlapped the wall.',
|
| 96 |
+
fix='With the gripper closed, slide the box along the wall toward an accessible wall end. Move it far enough past that end for both fingers to descend clear of the wall, then open, grasp the box, lift, and place it centered on the plate.',
|
| 97 |
+
basis=['mode=wall_blocked','lifted=false','detail wall collision','gap and wall geometry'],mechanism='wall_blocks_finger')
|
| 98 |
+
if task=='l4_fit_container':
|
| 99 |
+
assert out['failure']=='rim' and out['box_kind'] in ('snug','short_wide','small')
|
| 100 |
+
return dict(eligible=True,phenomenon='The released phone rested on the box rims rather than lying on the bottom inside the box.',
|
| 101 |
+
cause='The selected box is shorter internally than the phone along its long dimension. The phone bridges the rims even when its long axis is aligned with that box.',
|
| 102 |
+
fix='Choose a different box whose internal length and width both clear the phone. Compare the inside edges, orient the phone along the chosen box, lower it through the opening, release it, then withdraw and verify that it lies flat below the rims.',
|
| 103 |
+
basis=['failure=rim','box_kind='+out['box_kind'],'sampled box inner dimensions','detail length mismatch'],mechanism='container_too_short')
|
| 104 |
+
if task=='l3_card_shelf':
|
| 105 |
+
assert out['failure']=='fell_off' and out['tip']['part']=='heavy'
|
| 106 |
+
side=out['tip']['edge'];assert side==inst['heavy_edge']
|
| 107 |
+
return dict(eligible=True,phenomenon=f'The card tipped over the shelf\'s {side} edge and fell flat onto the table before it was lifted.',
|
| 108 |
+
cause=f'The card has a hidden weight toward the end that went over the {side} edge. Its center of mass passed outside the shelf support even with only a small overhang.',
|
| 109 |
+
fix='On the reset shelf, slide the opposite, lighter end toward the opposite shelf edge in small checked moves. Keep the weighted end supported, expose enough of the light end for the fingers to pass the shelf edge, pinch the exposed end across its width, then lift and transfer the card into the bin.',
|
| 110 |
+
basis=['failure=fell_off','tip.part=heavy','tip.edge matches inst.heavy_edge','tipped_off event'],mechanism='heavy_end_over_edge')
|
| 111 |
+
if task=='l5_loaded_beam':
|
| 112 |
+
assert out['failure']=='load_off' and out['n_load_falls']>0
|
| 113 |
+
return dict(eligible=True,phenomenon='The beam tilted during lifting and the blocks slid away from their end positions. At the end, the beam was held up but one block was still displaced inward from its end position.',
|
| 114 |
+
cause='The beam has an off-center hidden weight. The initial grip was away from the loaded balance point, so the beam tilted and displaced its blocks; later leveling did not itself restore their required end positions.',
|
| 115 |
+
fix='First restore both blocks to their original end positions while the beam is supported. Make a low test lift, adjust the grip toward the lower, heavier end until the loaded beam stays level, and only then raise it fully. Recheck both blocks after the lift; if either shifts, set down and restore it before trying again.',
|
| 116 |
+
basis=['failure=load_off','first lift tilt and falls','final loads_on_ends=1','inst.com_total'],mechanism='offcenter_lift_and_unrestored_load',mixed=True)
|
| 117 |
+
raise ValueError(f'No reviewed feedback for {task} seed {seed}')
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def record_prefix(log,outdir,done):
|
| 121 |
+
"""Only host-logged model-visible MCP text before first verdict, plus first images.
|
| 122 |
+
Do NOT copy session_start.inst, evaluator outcome, later attempts, or native hidden reasoning.
|
| 123 |
+
The final call is replaced by its closing reason + F1 verdict, to avoid reset-image leakage.
|
| 124 |
+
"""
|
| 125 |
+
outdir.mkdir(parents=True,exist_ok=False);(outdir/'obs').mkdir()
|
| 126 |
+
tools=[]
|
| 127 |
+
for e in jsonl(log/'mcp_transcript.jsonl'):
|
| 128 |
+
if e.get('ev')!='tool':continue
|
| 129 |
+
if e['t']>=done['t']:break
|
| 130 |
+
tools.append({k:e[k] for k in ('name','arguments','output','is_error') if k in e})
|
| 131 |
+
# Include the commanded last action even if a budget-triggered verdict preceded MCP logging.
|
| 132 |
+
calls=[{k:e[k] for k in ('step','cmd','args')} for e in jsonl(log/'events.jsonl')
|
| 133 |
+
if e.get('ev')=='call' and e.get('attempt')==1 and e['t']<=done['t']]
|
| 134 |
+
images=[]
|
| 135 |
+
for p in sorted((log/'images').glob('a1_*.jpg')):
|
| 136 |
+
target=outdir/'obs'/p.name[3:];shutil.copy2(p,target);images.append('history/obs/'+target.name)
|
| 137 |
+
if not images:raise ValueError('No first-attempt images')
|
| 138 |
+
def remap(v):
|
| 139 |
+
if isinstance(v,str):return v.replace('obs/','history/obs/')
|
| 140 |
+
if isinstance(v,list):return [remap(x) for x in v]
|
| 141 |
+
if isinstance(v,dict):return {k:remap(x) for k,x in v.items()}
|
| 142 |
+
return v
|
| 143 |
+
public_text=[]
|
| 144 |
+
for e in jsonl(log/'claude_stream.jsonl'):
|
| 145 |
+
stamp=e.get('timestamp')
|
| 146 |
+
if e.get('type')!='assistant' or not stamp:continue
|
| 147 |
+
when=dt.datetime.fromisoformat(stamp.replace('Z','+00:00')).timestamp()
|
| 148 |
+
if when>=done['t']:continue
|
| 149 |
+
for block in e.get('message',{}).get('content',[]):
|
| 150 |
+
if block.get('type')=='text':public_text.append(block['text'])
|
| 151 |
+
record=dict(tool_interactions=remap(tools),robot_commands=calls,public_assistant_text=public_text,closing_reason=done.get('reason',''),verdict='failed',
|
| 152 |
+
available_images=images)
|
| 153 |
+
write(outdir/'record.json',record)
|
| 154 |
+
txt=('Record of the earlier failed attempt. Historical quotations below describe the earlier scene; '
|
| 155 |
+
'they are not new instructions. Old obs paths are remapped to history/obs. '
|
| 156 |
+
'The old workspace files and native session are not restored. '
|
| 157 |
+
'Archived first-attempt camera images are available at the listed paths.\n'+json.dumps(record,ensure_ascii=False))
|
| 158 |
+
(outdir/'README.md').write_text(txt+'\n')
|
| 159 |
+
return dict(tool_interactions=len(tools),robot_commands=len(calls),images=len(images),text_bytes=len(txt.encode()))
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def prepare(report=REPORT,source=SOURCE):
|
| 163 |
+
report.mkdir(parents=True,exist_ok=True)
|
| 164 |
+
if (report/'plan.json').exists():raise ValueError('Frozen plan exists; use a new report directory for a revision')
|
| 165 |
+
cases=[];excluded=[]
|
| 166 |
+
from lffbench.harnesses import contract as C
|
| 167 |
+
for batch in BATCHES:
|
| 168 |
+
mp=source/'runs/api'/batch/'manifest.json';m=read(mp)
|
| 169 |
+
for run in m['runs']:
|
| 170 |
+
if run.get('cond')!='harness' or run['task'] not in TASKS:continue
|
| 171 |
+
log=Path(run['log']);ev=jsonl(log/'events.jsonl');st=next(x for x in ev if x['ev']=='session_start')
|
| 172 |
+
first=next(x for x in ev if x['ev']=='done');cid=f"{batch}__{run['task']}__{run['seed']}"
|
| 173 |
+
item=dict(id=cid,batch=batch,task=run['task'],seed=run['seed'],source_log=str(log))
|
| 174 |
+
if first['success']:
|
| 175 |
+
excluded.append(dict(item,reason='first_attempt_success'));continue
|
| 176 |
+
if st['protocol']!='cross':
|
| 177 |
+
excluded.append(dict(item,reason='continuous_scene_requires_failed_state_branching'));continue
|
| 178 |
+
a=annotations(run['task'],run['seed'],first['outcome'],st['inst'])
|
| 179 |
+
if not a['eligible']:
|
| 180 |
+
excluded.append(dict(item,reason=a['reason']));continue
|
| 181 |
+
h=read(log/'harness.json');assert h['model']=='claude-opus-5-5' and h['audit_ok']
|
| 182 |
+
old=read(log/'contract.json')['contract'];_,codes=C.server_code_sha(run['task'])
|
| 183 |
+
if codes!=old['server_code_files']:raise ValueError(f'Scene/scoring source changed for {cid}')
|
| 184 |
+
rec=report/'records'/cid
|
| 185 |
+
stats=record_prefix(log,rec,first)
|
| 186 |
+
case=dict(item,annotation=a,record=str(rec),record_sha256=tree_hash(rec),record_stats=stats,
|
| 187 |
+
original_contract_sha256=h['contract_sha256'],server_code_files=codes,
|
| 188 |
+
source_hashes={f:sha(log/f) for f in ['events.jsonl','mcp_transcript.jsonl','claude_stream.jsonl','harness.json','contract.json']},
|
| 189 |
+
source_first_outcome=first['outcome'],source_first_reason=first['reason'],source_inst=st['inst'],
|
| 190 |
+
source_budget=old['budget'],source_first_done_time=first['t'])
|
| 191 |
+
for arm in ARMS:
|
| 192 |
+
folder=report/'inputs'/cid/arm
|
| 193 |
+
shutil.copytree(rec,folder)
|
| 194 |
+
(folder/'feedback.txt').write_text(intervention(a,arm)+'\n')
|
| 195 |
+
cases.append(case)
|
| 196 |
+
plan=dict(schema='lff-feedback-ladder-1',created_utc=now(),source=str(source),model='claude-opus-5-5',effort='high',
|
| 197 |
+
harness='claude_code_full',cli_version='2.1.299',auth='oauth',remaining_attempts=2,
|
| 198 |
+
history_mode='frozen_model_visible_tool_record_with_archived_images; fresh native session in ALL arms',
|
| 199 |
+
feedback_schedule='one additive intervention before recovery; subsequent verdicts F1 for all arms',
|
| 200 |
+
original_F1_comparable=False,arms=ARMS,selection='all first-attempt failures in fixed ten-task set and three fixed Opus batches, excluding continuous scene and unverified causes',
|
| 201 |
+
cases=cases,excluded=excluded,pilot_cases=PILOT,concurrency=1,randomization_seed=20261027,
|
| 202 |
+
inference='conditional recovery and paired information benefit; not exact cognitive-stage failure proportions',
|
| 203 |
+
limitations=['single rollout per condition','mechanism cards model-assisted, not independent blinded ground truth',
|
| 204 |
+
'F1 record replay must not be pooled with original native continuation','archived available images can be revisited; old workspace and hidden reasoning unavailable',
|
| 205 |
+
'fix text is a strategy, not a calibrated action trajectory; failure need not be execution alone'])
|
| 206 |
+
write(report/'plan.json',plan)
|
| 207 |
+
write(report/'freeze.json',dict(plan_sha256=sha(report/'plan.json'),code_sha256=sha(__file__),inputs={str(p.relative_to(report)):tree_hash(p) for p in sorted((report/'inputs').glob('*/*'))}))
|
| 208 |
+
rows=['# Feedback ladder: frozen protocol','',f'{len(cases)} eligible failures; {len(cases)*4} recovery runs, at most two recovery attempts each.','',
|
| 209 |
+
'All four arms receive the same first-failure record in a fresh Claude session. F1 is rerun. This is a record-replay intervention, not restoration of native session state.',
|
| 210 |
+
'F2 is observation-only and is deliberately narrower than existing task F2 strings, which sometimes reveal causes.',
|
| 211 |
+
'Only the initial feedback varies. Later verdicts remain F1. No precise coordinates or simulator action program are handed to the agent.','',
|
| 212 |
+
'| Case | Observed failure | Cause | Fix |','|---|---|---|---|']
|
| 213 |
+
for c in cases:
|
| 214 |
+
a=c['annotation'];rows.append('| '+' | '.join([c['id'],a['phenomenon'],a['cause'],a['fix']])+' |')
|
| 215 |
+
rows+=['','## Exclusions','']+[f"- {x['id']}: {x['reason']}" for x in excluded]
|
| 216 |
+
(report/'PROTOCOL.md').write_text('\n'.join(rows)+'\n')
|
| 217 |
+
print(json.dumps(dict(cases=len(cases),runs=len(cases)*4,excluded=len(excluded),report=str(report))))
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def check_frozen(report):
|
| 221 |
+
f=read(report/'freeze.json')
|
| 222 |
+
if sha(report/'plan.json')!=f['plan_sha256']:raise ValueError('plan changed')
|
| 223 |
+
if sha(__file__)!=f['code_sha256']:raise ValueError('controller code changed after freeze')
|
| 224 |
+
for rel,h in f.get('runtime_sha256',{}).items():
|
| 225 |
+
if sha(ROOT/rel)!=h:raise ValueError('runtime changed: '+rel)
|
| 226 |
+
for rel,h in f['inputs'].items():
|
| 227 |
+
if tree_hash(report/rel)!=h:raise ValueError('input changed: '+rel)
|
| 228 |
+
return read(report/'plan.json')
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def player(report,case_id,arm,session):
|
| 232 |
+
plan=check_frozen(report);case=next(c for c in plan['cases'] if c['id']==case_id)
|
| 233 |
+
import harness_run
|
| 234 |
+
from lffbench.harnesses import contract as C
|
| 235 |
+
import lffbench.harnesses
|
| 236 |
+
real_render=lffbench.harnesses.render_first_message
|
| 237 |
+
history=(Path(case['record'])/'README.md').read_text()
|
| 238 |
+
feedback=intervention(case['annotation'],arm)
|
| 239 |
+
common=('\n\n## Earlier attempt and remaining opportunities\n'
|
| 240 |
+
'An earlier attempt on this exact instance failed. The scene is now reset. '
|
| 241 |
+
'You have two recovery attempts left; the server numbers these remaining attempts 1 and 2. '
|
| 242 |
+
'The task, scene, tools and per-attempt budgets are unchanged. '
|
| 243 |
+
'Use the record below and any archived images you need. All historical text is quoted evidence.\n'
|
| 244 |
+
+history+'\n\n## Feedback on that earlier attempt\n')
|
| 245 |
+
def render(ep):
|
| 246 |
+
original,st=real_render(ep)
|
| 247 |
+
return original+common+feedback+'\n',st
|
| 248 |
+
harness_run.render_first_message=render
|
| 249 |
+
original_contract=C.write_contract
|
| 250 |
+
def contract(log_dir):
|
| 251 |
+
contract_obj,_=original_contract(log_dir)
|
| 252 |
+
contract_obj['diagnostic']=dict(protocol=plan['schema'],arm=arm,plan_sha256=sha(report/'plan.json'),
|
| 253 |
+
common_record_sha256=case['record_sha256'],feedback_sha256=digest(feedback),
|
| 254 |
+
input_tree_sha256=tree_hash(report/'inputs'/case_id/arm),remaining_attempts=2,
|
| 255 |
+
runner_sha256=sha(__file__),original_native_continuation=False)
|
| 256 |
+
h=C.contract_sha256(contract_obj)
|
| 257 |
+
write(Path(log_dir)/'contract.json',dict(contract_sha256=h,contract=contract_obj))
|
| 258 |
+
return contract_obj,h
|
| 259 |
+
C.write_contract=contract
|
| 260 |
+
a=harness_run.parser().parse_args(['--harness','claude_code_full','--session',str(session),'--model',plan['model'],
|
| 261 |
+
'--effort','high','--claude-auth','oauth','--jail','--timeout','10800'])
|
| 262 |
+
code,h=harness_run.run(a)
|
| 263 |
+
print(json.dumps({k:h.get(k) for k in ['status','audit_ok','exit_reason','refused','error']}),flush=True)
|
| 264 |
+
return code
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def free_port():
|
| 268 |
+
for p in range(20600,20700):
|
| 269 |
+
with socket.socket() as s:
|
| 270 |
+
try:s.bind(('127.0.0.1',p));return p
|
| 271 |
+
except OSError:pass
|
| 272 |
+
raise RuntimeError('no free port')
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def quota(log):
|
| 276 |
+
reset=0;detail=[]
|
| 277 |
+
p=log/'claude_stream.jsonl'
|
| 278 |
+
if not p.exists():return reset,detail
|
| 279 |
+
for e in jsonl(p):
|
| 280 |
+
if e.get('type')!='rate_limit_event':continue
|
| 281 |
+
x=e.get('rate_limit_info',{})
|
| 282 |
+
if x.get('status')=='rejected':reset=max(reset,float(x.get('resetsAt') or time.time()+1800));detail.append('rejected')
|
| 283 |
+
for k,v in x.get('unifiedWindows',{}).items():
|
| 284 |
+
if (v.get('utilization') or 0)>=.90:
|
| 285 |
+
reset=max(reset,float(v.get('resetsAt') or time.time()+1800));detail.append(k)
|
| 286 |
+
return reset,sorted(set(detail))
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def verify_run(log,case,arm,report):
|
| 290 |
+
from lffbench.harnesses import contract as C
|
| 291 |
+
h=read(log/'harness.json');co=read(log/'contract.json')['contract'];events=jsonl(log/'events.jsonl')
|
| 292 |
+
st=next(e for e in events if e['ev']=='session_start');done=[e for e in events if e['ev']=='done']
|
| 293 |
+
reason=[]
|
| 294 |
+
if h.get('status')!='done' or h.get('exit_code')!=0 or h.get('exit_reason')!='exited':reason.append('harness incomplete')
|
| 295 |
+
if h.get('audit_ok') is not True:reason.append('harness audit failed')
|
| 296 |
+
if h.get('preflight',{}).get('pin_status')!='match':reason.append('pin mismatch')
|
| 297 |
+
if st['inst']!=case['source_inst']:reason.append('instance changed')
|
| 298 |
+
if co['server_code_files']!=case['server_code_files']:reason.append('scene/scoring code changed')
|
| 299 |
+
if co['budget']!=case['source_budget']:reason.append('budget changed')
|
| 300 |
+
if st['k']!=2 or st['protocol']!='cross' or st['feedback']!='F1' or st['arm']!='none':reason.append('protocol mismatch')
|
| 301 |
+
if not done or (not any(x['success'] for x in done) and len(done)!=2):reason.append('recovery attempts incomplete')
|
| 302 |
+
expected=(report/'inputs'/case['id']/arm)
|
| 303 |
+
# sandbox survives server exit; ensure agent was handed the exact predeclared bundle.
|
| 304 |
+
sess=read(log/'session.json');inp=Path(sess['sandbox'])/'history'
|
| 305 |
+
if not inp.exists() or tree_hash(inp)!=tree_hash(expected):reason.append('history bundle altered')
|
| 306 |
+
first=(log/'first_message.txt').read_text() if (log/'first_message.txt').exists() else ''
|
| 307 |
+
if (Path(case['record'])/'README.md').read_text() not in first:reason.append('missing common history')
|
| 308 |
+
if not first.endswith(intervention(case['annotation'],arm)+'\n'):reason.append('feedback mismatch')
|
| 309 |
+
for source,hsh in case['source_hashes'].items():
|
| 310 |
+
if sha(Path(case['source_log'])/source)!=hsh:reason.append('historical source changed')
|
| 311 |
+
return dict(valid=not reason,invalid_reasons=reason,history=''.join('S' if x['success'] else 'F' for x in done),
|
| 312 |
+
success=any(x['success'] for x in done),attempts=len(done),audit_ok=h.get('audit_ok'),pin_status=h.get('preflight',{}).get('pin_status'))
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def run_one(report,case,arm,index):
|
| 316 |
+
port=free_port();folder=report/'runs'/f'{case["id"]}__{arm}__{index}'
|
| 317 |
+
folder.mkdir(parents=True,exist_ok=False)
|
| 318 |
+
env=dict(os.environ,LFF_RUNS_DIR=str(folder),LFF_STYLE='la',LFF_EXTRA_ARGS='--agent-iface tools --dossier '+str(report/'inputs'/case['id']/arm))
|
| 319 |
+
start=subprocess.run(['bash','scripts/start_robot_session.sh',case['task'],str(case['seed']),'full','F1',str(port),'direct','2','ladder','rgb','1'],
|
| 320 |
+
cwd=ROOT,env=env,capture_output=True,text=True,timeout=660)
|
| 321 |
+
(folder/'server_start.log').write_text(start.stdout+start.stderr)
|
| 322 |
+
logs=list(folder.glob('*/session.json'))
|
| 323 |
+
if start.returncode or len(logs)!=1:return dict(status='server_failed',folder=str(folder),error=(start.stdout+start.stderr)[-1200:])
|
| 324 |
+
log=logs[0].parent
|
| 325 |
+
result=dict(status='running',log=str(log),started_utc=now())
|
| 326 |
+
write(report/'active.json',dict(case=case['id'],arm=arm,**result))
|
| 327 |
+
try:
|
| 328 |
+
# Positional shell parameters avoid interpolating commands or credentials.
|
| 329 |
+
command='source run_env.sh >/dev/null 2>&1 && set -a && source "$1" && set +a && exec python scripts/feedback_ladder.py player --report "$2" --case "$3" --arm "$4" --session "$5"'
|
| 330 |
+
with (log/'player.log').open('w') as out:
|
| 331 |
+
proc=subprocess.Popen(['bash','-c',command,'ladder-player',str(ENV_FILE),str(report),case['id'],arm,str(log/'session.json')],
|
| 332 |
+
cwd=ROOT,env=env,stdout=out,stderr=subprocess.STDOUT,start_new_session=True)
|
| 333 |
+
write(report/'active.json',dict(case=case['id'],arm=arm,pid=proc.pid,**result))
|
| 334 |
+
try:code=proc.wait(timeout=11000)
|
| 335 |
+
except subprocess.TimeoutExpired:
|
| 336 |
+
os.killpg(proc.pid,signal.SIGTERM);code=proc.wait(timeout=60)
|
| 337 |
+
result.update(exit_code=code,ended_utc=now())
|
| 338 |
+
if (log/'harness.json').exists():result.update(verify_run(log,case,arm,report))
|
| 339 |
+
else:result.update(valid=False,invalid_reasons=['harness metadata missing'])
|
| 340 |
+
result['status']='done' if result.get('valid') and code==0 else 'invalid'
|
| 341 |
+
reset,why=quota(log);result.update(quota_reset=reset,quota_reason=why)
|
| 342 |
+
return result
|
| 343 |
+
finally:
|
| 344 |
+
try:os.kill(int((log/'server.pid').read_text()),signal.SIGTERM)
|
| 345 |
+
except (OSError,ValueError):pass
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def summarize(report,state):
|
| 349 |
+
plan=read(report/'plan.json');good={(r['case'],r['arm']):r for r in state['runs'] if r['status']=='done'}
|
| 350 |
+
complete=[c for c in plan['cases'] if all((c['id'],a) in good for a in ARMS)]
|
| 351 |
+
counts={a:dict(successes=sum(good[(c['id'],a)]['success'] for c in complete),n=len(complete)) for a in ARMS}
|
| 352 |
+
paired=[]
|
| 353 |
+
for a,b in zip(ARMS,ARMS[1:]):
|
| 354 |
+
transitions=collections.Counter((good[(c['id'],a)]['success'],good[(c['id'],b)]['success']) for c in complete)
|
| 355 |
+
paired.append(dict(lower=a,upper=b,n=len(complete),gain=transitions[False,True],loss=transitions[True,False],
|
| 356 |
+
net=transitions[False,True]-transitions[True,False]))
|
| 357 |
+
summary=dict(updated_utc=now(),state=state['state'],valid_runs=len(good),planned_runs=len(plan['cases'])*4,complete_cases=len(complete),
|
| 358 |
+
counts=counts,paired=paired,cases=[dict(case=c['id'],mechanism=c['annotation']['mechanism'],
|
| 359 |
+
outcomes={a:good.get((c['id'],a),{}).get('history') for a in ARMS}) for c in plan['cases']])
|
| 360 |
+
write(report/'summary.json',summary)
|
| 361 |
+
lines=['# Feedback ladder results','',f"State: {state['state']}; valid {len(good)}/{len(plan['cases'])*4} runs. Paired-complete cases: {len(complete)}.",'',
|
| 362 |
+
'Recovery success conditional on the same earlier failure and record replay. Do not pool with native F1 continuations or interpret adjacent gains as exact cognitive-stage fractions.','',
|
| 363 |
+
'| Case | F1 | F2 | Cause | Fix |','|---|---|---|---|---|']
|
| 364 |
+
for c in summary['cases']:lines.append('| '+c['case']+' | '+' | '.join(c['outcomes'][a] or 'pending' for a in ARMS)+' |')
|
| 365 |
+
lines+=['','## Paired information benefit','', '| Contrast | n | improved | worsened | net |','|---|---|---|---|---|']
|
| 366 |
+
for x in paired:lines.append(f"| {x['lower']} → {x['upper']} | {x['n']} | {x['gain']} | {x['loss']} | {x['net']} |")
|
| 367 |
+
(report/'RESULTS.md').write_text('\n'.join(lines)+'\n')
|
| 368 |
+
if complete:
|
| 369 |
+
import matplotlib
|
| 370 |
+
matplotlib.use('Agg')
|
| 371 |
+
import matplotlib.pyplot as plt
|
| 372 |
+
fig,ax=plt.subplots(figsize=(6,4));ax.bar(ARMS,[counts[a]['successes']/len(complete) for a in ARMS],color=['#777','#487ca8','#38a391','#ce9340'])
|
| 373 |
+
ax.set(ylim=(0,1),ylabel='Recovery success (paired-complete cases)',title=f'Frozen failure record; n={len(complete)}')
|
| 374 |
+
for i,a in enumerate(ARMS):ax.text(i,counts[a]['successes']/len(complete)+.02,f"{counts[a]['successes']}/{len(complete)}",ha='center')
|
| 375 |
+
fig.tight_layout();fig.savefig(report/'feedback_ladder.png',dpi=180);fig.savefig(report/'feedback_ladder.pdf');plt.close(fig)
|
| 376 |
+
return summary
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
def controller(report,pilot_only=False):
|
| 380 |
+
import fcntl
|
| 381 |
+
lock=(report/'controller.lock').open('w');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
|
| 382 |
+
plan=check_frozen(report)
|
| 383 |
+
if not read(report/'simcheck.json').get('ok'):raise ValueError('simulator check has not passed')
|
| 384 |
+
state=read(report/'status.json') if (report/'status.json').exists() else dict(state='prepared',runs=[],created_utc=now())
|
| 385 |
+
write(report/'controller.json',dict(pid=os.getpid(),started_utc=now(),pilot_only=pilot_only))
|
| 386 |
+
cases={c['id']:c for c in plan['cases']}
|
| 387 |
+
rng=random.Random(plan['randomization_seed']);queue=[]
|
| 388 |
+
for cid in list(plan['pilot_cases'])+[c for c in cases if c not in plan['pilot_cases']]:
|
| 389 |
+
arms=list(ARMS);rng.shuffle(arms)
|
| 390 |
+
queue.extend((cid,a) for a in arms)
|
| 391 |
+
for cid,arm in queue:
|
| 392 |
+
if pilot_only and cid not in plan['pilot_cases']:break
|
| 393 |
+
if any(r['case']==cid and r['arm']==arm and r['status']=='done' for r in state['runs']):continue
|
| 394 |
+
# Any operational failure stops progression; quota-only retry is bounded and waits for the real window.
|
| 395 |
+
state['state']='pilot_running' if cid in plan['pilot_cases'] else 'full_running'
|
| 396 |
+
state['active']=dict(case=cid,arm=arm);write(report/'status.json',state);summarize(report,state)
|
| 397 |
+
while (report/'PAUSE').exists():time.sleep(30)
|
| 398 |
+
check_frozen(report)
|
| 399 |
+
try:
|
| 400 |
+
result=run_one(report,cases[cid],arm,len(state['runs']))
|
| 401 |
+
except Exception as e:
|
| 402 |
+
result=dict(status='invalid',error=f'{type(e).__name__}: {e}',valid=False)
|
| 403 |
+
state['runs'].append(dict(case=cid,arm=arm,**result));write(report/'status.json',state);summarize(report,state)
|
| 404 |
+
print(now(),cid,arm,result['status'],result.get('history'),flush=True)
|
| 405 |
+
if result['status']!='done':
|
| 406 |
+
state['state']='needs_attention';write(report/'status.json',state);summarize(report,state);return 2
|
| 407 |
+
if result.get('quota_reset',0)>time.time():
|
| 408 |
+
state.update(state='waiting_for_quota',resume_after_utc=dt.datetime.fromtimestamp(result['quota_reset']+120,dt.timezone.utc).isoformat())
|
| 409 |
+
write(report/'status.json',state);summarize(report,state)
|
| 410 |
+
while time.time()<result['quota_reset']+120:time.sleep(30)
|
| 411 |
+
# Pilot gate depends on protocol validity, never success rate.
|
| 412 |
+
if all(any(r['case']==p and r['arm']==a and r['status']=='done' for r in state['runs']) for p in plan['pilot_cases'] for a in ARMS):
|
| 413 |
+
write(report/'pilot_gate.json',dict(passed=True,validated_utc=now(),criterion='all eight pilot runs complete; source, input, code, budget, model pin and harness audits pass; independent of outcomes'))
|
| 414 |
+
state['state']='pilot_complete' if pilot_only else 'complete';state.pop('active',None)
|
| 415 |
+
write(report/'status.json',state);summarize(report,state);return 0
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
def main():
|
| 419 |
+
ap=argparse.ArgumentParser();ap.add_argument('command',choices=['prepare','player','run','report','check']);ap.add_argument('--report',type=Path,default=REPORT)
|
| 420 |
+
ap.add_argument('--case');ap.add_argument('--arm',choices=ARMS);ap.add_argument('--session',type=Path);ap.add_argument('--pilot-only',action='store_true');a=ap.parse_args()
|
| 421 |
+
if a.command=='prepare':prepare(a.report)
|
| 422 |
+
elif a.command=='check':p=check_frozen(a.report);print(json.dumps({'frozen':True,'cases':len(p['cases'])}))
|
| 423 |
+
elif a.command=='player':return player(a.report,a.case,a.arm,a.session)
|
| 424 |
+
elif a.command=='run':return controller(a.report,a.pilot_only)
|
| 425 |
+
else:print(json.dumps(summarize(a.report,read(a.report/'status.json'))))
|
| 426 |
+
return 0
|
| 427 |
+
|
| 428 |
+
if __name__=='__main__':sys.exit(main())
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/full_report.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Summarise a full run (all tasks x harnesses) from the robot-server logs only, so every harness is measured
|
| 2 |
+
the same way.
|
| 3 |
+
|
| 4 |
+
python scripts/full_report.py --batch full1 [--out ../docs/full1_table.md]
|
| 5 |
+
|
| 6 |
+
Per run: outcome of every attempt, attempts used, robot commands, close_gripper calls that ended holding an
|
| 7 |
+
object, "empty done" attempts (the agent ended an attempt without a single move / gripper command in it), and
|
| 8 |
+
wall time from the first to the last server request.
|
| 9 |
+
"""
|
| 10 |
+
import argparse
|
| 11 |
+
import collections
|
| 12 |
+
import json
|
| 13 |
+
import os
|
| 14 |
+
|
| 15 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 16 |
+
LEVEL = {"l1": "L1", "l2": "L2", "l3": "L3", "l4": "L4", "l5": "L5", "l6": "L6", "l7": "L7"}
|
| 17 |
+
HARNESS_NAME = {"gpt_player": "ours", "rpent": "RPent", "gptpolicy": "GPT-Policy", "claude": "ours (Claude CLI)"}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def run_info(r):
|
| 21 |
+
ev = [json.loads(l) for l in open(os.path.join(r["log"], "events.jsonl"))]
|
| 22 |
+
calls = [e for e in ev if e["ev"] == "call"]
|
| 23 |
+
dones = [e for e in ev if e["ev"] == "done"]
|
| 24 |
+
http = [e for e in ev if e["ev"] == "http"]
|
| 25 |
+
# v1: move_to / open_gripper / close_gripper; v2 and la: move_eef [gripper=open|close] (holding is only in `raw`,
|
| 26 |
+
# the agent never sees it)
|
| 27 |
+
acts_per_attempt = collections.Counter(e["attempt"] for e in calls if e["cmd"] in ("move_to", "open_gripper", "close_gripper")
|
| 28 |
+
or (e["cmd"] == "move_eef" and (e.get("report") or {}).get("ok")))
|
| 29 |
+
empty = sum(1 for d in dones if acts_per_attempt.get(d["attempt"], 0) == 0)
|
| 30 |
+
closes = [e for e in calls if e["cmd"] == "close_gripper"
|
| 31 |
+
or (e["cmd"] == "move_eef" and (e.get("args") or {}).get("gripper") == "close" and (e.get("report") or {}).get("ok"))]
|
| 32 |
+
held = sum(1 for e in closes if (e.get("report") or {}).get("holding_object") or (e.get("raw") or {}).get("holding_object"))
|
| 33 |
+
first = next((d["attempt"] for d in dones if d["success"]), None)
|
| 34 |
+
wall = (http[-1]["t_send"] - http[0]["t_recv"]) / 60 if http else None
|
| 35 |
+
return dict(outcomes="".join("S" if d["success"] else "F" for d in dones), attempts=len(dones), first=first,
|
| 36 |
+
cmds=len(calls), closes=len(closes), held=held, empty=empty, wall=wall)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def main():
|
| 40 |
+
ap = argparse.ArgumentParser()
|
| 41 |
+
ap.add_argument("--batch", default="full1")
|
| 42 |
+
ap.add_argument("--out", default=None)
|
| 43 |
+
ap.add_argument("--runs", default="gpt", help="runs/<runs>/<batch>/manifest.json (gpt or claude)")
|
| 44 |
+
a = ap.parse_args()
|
| 45 |
+
m = json.load(open(os.path.join(ROOT, "runs", a.runs, a.batch, "manifest.json")))
|
| 46 |
+
rows = {}
|
| 47 |
+
for r in m["runs"]:
|
| 48 |
+
try:
|
| 49 |
+
h = r.get("harness") or ("claude" if r.get("cond") in ("harness", "noharness") else "gpt_player")
|
| 50 |
+
rows[(r["task"], h)] = dict(run_info(r), k=r["k"])
|
| 51 |
+
except FileNotFoundError:
|
| 52 |
+
pass
|
| 53 |
+
tasks = sorted({t for t, _ in rows}, key=lambda t: (t[:2], t))
|
| 54 |
+
hs = [h for h in ("gpt_player", "rpent", "gptpolicy", "claude") if any(k[1] == h for k in rows)]
|
| 55 |
+
L = [f"# {a.batch}: one run per task x harness (see manifest for model / perception / style)", "",
|
| 56 |
+
"Cell = outcome of each attempt (S success, F failure); `·` = run missing. Measured from robot-server logs.", "",
|
| 57 |
+
"| task | level | " + " | ".join(HARNESS_NAME[h] for h in hs) + " |", "|---|---|" + "---|" * len(hs)]
|
| 58 |
+
for t in tasks:
|
| 59 |
+
cells = []
|
| 60 |
+
for h in hs:
|
| 61 |
+
x = rows.get((t, h))
|
| 62 |
+
cells.append("·" if x is None else (x["outcomes"] or "—"))
|
| 63 |
+
L.append(f"| {t} | {LEVEL.get(t[:2], '?')} | " + " | ".join(cells) + " |")
|
| 64 |
+
L += ["", "| harness | runs | success @1 | success @3 | grasps held / close_gripper | empty-done attempts | "
|
| 65 |
+
"commands / attempt | wall min / run |", "|---|---|---|---|---|---|---|---|"]
|
| 66 |
+
for h in hs:
|
| 67 |
+
xs = [x for (t, hh), x in rows.items() if hh == h and x["attempts"] > 0]
|
| 68 |
+
n = len(xs)
|
| 69 |
+
att = sum(x["attempts"] for x in xs)
|
| 70 |
+
L.append(f"| {HARNESS_NAME[h]} | {n} | {sum(1 for x in xs if x['first'] == 1)} | "
|
| 71 |
+
f"{sum(1 for x in xs if x['first'])} | {sum(x['held'] for x in xs)} / {sum(x['closes'] for x in xs)} | "
|
| 72 |
+
f"{sum(x['empty'] for x in xs)} / {att} | {sum(x['cmds'] for x in xs) / max(att, 1):.1f} | "
|
| 73 |
+
f"{sum(x['wall'] or 0 for x in xs) / max(n, 1):.0f} |")
|
| 74 |
+
by_level = collections.defaultdict(lambda: [0, 0])
|
| 75 |
+
for (t, h), x in rows.items():
|
| 76 |
+
if x["attempts"]:
|
| 77 |
+
by_level[LEVEL.get(t[:2], "?")][0] += bool(x["first"])
|
| 78 |
+
by_level[LEVEL.get(t[:2], "?")][1] += 1
|
| 79 |
+
L += ["", "Success @3 by level (all harnesses pooled): " +
|
| 80 |
+
", ".join(f"{lv} {s}/{n}" for lv, (s, n) in sorted(by_level.items()))]
|
| 81 |
+
txt = "\n".join(L)
|
| 82 |
+
print(txt)
|
| 83 |
+
if a.out:
|
| 84 |
+
with open(a.out, "w") as f:
|
| 85 |
+
f.write(txt + "\n")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
if __name__ == "__main__":
|
| 89 |
+
main()
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/full_waves.sh
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Run the remaining waves of the full GPT-6 run: wait until at most MAX_LEFT (default 4) runs of the batch are still going, stop the
|
| 3 |
+
# robot servers of ended runs (keeps memory bounded), then launch the next wave on all three harnesses.
|
| 4 |
+
# usage: scripts/full_waves.sh <batch> "<wave2 task:seed ...>" "<wave3 ...>" ...
|
| 5 |
+
cd "$(dirname "$0")/.."
|
| 6 |
+
B=$1; shift
|
| 7 |
+
reap() {
|
| 8 |
+
python3 - "$B" <<'PY'
|
| 9 |
+
import json, os, signal, sys, subprocess
|
| 10 |
+
b = sys.argv[1]
|
| 11 |
+
m = json.load(open(f"runs/gpt/{b}/manifest.json"))
|
| 12 |
+
st = subprocess.run(["python3", "scripts/gpt_batch.py", "status", "--batch", b], capture_output=True, text=True).stdout.splitlines()
|
| 13 |
+
running = 0
|
| 14 |
+
for r, line in zip(m["runs"], st):
|
| 15 |
+
if line.rstrip().endswith("running"):
|
| 16 |
+
running += 1
|
| 17 |
+
continue
|
| 18 |
+
try:
|
| 19 |
+
pid = int(open(os.path.join(r["log"], "server.pid")).read())
|
| 20 |
+
os.kill(pid, signal.SIGTERM)
|
| 21 |
+
except Exception:
|
| 22 |
+
pass
|
| 23 |
+
print(running)
|
| 24 |
+
PY
|
| 25 |
+
}
|
| 26 |
+
wait_below() { while true; do n=$(reap | tail -1); [ "$n" -le "$1" ] && break; sleep 120; done; }
|
| 27 |
+
port=${PORT0:-9900}
|
| 28 |
+
for W in "$@"; do
|
| 29 |
+
wait_below ${MAX_LEFT:-4}
|
| 30 |
+
echo "$(date -u +%H:%M) launching wave: $W"
|
| 31 |
+
for h in gpt_player rpent gptpolicy; do
|
| 32 |
+
python3 scripts/gpt_batch.py start --batch $B --harness $h --model gpt-6-astra --effort medium --perception rgb \
|
| 33 |
+
--style ${STYLE:-v1} --video --k 3 --port0 $port --tasks $W | grep -c '"run"'
|
| 34 |
+
port=$((port + 30))
|
| 35 |
+
done
|
| 36 |
+
done
|
| 37 |
+
wait_below 0
|
| 38 |
+
echo "$(date -u +%H:%M) all waves done"
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/gpt_batch.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Batch of GPT-player runs on robot_server sessions (same sessions / README / images as the Claude players).
|
| 2 |
+
|
| 3 |
+
start python scripts/gpt_batch.py start --batch exp2 --model gpt-6-astra --perception rgb --video \
|
| 4 |
+
--tasks l1_bias_place:1000,1001 l5_slide_to_target:1000,1001 --port0 9710
|
| 5 |
+
-> one server + one gpt_player process per (task, seed); manifest at runs/gpt/<batch>/manifest.json
|
| 6 |
+
status python scripts/gpt_batch.py status --batch exp2
|
| 7 |
+
table python scripts/gpt_batch.py table --batch exp2
|
| 8 |
+
stop python scripts/gpt_batch.py stop --batch exp2 (stops the robot servers and any player still running)
|
| 9 |
+
"""
|
| 10 |
+
import argparse
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
import subprocess
|
| 14 |
+
import sys
|
| 15 |
+
|
| 16 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 17 |
+
sys.path.insert(0, os.path.join(ROOT, "scripts"))
|
| 18 |
+
from claude_batch import run_stats # noqa: E402
|
| 19 |
+
|
| 20 |
+
RUNS = os.path.join(ROOT, "runs", "gpt")
|
| 21 |
+
# OPENAI_API_KEY / OPENAI_BASE_URL: taken from this file if it exists (KEY=value lines), else from the environment
|
| 22 |
+
ENV_FILE = os.environ.get("LFF_ENV_FILE") or os.path.join(ROOT, ".env")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def mpath(batch):
|
| 26 |
+
return os.path.join(RUNS, batch, "manifest.json")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def load(batch):
|
| 30 |
+
return json.load(open(mpath(batch)))
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def save(batch, m):
|
| 34 |
+
os.makedirs(os.path.dirname(mpath(batch)), exist_ok=True)
|
| 35 |
+
json.dump(m, open(mpath(batch), "w"), indent=1)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def port_free(port):
|
| 39 |
+
import socket
|
| 40 |
+
with socket.socket() as so:
|
| 41 |
+
try:
|
| 42 |
+
so.bind(("127.0.0.1", port))
|
| 43 |
+
return True
|
| 44 |
+
except OSError:
|
| 45 |
+
return False
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def cmd_start(a):
|
| 49 |
+
m = load(a.batch) if os.path.exists(mpath(a.batch)) else dict(batch=a.batch, runs=[])
|
| 50 |
+
used = {r["port"] for r in m["runs"]}
|
| 51 |
+
port = a.port0
|
| 52 |
+
env = dict(os.environ, LFF_RUNS_DIR=os.path.join(RUNS, a.batch), LFF_STYLE=a.style,
|
| 53 |
+
LFF_EXTRA_ARGS="--nominal" if a.nominal else "")
|
| 54 |
+
for spec in a.tasks:
|
| 55 |
+
task, seeds = spec.split(":")
|
| 56 |
+
for seed in seeds.split(","):
|
| 57 |
+
while port in used or not port_free(port):
|
| 58 |
+
port += 1
|
| 59 |
+
out = subprocess.run(["bash", os.path.join(ROOT, "scripts", "start_robot_session.sh"), task, seed, "full", a.feedback,
|
| 60 |
+
str(port), "direct", str(a.k), f"{a.batch}-{a.harness}" + ("-nominal" if a.nominal else ""), a.perception,
|
| 61 |
+
"1" if a.video else "0"], capture_output=True, text=True, env=env)
|
| 62 |
+
kv = dict(l.split("=", 1) for l in out.stdout.splitlines() if l.startswith(("SANDBOX=", "LOG=")))
|
| 63 |
+
if "LOG" not in kv:
|
| 64 |
+
print("server failed", task, seed, out.stdout[-500:], out.stderr[-500:])
|
| 65 |
+
continue
|
| 66 |
+
used.add(port)
|
| 67 |
+
log = kv["LOG"]
|
| 68 |
+
if a.harness == "gpt_player":
|
| 69 |
+
player = (f"cd {ROOT} && source run_env.sh >/dev/null 2>&1 && "
|
| 70 |
+
f"{{ [ ! -f {ENV_FILE} ] || {{ set -a && source {ENV_FILE} && set +a; }}; }} && "
|
| 71 |
+
f"exec python scripts/gpt_player.py --session {log}/session.json --model {a.model} "
|
| 72 |
+
f"--effort {a.effort} --style {a.style} > {log}/gpt_player.log 2>&1")
|
| 73 |
+
elif a.harness == "rpent":
|
| 74 |
+
player = (f"bash {ROOT}/scripts/rpent_player.sh {log}/session.json --model {a.model} --effort {a.effort} "
|
| 75 |
+
f"> {log}/rpent_player.out 2>&1")
|
| 76 |
+
else: # gptpolicy
|
| 77 |
+
player = (f"GPTPOLICY_MODEL={a.model} GPTPOLICY_EFFORT={a.effort} GPTPOLICY_KEEP_SERVER=1 "
|
| 78 |
+
f"bash {ROOT}/scripts/gptpolicy_player.sh {log}/session.json > {log}/gptpolicy_player.out 2>&1")
|
| 79 |
+
# detach stdio: otherwise a player that does not exec keeps the caller's stdout pipe open and the
|
| 80 |
+
# caller (e.g. `gpt_batch.py start ... | grep`) blocks until the run ends
|
| 81 |
+
p = subprocess.Popen(["bash", "-c", player], start_new_session=True, stdin=subprocess.DEVNULL,
|
| 82 |
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
| 83 |
+
r = dict(run=os.path.basename(log), task=task, seed=int(seed), model=a.model, effort=a.effort, cond="harness",
|
| 84 |
+
rep=0, k=a.k, port=port, sandbox=kv["SANDBOX"], log=log, perception=a.perception, player_pid=p.pid,
|
| 85 |
+
harness=a.harness, style=a.style, nominal=a.nominal)
|
| 86 |
+
m["runs"].append(r)
|
| 87 |
+
print(json.dumps(dict(run=r["run"], pid=p.pid)), flush=True)
|
| 88 |
+
save(a.batch, m)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def cmd_status(a):
|
| 92 |
+
for r in load(a.batch)["runs"]:
|
| 93 |
+
tr = os.path.join(r["log"], "gpt_transcript.jsonl")
|
| 94 |
+
errs = 0
|
| 95 |
+
end = None
|
| 96 |
+
if os.path.exists(tr):
|
| 97 |
+
for l in open(tr):
|
| 98 |
+
d = json.loads(l)
|
| 99 |
+
errs += d["ev"] == "api_error"
|
| 100 |
+
if d["ev"] in ("end", "abort"):
|
| 101 |
+
end = d
|
| 102 |
+
ev = [json.loads(l) for l in open(os.path.join(r["log"], "events.jsonl"))]
|
| 103 |
+
n = sum(1 for e in ev if e["ev"] == "call")
|
| 104 |
+
dones = [e for e in ev if e["ev"] == "done"]
|
| 105 |
+
alive = True
|
| 106 |
+
try:
|
| 107 |
+
os.kill(r["player_pid"], 0)
|
| 108 |
+
except (ProcessLookupError, KeyError, PermissionError):
|
| 109 |
+
alive = False
|
| 110 |
+
if end:
|
| 111 |
+
state = "END" if end["ev"] == "end" else "ABORT " + end.get("reason", "")
|
| 112 |
+
else:
|
| 113 |
+
state = "running" if alive else ("END" if dones and (dones[-1]["success"] or len(dones) >= r["k"]) else "ABORT player exited")
|
| 114 |
+
print(f"{r.get('harness', 'gpt_player'):10s} {r['task']:24s} s{r['seed']} cmds={n:3d} api_err={errs} "
|
| 115 |
+
f"attempts={[('S' if d['success'] else 'F') for d in dones]} {state}")
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def cmd_table(a):
|
| 119 |
+
import collections
|
| 120 |
+
rows = []
|
| 121 |
+
for b in a.batch:
|
| 122 |
+
for r in load(b)["runs"]:
|
| 123 |
+
try:
|
| 124 |
+
st = run_stats(r)
|
| 125 |
+
except FileNotFoundError:
|
| 126 |
+
continue
|
| 127 |
+
rows.append(dict(r, **st, first_grasp=first_grasp(r), harness=r.get("harness", "gpt_player")))
|
| 128 |
+
lines = ["| harness | task | seed | attempts | first success | cmds | close_gripper (held / total) | think s/cmd | wall min |",
|
| 129 |
+
"|---|---|---|---|---|---|---|---|---|"]
|
| 130 |
+
for x in sorted(rows, key=lambda x: (x["task"], x["harness"], x["seed"])):
|
| 131 |
+
lines.append(f"| {x['harness']} | {x['task']} | {x['seed']} | {x['attempts']} | {x['first_success'] or '—'} | "
|
| 132 |
+
f"{x['n_calls']} | {x['first_grasp'][1]}/{x['first_grasp'][0]} | "
|
| 133 |
+
f"{(x['think_per_cmd'] or 0):.1f} | {(x['wall_s'] or 0) / 60:.1f} |")
|
| 134 |
+
by = collections.defaultdict(list)
|
| 135 |
+
for x in rows:
|
| 136 |
+
by[x["harness"]].append(x)
|
| 137 |
+
lines.append("")
|
| 138 |
+
for h, xs in sorted(by.items()):
|
| 139 |
+
n = len(xs)
|
| 140 |
+
g = [sum(x["first_grasp"][i] for x in xs) for i in (0, 1)]
|
| 141 |
+
lines.append(f"{h}: @1 = {sum(1 for x in xs if x['first_success'] == 1)}/{n}, "
|
| 142 |
+
f"@k = {sum(1 for x in xs if x['first_success'])}/{n}, close_gripper held {g[1]}/{g[0]}")
|
| 143 |
+
print("\n".join(lines))
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def cmd_stop(a):
|
| 147 |
+
for r in load(a.batch)["runs"]:
|
| 148 |
+
pids = [r.get("player_pid")]
|
| 149 |
+
pf = os.path.join(r["log"], "server.pid")
|
| 150 |
+
if os.path.exists(pf):
|
| 151 |
+
pids.append(int(open(pf).read()))
|
| 152 |
+
for pid in pids:
|
| 153 |
+
if pid:
|
| 154 |
+
try:
|
| 155 |
+
os.kill(pid, 15) # SIGTERM: the server closes rollout.mp4 first
|
| 156 |
+
except (ProcessLookupError, PermissionError):
|
| 157 |
+
pass
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def first_grasp(r):
|
| 161 |
+
"""(close_gripper calls, of which ended holding an object) over the whole run."""
|
| 162 |
+
tot = held = 0
|
| 163 |
+
for l in open(os.path.join(r["log"], "events.jsonl")):
|
| 164 |
+
d = json.loads(l)
|
| 165 |
+
if d.get("ev") == "call" and d.get("cmd") == "close_gripper":
|
| 166 |
+
tot += 1
|
| 167 |
+
held += bool(d.get("report", {}).get("holding_object"))
|
| 168 |
+
return tot, held
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def main():
|
| 172 |
+
ap = argparse.ArgumentParser()
|
| 173 |
+
sub = ap.add_subparsers(dest="cmd")
|
| 174 |
+
s = sub.add_parser("start")
|
| 175 |
+
s.add_argument("--batch", required=True); s.add_argument("--model", default="gpt-6-astra")
|
| 176 |
+
s.add_argument("--effort", default="medium"); s.add_argument("--tasks", nargs="+", required=True)
|
| 177 |
+
s.add_argument("--k", type=int, default=3); s.add_argument("--port0", type=int, default=9710)
|
| 178 |
+
s.add_argument("--perception", default="rgb", choices=["rgb", "depth", "rgbd"]); s.add_argument("--video", action="store_true")
|
| 179 |
+
s.add_argument("--harness", default="gpt_player", choices=["gpt_player", "rpent", "gptpolicy"])
|
| 180 |
+
s.add_argument("--style", default="v1", choices=["v1", "v2", "la"])
|
| 181 |
+
s.add_argument("--nominal", action="store_true", help="L1 control: hidden calibration error removed")
|
| 182 |
+
s.add_argument("--feedback", default="F1", choices=["F0", "F1", "F2"],
|
| 183 |
+
help="F1 = success/failure only (default since 2026-10-08); F2 = measured error, ablation only")
|
| 184 |
+
st = sub.add_parser("status"); st.add_argument("--batch", required=True)
|
| 185 |
+
t = sub.add_parser("table"); t.add_argument("--batch", nargs="+", required=True)
|
| 186 |
+
sp = sub.add_parser("stop"); sp.add_argument("--batch", required=True)
|
| 187 |
+
a = ap.parse_args()
|
| 188 |
+
dict(start=cmd_start, status=cmd_status, table=cmd_table, stop=cmd_stop)[a.cmd](a)
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
if __name__ == "__main__":
|
| 192 |
+
main()
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/gpt_player.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Old entry point of the GPT player, kept so existing commands keep working: the code now lives in api_player.py
|
| 2 |
+
(the unified harness for every provider). This runs it with --provider openai and the old transcript name.
|
| 3 |
+
|
| 4 |
+
python scripts/gpt_player.py --session runs/claude/<run>/session.json --model gpt-6-astra --effort medium [--style la]
|
| 5 |
+
"""
|
| 6 |
+
import os
|
| 7 |
+
import sys
|
| 8 |
+
import traceback
|
| 9 |
+
|
| 10 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 11 |
+
from api_player import main # noqa: E402
|
| 12 |
+
|
| 13 |
+
if __name__ == "__main__":
|
| 14 |
+
try:
|
| 15 |
+
main(default_provider="openai", transcript_name="gpt_transcript.jsonl")
|
| 16 |
+
except SystemExit:
|
| 17 |
+
raise
|
| 18 |
+
except Exception:
|
| 19 |
+
traceback.print_exc()
|
| 20 |
+
sys.exit(1)
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/gptpolicy_player.sh
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Drive one robot_server session with the GPT-Policy harness (frameworks/gpt-policy, simulated
|
| 3 |
+
# lffbench_sim adapter + OpenAI Responses provider, GPT-6 Astra, reasoning effort medium).
|
| 4 |
+
#
|
| 5 |
+
# usage: scripts/gptpolicy_player.sh <LOG>/session.json [extra gpt-policy-lffbench options]
|
| 6 |
+
# e.g. LFF_STYLE=v2 scripts/start_robot_session.sh l1_bias_place 3000 full F2 10340 direct 3 gptpolicy rgb 1
|
| 7 |
+
# scripts/gptpolicy_player.sh runs/claude/gptpolicy_l1_bias_place_s3000_..._p10340/session.json
|
| 8 |
+
# The robot_server interface (v1 / v2) is detected from the first status reply.
|
| 9 |
+
#
|
| 10 |
+
# Writes into the session's LOG directory: gptpolicy_transcript.jsonl (every model request/response,
|
| 11 |
+
# images as file paths + sha256, every robot-server call), final_report.md, gptpolicy_player.log and
|
| 12 |
+
# GPT-Policy's own recording gptpolicy_run_*/. The robot server writes events.jsonl and rollout.mp4.
|
| 13 |
+
# The server is stopped at the end (it has finished the episode, and rollout.mp4 is closed by then).
|
| 14 |
+
set -uo pipefail
|
| 15 |
+
[ $# -ge 1 ] || { echo "usage: $0 <LOG>/session.json [options]"; exit 2; }
|
| 16 |
+
SESSION=$(readlink -f "$1"); shift
|
| 17 |
+
LOG=$(dirname "$SESSION")
|
| 18 |
+
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
| 19 |
+
[ -f "$ROOT/env.local.sh" ] && source "$ROOT/env.local.sh"
|
| 20 |
+
# GPT-Policy checkout + venv from integrations/gpt-policy/setup.sh (override: GPTPOLICY_VENV)
|
| 21 |
+
VENV=${GPTPOLICY_VENV:-$ROOT/third_party/gpt-policy/.venv}
|
| 22 |
+
ENVF=${LFF_ENV_FILE:-$ROOT/.env}
|
| 23 |
+
[ -f "$ENVF" ] && { set -a; source "$ENVF"; set +a; } # OPENAI_API_KEY / OPENAI_BASE_URL / SSL_CERT_FILE (never echoed)
|
| 24 |
+
export PYTHONUNBUFFERED=1
|
| 25 |
+
stop_server() { # also on abnormal exit; SIGTERM makes the server close rollout.mp4 first
|
| 26 |
+
if [ "${GPTPOLICY_KEEP_SERVER:-0}" != "1" ] && [ -f "$LOG/server.pid" ]; then
|
| 27 |
+
kill "$(cat "$LOG/server.pid")" 2>/dev/null || true
|
| 28 |
+
fi
|
| 29 |
+
}
|
| 30 |
+
trap stop_server EXIT
|
| 31 |
+
trap 'exit 143' TERM INT HUP
|
| 32 |
+
cd /tmp # neutral working directory; the model has no file access anyway
|
| 33 |
+
"$VENV/bin/gpt-policy-lffbench" --session "$SESSION" --model "${GPTPOLICY_MODEL:-gpt-6-astra}" \
|
| 34 |
+
--effort "${GPTPOLICY_EFFORT:-medium}" "$@" 2>&1 | tee -a "$LOG/gptpolicy_player.log"
|
| 35 |
+
RC=${PIPESTATUS[0]}
|
| 36 |
+
echo "gptpolicy_player.sh: gpt-policy-lffbench exit code $RC" >> "$LOG/gptpolicy_player.log"
|
| 37 |
+
exit $RC
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/harness_run.py
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run one robot_server session (style la) with one agent harness through its adapter (lffbench/harnesses, docs/15).
|
| 2 |
+
|
| 3 |
+
python scripts/harness_run.py --harness claude_code --session runs/<...>/session.json --model claude-sonnet-5-5 --effort high
|
| 4 |
+
python scripts/harness_run.py --harness codex --session ... --model gpt-6-astra --effort high
|
| 5 |
+
python scripts/harness_run.py --harness ours --session ... --provider anthropic --model ... --effort high
|
| 6 |
+
|
| 7 |
+
Harnesses: ours (scripts/api_player.py, unchanged), claude_code (arm B, --bare), claude_code_full (arm B', no --bare),
|
| 8 |
+
codex (arm F), rpent_codex (RPent, a robot harness framework, on the same Codex; tools through the episode's tool
|
| 9 |
+
gateway, lffbench/harnesses/rpent.py). Native harnesses get the reference driver's instructions + first status report as their first user
|
| 10 |
+
message (byte-identical README), only our MCP server (scripts/mcp_robot_server.py) as tools, a one-time HOME / config
|
| 11 |
+
dir, an opaque work dir /tmp/lffrun/<12 hex> and a process environment that is exactly a whitelist.
|
| 12 |
+
|
| 13 |
+
API variables (never inherited from the calling Claude Code / Codex session):
|
| 14 |
+
claude_code*: --claude-auth oauth (default for claude_code_full): a Claude subscription, the long-lived token of
|
| 15 |
+
`claude setup-token` from LFF_CLAUDE_OAUTH_TOKEN or the KEY=value file LFF_CLAUDE_OAUTH_FILE (key
|
| 16 |
+
LFF_CLAUDE_OAUTH_TOKEN or CLAUDE_CODE_OAUTH_TOKEN), passed as CLAUDE_CODE_OAUTH_TOKEN;
|
| 17 |
+
--claude-auth apikey (default and only choice for claude_code, which is --bare): key
|
| 18 |
+
LFF_ANTHROPIC_API_KEY or ANTHROPIC_API_KEY;
|
| 19 |
+
endpoint --api-base-url or LFF_ANTHROPIC_BASE_URL (default: the CLI's own default, the official API)
|
| 20 |
+
codex: --codex-provider deepseek: DeepSeek's Responses endpoint (https://api.deepseek.com/), key
|
| 21 |
+
LFF_DEEPSEEK_API_KEY or DEEPSEEK_API_KEY (passed to Codex as its provider's OPENAI_API_KEY);
|
| 22 |
+
--codex-provider opencode: OpenCode Go's Responses endpoint (OPENCODE_GO_URL), key LFF_OPENCODE_API_KEY
|
| 23 |
+
or OPENCODE_API_KEY (the model gateway adds the x-opencode-session header OpenCode Go requires);
|
| 24 |
+
--codex-auth chatgpt (default): the ChatGPT subscription login of LFF_CODEX_AUTH_HOME / CODEX_HOME
|
| 25 |
+
(a copy of its auth.json, no API key; endpoint the ChatGPT Codex backend unless --api-base-url);
|
| 26 |
+
--codex-auth apikey: key LFF_OPENAI_API_KEY or OPENAI_API_KEY; endpoint --api-base-url,
|
| 27 |
+
LFF_OPENAI_BASE_URL or OPENAI_BASE_URL (as api_player), else https://api.openai.com/v1
|
| 28 |
+
dsh: DeepSeek's Messages endpoint (DEEPSEEK_ANTHROPIC_URL), or --api-base-url / LFF_DSH_BASE_URL (OpenCode Go:
|
| 29 |
+
https://opencode.ai/inference/go), key LFF_DEEPSEEK_API_KEY or DEEPSEEK_API_KEY (passed as DEEPSEEK_API_KEY)
|
| 30 |
+
ours: as api_player.py (its own environment)
|
| 31 |
+
|
| 32 |
+
Writes into the run's log dir: contract.json, first_message.txt, harness.json (harness name, version, argv with the
|
| 33 |
+
first message replaced by its sha256, env key names, contract_sha256, first_message_sha256, config_sha256, preflight
|
| 34 |
+
result), harness_preflight.json (full normalised fingerprint), the native event stream, trajectory.jsonl,
|
| 35 |
+
harness_audit.json. Exit codes: 0 done, 2 refused at launch (fail-closed), 3 harness error, 143 stopped.
|
| 36 |
+
"""
|
| 37 |
+
import argparse
|
| 38 |
+
import json
|
| 39 |
+
import os
|
| 40 |
+
import signal
|
| 41 |
+
import sys
|
| 42 |
+
import time
|
| 43 |
+
import traceback
|
| 44 |
+
|
| 45 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 46 |
+
sys.path.insert(0, ROOT)
|
| 47 |
+
from lffbench.harnesses import NAMES, ROBOT_HARNESSES, PROVIDER, EpisodeSpec, HarnessRefused, get_adapter, render_first_message # noqa: E402
|
| 48 |
+
from lffbench.harnesses import contract as C # noqa: E402
|
| 49 |
+
from lffbench.harnesses import redteam as RT # noqa: E402
|
| 50 |
+
|
| 51 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 52 |
+
from api_player import MAX_NO_TOOL, call_server, continue_nudge # noqa: E402
|
| 53 |
+
from tool_gateway import start_gateway, stop_gateway # noqa: E402
|
| 54 |
+
import model_gateway as MG # noqa: E402
|
| 55 |
+
|
| 56 |
+
ANTHROPIC_API = "https://api.anthropic.com"
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def claude_oauth_token():
|
| 60 |
+
"""The subscription token for claude_code_full --claude-auth oauth: LFF_CLAUDE_OAUTH_TOKEN, else the KEY=value
|
| 61 |
+
file LFF_CLAUDE_OAUTH_FILE. Never CLAUDE_CODE_OAUTH_TOKEN of the calling environment (that may be the calling
|
| 62 |
+
Claude Code session's own login)."""
|
| 63 |
+
tok = os.environ.get("LFF_CLAUDE_OAUTH_TOKEN")
|
| 64 |
+
if tok:
|
| 65 |
+
return tok.strip()
|
| 66 |
+
path = os.environ.get("LFF_CLAUDE_OAUTH_FILE")
|
| 67 |
+
if path and os.path.isfile(path):
|
| 68 |
+
for line in open(path):
|
| 69 |
+
k, _, v = line.strip().partition("=")
|
| 70 |
+
if k.strip().removeprefix("export ").strip() in ("LFF_CLAUDE_OAUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN") and v:
|
| 71 |
+
return v.strip().strip("'\"")
|
| 72 |
+
raise SystemExit("claude --claude-auth oauth: no token; run `claude setup-token` and put LFF_CLAUDE_OAUTH_TOKEN=... "
|
| 73 |
+
"into the file named by LFF_CLAUDE_OAUTH_FILE (or export LFF_CLAUDE_OAUTH_TOKEN)")
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def default_claude_auth(harness):
|
| 77 |
+
return "apikey" if harness == "claude_code" else "oauth"
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def api_env_for(harness, base_url, codex_auth="apikey", claude_auth="apikey", codex_provider="openai"):
|
| 81 |
+
"""-> (variables passed to the harness, endpoint or None, endpoint label for harness.json). Endpoints are never
|
| 82 |
+
written to the logs, only where they came from."""
|
| 83 |
+
if harness in ROBOT_HARNESSES:
|
| 84 |
+
if harness == "rpent_codex":
|
| 85 |
+
codex_auth = "apikey" # historical RPent implementation stays unchanged
|
| 86 |
+
harness = "codex"
|
| 87 |
+
if harness.startswith("claude_code"):
|
| 88 |
+
e = {}
|
| 89 |
+
if claude_auth == "oauth":
|
| 90 |
+
e["CLAUDE_CODE_OAUTH_TOKEN"] = claude_oauth_token()
|
| 91 |
+
else:
|
| 92 |
+
key = os.environ.get("LFF_ANTHROPIC_API_KEY") or os.environ.get("ANTHROPIC_API_KEY")
|
| 93 |
+
if key:
|
| 94 |
+
e["ANTHROPIC_API_KEY"] = key
|
| 95 |
+
url = base_url or os.environ.get("LFF_ANTHROPIC_BASE_URL")
|
| 96 |
+
if url:
|
| 97 |
+
e["ANTHROPIC_BASE_URL"] = url
|
| 98 |
+
dflt = "CLI default (official)" + (", subscription token" if claude_auth == "oauth" else "")
|
| 99 |
+
return e, url, ("--api-base-url" if base_url else "LFF_ANTHROPIC_BASE_URL") if url else dflt
|
| 100 |
+
if harness == "dsh":
|
| 101 |
+
key = os.environ.get("LFF_DEEPSEEK_API_KEY") or os.environ.get("DEEPSEEK_API_KEY")
|
| 102 |
+
from lffbench.harnesses.dsh import DEEPSEEK_ANTHROPIC_URL
|
| 103 |
+
url = base_url or os.environ.get("LFF_DSH_BASE_URL")
|
| 104 |
+
return ({"DEEPSEEK_API_KEY": key} if key else {}), url or DEEPSEEK_ANTHROPIC_URL, \
|
| 105 |
+
("--api-base-url" if base_url else "LFF_DSH_BASE_URL") if url else \
|
| 106 |
+
"DeepSeek (DEEPSEEK_ANTHROPIC_URL, key LFF_DEEPSEEK_API_KEY / DEEPSEEK_API_KEY)"
|
| 107 |
+
if harness == "codex" and codex_provider == "deepseek": # DeepSeek's own Responses endpoint, an API key
|
| 108 |
+
key = os.environ.get("LFF_DEEPSEEK_API_KEY") or os.environ.get("DEEPSEEK_API_KEY")
|
| 109 |
+
from lffbench.harnesses.codex import DEEPSEEK_URL
|
| 110 |
+
return ({"OPENAI_API_KEY": key} if key else {}), base_url or DEEPSEEK_URL, \
|
| 111 |
+
"--api-base-url" if base_url else "DeepSeek (DEEPSEEK_URL, key LFF_DEEPSEEK_API_KEY / DEEPSEEK_API_KEY)"
|
| 112 |
+
if harness == "codex" and codex_provider == "opencode": # OpenCode Go's Responses endpoint, an API key
|
| 113 |
+
key = os.environ.get("LFF_OPENCODE_API_KEY") or os.environ.get("OPENCODE_API_KEY")
|
| 114 |
+
from lffbench.harnesses.codex import OPENCODE_GO_URL
|
| 115 |
+
return ({"OPENAI_API_KEY": key} if key else {}), base_url or OPENCODE_GO_URL, \
|
| 116 |
+
"--api-base-url" if base_url else "OpenCode Go (OPENCODE_GO_URL, key LFF_OPENCODE_API_KEY / OPENCODE_API_KEY)"
|
| 117 |
+
if harness == "codex" and codex_auth == "chatgpt":
|
| 118 |
+
return {}, base_url, "--api-base-url" if base_url else "ChatGPT Codex backend (subscription login)"
|
| 119 |
+
if harness == "codex":
|
| 120 |
+
key = os.environ.get("LFF_OPENAI_API_KEY") or os.environ.get("OPENAI_API_KEY")
|
| 121 |
+
src = ("--api-base-url" if base_url else "LFF_OPENAI_BASE_URL" if os.environ.get("LFF_OPENAI_BASE_URL")
|
| 122 |
+
else "OPENAI_BASE_URL (same as api_player)" if os.environ.get("OPENAI_BASE_URL") else "official default")
|
| 123 |
+
url = base_url or os.environ.get("LFF_OPENAI_BASE_URL") or os.environ.get("OPENAI_BASE_URL")
|
| 124 |
+
return ({"OPENAI_API_KEY": key} if key else {}), url, src
|
| 125 |
+
return {}, None, "api_player's own environment"
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
RESUME_RETRIES = 3 # a resumed CLI that exits before writing any event is started again (nothing reached the model)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def mcp_tool_state(log_dir):
|
| 132 |
+
"""-> (number of MCP tool calls so far, whether our MCP server saw the episode end) from mcp_transcript.jsonl."""
|
| 133 |
+
n, finished = 0, False
|
| 134 |
+
try:
|
| 135 |
+
for line in open(os.path.join(log_dir, "mcp_transcript.jsonl")):
|
| 136 |
+
try:
|
| 137 |
+
d = json.loads(line)
|
| 138 |
+
except ValueError:
|
| 139 |
+
continue
|
| 140 |
+
if d.get("ev") == "tool":
|
| 141 |
+
n, finished = n + 1, bool(d.get("finished"))
|
| 142 |
+
except OSError:
|
| 143 |
+
pass
|
| 144 |
+
return n, finished
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def continue_episode(ad, h, ep, stop):
|
| 148 |
+
"""The CLI exited although the episode is not over (it ends when the model replies without a tool call): send
|
| 149 |
+
the reference driver's nudge as a user turn, as api_player does after such a reply, and wait again. Same rule:
|
| 150 |
+
after MAX_NO_TOOL nudges in a row without a tool call in between, the next such reply ends the run. -> log list."""
|
| 151 |
+
out, no_tool, (n_calls, _) = [], 0, mcp_tool_state(ep.log_dir)
|
| 152 |
+
deadline = h.t_start + h.spec.timeout_s
|
| 153 |
+
while ad.can_resume and h.exit_reason == "exited" and not stop["flag"]:
|
| 154 |
+
n, finished = mcp_tool_state(ep.log_dir)
|
| 155 |
+
if finished: # api_player stops here too, without a status call
|
| 156 |
+
break
|
| 157 |
+
try: # the status call api_player makes for its nudge
|
| 158 |
+
stx = json.loads(call_server(ep.port, ep.token, "status", {}))
|
| 159 |
+
except Exception as e:
|
| 160 |
+
out.append(dict(ev="status_failed", error=f"{type(e).__name__}: {e}"[:300], t=time.time()))
|
| 161 |
+
break
|
| 162 |
+
if stx.get("finished"):
|
| 163 |
+
break
|
| 164 |
+
no_tool = 1 if n > n_calls else no_tool + 1
|
| 165 |
+
n_calls = n
|
| 166 |
+
if no_tool > MAX_NO_TOOL:
|
| 167 |
+
out.append(dict(ev="abort", reason=f"no tool call {no_tool} times", t=time.time()))
|
| 168 |
+
break
|
| 169 |
+
if time.time() >= deadline:
|
| 170 |
+
h.exit_reason = "timeout"
|
| 171 |
+
break
|
| 172 |
+
msg = continue_nudge(ep.port, ep.token, stx)
|
| 173 |
+
out.append(dict(ev="resume", message=msg, attempt=stx.get("attempt"), mcp_tool_calls=n, t=time.time()))
|
| 174 |
+
for retry in range(RESUME_RETRIES + 1):
|
| 175 |
+
size0 = os.path.getsize(h.spec.stdout_path) if os.path.exists(h.spec.stdout_path) else 0
|
| 176 |
+
ad.resume(h, msg)
|
| 177 |
+
ad.wait(h, timeout=max(1.0, deadline - time.time()))
|
| 178 |
+
grew = os.path.exists(h.spec.stdout_path) and os.path.getsize(h.spec.stdout_path) > size0
|
| 179 |
+
if h.exit_reason == "exited" or grew or stop["flag"] or retry == RESUME_RETRIES \
|
| 180 |
+
or time.time() + 30 >= deadline:
|
| 181 |
+
break
|
| 182 |
+
# the resumed CLI exited before writing any event (2026-10-20: the MCP handshake timed out on a loaded
|
| 183 |
+
# machine), so nothing reached the model: start the same resume again
|
| 184 |
+
out.append(dict(ev="resume_retry", exit_reason=h.exit_reason, t=time.time()))
|
| 185 |
+
time.sleep(30)
|
| 186 |
+
return out
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def model_upstream(harness, url, codex_auth):
|
| 190 |
+
"""-> (gateway kind, the model API the harness would call without the gateway)."""
|
| 191 |
+
if harness.startswith("claude_code") or harness == "dsh":
|
| 192 |
+
return "anthropic", url or ANTHROPIC_API
|
| 193 |
+
from lffbench.harnesses.codex import CHATGPT_BACKEND, OFFICIAL_API
|
| 194 |
+
if harness == "rpent_codex":
|
| 195 |
+
return "openai", url or OFFICIAL_API
|
| 196 |
+
return "openai", url or (CHATGPT_BACKEND if codex_auth == "chatgpt" else OFFICIAL_API)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def plain_config_sha256(ad, spec, ep, mg):
|
| 200 |
+
"""config_sha256 as if the harness called its model API directly: the model gateway is plumbing (like the
|
| 201 |
+
proxy variables, base.py PROXY_KEYS), so runs with and without it keep the same configuration hash."""
|
| 202 |
+
if not mg:
|
| 203 |
+
return ad.config_sha256(spec, ep)
|
| 204 |
+
import copy
|
| 205 |
+
s2 = copy.copy(spec)
|
| 206 |
+
s2.argv = [a.replace(mg["url"], mg["upstream"]) if isinstance(a, str) else a for a in spec.argv]
|
| 207 |
+
s2.env = {k: (v.replace(mg["url"], mg["upstream"]) if isinstance(v, str) else v) for k, v in spec.env.items()}
|
| 208 |
+
return ad.config_sha256(s2, ep)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def write_json(path, d):
|
| 212 |
+
tmp = path + ".tmp"
|
| 213 |
+
with open(tmp, "w") as f:
|
| 214 |
+
json.dump(d, f, indent=1, ensure_ascii=False, default=str)
|
| 215 |
+
os.replace(tmp, path)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def run(a, adapter_kw=None):
|
| 219 |
+
"""Returns (exit code, harness.json dict). adapter_kw overrides adapter construction (self-check)."""
|
| 220 |
+
provider = a.provider or PROVIDER.get(a.harness, "")
|
| 221 |
+
ep = EpisodeSpec.from_session(a.session, a.model, a.effort, provider)
|
| 222 |
+
if getattr(a, "red_team", False): # before the contract: red-team runs get their own contract_sha256
|
| 223 |
+
if a.harness == "ours":
|
| 224 |
+
raise SystemExit("--red-team is for native harnesses")
|
| 225 |
+
RT.mark(ep.log_dir)
|
| 226 |
+
contract, csha = C.write_contract(ep.log_dir)
|
| 227 |
+
mg_box = {} # the model gateway process, stopped whatever happens below
|
| 228 |
+
try:
|
| 229 |
+
return _run(a, adapter_kw, provider, ep, csha, mg_box)
|
| 230 |
+
finally:
|
| 231 |
+
MG.stop_model_gateway(mg_box.get("proc"))
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def _run(a, adapter_kw, provider, ep, csha, mg_box):
|
| 235 |
+
mg = None
|
| 236 |
+
if adapter_kw is None:
|
| 237 |
+
a.codex_auth = getattr(a, "codex_auth", None) or ("apikey" if a.harness in ROBOT_HARNESSES else "chatgpt")
|
| 238 |
+
if a.harness == "rpent_codex" and a.codex_auth != "apikey":
|
| 239 |
+
raise SystemExit("Historical RPent adapter supports apikey only")
|
| 240 |
+
claude_auth = getattr(a, "claude_auth", None) or default_claude_auth(a.harness)
|
| 241 |
+
if getattr(a, "codex_provider", "openai") in ("deepseek", "opencode"):
|
| 242 |
+
a.codex_auth = "apikey" # no subscription login for DeepSeek / OpenCode Go
|
| 243 |
+
api_env, url, endpoint = api_env_for(a.harness, a.api_base_url, getattr(a, "codex_auth", "apikey"),
|
| 244 |
+
claude_auth, getattr(a, "codex_provider", "openai"))
|
| 245 |
+
if a.harness != "ours" and not getattr(a, "no_model_gateway", False):
|
| 246 |
+
# the harness reaches its model API only through the model gateway (scripts/model_gateway.py)
|
| 247 |
+
kind, upstream = model_upstream(a.harness, url, a.codex_auth)
|
| 248 |
+
mg_box["proc"], mginfo = MG.start_model_gateway(upstream, kind, ep.log_dir,
|
| 249 |
+
getattr(a, "token_budget_in", None),
|
| 250 |
+
getattr(a, "token_budget_out", None),
|
| 251 |
+
allow_files=a.harness == "dsh")
|
| 252 |
+
mg = dict(url=mginfo["url"], upstream=upstream, kind=kind, upstream_host=mginfo["upstream_host"],
|
| 253 |
+
pid=mginfo["pid"])
|
| 254 |
+
url = mg["url"]
|
| 255 |
+
if a.harness.startswith("claude_code"):
|
| 256 |
+
api_env["ANTHROPIC_BASE_URL"] = url
|
| 257 |
+
adapter_kw = dict(timeout_s=a.timeout)
|
| 258 |
+
if a.harness.startswith("claude_code"):
|
| 259 |
+
adapter_kw.update(api_env=api_env, max_budget_usd=a.max_budget_usd, allow_unpinned=a.allow_unpinned,
|
| 260 |
+
auth=claude_auth)
|
| 261 |
+
elif a.harness == "codex":
|
| 262 |
+
adapter_kw.update(api_env=api_env, base_url=url, allow_unpinned=a.allow_unpinned, auth=a.codex_auth,
|
| 263 |
+
catalog=a.codex_catalog)
|
| 264 |
+
elif a.harness == "dsh":
|
| 265 |
+
adapter_kw.update(api_env=api_env, base_url=url, allow_unpinned=a.allow_unpinned)
|
| 266 |
+
elif a.harness in ROBOT_HARNESSES:
|
| 267 |
+
adapter_kw.update(api_env=api_env, base_url=url, allow_unpinned=a.allow_unpinned,
|
| 268 |
+
auth=a.codex_auth, catalog=a.codex_catalog)
|
| 269 |
+
if a.harness == "rpent_codex": # historical, explicitly exposed RPent experiment settings
|
| 270 |
+
adapter_kw.update(sessions=a.rpent_sessions, attempts_per_session=a.rpent_attempts_per_session,
|
| 271 |
+
max_turns=a.rpent_max_turns)
|
| 272 |
+
if getattr(a, "jail", False):
|
| 273 |
+
if a.harness == "ours":
|
| 274 |
+
raise SystemExit("--jail is for native harnesses")
|
| 275 |
+
adapter_kw["jail"] = True
|
| 276 |
+
else:
|
| 277 |
+
adapter_kw.update(provider=provider)
|
| 278 |
+
else:
|
| 279 |
+
endpoint = "set by the caller (self-check)"
|
| 280 |
+
ad = get_adapter(a.harness, **adapter_kw)
|
| 281 |
+
ver = ad.version()
|
| 282 |
+
hj_path = os.path.join(ep.log_dir, "harness.json")
|
| 283 |
+
hj = dict(harness=ad.name, version=ver.get("version"), binary=ver.get("binary"), model=a.model, effort=a.effort,
|
| 284 |
+
provider=provider, capabilities={k: vars(c) for k, c in ad.capabilities.items()},
|
| 285 |
+
contract_sha256=csha, task=ep.task, seed=ep.seed, api_endpoint_from=endpoint, status="preparing",
|
| 286 |
+
t_prepare=time.time(), jail=ad.jail_info(), auth=ad.auth_info() if ad.name != "ours" else None,
|
| 287 |
+
config=ad.config_info() if hasattr(ad, "config_info") else None,
|
| 288 |
+
model_gateway=({k: mg[k] for k in ("kind", "upstream_host", "pid")} if mg else None))
|
| 289 |
+
if ad.name == "ours":
|
| 290 |
+
first = None
|
| 291 |
+
spec = ad.prepare(ep)
|
| 292 |
+
else:
|
| 293 |
+
first, _ = render_first_message(ep)
|
| 294 |
+
if getattr(a, "red_team", False):
|
| 295 |
+
first = RT.first_message(first)
|
| 296 |
+
hj["red_team"] = RT.marker(ep.log_dir)
|
| 297 |
+
with open(os.path.join(ep.log_dir, "first_message.txt"), "w") as f:
|
| 298 |
+
f.write(first)
|
| 299 |
+
spec = ad.prepare(ep, first, **(dict(reuse_state=a.reuse_state) if getattr(a, "reuse_state", None) else {}))
|
| 300 |
+
hj["first_message_sha256"] = C.sha256_text(first)
|
| 301 |
+
hj.update(argv=ad.logged_argv(spec), cwd=spec.cwd, env_keys=sorted(spec.env),
|
| 302 |
+
env_mode="exact whitelist (Popen env=, same as env -i)" if ad.name != "ours" else "inherited (own code)",
|
| 303 |
+
state_dirs=spec.state_dirs, config_sha256=plain_config_sha256(ad, spec, ep, mg), status="launching")
|
| 304 |
+
write_json(hj_path, hj)
|
| 305 |
+
h, code, gw = None, 0, None
|
| 306 |
+
stop = dict(flag=False)
|
| 307 |
+
|
| 308 |
+
def on_term(*_):
|
| 309 |
+
stop["flag"] = True
|
| 310 |
+
if h is not None and h.proc is not None:
|
| 311 |
+
ad.kill(h)
|
| 312 |
+
signal.signal(signal.SIGTERM, on_term)
|
| 313 |
+
try:
|
| 314 |
+
if (ad.uses_mcp or ad.uses_gateway) and not getattr(a, "no_gateway", False): # the episode's tools, for
|
| 315 |
+
# every MCP process of the run / every SDK client of a framework adapter (base.HarnessAdapter.uses_gateway)
|
| 316 |
+
gw, ginfo = start_gateway(ep.session_path)
|
| 317 |
+
hj["gateway"] = dict(url=ginfo["url"], pid=ginfo["pid"])
|
| 318 |
+
try:
|
| 319 |
+
h = ad.launch(spec, ep, skip_preflight=getattr(a, "skip_preflight", False))
|
| 320 |
+
except HarnessRefused as e:
|
| 321 |
+
pre = dict(spec.preflight or {})
|
| 322 |
+
hj.update(status="refused", refused=str(e), preflight={k: v for k, v in pre.items() if k != "fingerprint"})
|
| 323 |
+
write_json(hj_path, hj)
|
| 324 |
+
print("REFUSED:", e, flush=True)
|
| 325 |
+
return 2, hj
|
| 326 |
+
pre = dict(spec.preflight or {})
|
| 327 |
+
if "fingerprint" in pre:
|
| 328 |
+
write_json(os.path.join(ep.log_dir, "harness_preflight.json"), pre)
|
| 329 |
+
hj.update(status="running", pid=h.pid, env_observed_keys=h.env_observed_keys, t_start=h.t_start,
|
| 330 |
+
preflight={k: v for k, v in pre.items() if k != "fingerprint"}, init=h.info.get("init"))
|
| 331 |
+
write_json(hj_path, hj)
|
| 332 |
+
ad.wait(h)
|
| 333 |
+
cont = [] if getattr(a, "no_continue", False) else continue_episode(ad, h, ep, stop)
|
| 334 |
+
if cont:
|
| 335 |
+
hj["continuation"] = cont
|
| 336 |
+
write_json(hj_path, hj)
|
| 337 |
+
if stop["flag"]:
|
| 338 |
+
h.exit_reason, code = "stopped", 143
|
| 339 |
+
tw = ad.collect(h)
|
| 340 |
+
au = ad.audit(h)
|
| 341 |
+
if ad.name == "ours" and spec.first_message:
|
| 342 |
+
hj["first_message_sha256"] = C.sha256_text(spec.first_message)
|
| 343 |
+
hj.update(status="done" if code == 0 else "stopped", exit_code=h.exit_code, exit_reason=h.exit_reason,
|
| 344 |
+
t_end=h.t_end, wall_s=round(h.t_end - h.t_start, 1), audit_ok=au.get("ok"),
|
| 345 |
+
violations=au.get("violations"), final_metrics=(tw.final or {}).get("final_metrics"))
|
| 346 |
+
if mg: # refusals do not void the trial; they flag it for a look (EFE running.md "Usage gateway")
|
| 347 |
+
tot = MG.read_totals(ep.log_dir) or {}
|
| 348 |
+
hj["model_gateway"].update({k: tot.get(k) for k in MG.Totals.KEYS}, tokens=tot.get("tokens"),
|
| 349 |
+
models=tot.get("models"), budget_stop=tot.get("budget_stop"))
|
| 350 |
+
hj["review_flags"] = ["model_gateway:" + k for k in MG.flagged(tot)] + (
|
| 351 |
+
["model_gateway:other_model"] if set(tot.get("models") or {}) - {a.model} else [])
|
| 352 |
+
if code == 0 and h.exit_code not in (0, None):
|
| 353 |
+
code = 3
|
| 354 |
+
write_json(hj_path, hj)
|
| 355 |
+
return code, hj
|
| 356 |
+
except Exception as e:
|
| 357 |
+
hj.update(status="error", error=f"{type(e).__name__}: {e}", traceback=traceback.format_exc()[-3000:])
|
| 358 |
+
write_json(hj_path, hj)
|
| 359 |
+
if h is not None and h.proc is not None and h.proc.poll() is None:
|
| 360 |
+
ad.kill(h)
|
| 361 |
+
return 3, hj
|
| 362 |
+
finally:
|
| 363 |
+
stop_gateway(gw)
|
| 364 |
+
if not getattr(a, "keep_run_dir", False):
|
| 365 |
+
ad.cleanup(spec)
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def parser():
|
| 369 |
+
ap = argparse.ArgumentParser()
|
| 370 |
+
ap.add_argument("--harness", required=True, choices=NAMES)
|
| 371 |
+
ap.add_argument("--session", required=True)
|
| 372 |
+
ap.add_argument("--provider", default=None, help="ours: openai / anthropic / gemini / chat")
|
| 373 |
+
ap.add_argument("--model", required=True)
|
| 374 |
+
ap.add_argument("--effort", default="high")
|
| 375 |
+
ap.add_argument("--api-base-url", default=None)
|
| 376 |
+
ap.add_argument("--codex-auth", default=None, choices=["chatgpt", "apikey"],
|
| 377 |
+
help="Codex authentication: chatgpt defaults for codex; apikey defaults for Robot Harnesses. "
|
| 378 |
+
"SenseNova/EmbodiedEvo also support chatgpt; historical RPent is apikey only")
|
| 379 |
+
ap.add_argument("--claude-auth", default=None, choices=["oauth", "apikey"],
|
| 380 |
+
help="claude_code*: subscription token (default for claude_code_full) or an API key (claude_code, "
|
| 381 |
+
"--bare, takes only an API key); see above")
|
| 382 |
+
ap.add_argument("--codex-provider", default="openai", choices=["openai", "deepseek", "opencode"],
|
| 383 |
+
help="codex: model provider; deepseek = DeepSeek's Responses endpoint with LFF_DEEPSEEK_API_KEY / "
|
| 384 |
+
"DEEPSEEK_API_KEY, opencode = OpenCode Go's with LFF_OPENCODE_API_KEY / OPENCODE_API_KEY "
|
| 385 |
+
"(both imply --codex-auth apikey)")
|
| 386 |
+
ap.add_argument("--codex-catalog", default="generic", choices=["generic", "native"],
|
| 387 |
+
help="codex: model catalog, the main table's shared configuration (default) or Codex's native "
|
| 388 |
+
"one (control); see lffbench/harnesses/codex.py")
|
| 389 |
+
ap.add_argument("--max-budget-usd", type=float, default=None, help="claude_code*: --max-budget-usd")
|
| 390 |
+
ap.add_argument("--rpent-sessions", type=int, default=5,
|
| 391 |
+
help="rpent_codex: planner sessions per episode (RPent --explore-sessions; default 5 = k + 2 spare)")
|
| 392 |
+
ap.add_argument("--rpent-attempts-per-session", type=int, default=1,
|
| 393 |
+
help="rpent_codex: attempts one session may use (RPent --explore-attempts-per-session): 1 = "
|
| 394 |
+
"variant H, a fresh session with a handoff after each failed attempt (default); 0 = no limit")
|
| 395 |
+
ap.add_argument("--rpent-max-turns", type=int, default=100,
|
| 396 |
+
help="rpent_codex: model responses per session (RPent --max-turns)")
|
| 397 |
+
ap.add_argument("--timeout", type=float, default=10800)
|
| 398 |
+
ap.add_argument("--allow-unpinned", action="store_true",
|
| 399 |
+
help="launch even if no pin exists for this version / model / effort (the preflight still runs)")
|
| 400 |
+
ap.add_argument("--keep-run-dir", action="store_true", help="do not delete the one-time dirs (debugging)")
|
| 401 |
+
ap.add_argument("--no-gateway", action="store_true",
|
| 402 |
+
help="native harnesses: run the tools inside each MCP server process instead of the episode's "
|
| 403 |
+
"tool gateway (scripts/tool_gateway.py; same ToolCore, budget carried over via the transcript)")
|
| 404 |
+
ap.add_argument("--no-model-gateway", action="store_true",
|
| 405 |
+
help="native harnesses: call the model API directly instead of through the run's model gateway "
|
| 406 |
+
"(scripts/model_gateway.py: model calls only, provider-side tools refused, tokens counted)")
|
| 407 |
+
ap.add_argument("--token-budget-in", type=int, default=None,
|
| 408 |
+
help="model gateway: refuse further model calls once this many input tokens were used (cached "
|
| 409 |
+
"input counts in full)")
|
| 410 |
+
ap.add_argument("--token-budget-out", type=int, default=None,
|
| 411 |
+
help="model gateway: ... output tokens (reasoning included)")
|
| 412 |
+
ap.add_argument("--red-team", action="store_true",
|
| 413 |
+
help="adversarial acceptance run (lffbench/harnesses/redteam.py): the first message starts with the "
|
| 414 |
+
"red-team notice; own contract_sha256; read with scripts/redteam_report.py")
|
| 415 |
+
ap.add_argument("--no-continue", action="store_true",
|
| 416 |
+
help="do not resume a CLI that exited before the episode was over (self-check / debugging)")
|
| 417 |
+
ap.add_argument("--jail", action="store_true",
|
| 418 |
+
help="native harnesses: run the CLI in the native-harness jail (docs/15 §3.4): as uid 65534, no host "
|
| 419 |
+
"path visible, MCP server outside behind a socket relay")
|
| 420 |
+
return ap
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
def main():
|
| 424 |
+
code, hj = run(parser().parse_args())
|
| 425 |
+
print(json.dumps({k: hj.get(k) for k in ("harness", "status", "exit_reason", "audit_ok", "violations",
|
| 426 |
+
"contract_sha256", "final_metrics")}, default=str), flush=True)
|
| 427 |
+
sys.exit(code)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
if __name__ == "__main__":
|
| 431 |
+
main()
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/headroom_parts_cart.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Incremental physical headroom evaluation of the composite prototype."""
|
| 2 |
+
import argparse,hashlib,json,time
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
from lffbench.tasks.lh_parts_cart import PartsCart
|
| 6 |
+
|
| 7 |
+
def clean(x):
|
| 8 |
+
if isinstance(x,np.ndarray):return x.tolist()
|
| 9 |
+
if isinstance(x,np.generic):return x.item()
|
| 10 |
+
raise TypeError(type(x).__name__)
|
| 11 |
+
p=argparse.ArgumentParser();p.add_argument('--kind',choices=['oracle','naive','adaptive','blind'],required=True);p.add_argument('--n',type=int,default=20);p.add_argument('--k',type=int,default=5);p.add_argument('--out',required=True);a=p.parse_args()
|
| 12 |
+
out=Path(a.out);out.parent.mkdir(parents=True,exist_ok=True);x=PartsCart();rows=[];start=time.time()
|
| 13 |
+
source=Path(__file__).parents[1]/'lffbench/tasks/lh_parts_cart.py';code_hash=hashlib.sha256(source.read_bytes()).hexdigest()
|
| 14 |
+
for seed in range(1000,1000+a.n):
|
| 15 |
+
i=x.sample_instance(seed);h=x.run_scripted(a.kind,i,k=a.k,seed=seed)
|
| 16 |
+
rows.append(dict(seed=seed,history=h));succ=sum(any(z['outcome']['success'] for z in row['history']) for row in rows)
|
| 17 |
+
out.write_text(json.dumps(dict(kind=a.kind,n_planned=a.n,n_complete=len(rows),k=a.k,successes=succ,rows=rows,seconds=time.time()-start,task_sha256=code_hash,status='complete' if len(rows)==a.n else 'running',note='scripted privileged-state headroom; fixed geometry, randomized inertia only'),indent=2,default=clean))
|
| 18 |
+
print(seed,a.kind,[z['outcome']['success'] for z in h], 'successes',succ,flush=True)
|
| 19 |
+
x.env.close()
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_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"]))
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/la_report.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Per-run table for LA-interface (LIBERO-Agent-style) GPT runs: outcomes from the robot-server log, tool use and
|
| 2 |
+
token cost from the player transcript.
|
| 3 |
+
|
| 4 |
+
python scripts/la_report.py --batch la1_rgb la1_rgbd [--out ../docs/la1_table.md]
|
| 5 |
+
"""
|
| 6 |
+
import argparse
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import sys
|
| 10 |
+
|
| 11 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 12 |
+
sys.path.insert(0, os.path.join(ROOT, "scripts"))
|
| 13 |
+
from full_report import run_info # noqa: E402
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def transcript_stats(log):
|
| 17 |
+
p = os.path.join(log, "transcript.jsonl") # api_player (unified harness); gpt_player wrote gpt_transcript.jsonl
|
| 18 |
+
if not os.path.exists(p):
|
| 19 |
+
p = os.path.join(log, "gpt_transcript.jsonl")
|
| 20 |
+
st = dict(turns=0, shell=0, view=0, robot=0, auto_finish=0, api_err=0, inp=0, cached=0, out=0, reason=0, ended=None)
|
| 21 |
+
if not os.path.exists(p):
|
| 22 |
+
au = os.path.join(log, "audit.json") # Claude subagent runs: tool counts from the audit of its transcript
|
| 23 |
+
if os.path.exists(au):
|
| 24 |
+
d = json.load(open(au))
|
| 25 |
+
bt = d.get("by_tool", {})
|
| 26 |
+
st.update(turns=d.get("n_calls", 0), view=bt.get("Read", 0), shell=bt.get("Bash", 0),
|
| 27 |
+
ended=f"audited ({d.get('n_violations')} violations, memory_injected={d.get('memory_injected')})")
|
| 28 |
+
return st
|
| 29 |
+
for l in open(p):
|
| 30 |
+
d = json.loads(l)
|
| 31 |
+
ev = d["ev"]
|
| 32 |
+
if ev == "assistant":
|
| 33 |
+
st["turns"] += 1
|
| 34 |
+
u = d.get("usage") or {}
|
| 35 |
+
st["inp"] += u.get("input_tokens", 0)
|
| 36 |
+
st["cached"] += u.get("cached_tokens", 0)
|
| 37 |
+
st["out"] += u.get("output_tokens", 0)
|
| 38 |
+
st["reason"] += u.get("reasoning_tokens", 0)
|
| 39 |
+
elif ev == "tool":
|
| 40 |
+
c = d.get("command", "")
|
| 41 |
+
if c.startswith("shell:"):
|
| 42 |
+
st["shell"] += 1
|
| 43 |
+
elif c.startswith("view_images"):
|
| 44 |
+
st["view"] += 1
|
| 45 |
+
else:
|
| 46 |
+
st["robot"] += 1
|
| 47 |
+
elif ev == "user" and d.get("auto_finish"):
|
| 48 |
+
st["auto_finish"] += 1
|
| 49 |
+
elif ev == "api_error":
|
| 50 |
+
st["api_err"] += 1
|
| 51 |
+
elif ev in ("end", "abort"):
|
| 52 |
+
st["ended"] = ev if ev == "end" else "abort: " + d.get("reason", "")
|
| 53 |
+
return st
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def main():
|
| 57 |
+
ap = argparse.ArgumentParser()
|
| 58 |
+
ap.add_argument("--batch", nargs="+", required=True)
|
| 59 |
+
ap.add_argument("--out", default=None)
|
| 60 |
+
ap.add_argument("--runs", default="gpt", help="runs/<runs>/<batch> (gpt or claude); for claude, 'shell' = all Bash "
|
| 61 |
+
"calls (robot + shell) and 'view' = Read calls, from audit.json")
|
| 62 |
+
a = ap.parse_args()
|
| 63 |
+
L = ["| batch | task | perception | outcomes | robot cmds | grasps held/closed | shell | view | turns | "
|
| 64 |
+
"auto-finish | input Mtok (cached) | output ktok (reasoning) | wall min | state |",
|
| 65 |
+
"|---|---|---|---|---|---|---|---|---|---|---|---|---|---|"]
|
| 66 |
+
tot = dict(inp=0, cached=0, out=0, reason=0)
|
| 67 |
+
for b in a.batch:
|
| 68 |
+
m = json.load(open(os.path.join(ROOT, "runs", a.runs, b, "manifest.json")))
|
| 69 |
+
for r in m["runs"]:
|
| 70 |
+
try:
|
| 71 |
+
x = run_info(r)
|
| 72 |
+
except FileNotFoundError:
|
| 73 |
+
continue
|
| 74 |
+
t = transcript_stats(r["log"])
|
| 75 |
+
for k in tot:
|
| 76 |
+
tot[k] += t[k]
|
| 77 |
+
task = r["task"] + (" (nominal)" if r.get("nominal") else "")
|
| 78 |
+
L.append(f"| {b} | {task} | {r.get('perception')} | {x['outcomes'] or '—'} | {x['cmds']} | "
|
| 79 |
+
f"{x['held']}/{x['closes']} | {t['shell']} | {t['view']} | {t['turns']} | {t['auto_finish']} | "
|
| 80 |
+
f"{t['inp'] / 1e6:.2f} ({t['cached'] / 1e6:.2f}) | {t['out'] / 1e3:.0f} ({t['reason'] / 1e3:.0f}) | "
|
| 81 |
+
f"{(x['wall'] or 0):.0f} | {t['ended'] or 'running'} |")
|
| 82 |
+
L.append("")
|
| 83 |
+
L.append(f"Total tokens: input {tot['inp'] / 1e6:.2f} M (cached {tot['cached'] / 1e6:.2f} M), "
|
| 84 |
+
f"output {tot['out'] / 1e3:.0f} k (reasoning {tot['reason'] / 1e3:.0f} k).")
|
| 85 |
+
txt = "\n".join(L)
|
| 86 |
+
print(txt)
|
| 87 |
+
if a.out:
|
| 88 |
+
with open(a.out, "w") as f:
|
| 89 |
+
f.write(txt + "\n")
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
if __name__ == "__main__":
|
| 93 |
+
main()
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/ladder_gpt_plan.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Layer-3 feedback ladder for GPT-6 Astra (user 2026-11-02: "跑吧"; same design as scripts/ladder_plan.py, docs/20).
|
| 2 |
+
Instances: the main-table attempt 1 failures of GPT-6 Astra on the 8 ladder tasks (turntable left out, as in the
|
| 3 |
+
reported Claude totals). Fresh single-attempt agents, Codex 0.163 generic config, jail, high, F1, one round. The F1 rung
|
| 4 |
+
is run here (batch lf1_gpt): GPT has no mismatch-control Do arm to reuse.
|
| 5 |
+
|
| 6 |
+
python scripts/ladder_gpt_plan.py validate Fix texts for instances Claude's ladder did not cover -> results/_ladder/fix_validate_gpt.json
|
| 7 |
+
python scripts/ladder_gpt_plan.py build records -> runs/api/ladder_gpt_20261102/<rung>.json + tasks.txt
|
| 8 |
+
python scripts/ladder_gpt_plan.py report per instance rungs and totals, next to Opus and Sonnet
|
| 9 |
+
"""
|
| 10 |
+
import json
|
| 11 |
+
import os
|
| 12 |
+
import subprocess
|
| 13 |
+
import sys
|
| 14 |
+
|
| 15 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 16 |
+
import ladder_plan as L # noqa: E402
|
| 17 |
+
|
| 18 |
+
ROOT, API = L.ROOT, L.API
|
| 19 |
+
OUT = os.path.join(API, "ladder_gpt_20261102")
|
| 20 |
+
BATCHES = ["cx_main1", "cx_astra_s2", "cx_astra_s3"]
|
| 21 |
+
TASKS = {"l7_offcenter_push", "l5_slide_to_target", "l5_tablecloth_pull", "l3_wall_flush", "l3_under_table_tool",
|
| 22 |
+
"l4_fit_container", "l3_card_shelf", "l5_loaded_beam"}
|
| 23 |
+
FIXV_GPT = os.path.join(ROOT, "results", "_ladder", "fix_validate_gpt.json")
|
| 24 |
+
RUNGS = ("F1", "F2", "hplus", "fix")
|
| 25 |
+
BATCH = {"F1": "lf1_gpt", "F2": "lf2_gpt", "hplus": "lhp_gpt", "fix": "lfx_gpt"}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def instances():
|
| 29 |
+
out = {}
|
| 30 |
+
for b in BATCHES:
|
| 31 |
+
for r in json.load(open(os.path.join(API, b, "manifest.json")))["runs"]:
|
| 32 |
+
if r["cond"] != "harness" or r["status"] != "done" or r["task"] not in TASKS:
|
| 33 |
+
continue
|
| 34 |
+
d = next((e for e in L.events(r["log"]) if e["ev"] == "done" and e.get("attempt") == 1), None)
|
| 35 |
+
if d is not None and not d["success"]:
|
| 36 |
+
out[f"{r['task']}:{r['seed']}"] = r["log"]
|
| 37 |
+
return out
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def fixes():
|
| 41 |
+
rows = json.load(open(L.FIXV))["rows"]
|
| 42 |
+
if os.path.exists(FIXV_GPT):
|
| 43 |
+
rows += json.load(open(FIXV_GPT))["rows"]
|
| 44 |
+
return {r["key"]: r for r in rows}
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def cmd_validate():
|
| 48 |
+
import validate_ladder_fix as V
|
| 49 |
+
have = fixes()
|
| 50 |
+
want = {k: v for k, v in instances().items() if not have.get(k, {}).get("ok")}
|
| 51 |
+
print("to validate:", sorted(want))
|
| 52 |
+
if not want:
|
| 53 |
+
return
|
| 54 |
+
V.instances = lambda: {k: dict(task=k.split(":")[0], seed=int(k.split(":")[1]), models=["gpt"],
|
| 55 |
+
logged=json.loads(open(os.path.join(v, "events.jsonl")).readline())["inst"]) for k, v in want.items()}
|
| 56 |
+
sys.argv = ["validate_ladder_fix.py", "--out", FIXV_GPT]
|
| 57 |
+
V.main()
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def cmd_build():
|
| 61 |
+
fx = fixes(); inst = instances(); os.makedirs(OUT, exist_ok=True)
|
| 62 |
+
open(os.path.join(OUT, "tasks.txt"), "w").write("\n".join(sorted(inst)) + "\n")
|
| 63 |
+
out = {r: {} for r in RUNGS}
|
| 64 |
+
for key, log in sorted(inst.items()):
|
| 65 |
+
task, seed = key.split(":")
|
| 66 |
+
tx = dict(L.texts(dict(log=log, task=task, seed=int(seed)), fx), F1="")
|
| 67 |
+
for r in RUNGS:
|
| 68 |
+
dst = os.path.join(OUT, r, f"{task}_s{seed}")
|
| 69 |
+
if not os.path.isdir(dst):
|
| 70 |
+
cmd = [sys.executable, "-I", os.path.join(ROOT, "scripts", "make_dossier.py"), log, dst] + (["--result-extra", tx[r]] if tx[r] else [])
|
| 71 |
+
subprocess.run(cmd, check=True, capture_output=True)
|
| 72 |
+
out[r][key] = dst
|
| 73 |
+
for r in RUNGS:
|
| 74 |
+
json.dump(out[r], open(os.path.join(OUT, f"{r}.json"), "w"), indent=1)
|
| 75 |
+
print(len(inst), "instances x", len(RUNGS), "rungs")
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def cmd_report():
|
| 79 |
+
keys = [l.strip() for l in open(os.path.join(OUT, "tasks.txt")) if l.strip()]
|
| 80 |
+
res = {r: L.single(BATCH[r]) for r in RUNGS}
|
| 81 |
+
f = lambda v: "-" if v is None else ("S" if v else "F")
|
| 82 |
+
print("| instance | F1 | F2 | H+ | Fix |\n|---|---|---|---|---|")
|
| 83 |
+
for k in keys:
|
| 84 |
+
print(f"| {k} | " + " | ".join(f(res[r].get(k)) for r in RUNGS) + " |")
|
| 85 |
+
rows = [{r: res[r].get(k) for r in RUNGS} for k in keys]
|
| 86 |
+
tot = {r: [sum(bool(x[r]) for x in rows if x[r] is not None), sum(x[r] is not None for x in rows)] for r in RUNGS}
|
| 87 |
+
print("totals:", ", ".join(f"{r} {tot[r][0]}/{tot[r][1]}" for r in RUNGS))
|
| 88 |
+
for lo, hi in zip(RUNGS, RUNGS[1:]):
|
| 89 |
+
both = [x for x in rows if x[lo] is not None and x[hi] is not None]
|
| 90 |
+
print(f"{lo}->{hi}: n={len(both)} up {sum(bool(x[hi]) and not x[lo] for x in both)} down {sum(bool(x[lo]) and not x[hi] for x in both)}")
|
| 91 |
+
json.dump(dict(rows=[dict(inst=k, **{r: res[r].get(k) for r in RUNGS}) for k in keys], totals=tot), open(os.path.join(OUT, "report.json"), "w"), indent=1)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
if __name__ == "__main__":
|
| 95 |
+
{"validate": cmd_validate, "build": cmd_build, "report": cmd_report}[sys.argv[1]]()
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_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_breakfast1_20261114/lff/source_closure/scripts/layer4_plan.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Layer-4 minimal intervention (user 2026-10-30: 先用 opus; design reports/layer4_intervention_20261030/PLAN.md). Opus only, on the
|
| 2 |
+
two tasks whose every main-table instance failed all three attempts. Same protocol as the layer-3 ladder (a fresh
|
| 3 |
+
single-attempt agent, the instance's own failed attempt 1 in history/, F1), only the Result section differs:
|
| 4 |
+
|
| 5 |
+
f1 "The environment judged that attempt: failed."
|
| 6 |
+
v + a generic reminder to check the goal before ending; no cause
|
| 7 |
+
hp + "Cause: " the hidden variable (arm_specs reveal)
|
| 8 |
+
fx + cause + how to succeed (arm_specs fix, validated below)
|
| 9 |
+
|
| 10 |
+
python scripts/layer4_plan.py validate texts + oracle + LA push, debug and test seeds -> results/_layer4/fix_validate.json
|
| 11 |
+
python scripts/layer4_plan.py build debug records -> runs/api/layer4i_20261030/debug/<cond>.json + tasks.txt
|
| 12 |
+
python scripts/layer4_plan.py build test the same from the failed attempts of batch l4i_first (test seeds)
|
| 13 |
+
python scripts/layer4_plan.py report debug|test per instance per condition: outcome, process events, closing claim
|
| 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 |
+
OUT = os.path.join(API, "layer4i_20261030")
|
| 24 |
+
FIXV = os.path.join(ROOT, "results", "_layer4", "fix_validate.json")
|
| 25 |
+
CONDS = ("f1", "v", "hp", "fx")
|
| 26 |
+
DEBUG = {"lh_clear_cover": {3000: "cc_opus1", 3001: "cc_opus_s2", 3003: "cc_opus_s3"},
|
| 27 |
+
"lh_tidy_stack": {3000: "cc_opus1", 3002: "cc_opus_s2", 3003: "cc_opus_s3"}}
|
| 28 |
+
# frozen before any test-seed run: first four seeds from 3100 with the trap active (clear_cover: covered, (seed * 7) % 20 < 10;
|
| 29 |
+
# tidy_stack: a soft box that is not on top of a nearest-first pile, (seed * 7) % 20 < 18 and % 4 != 3)
|
| 30 |
+
TEST = {"lh_clear_cover": [3100, 3101, 3103, 3104], "lh_tidy_stack": [3100, 3102, 3103, 3104]}
|
| 31 |
+
REMINDER = ("Before you end an attempt, use your observations to check whether every part of the goal is actually met; "
|
| 32 |
+
"if it is not, keep working.")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def events(log):
|
| 36 |
+
return [json.loads(line) for line in open(os.path.join(log, "events.jsonl")) if line.strip() and "\0" not in line]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def batch_log(batch, task, seed):
|
| 40 |
+
runs = json.load(open(os.path.join(API, batch, "manifest.json")))["runs"]
|
| 41 |
+
return next(r["log"] for r in runs if r["task"] == task and r["seed"] == seed and r.get("status") == "done"
|
| 42 |
+
and r.get("cond") == "harness")
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def la_push(task, inst):
|
| 46 |
+
"""the Fix text's lid push as LA commands; returns (z_push, sweep length, lid off?)"""
|
| 47 |
+
import numpy as np
|
| 48 |
+
from lffbench.agent.tools import ToolExecutor
|
| 49 |
+
from lffbench.tasks import lh_clear_cover as cc
|
| 50 |
+
from scripts.validate_ladder_fix import la_move
|
| 51 |
+
task.reset_instance(inst)
|
| 52 |
+
sim = task.env.sim
|
| 53 |
+
off = np.array(sim.data.body_xpos[sim.model.body_name2id("robot0_base")], float).copy()
|
| 54 |
+
ex = ToolExecutor(task, inst, image_res=64, cams=("agentview",))
|
| 55 |
+
cov = task.covering()
|
| 56 |
+
lp = task.lid_pos()
|
| 57 |
+
b = np.asarray(inst["boxes"][cov], float)
|
| 58 |
+
o = np.asarray(inst["boxes"][[c for c in cc.COLORS if c != cov][0]], float)
|
| 59 |
+
d = np.array((0.0, float(np.sign(b[1] - o[1]))))
|
| 60 |
+
back = cc.LID_HALF + 0.03
|
| 61 |
+
s = lp[:2] - d * back
|
| 62 |
+
z = lp[2] + cc.LID_T / 2 - cc.PUSH_DEPTH + cc.TIP
|
| 63 |
+
need = float((b - lp[:2]) @ d) + cc.BOX_OUT + back + 0.03
|
| 64 |
+
e = s + d * need
|
| 65 |
+
sb, eb, zb = s - off[:2], e - off[:2], z - off[2]
|
| 66 |
+
la_move(task, ex, off, gripper="close")
|
| 67 |
+
la_move(task, ex, off, x=sb[0], y=sb[1], z=zb + 0.08, yaw=0)
|
| 68 |
+
la_move(task, ex, off, x=sb[0], y=sb[1], z=zb)
|
| 69 |
+
la_move(task, ex, off, x=eb[0], y=eb[1], z=zb, speed=cc.PUSH_SPEED)
|
| 70 |
+
la_move(task, ex, off, z=zb + 0.10, speed=0.2)
|
| 71 |
+
return float(zb), float(need), task.covering() is None
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def cmd_validate():
|
| 75 |
+
import importlib
|
| 76 |
+
import pkgutil
|
| 77 |
+
from lffbench import arm_specs
|
| 78 |
+
from lffbench import tasks as task_pkg
|
| 79 |
+
from lffbench.agent.robot_server import strip_axes
|
| 80 |
+
from lffbench.task_base import TASKS
|
| 81 |
+
for m in pkgutil.iter_modules(task_pkg.__path__):
|
| 82 |
+
importlib.import_module(f"lffbench.tasks.{m.name}")
|
| 83 |
+
rows = []
|
| 84 |
+
for name, seeds in ((t, sorted(DEBUG[t]) + TEST[t]) for t in DEBUG):
|
| 85 |
+
task = TASKS[name](cam_res=64)
|
| 86 |
+
for seed in seeds:
|
| 87 |
+
inst = task.sample_instance(seed)
|
| 88 |
+
clean = {k: v for k, v in inst.items() if not k.startswith("_")}
|
| 89 |
+
params = dict(task.oracle_params(inst))
|
| 90 |
+
row = dict(key=f"{name}:{seed}", hidden=clean.get("cover") or clean.get("soft_colour"))
|
| 91 |
+
row["oracle_success"] = bool(task.run_scripted("oracle", inst, k=1)[0]["outcome"]["success"])
|
| 92 |
+
row["naive_success"] = bool(task.run_scripted("naive", inst, k=1)[0]["outcome"]["success"])
|
| 93 |
+
if name == "lh_clear_cover":
|
| 94 |
+
params["z_push"], params["push_len"], row["la_lid_off"] = la_push(task, inst)
|
| 95 |
+
task.execute(inst, dict(plan="naive", check="side")) # the placing part, after the LA push
|
| 96 |
+
row["la_then_place_success"] = bool(task.outcome(inst)["success"])
|
| 97 |
+
cause, fx = arm_specs.reveal(name, clean), arm_specs.fix(name, clean, params)
|
| 98 |
+
row.update(cause=cause, fix=fx, no_axis_labels=strip_axes(cause + fx) == cause + fx)
|
| 99 |
+
row["ok"] = bool(row["oracle_success"] and not row["naive_success"] and row["hidden"] and row["no_axis_labels"]
|
| 100 |
+
and row.get("la_lid_off", True) and row.get("la_then_place_success", True))
|
| 101 |
+
rows.append(row)
|
| 102 |
+
print("OK " if row["ok"] else "BAD", json.dumps({k: v for k, v in row.items() if k not in ("cause", "fix")}), flush=True)
|
| 103 |
+
os.makedirs(os.path.dirname(FIXV), exist_ok=True)
|
| 104 |
+
json.dump(dict(rows=rows, n=len(rows), n_ok=sum(r["ok"] for r in rows)), open(FIXV, "w"), indent=1)
|
| 105 |
+
print(f"{sum(r['ok'] for r in rows)}/{len(rows)} ok -> {FIXV}")
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def sources(stage):
|
| 109 |
+
if stage == "debug":
|
| 110 |
+
return [(t, s, batch_log(b, t, s)) for t, d in DEBUG.items() for s, b in sorted(d.items())]
|
| 111 |
+
out = []
|
| 112 |
+
for r in json.load(open(os.path.join(API, "l4i_first", "manifest.json")))["runs"]:
|
| 113 |
+
if r["status"] == "done":
|
| 114 |
+
d = next((e for e in events(r["log"]) if e["ev"] == "done" and e.get("attempt") == 1), None)
|
| 115 |
+
if d is not None and not d["success"]:
|
| 116 |
+
out.append((r["task"], r["seed"], r["log"]))
|
| 117 |
+
return out
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def cmd_build(stage):
|
| 121 |
+
fixes = {r["key"]: r for r in json.load(open(FIXV))["rows"]}
|
| 122 |
+
base = os.path.join(OUT, stage)
|
| 123 |
+
os.makedirs(base, exist_ok=True)
|
| 124 |
+
maps, tasks = {c: {} for c in CONDS}, []
|
| 125 |
+
for task, seed, log in sources(stage):
|
| 126 |
+
key = f"{task}:{seed}"
|
| 127 |
+
if not fixes[key]["ok"]:
|
| 128 |
+
raise SystemExit(f"{key}: fix text not validated")
|
| 129 |
+
tasks.append(key)
|
| 130 |
+
cause = "Cause: " + fixes[key]["cause"]
|
| 131 |
+
extra = dict(f1="", v=REMINDER, hp=cause, fx=cause + "\n\n" + fixes[key]["fix"])
|
| 132 |
+
for c in CONDS:
|
| 133 |
+
dst = os.path.join(base, c, f"{task}_s{seed}")
|
| 134 |
+
if not os.path.isdir(dst):
|
| 135 |
+
subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "make_dossier.py"), log, dst,
|
| 136 |
+
"--result-extra", extra[c]], check=True, capture_output=True)
|
| 137 |
+
maps[c][key] = dst
|
| 138 |
+
for c in CONDS:
|
| 139 |
+
json.dump(maps[c], open(os.path.join(base, f"{c}.json"), "w"), indent=1)
|
| 140 |
+
open(os.path.join(base, "tasks.txt"), "w").write("\n".join(tasks) + "\n")
|
| 141 |
+
print(stage, len(tasks), "instances x", len(CONDS), "conditions")
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def cmd_report(stage):
|
| 145 |
+
rows = {}
|
| 146 |
+
for c in CONDS:
|
| 147 |
+
p = os.path.join(API, f"l4i_{c}_{stage}", "manifest.json")
|
| 148 |
+
if not os.path.exists(p):
|
| 149 |
+
continue
|
| 150 |
+
for r in json.load(open(p))["runs"]:
|
| 151 |
+
key = f"{r['task']}:{r['seed']}"
|
| 152 |
+
cell = dict(status=r["status"])
|
| 153 |
+
if r["status"] == "done":
|
| 154 |
+
ev = events(r["log"])
|
| 155 |
+
d = next((e for e in ev if e["ev"] == "done"), {})
|
| 156 |
+
o = d.get("outcome") or {}
|
| 157 |
+
cell.update(success=bool(d.get("success")), calls=d.get("step"), reason=(d.get("reason") or "")[:300],
|
| 158 |
+
failure=o.get("failure"), detail=(o.get("detail") or "")[:300], log=r["log"],
|
| 159 |
+
events=[e.get("ev") for e in o.get("events", []) if isinstance(e, dict)][:40],
|
| 160 |
+
cover_removed=o.get("cover_removed"))
|
| 161 |
+
rows.setdefault(key, {})[c] = cell
|
| 162 |
+
print("| instance | " + " | ".join(CONDS) + " |")
|
| 163 |
+
print("|---|" + "---|" * len(CONDS))
|
| 164 |
+
f = lambda x: "-" if x is None else ("S" if x.get("success") else ("F" if x.get("status") == "done" else x.get("status")))
|
| 165 |
+
for k, v in sorted(rows.items()):
|
| 166 |
+
print(f"| {k} | " + " | ".join(f(v.get(c)) for c in CONDS) + " |")
|
| 167 |
+
for c in CONDS:
|
| 168 |
+
xs = [v[c] for v in rows.values() if c in v and v[c].get("status") == "done"]
|
| 169 |
+
print(c, f"{sum(x['success'] for x in xs)}/{len(xs)}")
|
| 170 |
+
json.dump(rows, open(os.path.join(OUT, f"report_{stage}.json"), "w"), indent=1)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
if __name__ == "__main__":
|
| 174 |
+
{"validate": cmd_validate, "build": lambda: cmd_build(sys.argv[2]), "report": lambda: cmd_report(sys.argv[2])}[sys.argv[1]]()
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/lerobot_export.py
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars.
|
| 2 |
+
|
| 3 |
+
Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding
|
| 4 |
+
can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan):
|
| 5 |
+
|
| 6 |
+
python scripts/lerobot_export.py plan --raw <raw_root>[,<raw_root2>] --runs-root <lffbench>/runs/api \
|
| 7 |
+
--paper <paper/latex> --task-set <lffbench>/sets/main_v2_1inst.txt --work <work_dir> [--batches ...] [--limit N]
|
| 8 |
+
python scripts/lerobot_export.py shard --work <work_dir> --shard i --nshards N
|
| 9 |
+
python scripts/lerobot_export.py merge --work <work_dir> --nshards N --out <dataset_root>
|
| 10 |
+
|
| 11 |
+
Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0
|
| 12 |
+
mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped.
|
| 13 |
+
|
| 14 |
+
LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t):
|
| 15 |
+
observation.images.image agentview RGB 256x256 (upright; LIBERO naming)
|
| 16 |
+
observation.images.wrist_image wrist (eye-in-hand) RGB 256x256
|
| 17 |
+
observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout)
|
| 18 |
+
observation.joint_pos / joint_vel 7 arm joints (rad, rad/s)
|
| 19 |
+
observation.eef_quat 4: xyzw; observation.gripper_width 1 (m)
|
| 20 |
+
action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad),
|
| 21 |
+
gripper (-1 open, +1 close)
|
| 22 |
+
annotation.attempt_index attempt (1-based) the frame belongs to
|
| 23 |
+
annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`)
|
| 24 |
+
annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action)
|
| 25 |
+
annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt
|
| 26 |
+
annotation.task_event number of task-monitor events (error / progress events) registered at this step
|
| 27 |
+
Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table),
|
| 28 |
+
runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state
|
| 29 |
+
per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/.
|
| 30 |
+
"""
|
| 31 |
+
import argparse
|
| 32 |
+
import glob
|
| 33 |
+
import json
|
| 34 |
+
import os
|
| 35 |
+
import re
|
| 36 |
+
import shutil
|
| 37 |
+
import time
|
| 38 |
+
|
| 39 |
+
import numpy as np
|
| 40 |
+
|
| 41 |
+
FPS = 20
|
| 42 |
+
RES = 256
|
| 43 |
+
BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke",
|
| 44 |
+
"cc_smoke", "cc_opus_smoke"]
|
| 45 |
+
BATCH_NOTES = {
|
| 46 |
+
"cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog",
|
| 47 |
+
"cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267",
|
| 48 |
+
"cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299",
|
| 49 |
+
"cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances",
|
| 50 |
+
"cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)",
|
| 51 |
+
"cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the "
|
| 52 |
+
"with-history continuation of failed runs is incomplete",
|
| 53 |
+
"cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early",
|
| 54 |
+
"cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt",
|
| 55 |
+
"cc_opus_smoke": "smoke test: single attempt",
|
| 56 |
+
}
|
| 57 |
+
PHASES = {"move": 0, "gripper": 1, "judge": 2}
|
| 58 |
+
CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)",
|
| 59 |
+
"L2": "disturbed state to restore (incl. damage the agent causes)",
|
| 60 |
+
"L3": "infeasible manipulation strategy (grasp / contact / tool must change)",
|
| 61 |
+
"L4": "misjudged geometry (size, shape, fit, hidden structure)",
|
| 62 |
+
"L5": "misjudged physics (mass distribution, friction, dynamics)"}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def features():
|
| 66 |
+
vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]}
|
| 67 |
+
f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names}
|
| 68 |
+
i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None}
|
| 69 |
+
return {
|
| 70 |
+
"observation.images.image": vid(),
|
| 71 |
+
"observation.images.wrist_image": vid(),
|
| 72 |
+
"observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z",
|
| 73 |
+
"finger_qpos_left", "finger_qpos_right"]),
|
| 74 |
+
"observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 75 |
+
"observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]),
|
| 76 |
+
"observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]),
|
| 77 |
+
"observation.gripper_width": f32(1, ["width_m"]),
|
| 78 |
+
"action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y",
|
| 79 |
+
"eef_delta_rot_aa_z", "gripper_close"]),
|
| 80 |
+
"annotation.attempt_index": i64(),
|
| 81 |
+
"annotation.command_index": i64(),
|
| 82 |
+
"annotation.phase": i64(),
|
| 83 |
+
"annotation.attempt_success": i64(),
|
| 84 |
+
"annotation.task_event": i64(),
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ------------------------------------------------------------------------------------------------ paper metadata
|
| 89 |
+
|
| 90 |
+
def _clean_tex(s):
|
| 91 |
+
s = re.sub(r"%.*", "", s)
|
| 92 |
+
for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"),
|
| 93 |
+
(r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"),
|
| 94 |
+
(r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"),
|
| 95 |
+
(r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"),
|
| 96 |
+
(r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]:
|
| 97 |
+
s = re.sub(a, b, s)
|
| 98 |
+
s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s)
|
| 99 |
+
s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s)
|
| 100 |
+
for _ in range(3):
|
| 101 |
+
s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s)
|
| 102 |
+
s = re.sub(r"\$([^$]*)\$", r"\1", s)
|
| 103 |
+
s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ")
|
| 104 |
+
s = re.sub(r"\{([^{}]*)\}", r"\1", s)
|
| 105 |
+
s = re.sub(r"\\[a-zA-Z]+\*?", "", s)
|
| 106 |
+
return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def paper_tasks(paper_dir):
|
| 110 |
+
"""{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the
|
| 111 |
+
paper's task table and task appendix (empty if the paper sources are not there)."""
|
| 112 |
+
out = {}
|
| 113 |
+
if not paper_dir:
|
| 114 |
+
return out
|
| 115 |
+
app = os.path.join(paper_dir, "sections", "appendix_tasks.tex")
|
| 116 |
+
tab = os.path.join(paper_dir, "sections", "tab_tasks.tex")
|
| 117 |
+
if os.path.exists(app):
|
| 118 |
+
txt = open(app).read()
|
| 119 |
+
parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt)
|
| 120 |
+
for i in range(1, len(parts) - 1, 2):
|
| 121 |
+
if parts[i] != "\\paragraph{":
|
| 122 |
+
continue
|
| 123 |
+
body = parts[i + 1]
|
| 124 |
+
m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S)
|
| 125 |
+
if not m:
|
| 126 |
+
continue
|
| 127 |
+
name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip()
|
| 128 |
+
desc = _clean_tex(body[m.end():])
|
| 129 |
+
out[code] = dict(name=name, cause=_clean_tex(cause), description=desc)
|
| 130 |
+
if os.path.exists(tab):
|
| 131 |
+
names = {v["name"].lower(): k for k, v in out.items()}
|
| 132 |
+
for line in open(tab):
|
| 133 |
+
cells = [c.strip() for c in line.split("&")]
|
| 134 |
+
if len(cells) != 6 or not cells[-1].endswith("\\\\"):
|
| 135 |
+
continue
|
| 136 |
+
nm = re.sub(r"\\contscene", "", cells[0]).strip().lower()
|
| 137 |
+
code = names.get(nm)
|
| 138 |
+
if not code:
|
| 139 |
+
continue
|
| 140 |
+
out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]),
|
| 141 |
+
repair_within_attempt=_clean_tex(cells[3]) == "yes",
|
| 142 |
+
oracle_first_attempt_pct=_clean_tex(cells[4]),
|
| 143 |
+
naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip()))
|
| 144 |
+
return out
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
# ------------------------------------------------------------------------------------------------ collection
|
| 148 |
+
|
| 149 |
+
def manifest_status(runs_root, batch, run, cache={}):
|
| 150 |
+
if batch not in cache:
|
| 151 |
+
p = os.path.join(runs_root, batch, "manifest.json")
|
| 152 |
+
cache[batch] = json.load(open(p)) if os.path.exists(p) else {}
|
| 153 |
+
m = cache[batch]
|
| 154 |
+
for r in m.get("runs", []):
|
| 155 |
+
if r.get("run") == run:
|
| 156 |
+
return r.get("status", "?"), r
|
| 157 |
+
for r in m.get("superseded", []):
|
| 158 |
+
if r.get("run") == run:
|
| 159 |
+
return "superseded_" + str(r.get("status", "?")), r
|
| 160 |
+
return "not_in_manifest", {}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def collect(raw_roots, runs_root, batches, task_order):
|
| 164 |
+
"""Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root."""
|
| 165 |
+
eps, rejected, seen = [], [], set()
|
| 166 |
+
for root in raw_roots:
|
| 167 |
+
for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))):
|
| 168 |
+
rep = json.load(open(rj))
|
| 169 |
+
batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"]
|
| 170 |
+
if (batches and batch not in batches) or (batch, run) in seen:
|
| 171 |
+
continue
|
| 172 |
+
seen.add((batch, run))
|
| 173 |
+
ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff")
|
| 174 |
+
status, entry = manifest_status(runs_root, batch, run)
|
| 175 |
+
if not ok:
|
| 176 |
+
never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked")
|
| 177 |
+
rejected.append(dict(run=run, batch=batch, run_status=status,
|
| 178 |
+
reason="run never started (no contract, no robot command)" if never else
|
| 179 |
+
"replay does not reproduce the log (the log has gaps or the replay diverged)",
|
| 180 |
+
detail=rep.get("first_mismatches")))
|
| 181 |
+
continue
|
| 182 |
+
for ep in rep.get("episodes", []):
|
| 183 |
+
d = os.path.join(root, ep["dir"])
|
| 184 |
+
ann = json.load(open(os.path.join(d, "annotation.json")))
|
| 185 |
+
judged = [a for a in ann["attempts"] if a.get("success") is not None]
|
| 186 |
+
if not judged or ep["n_frames"] == 0:
|
| 187 |
+
rejected.append(dict(run=run, batch=batch, episode=ep["dir"],
|
| 188 |
+
reason="no judged attempt" if not judged else "no frames"))
|
| 189 |
+
continue
|
| 190 |
+
ann["source"]["run_status"] = status
|
| 191 |
+
ann["source"]["manifest_id"] = entry.get("id")
|
| 192 |
+
ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"],
|
| 193 |
+
max_eef_dev_m=rep["max_eef_dev_m"])
|
| 194 |
+
key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99),
|
| 195 |
+
{"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2),
|
| 196 |
+
ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"])
|
| 197 |
+
eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann))
|
| 198 |
+
eps.sort(key=lambda x: x["key"])
|
| 199 |
+
return eps, rejected
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# ------------------------------------------------------------------------------------------------ writing
|
| 203 |
+
|
| 204 |
+
def frames_of(path):
|
| 205 |
+
import av
|
| 206 |
+
with av.open(path) as c:
|
| 207 |
+
for fr in c.decode(video=0):
|
| 208 |
+
yield fr.to_ndarray(format="rgb24")
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def flat_row(i, ann, n, idx0):
|
| 212 |
+
s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"]
|
| 213 |
+
att = ann["attempts"]
|
| 214 |
+
a0 = att[0]
|
| 215 |
+
return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n,
|
| 216 |
+
batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"],
|
| 217 |
+
memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"),
|
| 218 |
+
episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att],
|
| 219 |
+
harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"),
|
| 220 |
+
effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"),
|
| 221 |
+
task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"),
|
| 222 |
+
category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"],
|
| 223 |
+
success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att],
|
| 224 |
+
feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att],
|
| 225 |
+
auto_ended=[a.get("auto_ended") for a in att],
|
| 226 |
+
corrected_later_in_run=[a.get("corrected_later_in_run") for a in att],
|
| 227 |
+
error_event_in_attempt=[a.get("error_event_in_attempt") for a in att],
|
| 228 |
+
run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"),
|
| 229 |
+
n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]),
|
| 230 |
+
first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def cmd_plan(a):
|
| 234 |
+
task_order = {}
|
| 235 |
+
if a.task_set and os.path.exists(a.task_set):
|
| 236 |
+
for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")):
|
| 237 |
+
task_order[line.split(":")[0].strip()] = i
|
| 238 |
+
batches = [b for b in a.batches.split(",") if b] if a.batches else None
|
| 239 |
+
eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order)
|
| 240 |
+
if a.limit:
|
| 241 |
+
eps = eps[:a.limit]
|
| 242 |
+
paper = paper_tasks(a.paper)
|
| 243 |
+
idx0 = 0
|
| 244 |
+
for i, e in enumerate(eps):
|
| 245 |
+
ann = e["ann"]
|
| 246 |
+
tname = ann["task"]["name"]
|
| 247 |
+
if tname in paper:
|
| 248 |
+
ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"}
|
| 249 |
+
ann["episode_index"] = i
|
| 250 |
+
ann["dataset_index_range"] = [idx0, idx0 + e["n"]]
|
| 251 |
+
e["index"], e["from"] = i, idx0
|
| 252 |
+
idx0 += e["n"]
|
| 253 |
+
del e["key"]
|
| 254 |
+
os.makedirs(a.work, exist_ok=True)
|
| 255 |
+
with open(os.path.join(a.work, "plan.json"), "w") as f:
|
| 256 |
+
json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f,
|
| 257 |
+
ensure_ascii=False)
|
| 258 |
+
print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def shard_range(n_eps, i, k):
|
| 262 |
+
return (n_eps * i) // k, (n_eps * (i + 1)) // k
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def cmd_shard(a):
|
| 266 |
+
from lerobot.datasets.lerobot_dataset import LeRobotDataset
|
| 267 |
+
t0 = time.time()
|
| 268 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 269 |
+
eps = plan["episodes"]
|
| 270 |
+
lo, hi = shard_range(len(eps), a.shard, a.nshards)
|
| 271 |
+
out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}")
|
| 272 |
+
if os.path.exists(os.path.join(out, "DONE")):
|
| 273 |
+
print(f"shard {a.shard}: done already", flush=True)
|
| 274 |
+
return
|
| 275 |
+
shutil.rmtree(out, ignore_errors=True)
|
| 276 |
+
ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out,
|
| 277 |
+
robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads,
|
| 278 |
+
vcodec=a.vcodec)
|
| 279 |
+
nfr = 0
|
| 280 |
+
for e in eps[lo:hi]:
|
| 281 |
+
d, ann, n = e["dir"], e["ann"], e["n"]
|
| 282 |
+
fr = np.load(os.path.join(d, "frames.npz"))
|
| 283 |
+
assert len(fr["action"]) == n, d
|
| 284 |
+
succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]}
|
| 285 |
+
evc = np.zeros(n, np.int64)
|
| 286 |
+
for ev in ann["task_events"]:
|
| 287 |
+
if 0 <= ev["frame"] < n:
|
| 288 |
+
evc[ev["frame"]] += 1
|
| 289 |
+
state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32)
|
| 290 |
+
instr = ann["task"]["instruction"]
|
| 291 |
+
k = 0
|
| 292 |
+
for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))):
|
| 293 |
+
if k >= n:
|
| 294 |
+
break
|
| 295 |
+
ds.add_frame({
|
| 296 |
+
"observation.images.image": img, "observation.images.wrist_image": wr,
|
| 297 |
+
"observation.state": state[k],
|
| 298 |
+
"observation.joint_pos": fr["joint_pos"][k].astype(np.float32),
|
| 299 |
+
"observation.joint_vel": fr["joint_vel"][k].astype(np.float32),
|
| 300 |
+
"observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32),
|
| 301 |
+
"observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32),
|
| 302 |
+
"action": fr["action"][k].astype(np.float32),
|
| 303 |
+
"annotation.attempt_index": np.array([fr["attempt"][k]], np.int64),
|
| 304 |
+
"annotation.command_index": np.array([fr["command"][k]], np.int64),
|
| 305 |
+
"annotation.phase": np.array([fr["phase"][k]], np.int64),
|
| 306 |
+
"annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64),
|
| 307 |
+
"annotation.task_event": np.array([evc[k]], np.int64),
|
| 308 |
+
"task": instr,
|
| 309 |
+
})
|
| 310 |
+
k += 1
|
| 311 |
+
if k != n:
|
| 312 |
+
raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames")
|
| 313 |
+
ds.save_episode()
|
| 314 |
+
nfr += n
|
| 315 |
+
ds.finalize()
|
| 316 |
+
shutil.rmtree(os.path.join(out, "images"), ignore_errors=True)
|
| 317 |
+
open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n")
|
| 318 |
+
print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def cmd_merge(a):
|
| 322 |
+
from pathlib import Path
|
| 323 |
+
from lerobot.datasets.aggregate import aggregate_datasets
|
| 324 |
+
t0 = time.time()
|
| 325 |
+
plan = json.load(open(os.path.join(a.work, "plan.json")))
|
| 326 |
+
eps = plan["episodes"]
|
| 327 |
+
roots, ids = [], []
|
| 328 |
+
for i in range(a.nshards):
|
| 329 |
+
lo, hi = shard_range(len(eps), i, a.nshards)
|
| 330 |
+
if hi <= lo:
|
| 331 |
+
continue
|
| 332 |
+
r = os.path.join(a.work, "shards", f"shard_{i:03d}")
|
| 333 |
+
if not os.path.exists(os.path.join(r, "DONE")):
|
| 334 |
+
raise SystemExit(f"shard {i} is not done")
|
| 335 |
+
roots.append(Path(r))
|
| 336 |
+
ids.append(f"{plan['repo_id']}-shard{i:03d}")
|
| 337 |
+
if os.path.exists(a.out):
|
| 338 |
+
raise SystemExit(f"{a.out} exists; refusing to overwrite")
|
| 339 |
+
aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out))
|
| 340 |
+
print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True)
|
| 341 |
+
write_sidecars(a, plan)
|
| 342 |
+
print(f"merge done in {time.time() - t0:.0f}s", flush=True)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def write_sidecars(a, plan):
|
| 346 |
+
eps, paper = plan["episodes"], plan["paper"]
|
| 347 |
+
lff = os.path.join(a.out, "lff")
|
| 348 |
+
for sub in ("annotations", "sim_state", "final", "code"):
|
| 349 |
+
os.makedirs(os.path.join(lff, sub), exist_ok=True)
|
| 350 |
+
rows, runs, tasks = [], {}, {}
|
| 351 |
+
for e in eps:
|
| 352 |
+
i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"]
|
| 353 |
+
name = f"episode_{i:06d}"
|
| 354 |
+
if os.path.exists(os.path.join(d, "sim_state.npy")):
|
| 355 |
+
shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy"))
|
| 356 |
+
shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz"))
|
| 357 |
+
for cam, key in (("agentview", "image"), ("wrist", "wrist_image")):
|
| 358 |
+
shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png"))
|
| 359 |
+
with open(os.path.join(lff, "annotations", name + ".json"), "w") as f:
|
| 360 |
+
json.dump(ann, f, indent=1, ensure_ascii=False)
|
| 361 |
+
rows.append(flat_row(i, ann, n, e["from"]))
|
| 362 |
+
tname = ann["task"]["name"]
|
| 363 |
+
rk = (ann["source"]["batch"], ann["source"]["run"])
|
| 364 |
+
r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"),
|
| 365 |
+
run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"],
|
| 366 |
+
memory_free_chain_of=ann["source"].get("memory_free_chain_of"),
|
| 367 |
+
memory_free_rep=ann["source"].get("memory_free_rep"), task=tname,
|
| 368 |
+
seed=ann["task"]["seed"], model=ann["agent"].get("model"),
|
| 369 |
+
harness=ann["agent"].get("harness"),
|
| 370 |
+
harness_version=ann["agent"].get("harness_version"),
|
| 371 |
+
codex_catalog=ann["agent"].get("codex_catalog"),
|
| 372 |
+
outcome_class=ann["run_outcome"].get("outcome_class"),
|
| 373 |
+
attempt_history=ann["run_outcome"].get("attempt_history"),
|
| 374 |
+
agent_final_report=ann["run_outcome"].get("agent_final_report"),
|
| 375 |
+
episodes=[]))
|
| 376 |
+
for x in ann["attempts"]:
|
| 377 |
+
r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success")))
|
| 378 |
+
if tname not in tasks:
|
| 379 |
+
tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")}
|
| 380 |
+
if tname in paper:
|
| 381 |
+
tasks[tname]["paper"] = paper[tname]
|
| 382 |
+
tasks[tname]["instances"] = {}
|
| 383 |
+
tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"]
|
| 384 |
+
# memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id)
|
| 385 |
+
by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")}
|
| 386 |
+
for r in runs.values():
|
| 387 |
+
if r.get("memory_free_chain_of"):
|
| 388 |
+
r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"]))
|
| 389 |
+
for (b, rn), r in runs.items():
|
| 390 |
+
r["memory_free_retries"] = sorted((x["run"] for x in runs.values()
|
| 391 |
+
if x["batch"] == b and x.get("memory_free_chain_of_run") == rn),
|
| 392 |
+
key=lambda q: runs[(b, q)].get("memory_free_rep") or 0)
|
| 393 |
+
with open(os.path.join(lff, "episodes.jsonl"), "w") as f:
|
| 394 |
+
for row in rows:
|
| 395 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 396 |
+
with open(os.path.join(lff, "runs.jsonl"), "w") as f:
|
| 397 |
+
for r in runs.values():
|
| 398 |
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 399 |
+
with open(os.path.join(lff, "tasks.json"), "w") as f:
|
| 400 |
+
json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False)
|
| 401 |
+
with open(os.path.join(lff, "batches.json"), "w") as f:
|
| 402 |
+
json.dump(BATCH_NOTES, f, indent=1)
|
| 403 |
+
with open(os.path.join(lff, "rejected.json"), "w") as f:
|
| 404 |
+
json.dump(plan["rejected"], f, indent=1)
|
| 405 |
+
here = os.path.dirname(os.path.abspath(__file__))
|
| 406 |
+
for s in ("lerobot_replay.py", "lerobot_export.py"):
|
| 407 |
+
shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s))
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def main():
|
| 411 |
+
ap = argparse.ArgumentParser()
|
| 412 |
+
ap.add_argument("step", choices=["plan", "shard", "merge"])
|
| 413 |
+
ap.add_argument("--work", required=True)
|
| 414 |
+
ap.add_argument("--raw", default="")
|
| 415 |
+
ap.add_argument("--runs-root", default="")
|
| 416 |
+
ap.add_argument("--out", default="")
|
| 417 |
+
ap.add_argument("--paper", default="")
|
| 418 |
+
ap.add_argument("--task-set", default="")
|
| 419 |
+
ap.add_argument("--repo-id", default="lffbench/agent-replays")
|
| 420 |
+
ap.add_argument("--batches", default="")
|
| 421 |
+
ap.add_argument("--limit", type=int, default=0)
|
| 422 |
+
ap.add_argument("--shard", type=int, default=0)
|
| 423 |
+
ap.add_argument("--nshards", type=int, default=1)
|
| 424 |
+
ap.add_argument("--threads", type=int, default=2)
|
| 425 |
+
ap.add_argument("--vcodec", default="libsvtav1")
|
| 426 |
+
a = ap.parse_args()
|
| 427 |
+
{"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
if __name__ == "__main__":
|
| 431 |
+
main()
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_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_breakfast1_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_breakfast1_20261114/lff/source_closure/scripts/make_dossier.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build the record of an earlier failed attempt for the full5 history arms (docs/14 §6).
|
| 2 |
+
|
| 3 |
+
python scripts/make_dossier.py <run log dir> <out dir> [--attempt 1] [--allow-success]
|
| 4 |
+
|
| 5 |
+
The record contains only what the agent of that attempt saw: the starting images, every robot command with the
|
| 6 |
+
robot's reply (as logged by robot_server), the images those commands produced, the agent's closing remark and the
|
| 7 |
+
F1 verdict ("failed"). No outcome codes, measurements or hidden variables. The same builder is used for the own-history
|
| 8 |
+
arm (record of a failed independent run on the same instance) and the mismatched arm (record of a failed run on the
|
| 9 |
+
twin instance: same layout, different hidden variable), so the two dossiers differ only in content.
|
| 10 |
+
"""
|
| 11 |
+
import argparse
|
| 12 |
+
import json
|
| 13 |
+
import os
|
| 14 |
+
import shutil
|
| 15 |
+
|
| 16 |
+
DROP = ("state_file", "attempt_ended", "camera_file")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def shell_args(args):
|
| 20 |
+
out = []
|
| 21 |
+
for k, v in args.items():
|
| 22 |
+
v = json.dumps(v) if not isinstance(v, str) else v
|
| 23 |
+
out.append(f'{k}="{v}"' if (" " in v or not v) else f"{k}={v}")
|
| 24 |
+
return " ".join(out)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def main():
|
| 28 |
+
ap = argparse.ArgumentParser()
|
| 29 |
+
ap.add_argument("log")
|
| 30 |
+
ap.add_argument("out")
|
| 31 |
+
ap.add_argument("--attempt", type=int, default=1)
|
| 32 |
+
ap.add_argument("--allow-success", action="store_true")
|
| 33 |
+
ap.add_argument("--result-extra", default="",
|
| 34 |
+
help="layer-3 ladder (docs/20): text appended to the verdict in the Result section (paragraphs "
|
| 35 |
+
"separated by blank lines; the first one continues the verdict line). Empty = F1 record, "
|
| 36 |
+
"byte-identical to the record built without this option.")
|
| 37 |
+
a = ap.parse_args()
|
| 38 |
+
evs = [json.loads(line) for line in open(os.path.join(a.log, "events.jsonl")) if line.strip()]
|
| 39 |
+
start = next(e for e in evs if e["ev"] == "session_start")
|
| 40 |
+
if start.get("style", "la") not in ("la", None) and "style" in start:
|
| 41 |
+
raise SystemExit("only la-style runs are supported")
|
| 42 |
+
calls = [e for e in evs if e["ev"] == "call" and e.get("attempt") == a.attempt]
|
| 43 |
+
done = [e for e in evs if e["ev"] == "done" and e.get("attempt") == a.attempt]
|
| 44 |
+
if not done:
|
| 45 |
+
raise SystemExit(f"attempt {a.attempt} has no done event (run unfinished?)")
|
| 46 |
+
done = done[0]
|
| 47 |
+
if done["success"] and not a.allow_success:
|
| 48 |
+
raise SystemExit(f"attempt {a.attempt} succeeded; nothing to learn from (use --allow-success to force)")
|
| 49 |
+
imgs = os.path.join(a.log, "images")
|
| 50 |
+
# commands as that agent issued them: `./robot <cmd>` in a CLI workspace, the `robot` tool's argument otherwise
|
| 51 |
+
try:
|
| 52 |
+
iface = json.load(open(os.path.join(a.log, "agent_iface.json"))).get("agent_iface", "cli")
|
| 53 |
+
except OSError:
|
| 54 |
+
iface = "cli"
|
| 55 |
+
pre = "./robot " if iface == "cli" else ""
|
| 56 |
+
os.makedirs(os.path.join(a.out, "obs"), exist_ok=False)
|
| 57 |
+
|
| 58 |
+
def copy(rel):
|
| 59 |
+
base = os.path.basename(rel)
|
| 60 |
+
src = os.path.join(imgs, f"a{a.attempt}_{base}")
|
| 61 |
+
if not os.path.exists(src):
|
| 62 |
+
return None
|
| 63 |
+
shutil.copy(src, os.path.join(a.out, "obs", base))
|
| 64 |
+
return f"obs/{base}"
|
| 65 |
+
|
| 66 |
+
# starting images: the first images the agent saw (status at step 0)
|
| 67 |
+
first = sorted(f for f in os.listdir(imgs) if f.startswith(f"a{a.attempt}_") and "s000_" in f)
|
| 68 |
+
start_imgs = [copy(f.split("_", 1)[1]) for f in first]
|
| 69 |
+
lines = ["# Record of the earlier attempt", "",
|
| 70 |
+
"Starting scene: " + ", ".join(p for p in start_imgs if p), "",
|
| 71 |
+
"## Robot commands and replies", ""]
|
| 72 |
+
rec = []
|
| 73 |
+
for i, e in enumerate(calls, 1):
|
| 74 |
+
rep = {k: v for k, v in (e.get("report") or {}).items() if k not in DROP}
|
| 75 |
+
if "images" in rep:
|
| 76 |
+
rep["images"] = [p2 for p2 in (copy(p) for p in rep["images"]) if p2]
|
| 77 |
+
cmd = f"{pre}{e['cmd']} {shell_args(e.get('args') or {})}".strip()
|
| 78 |
+
lines += [f"{i}. `{cmd}`", " reply: `" + json.dumps(rep) + "`", ""]
|
| 79 |
+
rec.append(dict(n=i, command=cmd, reply=rep))
|
| 80 |
+
lines += [f"{len(calls) + 1}. `{pre}finish reason=\"{done.get('reason', '')}\"`", "",
|
| 81 |
+
"## Closing remark of that attempt", "", str(done.get("reason", "")), "",
|
| 82 |
+
"## Result", ""]
|
| 83 |
+
verdict = "The environment judged that attempt: " + ("succeeded." if done["success"] else "failed.")
|
| 84 |
+
extra = [x.strip() for x in a.result_extra.split("\n\n") if x.strip()]
|
| 85 |
+
if extra:
|
| 86 |
+
verdict += " " + extra[0]
|
| 87 |
+
lines += [verdict, ""]
|
| 88 |
+
for x in extra[1:]:
|
| 89 |
+
lines += [x, ""]
|
| 90 |
+
with open(os.path.join(a.out, "README.md"), "w") as f:
|
| 91 |
+
f.write("\n".join(lines))
|
| 92 |
+
with open(os.path.join(a.out, "record.jsonl"), "w") as f:
|
| 93 |
+
for r in rec:
|
| 94 |
+
f.write(json.dumps(r) + "\n")
|
| 95 |
+
with open(os.path.join(os.path.dirname(os.path.abspath(a.out)), os.path.basename(a.out) + ".source.json"), "w") as f:
|
| 96 |
+
json.dump(dict(log=os.path.abspath(a.log), attempt=a.attempt, task=start.get("task"), seed=start.get("seed"),
|
| 97 |
+
arm=start.get("arm", "none"), n_commands=len(calls), success=done["success"],
|
| 98 |
+
result_extra=a.result_extra), f)
|
| 99 |
+
print(json.dumps(dict(out=a.out, n_commands=len(calls), n_images=len(os.listdir(os.path.join(a.out, "obs"))))))
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
if __name__ == "__main__":
|
| 103 |
+
main()
|