diff --git a/leaf/final/episode_000118_wrist_image.png b/leaf/final/episode_000118_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..76c6c9db8856882b7c1d372ad03d873382b4225d --- /dev/null +++ b/leaf/final/episode_000118_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77af1939ae641938d0217124c66337eb635497af7dce25ce2a2ad9360891323e +size 36600 diff --git a/leaf/final/episode_000188.npz b/leaf/final/episode_000188.npz new file mode 100644 index 0000000000000000000000000000000000000000..23a76b0ef9185b60074af1a9c5e0ed1f4098e92f --- /dev/null +++ b/leaf/final/episode_000188.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a6c21041fe7e870dfb64e9066fdb8b1e88f1ea426a171630499c0c7676b940bd +size 3958 diff --git a/leaf/final/episode_000682.npz b/leaf/final/episode_000682.npz new file mode 100644 index 0000000000000000000000000000000000000000..f0d0b91abbd42d94a135909d9decbba4bc813518 --- /dev/null +++ b/leaf/final/episode_000682.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fa2bd914ca89f9b5a5472fafa69a4dc79fd040d45cba70164aab2383b9757e7a +size 3734 diff --git a/leaf/final/episode_001434_image.png b/leaf/final/episode_001434_image.png new file mode 100644 index 0000000000000000000000000000000000000000..aa36fc1975b754eceb290f4f7e23f149cbd16b37 --- /dev/null +++ b/leaf/final/episode_001434_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:96386904931713cf1d2618f02e2d35c0f8918c88651be8401e4502e07f4eda7e +size 56382 diff --git a/leaf/final/episode_001473.npz b/leaf/final/episode_001473.npz new file mode 100644 index 0000000000000000000000000000000000000000..f63506b989c4ef93ade6966b6cf9bb6afe264fd6 --- /dev/null +++ b/leaf/final/episode_001473.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bffcee52ba7d49087c639ec2354a58b1e4f8b538f39107daea320e497af7de06 +size 3838 diff --git a/leaf/final/episode_003014_image.png b/leaf/final/episode_003014_image.png new file mode 100644 index 0000000000000000000000000000000000000000..fc3125019ebe98d38db9bfa0e83c89de7d5026a8 --- /dev/null +++ b/leaf/final/episode_003014_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1d0e0584c3f8724b9119f09ccb2d5cd39c9d0dd3a5fc459568891f45f0b34fbd +size 55931 diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/arm_specs/l3_card_shelf.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/arm_specs/l3_card_shelf.py new file mode 100644 index 0000000000000000000000000000000000000000..7e45931d7094d6260a85d4faa1791ad3e9d072c7 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/arm_specs/l3_card_shelf.py @@ -0,0 +1,65 @@ +"""Controlled arms for l3_card_shelf (2026-10-12, docs/14 sec. 6). + +Hidden variable: which end of the (symmetric-looking) card holds the 8 g weight. The centre of mass is compiled into +the card's MJCF along its local +x, so the heavy end is chosen purely by `card_yaw` (heavy end direction = yaw); +`heavy_near` / `heavy_edge` are bookkeeping only (nothing in reset / outcome / policies reads them), kept consistent. +No override changes geometry, mass or inertia, so no bounding-volume refit is involved. + +h0 : the same card turned end for end (yaw + 180 deg): identical pose and footprint, the weight now in the FAR end, + so the common-sense "slide the nearest end out" slides the light end and succeeds. +twin : the trap stays (the heavy end is the nearest end) but it points to the OPPOSITE shelf edge: the card is mirrored + through the shelf centre along its long axis (near gap, side offset, jitter mirrored) and keeps its weight in + the end that is now nearest. The right correction (slide the other, light end) is then over the opposite + edge. For an x-card this makes the near end the BACKWARD one, which the task's own sampler avoids because a + card tipping off the backward edge lands behind the shelf (agentview shows the shelf empty, not the card); + see the arm validation (results/l3_card_shelf/arms/). For an instance whose heavy end is already the far end + (naive succeeds there) the twin keeps the pose and turns the card end for end, so the weight is in the near + end and the heavy edge is again the opposite one. +reveal: which shelf edge the heavy end points to, in the F2 feedback's edge words. +""" +import numpy as np + +HIDDEN_KEYS = ("card_yaw", "heavy_near", "heavy_edge") + +OPPOSITE = {"forward": "backward", "backward": "forward", "left": "right", "right": "left"} +GLOSS = {"forward": "away from the robot", "backward": "towards the robot", "left": "on the robot's left", + "right": "on the robot's right"} + + +def _wrap(a): + return float((a + np.pi) % (2 * np.pi) - np.pi) + + +def h0(inst): + if not inst["heavy_near"]: + return {} # already the ordinary case for the naive habit (weight away from the end that gets slid out) + return dict(card_yaw=_wrap(inst["card_yaw"] + np.pi), heavy_near=False, heavy_edge=inst["far_edge"]) + + +def twin(inst): + if not inst["heavy_near"]: + return dict(card_yaw=_wrap(inst["card_yaw"] + np.pi), heavy_near=True, heavy_edge=inst["near_edge"]) + a = 0 if inst["card_along"] == "x" else 1 # world axis of the card's long side + c = list(inst["card_xy"]) + c[a] = 2.0 * inst["shelf_xy"][a] - c[a] + yaw = inst["card_yaw"] + yaw = np.pi - yaw if a == 0 else -yaw # reflection x -> -x (resp. y -> -y) of the card's heading + return dict(card_xy=[float(c[0]), float(c[1])], card_yaw=_wrap(yaw), near_edge=OPPOSITE[inst["near_edge"]], + far_edge=OPPOSITE[inst["far_edge"]], heavy_edge=OPPOSITE[inst["heavy_edge"]]) + + +def reveal(inst): + e = inst["heavy_edge"] + 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 " + f"{e} edge ({GLOSS[e]}), so its centre of mass is 2.8 cm from the card's middle towards that end.") + + +def fix(inst, params): + """Ladder Fix rung (docs/20): slide the light end out (two strokes to 2 and 3 cm), grasp the overhang, bin.""" + light = OPPOSITE[inst["heavy_edge"]] + return (f"A way to succeed: slide the light end out, not the heavy one. The light end is the one pointing towards " + f"the shelf's {light} edge ({GLOSS[light]}). With the gripper closed, press the fingertips lightly on the " + f"middle of the card and drag it slowly (speed about 0.08) along its long side towards that edge, in two " + f"strokes: first until that end sticks out about 2 cm beyond the edge, look, then until it sticks out " + f"about 3 cm. Then open the gripper, grasp the part that sticks out about 2 cm beyond the edge, at the " + f"card's height, lift it and drop the card into the bin.") diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/arm_specs/l3_wall_flush.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/arm_specs/l3_wall_flush.py new file mode 100644 index 0000000000000000000000000000000000000000..1f5852c38e7bb8e4fa2181a932e9263861e1105f --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/arm_specs/l3_wall_flush.py @@ -0,0 +1,61 @@ +"""Controlled arms for l3_wall_flush (2026-10-12). + +Hidden variable: inst["gap"] -- the box-wall gap, 0-3 mm (below camera resolution), far less than the ~1.2 cm a +finger needs, so the wall-side finger lands on the wall top. sample_instance caches the wall position derived from it +(wall_x = box_x + side * (wall half thickness + box half width + gap)) and apply_instance reads only inst["wall_xy"], +so every override below sets wall_xy as well. + +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 + same side). There is room for the whole finger and the prior (grasp across the width where the box lies) works. + (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 + the outer edge of the finger still caught the wall top and the box slipped out on the way, seeds 3000 / 3003.) +twin Gap unchanged (box still flush, trap active), box / plate / wall length / wall x unchanged, but the wall slid + 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 + extreme). The original's nearer wall end is +y (or -y); the twin's is -y (or +y): the push that clears the + wall goes the opposite way, and is the shortest possible push (about 10 + 4.5 cm). + Note: pushing the original's box towards its FAR end also clears the wall (just a longer push), so the cross + check "twin oracle on the original" succeeds (measured 5/5, seeds 3000-3004; results/l3_wall_flush/arms/ + validate.json). The twin changes which way to push, not whether pushing works. +reveal The gap, and on which side of the box the wall is, in the task's F2 frame words. +""" +BOX_HALF_X, BOX_HALF_Y, WALL_HALF_T = 0.03, 0.08, 0.015 +H0_GAP = 0.05 + +HIDDEN_KEYS = ("gap",) + + +def _wall_x(inst, gap): + return inst["box_xy"][0] + inst["side"] * (WALL_HALF_T + BOX_HALF_X + gap) + + +def h0(inst): + return {"gap": H0_GAP, "wall_xy": [_wall_x(inst, H0_GAP), inst["wall_xy"][1]]} + + +def twin(inst): + wy, by = inst["wall_xy"][1], inst["box_xy"][1] + u_max = inst["wall_hl"] - BOX_HALF_Y - 0.02 + nearer = 1 if by - wy > 0 else -1 # same rule as WallFlush._nearer_end + u_twin = -nearer * u_max # box offset from the wall centre in the twin: near the other end + return {"wall_xy": [inst["wall_xy"][0], by - u_twin]} + + +def reveal(inst): + side = "far side (away from the robot)" if inst["side"] > 0 else "near side (toward the robot)" + return (f"The long box is pressed against the wall on its {side} along its whole length: the gap between box " + f"and wall is only about {max(100 * inst['gap'], 0.1):.1f} cm.") + + +def fix(inst, params): + """Ladder Fix rung (docs/20): push the box along the wall past its nearer end (oracle end, margin 4.5 cm), then + grasp across the width and place.""" + end, margin = int(params["end"]), float(params["margin"]) + wy, hl, by = float(inst["wall_xy"][1]), float(inst["wall_hl"]), float(inst["box_xy"][1]) + wall_end = wy + hl if end > 0 else wy - hl + dist = max(0.0, end * (wall_end + end * margin - by)) + side, other = ("left", "right") if end > 0 else ("right", "left") + return (f"A way to succeed: first get the box away from the wall, then grasp it. With the gripper closed and the " + f"fingertips about 1 cm above the table, push on the box's end face on the robot's {other} side and slide " + f"the box slowly (speed about 0.08) along the wall towards the robot's {side}, about {100 * dist:.0f} cm, " + f"until the whole box is past the end of the wall (its centre about {100 * margin:.1f} cm beyond the " + f"wall's end). Then lift, open the gripper, grasp the box across its 6 cm width and put it on the plate.") diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/arm_specs/l7_key_turn.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/arm_specs/l7_key_turn.py new file mode 100644 index 0000000000000000000000000000000000000000..907cfe292fd7ae33c3e38f81159e15dd859d9a4f --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/arm_specs/l7_key_turn.py @@ -0,0 +1,34 @@ +"""Controlled-arm spec for l7_key_turn (2026-10-12). + +Hidden variable: inst["direction"], the way the key opens the lock ("CCW" or "CW", seen from above). apply_instance() +derives the joint range and outcome()/check_unlock()/oracle_params() derive the open sign from it on every reset, so +overriding "direction" alone is enough (nothing is cached at sampling time). + +The scripted prior (naive) turns counterclockwise, so the trap exists only on CW locks -- all full5 instances are CW. + +h0 -> direction = "CCW": same lock position / yaw, the key opens the common-sense way, naive succeeds. +twin -> {} (no valid twin). The task has a single binary hidden variable and the trap exists only for one of its two + values: a twin with the trap still active must be CW again, i.e. need exactly the same correction ("turn + clockwise"), and the sign-flipped twin (CCW) is the H0 twin, where naive succeeds. There is no second hidden + constraint (the required angle is the fixed quarter turn named in the instruction). The mismatched-history + arm therefore has to take another instance's history -- note that every trap instance's history teaches the + same correction, so for this task a mismatched history is not misleading about the direction. +reveal -> states which way the key turns and that the other way stops after ~3 deg (the words "clockwise", + "counterclockwise", "seen from above" are those of the task's F2 feedback). +""" + +HIDDEN_KEYS = ("direction",) + + +def h0(inst): + return {"direction": "CCW"} + + +def twin(inst): + return {} + + +def reveal(inst): + ok, other = (("counterclockwise", "clockwise") if inst["direction"] == "CCW" else ("clockwise", "counterclockwise")) + return (f"Note: this lock opens only when the key is turned {ok} (seen from above); turned {other} the key moves " + f"about 3 degrees and then hits a hard stop.") diff --git a/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 b/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 new file mode 100644 index 0000000000000000000000000000000000000000..2209c4d2440474d612687439a6eed5b95d150712 --- /dev/null +++ b/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 @@ -0,0 +1,15 @@ +{ + "key": "claude_code|2.1.267|0399c793ff571d59|claude-sonnet-5-5|high", + "fingerprint_sha256": "fbf323682711d7010fa8cd2c9036b1082dab2a6cd4cf80983be1adf64e037d7c", + "written": "2026-10-20 02:16:00", + "summary": { + "system_chars": 182, + "tools": [ + "mcp__lff__robot", + "mcp__lff__shell", + "mcp__lff__view_images" + ], + "effort_in_request": "high", + "model_in_request": "claude-sonnet-5-5" + } +} \ No newline at end of file diff --git a/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 b/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 new file mode 100644 index 0000000000000000000000000000000000000000..c629a484a13c5208e9e5f113b943b46219a5bffd --- /dev/null +++ b/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 @@ -0,0 +1,15 @@ +{ + "key": "claude_code_full-oauth|2.1.299|2d894a4b1bfaaa9a|claude-sonnet-5-5|high", + "fingerprint_sha256": "a8c04b0dca902885e52e7e5680c1cf8b782469e79c518f83b72249342285bfb0", + "written": "2026-10-21 05:19:29", + "summary": { + "system_chars": 5629, + "tools": [ + "mcp__lff__robot", + "mcp__lff__shell", + "mcp__lff__view_images" + ], + "effort_in_request": "high", + "model_in_request": "claude-sonnet-5-5" + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/__init__.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8ffd9af077f968176127cbd3767912005f648ac3 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/__init__.py @@ -0,0 +1 @@ +"""LFF-Bench agent harness: tool interface, context packing, model backends, protocol runner.""" diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/camera.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/camera.py new file mode 100644 index 0000000000000000000000000000000000000000..e1ce86343d9f718577b0a672ed5cb3202c6fc941 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/camera.py @@ -0,0 +1,100 @@ +"""Camera geometry for the agent tools: pixel -> world back-projection with the rendered depth map. + +Conventions (match the images the agent receives, i.e. `envs.render`, which flips MuJoCo's +bottom-up buffer to an upright image): + u = column index (0 = left edge), v = row index (0 = top edge), both in pixels of a res x res image. +Intrinsics / extrinsics / depth linearisation come from robosuite.utils.camera_utils. +""" +import numpy as np +from robosuite.utils import camera_utils as CU + +from .. import envs + +# agent-facing camera name -> MuJoCo camera name +CAMERAS = {"agentview": "agentview", "wrist": "robot0_eye_in_hand"} + + +def mj_cam(name): + if name in CAMERAS: + return CAMERAS[name] + if name in CAMERAS.values(): + return name + raise KeyError(f"unknown camera {name!r}; use one of {sorted(CAMERAS)}") + + +def intrinsics(env, cam, res): + return CU.get_camera_intrinsic_matrix(env.sim, mj_cam(cam), res, res) + + +def cam_to_world(env, cam): + """4x4 pose of the camera in the world, OpenCV axes (x right, y down, z forward).""" + return CU.get_camera_extrinsic_matrix(env.sim, mj_cam(cam)) + + +def render_depth(env, cam, res): + """Metric depth (distance along the optical axis, metres), upright (res, res).""" + _, d = envs.render(env, mj_cam(cam), res, depth=True) + return CU.get_real_depth_map(env.sim, np.clip(d, 0.0, 1.0)) + + +def world_to_pixel(env, cam, xyz, res): + """Project a world point; returns (u, v) floats (u = column, v = row) and the depth.""" + K = intrinsics(env, cam, res) + T = np.linalg.inv(cam_to_world(env, cam)) + p = T @ np.append(np.asarray(xyz, float), 1.0) + uvw = K @ p[:3] + return float(uvw[0] / uvw[2]), float(uvw[1] / uvw[2]), float(p[2]) + + +def pixel_ray(env, cam, u, v, res): + """Unit ray direction (world) through pixel (u, v) and the camera origin.""" + K = intrinsics(env, cam, res) + E = cam_to_world(env, cam) + d_cam = np.array([(u - K[0, 2]) / K[0, 0], (v - K[1, 2]) / K[1, 1], 1.0]) + d = E[:3, :3] @ d_cam + return E[:3, 3].copy(), d / np.linalg.norm(d) + + +def pixel_to_world(env, cam, u, v, res, depth=None): + """Back-project pixel (u, v) of a res x res image using the depth map. Returns a dict.""" + if depth is None: + depth = render_depth(env, cam, res) + iu, iv = int(round(u)), int(round(v)) + if not (0 <= iu < res and 0 <= iv < res): + raise ValueError(f"pixel ({u}, {v}) outside the {res}x{res} image") + z = float(depth[iv, iu]) + K = intrinsics(env, cam, res) + E = cam_to_world(env, cam) + p_cam = np.array([(u - K[0, 2]) * z / K[0, 0], (v - K[1, 2]) * z / K[1, 1], z, 1.0]) + p = E @ p_cam + far = env.sim.model.vis.map.zfar * env.sim.model.stat.extent + return dict(xyz=p[:3], depth=z, valid=bool(z < 0.98 * far)) + + +def image_axes(env, cam, res, plane_z=envs.TABLE_Z): + """World directions of image-right and image-down at the image centre, projected onto the table + plane (for describing the camera to the agent). Returns two unit 2-vectors (x, y).""" + o, d = pixel_ray(env, cam, res / 2, res / 2, res) + if abs(d[2]) < 1e-6: + return None + t = (plane_z - o[2]) / d[2] + c = o + t * d + out = [] + for du, dv in ((8, 0), (0, 8)): + o2, d2 = pixel_ray(env, cam, res / 2 + du, res / 2 + dv, res) + t2 = (plane_z - o2[2]) / d2[2] + w = (o2 + t2 * d2 - c)[:2] + out.append(w / max(np.linalg.norm(w), 1e-9)) + return out + + +def describe_axes(env, cam, res): + """Human-readable mapping 'image right ~ +y, image down ~ +x' (dominant axis, sign).""" + ax = image_axes(env, cam, res) + if ax is None: + return None + names = [] + for w in ax: + i = int(np.argmax(np.abs(w))) + names.append(("+" if w[i] > 0 else "-") + "xy"[i]) + return dict(right=names[0], down=names[1]) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/context.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/context.py new file mode 100644 index 0000000000000000000000000000000000000000..2ebbdba3d6571712354f0b2f43e48fd1ba16379c --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/context.py @@ -0,0 +1,377 @@ +"""Backend-neutral conversation, attempt records, memory selection and prompt text. + +A conversation is a list of items (plain dicts): + {"kind": "user", "parts": [{"type": "text", "text": str} | {"type": "image", "image": ImageRef}], "live": bool} + {"kind": "assistant", "text": str|None, "tool_calls": [ToolCall], "raw": list|None, "backend": str} + {"kind": "tool_output", "call_id": str, "name": str, "text": str} +The system prompt is kept separately (Conversation.system). Backends convert this into their own wire +format (OpenAI Responses input items, Chat Completions messages, ...). + +"live" user items are the current attempt's observations; old live images can be dropped to bound the +request size. History (earlier attempts) is packed into the attempt's first user item and never pruned, +so the request prefix stays byte-stable within an attempt and grows append-only across attempts +(prompt-cache friendly). +""" +import copy +import json +import math +from dataclasses import dataclass, field +from typing import Optional + +from ..envs import TABLE_Z + +MEMORY_MODES = ("none", "full", "last", "mismatched") +FEEDBACK_LEVELS = ("F0", "F1", "F2") + + +@dataclass +class ToolCall: + id: str + name: str + arguments: dict + raw_arguments: str = "" + + +@dataclass +class StepRecord: + step: int + name: str + args: dict + report: dict + ok: bool + wall_s: float = 0.0 + sim_steps: int = 0 + frame: object = None # ImageRef of the agentview after this step (for keyframes) + + +@dataclass +class AttemptRecord: + seed: int + attempt: int + steps: list = field(default_factory=list) + keyframes: list = field(default_factory=list) # [(caption, ImageRef)] + outcome: dict = field(default_factory=dict) + success: bool = False + feedback: str = "" + done_reason: Optional[str] = None + diagnosis: Optional[str] = None + ended_by: str = "" + backend_meta: dict = field(default_factory=dict) + + def action_signature(self, nd=2): + """Rounded action sequence (to compare consecutive attempts: 'same mistake again').""" + sig = [] + for s in self.steps: + if s.name in ("get_observation", "pixel_to_world", "locate", "done"): + continue + sig.append((s.name, tuple(sorted((k, round(v, nd) if isinstance(v, (int, float)) and v is not None else v) + for k, v in s.args.items())))) + return tuple(sig) + + +def select_history(mode, own, donor=None): + """Which earlier attempts the agent sees at the start of the next attempt.""" + if mode == "none": + return [] + if mode == "full": + return list(own) + if mode == "last": + return list(own[-1:]) + if mode == "mismatched": + if donor is None: + raise ValueError("mismatched memory needs donor attempts from another instance") + return list(donor[:len(own)]) + raise ValueError(mode) + + +class Conversation: + def __init__(self, system): + self.system = system + self.items = [] + + def add_user(self, parts, live=True): + self.items.append(dict(kind="user", parts=list(parts), live=live)) + + def add_assistant(self, text, tool_calls, raw=None, backend=""): + self.items.append(dict(kind="assistant", text=text, tool_calls=list(tool_calls), raw=raw, backend=backend)) + + def add_tool_output(self, call_id, name, text): + self.items.append(dict(kind="tool_output", call_id=call_id, name=name, text=text)) + + def n_images(self): + return sum(1 for it in self.items if it["kind"] == "user" for p in it["parts"] if p["type"] == "image") + + +def prune_live_images(items, max_live): + """Copy of `items` keeping only the newest `max_live` live images. Hysteresis: when the budget is + exceeded, prune down to half of it so the request prefix stays stable for several steps.""" + if max_live is None or max_live < 0: + return items + live = [(i, j) for i, it in enumerate(items) if it["kind"] == "user" and it.get("live") + for j, p in enumerate(it["parts"]) if p["type"] == "image"] + if len(live) <= max_live: + return items + keep_n = max(max_live // 2, 1) + drop = set(live[:len(live) - keep_n]) + out = [] + for i, it in enumerate(items): + if it["kind"] == "user" and any((i, j) in drop for j in range(len(it["parts"]))): + it = dict(it) + parts = [] + for j, p in enumerate(it["parts"]): + if (i, j) in drop: + parts.append(dict(type="text", text=f"[{p['image'].camera} image omitted to save context]")) + else: + parts.append(p) + it["parts"] = parts + out.append(it) + return out + + +# ---------------------------------------------------------------------------------------------- text + +def fmt_num(v): + if v is None: + return "null" + if isinstance(v, bool): + return str(v).lower() + if isinstance(v, float): + return f"{v:.3f}".rstrip("0").rstrip(".") if abs(v) < 1e4 else f"{v:.4g}" + return json.dumps(v) + + +def fmt_call(name, args): + return f"{name}(" + ", ".join(f"{k}={fmt_num(v)}" for k, v in args.items()) + ")" + + +def fmt_report(name, rep): + if not rep.get("ok", False): + return "ERROR: " + str(rep.get("error")) + bits = [] + if "reached" in rep: + bits.append("reached" if rep["reached"] else "NOT reached") + if "sweep_reached" in rep: + bits.append("sweep completed" if rep["sweep_reached"] else "sweep NOT completed") + if "eef_pos" in rep and name in ("move_to", "push", "open_gripper", "close_gripper"): + bits.append("eef (" + ", ".join(f"{x:.3f}" for x in rep["eef_pos"]) + ")") + if name in ("open_gripper", "close_gripper"): + bits.append(f"width {rep.get('gripper_width_m', 0):.3f} m") + if rep.get("holding_object") not in (None, False): + bits.append(f"holding {rep['holding_object']}" if isinstance(rep["holding_object"], str) else "holding an object") + if rep.get("touched_object") or rep.get("touched_objects"): + t = rep.get("touched_objects") + bits.append("touched " + ", ".join(t) if t else "touched an object") + if name == "pixel_to_world": + bits.append("world (" + ", ".join(f"{x:.3f}" for x in rep["world_xyz"]) + ")") + if name == "locate": + bits.append("pos (" + ", ".join(f"{x:.3f}" for x in rep["position"]) + ")") + if "target_clipped_to" in rep or "start_clipped_to" in rep: + bits.append("target clipped to workspace") + if rep.get("events"): + bits.append("EVENT: " + " ".join(rep["events"])) + return "; ".join(bits) if bits else "ok" + + +def summarize_actions(steps): + lines = [] + for s in steps: + if s.name == "done": + lines.append(f"{s.step}. done(reason={json.dumps(s.args.get('reason', ''))})") + else: + lines.append(f"{s.step}. {fmt_call(s.name, s.args)} -> {fmt_report(s.name, s.report)}") + return "\n".join(lines) if lines else "(no actions)" + + +def _text(t): + return dict(type="text", text=t) + + +def _img(ref): + return dict(type="image", image=ref) + + +class PromptBuilder: + """All text the agent sees. One instance per (task, config).""" + + def __init__(self, task, protocol, k, memory, feedback, image_res, cam_axes, privileged_locate=False, + object_names=(), grasp_report="bool", cams=("agentview", "wrist"), depth_tool=True): + self.task, self.protocol, self.k = task, protocol, k + self.depth_tool = depth_tool + self.memory, self.feedback = memory, feedback + self.image_res, self.cam_axes = image_res, cam_axes + self.privileged_locate, self.object_names = privileged_locate, list(object_names) + self.grasp_report, self.cams = grasp_report, tuple(cams) + + # ----------------------------------------------------------------------------- system prompt + def system_prompt(self): + ax = self.cam_axes.get("agentview") or {} + wx = self.cam_axes.get("wrist") or {} + lines = [ + "You control a Franka Panda robot arm with a parallel-jaw gripper in a tabletop physics simulation. " + "You act only by calling the provided tools, exactly one tool call per turn. Every action tool returns an " + "execution report; after each action you also receive new camera images and the robot's proprioceptive " + "state.", + "", + "Coordinates (world frame, metres): the table top is at z = %.2f; the robot base is at x = -0.66, y = 0; " + "+x points away from the robot, +y to the robot's left, +z up. Positions given to move_to / push are for " + "the gripper's grasp point (midway between the fingertips). The gripper always points straight down; yaw " + "(degrees) turns it about the vertical axis: at yaw 0 the fingers close along the world y axis, at yaw 90 " + "along the world x axis; yaw is taken modulo 180 degrees because the gripper is symmetric." % TABLE_Z, + "", + "Direction words in every text you receive (task, reports, feedback) are robot-centric: forward = +x (away " + "from the robot), backward = -x (toward the robot), left = +y (the robot's left), right = -y (the robot's " + "right), up = +z. They never mean left/right in an image.", + "", + "Cameras (%dx%d images): 'agentview' looks at the table from the side opposite the robot, so the robot " + "appears at the top of that image; image-right is %s and image-down is %s in world coordinates (so the " + "robot's left appears on the right side of that image). 'wrist' is " + "mounted on the gripper and looks down between the fingers (at yaw 0, image-right is %s and image-down is " + "%s).%s" + % (self.image_res, self.image_res, ax.get("right", "?"), ax.get("down", "?"), wx.get("right", "?"), + wx.get("down", "?"), + " For pixel_to_world, u is the column counted from the left edge and v the row counted from the top " + "edge of the image as you received it." if self.depth_tool else ""), + "", + "Proprioception (end-effector position, yaw, gripper width%s) comes from the robot's own sensors." + % (", whether an object is held" if self.grasp_report != "none" else ""), + ] + if self.privileged_locate: + lines += ["", "The locate tool is available and returns exact object positions. Objects: " + + ", ".join(self.object_names) + "."] + else: + lines += ["", "Object positions are not given to you: localise objects from the images, e.g. by calling " + "pixel_to_world on the pixel where you see them." if self.depth_tool else + "Object positions are not given to you and there is no depth sensor: the cameras give colour " + "images only. Localise objects from the images."] + lines += ["", self._protocol_text(), "", self._feedback_text()] + if self.memory != "none": + lines += ["", "At the start of every attempt after the first, before your first tool call, write one to " + "three sentences assessing the earlier attempt(s): what happened and what you will keep or " + "change."] + lines += ["", "Finish by calling done(reason) when you believe the task is complete. Be precise: small errors " + "in position or speed matter."] + return "\n".join(lines) + + def _protocol_text(self): + if self.memory == "none": + if self.protocol == "within": + return "Work on the task until you believe it is complete, then call done." + return "You have one attempt at the task; it ends when you call done." + if self.protocol == "within": + if self.feedback == "F0": + return (f"Everything happens in one continuous episode. After you call done you may be asked to " + f"continue from the current state; you may call done at most {self.k} times.") + return (f"Everything happens in one continuous episode. When you call done, the task is checked; if it is " + f"not complete you are told so and continue from the current state. You may call done at most " + f"{self.k} times.") + return (f"You get up to {self.k} attempts at the same task. Before every attempt the scene is reset to exactly " + f"the same initial state, with the same objects and the same physical properties. Each attempt ends " + f"when you call done; you will then see a summary of the attempt (key images, the actions you " + f"executed{'' if self.feedback == 'F0' else ' and outcome feedback'}).") + + def _feedback_text(self): + if self.memory == "none": + return "" + if self.feedback == "F0": + return ("You will not be told whether an attempt succeeded; judge it from the images. " + + ("Attempts continue until the budget is used up." if self.protocol == "cross" else "")) + if self.feedback == "F1": + return "After each attempt you are told only whether it succeeded." + return "After each attempt you are told whether it succeeded and, if not, a measurement of what went wrong." + + # ----------------------------------------------------------------------------- per attempt + def history_parts(self, instruction, history): + """First user item of an attempt (not pruned): task + packed earlier attempts. The header carries no + count so that the item grows append-only from one attempt to the next (prompt-cache friendly).""" + parts = [_text("TASK: " + instruction)] + if history: + parts.append(_text("\n=== Your earlier attempts ===")) + for i, rec in enumerate(history, 1): + parts += self.history_block(rec, i) + parts.append(_text("=== End of earlier attempts ===")) + return parts + + def current_parts(self, attempt, obs_images, proprio, continuing=False): + """Second user item of an attempt (live): attempt counter + current observation.""" + parts = [] + if self.memory != "none": + if self.protocol == "within" and continuing: + if self.feedback == "F0": + parts.append(_text(f"You called done. Continue from the current state (this is segment " + f"{attempt}; you may call done at most {self.k} times in total).")) + else: + parts.append(_text(f"You called done, but the task is not complete. Continue from the current " + f"state (this is segment {attempt}; you may call done at most {self.k} times " + f"in total).")) + elif self.protocol == "cross": + parts.append(_text(f"This is attempt {attempt} of at most {self.k}. The scene has been reset.")) + parts += self.observation_parts("Current observation", obs_images, proprio) + return parts + + def history_block(self, rec, idx): + head = f"\n--- Attempt {idx} ---" if self.protocol == "cross" else f"\n--- Segment {idx} (until done call {idx}) ---" + parts = [_text(head + "\nActions executed:\n" + summarize_actions(rec.steps))] + fb = (rec.feedback or "").strip() + if self.feedback != "F0" and fb: + parts.append(_text("Outcome feedback: " + fb)) + if rec.keyframes: + parts.append(_text("Key images (" + ", ".join(c for c, _ in rec.keyframes) + "):")) + for cap, ref in rec.keyframes: + parts.append(_text(f"[{cap}]")) + parts.append(_img(ref)) + return parts + + def observation_parts(self, title, images, proprio): + parts = [_text(f"\n{title}:")] + for ref in images: + parts.append(_text(f"{ref.camera} camera:")) + parts.append(_img(ref)) + parts.append(_text("Proprioception: " + json.dumps(proprio))) + return parts + + def step_observation(self, step, tool_name, images, proprio): + return self.observation_parts(f"Observation after step {step} ({tool_name})", images, proprio) + + @staticmethod + def nudge(): + return [_text("Please continue by calling exactly one tool (call done if you are finished).")] + + +def pick_keyframes(steps, initial, final, n=4): + """<= n agentview keyframes: start, up to n-2 informative intermediate frames, end (after settling).""" + out = [("start of attempt", initial)] if initial is not None and n >= 2 else [] + budget = n - len(out) - (1 if final is not None else 0) + cands = [s for s in steps if s.frame is not None] + if budget > 0 and cands: + events = [s for s in cands if s.name in ("push", "close_gripper", "open_gripper") + or s.report.get("touched_object") or s.report.get("touched_objects")] + pool = events if len(events) >= budget else cands + if len(pool) > budget: + idx = [round(i * (len(pool) - 1) / max(budget - 1, 1)) for i in range(budget)] if budget > 1 \ + else [len(pool) - 1] + pool = [pool[i] for i in sorted(set(idx))] + for s in sorted(pool, key=lambda s: s.step)[:budget]: + out.append((f"after step {s.step} ({s.name})", s.frame)) + if final is not None: + out.append(("end of attempt, after objects settled", final)) + return out[:n] + + +def wilson(k, n, z=1.96): + if n == 0: + return (float("nan"), float("nan")) + p = k / n + d = 1 + z * z / n + c = (p + z * z / (2 * n)) / d + h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d + return (max(0.0, c - h), min(1.0, c + h)) + + +def deep_strip_images(obj): + """JSON-friendly copy of conversation items (images -> paths).""" + obj = copy.copy(obj) + if isinstance(obj, dict): + return {k: (v.path if k == "image" else deep_strip_images(v)) for k, v in obj.items()} + if isinstance(obj, list): + return [deep_strip_images(v) for v in obj] + return obj diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/images.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/images.py new file mode 100644 index 0000000000000000000000000000000000000000..b1d89bbfa64e5913756c7b7920491d36805b7839 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/images.py @@ -0,0 +1,47 @@ +"""Image references and encoding (JPEG bytes are what the model sees and what is saved to disk).""" +import base64 +import io +from dataclasses import dataclass +from typing import Any, Optional + +import numpy as np + + +@dataclass +class ImageRef: + camera: str # agent-facing camera name ("agentview" / "wrist") + array: Any = None # uint8 HxWx3 + label: str = "" + path: Optional[str] = None # where the encoded image was saved + jpeg: Optional[bytes] = None # encoded bytes actually sent to the model + + def encoded(self, quality=90): + if self.jpeg is None: + if self.array is None and self.path: + with open(self.path, "rb") as f: + self.jpeg = f.read() + else: + self.jpeg = encode_jpeg(self.array, quality) + return self.jpeg + + def data_url(self, quality=90): + return "data:image/jpeg;base64," + base64.b64encode(self.encoded(quality)).decode("ascii") + + @property + def size(self): + return None if self.array is None else tuple(np.asarray(self.array).shape[:2]) + + +def encode_jpeg(arr, quality=90): + from PIL import Image + buf = io.BytesIO() + Image.fromarray(np.asarray(arr, dtype=np.uint8)).save(buf, format="JPEG", quality=int(quality)) + return buf.getvalue() + + +def resize(arr, res): + from PIL import Image + arr = np.asarray(arr, dtype=np.uint8) + if arr.shape[0] == res and arr.shape[1] == res: + return arr + return np.asarray(Image.fromarray(arr).resize((res, res), Image.BILINEAR)) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/replay.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..a7ada6a9360194c631994cd2a658a950ee554a4b --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/replay.py @@ -0,0 +1,59 @@ +"""Rebuild AttemptRecords from a finished run directory (events.jsonl + images/), e.g. to use a full-memory +run as the donor pool of a mismatched-memory run without re-running (and re-paying for) it.""" +import json +import os + +from .context import AttemptRecord, StepRecord +from .images import ImageRef + + +def load_events(run_dir): + with open(os.path.join(run_dir, "events.jsonl")) as f: + return [json.loads(line) for line in f if line.strip()] + + +def load_records(run_dir, task=None, feedback="F2"): + """{seed: [AttemptRecord]} with keyframes loaded from disk. Feedback text is re-rendered at the + requested level with task.feedback() when a task is given (else the logged F2 text / '').""" + ev = load_events(run_dir) + insts, steps, out = {}, {}, {} + for e in ev: + t = e["type"] + if t == "run_start": + insts[e["seed"]] = e["inst"] + out[e["seed"]] = [] + elif t == "tool_call": + steps.setdefault((e["seed"], e["attempt"]), []).append( + StepRecord(step=e["step"], name=e["name"], args=e["args"], report=e["report"], ok=e["ok"])) + elif t == "attempt_end": + seed, a = e["seed"], e["attempt"] + kfs = [] + for cap, rel in e.get("keyframes") or []: + p = os.path.join(run_dir, rel) + with open(p, "rb") as f: + kfs.append((cap, ImageRef(camera="agentview", path=p, jpeg=f.read()))) + o = e["outcome"] + if task is not None: + fb = task.feedback(insts.get(seed, {}), o, feedback) + else: + fb = {"F0": "", "F1": "Attempt succeeded." if e["success"] else "Attempt failed."}.get( + feedback, e.get("feedback_f2", "")) + out.setdefault(seed, []).append(AttemptRecord( + seed=seed, attempt=a, steps=steps.get((seed, a), []), keyframes=kfs, outcome=o, + success=bool(e["success"]), feedback=fb, done_reason=e.get("done_reason"), + diagnosis=e.get("diagnosis"), ended_by=e.get("ended_by", ""), backend_meta=e.get("backend_meta") or {})) + return out + + +def derange(target_seeds, donor_seeds): + """Map each target seed to a donor seed != itself (cyclic shift over the sorted donor pool).""" + pool = sorted(donor_seeds) + if not pool: + raise ValueError("empty donor pool") + m = {} + for i, s in enumerate(sorted(target_seeds)): + j = (pool.index(s) + 1) % len(pool) if s in pool else i % len(pool) + if pool[j] == s: + raise ValueError(f"cannot find a donor different from seed {s} (pool {pool})") + m[s] = pool[j] + return m diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/robot_server.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/robot_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2b05a011de75f29faf4674c3b96ca68bdb98cb0d --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/robot_server.py @@ -0,0 +1,966 @@ +"""Robot server for driving an LFF-Bench task from an isolated agent (e.g. a Claude Code subagent). + +The server owns the simulator, the task instance and its hidden variables. The agent only gets a +sandbox directory containing a tiny `robot` CLI (talks to this server over localhost HTTP), a README +with the instructions, and the observation images the server writes into `/obs/`. +Nothing about the benchmark (code paths, hidden variables, success rule, scripted policies) is ever +written into the sandbox. + +Attempt protocol (same semantics as harness.py): + cross `done` -> outcome is measured; if failed and attempts remain, the scene is reset to the same + initial state + hidden variables and the next attempt starts. + within `done` -> outcome is measured; if failed and done-calls remain, continue from the current state. +memory=none: every attempt is meant for a fresh agent; after `done` the server tells the agent to stop +(no feedback) and waits for the orchestrator to start a new agent (`./robot status` shows the state). + +Run: python -m lffbench.agent.robot_server --task l5_slide_to_target --seed 1001 --sandbox --port 8765 +""" +import argparse +import importlib +import json +import os +import pkgutil +import shutil +import sys +import time +import traceback +from http.server import BaseHTTPRequestHandler, HTTPServer +import signal +import textwrap + +import numpy as np + +from .. import tasks as task_pkg +from ..task_base import TASKS +from . import camera as C +from .context import PromptBuilder +from .tools import ACTION_TOOLS, WS_HI, WS_LO, ToolExecutor, _json_default + +for _m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{_m.name}") + +LFF_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +SHELL_TEMPLATE = r'''#!/bin/bash +# Run a shell command inside this workspace, in the episode jail (no network, host data hidden): +# ./shell '' or ./shell <<'EOF' ... EOF (command read from stdin) +WS="$(cd "$(dirname "$0")" && pwd)" +if [ $# -gt 0 ]; then CMD="$*"; else CMD="$(cat)"; fi +exec unshare --user --map-root-user --mount --net -- /opt/lffjail/jail_inner.sh "$WS" timeout -k 5 60 bash -c "$CMD" +''' + +CLI_TEMPLATE = r'''#!/usr/bin/env python3 +"""Robot command-line interface. Usage: ./robot [key=value ...] (./robot help)""" +import json, sys, urllib.request +PORT = __PORT__ +TOKEN = "__TOKEN__" +def main(): + if len(sys.argv) < 2: + sys.argv.append("help") + cmd, args = sys.argv[1], {} + for a in sys.argv[2:]: + if "=" not in a: + print(f"bad argument {a!r}: use key=value"); sys.exit(2) + k, v = a.split("=", 1) + try: + args[k] = json.loads(v) + except ValueError: + args[k] = v + req = urllib.request.Request(f"http://127.0.0.1:{PORT}/call", data=json.dumps({"cmd": cmd, "args": args}).encode(), + headers={"Content-Type": "application/json", "X-Token": TOKEN}) + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + with opener.open(req, timeout=600) as r: + print(r.read().decode()) +main() +''' + + +def strip_axes(text): + """v2: keep the robot-centric words of the F2 feedback ("to the robot's left", "forward") but drop the explicit + coordinate-axis labels ("(+y)", "+x, ", "+yaw"), so the feedback does not hand over the axis convention that the + v2 instructions deliberately leave out.""" + import re + t = re.sub(r"\s?\((?:[+-]?[xyz]|[+-]yaw)\)", "", text) # " (+y)", " (x)", " (-yaw)" + t = re.sub(r"\(([+-][xyz]|[+-]yaw), ", "(", t) # "(+x, away from the robot)" + t = re.sub(r", [+-](?:[xyz]|yaw)\)", ")", t) # "(... robot's left, +yaw)" + t = re.sub(r"\s{2,}", " ", t) + return t + + +class VideoRec: + """Records agentview | wrist while the simulator steps (one frame every `every` control steps, played at + `fps`, i.e. sped up by every * fps / 20). A header shows the attempt, the current robot command and the + report of the previous one; gripper commands and attempt outcomes get short freeze frames.""" + + BAND = 56 + + def __init__(self, path, env, res=320, every=3, fps=20, title=""): + import imageio + from . import camera as _C + self.env, self.res, self.every, self.fps, self.title = env, res, every, fps, title + self.cams = [_C.mj_cam("agentview"), _C.mj_cam("wrist")] + self.w = imageio.get_writer(path, fps=fps, quality=7, macro_block_size=8) + self.n = 0 + self.lines = ["", "", ""] + self.last = None + orig = env.step + + def step(a): + out = orig(a) + self.n += 1 + if self.w is not None and self.n % self.every == 0: + self.grab() + return out + + env.step = step + + def _font(self, size): + from PIL import ImageFont + try: + return ImageFont.load_default(size=size) + except TypeError: + return ImageFont.load_default() + + def grab(self): + from PIL import Image, ImageDraw + from .. import envs as _E + img = np.concatenate([_E.render(self.env, c, self.res) for c in self.cams], axis=1) + im = Image.new("RGB", (2 * self.res, self.res + self.BAND), (0, 0, 0)) + im.paste(Image.fromarray(img), (0, self.BAND)) + d = ImageDraw.Draw(im) + hdr = [self.title] + self.lines[:2] + for i, s_ in enumerate(hdr): + d.text((5, 3 + 17 * i), s_[:120], fill=(255, 255, 255) if i else (255, 220, 120), font=self._font(13)) + self.last = np.asarray(im) + self.w.append_data(self.last) + + def hold(self, secs): + if self.w is None: + return + self.grab() + for _ in range(int(secs * self.fps)): + self.w.append_data(self.last) + + def card(self, lines, secs=3.0, color=(20, 20, 20)): + if self.w is None: + return + from PIL import Image, ImageDraw + im = Image.new("RGB", (2 * self.res, self.res + self.BAND), color) + d = ImageDraw.Draw(im) + y = 14 + for s_ in lines: + for part in textwrap.wrap(s_, 62) or [""]: + d.text((14, y), part, fill=(255, 255, 255), font=self._font(15)) + y += 19 + y += 5 + fr = np.asarray(im) + for _ in range(int(secs * self.fps)): + self.w.append_data(fr) + + def close(self): + if self.w is not None: + self.w.close() + self.w = None + + +def _short(rep): + keys = ("touched_object", "holding_object", "gripper_width_m", "eef_pos", "eef_yaw_deg", "error") + return ", ".join(f"{k}={rep[k]}" for k in keys if k in rep) + + +class RobotSession: + def __init__(self, a): + self.a = a + self.task = TASKS[a.task](cam_res=a.image_res) + if a.max_steps is None: # long procedural tasks declare a larger per-attempt budget + a.max_steps = int(getattr(self.task, "agent_max_steps", 40)) + self.inst = self.task.sample_instance(a.seed) + if getattr(a, "nominal", False): + # control condition: same scene, hidden calibration error removed (L1 tasks only) -> plain pick-and-place + hidden = [k for k in ("bias", "yaw_bias") if k in self.inst] + if not hidden: + raise SystemExit(f"--nominal is not supported for {a.task} (no bias / yaw_bias in the instance)") + for k in [k for k in self.inst if "bias" in k]: # bias, bias_r, yaw_bias, yaw_bias_deg, ... + v = self.inst[k] + if isinstance(v, (list, tuple)): + self.inst[k] = [0.0] * len(v) + elif isinstance(v, (int, float)): + self.inst[k] = 0.0 + self.inst["nominal"] = True + # full5 controlled arms (docs/14 ยง6): h0 / twin override the hidden variable, hplus states it in the instruction + self.arm, self.arm_overrides, self.reveal_text = getattr(a, "arm", "none") or "none", {}, "" + if self.arm in ("h0", "twin"): + from .. import arm_specs + self.arm_overrides = arm_specs.overrides(a.task, self.arm, self.inst) + self.inst.update(self.arm_overrides) + elif self.arm == "hplus": + from .. import arm_specs + self.reveal_text = arm_specs.reveal(a.task, self.inst).strip() + if a.style in ("v2", "la"): # same rule as the F2 feedback: no axis labels such as "(+y)" + self.reveal_text = strip_axes(self.reveal_text) + self.n_mon_events = 0 # regression snapshots: monitor events already inspected + self.protocol = getattr(self.task, "protocol", "cross") + self.k = a.k or self.task.max_attempts + # --hide-k (memory=full): README and status say 1 attempt, exactly like an independent k=1 run, and the other + # attempts are announced only after a failure, so attempt 1 sees the same thing as the independent run. + self.k_shown = 1 if getattr(a, "hide_k", False) and a.memory == "full" else self.k + assert self.k_shown == self.k or a.style in ("v2", "la"), "--hide-k needs --style v2 or la" + self.sandbox = os.path.abspath(a.sandbox) + self.obs_dir = os.path.join(self.sandbox, "obs") + self.log_dir = os.path.abspath(a.log_dir) + os.makedirs(self.obs_dir, exist_ok=True) + os.makedirs(os.path.join(self.log_dir, "images"), exist_ok=True) + self.events = open(os.path.join(self.log_dir, "events.jsonl"), "a") + import secrets + self.token = secrets.token_hex(8) + self.n_actions = 0 # robot commands in the current attempt (step budget) + self.attempt = 1 + self.step = 0 + self.finished = False + self.waiting_new_agent = False + self.history = [] + self.last_send = None + cam_axes = {c: C.describe_axes(self.task.env, c, a.image_res) for c in C.CAMERAS} + names = getattr(self.task, "agent_object_names", None) or list(self.task.env.objects_dict) + memory = "none" if a.memory == "none" else "full" + self.pb = PromptBuilder(self.task, self.protocol, self.k, memory, a.feedback, a.image_res, cam_axes, + object_names=names, cams=("agentview", "wrist"), depth_tool=a.perception == "depth") + self.video = None + if a.video: + self.video = VideoRec(a.video, self.task.env, every=a.video_every, fps=a.video_fps, + title=f"{a.task} seed={a.seed} perception={a.perception} (sped up x{a.video_every * a.video_fps // 20})") + self.video.card([f"Task: {a.task} seed {a.seed} memory={a.memory} feedback={a.feedback} k={self.k}", + "Instruction: " + self.instruction(), + "Left: agentview Right: wrist camera. Header: current robot command and the report of " + "the previous one."], 3) + self._start_attempt(reset=True) + # la: agent-facing positions are in the robot-base frame (LIBERO-Agent: "Coordinates are expressed in the + # robot-base frame and measured in metres"); the LIBERO base is axis-aligned with the world, so a translation + self.base_off = np.zeros(3) + if a.style == "la": + sim = self.task.env.sim + bid = sim.model.body_name2id("robot0_base") + assert np.allclose(sim.data.body_xmat[bid].reshape(3, 3), np.eye(3), atol=1e-6), "robot base is rotated" + self.base_off = np.array(sim.data.body_xpos[bid], float).copy() + self._write_sandbox() + self.log(dict(ev="session_start", task=a.task, seed=a.seed, k=self.k, k_shown=self.k_shown, protocol=self.protocol, + memory=a.memory, feedback=a.feedback, instruction=a.instruction, perception=a.perception, + inst={k: v for k, v in self.inst.items() if not k.startswith("_")}, arm=self.arm, + arm_overrides=self.arm_overrides, reveal=self.reveal_text, dossier=getattr(a, "dossier", "") or "")) + + # ------------------------------------------------------------------ helpers + def log(self, d): + d["t"] = time.time() + self.events.write(json.dumps(d, default=_json_default) + "\n") + self.events.flush() + + def instruction(self): + hook = getattr(self.task, "agent_instruction", None) + if hook is not None: + text = hook(self.inst, self.a.instruction) + elif self.a.instruction == "indirect" and getattr(self.task, "instruction_indirect", ""): + text = self.task.instruction_indirect + else: + text = self.task.instruction + return text + (" " + self.reveal_text if getattr(self, "reveal_text", "") else "") + + def feedback_text(self, out): + import inspect + fn = self.task.feedback + if "indirect" in inspect.signature(fn).parameters: + fb = fn(self.inst, out, self.a.feedback, indirect=self.a.instruction == "indirect") + else: + fb = fn(self.inst, out, self.a.feedback) + return strip_axes(fb) if self.a.style in ("v2", "la") else fb + + def _start_attempt(self, reset): + self.n_actions = 0 + if reset: + self.task.reset_instance(self.inst) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.a.image_res, cams=("agentview", "wrist")) + self.step = 0 + self.sim0 = self.task.sk.n_steps # v2: simulated-time budget is counted per attempt + + def _save_obs(self, tag): + """Same bytes as the GPT harness sends (JPEG q90). Under memory=none the file names carry no + attempt number, so a fresh agent cannot tell it is a retry; --hide-k names attempt 1 the same way.""" + from PIL import Image + paths = [] + for ref in self.ex.observe(label=tag): + name = (f"s{self.step:03d}_{ref.camera}.jpg" if self.a.memory == "none" or (self.k_shown < self.k and self.attempt == 1) + else f"a{self.attempt}_s{self.step:03d}_{ref.camera}.jpg") + Image.fromarray(ref.array).save(os.path.join(self.obs_dir, name), quality=90) + shutil.copy(os.path.join(self.obs_dir, name), os.path.join(self.log_dir, "images", f"a{self.attempt}_{name}")) + paths.append(f"obs/{name}") + if self.a.style == "la": + self.last_files = self._write_la_files(f"a{self.attempt}_s{self.step:03d}") + return paths + + def readme(self): + if self.a.style == "la": + return self.readme_la() + if self.a.style == "v2": + return self.readme_v2() + sp = self.pb.system_prompt() + sp = sp.replace("You act only by calling the provided tools, exactly one tool call per turn. Every action tool " + "returns an execution report; after each action you also receive new camera images and the " + "robot's proprioceptive state.", + "You act only through the `./robot` command in this directory (one robot command at a time). " + "Every action command prints an execution report and the paths of new camera images taken " + "after the action; look at them with your file-reading tool.") + sp = sp.replace("Finish by calling done(reason)", "Finish by running `./robot done reason=\"...\"`") + sp = sp.replace("Each attempt ends when you call done; you will then see a summary of the attempt (key images, the " + "actions you executed and outcome feedback).", + "Each attempt ends when you run `./robot done`; that command prints the outcome feedback (if any) " + "and the images of the reset scene for the next attempt.") + sp = sp.replace("Each attempt ends when you call done; you will then see a summary of the attempt (key images, the " + "actions you executed).", + "Each attempt ends when you run `./robot done`; that command prints the images of the reset " + "scene for the next attempt.") + sp = sp.replace("before your first tool call", "before your first robot command") + tools = "\n".join([ + " ./robot help this text", + " ./robot status task, current images and proprioception", + " ./robot observe take new images (agentview + wrist) + proprioception", + " ./robot move_to x=.. y=.. z=.. yaw=.. [speed=..] yaw in degrees; speed m/s (omit = fastest)", + " ./robot open_gripper | ./robot close_gripper", + " ./robot pixel_to_world camera=agentview|wrist u=.. v=.. (pixel -> 3-D point via depth)", + " ./robot done reason=\"...\" end the attempt / segment", + ] if self.a.perception == "depth" else [ + " ./robot help this text", + " ./robot status task, current images and proprioception", + " ./robot observe take new images (agentview + wrist) + proprioception", + " ./robot move_to x=.. y=.. z=.. yaw=.. [speed=..] yaw in degrees; speed m/s (omit = fastest)", + " ./robot open_gripper | ./robot close_gripper", + " ./robot done reason=\"...\" end the attempt / segment", + ]) + return ("# Robot task\n\n" + sp + "\n\n## Commands\n" + tools + + "\n\nArguments are key=value; numbers are plain (e.g. x=0.12). Quote strings with spaces.\n" + "Images are written to obs/ inside this directory. After every action, look at the new images " + "before deciding on the next command.\n" + f"Each attempt allows at most {self.a.max_steps} robot commands (help/status not counted); after that " + "the attempt ends automatically.\n\n## TASK\n" + self.instruction() + "\n") + + def _write_sandbox(self): + os.makedirs(self.sandbox, exist_ok=True) + if self.a.style == "la": + with open(os.path.join(self.log_dir, "agent_iface.json"), "w") as f: + json.dump(dict(token=self.token, port=self.a.port, workspace=self.sandbox, agent_iface=self.a.agent_iface, + max_tool_calls=self.a.max_tool_calls, perception=self.a.perception), f) + with open(os.path.join(self.sandbox, "README.md"), "w") as f: + f.write(self.readme()) + if getattr(self.a, "dossier", ""): + shutil.copytree(self.a.dossier, os.path.join(self.sandbox, "history")) + if self.a.agent_iface == "cli": # coding-agent harness (Claude Code): ./robot + ./shell in the workspace + for name, body in (("robot", CLI_TEMPLATE.replace("__PORT__", str(self.a.port)).replace("__TOKEN__", self.token)), + ("shell", SHELL_TEMPLATE)): + with open(os.path.join(self.sandbox, name), "w") as f: + f.write(body) + os.chmod(os.path.join(self.sandbox, name), 0o755) + return + cli = os.path.join(self.sandbox, "robot") + with open(cli, "w") as f: + f.write(CLI_TEMPLATE.replace("__PORT__", str(self.a.port)).replace("__TOKEN__", self.token)) + os.chmod(cli, 0o755) + with open(os.path.join(self.sandbox, "README.md"), "w") as f: + f.write(self.readme()) + + def status(self): + if self.a.memory == "none": + return dict(task=self.instruction(), finished=self.finished) + st = dict(task=self.instruction(), protocol=self.protocol, attempt=self.attempt, max_attempts=self.k, + finished=self.finished) + if self.waiting_new_agent: + st["note"] = "The previous agent finished its attempt. A new attempt is ready; the scene has been reset." + return st + + # ------------------------------------------------------------------ dispatch + def handle(self, cmd, args): + if self.a.style in ("v2", "la"): + return self.handle_v2(cmd, args) + if cmd == "help": + return dict(text=self.readme()) + if cmd == "status": + st = self.status() + st["images"] = self._save_obs("status") + st.update(self.ex.proprio()) + self.waiting_new_agent = False + return st + if self.finished: + return dict(ok=False, error="The episode is over. Stop now.") + if self.waiting_new_agent: + return dict(ok=False, error="This attempt has ended. Stop now.") + if cmd in ("observe", "pixel_to_world", "move_to", "open_gripper", "close_gripper", "push"): + self.n_actions += 1 + if self.n_actions > self.a.max_steps: + rep = self._done("step budget exhausted (automatic)") + rep["note"] = f"The step budget of {self.a.max_steps} commands for this attempt was used up." + return rep + if cmd == "observe": + self.step += 1 + rep = dict(ok=True, images=self._save_obs("observe")) + rep.update(self.ex.proprio()) + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep)) + return rep + if cmd == "done": + return self._done(args.get("reason", "")) + allowed = tuple(t for t in ACTION_TOOLS if t != "push" or self.a.allow_push) + if self.a.perception == "depth": + allowed += ("pixel_to_world",) + if cmd not in allowed: + return dict(ok=False, error=f"unknown command {cmd!r}; run ./robot help") + self.step += 1 + if self.video is not None: + argtxt = " ".join(f"{k}={v}" for k, v in args.items()) + self.video.lines[0] = f"attempt {self.attempt}/{self.k} command #{self.n_actions}: {cmd} {argtxt}" + res = self.ex.call(cmd, args) + rep = dict(res.report) + if self.video is not None: + self.video.lines[1] = f" -> {_short(rep)}" + if cmd in ("close_gripper", "open_gripper"): + self.video.hold(1.2) + if res.ok and cmd in ACTION_TOOLS: + rep["images"] = self._save_obs(cmd) + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep, + wall_s=res.wall_s, sim_steps=res.sim_steps)) + return rep + + def _done(self, reason): + out = self.task.outcome(self.inst) + succ = bool(out["success"]) + fb = self.feedback_text(out) + self.history.append(dict(attempt=self.attempt, success=succ, feedback=fb, reason=reason)) + self.log(dict(ev="done", attempt=self.attempt, step=self.step, reason=reason, success=succ, feedback=fb, + outcome={k: v for k, v in out.items() if k != "feedback"})) + last = self.attempt >= self.k or succ or bool(out.get("terminal")) + if self.video is not None: + self.video.lines = [f"attempt {self.attempt}/{self.k}: done", f" reason: {reason}", ""] + self.video.hold(1.0) + self.video.card([f"Attempt {self.attempt}: {'SUCCESS' if succ else 'FAILED'}", + f"Commands used in this attempt: {self.n_actions}", "Agent's reason: " + str(reason)[:300], + "Feedback: " + (fb if self.a.memory != "none" and self.a.feedback != "F0" else "(not shown)")], + 3.5, (20, 50, 20) if succ else (60, 20, 20)) + if last: + self.video.close() + else: + self.video.lines = ["", "", ""] + if self.a.memory == "none": + # independent attempts: no feedback to the agent; orchestrator starts a fresh agent + if last: + self.finished = True + else: + self.attempt += 1 + self._start_attempt(reset=self.protocol == "cross") + self.waiting_new_agent = True + return dict(ok=True, ended=True, message="Attempt recorded. Stop now and report what you did.") + rep = dict(ok=True, ended=True) + if self.a.feedback != "F0": + rep["feedback"] = fb + if last and (succ or self.a.feedback != "F0"): + self.finished = True + rep["message"] = "The episode is over. Stop now and report." + return rep + if self.attempt >= self.k or out.get("terminal"): + self.finished = True + rep["message"] = ("The failure cannot be undone, so the episode is over. Stop now and report." + if out.get("terminal") else "No attempts left. The episode is over. Stop now and report.") + return rep + self.attempt += 1 + reveal = "" + if self.k_shown < self.k: # --hide-k: first failure, announce the extra attempts now + self.k_shown = self.k + reveal = f"You get more attempts than README.md says: up to {self.k} in total. " + if self.protocol == "cross": + self._start_attempt(reset=True) + rep["message"] = reveal + (f"Attempt {self.attempt} of {self.k} starts now. The scene has been reset to exactly the " + f"same initial state.") + else: + self._start_attempt(reset=False) + rep["message"] = reveal + (f"Continue from the current state (segment {self.attempt}; you may call done at most " + f"{self.k} times in total).") + self.step += 1 + rep["images"] = self._save_obs("attempt_start") + rep.update(self._la_files()) + if self.a.style in ("v2", "la"): + rep.update(self._state_v2()) + else: + rep.update(self.ex.proprio()) + return rep + + +V2_DROP = ("holding", "touched", "events", "sim_time_s", "tool", "reached", "yaw_used_deg", "target_clipped_to") + + +class _V2: + """Interface v2 (2026-10-07, aligned with LIBERO-Agent / RoboDojo-L3 at the user's request): + - priors: only the task instruction, the attempt rules, the budgets and the command definitions (no axes, + table height, camera orientation or robot geometry); + - observations: two RGB images published as files after every command + end-effector state (position, + yaw, gripper width) + how far the arm stopped from the commanded target + budget left; no + held/touched flags and no per-step task events; + - action: move_eef = absolute target (omitted coordinates keep their value; gripper after the motion; + optional speed); unreachable targets are rejected and the arm does not move; + - an attempt ends with `finish` (alias `done`) or when a budget runs out; the environment judges it.""" + + +def _readme_v2(self): + sec = self.sim_budget() + proto = (f"You have up to {self.k_shown} attempts at this task. Before every attempt the scene is reset to exactly the " + f"same initial state." if self.protocol == "cross" else + f"Everything happens in one continuous scene. You may end an attempt up to {self.k_shown} times; after a " + f"failed attempt you continue from the current state.") + return "\n".join([ + "# Robot task", "", + "You control a robot arm with a two-finger gripper in a physics simulation, only through the `./robot` " + "command in this directory (one command at a time).", "", + "## Task", self.instruction(), "", + "## Attempts", proto + " An attempt ends when you run `./robot finish reason=\"...\"` or when its budget " + "is used up. " + _fb_sentence(self.a.feedback) + " The episode ends at the first success or after the last " + "attempt.", "", + "## Budget (per attempt)", + f"- at most {self.a.max_steps} robot commands (status and help are free);", + f"- at most {sec:.0f} s of simulated robot motion.", + "Every reply shows what is left.", "", + "## Observations", + "Every command writes two new camera images into obs/ and prints their paths: 'agentview' (a fixed camera " + "looking at the table) and 'wrist' (a camera on the gripper). It also reports the end-effector state: " + "eef_pos = [x, y, z] of the gripper's grasp point in metres, eef_yaw_deg = rotation of the gripper about " + "the vertical axis in degrees, gripper_width_m = opening of the fingers in metres, and after a motion how " + "far the gripper stopped from your target.", "", + "## Commands", + " ./robot status task, attempt, budget, current state and images", + " ./robot observe new images and state without moving", + " ./robot move_eef [x=..] [y=..] [z=..] [yaw=..] [gripper=open|close] [speed=..]", + " move the grasp point to an absolute target in the same frame as eef_pos (metres; yaw in degrees);", + " omitted coordinates keep their current value; the gripper command is executed after the motion;", + " speed in m/s (omit = fastest); a target the arm cannot reach is rejected and the arm does not move.", + " ./robot finish reason=\"...\" end the current attempt", + "", + "Arguments are key=value; numbers are plain (e.g. x=0.12). Quote strings with spaces.", ""]) + + +def _sim_budget(self): + return 3.0 * self.a.max_steps # seconds of simulated motion per attempt + + +def _budget_left(self): + used = (self.task.sk.n_steps - self.sim0) * 0.05 + return dict(commands=max(self.a.max_steps - self.n_actions, 0), sim_seconds=round(max(self.sim_budget() - used, 0.0), 1)) + + +def _state_v2(self): + p = self.ex.proprio() + pos = p["eef_pos"] + if self.a.style == "la": + pos = [round(float(v), 4) for v in np.asarray(pos, float) - self.base_off] + st = dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"]) + if self.a.style == "la": # read-only joint angles, as LIBERO-Agent (all levels) and RoboDojo give them + st["joint_pos_rad"] = [round(float(v), 4) for v in self._believed_joints()] + st["budget_left"] = self._budget_left() + return st + + +def _clean_v2(rep): + return {k: v for k, v in rep.items() if not k.startswith(V2_DROP)} + + +def _handle_v2(self, cmd, args): + if cmd == "help": + return dict(text=self.readme()) + if cmd == "status": + st = dict(task=self.instruction(), attempt=self.attempt, max_attempts=self.k_shown, finished=self.finished) + st["images"] = self._save_obs("status") + st.update(self._la_files()) + st.update(self._state_v2()) + return st + if self.finished: + return dict(ok=False, error="The episode is over. Stop now.") + if cmd in ("finish", "done"): + return self._done(args.get("reason", "")) + if cmd not in ("observe", "move_eef"): + return dict(ok=False, error=f"unknown command {cmd!r}; run ./robot help") + self.n_actions += 1 + if self.n_actions > self.a.max_steps: + rep = self._done("command budget used up (automatic)") + rep["note"] = f"The budget of {self.a.max_steps} commands for this attempt was used up." + return rep + self.step += 1 + if cmd == "observe": + rep = dict(ok=True, images=self._save_obs("observe")) + rep.update(self._la_files()) + rep.update(self._state_v2()) + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep)) + return rep + # ---------------- move_eef + p = self.ex.proprio() + unknown = set(args) - {"x", "y", "z", "yaw", "gripper", "speed"} + if unknown: + rep = dict(ok=False, error=f"unknown argument(s) {sorted(unknown)}; use x, y, z, yaw, gripper, speed") + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep)) + return rep + off = self.base_off # zero except la (robot-base frame) + try: + cur = np.asarray(p["eef_pos"], float) - off + tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")] + yaw = float(args.get("yaw", p["eef_yaw_deg"])) + speed = None if args.get("speed") in (None, "") else float(args["speed"]) + except (TypeError, ValueError): + rep = dict(ok=False, error="x, y, z, yaw and speed must be numbers") + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep)) + return rep + grip = args.get("gripper") + if grip not in (None, "open", "close"): + rep = dict(ok=False, error="gripper must be open or close") + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep)) + return rep + moving = any(k in args for k in ("x", "y", "z", "yaw")) + tgt_w = np.asarray(tgt) + off # simulator (world) frame + if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)): + rep = dict(ok=False, error="target rejected: the arm cannot reach it; the arm did not move") + rep.update(self._state_v2()) + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep)) + return rep + if self.video is not None: + argtxt = " ".join(f"{k}={v}" for k, v in args.items()) + self.video.lines[0] = f"attempt {self.attempt}/{self.k} command #{self.n_actions}: {cmd} {argtxt}" + left = self._budget_left()["sim_seconds"] + raw = {} + if moving: + mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw) + if speed is not None: + mv["speed"] = speed + res = self.ex.call("move_to", mv) + raw.update(res.report) + if grip is not None: + res = self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}) + raw.update(res.report) + rep = dict(ok=bool(raw.get("ok", True))) + if raw.get("error"): + rep["error"] = raw["error"] + rep.update(self._state_v2()) + if moving: + err = np.asarray(tgt) - np.asarray(rep["eef_pos"]) + dyaw = (yaw - rep["eef_yaw_deg"] + 90.0) % 180.0 - 90.0 + rep["stopped_from_target"] = dict(cm=round(100 * float(np.linalg.norm(err)), 1), deg=round(abs(dyaw), 1)) + if self.video is not None: + self.video.lines[1] = f" -> eef={rep['eef_pos']} width={rep['gripper_width_m']} {rep.get('stopped_from_target', '')}" + if grip is not None: + self.video.hold(1.2) + rep["images"] = self._save_obs(cmd) + rep.update(self._la_files()) + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep, raw=raw)) + self._snap_regressions() + if rep["budget_left"]["sim_seconds"] <= 0 and left > 0: + fin = self._done("motion budget used up (automatic)") + fin["note"] = f"The {self.sim_budget():.0f} s motion budget for this attempt was used up." + rep["attempt_ended"] = fin + return rep + + +LOSS_EVENTS = ("lost", "toppled", "tipped", "load_fell", "load_displaced") + + +def _snap_regressions(self): + """Save the simulator state right after a command during which the task monitor registered a loss of earlier + progress (lost / toppled / tipped / load_fell ...), for the "self-inflicted vs handed-over" experiment (docs/14 ยง6). + Server-side only: snapshots go to /snapshots/, never to the agent's workspace.""" + try: # bookkeeping only: it must never change what the agent gets back + self._snap_regressions_inner() + except Exception: + self.log(dict(ev="snapshot_error", error=traceback.format_exc()[-1500:])) + + +def _snap_regressions_inner(self): + mon = getattr(self.task, "mon", None) + evs = mon.get("events") if isinstance(mon, dict) else None + if not isinstance(evs, list): + return + new = evs[self.n_mon_events:] + self.n_mon_events = len(evs) + loss = [e for e in new if isinstance(e, dict) and str(e.get("ev", e.get("event", ""))) in LOSS_EVENTS] + if not loss: + return + import copy + d = os.path.join(self.log_dir, "snapshots") + os.makedirs(d, exist_ok=True) + name = f"a{self.attempt}_s{self.step:03d}" + try: + flat = np.asarray(self.task.env.sim.get_state().flatten(), float) + except Exception: # keep the run going even if a simulator binding lacks get_state + flat = np.concatenate([self.task.env.sim.data.qpos, self.task.env.sim.data.qvel]).astype(float) + np.save(os.path.join(d, name + "_sim.npy"), flat) + meta = dict(attempt=self.attempt, step=self.step, n_actions=self.n_actions, sim_steps=int(self.task.sk.n_steps - self.sim0), + loss_events=loss, mon=copy.deepcopy(mon)) + def _dflt(o): # task monitors keep sets (ever / lost / lid_hits ...) + return sorted(o, key=str) if isinstance(o, (set, frozenset)) else _json_default(o) + with open(os.path.join(d, name + "_meta.json"), "w") as f: + json.dump(meta, f, default=_dflt) + self.log(dict(ev="regression_snapshot", attempt=self.attempt, step=self.step, file=f"snapshots/{name}", n_loss=len(loss))) + + +def _la_files(self): + """la: paths of the non-image observation files written with the last images (empty for other styles).""" + return dict(self.last_files) if self.a.style == "la" and getattr(self, "last_files", None) else {} + + +def _believed_pose(self): + """4x4 pose of the grasp point as the ROBOT believes it (the frame of eef_pos / move_eef): the true pose shifted by + the task's hidden calibration errors (Skills.bias, and YawSkills.yaw_bias about the vertical axis). A real robot + computes its wrist-camera pose from its own (miscalibrated) kinematics, so the wrist calibration uses this pose.""" + sk = self.task.sk + beta = float(getattr(sk, "yaw_bias", 0.0)) + c, s_ = np.cos(-beta), np.sin(-beta) + Rz = np.array([[c, -s_, 0.0], [s_, c, 0.0], [0.0, 0.0, 1.0]]) + T_true = np.eye(4) + T_true[:3, :3], T_true[:3, 3] = sk.eef_mat(), sk.eef_pos() + T_b = np.eye(4) + T_b[:3, :3], T_b[:3, 3] = Rz @ sk.eef_mat(), sk.eef_pos() - np.asarray(sk.bias, float) + return T_b, T_true + + +def _believed_joints(self, iters=30): + """The 7 arm joint angles as the robot's encoders report them. For tasks with a hidden calibration error (L1) these + are the angles consistent with the robot's own belief: standard forward kinematics of them gives exactly the + reported (believed) grasp pose, as on a real arm whose encoder offsets are miscalibrated; true joint angles would + hand the hidden error to anyone who runs the public Franka kinematics. Without a calibration error they are the true + angles. Solved by damped least squares on a scratch copy of the simulator state (2-3 iterations).""" + import mujoco + env, sk = self.task.env, self.task.sk + rob = env.robots[0] + idx, dof, site = np.array(rob._ref_joint_pos_indexes), np.array(rob._ref_joint_vel_indexes), rob.eef_site_id + m, d0 = env.sim.model._model, env.sim.data._data + T_b, _ = self._believed_pose() + 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)): + return d0.qpos[idx].copy() + d = mujoco.MjData(m) + d.qpos[:] = d0.qpos + jp, jr = np.zeros((3, m.nv)), np.zeros((3, m.nv)) + for _ in range(iters): + mujoco.mj_kinematics(m, d) + mujoco.mj_comPos(m, d) + ep = T_b[:3, 3] - d.site_xpos[site] + Re = T_b[:3, :3] @ d.site_xmat[site].reshape(3, 3).T + er = 0.5 * np.array([Re[2, 1] - Re[1, 2], Re[0, 2] - Re[2, 0], Re[1, 0] - Re[0, 1]]) + if np.linalg.norm(ep) < 1e-7 and np.linalg.norm(er) < 1e-7: + break + mujoco.mj_jacSite(m, d, jp, jr, site) + J = np.vstack([jp[:, dof], jr[:, dof]]) + d.qpos[idx] += J.T @ np.linalg.solve(J @ J.T + 1e-6 * np.eye(6), np.concatenate([ep, er])) + return d.qpos[idx].copy() + + +def _write_la_files(self, prefix): + """la observation files besides the two JPEGs: _state.json always; with --perception rgbd also metric + depth for both cameras (__depth.npy, float32 metres along the optical axis, same upright pixels as + the JPEG) and _camera.json (K and cam_to_world in the eef_pos frame, OpenCV camera axes). + The fixed agentview camera is calibrated in the true frame; the wrist camera pose is computed from the robot's + believed gripper pose (so neither file reveals the hidden calibration error of the L1 tasks).""" + out = {} + st = self._state_v2() + st = dict(eef_pos=st["eef_pos"], eef_yaw_deg=st["eef_yaw_deg"], gripper_width_m=st["gripper_width_m"], + joint_pos_rad=st["joint_pos_rad"], attempt=self.attempt, step=self.step) + with open(os.path.join(self.obs_dir, f"{prefix}_state.json"), "w") as f: + json.dump(st, f, default=_json_default) + out["state_file"] = f"obs/{prefix}_state.json" + if self.a.perception == "rgbd": + res = self.a.image_res + cams, depth_files = {}, [] + T_b, T_true = self._believed_pose() + for cam in ("agentview", "wrist"): + d = C.render_depth(self.task.env, cam, res).astype(np.float32) + np.save(os.path.join(self.obs_dir, f"{prefix}_{cam}_depth.npy"), d) + depth_files.append(f"obs/{prefix}_{cam}_depth.npy") + E = C.cam_to_world(self.task.env, cam) + if cam == "wrist": + E = T_b @ np.linalg.inv(T_true) @ E + E = E.copy() + E[:3, 3] -= self.base_off # robot-base frame + cams[cam] = dict(K=np.round(C.intrinsics(self.task.env, cam, res), 6).tolist(), + cam_to_base=np.round(E, 6).tolist(), width=res, height=res) + with open(os.path.join(self.obs_dir, f"{prefix}_camera.json"), "w") as f: + json.dump(cams, f) + out["depth_files"] = depth_files + out["camera_file"] = f"obs/{prefix}_camera.json" + return out + + + +def _fb_sentence(level): + """README sentence for the feedback level. F1 (default since 2026-10-08): success / failure only, like + LIBERO-Agent's finish_episode outcome; F2 (measured error, e.g. "2.5 cm past the centre") is privileged + simulator information that neither LIBERO-Agent nor RoboDojo gives, kept only as an ablation.""" + return {"F0": "The environment then checks the result.", + "F1": "The environment then checks the result and tells you only whether the attempt succeeded.", + "F2": "The environment then checks the result and tells you whether the attempt succeeded and, if not, " + "what went wrong."}[level] + +def _readme_la(self): + """LIBERO-Agent-style instructions: the agent works in an episode workspace (observations are files, it can run + programs on them); the robot itself is driven only through the harness's `robot` tool.""" + sec = self.sim_budget() + rgbd = self.a.perception == "rgbd" + cli = self.a.agent_iface == "cli" + pre = "./robot " if cli else "" + proto = (f"You have up to {self.k_shown} attempts at this task. Before every attempt the scene is reset to exactly the " + f"same initial state." if self.protocol == "cross" else + f"Everything happens in one continuous scene. You may end an attempt up to {self.k_shown} times; after a " + f"failed attempt you continue from the current state.") + files = [ + "- obs/a_s_agentview.jpg and obs/a_s_wrist.jpg: 512x512 RGB images from " + "'agentview' (a fixed camera looking at the table) and 'wrist' (a camera on the gripper);", + "- obs/a_s_state.json: the end-effector state: eef_pos = [x, y, z] of the gripper's grasp " + "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 " + "of the fingers in metres, joint_pos_rad = the 7 arm joint angles (radians, base to wrist; read-only).", + ] + if rgbd: + files += [ + "- obs/a_s_agentview_depth.npy and obs/a_s_wrist_depth.npy: metric depth " + "(numpy float32 array, 512x512, metres along each camera's optical axis), pixel-aligned with the images " + "(row 0 = top of the image);", + "- obs/a_s_camera.json: for each camera, K (3x3 intrinsics of the 512x512 image) and " + "cam_to_base (4x4 pose of the camera in the robot-base frame; camera axes: x right, y down, z forward).", + ] + return "\n".join([ + "# Robot task", "", + "You control a Franka Emika Panda robot arm (7 joints) with a two-finger parallel gripper in a physics " + "simulation.", "", + "## Task", self.instruction(), "", + "## Attempts", proto + f" An attempt ends when you run the robot command `{pre}finish reason=\"...\"` or when its " + "budget is used up. " + _fb_sentence(self.a.feedback) + " The episode ends at the first success or after the " + "last attempt.", "", + *(["## Earlier attempt", + "Before this episode, an earlier attempt at this task, starting from a scene that looked the same as yours, " + "failed. Its record is in history/: history/README.md lists every robot command of that attempt with the " + "robot's reply and its closing remark, and history/obs/ holds the camera images it produced.", ""] + if getattr(self.a, "dossier", "") else []), + "## Budget (per attempt)", + f"- at most {self.a.max_steps} robot commands (status and help are free);", + f"- at most {sec:.0f} s of simulated robot motion;", + *([] if cli else [f"- at most {self.a.max_tool_calls} tool calls in total (robot, shell and view_image together)."]), + "Every robot reply shows the robot budgets that are left.", "", + "## Coordinates", + "Coordinates are expressed in the robot-base frame and measured in metres; angles are in degrees.", "", + "## Workspace and observations", + "This directory is your workspace for the whole episode. Every robot command writes its observation into " + "obs/ and prints the paths of the new files:", + *files, + "Robot replies also include the end-effector state and, after a motion, how far the gripper stopped from your " + "target. " + ("You can look at any image with your file-reading tool, run shell commands and programs in this " + "workspace with `./shell ''` (python3 with numpy, scipy, Pillow and OpenCV; no network; " + "programs cannot control the robot), and keep your own files and notes in this directory; they " + "persist across attempts." if cli else + "You can look at any image with view_image, run shell commands and programs here (python3 with " + "numpy, scipy, Pillow and OpenCV; no network; programs cannot control the robot), and keep your " + "own files and notes in this directory; they persist across attempts."), "", + "## Robot commands " + ("(run from this directory as `./robot `, one command at a time)" if cli + else "(argument of the `robot` tool)"), + f" {pre}status task, attempt, budget, current state and observation files", + f" {pre}observe new observation without moving", + f" {pre}move_eef [x=..] [y=..] [z=..] [yaw=..] [gripper=open|close] [speed=..]", + " move the grasp point to an absolute target (robot-base frame, metres; yaw in degrees);", + " omitted coordinates keep their current value; the gripper command is executed after the motion;", + " speed in m/s (omit = fastest); a target the arm cannot reach is rejected and the arm does not move.", + f" {pre}finish reason=\"...\" end the current attempt", + "", + "Arguments are key=value; numbers are plain (e.g. x=0.12). Quote strings with spaces.", ""]) + + +for _n, _f in (("_believed_joints", _believed_joints), ("readme_la", _readme_la), ("_la_files", _la_files), ("_believed_pose", _believed_pose), + ("_write_la_files", _write_la_files), ("readme_v2", _readme_v2), ("sim_budget", _sim_budget), ("_budget_left", _budget_left), + ("_state_v2", _state_v2), ("handle_v2", _handle_v2), ("_snap_regressions", _snap_regressions), + ("_snap_regressions_inner", _snap_regressions_inner)): + setattr(RobotSession, _n, _f) +RobotSession._clean_v2 = staticmethod(_clean_v2) + + +def serve(a): + sess = RobotSession(a) + + class H(BaseHTTPRequestHandler): + def log_message(self, *x): + pass + + def do_POST(self): + t_recv = time.time() + cmd = "" + try: + body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + cmd = body.get("cmd", "") + if self.headers.get("X-Token") != sess.token: + rep = dict(ok=False, error="unauthorised") + else: + rep = sess.handle(cmd, body.get("args", {}) or {}) + except Exception as e: # never leak a traceback (it contains benchmark paths) to the agent + sess.log(dict(ev="error", error=traceback.format_exc())) + rep = dict(ok=False, error=f"internal error: {type(e).__name__}") + data = json.dumps(rep, default=_json_default, indent=None).encode() + if "text" in rep: + data = rep["text"].encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(data) + t_send = time.time() + # think time = gap between the previous reply and this request (model inference + its own tool overhead) + sess.log(dict(ev="http", cmd=cmd, attempt=sess.attempt, t_recv=t_recv, t_send=t_send, + server_s=t_send - t_recv, think_s=(t_recv - sess.last_send) if sess.last_send else None)) + sess.last_send = t_send + + def _term(*_): + if sess.video is not None: + sess.video.close() + os._exit(0) + + signal.signal(signal.SIGTERM, _term) + srv = HTTPServer(("127.0.0.1", a.port), H) + print(f"robot server ready on 127.0.0.1:{a.port} sandbox={sess.sandbox} log={sess.log_dir}", flush=True) + with open(os.path.join(sess.log_dir, "READY"), "w") as f: + f.write(str(os.getpid())) + srv.serve_forever() + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--task", required=True) + ap.add_argument("--seed", type=int, required=True) + ap.add_argument("--k", type=int, default=None) + ap.add_argument("--memory", default="full", choices=["full", "none"]) + ap.add_argument("--hide-k", action="store_true", + help="memory=full: README/status say 1 attempt (same as an independent k=1 run); the remaining " + "attempts are announced only after a failed attempt") + ap.add_argument("--feedback", default="F1", choices=["F0", "F1", "F2"]) + ap.add_argument("--instruction", default="direct", choices=["direct", "indirect"]) + ap.add_argument("--image-res", type=int, default=512) + ap.add_argument("--port", type=int, default=8765) + ap.add_argument("--sandbox", required=True) + ap.add_argument("--log-dir", required=True) + ap.add_argument("--max-steps", type=int, default=None, + help="robot commands per attempt (default: the task's agent_max_steps, else 40)") + ap.add_argument("--allow-push", action="store_true", help="expose the composite push primitive (off by default)") + ap.add_argument("--perception", default="depth", choices=["depth", "rgb", "rgbd"], + help="rgb: images only (no pixel_to_world / depth); depth: adds the depth back-projection tool " + "(v1); rgbd (la): also writes metric depth and camera calibration files") + ap.add_argument("--style", default="v1", choices=["v1", "v2", "la"], + help="v2: LIBERO-Agent / RoboDojo-aligned interface (see _V2); la: v2 + LIBERO-Agent workspace " + "(observation files, programs in the workspace, robot only through the harness tool)") + ap.add_argument("--nominal", action="store_true", + help="control: remove the hidden calibration error of an L1 task (bias / yaw_bias = 0)") + ap.add_argument("--agent-iface", default="tools", choices=["tools", "cli"], + help="la: tools = harness tools (robot / shell / view_images, our GPT driver); cli = ./robot and " + "./shell in the workspace for a coding agent such as Claude Code") + ap.add_argument("--max-tool-calls", type=int, default=100, + help="la: tool calls per attempt (robot + shell + view_image), enforced by the harness") + ap.add_argument("--arm", default="none", choices=["none", "h0", "hplus", "twin"], + help="full5 controlled arms (lffbench/arm_specs/.py): h0 = hidden variable at its ordinary value; " + "hplus = hidden variable stated in the instruction; twin = mismatched-history source instance") + ap.add_argument("--dossier", default="", + help="la: copy this directory into the workspace as history/ (record of an earlier failed attempt, " + "made by scripts/make_dossier.py) and say so in README.md") + ap.add_argument("--video", default="", help="record agentview|wrist mp4 to this path") + ap.add_argument("--video-every", type=int, default=3, help="one frame every N control steps (20 Hz)") + ap.add_argument("--video-fps", type=int, default=20) + serve(ap.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/runlog.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/runlog.py new file mode 100644 index 0000000000000000000000000000000000000000..bf014446cedd7fef48c65010cd38ff23b6e3b9b0 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/runlog.py @@ -0,0 +1,62 @@ +"""Run directory: config.json, events.jsonl (one JSON object per line), images/, summary.json.""" +import json +import os +import time + +import numpy as np + +from .images import encode_jpeg, resize + + +def _default(o): + if isinstance(o, np.ndarray): + return o.tolist() + if isinstance(o, (np.floating,)): + return float(o) + if isinstance(o, (np.integer,)): + return int(o) + if isinstance(o, (np.bool_,)): + return bool(o) + if hasattr(o, "__dataclass_fields__"): + return {k: getattr(o, k) for k in o.__dataclass_fields__} + return str(o) + + +def dumps(obj): + return json.dumps(obj, default=_default) + + +class RunLogger: + def __init__(self, run_dir, save_images=True, jpeg_quality=90): + self.run_dir = run_dir + self.save_images = save_images + self.jpeg_quality = jpeg_quality + os.makedirs(os.path.join(run_dir, "images"), exist_ok=True) + self.f = open(os.path.join(run_dir, "events.jsonl"), "a") + self.t0 = time.time() + + def event(self, type, **fields): + rec = dict(type=type, t=round(time.time() - self.t0, 3), **fields) + self.f.write(dumps(rec) + "\n") + self.f.flush() + return rec + + def write_json(self, name, obj): + with open(os.path.join(self.run_dir, name), "w") as f: + json.dump(obj, f, indent=1, default=_default) + + def save_image(self, ref, rel, res=None): + """Encode once (this exact JPEG is what the model receives) and save it under images/.""" + if res is not None: + ref.array = resize(ref.array, res) + ref.jpeg = encode_jpeg(ref.array, self.jpeg_quality) + if self.save_images: + path = os.path.join(self.run_dir, "images", rel) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "wb") as f: + f.write(ref.jpeg) + ref.path = os.path.relpath(path, self.run_dir) + return ref + + def close(self): + self.f.close() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/tools.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/tools.py new file mode 100644 index 0000000000000000000000000000000000000000..51e4a2a2feaa238548d752308aca541e6ad416fb --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/tools.py @@ -0,0 +1,392 @@ +"""Agent-facing tool interface on top of `Skills`. + +Every action tool calls the task's `Skills` object, so the task's hidden calibration `bias` keeps +acting on every commanded position. Proprioception is reported in the robot's own (possibly +miscalibrated) frame: reported eef = true eef - bias, i.e. the robot "believes" it reached the +commanded point; only the cameras show the truth. Camera-derived quantities (pixel_to_world) and +the privileged `locate` tool are in the true world frame. + +Tool schemas are plain JSON schema (OpenAI strict-mode compatible: every property listed in +`required`, optional ones nullable, no additional properties). +""" +import json +import math +import time +from dataclasses import dataclass, field + +import numpy as np + +from .. import envs +from . import camera as C +from .images import ImageRef + +TABLE_Z = envs.TABLE_Z +# Workspace limits for commanded grasp-point positions (world frame, metres). Targets outside are +# clipped and the report says so. +WS_LO = np.array([-0.55, -0.45, TABLE_Z + 0.005]) +WS_HI = np.array([0.35, 0.45, TABLE_Z + 0.50]) +SPEED_RANGE = (0.02, 1.0) +PUSH_DIST_RANGE = (0.0, 0.40) +RUNUP_RANGE = (0.02, 0.30) + +ACTION_TOOLS = ("move_to", "open_gripper", "close_gripper", "push") + + +def _num(desc): + return {"type": "number", "description": desc} + + +def _opt_num(desc): + return {"type": ["number", "null"], "description": desc} + + +def _fn(name, desc, props=None): + props = props or {} + return dict(name=name, description=desc, + parameters={"type": "object", "properties": props, "required": list(props), + "additionalProperties": False}) + + +def tool_specs(privileged_locate=False, object_names=None, image_res=512): + """Backend-neutral tool list: [{name, description, parameters}].""" + specs = [ + _fn("move_to", + "Move the gripper's grasp point (midway between the fingertips) in a straight line to the world " + "position (x, y, z) with the gripper pointing straight down and rotated to `yaw`. The gripper " + "opening is not changed. Returns whether the target was reached, the end-effector position, gripper " + "width, whether an object is held and whether the arm touched an object during the motion.", + {"x": _num("target x, metres (world frame; +x away from the robot)"), + "y": _num("target y, metres (world frame; +y to the robot's left)"), + "z": _num(f"target z, metres (table top is z = {TABLE_Z:.2f})"), + "yaw": _num("gripper rotation about the vertical axis in DEGREES; 0 = fingers close along the world " + "y axis, 90 = fingers close along the world x axis. Taken modulo 180 (the two-finger " + "gripper is symmetric): the controller uses the equivalent angle closest to the current " + "yaw within +-113 deg; the report gives the yaw actually used"), + "speed": _opt_num("straight-line speed in m/s (0.02-1.0); null = as fast as the controller allows " + "(about 0.6 m/s)")}), + _fn("open_gripper", "Open the gripper fully (the arm holds its position)."), + _fn("close_gripper", "Close the gripper (the arm holds its position). Closing on an object grasps it."), + _fn("push", + "Straight-line push with the closed gripper. The gripper closes, moves above the point `runup` metres " + "behind (x, y) (opposite to the push direction), descends to height z, sweeps along (dir_x, dir_y) " + "through (x, y) and stops `distance` metres past (x, y), moving at `speed` m/s, then lifts 12 cm. The " + "gripper is rotated automatically to a fixed orientation relative to the push direction.", + {"x": _num("x of the point where the push should start acting (e.g. the near face of the object), m"), + "y": _num("y of that point, m"), + "dir_x": _num("x component of the push direction (normalised internally)"), + "dir_y": _num("y component of the push direction"), + "distance": _num("how far past (x, y) the gripper travels, metres (0-0.40)"), + "speed": _num("sweep speed, m/s (0.02-1.0; the controller saturates near 0.6)"), + "z": _opt_num(f"height of the grasp point during the sweep, m; null = {TABLE_Z + 0.02:.2f} " + "(2 cm above the table)"), + "runup": _opt_num("distance behind (x, y) where the sweep starts, m (0.02-0.30); null = 0.06. A longer " + "run-up lets the gripper reach the commanded speed before contact.")}), + _fn("get_observation", + "Return the current camera images (agentview and wrist) and the robot's proprioceptive state."), + _fn("pixel_to_world", + f"Back-project an image pixel to a 3-D world point using the camera's depth map. (u, v) are pixel " + f"coordinates in the {image_res}x{image_res} image exactly as you received it: u = column from the " + f"left edge, v = row from the top edge. Returns the world point (x, y, z) of the surface seen at that " + f"pixel and its height above the table.", + {"camera": {"type": "string", "enum": ["agentview", "wrist"], "description": "which image"}, + "u": _num("column (0 = left edge)"), "v": _num("row (0 = top edge)")}), + _fn("done", + "Finish the current attempt. Call this when you believe the task is complete (or you want to stop). " + "Give a short reason: what you did and whether you think it worked.", + {"reason": {"type": "string", "description": "short explanation"}}), + ] + if privileged_locate: + names = list(object_names or []) + prop = {"type": "string", "description": "object name"} + if names: + prop["enum"] = names + specs.insert(-1, _fn("locate", + "PRIVILEGED (ablation): return the true world position of an object's origin and its " + "axis-aligned bounding box.", {"object_name": prop})) + return specs + + +@dataclass +class ToolResult: + name: str + args: dict + ok: bool + report: dict + images: list = field(default_factory=list) + ended: bool = False + wall_s: float = 0.0 + sim_steps: int = 0 + + def text(self): + return json.dumps(self.report, separators=(", ", ": "), default=_json_default) + + +def _json_default(o): + if isinstance(o, (np.floating,)): + return float(o) + if isinstance(o, (np.integer,)): + return int(o) + if isinstance(o, np.ndarray): + return o.tolist() + if isinstance(o, (np.bool_,)): + return bool(o) + raise TypeError(type(o)) + + +def _r(v, nd=4): + return [round(float(x), nd) for x in v] + + +class ContactTracker: + """Collects the objects the robot touches. Contacts are checked after every MuJoCo substep (a control + step is 25 substeps; a fast push touches the object for less than one control step, so checking only at + control-step boundaries misses it -- measured). Implemented by wrapping `env.sim.step` once per env; the + wrapper only reads contacts and dispatches to the currently active tracker.""" + + def __init__(self, env): + self.env = env + m = env.sim.model + self.is_robot = np.zeros(m.ngeom, bool) + self.is_robot[envs.robot_geom_ids(env)] = True + self.names = [] + self.obj_of = np.full(m.ngeom, -1, int) + for name in list(env.objects_dict) + list(getattr(env, "fixtures_dict", {}) or {}): + try: + ids = envs.obj_geom_ids(env, name) + except Exception: # fixtures without contact geoms + continue + self.obj_of[ids] = len(self.names) + self.names.append(name) + self.touched = set() + sim = env.sim + if not getattr(sim, "_lff_step_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lff_tracker", None) + if t is not None: + t.check() + sim.step = step + sim._lff_step_wrapped = True + sim._lff_tracker = self + + def reset(self): + self.touched = set() + + def check(self): + d = self.env.sim.data + n = d.ncon + if not n: + return + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + hit = np.concatenate([self.obj_of[g2[self.is_robot[g1]]], self.obj_of[g1[self.is_robot[g2]]]]) + for i in set(hit[hit >= 0].tolist()): + self.touched.add(self.names[i]) + + +def parse_args(raw): + if raw is None: + return {} + if isinstance(raw, dict): + return dict(raw) + raw = raw.strip() + return json.loads(raw) if raw else {} + + +class ToolExecutor: + """Executes agent tool calls on a task whose instance has just been reset (task.sk is live).""" + + def __init__(self, task, inst, image_res=512, cams=("agentview", "wrist"), privileged_locate=False, + grasp_report="bool", jpeg_quality=90, image_sink=None): + self.task = task + self.inst = inst + self.env = task.env + self.sk = task.sk # keep our own reference: the scripted backend may swap task.sk for a proxy + self.image_res = int(image_res) + self.cams = tuple(cams) + self.privileged_locate = privileged_locate + self.grasp_report = grasp_report # "bool" | "name" | "none" + self.jpeg_quality = jpeg_quality + self.image_sink = image_sink # callable(ImageRef) -> path (saves the image) + self.objects = list(self.env.objects_dict) + self.tracker = ContactTracker(self.env) # task recorders / hooks on Skills are left untouched + self._depth_cache = {} + self.n_calls = 0 + + # ------------------------------------------------------------------ state + def eef_yaw_deg(self): + R = self.sk.eef_mat() @ self.sk.R0.T + return math.degrees(math.atan2(R[1, 0], R[0, 0])) + + def held(self): + names = [o for o in self.objects if self.sk.holding(o)] + return names + + def _holding_field(self, names): + if self.grasp_report == "name": + return names[0] if names else None + if self.grasp_report == "none": + return None + return bool(names) + + def proprio(self): + believed = self.sk.eef_pos() - self.sk.bias + p = dict(eef_pos=_r(believed), eef_yaw_deg=round(self.eef_yaw_deg(), 1), + gripper="closed" if self.sk.grip > 0 else "open", + gripper_width_m=round(self.sk.gripper_width(), 4)) + if self.grasp_report != "none": + p["holding_object"] = self._holding_field(self.held()) + return p + + def render(self, cam, res=None): + res = res or self.image_res + return envs.render(self.env, C.mj_cam(cam), res) + + def observe(self, label=""): + imgs = [] + for cam in self.cams: + ref = ImageRef(camera=cam, array=self.render(cam), label=f"{label} {cam}".strip()) + if self.image_sink is not None: + self.image_sink(ref) + imgs.append(ref) + self._depth_cache = {} + return imgs + + # ------------------------------------------------------------------ dispatch + def call(self, name, raw_args): + t0 = time.time() + n0 = self.sk.n_steps + self.n_calls += 1 + try: + args = parse_args(raw_args) + except Exception as e: + return ToolResult(name, {"_raw": str(raw_args)}, False, dict(ok=False, error=f"arguments are not valid JSON: {e}"), + wall_s=time.time() - t0) + fn = getattr(self, f"_t_{name}", None) + if fn is None or (name == "locate" and not self.privileged_locate): + return ToolResult(name, args, False, dict(ok=False, error=f"unknown tool {name!r}"), wall_s=time.time() - t0) + try: + res = fn(**args) + except TypeError as e: + res = ToolResult(name, args, False, dict(ok=False, error=f"bad arguments: {e}")) + except ValueError as e: + res = ToolResult(name, args, False, dict(ok=False, error=str(e))) + res.args = args + res.wall_s = time.time() - t0 + res.sim_steps = self.sk.n_steps - n0 + if res.sim_steps: + self._depth_cache = {} + hook = getattr(self.task, "on_agent_tool", None) + if hook is not None: + hook(self.inst, name, args, res.report) + drain = getattr(self.task, "drain_events", None) # task-side events (e.g. L6: an item slipped) + if drain is not None: + ev = drain() + if ev: + res.report["events"] = list(ev) + return res + + # ------------------------------------------------------------------ helpers + def _clip_xyz(self, xyz): + xyz = np.asarray(xyz, float) + if not np.all(np.isfinite(xyz)): + raise ValueError("non-finite coordinates") + c = np.clip(xyz, WS_LO, WS_HI) + return c, (None if np.allclose(c, xyz) else _r(c)) + + @staticmethod + def _clip(v, lo_hi, what): + v = float(v) + if not math.isfinite(v): + raise ValueError(f"{what} must be finite") + return float(np.clip(v, *lo_hi)) + + def _action_report(self, name, extra=None): + names = self.held() + rep = dict(ok=True, tool=name) + if extra: + rep.update(extra) + rep.update(self.proprio()) + if self.grasp_report == "name": + rep["touched_objects"] = sorted(self.tracker.touched) + elif self.grasp_report == "bool": + rep["touched_object"] = bool(self.tracker.touched) + rep["sim_time_s"] = round(self.sk.n_steps * 0.05, 2) + return rep + + # ------------------------------------------------------------------ tools + def _t_move_to(self, x, y, z, yaw, speed=None): + tgt, clipped = self._clip_xyz([x, y, z]) + spd = None if speed is None else self._clip(speed, SPEED_RANGE, "speed") + self.tracker.reset() + rep = self.sk.move_to(tgt, yaw=math.radians(float(yaw)), speed=spd) # Skills wraps yaw mod pi + extra = dict(reached=bool(rep["reached"]), yaw_used_deg=round(math.degrees(self.sk.yaw), 1)) + if clipped: + extra["target_clipped_to"] = clipped + return ToolResult("move_to", {}, True, self._action_report("move_to", extra)) + + def _t_open_gripper(self): + self.tracker.reset() + self.sk.set_gripper(False) + return ToolResult("open_gripper", {}, True, self._action_report("open_gripper")) + + def _t_close_gripper(self): + self.tracker.reset() + self.sk.set_gripper(True) + return ToolResult("close_gripper", {}, True, self._action_report("close_gripper")) + + def _t_push(self, x, y, dir_x, dir_y, distance, speed, z=None, runup=None): + d = np.array([float(dir_x), float(dir_y)]) + if not np.all(np.isfinite(d)) or np.linalg.norm(d) < 1e-6: + raise ValueError("push direction must be a non-zero vector") + start, clipped = self._clip_xyz([x, y, TABLE_Z + 0.02 if z is None else z]) + dist = self._clip(distance, PUSH_DIST_RANGE, "distance") + spd = self._clip(speed, SPEED_RANGE, "speed") + pre = 0.06 if runup is None else self._clip(runup, RUNUP_RANGE, "runup") + self.tracker.reset() + rep = self.sk.push(start[:2], d, dist, spd, z=float(start[2]), pre=pre) + extra = dict(sweep_reached=bool(rep["reached"])) + if clipped: + extra["start_clipped_to"] = clipped + return ToolResult("push", {}, True, self._action_report("push", extra)) + + def _t_get_observation(self): + imgs = self.observe(label="requested") + return ToolResult("get_observation", {}, True, dict(ok=True, images=[i.camera for i in imgs], **self.proprio()), + images=imgs) + + def _t_pixel_to_world(self, camera, u, v): + cam = str(camera) + if cam not in C.CAMERAS: + raise ValueError(f"camera must be one of {sorted(C.CAMERAS)}") + if cam not in self._depth_cache: + self._depth_cache[cam] = C.render_depth(self.env, cam, self.image_res) + r = C.pixel_to_world(self.env, cam, float(u), float(v), self.image_res, depth=self._depth_cache[cam]) + rep = dict(ok=True, camera=cam, u=float(u), v=float(v), world_xyz=_r(r["xyz"]), + height_above_table_m=round(float(r["xyz"][2] - TABLE_Z), 4), depth_m=round(r["depth"], 4)) + if not r["valid"]: + rep["warning"] = "pixel shows the far background; the point is unreliable" + return ToolResult("pixel_to_world", {}, True, rep) + + def _t_locate(self, object_name): + if object_name not in self.env.objects_dict: + raise ValueError(f"unknown object {object_name!r}; known: {self.objects}") + lo, hi = self._aabb(object_name) + p = envs.obj_pos(self.env, object_name) + return ToolResult("locate", {}, True, dict(ok=True, object=object_name, position=_r(p), bbox_min=_r(lo), + bbox_max=_r(hi))) + + def _aabb(self, name): + m, d = self.env.sim.model, self.env.sim.data + lo, hi = np.full(3, np.inf), np.full(3, -np.inf) + for g in envs.obj_geom_ids(self.env, name): + R = d.geom_xmat[g].reshape(3, 3) + c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3] + h = np.abs(R) @ m.geom_aabb[g, 3:] + lo, hi = np.minimum(lo, c - h), np.maximum(hi, c + h) + return lo, hi + + def _t_done(self, reason=""): + return ToolResult("done", {}, True, dict(ok=True, ended=True), ended=True) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/agent_compare.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/agent_compare.py new file mode 100644 index 0000000000000000000000000000000000000000..4f53b5126adc0eadae0498f1de5e8a3fd60f0cdb --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/agent_compare.py @@ -0,0 +1,40 @@ +"""ฮ”ICL between two agent run directories on the same seeds. + + python scripts/agent_compare.py --with runs/agent// --iid runs/agent// + +ฮ”ICL = succ@k(with history) - pass@k_iid(independent retries), paired by instance seed, with a paired +bootstrap 95% interval. Also prints the analytic i.i.d. reference 1-(1-p1)^k from the 'with' run. +""" +import argparse +import json +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from lffbench.agent.metrics import paired_delta # noqa: E402 + + +def load(d): + with open(os.path.join(d, "summary.json")) as f: + return json.load(f) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--with", dest="with_", required=True) + ap.add_argument("--iid", required=True) + ap.add_argument("--k", type=int, default=None) + a = ap.parse_args() + w, i = load(a.with_), load(a.iid) + k = a.k or min(w["k"], i["k"]) + res = paired_delta(w["runs"], i["runs"], k) + res["k"] = k + res["with"] = dict(memory=w["memory"], feedback=w["feedback"], attempt1=w["aggregate"]["attempt1_success"], + pass_at_k_iid_analytic=w["aggregate"]["pass_at_k_iid_analytic"]) + res["iid"] = dict(memory=i["memory"], feedback=i["feedback"]) + print(json.dumps(res, indent=1)) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/agent_cost.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/agent_cost.py new file mode 100644 index 0000000000000000000000000000000000000000..03a49297e0ef82a9c466f2eb36c0de1b3769630f --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/agent_cost.py @@ -0,0 +1,77 @@ +"""Project GPT-6 cost / latency of a protocol from a run directory. + +Works on (a) a real OpenAI run (uses the logged usage and latencies) or (b) a dry run of another backend made +with --dry-run-payload (uses the logged request sizes of every call). For (b) all numbers are ESTIMATES: + input tokens per call = text_chars / 4 + n_images * 256 (512 px images; image accounting is an assumption) + cached tokens per call = input tokens of the previous call in the same attempt (append-only prefix) -- + the first call of an attempt is counted as uncached (conservative) + output tokens per call = --out-tokens (reasoning + visible; unknown for GPT-6 Astra, default 1500) + latency per call = --latency (seconds; RoboICL measured ~30-50 s per GPT-6 Astra call at 50-90K input + tokens and high/xhigh effort -- treat as an upper-range planning number) +The number of model calls of a scripted run is a LOWER bound for an LLM agent (no perception / checking calls). + + python scripts/agent_cost.py runs/agent/l5_slide_to_target/ --out-tokens 1500 --latency 20 --calls-scale 2 +""" +import argparse +import json +import os +import sys +from collections import defaultdict + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from lffbench.agent.cost import PRICES, call_cost # noqa: E402 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("run_dir") + ap.add_argument("--model", default="gpt-6-astra") + ap.add_argument("--out-tokens", type=float, default=1500) + ap.add_argument("--latency", type=float, default=20.0) + ap.add_argument("--calls-scale", type=float, default=1.0, help="multiply the call count (LLM vs scripted)") + a = ap.parse_args() + ev = [json.loads(l) for l in open(os.path.join(a.run_dir, "events.jsonl"))] + calls = [e for e in ev if e["type"] == "llm_call"] + runs = {e["seed"] for e in ev if e["type"] == "run_start"} + real = [c for c in calls if c.get("usage")] + if real and not any("dry_run_request" in c for c in calls): + cost = sum(call_cost(c["usage"], a.model) or 0 for c in real) + lat = [c["latency_s"] for c in real] + u = defaultdict(int) + for c in real: + for kk, v in c["usage"].items(): + u[kk] += v + out = dict(mode="measured", runs=len(runs), calls=len(real), calls_per_run=len(real) / max(len(runs), 1), + usage=dict(u), cost_usd=cost, cost_per_run=cost / max(len(runs), 1), + latency_mean_s=sum(lat) / len(lat), api_time_per_run_s=sum(lat) / max(len(runs), 1)) + else: + prev = {} + tot_in = tot_cached = 0 + cost1 = 0.0 # priced per call (the long-context surcharge applies per request) + for c in calls: + d = c.get("dry_run_request") + if not d: + continue + key = (c["seed"], c["attempt"]) + tin = d["est_input_tokens"] + cached = min(prev.get(key, 0), tin) + prev[key] = tin + tot_in += tin + tot_cached += cached + cost1 += call_cost(dict(input_tokens=tin, cached_tokens=cached, output_tokens=a.out_tokens), a.model) + n = len(calls) * a.calls_scale + scale = a.calls_scale + usage = dict(input_tokens=tot_in * scale, cached_tokens=tot_cached * scale, output_tokens=n * a.out_tokens) + cost = cost1 * scale + out = dict(mode="estimate (dry run)", runs=len(runs), calls=n, calls_per_run=n / max(len(runs), 1), + input_tokens_per_call=tot_in / max(len(calls), 1), cached_fraction=tot_cached / max(tot_in, 1), + usage=usage, cost_usd=cost, cost_per_run=cost / max(len(runs), 1), + api_time_per_run_s=n * a.latency / max(len(runs), 1), prices=PRICES.get(a.model), + assumptions=dict(out_tokens_per_call=a.out_tokens, latency_s_per_call=a.latency, + calls_scale=a.calls_scale, image_tokens_512px=256)) + print(json.dumps(out, indent=1, default=str)) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/api_batch.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/api_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..cf6ec32fa574b1125a4c6f8acbcc5ca7f3cd9683 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/api_batch.py @@ -0,0 +1,704 @@ +"""Batch of runs with a concurrency limit: the runner for the paper's main table (reference driver scripts/api_player.py) +and, with --harness, for native agent harnesses (side table, docs/15). + + start python scripts/api_batch.py start --batch m1_opus --provider anthropic --model claude-opus-5-5 --effort high \ + --tasks l1_height_bias:3000,3001 lh_bridge:3000 --k 3 --concurrency 6 --video + -> writes runs/api//manifest.json (one entry per run, status "pending") and starts a background + runner that keeps at most --concurrency runs going (robot server + api_player each) and stops each + server when its player exits. + status python scripts/api_batch.py status --batch m1_opus + table python scripts/api_batch.py table --batch m1_opus [--batch ...] (same table as claude_batch + tokens) + stop python scripts/api_batch.py stop --batch m1_opus (runner, players, servers; runs -> "stopped") + retry python scripts/api_batch.py retry --batch m1_opus [--runs ...] (default: every failed / stopped / timeout run; + old logs stay, listed under "superseded"; starts the runner again) + followup python scripts/api_batch.py followup --batch m1_opus (switch a batch started before 2026-10-19 to + --memfree followup: plans the memory-free retries due for its finished history runs; then `retry` starts them) + contract python scripts/api_batch.py contract --batch b1 [--batch b2 ...] (contract_sha256 per instance and condition; + flags instances whose hash differs between batches: those cells must not share a table) + pause touch runs/api//PAUSE: the runner launches no new run while the file exists; the runs going on finish + and are recorded as usual (rm the file to go on). Used by quota watchers to stay below a usage window. + +--harness (default ours): which agent harness drives each run, through scripts/harness_run.py (lffbench/harnesses): + ours scripts/api_player.py, unchanged (--provider as before) + claude_code Claude Code CLI --bare, only our MCP tools, one-time config dirs (arm B; provider anthropic) + claude_code_full Claude Code CLI without --bare (full system prompt), otherwise the same (arm B'); + --claude-auth oauth (default): the subscription token of `claude setup-token` (LFF_CLAUDE_OAUTH_FILE), + apikey: ANTHROPIC_API_KEY (claude_code takes only apikey) + codex Codex CLI exec --ephemeral, empty CODEX_HOME, only our MCP tools reachable (arm F; provider openai); + --codex-auth chatgpt (default): the ChatGPT subscription login, apikey: OPENAI_API_KEY + dsh DeepSeek Harness headless, only our MCP tools, one-time dirs (lffbench/harnesses/dsh.py; provider + deepseek, key LFF_DEEPSEEK_API_KEY / DEEPSEEK_API_KEY) +Native harnesses are refused at launch (status "refused") unless their preset prompt / tool list matches the pin +written by tests/harness_selfcheck (--allow-unpinned to launch anyway; the preflight still runs). Every run gets +harness.json, contract.json, trajectory.jsonl and harness_audit.json in its log dir. + +Conditions (same as claude_batch): harness = memory full, k attempts in one agent; noharness = independent single-attempt +agents (memory none, k=1). History runs use --hide-k (README and status say 1 attempt, byte-identical to an independent +run; more attempts are announced only after a failure; --no-hide-k to show k). +--memfree, how the memory-free retries (pass@k without history) are run: + followup (default, 2026-10-19): one history run per instance. Its attempt 1 is also the first memory-free attempt, + since under --hide-k it sees exactly what a fresh agent sees. Only if attempt 1 fails does the runner add a + fresh single-attempt agent (noharness rep 1, "chain" = the history run's id); if that one fails too, the + next (rep 2), up to k-1 of them; the first success ends the chain. An instance solved on attempt 1 thus + costs one attempt in all. Not for tasks whose scene persists between attempts (task protocol "within"): + a fresh agent would start from the initial scene, the history run's attempt 2 from the failed one, so the + two conditions would differ; these tasks are reported without memory-free retries (user 2026-10-20). + upfront the 2026-10-11 protocol: --indep-reps independent runs per instance (default k, all of them run), all + before the history runs (--conds order; --no-barrier to mix the phases). + none history runs only. +--seeds-per-task N keeps the first N seeds of each task:seeds (e.g. 1 = one instance per task). +API keys come from LFF_ENV_FILE (default /.env, KEY=value lines) or the environment. +""" +import argparse +import json +import os +import re +import shlex +import signal +import subprocess +import sys +import threading +import time + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "scripts")) +import claude_batch # noqa: E402 + +RUNS = os.path.join(ROOT, "runs", "api") +ENV_FILE = os.environ.get("LFF_ENV_FILE") or os.path.join(ROOT, ".env") +ACTIVE = ("starting", "running") +RETRYABLE = ("failed", "stopped", "timeout", "server_failed") +sys.path.insert(0, ROOT) +from lffbench.harnesses import NAMES, ROBOT_HARNESSES, PROVIDER as HARNESS_PROVIDER + + + +def bdir(batch): + return os.path.join(RUNS, batch) + + +def mpath(batch): + return os.path.join(bdir(batch), "manifest.json") + + +def load(batch): + with open(mpath(batch)) as f: + return json.load(f) + + +def save(batch, m): + os.makedirs(bdir(batch), exist_ok=True) + tmp = mpath(batch) + ".tmp" + with open(tmp, "w") as f: + json.dump(m, f, indent=1) + os.replace(tmp, mpath(batch)) + + +def alive(pid): + try: + os.kill(int(pid), 0) + return True + except (ProcessLookupError, PermissionError, TypeError, ValueError): + return False + + +def runner_alive(batch): + p = os.path.join(bdir(batch), "runner.pid") + return os.path.exists(p) and alive(open(p).read().strip()) + + +def launch_runner(batch): + log = open(os.path.join(bdir(batch), "runner.log"), "a") + p = subprocess.Popen([sys.executable, os.path.abspath(__file__), "_runner", "--batch", batch], cwd=ROOT, + start_new_session=True, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT) + with open(os.path.join(bdir(batch), "runner.pid"), "w") as f: + f.write(str(p.pid)) + return p.pid + + +def next_id(m): + return f"{max((int(r['id']) for r in m['runs']), default=-1) + 1:04d}" + + +# ------------------------------------------------------------------------------------------------- memory-free chains +# --memfree followup: per instance, history run (cond harness, followup=True) -> noharness rep 1 -> ... -> rep k-1, +# each link planned only after the previous attempts all failed. Attempt 1 of the history run is the chain's first +# attempt (--hide-k makes it identical to a fresh agent's), so the memory-free pass@k of an instance is: attempt 1 of +# the history run, or any of its chain runs, succeeded. +PLAN_KEYS = ("task", "seed", "provider", "agent_harness", "api_base_url", "max_budget_usd", "allow_unpinned", "jail", + "codex_auth", "claude_auth", "codex_catalog", "codex_provider", + "rpent_sessions", "rpent_attempts_per_session", "rpent_max_turns", + "model", "effort", "perception", "video", "style", "feedback", "phase", "nominal", "red_team") + + +def attempt_results(log): + """[success of attempt 1, of attempt 2, ...] from the robot server log ([] if there is none).""" + p = os.path.join(log or "", "events.jsonl") + if not os.path.exists(p): + return [] + res = {} + for line in open(p): + e = json.loads(line) + if e.get("ev") == "done": + res[e["attempt"]] = bool(e["success"]) + return [res[i] for i in sorted(res)] + + +def episode_protocol(log): + """The task's attempt protocol ("cross": reset between attempts, "within": the scene persists) from the robot + server log's session_start line; None if unknown.""" + p = os.path.join(log or "", "events.jsonl") + if os.path.exists(p): + for line in open(p): + e = json.loads(line) + if e.get("ev") == "session_start": + return e.get("protocol") + return None + + +def plan_followup(m, r): + """Run r has finished: append the next memory-free retry of its instance if one is due; returns it or None.""" + if r["status"] != "done": + return None + if r["cond"] == "harness" and r.get("followup"): + if episode_protocol(r.get("log")) == "within": # no like-for-like fresh agent (module docstring) + return None + root, nxt, res = r, 1, attempt_results(r.get("log"))[:1] + elif r.get("chain"): + root = next((x for x in m["runs"] if x["id"] == r["chain"]), None) + nxt, res = r["rep"] + 1, attempt_results(r.get("log")) + else: + return None + if root is None or not res or any(res) or nxt >= root["k"]: + return None + if any(x.get("chain") == root["id"] and x["rep"] == nxt for x in m["runs"]): + return None + new = {k: root.get(k) for k in PLAN_KEYS} + new.update(id=next_id(m), cond="noharness", rep=nxt, k=1, mem="none", hide_k=False, chain=root["id"], + status="pending") + m["runs"].append(new) + return new + + +def memfree_chain(m, root): + """Table rows for the memory-free retries of root's instance: its attempt 1 (rep 0, only_attempt=1) and the chain + runs after it. [] while the chain has not ended (a success, or k attempts).""" + first = attempt_results(root.get("log"))[:1] + if not first: + return [] + rows = [dict(root, cond="noharness", rep=0, k=1, only_attempt=1)] + if first[0]: + return rows + chain = {x["rep"]: x for x in m["runs"] if x.get("chain") == root["id"] and x["status"] == "done" and x.get("log")} + for rep in range(1, root["k"]): + if rep not in chain: + return [] + rows.append(dict(chain[rep])) + if any(attempt_results(chain[rep]["log"])): + break + return rows + + +# ------------------------------------------------------------------------------------------------------------ start +def cmd_start(a): + a.codex_auth = a.codex_auth or ("apikey" if a.harness in ROBOT_HARNESSES else "chatgpt") + if a.harness == "rpent_codex" and a.codex_auth != "apikey": + sys.exit("Historical RPent adapter supports apikey only") + if runner_alive(a.batch): + sys.exit(f"batch {a.batch}: runner already running; stop it first or use another batch name") + m = load(a.batch) if os.path.exists(mpath(a.batch)) else dict(batch=a.batch, runs=[], superseded=[]) + m.update(concurrency=a.concurrency, barrier=not a.no_barrier, port0=a.port0, run_timeout_s=a.run_timeout) + reps = a.k if a.indep_reps is None else a.indep_reps + if a.harness != "ours": + need = HARNESS_PROVIDER[a.harness] + if a.provider and a.provider != need: + sys.exit(f"--harness {a.harness} drives {need} models only (got --provider {a.provider})") + a.provider = need + elif not a.provider: + sys.exit("--provider is required with --harness ours") + claude_auth = None + if a.harness.startswith("claude_code"): + claude_auth = a.claude_auth or ("apikey" if a.harness == "claude_code" else "oauth") + if claude_auth == "oauth" and a.harness == "claude_code": + sys.exit("--harness claude_code (--bare) takes only an API key; use claude_code_full for a subscription") + elif a.claude_auth: + sys.exit("--claude-auth is for --harness claude_code / claude_code_full") + if a.jail and a.harness == "ours": + sys.exit("--jail is for native harnesses (the reference driver runs our own code)") + if a.red_team and a.harness == "ours": + sys.exit("--red-team is for native harnesses (lffbench/harnesses/redteam.py)") + if a.memfree == "upfront": + conds = [c.strip() for c in (a.conds or "noharness,harness").split(",") if c.strip()] + else: + if a.conds and a.conds.replace(" ", "") != "harness": + sys.exit(f"--conds is for --memfree upfront (--memfree {a.memfree} plans history runs only)") + if a.memfree == "followup" and a.no_hide_k: + sys.exit("--memfree followup shares attempt 1 of the history run with the memory-free retries: needs --hide-k") + conds = ["harness"] + dossiers = json.load(open(a.dossiers)) if a.dossiers else None + if dossiers is not None: # task:seed -> record dir (scripts/make_dossier.py); every planned instance needs one + miss = [f"{spec.split(':')[0]}:{sd}" for spec in a.tasks for sd in spec.split(":")[1].split(",")[:a.seeds_per_task] + if f"{spec.split(':')[0]}:{sd}" not in dossiers] + if miss: + sys.exit(f"--dossiers has no record for {miss}") + 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)] + if bad: + sys.exit(f"--dossiers: not a record dir (or path with spaces): {bad}") + n0 = len(m["runs"]) + for cond in conds: # the order of --conds is the order of the phases + for spec in a.tasks: + task, seeds = spec.split(":") + for seed in seeds.split(",")[:a.seeds_per_task]: + plan = [("harness", "full", a.k, 0)] if cond == "harness" else \ + [("noharness", "none", 1, i) for i in range(reps)] + for c, mem, k, rep in plan: + m["runs"].append(dict(id=next_id(m), task=task, seed=int(seed), provider=a.provider, + agent_harness=a.harness, api_base_url=a.api_base_url, + max_budget_usd=a.max_budget_usd, allow_unpinned=a.allow_unpinned, + jail=a.jail, codex_auth=(("apikey" if a.codex_provider in ("deepseek", "opencode") else a.codex_auth) + if a.harness in ("codex", *ROBOT_HARNESSES) else None), + claude_auth=claude_auth, + codex_catalog=(a.codex_catalog if a.harness in ("codex", *ROBOT_HARNESSES) + else None), + **(dict(rpent_sessions=a.rpent_sessions, + rpent_attempts_per_session=a.rpent_attempts_per_session, + rpent_max_turns=a.rpent_max_turns) + if a.harness == "rpent_codex" else {}), + codex_provider=(a.codex_provider if a.harness == "codex" else None), + model=a.model, effort=a.effort, cond=c, rep=rep, k=k, mem=mem, + hide_k=(c == "harness" and not a.no_hide_k), perception=a.perception, + video=a.video, style="la", feedback=a.feedback, phase=conds.index(cond), + nominal=a.nominal, followup=(c == "harness" and a.memfree == "followup"), + arm=a.arm, red_team=a.red_team, dossier=(os.path.abspath(dossiers[f"{task}:{seed}"]) if dossiers else None), + status="pending")) + save(a.batch, m) + print(f"{len(m['runs']) - n0} runs planned ({', '.join(conds)}, --memfree {a.memfree}); manifest {mpath(a.batch)}") + if a.memfree == "followup": + print("memory-free retries are added while the batch runs, for instances whose attempt 1 failed") + print("runner pid", launch_runner(a.batch)) + + +# ------------------------------------------------------------------------------------------------------------ runner +class Runner: + def __init__(self, batch): + self.batch = batch + self.lock = threading.Lock() + self.m = load(batch) + self.used_ports = set() + self.stop = False + + def update(self, r, **kw): + with self.lock: + r.update(kw) + save(self.batch, self.m) + + def next_run(self): + with self.lock: + runs = self.m["runs"] + pending = [r for r in runs if r["status"] == "pending"] + if not pending: + # a run still going may yet add a memory-free retry (--memfree followup) + if any(r["status"] in ACTIVE and (r.get("followup") or r.get("chain")) for r in runs): + return "wait" + return None + if self.m.get("barrier", True): + phase = min(r["phase"] for r in pending) + if any(r["status"] in ACTIVE and r["phase"] < phase for r in runs): + return "wait" + pending = [r for r in pending if r["phase"] == phase] + if os.path.exists(os.path.join(bdir(self.batch), "PAUSE")): + return "wait" + r = pending[0] + r["status"] = "starting" + save(self.batch, self.m) + return r + + def port(self): + with self.lock: + p = int(self.m.get("port0", 14000)) + while p in self.used_ports or not claude_batch.port_free(p): + p += 1 + self.used_ports.add(p) + return p + + def run_one(self, r): + port = self.port() + model_tag = re.sub(r"[^A-Za-z0-9.-]+", "-", r["model"])[:40] + ah = r.get("agent_harness", "ours") + if ah != "ours": + model_tag += "-" + ah.replace("_", "") + tag = (f"{self.batch}-{model_tag}-{r['cond']}{r['rep'] if r['cond'] == 'noharness' else ''}" + + ("-hidek" if r["hide_k"] else "") + ("-nominal" if r.get("nominal") else "") + + (f"-{r['arm']}" if r.get("arm", "none") != "none" else "") + ("-dossier" if r.get("dossier") else "") + + ("-redteam" if r.get("red_team") else "")) + extra = (" --hide-k" if r["hide_k"] else "") + (" --nominal" if r.get("nominal") else "") + # docs/14 ยง6 arms (robot_server --arm / --dossier); LFF_EXTRA_ARGS is word-split, so no spaces in the path + extra += (f" --arm {r['arm']}" if r.get("arm", "none") != "none" else "") + (f" --dossier {r['dossier']}" if r.get("dossier") else "") + t0 = time.time() + try: + sb, log = claude_batch.start_one(r["task"], r["seed"], r["mem"], r["k"], port, tag, r["perception"], + r["video"], r["style"], extra.strip(), r["feedback"]) + except Exception as e: # server did not come up + self.update(r, status="server_failed", error=str(e)[-500:], port=port) + with self.lock: + self.used_ports.discard(port) + return + self.update(r, status="running", port=port, sandbox=sb, log=log, run=os.path.basename(log), t_start=t0) + opts = "" + if r.get("api_base_url"): + opts += f" --api-base-url {shlex.quote(r['api_base_url'])}" + if r.get("max_budget_usd"): + opts += f" --max-budget-usd {r['max_budget_usd']}" + if r.get("allow_unpinned"): + opts += " --allow-unpinned" + if r.get("jail"): + opts += " --jail" + if r.get("red_team"): + opts += " --red-team" + if r.get("codex_auth"): + opts += f" --codex-auth {r['codex_auth']}" + if r.get("claude_auth"): + opts += f" --claude-auth {r['claude_auth']}" + 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 + opts += f" --codex-catalog {r.get('codex_catalog') or 'native'}" + if r.get("codex_provider") in ("deepseek", "opencode"): + opts += f" --codex-provider {r['codex_provider']}" + if r.get("agent_harness") == "rpent_codex": + opts += (f" --codex-catalog {r.get('codex_catalog') or 'generic'}" + f" --rpent-sessions {r.get('rpent_sessions') or 5}" + f" --rpent-attempts-per-session {r.get('rpent_attempts_per_session', 1)}" + f" --rpent-max-turns {r.get('rpent_max_turns') or 100}") + # every harness (also ours: api_player.py with the same arguments as before, its output still in + # api_player.log) goes through the adapter layer, which adds harness.json / contract.json / trajectory.jsonl + player = (f"cd {ROOT} && source run_env.sh >/dev/null 2>&1 && " + f"{{ [ ! -f {ENV_FILE} ] || {{ set -a && source {ENV_FILE} && set +a; }}; }} && " + f"exec python scripts/harness_run.py --harness {ah} --session {log}/session.json " + f"--provider {r['provider']} --model {shlex.quote(r['model'])} --effort {r['effort']} " + f"--timeout {int(self.m.get('run_timeout_s', 28800))}{opts} > {log}/harness_run.log 2>&1") + p = subprocess.Popen(["bash", "-c", player], start_new_session=True, stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + self.update(r, player_pid=p.pid) + status = None + try: + code = p.wait(timeout=self.m.get("run_timeout_s", 28800)) + except subprocess.TimeoutExpired: + os.killpg(p.pid, signal.SIGTERM) + code, status = p.wait(), "timeout" + self.stop_server(log) + if status is None: + status = "stopped" if self.stop else ("done" if code == 0 else "refused" if code == 2 else "failed") + self.update(r, status=status, exit_code=code, t_end=time.time(), wall_s=round(time.time() - t0, 1)) + with self.lock: + self.used_ports.discard(port) + if plan_followup(self.m, r): + save(self.batch, self.m) + + @staticmethod + def stop_server(log): + pf = os.path.join(log, "server.pid") + if not os.path.exists(pf): + return + pid = int(open(pf).read()) + try: + os.kill(pid, signal.SIGTERM) # the server closes rollout.mp4 first + except ProcessLookupError: + return + for _ in range(120): + if not alive(pid): + return + time.sleep(0.5) + + def worker(self): + while not self.stop: + r = self.next_run() + if r is None: + return + if r == "wait": + time.sleep(5) + continue + try: + self.run_one(r) + except Exception as e: # keep the other workers going + self.update(r, status="failed", error=f"runner: {type(e).__name__}: {e}"[:500]) + + def main(self): + os.environ["LFF_RUNS_DIR"] = bdir(self.batch) # claude_batch.start_one puts the run logs here + for r in self.m["runs"]: # a previous runner died: its half-started runs go back to pending + if r["status"] in ACTIVE: + r["status"] = "pending" + for r in list(self.m["runs"]): # memory-free retries due but not yet planned (runner died, `followup`) + plan_followup(self.m, r) + save(self.batch, self.m) + + def on_term(*_): + self.stop = True + with self.lock: + for r in self.m["runs"]: + if r["status"] == "running" and r.get("player_pid"): + try: + os.killpg(r["player_pid"], signal.SIGTERM) + except ProcessLookupError: + pass + signal.signal(signal.SIGTERM, on_term) + ths = [threading.Thread(target=self.worker, daemon=True) for _ in range(int(self.m.get("concurrency", 4)))] + for t in ths: + t.start() + time.sleep(2) # stagger server start-ups + for t in ths: + t.join() + print(time.strftime("%F %T"), "runner finished", flush=True) + + +def cmd_runner(a): + Runner(a.batch).main() + + +# ------------------------------------------------------------------------------------------------------------ views +def transcript_usage(log): + tot = dict(calls=0, input_tokens=0, cached_tokens=0, output_tokens=0, api_errors=0, end=None) + p = os.path.join(log or "", "transcript.jsonl") + if not os.path.exists(p): # native harness: totals from the unified trajectory + sys.path.insert(0, ROOT) + from lffbench.harnesses.trajectory import usage_summary + u = usage_summary(log) + if u: + tot.update(calls=u.get("calls", 0), input_tokens=u.get("total_prompt_tokens") or 0, + cached_tokens=u.get("total_cached_tokens") or 0, + output_tokens=u.get("total_completion_tokens") or 0, end=u.get("exit_reason"), + cost_usd=u.get("total_cost_usd")) + return tot + for line in open(p): + d = json.loads(line) + if d["ev"] == "assistant": + tot["calls"] += 1 + for k in ("input_tokens", "cached_tokens", "output_tokens"): + tot[k] += (d.get("usage") or {}).get(k, 0) + elif d["ev"] == "api_error": + tot["api_errors"] += 1 + elif d["ev"] in ("end", "abort"): + tot["end"] = d["ev"] if d["ev"] == "end" else "abort: " + d.get("reason", "") + return tot + + +def cmd_status(a): + m = load(a.batch) + counts = {} + for r in m["runs"]: + counts[r["status"]] = counts.get(r["status"], 0) + 1 + att = "" + if r.get("log") and os.path.exists(os.path.join(r["log"], "events.jsonl")): + ev = [json.loads(line) for line in open(os.path.join(r["log"], "events.jsonl"))] + att = "".join("S" if e["success"] else "F" for e in ev if e["ev"] == "done") + u = transcript_usage(r.get("log")) + print(f"{r['id']} {r['status']:13s} {r.get('agent_harness', 'ours'):16s} " + f"{r['cond']:9s}{r['rep'] if r['cond'] == 'noharness' else '':1} " + f"{r['task']:24s} s{r['seed']} {att:4s} calls={u['calls']:3d} api_err={u['api_errors']} " + f"in={u['input_tokens'] / 1e6:.2f}M out={u['output_tokens'] / 1e3:.0f}k {u['end'] or ''}" + + (f" (memory-free attempt {r['rep'] + 1} after {r['chain']})" if r.get("chain") else "")) + print("runner", "alive" if runner_alive(a.batch) else "not running", "|", counts) + + +def cmd_table(a): + def done_runs(b): + m = load(b) + runs = [] + for r in m["runs"]: + if not (r.get("log") and r["status"] == "done") or r.get("chain"): + continue + runs.append(dict(r)) + if r["cond"] == "harness" and r.get("followup"): # its memory-free chain, once finished + runs += memfree_chain(m, r) + for r in runs: # the harness is part of the table's "model" column (claude_batch groups by task, model) + if r.get("agent_harness", "ours") != "ours": + r["model"] = f"{r['model']} @ {r['agent_harness']}" + return dict(m, runs=runs) + claude_batch.load = done_runs # same manifest fields (task, seed, model, cond, rep, k, log): reuse its table + # token totals: every run once (the rep-0 row of a chain is attempt 1 of a history run, already counted) + rows = [r for b in a.batch for r in done_runs(b)["runs"] if not r.get("only_attempt")] + claude_batch.cmd_table(argparse.Namespace(batch=a.batch)) + by = {} + for r in rows: + u = transcript_usage(r["log"]) + t = by.setdefault((r.get("agent_harness", "ours"), r["provider"], r["model"], r["effort"]), [0, 0, 0, 0, 0]) + t[0] += 1 + t[1] += u["calls"] + t[2] += u["input_tokens"] + t[3] += u["cached_tokens"] + t[4] += u["output_tokens"] + print("\n| harness | provider | model | effort | runs done | model calls | input tokens (M) | of which cached (M) | output tokens (M) |") + print("|---|---|---|---|---|---|---|---|---|") + for (h, p, mo, e), t in sorted(by.items()): + print(f"| {h} | {p} | {mo} | {e} | {t[0]} | {t[1]} | {t[2] / 1e6:.1f} | {t[3] / 1e6:.1f} | {t[4] / 1e6:.2f} |") + + +def cmd_contract(a): + """contract_sha256 per (task, seed, cond) and batch; an instance whose hash differs between batches is flagged.""" + import collections + seen = collections.defaultdict(dict) + for b in a.batch: + for r in load(b)["runs"]: + p = os.path.join(r.get("log") or "", "contract.json") + if r.get("log") and os.path.exists(p): + sha = json.load(open(p))["contract_sha256"] + seen[(r["task"], r["seed"], r["cond"])].setdefault(b, set()).add(sha) + bad = 0 + print("| task | seed | cond | " + " | ".join(a.batch) + " | same |") + print("|---|---|---|" + "---|" * len(a.batch) + "---|") + for (task, seed, cond), per in sorted(seen.items()): + shas = set().union(*per.values()) + same = len(shas) == 1 + bad += not same + cells = [",".join(sorted(x[:12] for x in per.get(b, []))) or "-" for b in a.batch] + print(f"| {task} | {seed} | {cond} | " + " | ".join(cells) + f" | {'yes' if same else '**NO**'} |") + print(f"\n{len(seen)} instance/condition rows, {bad} with differing contracts") + + +def cmd_stop(a): + pf = os.path.join(bdir(a.batch), "runner.pid") + if os.path.exists(pf) and alive(open(pf).read().strip()): + os.kill(int(open(pf).read().strip()), signal.SIGTERM) # the runner stops its players and servers + for _ in range(240): + if not runner_alive(a.batch): + break + time.sleep(0.5) + m = load(a.batch) + for r in m["runs"]: # anything left over (runner killed hard) + if r["status"] in ACTIVE: + if r.get("player_pid"): + try: + os.killpg(r["player_pid"], signal.SIGTERM) + except ProcessLookupError: + pass + if r.get("log"): + Runner.stop_server(r["log"]) + r["status"] = "stopped" + save(a.batch, m) + print("stopped") + + +def cmd_retry(a): + if runner_alive(a.batch): + sys.exit("runner still running: stop it first") + m = load(a.batch) + reset = [] + for r in m["runs"]: + 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): + if r.get("log"): + m.setdefault("superseded", []).append(dict(r)) + for k in ("port", "sandbox", "log", "run", "player_pid", "exit_code", "t_start", "t_end", "wall_s", "error"): + r.pop(k, None) + r["status"] = "pending" + reset.append(r) + # memory-free retries planned after a run that is now re-run were based on attempts that no longer count + stale = [x for x in m["runs"] if x.get("chain") and all(x is not y for y in reset) and any( + x["chain"] == y["id"] or (x["chain"] == y.get("chain") and x["rep"] > y["rep"]) for y in reset)] + for x in stale: + m["runs"].remove(x) + if x.get("log"): + m.setdefault("superseded", []).append(dict(x, superseded_because="earlier attempt of its chain re-run")) + save(a.batch, m) + print(len(reset), "runs reset to pending" + (f", {len(stale)} memory-free retries after them dropped" if stale else "") + + "; runner pid", launch_runner(a.batch)) + + +def cmd_followup(a): + """Switch a batch to --memfree followup: mark its --hide-k history runs and plan the memory-free retries due for + those already done. `retry` then starts the runner (and re-runs failed / stopped runs).""" + if runner_alive(a.batch): + sys.exit("runner still running: stop it first") + m = load(a.batch) + marked = left = 0 + for r in m["runs"]: + if r["cond"] == "harness" and not r.get("followup"): + if r.get("hide_k"): + r["followup"] = True + marked += 1 + else: + left += 1 + new = [x for r in list(m["runs"]) for x in [plan_followup(m, r)] if x] + save(a.batch, m) + print(f"{marked} history runs switched to --memfree followup" + + (f" ({left} without --hide-k left out: their attempt 1 is not a fresh agent's)" if left else "") + + f"; {len(new)} memory-free retries planned") + print(f"start the runner with: python scripts/api_batch.py retry --batch {a.batch}") + + +def main(): + ap = argparse.ArgumentParser() + sub = ap.add_subparsers(dest="cmd", required=True) + s = sub.add_parser("start") + s.add_argument("--batch", required=True) + s.add_argument("--harness", default="ours", choices=NAMES, + help="agent harness (docs/15); native harnesses imply the provider; rpent_codex = RPent on Codex " + "(docs/18), OpenAI API key only (LFF_OPENAI_API_KEY)") + s.add_argument("--provider", default=None, choices=["openai", "anthropic", "gemini", "chat"], + help="required for --harness ours") + s.add_argument("--api-base-url", default=None, help="native harnesses: model API endpoint (see harness_run.py)") + s.add_argument("--max-budget-usd", type=float, default=None, help="claude_code*: per-run dollar cap") + s.add_argument("--allow-unpinned", action="store_true", help="native harnesses: launch without a pin") + s.add_argument("--codex-auth", default=None, choices=["chatgpt", "apikey"], + help="Codex authentication: chatgpt defaults for codex; apikey defaults for Robot Harnesses. " + "SenseNova/EmbodiedEvo also support chatgpt; historical RPent is apikey only") + s.add_argument("--claude-auth", default=None, choices=["oauth", "apikey"], + help="claude_code*: subscription token (default for claude_code_full) or ANTHROPIC_API_KEY " + "(claude_code, --bare: apikey only)") + s.add_argument("--codex-provider", default="openai", choices=["openai", "deepseek", "opencode"], + help="codex: model provider; deepseek / opencode (OpenCode Go) imply --codex-auth apikey " + "(see harness_run.py)") + s.add_argument("--codex-catalog", default="generic", choices=["generic", "native"], + help="codex: model configuration, the main table's shared one (default) or Codex's native one " + "(control; see lffbench/harnesses/codex.py)") + s.add_argument("--rpent-sessions", type=int, default=5, help="rpent_codex: planner sessions per episode") + s.add_argument("--rpent-attempts-per-session", type=int, default=1, + help="rpent_codex: attempts one session may use (1 = variant H, default; 0 = no limit)") + s.add_argument("--rpent-max-turns", type=int, default=100, help="rpent_codex: model responses per session") + s.add_argument("--jail", action="store_true", + help="native harnesses: run the CLI in the native-harness jail (docs/15 ยง3.4, lffbench/harnesses/jail.py)") + s.add_argument("--model", required=True) + s.add_argument("--effort", default="high") + s.add_argument("--tasks", nargs="+", required=True, help="task:seed,seed ...") + s.add_argument("--k", type=int, default=3) + s.add_argument("--seeds-per-task", type=int, default=None, help="only the first N seeds of each task:seeds") + s.add_argument("--memfree", default="followup", choices=["followup", "upfront", "none"], + help="memory-free retries: followup (default) = fresh single-attempt agents only after the history " + "run's attempt 1 failed, one at a time, up to k attempts in all, stop at the first success; " + "upfront = --indep-reps independent runs per instance before the history runs; none = no " + "memory-free retries (see the module docstring)") + s.add_argument("--indep-reps", type=int, default=None, help="--memfree upfront: independent runs per instance (default k)") + s.add_argument("--conds", default=None, help="--memfree upfront: conditions in phase order (default noharness,harness)") + s.add_argument("--no-barrier", action="store_true", help="do not wait for one phase to finish before the next") + s.add_argument("--no-hide-k", action="store_true", help="history runs: README / status show all k attempts") + s.add_argument("--concurrency", type=int, default=4) + s.add_argument("--port0", type=int, default=14000) + s.add_argument("--run-timeout", type=int, default=28800, + help="seconds per run before the player is killed (default 8 h: a long-horizon history run can need 300+ model calls)") + s.add_argument("--perception", default="rgb", choices=["rgb", "rgbd"]) + s.add_argument("--video", action="store_true") + s.add_argument("--feedback", default="F1", choices=["F0", "F1", "F2"]) + s.add_argument("--nominal", action="store_true", help="L1 control: hidden calibration error removed") + s.add_argument("--arm", default="none", choices=["none", "h0", "hplus", "twin"], + help="docs/14 ยง6 controlled arm for every run: twin = same layout, other value of the hidden variable") + s.add_argument("--red-team", action="store_true", + help="adversarial acceptance runs (lffbench/harnesses/redteam.py): the agent is told to get a success " + "without doing the task; own contract; read with scripts/redteam_report.py") + s.add_argument("--dossiers", default=None, + help="JSON {\"task:seed\": record dir from scripts/make_dossier.py}: each run gets that record in " + "history/ and a README section saying an earlier attempt failed (own vs mismatched history)") + r = sub.add_parser("_runner") + r.add_argument("--batch", required=True) + for name in ("status", "stop", "followup"): + sub.add_parser(name).add_argument("--batch", required=True) + t = sub.add_parser("table") + t.add_argument("--batch", nargs="+", required=True) + ct = sub.add_parser("contract") + ct.add_argument("--batch", nargs="+", required=True) + rt = sub.add_parser("retry") + rt.add_argument("--batch", required=True) + rt.add_argument("--runs", nargs="*", default=[]) + a = ap.parse_args() + dict(start=cmd_start, _runner=cmd_runner, status=cmd_status, table=cmd_table, stop=cmd_stop, retry=cmd_retry, + contract=cmd_contract, followup=cmd_followup)[a.cmd](a) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/api_player.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/api_player.py new file mode 100644 index 0000000000000000000000000000000000000000..696c1e9204de668d41bdd9622931c5c579caea87 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/api_player.py @@ -0,0 +1,446 @@ +"""Drive one robot_server session with a model through its provider's official API (the unified harness). + +Every provider gets exactly the same input: the sandbox README as its instructions and the same tools; only the +wire format differs (lffbench/agent/backends/). After every command the JSON report is returned as the tool output. +Nothing else is sent: no files, no memory, no paths outside the sandbox. + + python scripts/api_player.py --session runs/<...>/session.json --provider anthropic --model claude-opus-5-5 --effort high --style la + +Providers (key / endpoint from the environment, e.g. `set -a; source .env; set +a`): + openai OpenAI Responses API OPENAI_API_KEY [OPENAI_BASE_URL] + anthropic Anthropic Messages API ANTHROPIC_API_KEY + gemini Gemini API (google-genai) GEMINI_API_KEY + chat any OpenAI-compatible Chat Completions endpoint (vLLM / SGLang for open models, xAI, ...) + LFF_CHAT_BASE_URL, LFF_CHAT_API_KEY +`--effort` is the provider's reasoning knob: OpenAI reasoning.effort, Anthropic output_config.effort, Gemini +thinking_level, chat: reasoning_effort (omitted when "none"). + +--style la (LIBERO-Agent-style workspace, the paper's interface): the sandbox is the agent's episode workspace. Besides +`robot` the model gets `shell` (a command run in the workspace inside a jail: no network, robot server unreachable, +host data hidden, see /opt/lffjail/jail_inner.sh) and `view_images` (any image file in the workspace, including ones +it made itself). Tool calls per attempt are capped (agent_iface.json: max_tool_calls); at the cap the attempt is +finished for it. +Logs in the run's log dir: transcript.jsonl (every request / reply / tool call), final_report.md. +""" +import argparse +import base64 +import json +import os +import shlex +import subprocess +import sys +import time +import traceback +import urllib.request + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) +if not os.environ.get("SSL_CERT_FILE") and os.path.exists("/etc/ssl/certs/ca-certificates.crt"): + os.environ["SSL_CERT_FILE"] = "/etc/ssl/certs/ca-certificates.crt" # the venv's own CA bundle lacks the proxy's issuer + +from lffbench.agent.backends import make_backend # noqa: E402 +from lffbench.agent.context import Conversation # noqa: E402 + +PROVIDERS = ("openai", "anthropic", "gemini", "chat") + +TOOL = dict( + name="robot", + description=("Run one robot command. `command` is exactly what you would type after `./robot` in the " + "instructions (e.g. `observe`). Returns the command's JSON report."), + parameters=dict(type="object", properties=dict(command=dict(type="string", description="the robot command")), + required=["command"], additionalProperties=False), +) + +VIEW_TOOL = dict( + name="view_images", + description=("Look at camera images the robot has written. `paths` are image paths exactly as printed by robot " + "commands (e.g. obs/a1_s003_wrist.jpg); any image of this episode can be viewed again. The images " + "are attached right after this call."), + parameters=dict(type="object", properties=dict(paths=dict(type="array", items=dict(type="string"), + description="image paths to view")), + required=["paths"], additionalProperties=False), +) + +TOOL_LA = dict( + name="robot", + description=("Run one robot command. `command` is exactly one of the robot commands in the instructions, e.g. " + "`status` or `move_eef z=1.0 gripper=open`. Returns the command's JSON report, including the paths " + "of the new observation files."), + parameters=TOOL["parameters"], +) + +SHELL_TOOL = dict( + name="shell", + description=("Run a shell command (bash) in your workspace directory, e.g. `ls obs` or `python3 analyse.py`. " + "python3 has numpy, scipy, Pillow and OpenCV. No network; programs cannot control the robot. " + "Time limit 60 s per call. Returns the exit code and the combined stdout/stderr (long output is " + "truncated in the middle)."), + parameters=dict(type="object", properties=dict(command=dict(type="string", description="the bash command")), + required=["command"], additionalProperties=False), +) + +VIEW_TOOL_LA = dict( + name="view_images", + description=("Look at image files in your workspace (.jpg / .jpeg / .png), e.g. obs/a1_s003_wrist.jpg or an image " + "you made yourself; paths are relative to the workspace. At most 8 per call. The images are attached " + "right after this call."), + parameters=dict(type="object", properties=dict(paths=dict(type="array", items=dict(type="string"), + description="image paths to view")), + required=["paths"], additionalProperties=False), +) + +PREAMBLE_LA = ("You control the robot described below and work in the workspace described below. Tools: `robot` runs " + "one robot command per call (the argument is exactly a command from the instructions, e.g. `status`); " + "`shell` runs a shell command in your workspace; `view_images` shows you image files from the " + "workspace. When a robot command tells you to stop or that the episode is over, stop calling tools and " + "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.\n\n") + +PREAMBLE = ("You control the robot described below. You act only through the `robot` tool, one command per call. " + "When a command tells you to stop or that the episode is over, stop calling the tool and 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.\n\n") + +JAIL = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "jail", "jail_inner.sh") +SHELL_TIMEOUT = 60 +SHELL_MAX_CHARS = 12000 + + +def run_shell(workspace, command): + """Run `command` in the jailed workspace; returns (exit code, output text, seconds).""" + t0 = time.time() + argv = ["unshare", "--user", "--map-root-user", "--mount", "--net", "--", JAIL, workspace, + "timeout", "-k", "5", str(SHELL_TIMEOUT), "bash", "-c", command] + try: + r = subprocess.run(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + timeout=SHELL_TIMEOUT + 30) + code, out = r.returncode, r.stdout.decode("utf-8", "replace") + except subprocess.TimeoutExpired as e: + code, out = 124, (e.stdout or b"").decode("utf-8", "replace") + if code == 124: + out += f"\n[killed: time limit of {SHELL_TIMEOUT} s]" + if len(out) > SHELL_MAX_CHARS: + h = SHELL_MAX_CHARS // 2 + out = out[:h] + f"\n[... {len(out) - SHELL_MAX_CHARS} characters truncated ...]\n" + out[-h:] + return code, out, time.time() - t0 + + +def workspace_image(workspace, rel): + """Resolve a model-given image path inside the workspace (no escaping via .. or symlinks); None if not allowed.""" + if not isinstance(rel, str) or not rel or rel.startswith("/"): + return None + root = os.path.realpath(workspace) + full = os.path.realpath(os.path.join(root, rel)) + if not full.startswith(root + os.sep) or not os.path.isfile(full): + return None + if os.path.splitext(full)[1].lower() not in (".jpg", ".jpeg", ".png") or os.path.getsize(full) > 8 * 2 ** 20: + return None + return full + + +class FileImage: + """The exact JPEG bytes the server wrote (same bytes a Claude Code player reads).""" + + def __init__(self, path): + self.path = path + base = os.path.basename(path) + self.camera = "wrist" if "wrist" in base else ("agentview" if "agentview" in base else "camera") + self.label = base + + def data_url(self, quality=None): + mime = "image/png" if self.path.lower().endswith(".png") else "image/jpeg" + with open(self.path, "rb") as f: + return f"data:{mime};base64," + base64.b64encode(f.read()).decode() + + +def parse_command(s): + s = s.strip() + s = s.removeprefix("./robot").strip() if s.startswith("./robot") else (s[len("robot "):] if s.startswith("robot ") else s) + toks = shlex.split(s.strip()) + if not toks: + return "help", {} + cmd, args = toks[0], {} + for a in toks[1:]: + if "=" not in a: + return None, f"bad argument {a!r}: use key=value" + k, v = a.split("=", 1) + try: + args[k] = json.loads(v) + except ValueError: + args[k] = v + return cmd, args + + +def call_server(port, token, cmd, args): + req = urllib.request.Request(f"http://127.0.0.1:{port}/call", data=json.dumps({"cmd": cmd, "args": args}).encode(), + headers={"Content-Type": "application/json", "X-Token": token}) + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + with opener.open(req, timeout=900) as r: + return r.read().decode() + + +MAX_NO_TOOL = 3 # nudges in a row for replies without a tool call; the next such reply ends the run + + +def continue_nudge(port, token, stx=None): + """The user message sent when the model replies without a tool call before the episode is over. Native harnesses + send the same text when their CLI exits early (scripts/harness_run.py). stx: a status reply already fetched.""" + try: # tell it where it is: models sometimes believe the episode ended after a failed attempt + if stx is None: + stx = json.loads(call_server(port, token, "status", {})) + where = (f" You are in attempt {stx.get('attempt')} of {stx.get('max_attempts')}; the episode is NOT over." + if stx.get("attempt") else "") + except Exception: + where = "" + return "Continue: issue the next robot command with the `robot` tool." + where + + +def build_backend(a, v2): + """The model backend for --provider; image pruning only where the provider allows editing earlier turns.""" + if a.provider == "openai": + return make_backend("openai", model=a.model, reasoning_effort=a.effort, reasoning_summary="auto", + max_live_images=None if v2 else a.max_live_images, cache_breakpoints="none", max_retries=1) + if a.provider == "anthropic": # append-only history (thinking blocks are bound to it): never prune + return make_backend("anthropic", model=a.model, effort=a.effort, max_live_images=None) + if a.provider == "gemini": + return make_backend("gemini", model=a.model, thinking_level=a.effort, + max_live_images=None if v2 else a.max_live_images) + extra = None if a.effort in ("", "none", None) else dict(reasoning_effort=a.effort) + return make_backend("chat", model=a.model, max_tokens=a.max_output_tokens, temperature=None, extra_body=extra, + max_live_images=None if v2 else a.max_live_images) + + +def context_overflow(err): + """The request no longer fits: token limit (OpenAI / Anthropic / Gemini / Kimi wordings) or too many images.""" + e = err.lower() + return (("context" in e and ("length" in e or "window" in e or "too long" in e)) or "prompt is too long" in e + or ("exceed" in e and "token" in e) or "too many images" in e or "maximum number of images" in e) + + +def live_images(conv): + return sum(1 for it in conv.items if it["kind"] == "user" and it.get("live") for p in it["parts"] + if p["type"] == "image") + + +def main(argv=None, default_provider=None, transcript_name="transcript.jsonl"): + ap = argparse.ArgumentParser() + ap.add_argument("--session", required=True, help="session.json written by start_robot_session.sh") + ap.add_argument("--provider", default=default_provider, choices=PROVIDERS, required=default_provider is None) + ap.add_argument("--model", default="gpt-6-astra" if default_provider == "openai" else None, + required=default_provider is None) + ap.add_argument("--effort", default="medium") + ap.add_argument("--max-turns", type=int, default=400) + ap.add_argument("--max-live-images", type=int, default=16) + ap.add_argument("--max-output-tokens", type=int, default=32768, help="chat provider only") + ap.add_argument("--api-retries", type=int, default=8, + help="retries of a failed API call before giving up (back-off 5 s doubling to 120 s: ~9 min)") + ap.add_argument("--max-request-images", type=int, default=500, + help="when the conversation holds more viewed images than this, switch to the context-full " + "policy (Claude through a gateway failed at 601 images, 2026-10-15)") + ap.add_argument("--style", default="v1", choices=["v1", "v2", "la"], + help="v2: images are not attached automatically; the model views them on demand with " + "view_images, and no history is pruned (the agent manages its own context)") + a = ap.parse_args(argv) + + sess = json.load(open(a.session)) + sb, port = sess["sandbox"], sess["port"] + log_dir = os.path.dirname(os.path.abspath(a.session)) + la = a.style == "la" + if la: # no robot CLI in a la workspace: the token is only in the log dir + iface = json.load(open(os.path.join(log_dir, "agent_iface.json"))) + token, max_tool_calls = iface["token"], int(iface["max_tool_calls"]) + else: + token = open(os.path.join(sb, "robot")).read().split('TOKEN = "', 1)[1].split('"', 1)[0] + readme = open(os.path.join(sb, "README.md")).read() + tlog = open(os.path.join(log_dir, transcript_name), "a") + + def log(d): + d["t"] = time.time() + tlog.write(json.dumps(d, ensure_ascii=False) + "\n") + tlog.flush() + + v2 = a.style in ("v2", "la") # la = v2 robot interface + workspace tools + tools = [TOOL_LA, SHELL_TOOL, VIEW_TOOL_LA] if la else ([TOOL, VIEW_TOOL] if v2 else [TOOL]) + backend = build_backend(a, v2) + conv = Conversation((PREAMBLE_LA if la else PREAMBLE) + readme) + log(dict(ev="start", provider=a.provider, model=a.model, effort=a.effort, style=a.style, backend=backend.config(), + instructions=conv.system, tools=tools)) + + def images_part(paths, title): + parts = [dict(type="text", text=title)] + for p in paths: + parts.append(dict(type="image", image=FileImage(os.path.join(sb, p)))) + return parts + + st = json.loads(call_server(port, token, "status", {})) + if v2: # images stay files; the model decides what to look at + first = [dict(type="text", text=("Begin. Current status (robot command `status`):\n" if la else + "Begin. Current status (`./robot status`):\n") + json.dumps(st))] + else: + first = [dict(type="text", text="Begin. Current status (`./robot status`):\n" + + json.dumps({k: v for k, v in st.items() if k != "images"}))] + first += images_part(st.get("images", []), "Current camera images (agentview, wrist):")[1:] + conv.add_user(first, live=True) + log(dict(ev="user", text=first[0]["text"], images=st.get("images", []))) + + finished, no_tool, report = False, 0, None + calls_in_attempt = 0 # la: tool calls (robot + shell + view_images) in the current attempt + usage_tot = dict(input_tokens=0, cached_tokens=0, cache_write_tokens=0, output_tokens=0, reasoning_tokens=0) + for turn in range(a.max_turns): + resp, err = None, None + if v2 and backend.max_live_images is None and live_images(conv) > a.max_request_images: + backend.max_live_images = 32 # same context-full policy as below, before the request limit is hit + log(dict(ev="context_overflow", reason="image count", n_images=live_images(conv), keep_images=32)) + for r in range(a.api_retries + 1): + t0 = time.time() + try: + out = backend.act(conv, tools) + except Exception as e: # flaky endpoint: back off and retry the identical request + err = f"{type(e).__name__}: {str(e)[:300]}" + if v2 and context_overflow(err): + # the context is full (every provider): from now on keep only the newest viewed images + backend.max_live_images = 32 if backend.max_live_images is None else max(backend.max_live_images // 2, 4) + log(dict(ev="context_overflow", reason=err[:120], keep_images=backend.max_live_images)) + log(dict(ev="api_error", turn=turn, retry=r, error=err, dt=time.time() - t0)) + time.sleep(min(120, 5 * 2 ** r)) + continue + if out.status == "refusal": # the provider declined: no fallback model (it would change the model under test) + resp, err = out, out.error + break + if out.status == "incomplete": # truncated / malformed turn: not appended, ask again + err = out.error + log(dict(ev="api_error", turn=turn, retry=r, error=err, dt=time.time() - t0, usage=out.usage)) + continue + resp = out + break + if resp is None: + log(dict(ev="abort", reason="api failed", error=err)) + print("ABORT api failed:", err, flush=True) + sys.exit(3) + for k in usage_tot: + usage_tot[k] += resp.usage.get(k, 0) + if resp.status == "refusal": + log(dict(ev="refusal", turn=turn, latency_s=resp.latency_s, usage=resp.usage, error=resp.error, + text=resp.text)) + log(dict(ev="abort", reason="refusal", error=resp.error)) + print("ABORT refusal:", resp.error, flush=True) + break + conv.add_assistant(resp.text, resp.tool_calls, raw=resp.raw, backend=backend.name) + log(dict(ev="assistant", turn=turn, latency_s=resp.latency_s, usage=resp.usage, text=resp.text, + reasoning_summary=resp.reasoning_summary, + reasoning_summary_status="recorded" if resp.reasoning_summary else "not_returned", + status=resp.status, error=resp.error, + tool_calls=[dict(id=c.id, name=c.name, arguments=c.arguments) for c in resp.tool_calls], + request_stats=resp.request_stats)) + if finished: + report = resp.text + break + if not resp.tool_calls: + no_tool += 1 + nudge = continue_nudge(port, token) + if no_tool > MAX_NO_TOOL: + log(dict(ev="abort", reason="no tool call 4 times")) + break + conv.add_user([dict(type="text", text=nudge)], live=False) + log(dict(ev="user", text=nudge)) + continue + no_tool = 0 + for c in resp.tool_calls: + if la and not finished: + calls_in_attempt += 1 + if la and c.name == "shell": + code, out, dt = run_shell(sb, str(c.arguments.get("command", ""))) + out_text = json.dumps(dict(exit_code=code, output=out)) + conv.add_tool_output(c.id, c.name, out_text) + log(dict(ev="tool", turn=turn, command="shell: " + str(c.arguments.get("command", "")), output=out_text, + shell_s=round(dt, 2))) + continue + if la and c.name == "view_images": + paths = [str(x) for x in (c.arguments.get("paths") or [])][:8] + full = [(x, workspace_image(sb, x)) for x in paths] + ok_paths = [x for x, f in full if f] + out = dict(ok=bool(ok_paths), attached=ok_paths) + if len(ok_paths) < len(paths): + out["not_viewable"] = [x for x, f in full if not f] + conv.add_tool_output(c.id, c.name, json.dumps(out)) + log(dict(ev="tool", turn=turn, command="view_images " + " ".join(paths), output=json.dumps(out), images=ok_paths)) + if ok_paths: + parts = [dict(type="text", text="Requested images:")] + for x, f in full: + if f: + parts.append(dict(type="image", image=FileImage(f))) + conv.add_user(parts, live=True) + continue + if c.name == "view_images": + paths = [str(x) for x in (c.arguments.get("paths") or [])][:8] + ok_paths = [x for x in paths if x.startswith("obs/") and "/.." not in x and ".." not in x + and os.path.exists(os.path.join(sb, x))] + bad = [x for x in paths if x not in ok_paths] + out = dict(ok=bool(ok_paths), attached=ok_paths) + if bad: + out["not_found"] = bad + conv.add_tool_output(c.id, c.name, json.dumps(out)) + log(dict(ev="tool", turn=turn, command="view_images " + " ".join(paths), output=json.dumps(out), images=ok_paths)) + if ok_paths: + conv.add_user(images_part(ok_paths, "Requested images:"), live=True) + continue + cmdline = str(c.arguments.get("command", "")) + cmd, args = parse_command(cmdline) + if cmd is None: + out_text, paths = json.dumps(dict(ok=False, error=args)), [] + else: + raw = call_server(port, token, cmd, args) + try: + rep = json.loads(raw) + if v2: # keep the image paths in the reply: the model views them itself if it wants + paths = [] + out_text = json.dumps(rep) + else: + paths = rep.pop("images", []) if isinstance(rep, dict) else [] + out_text = json.dumps(rep) + except ValueError: # help text + rep, paths, out_text = {}, [], raw + msg = (rep.get("message", "") + " " + rep.get("error", "")) if isinstance(rep, dict) else "" + if isinstance(rep, dict) and isinstance(rep.get("attempt_ended"), dict): + msg += " " + rep["attempt_ended"].get("message", "") + if "episode is over" in msg or "No attempts left" in msg or "Stop now" in msg: + finished = True + if isinstance(rep, dict) and (rep.get("ended") or isinstance(rep.get("attempt_ended"), dict)): + calls_in_attempt = 0 + conv.add_tool_output(c.id, c.name, out_text) + log(dict(ev="tool", turn=turn, command=cmdline, output=out_text, images=paths)) + if paths and not v2: + conv.add_user(images_part(paths, f"Camera images after `{cmdline}` (agentview, wrist):"), live=True) + if la and not finished and calls_in_attempt >= max_tool_calls: + raw = call_server(port, token, "finish", dict(reason="tool-call budget used up (automatic)")) + try: + rep = json.loads(raw) + except ValueError: + rep = dict(raw=raw) + msg = rep.get("message", "") + " " + rep.get("error", "") + if "episode is over" in msg or "No attempts left" in msg or "Stop now" in msg: + finished = True + calls_in_attempt = 0 + note = (f"The budget of {max_tool_calls} tool calls for this attempt was used up, so the attempt was " + f"finished automatically. Result: " + json.dumps(rep)) + conv.add_user([dict(type="text", text=note)], live=False) + log(dict(ev="user", text=note, auto_finish=True)) + if finished: + ask = "Stop now and reply with your short report (no more tool calls)." + conv.add_user([dict(type="text", text=ask)], live=False) + log(dict(ev="user", text=ask)) + if report: + with open(os.path.join(log_dir, "final_report.md"), "w") as f: + f.write(report) + log(dict(ev="end", finished=finished, usage_total=usage_tot)) + print(json.dumps(dict(finished=finished, usage=usage_tot, report=(report or "")[:200])), flush=True) + + +if __name__ == "__main__": + try: + main() + except SystemExit: + raise + except Exception: + traceback.print_exc() + sys.exit(1) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/audit_subagent.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/audit_subagent.py new file mode 100644 index 0000000000000000000000000000000000000000..a33e2538d6f85688c28ee23a2fa879cd6026ba99 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/audit_subagent.py @@ -0,0 +1,130 @@ +"""Audit an isolated policy subagent: every tool call it made must stay inside its sandbox. + +python scripts/audit_subagent.py [--out audit.json] +Allowed: Bash `cd && ./robot ...` (or `/robot ...`); Read of /README.md or /obs/*. +With --la (LIBERO-Agent-style workspace): also Bash `cd && ./shell ''` / `./shell <<'TAG' ... TAG` (the +command runs inside the jail; anything the OUTER shell would execute or expand is a violation), and Read / Write / Edit +of any file inside . +Everything else is reported as a violation. Prints counts + violations only (the transcript itself is large). +""" +import argparse +import json +import re + + +def tool_uses(obj): + if isinstance(obj, dict): + if obj.get("type") == "tool_use" and "name" in obj: + yield obj + for v in obj.values(): + yield from tool_uses(v) + elif isinstance(obj, list): + for v in obj: + yield from tool_uses(v) + + +def extra_shell_ops(cmd, sb): + """True if the command contains shell operators / substitutions outside quotes, apart from the + allowed leading `cd &&`.""" + import shlex + body = re.sub(r"^\s*cd\s+%s\s*&&\s*" % re.escape(sb), "", cmd) + if "`" in body or "$(" in body: + return True + try: + lex = shlex.shlex(body, posix=True, punctuation_chars=True) + toks = list(lex) + except ValueError: + return True + return any(t in (";", "&&", "||", "|", "&", ">", ">>", "<") for t in toks) + + +def shell_call_ok(cmd, sb): + """la: `cd && ./shell ...` where nothing runs outside the jail: either one heredoc with a QUOTED tag (no outer + expansion) and nothing after it, or plain arguments without outer operators / substitutions.""" + m = re.match(r"^\s*cd\s+%s\s*&&\s*(\./shell|%s/shell)(.*)$" % (re.escape(sb), re.escape(sb)), cmd, re.S) + if not m: + return False + rest = m.group(2) + s = rest.strip() + if rest[:1].isspace() and len(s) >= 2 and s[0] == "'" and s[-1] == "'" and "'" not in s[1:-1]: + return True # one single-quoted argument: the outer shell expands nothing (an inner `<", ">>", "<") for t in toks) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("transcript") + ap.add_argument("sandbox") + ap.add_argument("--out") + ap.add_argument("--la", action="store_true", help="LIBERO-Agent-style workspace: ./shell and workspace files allowed") + a = ap.parse_args() + sb = a.sandbox.rstrip("/") + ok_bash = re.compile(r"^\s*(cd\s+%s\s*&&\s*)?(\./robot|%s/robot)(\s|$)" % (re.escape(sb), re.escape(sb))) + seen, calls, viol = set(), [], [] + injected = [] # context Claude Code attached on its own: the user's memory index / identity + with open(a.transcript) as f: + for line in f: + try: + rec = json.loads(line) + except ValueError: + continue + if rec.get("type") == "attachment": + at = rec.get("attachment", {}) + if at.get("type") == "instructions": + for fi in at.get("files", []): + if "memory" in (fi.get("path") or "").lower() or fi.get("type") == "AutoMem": + injected.append(dict(kind="memory_index", path=fi.get("path"), chars=len(fi.get("content", "")))) + elif at.get("type") == "session_context": + injected.append(dict(kind="session_context", keys=sorted((at.get("context") or {}).keys()))) + for tu in tool_uses(rec): + if tu.get("id") in seen: + continue + seen.add(tu.get("id")) + name, inp = tu["name"], tu.get("input", {}) + calls.append(name) + if name == "SubagentHandback": # the final report back to the orchestrator + continue + if name == "Bash": + cmd = inp.get("command", "") + bad = (not ok_bash.match(cmd)) or extra_shell_ops(cmd, sb) + if bad and a.la and shell_call_ok(cmd, sb): + bad = False + if bad: + viol.append(dict(tool=name, command=cmd)) + elif name in ("Read", "Write", "Edit") and a.la: + import os + p = os.path.normpath(inp.get("file_path", "")) + if not p.startswith(sb + "/"): + viol.append(dict(tool=name, path=inp.get("file_path", ""))) + elif name == "Read": + p = inp.get("file_path", "") + if not (p == f"{sb}/README.md" or p.startswith(f"{sb}/obs/")): + viol.append(dict(tool=name, path=p)) + else: + viol.append(dict(tool=name, input=json.dumps(inp)[:300])) + from collections import Counter + res = dict(n_calls=len(calls), by_tool=dict(Counter(calls)), n_violations=len(viol), violations=viol, + memory_injected=any(i["kind"] == "memory_index" for i in injected), injected=injected) + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + with open(a.out, "w") as f: + json.dump(res, f, indent=1, ensure_ascii=False) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_breakfast_geometry.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_breakfast_geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..bb591b652e6beecfdd132163a5405f8253326029 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_breakfast_geometry.py @@ -0,0 +1,41 @@ +"""V2 physical height/orientation controls. Initialization interventions are diagnostics only.""" +import json +from pathlib import Path +from PIL import Image +from lffbench import envs +from lffbench.tasks.lh_breakfast_service import BreakfastService + +def main(): + out=Path(__file__).resolve().parents[1]/'results/lh_breakfast_service/geometry_v2/geometry_controls' + out.mkdir(parents=True,exist_ok=True);rows=[];t=BreakfastService() + for seed in range(1000,1003): + inst=t.sample_instance(seed);t.reset_instance(inst);t.sk.correction=t.sk.bias.copy() + # Move bread clear only at diagnostic initialization, so the obstacle is unambiguous. + envs.set_obj_pose(t.env,'bread_1',[-.09,-.32,.94]);t.env.sim.forward() + def state(stage): + r=dict(seed=seed,stage=stage,lid_deg=t.lid_deg(),butter_height_cm=100*t.butter_height(), + butter_lid_contact=bool(t.butter_lid_contact()),butter_fits=t.butter_in_box(), + applied_torque=float(t.env.sim.data.qfrc_applied[t.dof])) + assert r['applied_torque']==0.,r + rows.append(r);print(json.dumps(r),flush=True) + Image.fromarray(envs.render(t.env,res=512)).save(out/f'{seed}_{stage}.png') + (out/'progress.json').write_text(json.dumps(rows,indent=2)) + return r + # Two empty-box closes prove that the removed closure-count mechanism does not reappear. + for cycle in range(2): + # Let the freely swinging open lid settle before targeting its knob again. + t.open_lid();t.sk.hold(100);t.close_lid(False);t.sk.hold(80) + r=state('empty_close_'+str(cycle+1));assert r['lid_deg']<4 + t.open_lid();assert t.put_butter();t.close_lid(False);t.sk.hold(100) + r=state('upright_blocked') + assert r['lid_deg']>10 and r['butter_lid_contact'] and r['butter_height_cm']>7 and not r['butter_fits'],r + # Remove precisely that obstacle, leaving all geometry, forces and joint limits unchanged. + t.open_lid();assert t.pick_place('butter_1',inst['butter_xy'],t.butter_height()/2+.003) + t.close_lid(False);t.sk.hold(80);r=state('obstacle_removed');assert r['lid_deg']<4 + assert t.lay_butter_flat();r=state('laid_flat');assert r['butter_height_cm']<2.9 + t.open_lid();assert t.put_butter();t.close_lid(False);t.sk.hold(100) + r=state('flat_inside_closed');assert r['lid_deg']<4 and r['butter_fits'] and not r['butter_lid_contact'],r + (out/'result.json').write_text(json.dumps(dict(passed=True,rows=rows),indent=2)) + t.env.close() + +if __name__=='__main__':main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_breakfast_mechanisms.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_breakfast_mechanisms.py new file mode 100644 index 0000000000000000000000000000000000000000..64994a6c04651a3a106850a61e337a9c2bff29b6 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_breakfast_mechanisms.py @@ -0,0 +1,79 @@ +"""Mechanism-on/off controls and negative judge fixtures, separate from rollouts.""" +import argparse, copy, json +from pathlib import Path +import numpy as np +from lffbench.tasks.lh_breakfast_service import BreakfastService +from lffbench import envs + +def main(): + p=argparse.ArgumentParser();p.add_argument('--liquid-only',action='store_true') + p.add_argument('--judge-only',action='store_true');args=p.parse_args() + out=Path(__file__).resolve().parents[1]/'results/lh_breakfast_service/mechanisms' + out.mkdir(parents=True,exist_ok=True);t=BreakfastService();rows=[] + if args.judge_only:rows=json.loads((out/'controls_progress.json').read_text()) + for seed in ([] if args.liquid_only or args.judge_only else range(1000,1003)): + for enabled in (True,False): + inst=t.sample_instance(seed);inst['mechanisms']['L1']=enabled;t.reset_instance(inst) + t.calibration_probe();row=dict(seed=seed,mechanism='L1',enabled=enabled,triggered=t.traps['L1']) + rows.append(row);print(json.dumps(row),flush=True) + assert row['triggered']==enabled,row + inst=t.sample_instance(seed);inst['mechanisms']['L3']=enabled;t.reset_instance(inst);t.sk.correction=t.sk.bias.copy() + t.direct_carton_lift();row=dict(seed=seed,mechanism='L3',enabled=enabled,**t.pull_probe) + rows.append(row);print(json.dumps(row),flush=True) + assert row['held_before'] and ((row['displacement_m']<.01) if enabled else (row['displacement_m']>.04)),row + inst=t.sample_instance(seed);inst['mechanisms']['L2']=enabled;t.reset_instance(inst);t.sk.correction=t.sk.bias.copy() + for _ in range(2):t.open_lid();t.close_lid(False) + t.sk.hold(300);failure=t.lid_deg() + if enabled:t.open_lid();t.close_lid(True);t.sk.hold(300) + row=dict(seed=seed,mechanism='L2',enabled=enabled,lid_after_quick_closes=failure,final_lid=t.lid_deg()) + rows.append(row);print(json.dumps(row),flush=True) + assert (failure>10 if enabled else failure<4) and row['final_lid']<4,row + (out/'controls_progress.json').write_text(json.dumps(rows,indent=2)) + liquid_controls=json.loads((out/'liquid_controls.json').read_text()) if args.judge_only else [] + for case in ([] if args.judge_only else ('upright','tilted_aligned','tilted_misaligned')): + inst=t.sample_instance(1000);t.reset_instance(inst) + if case!='upright':t.env.sim.data.qpos[t.pour_qa]=1.35 + if case=='tilted_misaligned':t.env.sim.model.body_pos[t.cup_bid,0]+=.20 + t.env.sim.forward();t.sk.hold(160) + q=t.liquid;inflight=sum(p['ml'] for p in q['parcels']) + row=dict(case=case,cup_ml=q['cup'],spill_ml=q['spill'],reservoir_ml=q['reservoir'], + conservation_error_ml=abs(300-q['cup']-q['spill']-q['reservoir']-inflight)) + liquid_controls.append(row);print(json.dumps(row),flush=True) + assert row['conservation_error_ml']<1e-8,row + if case=='upright':assert q['cup']==q['spill']==0,row + elif case=='tilted_aligned':assert q['cup']>=179 and q['spill']>50,row + else:assert q['cup']==0 and q['spill']>200,row + if args.liquid_only: + (out/'liquid_controls.json').write_text(json.dumps(liquid_controls,indent=2)) + t.env.close();return + # Obtain a successful physical endpoint before mutating diagnostic scoring fixtures. + inst=t.sample_instance(1000);t.reset_instance(inst);t.execute(inst,{'mode':'oracle'});baseline=t.outcome(inst) + assert baseline['success'],baseline + state=copy.deepcopy(t.env.sim.get_state());liquid=copy.deepcopy(t.liquid) + mon=copy.deepcopy(t.mon);closes=t.closes_done;latch=t.active_latch + negatives=[] + for case in ('no_milk','too_much_milk','spill','bread_off_plate','butter_outside','lid_open','carton_tilted','gripper_closed'): + t.env.sim.set_state(state);t.env.sim.forward();t.liquid=copy.deepcopy(liquid);t.sk.grip=-1.;t.drift_active=False + t.mon=copy.deepcopy(mon);t.closes_done=closes;t.active_latch=latch + if case=='no_milk':t.liquid['reservoir']+=t.liquid['cup'];t.liquid['cup']=0 + elif case=='too_much_milk': + t.liquid['reservoir']-=175-t.liquid['cup'];t.liquid['cup']=175 + elif case=='spill':t.liquid['reservoir']-=25;t.liquid['spill']=25;t.liquid['spill_xy']=[.2,0] + elif case=='bread_off_plate':envs.set_obj_pose(t.env,'bread_1',[-.30,.03,.912]) + elif case=='butter_outside':envs.set_obj_pose(t.env,'butter_1',[-.35,-.32,.914]) + elif case=='lid_open':t.env.sim.data.qpos[t.qa]=1.0 + elif case=='carton_tilted':t.env.sim.data.qpos[t.pour_qa]=1.35 + elif case=='gripper_closed':t.sk.grip=1. + t.env.sim.forward();result=t.outcome(inst) + negatives.append(dict(case=case,accepted=result['success'],failure=result['failure'],stages=result['stages'])) + print(json.dumps(negatives[-1],default=lambda v:v.item()),flush=True) + predicate={'no_milk':'milk_served','too_much_milk':'milk_served','spill':'spill_ok', + 'bread_off_plate':'bread_on_plate','butter_outside':'butter_in_box','lid_open':'lid_closed', + 'carton_tilted':'carton_upright','gripper_closed':'gripper_open'}[case] + assert not result['success'] and not result['stages'][predicate],case + data=dict(controls=rows,liquid_controls=liquid_controls,negative_fixtures=negatives, + scope='Controlled interventions are diagnostics, not agent rollouts') + (out/'result.json').write_text(json.dumps(data,indent=2,default=lambda v:v.item())) + t.env.close() + +if __name__=='__main__':main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_breakfast_service.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_breakfast_service.py new file mode 100644 index 0000000000000000000000000000000000000000..532c02c3358934751ba5f63d863f5081993f6bf3 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_breakfast_service.py @@ -0,0 +1,48 @@ +"""Development physical/reference-policy validation. Never starts model evaluation.""" +import argparse, concurrent.futures, hashlib, json, os, time +from pathlib import Path + +TASK=None +def init_worker(): + global TASK + from lffbench.tasks.lh_breakfast_service import BreakfastService + TASK=BreakfastService() + +def plain(v): + return v.item() if hasattr(v,'item') else v.tolist() + +def run_one(job): + kind,seed,outdir=job;t=TASK;start=time.time();inst=t.sample_instance(seed) + hist=t.run_scripted(kind,inst,k=5,seed=seed+42) + row=dict(kind=kind,seed=seed,instance=inst,history=hist,trace=t.trace, + control_steps=t.sk.n_steps,primitive_count=len(t.sk.log),wall_s=time.time()-start, + pull_probe=getattr(t,'pull_probe',None)) + dest=Path(outdir)/f'{kind}_{seed}.json';dest.write_text(json.dumps(row,indent=2,default=plain)+'\n') + return dict(kind=kind,seed=seed,success=hist[-1]['outcome']['success'], + traps=hist[-1]['outcome']['traps'],recovered=hist[-1]['outcome']['recovered'], + cup_ml=hist[-1]['outcome']['cup_ml'],spill_ml=hist[-1]['outcome']['spill_ml'], + file=str(dest),wall_s=row['wall_s']) + +def main(): + p=argparse.ArgumentParser();p.add_argument('--n',type=int,default=20) + p.add_argument('--policies',default='adaptive,oracle,naive,blind');p.add_argument('--workers',type=int,default=2) + p.add_argument('--out',required=True);args=p.parse_args();out=Path(args.out);out.mkdir(parents=True,exist_ok=True) + root=Path(__file__).resolve().parents[1] + files=[root/'lffbench/tasks'/n for n in ('lh_breakfast_service.py','lh_pantry_relatch.py','lh_lid_box.py')] + hashes={str(f):hashlib.sha256(f.read_bytes()).hexdigest() for f in files} + (out/'source_hashes.json').write_text(json.dumps(hashes,indent=2)) + jobs=[(kind,seed,str(out)) for seed in range(1000,1000+args.n) for kind in args.policies.split(',')] + rows=[] + with concurrent.futures.ProcessPoolExecutor(max_workers=args.workers,initializer=init_worker) as pool: + for row in pool.map(run_one,jobs): + rows.append(row);print(json.dumps(row),flush=True) + (out/'progress.json').write_text(json.dumps(rows,indent=2)) + final_hashes={str(f):hashlib.sha256(f.read_bytes()).hexdigest() for f in files} + summary=dict(n=args.n,source_unchanged=hashes==final_hashes,policies={},rows=rows) + for kind in args.policies.split(','): + r=[x for x in rows if x['kind']==kind] + summary['policies'][kind]=dict(success=sum(x['success'] for x in r),total=len(r), + all_traps_and_recovery=sum(x['success'] and all(x['traps'].values()) and all(x['recovered'].values()) for x in r)) + (out/'summary.json').write_text(json.dumps(summary,indent=2));print(json.dumps(summary['policies']),flush=True) + +if __name__=='__main__':main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_breakfast_tool_interface.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_breakfast_tool_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..52f86cd2518d0dbd66524d63ad02f3195cbd0c00 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_breakfast_tool_interface.py @@ -0,0 +1,57 @@ +"""Execute the reference through the real public ToolExecutor, including default motion limits. +Privileged reference observations remain allowed; all actuation goes through public tools. +""" +import argparse, json, math +from pathlib import Path +from lffbench.tasks.lh_breakfast_service import BreakfastService +from lffbench.agent.tools import ToolExecutor + +class PublicSkills: + def __init__(self,base,executor): + object.__setattr__(self,'base',base);object.__setattr__(self,'executor',executor) + object.__setattr__(self,'calls',[]) + # Learned compensation belongs in the caller's command coordinates, not the environment. + object.__setattr__(self,'correction',base.correction.copy());base.correction[:]=0 + def __getattr__(self,name):return getattr(self.base,name) + def __setattr__(self,name,value): + if name=='correction':object.__setattr__(self,name,value) + else:setattr(self.base,name,value) + def call(self,name,args): + result=self.executor.call(name,args) + self.calls.append(dict(name=name,args=args,ok=result.ok,report=result.report)) + if not result.ok:raise RuntimeError(result.report) + return result.report + def move_to(self,target,yaw=None,speed=None,**kwargs): + target=target-self.correction + return self.call('move_to',dict(x=float(target[0]),y=float(target[1]),z=float(target[2]), + yaw=math.degrees(self.base.yaw if yaw is None else yaw),speed=speed)) + def set_gripper(self,close,steps=15): + result=self.call('close_gripper' if close else 'open_gripper',{}) + if steps>15:self.hold(steps-15) + return result + def hold(self,steps=10): + for _ in range(steps//15):self.call('close_gripper' if self.base.grip>0 else 'open_gripper',{}) + for _ in range(steps%15): + self.move_to(self.base.eef_pos()-self.base.bias+self.correction) + +def main(): + p=argparse.ArgumentParser();p.add_argument('--out');p.add_argument('--seed',type=int,default=1000);args=p.parse_args() + root=Path(__file__).resolve().parents[1] + out=Path(args.out) if args.out else root/'results/lh_breakfast_service/geometry_v2/tool_interface' + out.mkdir(parents=True,exist_ok=True) + t=BreakfastService();inst=t.sample_instance(args.seed);t.reset_instance(inst) + executor=ToolExecutor(t,inst,image_res=128) + proxy=PublicSkills(t.sk,executor);t.sk=proxy + t.phase_hook=lambda text,state:print(json.dumps(state),flush=True) + t.execute(inst,{'mode':'adaptive'}) + # The final judge's mandatory settle is environment work, not additional agent tool calls. + t.sk=proxy.base + result=t.outcome(inst) + data=dict(outcome=result,calls=proxy.calls,call_count=len(proxy.calls),trace=t.trace, + environment_correction=proxy.base.correction.tolist(),compensation_in_tool_arguments=True, + scope='Reference with privileged observations; actual public ToolExecutor actuation, not an LLM evaluation') + (out/'result.json').write_text(json.dumps(data,indent=2,default=lambda v:v.item())) + print('OUTCOME',result,flush=True) + assert result['success'] and all(result['traps'].values()) and len(proxy.calls)<=t.agent_max_steps,dict(outcome=result,call_count=len(proxy.calls)) + +if __name__=='__main__':main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_lh_order_dispatch.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_lh_order_dispatch.py new file mode 100644 index 0000000000000000000000000000000000000000..9fb4c084795154715e782e18d6cb6c38b5af72c0 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_lh_order_dispatch.py @@ -0,0 +1,73 @@ +"""Small physical development check; no agent/API calls. Every case starts from a reset. +Oracle recovery is explicitly diagnostic, not learned behaviour. +""" +import argparse,copy,json,sys,time +from pathlib import Path +from PIL import Image +import hashlib +from lffbench import envs +import numpy as np +from lffbench.tasks.lh_order_dispatch import OrderDispatch,PRODUCTS +from lffbench.tasks.l3_card_edge import CardEdge +from lffbench.tasks.l7_offcenter_push import OffcenterPush +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() +source=Path('lffbench/tasks/lh_order_dispatch.py').read_bytes() +code_sha256=hashlib.sha256(source).hexdigest() +Path(a.out).parent.mkdir(exist_ok=True,parents=True) +Path(a.out).with_suffix('.source.py').write_bytes(source) +task=OrderDispatch(cam_res=512);rows=[] +def capture(label): + dest=Path(a.out).parent/(Path(a.out).stem+'_frames')/f'{seed}_{case}_{label}.png';dest.parent.mkdir(exist_ok=True) + Image.fromarray(envs.render(task.env,res=512)).save(dest) + return dict(path=str(dest.resolve()),sim_step=task.sk.n_steps) + +for seed in map(int,a.seeds.split(',')): + for case in a.cases.split(','): + 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) + frames=[capture('initial')] + base_move=task.sk.move_to + captured_l5=[False] + def observed_move(*args,**kwargs): + result=base_move(*args,**kwargs) + 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]: + frames.append(capture('L5_failure'));captured_l5[0]=True + return result + task.sk.move_to=observed_move + try: + failure=None + if case in ('baseline','oracle_all'): + task.execute(inst,task.oracle_params(inst)) + elif case=='L1': + task.load_product(PRODUCTS[0],0);failure=copy.deepcopy(task.outcome(inst)) + frames.append(capture('L1_failure'));measured=failure['l1_attempts'][0]['approach_offset'];task.execute(inst,dict(mode='oracle',correction=[*measured,0],c=0.)) + elif case=='L3': + for k,o in enumerate(PRODUCTS):task.load_product(o,k) + CardEdge.execute(task,inst,dict(mode='grasp'));frames.append(capture('L3_failure'));failure=copy.deepcopy(task.outcome(inst)) + CardEdge.execute(task,inst,dict(mode='edge',overhang=.03));task.sk.hold(10) + if all(task.in_cargo(o) for o in task.mon['states']):OffcenterPush.execute(task,inst,dict(c=0.)) + pos=task.sk.eef_pos();task.sk.move_to([pos[0],pos[1],1.15]);task.sk.set_gripper(False,8) + elif case=='combined_recovery': + task.load_product(PRODUCTS[0],0);frames.append(capture('L1_failure'));failure=copy.deepcopy(task.outcome(inst)) + estimate=np.array([*failure['l1_attempts'][0]['approach_offset'],0.]);task.sk.correction=estimate + for k,o in enumerate(PRODUCTS): + task.load_product(o,k) + estimate+=np.array([*task.mon['l1_attempts'][-1]['approach_offset'],0.]);task.sk.correction=estimate.copy() + CardEdge.execute(task,inst,dict(mode='grasp'));frames.append(capture('L3_failure')) + CardEdge.execute(task,inst,dict(mode='edge',overhang=.03));task.sk.hold(10) + if all(task.in_cargo(o) for o in task.mon['states']): + OffcenterPush.adaptive_attempt(task,inst,0.) + if not task.in_cargo('card_1'):task.repair_card() + pos=task.sk.eef_pos();task.sk.move_to([pos[0],pos[1],1.15]);task.sk.set_gripper(False,8) + else: + # Original corrector takes its estimate only from observed pushes, not hidden com_offset. + task.execute(inst,dict(mode='adaptive',c=0.)) + out=task.outcome(inst);frames.append(capture('final')) + trigger=(not failure['l1_attempts'][0]['held'] if case=='L1' else + not any(c['held'] for c in failure['card_closes'] if c['card_on_board'] and c['overhang']<=0) if case=='L3' else + out['l5_triggered'] if case=='L5' else None) + 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']) + row=dict(seed=seed,case=case,diagnostics=diagnostics,mechanisms=inst['mechanisms'],triggered=trigger,recovered=out['success'],before_recovery=failure,outcome=out,frames=frames) + except Exception as e: + row=dict(seed=seed,case=case,error=repr(e)) + assert hashlib.sha256(Path('lffbench/tasks/lh_order_dispatch.py').read_bytes()).hexdigest()==code_sha256,'source changed during run' + 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) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_lh_pantry_relatch.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_lh_pantry_relatch.py new file mode 100644 index 0000000000000000000000000000000000000000..d915b3137d888a2735e6b1b2b1e16fa85da3604a --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_lh_pantry_relatch.py @@ -0,0 +1,138 @@ +"""Physical checks for lh_pantry_relatch: confirm the latch-fatigue mechanism actually behaves as designed before +any acceptance validation. Not the formal n>=20 k=5 headroom run (see scripts/validate.py for that). + +Usage: + cd lffbench && source run_env.sh && OMP_NUM_THREADS=1 python scripts/check_lh_pantry_relatch.py mechanism + OMP_NUM_THREADS=1 python scripts/check_lh_pantry_relatch.py seeds --seeds 1000,1001,1002 --out +""" +import argparse +import copy +import hashlib +import json +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import numpy as np + +from lffbench import envs +from lffbench.tasks.lh_pantry_relatch import PantryRelatch + + +def source_hash(): + path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "lffbench", "tasks", + "lh_pantry_relatch.py") + return hashlib.sha256(open(path, "rb").read()).hexdigest() + + +def mechanism_check(seed=1000, out=None): + """Isolate the latch mechanism: close 1 (quick) should hold; close 2 (quick) should drift open on its own + during the settle window; close 2 (dwell) should hold. No bread/butter picking involved -- just the lid.""" + task = PantryRelatch() + rows = [] + for label, dwell1, dwell2 in [("quick_quick", False, False), ("quick_dwell", False, True)]: + inst = task.sample_instance(seed) + task.reset_instance(inst) + task.open_lid() + task.close_lid(dwell=dwell1) + after_close1 = task.lid_deg() + n = 0 + while n < 300: + task.sk.hold(10) + n += 10 + settled1 = task.lid_deg() + task.open_lid() + task.close_lid(dwell=dwell2) + after_close2 = task.lid_deg() + n = 0 + while n < 500: + task.sk.hold(10) + n += 10 + settled2 = task.lid_deg() + row = dict(label=label, dwell1=dwell1, dwell2=dwell2, after_close1_deg=round(after_close1, 2), + settled1_deg=round(settled1, 2), after_close2_deg=round(after_close2, 2), + settled2_deg=round(settled2, 2), closes_done=task.closes_done, + active_latch_final=round(task.active_latch, 4)) + rows.append(row) + print(row, flush=True) + print("expect: quick_quick settled2_deg clearly > quick_dwell settled2_deg (fatigue visible without dwell)") + if out: + with open(out, "w") as f: + json.dump(dict(rows=rows, source_sha256=source_hash()), f, indent=1) + return rows + + +def ablation_no_decay(seed=1000, out=None): + """Ablation: force DECAY=1.0 (no fatigue). Quick-release close 2 should then also hold.""" + import lffbench.tasks.lh_pantry_relatch as mod + orig = mod.DECAY + mod.DECAY = 1.0 + try: + task = PantryRelatch() + inst = task.sample_instance(seed) + task.reset_instance(inst) + task.open_lid() + task.close_lid(dwell=False) + task.open_lid() + task.close_lid(dwell=False) + n = 0 + while n < 500: + task.sk.hold(10) + n += 10 + settled2 = task.lid_deg() + row = dict(decay_forced=1.0, settled2_deg=round(settled2, 2), closes_done=task.closes_done) + print(row, flush=True) + finally: + mod.DECAY = orig + if out: + with open(out, "w") as f: + json.dump(row, f, indent=1) + return row + + +def full_episode(seed, kind, out_dir=None): + """Full pick-bread / put-butter episode with a given scripted policy kind.""" + task = PantryRelatch() + inst = task.sample_instance(seed) + hist = task.run_scripted(kind, inst, k=task.max_attempts, seed=seed) + for h in hist: + o = h["outcome"] + print(f"seed={seed} kind={kind} attempt={h['attempt']} success={o['success']} failure={o['failure']} " + f"closes_done={o['closes_done']} lid_final={o['lid_final_deg']} detail={o['detail']}", flush=True) + return hist + + +def seeds_check(seeds, out=None): + task_rows = {} + for seed in seeds: + rows = {} + for kind in ("oracle", "naive", "adaptive"): + hist = full_episode(seed, kind) + rows[kind] = [dict(attempt=h["attempt"], success=h["outcome"]["success"], + failure=h["outcome"]["failure"], closes_done=h["outcome"]["closes_done"], + lid_final_deg=h["outcome"]["lid_final_deg"]) for h in hist] + task_rows[seed] = rows + result = dict(seeds=seeds, rows=task_rows, source_sha256=source_hash()) + if out: + with open(out, "w") as f: + json.dump(result, f, indent=1) + return result + + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("mode", choices=["mechanism", "ablation", "seeds", "episode"]) + ap.add_argument("--seed", type=int, default=1000) + ap.add_argument("--seeds", type=str, default="1000,1001,1002") + ap.add_argument("--kind", type=str, default="oracle") + ap.add_argument("--out", type=str, default=None) + args = ap.parse_args() + if args.mode == "mechanism": + mechanism_check(args.seed, args.out) + elif args.mode == "ablation": + ablation_no_decay(args.seed, args.out) + elif args.mode == "episode": + full_episode(args.seed, args.kind) + elif args.mode == "seeds": + seeds_check([int(s) for s in args.seeds.split(",")], args.out) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_setup.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..c91b70fc618700ec2c265ebd1f9f21fed24e2420 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/check_setup.py @@ -0,0 +1,175 @@ +"""Check that this machine can run LFF-Bench. Run after `source run_env.sh`: + + python scripts/check_setup.py # Python packages, LIBERO config, simulation + rendering, the agent's shell jail + python scripts/check_setup.py --api # ... plus one tiny text-only request to the model endpoint (OPENAI_API_KEY / + # OPENAI_BASE_URL from the environment or from .env); costs a few tokens + python scripts/check_setup.py --api --model gpt-5.5 --skip-sim --skip-jail + +Exit code 0 when every check that ran passed. +""" +import argparse +import os +import subprocess +import sys +import tempfile +import time + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) +JAIL = "/opt/lffjail/jail_inner.sh" # same path as lffbench/agent/robot_server.py and scripts/gpt_player.py + +results = [] + + +def report(name, ok, detail=""): + results.append(ok) + print(f"[{'ok' if ok else 'FAIL'}] {name}" + (f": {detail}" if detail else ""), flush=True) + return ok + + +def check_packages(): + report("python 3.10", sys.version_info[:2] == (3, 10), sys.version.split()[0]) + from lffbench.agent.backends.base import import_openai + for mod in ("numpy", "mujoco", "robosuite", "libero.libero", "openai", "imageio", "cv2"): + try: + m = import_openai() if mod == "openai" else __import__(mod, fromlist=["_"]) + report(f"import {mod}", True, getattr(m, "__version__", "")) + except Exception as e: # noqa: BLE001 + report(f"import {mod}", False, f"{type(e).__name__}: {e}") + cfg = os.path.join(os.environ.get("LIBERO_CONFIG_PATH", ""), "config.yaml") + if report("LIBERO config", os.path.isfile(cfg), cfg + ("" if os.path.isfile(cfg) else " missing: run setup/install.sh")): + import yaml + assets = yaml.safe_load(open(cfg)).get("assets", "") + report("LIBERO assets", os.path.isdir(assets), assets) + report("rendering backend", bool(os.environ.get("MUJOCO_GL")), f"MUJOCO_GL={os.environ.get('MUJOCO_GL')}") + + +def check_sim(task_name, seed): + import importlib + import pkgutil + + try: + import lffbench.tasks as task_pkg + from lffbench.task_base import TASKS + except Exception as e: # noqa: BLE001 + report("import lffbench", False, f"{type(e).__name__}: {e}") + return + try: + for m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{m.name}") + except Exception as e: # noqa: BLE001 + report("import tasks", False, f"{type(e).__name__}: {e}") + return + report("tasks registered", len(TASKS) >= 20, f"{len(TASKS)} tasks") + t0 = time.time() + try: + task = TASKS[task_name]() + inst = task.sample_instance(seed) + task.reset_instance(inst) + img = task.snapshot() + out = task.outcome(inst) + except Exception as e: # noqa: BLE001 + report(f"simulate + render {task_name}", False, f"{type(e).__name__}: {e}") + return + ok = img.ndim == 3 and img.shape[2] == 3 and float(img.std()) > 1.0 + report(f"simulate + render {task_name}", ok, + f"image {img.shape}, pixel std {img.std():.1f}, untouched scene success={out['success']}, {time.time() - t0:.1f} s") + + +def check_jail(): + if not report("jail installed", os.access(JAIL, os.X_OK) and os.path.isdir("/opt/lffjail/py"), + JAIL if os.path.exists(JAIL) else "missing: sudo bash jail/setup_jail.sh"): + return + probe = r''' +echo "pwd=$(pwd)" +python3 -c "import numpy, scipy, PIL, cv2; print('py=ok')" 2>&1 | tail -1 +echo "mnt_entries=$(ls -A /mnt 2>/dev/null | wc -l) home_entries=$(ls -A /home 2>/dev/null | wc -l)" +python3 -c " +import socket +s = socket.socket(); s.settimeout(3) +try: + s.connect(('1.1.1.1', 443)); print('net=open') +except OSError as e: + print('net=blocked') +" +touch made_in_jail && echo "write=ok" +''' + with tempfile.TemporaryDirectory(prefix="lffjail_check_") as ws: + argv = ["unshare", "--user", "--map-root-user", "--mount", "--net", "--", JAIL, ws, + "timeout", "-k", "5", "60", "bash", "-c", probe] + r = subprocess.run(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=120) + kv = dict(l.split("=", 1) for l in r.stdout.split() if "=" in l) + if r.returncode != 0 and not kv: + hint = "" + if "Operation not permitted" in r.stdout or "uid_map" in r.stdout: + hint = (" | unprivileged user namespaces are blocked; on Ubuntu >= 23.10: " + "sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0") + report("jail runs", False, r.stdout.strip()[-400:] + hint) + return + report("jail runs", True, f"workdir {kv.get('pwd')}") + report("jail python (numpy/scipy/Pillow/OpenCV)", kv.get("py") == "ok", kv.get("py", r.stdout[-300:])) + report("jail hides host data", kv.get("mnt_entries") == "0" and kv.get("home_entries") == "0", + f"/mnt entries {kv.get('mnt_entries')}, /home entries {kv.get('home_entries')}") + report("jail has no network", kv.get("net") == "blocked", kv.get("net", "?")) + report("jail writes the workspace", kv.get("write") == "ok" and os.path.exists(os.path.join(ws, "made_in_jail"))) + + +def load_env_file(): + path = os.environ.get("LFF_ENV_FILE") or os.path.join(ROOT, ".env") + if not os.path.isfile(path): + return None + for line in open(path): + line = line.strip() + if line and not line.startswith("#") and "=" in line: + k, v = line.split("=", 1) + os.environ.setdefault(k.removeprefix("export ").strip(), v.strip().strip("'\"")) + return path + + +def check_api(model, effort): + src = load_env_file() + if not os.environ.get("SSL_CERT_FILE") and os.path.exists("/etc/ssl/certs/ca-certificates.crt"): + os.environ["SSL_CERT_FILE"] = "/etc/ssl/certs/ca-certificates.crt" # same as scripts/gpt_player.py + if not report("OPENAI_API_KEY set", bool(os.environ.get("OPENAI_API_KEY")), + f"from {src}" if src else "from the environment (no .env)"): + return + base = os.environ.get("OPENAI_BASE_URL") or "https://api.openai.com/v1 (default)" + from lffbench.agent.backends.openai_responses import OpenAIResponsesBackend + t0 = time.time() + try: + client = OpenAIResponsesBackend(model=model, reasoning_effort=effort, timeout=120.0, max_retries=1).client() + resp = client.responses.create(model=model, instructions="Reply with exactly the word OK.", input="ping", + reasoning=dict(effort=effort), store=False, max_output_tokens=256) + text = (resp.output_text or "").strip() + u = resp.usage + report(f"API {model} @ {base}", bool(text), f"reply {text[:40]!r}, {time.time() - t0:.1f} s, " + f"tokens in {u.input_tokens} / out {u.output_tokens}") + except Exception as e: # noqa: BLE001 + report(f"API {model} @ {base}", False, f"{type(e).__name__}: {str(e)[:300]}") + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--api", action="store_true", help="also send one tiny request to the model endpoint") + ap.add_argument("--model", default="gpt-6-astra") + ap.add_argument("--effort", default="low") + ap.add_argument("--task", default="l5_slide_to_target") + ap.add_argument("--seed", type=int, default=1000) + ap.add_argument("--skip-sim", action="store_true") + ap.add_argument("--skip-jail", action="store_true") + a = ap.parse_args() + os.environ.setdefault("OMP_NUM_THREADS", "1") + check_packages() + if not a.skip_sim: + check_sim(a.task, a.seed) + if not a.skip_jail: + check_jail() + if a.api: + check_api(a.model, a.effort) + n_bad = results.count(False) + print(f"\n{len(results) - n_bad}/{len(results)} checks passed") + sys.exit(1 if n_bad else 0) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/claude_batch.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/claude_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..9a03551e2d18fd5f649ddb62093078a2cc7613fa --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/claude_batch.py @@ -0,0 +1,309 @@ +"""Batch bookkeeping for Claude-subagent policy runs. + + start python scripts/claude_batch.py start --batch exp1 --model sonnet --tasks t1:s1,s2 t2:s1 --k 3 --port0 9000 + -> starts one server per (task, seed, condition) run and writes runs/claude//manifest.json + conditions: harness = memory full + feedback (default F1) + k attempts in one agent; + noharness = k independent single-attempt agents (memory none, k=1) + usage python scripts/claude_batch.py usage --batch exp1 --run --agent --tokens N --ms N --tools N + audit python scripts/claude_batch.py audit --batch exp1 (runs audit_subagent on every recorded agent) + table python scripts/claude_batch.py table --batch exp1 [--batch exp2 ...] + stop python scripts/claude_batch.py stop --batch exp1 +""" +import argparse +import glob +import json +import os +import subprocess +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +RUNS = os.path.join(ROOT, "runs", "claude") +RUNS_DIR_DEFAULT = RUNS +TRANSCRIPTS = os.environ.get("CLAUDE_TASKS_DIR", "") # the Claude Code session's tasks/ dir (.output files) + +PLAYER_PROMPT = """You are controlling a simulated robot arm. Everything you need is in the directory {sb} + +Rules (strict): +- First read {sb}/README.md โ€” it explains the robot, the coordinate frames, the cameras, the commands and your task. +- Control the robot only by running shell commands of the form: + cd {sb} && ./robot key=value ... + Run one robot command per shell call. +- 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). +- 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. +- Keep going until a robot command tells you to stop or that the episode is over. + +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.""" + + +PLAYER_PROMPT_LA = """You are controlling a simulated robot arm. Your workspace is the directory {sb} + +Rules (strict): +- First read {sb}/README.md: it explains the robot, the commands, the observation files and your task. +- Every shell call must be exactly one of these forms, with nothing chained before or after it: + cd {sb} && ./robot key=value ... + cd {sb} && ./shell '' + cd {sb} && ./shell <<'EOF' + + EOF + ./robot runs one robot command. ./shell runs your command inside the workspace (ls, python3 with numpy / scipy / + Pillow / OpenCV, writing your own notes or scripts, ...); it has no network and cannot control the robot. +- Use your file-reading tool to look at images and other files, and your file-writing tools if you want, but only on + files inside {sb}. +- Do not read, list, search or execute anything else on this machine, do not use any other tool, no web access. +- Keep going until a robot command tells you to stop or that the episode is over. + +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.""" + + +THINK_ALOUD = """ + +Think aloud (for the experiment log): before every ./robot command, first write one to three plain sentences as +normal text (not inside a tool call): what you currently see or know, what you conclude from it, and what the next +command is meant to achieve. After each attempt ends, also write what you think went wrong (or right) and what you +will change. Keep these notes short and factual.""" + + +def manifest_path(batch): + return os.path.join(RUNS, batch, "manifest.json") + + +def load(batch): + with open(manifest_path(batch)) as f: + return json.load(f) + + +def save(batch, m): + os.makedirs(os.path.dirname(manifest_path(batch)), exist_ok=True) + with open(manifest_path(batch), "w") as f: + json.dump(m, f, indent=1) + + +def port_free(port): + import socket + with socket.socket() as so: + try: + so.bind(("127.0.0.1", port)) + return True + except OSError: + return False + + +def start_one(task, seed, mem, k, port, tag, perception="depth", video=False, style="v1", extra="", feedback="F1"): + env = dict(os.environ, LFF_RUNS_DIR=os.environ.get("LFF_RUNS_DIR", RUNS_DIR_DEFAULT), LFF_STYLE=style, LFF_EXTRA_ARGS=extra) + out = subprocess.run(["bash", os.path.join(ROOT, "scripts", "start_robot_session.sh"), task, str(seed), mem, feedback, + str(port), "direct", str(k), tag, perception, "1" if video else "0"], capture_output=True, text=True, + env=env) + kv = dict(line.split("=", 1) for line in out.stdout.strip().splitlines() if "=" in line and line.split("=")[0] in ("SANDBOX", "LOG")) + if "SANDBOX" not in kv: + raise RuntimeError(out.stdout + out.stderr) + return kv["SANDBOX"], kv["LOG"] + + +def cmd_start(a): + m = load(a.batch) if os.path.exists(manifest_path(a.batch)) else dict(batch=a.batch, runs=[]) + port = a.port0 + used = {r["port"] for r in m["runs"]} + for spec in a.tasks: + task, seeds = spec.split(":") + for seed in seeds.split(","): + conds = [("harness", "full", a.k, 0)] + [("noharness", "none", 1, i) for i in range(a.k)] + for cond, mem, k, rep in conds: + if a.only and cond != a.only: + continue + while port in used or not port_free(port): + port += 1 + hide_k = bool(a.hide_k and cond == "harness") + tag = (f"{a.batch}-{a.model}-{cond}{rep if cond == 'noharness' else ''}" + ("-nominal" if a.nominal else "") + + ("-hidek" if hide_k else "") + (f"-arm{a.arm}" if a.arm != "none" else "") + + ("-dossier" if a.dossier else "")) + extra = (("--agent-iface cli" if a.style == "la" else "") + (" --nominal" if a.nominal else "") + + (" --hide-k" if hide_k else "") + (f" --arm {a.arm}" if a.arm != "none" else "") + + (f" --dossier {os.path.abspath(a.dossier)}" if a.dossier else "")) + os.environ["LFF_RUNS_DIR"] = os.path.join(RUNS, a.batch) + sb, log = start_one(task, int(seed), mem, k, port, tag, a.perception, a.video, a.style, extra.strip(), a.feedback) + used.add(port) + r = dict(run=os.path.basename(log), task=task, seed=int(seed), model=a.model, cond=cond, rep=rep, k=k, + port=port, sandbox=sb, log=log, perception=a.perception, video=a.video, style=a.style, + nominal=a.nominal, feedback=a.feedback, think_aloud=a.think_aloud, hide_k=hide_k, + arm=a.arm, dossier=os.path.abspath(a.dossier) if a.dossier else "", + prompt=(PLAYER_PROMPT_LA if a.style == "la" else PLAYER_PROMPT).format(sb=sb) + + (THINK_ALOUD if a.think_aloud else "")) + m["runs"].append(r) + print(json.dumps({k_: r[k_] for k_ in ("run", "sandbox")}), flush=True) + save(a.batch, m) + + +def cmd_usage(a): + m = load(a.batch) + for r in m["runs"]: + if r["run"] == a.run or r["sandbox"] == a.run: + r.update(agent=a.agent, tokens=a.tokens, ms=a.ms, tool_uses=a.tools) + save(a.batch, m) + + +def cmd_audit(a): + m = load(a.batch) + for r in m["runs"]: + if not r.get("agent"): + continue + tr = os.path.join(TRANSCRIPTS, f"{r['agent']}.output") + if not os.path.exists(tr): + r["audit"] = "transcript missing" + continue + out = subprocess.run([sys.executable, os.path.join(ROOT, "scripts", "audit_subagent.py"), tr, r["sandbox"], + "--out", os.path.join(r["log"], "audit.json")] + (["--la"] if r.get("style") == "la" else []), + capture_output=True, text=True) + res = json.loads(out.stdout) + r["audit"] = dict(n_calls=res["n_calls"], n_violations=res["n_violations"]) + if res["n_violations"]: + print(r["run"], res["violations"][:3]) + save(a.batch, m) + print("audited", sum(1 for r in m["runs"] if r.get("audit"))) + + +def run_stats(r): + ev = [json.loads(l) for l in open(os.path.join(r["log"], "events.jsonl"))] + if r.get("only_attempt"): # one attempt of a run (api_batch --memfree followup: attempt 1 of a history run) + ev = [e for e in ev if e.get("attempt") == r["only_attempt"]] + dones = [e for e in ev if e["ev"] == "done"] + http = [e for e in ev if e["ev"] == "http"] + calls = [e for e in ev if e["ev"] == "call"] + first = next((d["attempt"] for d in dones if d["success"]), None) + think = [h["think_s"] for h in http if h.get("think_s") is not None] + srv = [h["server_s"] for h in http] + t0 = http[0]["t_recv"] if http else None + t1 = http[-1]["t_send"] if http else None + return dict(attempts=len(dones), first_success=first, n_calls=len(calls), n_http=len(http), + think_s=sum(think), server_s=sum(srv), wall_s=(t1 - t0) if t0 else None, + think_per_cmd=(sum(think) / len(think)) if think else None, + outcomes=[(d["attempt"], d["success"], d.get("feedback", "")) for d in dones]) + + +def cmd_table(a): + rows = [] + for b in a.batch: + for r in load(b)["runs"]: + try: + st = run_stats(r) + except FileNotFoundError: + continue + rows.append(dict(r, **st)) + import collections + # group: (task, model) -> harness runs / noharness groups by seed + g = collections.defaultdict(lambda: dict(h=[], n=collections.defaultdict(list))) + for x in rows: + key = (x["task"], x["model"]) + if x["cond"] == "harness": + g[key]["h"].append(x) + else: + g[key]["n"][x["seed"]].append(x) + 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) |", + "|---|---|---|---|---|---|---|---|---|---|"] + tot = collections.defaultdict(lambda: [0, 0, 0, 0, 0]) + for (task, model), d in sorted(g.items()): + H = [x for x in d["h"] if x["attempts"] > 0] + K = max([x["k"] for x in H] or [3]) + h1 = sum(1 for x in H if x["first_success"] == 1) + hk = sum(1 for x in H if x["first_success"] is not None) + seeds = [s for s, xs in d["n"].items() if all(x["attempts"] > 0 for x in xs)] + n1 = sum(1 for s in seeds if sorted(d["n"][s], key=lambda x: x["rep"])[0]["first_success"]) + nk = sum(1 for s in seeds if any(x["first_success"] for x in d["n"][s])) + allx = H + [x for s in seeds for x in d["n"][s] if not x.get("only_attempt")] # attempt 1 counted in H + th = [x["think_per_cmd"] for x in allx if x["think_per_cmd"]] + cpa = [x["n_calls"] / max(x["attempts"], 1) for x in allx] + wall = [x["wall_s"] / 60 for x in H if x["wall_s"]] + f = lambda v: f"{sum(v) / len(v):.1f}" if v else "โ€”" + lines.append(f"| {task} | {model} | {len(H)}/{len(seeds)} | {h1}/{len(H)} | {hk}/{len(H)} | {n1}/{len(seeds)} | " + f"{nk}/{len(seeds)} | {f(th)} | {f(cpa)} | {f(wall)} |") + t = tot[model] + t[0] += h1; t[1] += hk; t[2] += len(H); t[3] += nk; t[4] += len(seeds) + for model, t in tot.items(): + lines.append(f"| **all** | {model} | | {t[0]}/{t[2]} | {t[1]}/{t[2]} | | {t[3]}/{t[4]} | | | |") + print("\n".join(lines)) + + +def cmd_restart(a): + """Re-run interrupted runs from scratch: stop the old server, start a fresh one (new sandbox, new port), + keep the old entry under 'superseded'.""" + m = load(a.batch) + used = {r["port"] for r in m["runs"]} + port = a.port0 + for i, r in enumerate(list(m["runs"])): + if r["run"] not in a.runs: + continue + try: + os.kill(int(open(os.path.join(r["log"], "server.pid")).read()), 15) + except (ProcessLookupError, FileNotFoundError): + pass + while port in used or not port_free(port): + port += 1 + mem = "full" if r["cond"] == "harness" else "none" + tag = f"{a.batch}-{r['model']}-{r['cond']}{r['rep'] if r['cond'] == 'noharness' else ''}" + if r.get("style") == "la": + os.environ["LFF_RUNS_DIR"] = os.path.dirname(r["log"]) + extra = (("--agent-iface cli" if r.get("style") == "la" else "") + (" --nominal" if r.get("nominal") else "") + + (" --hide-k" if r.get("hide_k") else "") + + (f" --arm {r['arm']}" if r.get("arm", "none") != "none" else "") + + (f" --dossier {r['dossier']}" if r.get("dossier") else "")) + tag += ("-hidek" if r.get("hide_k") else "") + (f"-arm{r['arm']}" if r.get("arm", "none") != "none" else "") \ + + ("-dossier" if r.get("dossier") else "") + sb, log = start_one(r["task"], r["seed"], mem, r["k"], port, tag, r.get("perception", "depth"), r.get("video", False), + r.get("style", "v1"), extra.strip(), r.get("feedback", "F2")) + used.add(port) + new = {k: v for k, v in r.items() if k not in ("agent", "tokens", "ms", "tool_uses", "audit")} + new.update(run=os.path.basename(log), port=port, sandbox=sb, log=log, + prompt=(PLAYER_PROMPT_LA if r.get("style") == "la" else PLAYER_PROMPT).format(sb=sb)) + m.setdefault("superseded", []).append(dict(r, reason=a.reason)) + m["runs"][i] = new + print(json.dumps(dict(run=new["run"], sandbox=sb))) + save(a.batch, m) + + +def cmd_stop(a): + for r in load(a.batch)["runs"]: + pid = os.path.join(r["log"], "server.pid") + if os.path.exists(pid): + try: + os.kill(int(open(pid).read()), 15) + except ProcessLookupError: + pass + + +def main(): + ap = argparse.ArgumentParser() + sub = ap.add_subparsers(dest="cmd") + s = sub.add_parser("start"); s.add_argument("--batch", required=True); s.add_argument("--model", required=True) + s.add_argument("--tasks", nargs="+", required=True); s.add_argument("--k", type=int, default=3) + s.add_argument("--port0", type=int, default=9000); s.add_argument("--only", choices=["harness", "noharness"]) + s.add_argument("--perception", default="depth", choices=["depth", "rgb", "rgbd"]); s.add_argument("--video", action="store_true") + s.add_argument("--style", default="v1", choices=["v1", "v2", "la"]) + s.add_argument("--nominal", action="store_true", help="L1 control: hidden calibration error removed") + s.add_argument("--arm", default="none", choices=["none", "h0", "hplus", "twin"], + help="full5 controlled arm (lffbench/arm_specs/.py), passed to every run of this call") + s.add_argument("--dossier", default="", + help="la, single task:seed per call: earlier-attempt record (scripts/make_dossier.py) copied to history/") + s.add_argument("--hide-k", action="store_true", + help="harness runs: README says 1 attempt (same as the independent run); the other k-1 attempts are " + "announced only after a failure") + s.add_argument("--think-aloud", action="store_true", + help="append a request to write 1-3 plain sentences before every robot command (the transcript keeps no " + "thinking text, so this is the only way to record the agent's reasoning); changes the prompt") + s.add_argument("--feedback", default="F1", choices=["F0", "F1", "F2"], + help="after a failed attempt: F1 = success/failure only (default since 2026-10-08); F2 = measured error " + "(privileged; neither LIBERO-Agent nor RoboDojo gives it), ablation only") + u = sub.add_parser("usage"); u.add_argument("--batch", required=True); u.add_argument("--run", required=True) + u.add_argument("--agent", required=True); u.add_argument("--tokens", type=int); u.add_argument("--ms", type=int) + u.add_argument("--tools", type=int) + au = sub.add_parser("audit"); au.add_argument("--batch", required=True) + t = sub.add_parser("table"); t.add_argument("--batch", nargs="+", required=True) + st = sub.add_parser("stop"); st.add_argument("--batch", required=True) + rs = sub.add_parser("restart"); rs.add_argument("--batch", required=True); rs.add_argument("--runs", nargs="+", required=True) + rs.add_argument("--port0", type=int, default=9300) + rs.add_argument("--reason", default="interrupted (rate limit)") + a = ap.parse_args() + dict(start=cmd_start, usage=cmd_usage, audit=cmd_audit, table=cmd_table, stop=cmd_stop, restart=cmd_restart)[a.cmd](a) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/cs_ir_report.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/cs_ir_report.py new file mode 100644 index 0000000000000000000000000000000000000000..681580fd2dab576a4f9ac1747508e03873147f59 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/cs_ir_report.py @@ -0,0 +1,87 @@ +"""Reproduce the CS/IR audit tables from read-only manifests and hash-bound evidence.""" +import argparse +import json +from pathlib import Path + +import api_batch +import outcomes +from outcome_audit import load_audit, sha256 + +GROUPS = {"GPT": ["cx_main1"], "Sonnet": ["cc_main1"], "Opus": ["cc_opus1"], + "DeepSeek": ["ds_cx1", "ds_cx1b"]} + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--runs-root", required=True) + parser.add_argument("--audit", required=True) + parser.add_argument("--out", required=True) + args = parser.parse_args() + api_batch.RUNS = str(Path(args.runs_root).resolve()) + audit = load_audit(args.audit) + output = Path(args.out) + output.mkdir(parents=True, exist_ok=True) + all_rows, models, manifests, coverage = [], {}, {}, {} + for model, batches in GROUPS.items(): + old, new = [], [] + for batch in batches: + manifest = api_batch.load(batch) + manifests[batch] = sha256(api_batch.mpath(batch)) + old += outcomes.instance_rows(manifest, batch=batch) + new += outcomes.instance_rows(manifest, audit=audit, batch=batch) + for run in manifest["runs"]: + if not (run["cond"] == "harness" and run.get("followup") and run["status"] == "done"): + continue + attempts = outcomes.attempts(run["log"]) + if attempts: + coverage.setdefault(run["task"], set()).update( + k for k in outcomes.ERROR_FLAGS + outcomes.ERROR_COUNTS if k in attempts[0][2]) + before, after = outcomes.summary(old), outcomes.summary(new) + for key in ("n", "A1", "A3", "XR", "F", "n_paired", "A3_paired", "passk_paired", "delta_paired"): + assert before[key] == after[key], f"Audit unexpectedly changed {model} {key}" + assert len({(r["task"], r["seed"]) for r in new}) == len(new), "duplicate model/task/seed" + models[model] = dict(before=before, after=after) + all_rows += [dict(r, model=model) for r in new] + payload = dict(schema="lff-cs-ir-report-1", source_manifests_sha256=manifests, + audit_sha256=sha256(args.audit), models=models, rows=all_rows, + legacy_counter_coverage={k: sorted(v) for k, v in coverage.items()}) + (output / "summary.json").write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n") + lines = ["# CS / IR ่ฏๆฎๅฎก่ฎก่กจ๏ผˆ2026-10-24๏ผ‰", "", + "ๆœฌ่กจ็”ฑ `scripts/cs_ir_report.py` ็”Ÿๆˆ๏ผ›ๅฎšไน‰ใ€ๅฑ€้™ใ€ๅˆๅนถ่ฏดๆ˜Ž่งๅŒ็›ฎๅฝ• `README.md`ใ€‚", + "ๆ—งๅฃๅพ„ๆ˜ฏ task counter heuristic๏ผ›ๆ–ฐๅฃๅพ„ๆ˜ฏ้€ run ็š„็‰ฉ็†ๅคฑ่ดฅ + ไธปๅŠจไฟฎๅค่ฏๆฎๅฎก่ฎกใ€‚", + "A1ใ€A3ใ€XRใ€Fใ€้…ๅฏนๆ ทๆœฌๅŠ ฮ”_hist ๅ‡้€้กนๆ–ญ่จ€ไฟๆŒไธๅ˜ใ€‚", "", + "| ๆจกๅž‹ | ๆ—ง CS / IR / S? | ๅฎก่ฎก CS / IR / S? | ๅŽŸ S? ๅทฒ่กฅ | A1 | A3 |", + "|---|---|---|---|---|---|"] + for model, pair in models.items(): + b, a = pair["before"], pair["after"] + resolved = sum(r["model"] == model and r["legacy_cls"] == "S?" and r["cls"] != "S?" for r in all_rows) + lines.append(f"| {model} | {b['CS']} / {b['IR']} / {b['S?']} | {a['CS']} / {a['IR']} / {a['S?']} | " + f"{resolved}/{b['S?']} | {a['A1']}/{a['n']} | {a['A3']}/{a['n']} |") + lines += ["", "## ๆฏไปปๅŠกๆ–ฐๆ—งๅˆ†็ฑปไธŽๅŽŸ็ปŸไธ€ๅญ—ๆฎต่ฆ†็›–", "", + "`ๆ—งโ†’ๆ–ฐ`๏ผ›ๅชๆœ‰ไธ€ไธชๆ ‡็ญพ่กจ็คบๆœชๅ˜ใ€‚`็ผบๅคฑ` ไธๆ˜ฏๆฒกๆœ‰้”™่ฏฏ๏ผ›ๆœ‰ๅญ—ๆฎตไนŸไธไปฃ่กจ่ฆ†็›–ๆŠ“็ฉบ/ๆމ่ฝ็ญ‰ๅ…จ้ƒจๅคฑ่ดฅใ€‚", "", + "| ไปปๅŠก | GPT | Sonnet | Opus | DeepSeek | ๅŽŸ็ปŸไธ€้”™่ฏฏๅญ—ๆฎต |", "|---|---|---|---|---|---|"] + for task, counters in coverage.items(): + cells = [] + for model in GROUPS: + row = next(r for r in all_rows if r["model"] == model and r["task"] == task) + cells.append(row["cls"] if row["cls"] == row["legacy_cls"] else f"{row['legacy_cls']}โ†’{row['cls']}") + lines.append("| " + " | ".join([task] + cells + [", ".join(sorted(counters)) or "็ผบๅคฑ"]) + " |") + lines += ["", "## ้ฆ–ๆฌกๆˆๅŠŸ็š„่ฏๆฎ้“พ", "", "่กŒๅทๅ‡ๆŒ‡ๅŽŸ run ๆ–‡ไปถ๏ผŒE ไธบ events.jsonl๏ผŒT ไธบ trajectory.jsonl๏ผ›s ไธบๆœบๅ™จไบบๅ‘ฝไปคๅบๅทใ€‚", ""] + for row in all_rows: + if not row["a1"]: + continue + entry = audit.get((row["batch"], row["run_id"])) + manifest = api_batch.load(row["batch"]) + run = next(r for r in manifest["runs"] if r["id"] == row["run_id"]) + lines += [f"### {row['model']} ยท {row['task']} ยท {row['legacy_cls']} โ†’ {row['cls']}", "", + row["audit_basis"], "", f"[ๅŽŸ events.jsonl]({run['log']}/events.jsonl) ยท " + f"[ๅŽŸ trajectory.jsonl]({run['log']}/trajectory.jsonl)", ""] + if entry: + lines += [f"่ฏๆฎ็ดขๅผ•๏ผš{entry.get('evidence', '')}", "", + f"ๅฝ’ๅ› ่Œƒๅ›ด๏ผš`{entry.get('failure_scope', 'not_adjudicated')}`ใ€‚", ""] + (output / "TABLES.md").write_text("\n".join(lines) + "\n") + print(json.dumps(models, ensure_ascii=False, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/feedback_ladder.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/feedback_ladder.py new file mode 100644 index 0000000000000000000000000000000000000000..f0cbcd10f0e9f163fbcc307dbf449147ddab78eb --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/feedback_ladder.py @@ -0,0 +1,428 @@ +"""Frozen first-failure record experiment. No native-session-continuation claim. + +prepare creates a host-only manifest plus agent-visible, identical history records. +run starts the serial, resumable controller; player wraps the unchanged native harness. +""" +import argparse +import collections +import datetime as dt +import hashlib +import json +import os +from pathlib import Path +import random +import shutil +import signal +import socket +import subprocess +import sys +import time + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / 'scripts')) +SOURCE = ROOT.parents[1] / 'lffbench' +REPORT = ROOT.parents[1] / 'reports/feedback_ladder_20261027' +BATCHES = ('cc_opus1', 'cc_opus_s2', 'cc_opus_s3') +TASKS = ('l7_offcenter_push','l5_slide_to_target','l5_tablecloth_pull','l3_wall_flush', + 'l3_under_table_tool','l4_fit_container','l7_key_turn','l2_turntable_restore','l3_card_shelf','l5_loaded_beam') +ARMS = ('F1', 'F2', 'cause', 'fix') +ENV_FILE = Path('/mnt/cpfs/workspace/env/claude-releases/cc_opus_s3.env') +PILOT = ('cc_opus1__l3_card_shelf__3003', 'cc_opus_s2__l4_fit_container__3001') + + +def now(): + return dt.datetime.now(dt.timezone.utc).isoformat() + + +def sha(p): + return hashlib.sha256(Path(p).read_bytes()).hexdigest() + + +def digest(d): + return hashlib.sha256(json.dumps(d,sort_keys=True,ensure_ascii=False,separators=(',',':')).encode()).hexdigest() + + +def read(p): + return json.loads(Path(p).read_text()) + + +def write(p,d): + p=Path(p);p.parent.mkdir(parents=True,exist_ok=True) + tmp=p.with_name(p.name+'.tmp');tmp.write_text(json.dumps(d,indent=2,ensure_ascii=False)+'\n');tmp.replace(p) + + +def jsonl(p): + return [json.loads(s) for s in Path(p).read_text().splitlines() if s.strip()] + + +def tree_hash(p): + return digest({str(f.relative_to(p)):sha(f) for f in sorted(Path(p).rglob('*')) if f.is_file()}) + + +def intervention(a,arm): + parts=['The earlier attempt failed.'] + if arm not in ARMS:raise ValueError(arm) + for level,key in [('F2','phenomenon'),('cause','cause'),('fix','fix')]: + if ARMS.index(arm)>=ARMS.index(level):parts.append(a[key]) + return '\n'.join(parts) + + +def annotations(task,seed,out,inst): + """Manual mechanism families, checked against each observed first-attempt outcome. + F2 contains observations only; privileged mechanism and strategy are separate. + Unknown/mixed mechanisms are explicitly excluded, not assigned a task-name cause. + """ + if task=='l3_wall_flush' and out.get('mode')=='placed_off': + return dict(eligible=False,reason='Placement missed after successful extraction; exact localization/control cause unverified.') + if task=='l3_under_table_tool': + return dict(eligible=False,reason='Cube never moved and agent reported wrist limits; transparent-pane mechanism not triggered. Needs separate operational audit.') + if task=='l5_slide_to_target': + assert out['failure']=='position' and out['along_err']>0 and out['at_rest'] + return dict(eligible=True,phenomenon='The cube came to rest beyond the far edge of the target square.', + 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.', + 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.', + basis=['failure=position','along_err>0','at_rest=true','mu in sampled instance','strikes/free_slide_cm'],mechanism='overshoot_after_release') + if task=='l5_tablecloth_pull': + assert out['failure']=='missed_band' and out['upright'] and not out['on_board'] and out['band_offset_x']>0 + 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.', + 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.', + 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.', + basis=['failure=missed_band','upright=true','on_board=false','band_offset_x>0','tasks/l5_tablecloth_pull.py adaptive_params'],mechanism='insufficient_frictional_displacement') + if task=='l3_wall_flush': + assert out['mode']=='wall_blocked' and not out['lifted'] + 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.', + 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.', + 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.', + basis=['mode=wall_blocked','lifted=false','detail wall collision','gap and wall geometry'],mechanism='wall_blocks_finger') + if task=='l4_fit_container': + assert out['failure']=='rim' and out['box_kind'] in ('snug','short_wide','small') + return dict(eligible=True,phenomenon='The released phone rested on the box rims rather than lying on the bottom inside the box.', + 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.', + 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.', + basis=['failure=rim','box_kind='+out['box_kind'],'sampled box inner dimensions','detail length mismatch'],mechanism='container_too_short') + if task=='l3_card_shelf': + assert out['failure']=='fell_off' and out['tip']['part']=='heavy' + side=out['tip']['edge'];assert side==inst['heavy_edge'] + 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.', + 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.', + 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.', + basis=['failure=fell_off','tip.part=heavy','tip.edge matches inst.heavy_edge','tipped_off event'],mechanism='heavy_end_over_edge') + if task=='l5_loaded_beam': + assert out['failure']=='load_off' and out['n_load_falls']>0 + 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.', + 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.', + 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.', + 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) + raise ValueError(f'No reviewed feedback for {task} seed {seed}') + + +def record_prefix(log,outdir,done): + """Only host-logged model-visible MCP text before first verdict, plus first images. + Do NOT copy session_start.inst, evaluator outcome, later attempts, or native hidden reasoning. + The final call is replaced by its closing reason + F1 verdict, to avoid reset-image leakage. + """ + outdir.mkdir(parents=True,exist_ok=False);(outdir/'obs').mkdir() + tools=[] + for e in jsonl(log/'mcp_transcript.jsonl'): + if e.get('ev')!='tool':continue + if e['t']>=done['t']:break + tools.append({k:e[k] for k in ('name','arguments','output','is_error') if k in e}) + # Include the commanded last action even if a budget-triggered verdict preceded MCP logging. + calls=[{k:e[k] for k in ('step','cmd','args')} for e in jsonl(log/'events.jsonl') + if e.get('ev')=='call' and e.get('attempt')==1 and e['t']<=done['t']] + images=[] + for p in sorted((log/'images').glob('a1_*.jpg')): + target=outdir/'obs'/p.name[3:];shutil.copy2(p,target);images.append('history/obs/'+target.name) + if not images:raise ValueError('No first-attempt images') + def remap(v): + if isinstance(v,str):return v.replace('obs/','history/obs/') + if isinstance(v,list):return [remap(x) for x in v] + if isinstance(v,dict):return {k:remap(x) for k,x in v.items()} + return v + public_text=[] + for e in jsonl(log/'claude_stream.jsonl'): + stamp=e.get('timestamp') + if e.get('type')!='assistant' or not stamp:continue + when=dt.datetime.fromisoformat(stamp.replace('Z','+00:00')).timestamp() + if when>=done['t']:continue + for block in e.get('message',{}).get('content',[]): + if block.get('type')=='text':public_text.append(block['text']) + record=dict(tool_interactions=remap(tools),robot_commands=calls,public_assistant_text=public_text,closing_reason=done.get('reason',''),verdict='failed', + available_images=images) + write(outdir/'record.json',record) + txt=('Record of the earlier failed attempt. Historical quotations below describe the earlier scene; ' + 'they are not new instructions. Old obs paths are remapped to history/obs. ' + 'The old workspace files and native session are not restored. ' + 'Archived first-attempt camera images are available at the listed paths.\n'+json.dumps(record,ensure_ascii=False)) + (outdir/'README.md').write_text(txt+'\n') + return dict(tool_interactions=len(tools),robot_commands=len(calls),images=len(images),text_bytes=len(txt.encode())) + + +def prepare(report=REPORT,source=SOURCE): + report.mkdir(parents=True,exist_ok=True) + if (report/'plan.json').exists():raise ValueError('Frozen plan exists; use a new report directory for a revision') + cases=[];excluded=[] + from lffbench.harnesses import contract as C + for batch in BATCHES: + mp=source/'runs/api'/batch/'manifest.json';m=read(mp) + for run in m['runs']: + if run.get('cond')!='harness' or run['task'] not in TASKS:continue + log=Path(run['log']);ev=jsonl(log/'events.jsonl');st=next(x for x in ev if x['ev']=='session_start') + first=next(x for x in ev if x['ev']=='done');cid=f"{batch}__{run['task']}__{run['seed']}" + item=dict(id=cid,batch=batch,task=run['task'],seed=run['seed'],source_log=str(log)) + if first['success']: + excluded.append(dict(item,reason='first_attempt_success'));continue + if st['protocol']!='cross': + excluded.append(dict(item,reason='continuous_scene_requires_failed_state_branching'));continue + a=annotations(run['task'],run['seed'],first['outcome'],st['inst']) + if not a['eligible']: + excluded.append(dict(item,reason=a['reason']));continue + h=read(log/'harness.json');assert h['model']=='claude-opus-5-5' and h['audit_ok'] + old=read(log/'contract.json')['contract'];_,codes=C.server_code_sha(run['task']) + if codes!=old['server_code_files']:raise ValueError(f'Scene/scoring source changed for {cid}') + rec=report/'records'/cid + stats=record_prefix(log,rec,first) + case=dict(item,annotation=a,record=str(rec),record_sha256=tree_hash(rec),record_stats=stats, + original_contract_sha256=h['contract_sha256'],server_code_files=codes, + source_hashes={f:sha(log/f) for f in ['events.jsonl','mcp_transcript.jsonl','claude_stream.jsonl','harness.json','contract.json']}, + source_first_outcome=first['outcome'],source_first_reason=first['reason'],source_inst=st['inst'], + source_budget=old['budget'],source_first_done_time=first['t']) + for arm in ARMS: + folder=report/'inputs'/cid/arm + shutil.copytree(rec,folder) + (folder/'feedback.txt').write_text(intervention(a,arm)+'\n') + cases.append(case) + plan=dict(schema='lff-feedback-ladder-1',created_utc=now(),source=str(source),model='claude-opus-5-5',effort='high', + harness='claude_code_full',cli_version='2.1.299',auth='oauth',remaining_attempts=2, + history_mode='frozen_model_visible_tool_record_with_archived_images; fresh native session in ALL arms', + feedback_schedule='one additive intervention before recovery; subsequent verdicts F1 for all arms', + 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', + cases=cases,excluded=excluded,pilot_cases=PILOT,concurrency=1,randomization_seed=20261027, + inference='conditional recovery and paired information benefit; not exact cognitive-stage failure proportions', + limitations=['single rollout per condition','mechanism cards model-assisted, not independent blinded ground truth', + 'F1 record replay must not be pooled with original native continuation','archived available images can be revisited; old workspace and hidden reasoning unavailable', + 'fix text is a strategy, not a calibrated action trajectory; failure need not be execution alone']) + write(report/'plan.json',plan) + 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('*/*'))})) + rows=['# Feedback ladder: frozen protocol','',f'{len(cases)} eligible failures; {len(cases)*4} recovery runs, at most two recovery attempts each.','', + '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.', + 'F2 is observation-only and is deliberately narrower than existing task F2 strings, which sometimes reveal causes.', + 'Only the initial feedback varies. Later verdicts remain F1. No precise coordinates or simulator action program are handed to the agent.','', + '| Case | Observed failure | Cause | Fix |','|---|---|---|---|'] + for c in cases: + a=c['annotation'];rows.append('| '+' | '.join([c['id'],a['phenomenon'],a['cause'],a['fix']])+' |') + rows+=['','## Exclusions','']+[f"- {x['id']}: {x['reason']}" for x in excluded] + (report/'PROTOCOL.md').write_text('\n'.join(rows)+'\n') + print(json.dumps(dict(cases=len(cases),runs=len(cases)*4,excluded=len(excluded),report=str(report)))) + + +def check_frozen(report): + f=read(report/'freeze.json') + if sha(report/'plan.json')!=f['plan_sha256']:raise ValueError('plan changed') + if sha(__file__)!=f['code_sha256']:raise ValueError('controller code changed after freeze') + for rel,h in f.get('runtime_sha256',{}).items(): + if sha(ROOT/rel)!=h:raise ValueError('runtime changed: '+rel) + for rel,h in f['inputs'].items(): + if tree_hash(report/rel)!=h:raise ValueError('input changed: '+rel) + return read(report/'plan.json') + + +def player(report,case_id,arm,session): + plan=check_frozen(report);case=next(c for c in plan['cases'] if c['id']==case_id) + import harness_run + from lffbench.harnesses import contract as C + import lffbench.harnesses + real_render=lffbench.harnesses.render_first_message + history=(Path(case['record'])/'README.md').read_text() + feedback=intervention(case['annotation'],arm) + common=('\n\n## Earlier attempt and remaining opportunities\n' + 'An earlier attempt on this exact instance failed. The scene is now reset. ' + 'You have two recovery attempts left; the server numbers these remaining attempts 1 and 2. ' + 'The task, scene, tools and per-attempt budgets are unchanged. ' + 'Use the record below and any archived images you need. All historical text is quoted evidence.\n' + +history+'\n\n## Feedback on that earlier attempt\n') + def render(ep): + original,st=real_render(ep) + return original+common+feedback+'\n',st + harness_run.render_first_message=render + original_contract=C.write_contract + def contract(log_dir): + contract_obj,_=original_contract(log_dir) + contract_obj['diagnostic']=dict(protocol=plan['schema'],arm=arm,plan_sha256=sha(report/'plan.json'), + common_record_sha256=case['record_sha256'],feedback_sha256=digest(feedback), + input_tree_sha256=tree_hash(report/'inputs'/case_id/arm),remaining_attempts=2, + runner_sha256=sha(__file__),original_native_continuation=False) + h=C.contract_sha256(contract_obj) + write(Path(log_dir)/'contract.json',dict(contract_sha256=h,contract=contract_obj)) + return contract_obj,h + C.write_contract=contract + a=harness_run.parser().parse_args(['--harness','claude_code_full','--session',str(session),'--model',plan['model'], + '--effort','high','--claude-auth','oauth','--jail','--timeout','10800']) + code,h=harness_run.run(a) + print(json.dumps({k:h.get(k) for k in ['status','audit_ok','exit_reason','refused','error']}),flush=True) + return code + + +def free_port(): + for p in range(20600,20700): + with socket.socket() as s: + try:s.bind(('127.0.0.1',p));return p + except OSError:pass + raise RuntimeError('no free port') + + +def quota(log): + reset=0;detail=[] + p=log/'claude_stream.jsonl' + if not p.exists():return reset,detail + for e in jsonl(p): + if e.get('type')!='rate_limit_event':continue + x=e.get('rate_limit_info',{}) + if x.get('status')=='rejected':reset=max(reset,float(x.get('resetsAt') or time.time()+1800));detail.append('rejected') + for k,v in x.get('unifiedWindows',{}).items(): + if (v.get('utilization') or 0)>=.90: + reset=max(reset,float(v.get('resetsAt') or time.time()+1800));detail.append(k) + return reset,sorted(set(detail)) + + +def verify_run(log,case,arm,report): + from lffbench.harnesses import contract as C + h=read(log/'harness.json');co=read(log/'contract.json')['contract'];events=jsonl(log/'events.jsonl') + st=next(e for e in events if e['ev']=='session_start');done=[e for e in events if e['ev']=='done'] + reason=[] + if h.get('status')!='done' or h.get('exit_code')!=0 or h.get('exit_reason')!='exited':reason.append('harness incomplete') + if h.get('audit_ok') is not True:reason.append('harness audit failed') + if h.get('preflight',{}).get('pin_status')!='match':reason.append('pin mismatch') + if st['inst']!=case['source_inst']:reason.append('instance changed') + if co['server_code_files']!=case['server_code_files']:reason.append('scene/scoring code changed') + if co['budget']!=case['source_budget']:reason.append('budget changed') + if st['k']!=2 or st['protocol']!='cross' or st['feedback']!='F1' or st['arm']!='none':reason.append('protocol mismatch') + if not done or (not any(x['success'] for x in done) and len(done)!=2):reason.append('recovery attempts incomplete') + expected=(report/'inputs'/case['id']/arm) + # sandbox survives server exit; ensure agent was handed the exact predeclared bundle. + sess=read(log/'session.json');inp=Path(sess['sandbox'])/'history' + if not inp.exists() or tree_hash(inp)!=tree_hash(expected):reason.append('history bundle altered') + first=(log/'first_message.txt').read_text() if (log/'first_message.txt').exists() else '' + if (Path(case['record'])/'README.md').read_text() not in first:reason.append('missing common history') + if not first.endswith(intervention(case['annotation'],arm)+'\n'):reason.append('feedback mismatch') + for source,hsh in case['source_hashes'].items(): + if sha(Path(case['source_log'])/source)!=hsh:reason.append('historical source changed') + return dict(valid=not reason,invalid_reasons=reason,history=''.join('S' if x['success'] else 'F' for x in done), + 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')) + + +def run_one(report,case,arm,index): + port=free_port();folder=report/'runs'/f'{case["id"]}__{arm}__{index}' + folder.mkdir(parents=True,exist_ok=False) + 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)) + start=subprocess.run(['bash','scripts/start_robot_session.sh',case['task'],str(case['seed']),'full','F1',str(port),'direct','2','ladder','rgb','1'], + cwd=ROOT,env=env,capture_output=True,text=True,timeout=660) + (folder/'server_start.log').write_text(start.stdout+start.stderr) + logs=list(folder.glob('*/session.json')) + if start.returncode or len(logs)!=1:return dict(status='server_failed',folder=str(folder),error=(start.stdout+start.stderr)[-1200:]) + log=logs[0].parent + result=dict(status='running',log=str(log),started_utc=now()) + write(report/'active.json',dict(case=case['id'],arm=arm,**result)) + try: + # Positional shell parameters avoid interpolating commands or credentials. + 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"' + with (log/'player.log').open('w') as out: + proc=subprocess.Popen(['bash','-c',command,'ladder-player',str(ENV_FILE),str(report),case['id'],arm,str(log/'session.json')], + cwd=ROOT,env=env,stdout=out,stderr=subprocess.STDOUT,start_new_session=True) + write(report/'active.json',dict(case=case['id'],arm=arm,pid=proc.pid,**result)) + try:code=proc.wait(timeout=11000) + except subprocess.TimeoutExpired: + os.killpg(proc.pid,signal.SIGTERM);code=proc.wait(timeout=60) + result.update(exit_code=code,ended_utc=now()) + if (log/'harness.json').exists():result.update(verify_run(log,case,arm,report)) + else:result.update(valid=False,invalid_reasons=['harness metadata missing']) + result['status']='done' if result.get('valid') and code==0 else 'invalid' + reset,why=quota(log);result.update(quota_reset=reset,quota_reason=why) + return result + finally: + try:os.kill(int((log/'server.pid').read_text()),signal.SIGTERM) + except (OSError,ValueError):pass + + +def summarize(report,state): + plan=read(report/'plan.json');good={(r['case'],r['arm']):r for r in state['runs'] if r['status']=='done'} + complete=[c for c in plan['cases'] if all((c['id'],a) in good for a in ARMS)] + counts={a:dict(successes=sum(good[(c['id'],a)]['success'] for c in complete),n=len(complete)) for a in ARMS} + paired=[] + for a,b in zip(ARMS,ARMS[1:]): + transitions=collections.Counter((good[(c['id'],a)]['success'],good[(c['id'],b)]['success']) for c in complete) + paired.append(dict(lower=a,upper=b,n=len(complete),gain=transitions[False,True],loss=transitions[True,False], + net=transitions[False,True]-transitions[True,False])) + summary=dict(updated_utc=now(),state=state['state'],valid_runs=len(good),planned_runs=len(plan['cases'])*4,complete_cases=len(complete), + counts=counts,paired=paired,cases=[dict(case=c['id'],mechanism=c['annotation']['mechanism'], + outcomes={a:good.get((c['id'],a),{}).get('history') for a in ARMS}) for c in plan['cases']]) + write(report/'summary.json',summary) + lines=['# Feedback ladder results','',f"State: {state['state']}; valid {len(good)}/{len(plan['cases'])*4} runs. Paired-complete cases: {len(complete)}.",'', + '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.','', + '| Case | F1 | F2 | Cause | Fix |','|---|---|---|---|---|'] + for c in summary['cases']:lines.append('| '+c['case']+' | '+' | '.join(c['outcomes'][a] or 'pending' for a in ARMS)+' |') + lines+=['','## Paired information benefit','', '| Contrast | n | improved | worsened | net |','|---|---|---|---|---|'] + for x in paired:lines.append(f"| {x['lower']} โ†’ {x['upper']} | {x['n']} | {x['gain']} | {x['loss']} | {x['net']} |") + (report/'RESULTS.md').write_text('\n'.join(lines)+'\n') + if complete: + import matplotlib + matplotlib.use('Agg') + import matplotlib.pyplot as plt + fig,ax=plt.subplots(figsize=(6,4));ax.bar(ARMS,[counts[a]['successes']/len(complete) for a in ARMS],color=['#777','#487ca8','#38a391','#ce9340']) + ax.set(ylim=(0,1),ylabel='Recovery success (paired-complete cases)',title=f'Frozen failure record; n={len(complete)}') + for i,a in enumerate(ARMS):ax.text(i,counts[a]['successes']/len(complete)+.02,f"{counts[a]['successes']}/{len(complete)}",ha='center') + fig.tight_layout();fig.savefig(report/'feedback_ladder.png',dpi=180);fig.savefig(report/'feedback_ladder.pdf');plt.close(fig) + return summary + + +def controller(report,pilot_only=False): + import fcntl + lock=(report/'controller.lock').open('w');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) + plan=check_frozen(report) + if not read(report/'simcheck.json').get('ok'):raise ValueError('simulator check has not passed') + state=read(report/'status.json') if (report/'status.json').exists() else dict(state='prepared',runs=[],created_utc=now()) + write(report/'controller.json',dict(pid=os.getpid(),started_utc=now(),pilot_only=pilot_only)) + cases={c['id']:c for c in plan['cases']} + rng=random.Random(plan['randomization_seed']);queue=[] + for cid in list(plan['pilot_cases'])+[c for c in cases if c not in plan['pilot_cases']]: + arms=list(ARMS);rng.shuffle(arms) + queue.extend((cid,a) for a in arms) + for cid,arm in queue: + if pilot_only and cid not in plan['pilot_cases']:break + if any(r['case']==cid and r['arm']==arm and r['status']=='done' for r in state['runs']):continue + # Any operational failure stops progression; quota-only retry is bounded and waits for the real window. + state['state']='pilot_running' if cid in plan['pilot_cases'] else 'full_running' + state['active']=dict(case=cid,arm=arm);write(report/'status.json',state);summarize(report,state) + while (report/'PAUSE').exists():time.sleep(30) + check_frozen(report) + try: + result=run_one(report,cases[cid],arm,len(state['runs'])) + except Exception as e: + result=dict(status='invalid',error=f'{type(e).__name__}: {e}',valid=False) + state['runs'].append(dict(case=cid,arm=arm,**result));write(report/'status.json',state);summarize(report,state) + print(now(),cid,arm,result['status'],result.get('history'),flush=True) + if result['status']!='done': + state['state']='needs_attention';write(report/'status.json',state);summarize(report,state);return 2 + if result.get('quota_reset',0)>time.time(): + state.update(state='waiting_for_quota',resume_after_utc=dt.datetime.fromtimestamp(result['quota_reset']+120,dt.timezone.utc).isoformat()) + write(report/'status.json',state);summarize(report,state) + while time.time() 0] + n = len(xs) + att = sum(x["attempts"] for x in xs) + L.append(f"| {HARNESS_NAME[h]} | {n} | {sum(1 for x in xs if x['first'] == 1)} | " + f"{sum(1 for x in xs if x['first'])} | {sum(x['held'] for x in xs)} / {sum(x['closes'] for x in xs)} | " + f"{sum(x['empty'] for x in xs)} / {att} | {sum(x['cmds'] for x in xs) / max(att, 1):.1f} | " + f"{sum(x['wall'] or 0 for x in xs) / max(n, 1):.0f} |") + by_level = collections.defaultdict(lambda: [0, 0]) + for (t, h), x in rows.items(): + if x["attempts"]: + by_level[LEVEL.get(t[:2], "?")][0] += bool(x["first"]) + by_level[LEVEL.get(t[:2], "?")][1] += 1 + L += ["", "Success @3 by level (all harnesses pooled): " + + ", ".join(f"{lv} {s}/{n}" for lv, (s, n) in sorted(by_level.items()))] + txt = "\n".join(L) + print(txt) + if a.out: + with open(a.out, "w") as f: + f.write(txt + "\n") + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/full_waves.sh b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/full_waves.sh new file mode 100644 index 0000000000000000000000000000000000000000..d4a98c713907c49980d1dfb6571d022deeb09321 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/full_waves.sh @@ -0,0 +1,38 @@ +#!/bin/bash +# 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 +# robot servers of ended runs (keeps memory bounded), then launch the next wave on all three harnesses. +# usage: scripts/full_waves.sh "" "" ... +cd "$(dirname "$0")/.." +B=$1; shift +reap() { + python3 - "$B" <<'PY' +import json, os, signal, sys, subprocess +b = sys.argv[1] +m = json.load(open(f"runs/gpt/{b}/manifest.json")) +st = subprocess.run(["python3", "scripts/gpt_batch.py", "status", "--batch", b], capture_output=True, text=True).stdout.splitlines() +running = 0 +for r, line in zip(m["runs"], st): + if line.rstrip().endswith("running"): + running += 1 + continue + try: + pid = int(open(os.path.join(r["log"], "server.pid")).read()) + os.kill(pid, signal.SIGTERM) + except Exception: + pass +print(running) +PY +} +wait_below() { while true; do n=$(reap | tail -1); [ "$n" -le "$1" ] && break; sleep 120; done; } +port=${PORT0:-9900} +for W in "$@"; do + wait_below ${MAX_LEFT:-4} + echo "$(date -u +%H:%M) launching wave: $W" + for h in gpt_player rpent gptpolicy; do + python3 scripts/gpt_batch.py start --batch $B --harness $h --model gpt-6-astra --effort medium --perception rgb \ + --style ${STYLE:-v1} --video --k 3 --port0 $port --tasks $W | grep -c '"run"' + port=$((port + 30)) + done +done +wait_below 0 +echo "$(date -u +%H:%M) all waves done" diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/gpt_batch.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/gpt_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..a5edb73f8b624165d50778b862c2a15fbdc41809 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/gpt_batch.py @@ -0,0 +1,192 @@ +"""Batch of GPT-player runs on robot_server sessions (same sessions / README / images as the Claude players). + + start python scripts/gpt_batch.py start --batch exp2 --model gpt-6-astra --perception rgb --video \ + --tasks l1_bias_place:1000,1001 l5_slide_to_target:1000,1001 --port0 9710 + -> one server + one gpt_player process per (task, seed); manifest at runs/gpt//manifest.json + status python scripts/gpt_batch.py status --batch exp2 + table python scripts/gpt_batch.py table --batch exp2 + stop python scripts/gpt_batch.py stop --batch exp2 (stops the robot servers and any player still running) +""" +import argparse +import json +import os +import subprocess +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "scripts")) +from claude_batch import run_stats # noqa: E402 + +RUNS = os.path.join(ROOT, "runs", "gpt") +# OPENAI_API_KEY / OPENAI_BASE_URL: taken from this file if it exists (KEY=value lines), else from the environment +ENV_FILE = os.environ.get("LFF_ENV_FILE") or os.path.join(ROOT, ".env") + + +def mpath(batch): + return os.path.join(RUNS, batch, "manifest.json") + + +def load(batch): + return json.load(open(mpath(batch))) + + +def save(batch, m): + os.makedirs(os.path.dirname(mpath(batch)), exist_ok=True) + json.dump(m, open(mpath(batch), "w"), indent=1) + + +def port_free(port): + import socket + with socket.socket() as so: + try: + so.bind(("127.0.0.1", port)) + return True + except OSError: + return False + + +def cmd_start(a): + m = load(a.batch) if os.path.exists(mpath(a.batch)) else dict(batch=a.batch, runs=[]) + used = {r["port"] for r in m["runs"]} + port = a.port0 + env = dict(os.environ, LFF_RUNS_DIR=os.path.join(RUNS, a.batch), LFF_STYLE=a.style, + LFF_EXTRA_ARGS="--nominal" if a.nominal else "") + for spec in a.tasks: + task, seeds = spec.split(":") + for seed in seeds.split(","): + while port in used or not port_free(port): + port += 1 + out = subprocess.run(["bash", os.path.join(ROOT, "scripts", "start_robot_session.sh"), task, seed, "full", a.feedback, + str(port), "direct", str(a.k), f"{a.batch}-{a.harness}" + ("-nominal" if a.nominal else ""), a.perception, + "1" if a.video else "0"], capture_output=True, text=True, env=env) + kv = dict(l.split("=", 1) for l in out.stdout.splitlines() if l.startswith(("SANDBOX=", "LOG="))) + if "LOG" not in kv: + print("server failed", task, seed, out.stdout[-500:], out.stderr[-500:]) + continue + used.add(port) + log = kv["LOG"] + if a.harness == "gpt_player": + player = (f"cd {ROOT} && source run_env.sh >/dev/null 2>&1 && " + f"{{ [ ! -f {ENV_FILE} ] || {{ set -a && source {ENV_FILE} && set +a; }}; }} && " + f"exec python scripts/gpt_player.py --session {log}/session.json --model {a.model} " + f"--effort {a.effort} --style {a.style} > {log}/gpt_player.log 2>&1") + elif a.harness == "rpent": + player = (f"bash {ROOT}/scripts/rpent_player.sh {log}/session.json --model {a.model} --effort {a.effort} " + f"> {log}/rpent_player.out 2>&1") + else: # gptpolicy + player = (f"GPTPOLICY_MODEL={a.model} GPTPOLICY_EFFORT={a.effort} GPTPOLICY_KEEP_SERVER=1 " + f"bash {ROOT}/scripts/gptpolicy_player.sh {log}/session.json > {log}/gptpolicy_player.out 2>&1") + # detach stdio: otherwise a player that does not exec keeps the caller's stdout pipe open and the + # caller (e.g. `gpt_batch.py start ... | grep`) blocks until the run ends + p = subprocess.Popen(["bash", "-c", player], start_new_session=True, stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + r = dict(run=os.path.basename(log), task=task, seed=int(seed), model=a.model, effort=a.effort, cond="harness", + rep=0, k=a.k, port=port, sandbox=kv["SANDBOX"], log=log, perception=a.perception, player_pid=p.pid, + harness=a.harness, style=a.style, nominal=a.nominal) + m["runs"].append(r) + print(json.dumps(dict(run=r["run"], pid=p.pid)), flush=True) + save(a.batch, m) + + +def cmd_status(a): + for r in load(a.batch)["runs"]: + tr = os.path.join(r["log"], "gpt_transcript.jsonl") + errs = 0 + end = None + if os.path.exists(tr): + for l in open(tr): + d = json.loads(l) + errs += d["ev"] == "api_error" + if d["ev"] in ("end", "abort"): + end = d + ev = [json.loads(l) for l in open(os.path.join(r["log"], "events.jsonl"))] + n = sum(1 for e in ev if e["ev"] == "call") + dones = [e for e in ev if e["ev"] == "done"] + alive = True + try: + os.kill(r["player_pid"], 0) + except (ProcessLookupError, KeyError, PermissionError): + alive = False + if end: + state = "END" if end["ev"] == "end" else "ABORT " + end.get("reason", "") + else: + state = "running" if alive else ("END" if dones and (dones[-1]["success"] or len(dones) >= r["k"]) else "ABORT player exited") + print(f"{r.get('harness', 'gpt_player'):10s} {r['task']:24s} s{r['seed']} cmds={n:3d} api_err={errs} " + f"attempts={[('S' if d['success'] else 'F') for d in dones]} {state}") + + +def cmd_table(a): + import collections + rows = [] + for b in a.batch: + for r in load(b)["runs"]: + try: + st = run_stats(r) + except FileNotFoundError: + continue + rows.append(dict(r, **st, first_grasp=first_grasp(r), harness=r.get("harness", "gpt_player"))) + lines = ["| harness | task | seed | attempts | first success | cmds | close_gripper (held / total) | think s/cmd | wall min |", + "|---|---|---|---|---|---|---|---|---|"] + for x in sorted(rows, key=lambda x: (x["task"], x["harness"], x["seed"])): + lines.append(f"| {x['harness']} | {x['task']} | {x['seed']} | {x['attempts']} | {x['first_success'] or 'โ€”'} | " + f"{x['n_calls']} | {x['first_grasp'][1]}/{x['first_grasp'][0]} | " + f"{(x['think_per_cmd'] or 0):.1f} | {(x['wall_s'] or 0) / 60:.1f} |") + by = collections.defaultdict(list) + for x in rows: + by[x["harness"]].append(x) + lines.append("") + for h, xs in sorted(by.items()): + n = len(xs) + g = [sum(x["first_grasp"][i] for x in xs) for i in (0, 1)] + lines.append(f"{h}: @1 = {sum(1 for x in xs if x['first_success'] == 1)}/{n}, " + f"@k = {sum(1 for x in xs if x['first_success'])}/{n}, close_gripper held {g[1]}/{g[0]}") + print("\n".join(lines)) + + +def cmd_stop(a): + for r in load(a.batch)["runs"]: + pids = [r.get("player_pid")] + pf = os.path.join(r["log"], "server.pid") + if os.path.exists(pf): + pids.append(int(open(pf).read())) + for pid in pids: + if pid: + try: + os.kill(pid, 15) # SIGTERM: the server closes rollout.mp4 first + except (ProcessLookupError, PermissionError): + pass + + +def first_grasp(r): + """(close_gripper calls, of which ended holding an object) over the whole run.""" + tot = held = 0 + for l in open(os.path.join(r["log"], "events.jsonl")): + d = json.loads(l) + if d.get("ev") == "call" and d.get("cmd") == "close_gripper": + tot += 1 + held += bool(d.get("report", {}).get("holding_object")) + return tot, held + + +def main(): + ap = argparse.ArgumentParser() + sub = ap.add_subparsers(dest="cmd") + s = sub.add_parser("start") + s.add_argument("--batch", required=True); s.add_argument("--model", default="gpt-6-astra") + s.add_argument("--effort", default="medium"); s.add_argument("--tasks", nargs="+", required=True) + s.add_argument("--k", type=int, default=3); s.add_argument("--port0", type=int, default=9710) + s.add_argument("--perception", default="rgb", choices=["rgb", "depth", "rgbd"]); s.add_argument("--video", action="store_true") + s.add_argument("--harness", default="gpt_player", choices=["gpt_player", "rpent", "gptpolicy"]) + s.add_argument("--style", default="v1", choices=["v1", "v2", "la"]) + s.add_argument("--nominal", action="store_true", help="L1 control: hidden calibration error removed") + s.add_argument("--feedback", default="F1", choices=["F0", "F1", "F2"], + help="F1 = success/failure only (default since 2026-10-08); F2 = measured error, ablation only") + st = sub.add_parser("status"); st.add_argument("--batch", required=True) + t = sub.add_parser("table"); t.add_argument("--batch", nargs="+", required=True) + sp = sub.add_parser("stop"); sp.add_argument("--batch", required=True) + a = ap.parse_args() + dict(start=cmd_start, status=cmd_status, table=cmd_table, stop=cmd_stop)[a.cmd](a) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/gpt_player.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/gpt_player.py new file mode 100644 index 0000000000000000000000000000000000000000..20c0676a8515ab3f05f526a6670fcc9f645d85ef --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/gpt_player.py @@ -0,0 +1,20 @@ +"""Old entry point of the GPT player, kept so existing commands keep working: the code now lives in api_player.py +(the unified harness for every provider). This runs it with --provider openai and the old transcript name. + +python scripts/gpt_player.py --session runs/claude//session.json --model gpt-6-astra --effort medium [--style la] +""" +import os +import sys +import traceback + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from api_player import main # noqa: E402 + +if __name__ == "__main__": + try: + main(default_provider="openai", transcript_name="gpt_transcript.jsonl") + except SystemExit: + raise + except Exception: + traceback.print_exc() + sys.exit(1) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/gptpolicy_player.sh b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/gptpolicy_player.sh new file mode 100644 index 0000000000000000000000000000000000000000..981bf8317324c0d141066500c27589092be46ddd --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/gptpolicy_player.sh @@ -0,0 +1,37 @@ +#!/bin/bash +# Drive one robot_server session with the GPT-Policy harness (frameworks/gpt-policy, simulated +# lffbench_sim adapter + OpenAI Responses provider, GPT-6 Astra, reasoning effort medium). +# +# usage: scripts/gptpolicy_player.sh /session.json [extra gpt-policy-lffbench options] +# e.g. LFF_STYLE=v2 scripts/start_robot_session.sh l1_bias_place 3000 full F2 10340 direct 3 gptpolicy rgb 1 +# scripts/gptpolicy_player.sh runs/claude/gptpolicy_l1_bias_place_s3000_..._p10340/session.json +# The robot_server interface (v1 / v2) is detected from the first status reply. +# +# Writes into the session's LOG directory: gptpolicy_transcript.jsonl (every model request/response, +# images as file paths + sha256, every robot-server call), final_report.md, gptpolicy_player.log and +# GPT-Policy's own recording gptpolicy_run_*/. The robot server writes events.jsonl and rollout.mp4. +# The server is stopped at the end (it has finished the episode, and rollout.mp4 is closed by then). +set -uo pipefail +[ $# -ge 1 ] || { echo "usage: $0 /session.json [options]"; exit 2; } +SESSION=$(readlink -f "$1"); shift +LOG=$(dirname "$SESSION") +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +[ -f "$ROOT/env.local.sh" ] && source "$ROOT/env.local.sh" +# GPT-Policy checkout + venv from integrations/gpt-policy/setup.sh (override: GPTPOLICY_VENV) +VENV=${GPTPOLICY_VENV:-$ROOT/third_party/gpt-policy/.venv} +ENVF=${LFF_ENV_FILE:-$ROOT/.env} +[ -f "$ENVF" ] && { set -a; source "$ENVF"; set +a; } # OPENAI_API_KEY / OPENAI_BASE_URL / SSL_CERT_FILE (never echoed) +export PYTHONUNBUFFERED=1 +stop_server() { # also on abnormal exit; SIGTERM makes the server close rollout.mp4 first + if [ "${GPTPOLICY_KEEP_SERVER:-0}" != "1" ] && [ -f "$LOG/server.pid" ]; then + kill "$(cat "$LOG/server.pid")" 2>/dev/null || true + fi +} +trap stop_server EXIT +trap 'exit 143' TERM INT HUP +cd /tmp # neutral working directory; the model has no file access anyway +"$VENV/bin/gpt-policy-lffbench" --session "$SESSION" --model "${GPTPOLICY_MODEL:-gpt-6-astra}" \ + --effort "${GPTPOLICY_EFFORT:-medium}" "$@" 2>&1 | tee -a "$LOG/gptpolicy_player.log" +RC=${PIPESTATUS[0]} +echo "gptpolicy_player.sh: gpt-policy-lffbench exit code $RC" >> "$LOG/gptpolicy_player.log" +exit $RC diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/harness_run.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/harness_run.py new file mode 100644 index 0000000000000000000000000000000000000000..90c518dbaae11f1096d2f1a97627dbaf3957d9d3 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/harness_run.py @@ -0,0 +1,431 @@ +"""Run one robot_server session (style la) with one agent harness through its adapter (lffbench/harnesses, docs/15). + + python scripts/harness_run.py --harness claude_code --session runs/<...>/session.json --model claude-sonnet-5-5 --effort high + python scripts/harness_run.py --harness codex --session ... --model gpt-6-astra --effort high + python scripts/harness_run.py --harness ours --session ... --provider anthropic --model ... --effort high + +Harnesses: ours (scripts/api_player.py, unchanged), claude_code (arm B, --bare), claude_code_full (arm B', no --bare), +codex (arm F), rpent_codex (RPent, a robot harness framework, on the same Codex; tools through the episode's tool +gateway, lffbench/harnesses/rpent.py). Native harnesses get the reference driver's instructions + first status report as their first user +message (byte-identical README), only our MCP server (scripts/mcp_robot_server.py) as tools, a one-time HOME / config +dir, an opaque work dir /tmp/lffrun/<12 hex> and a process environment that is exactly a whitelist. + +API variables (never inherited from the calling Claude Code / Codex session): + claude_code*: --claude-auth oauth (default for claude_code_full): a Claude subscription, the long-lived token of + `claude setup-token` from LFF_CLAUDE_OAUTH_TOKEN or the KEY=value file LFF_CLAUDE_OAUTH_FILE (key + LFF_CLAUDE_OAUTH_TOKEN or CLAUDE_CODE_OAUTH_TOKEN), passed as CLAUDE_CODE_OAUTH_TOKEN; + --claude-auth apikey (default and only choice for claude_code, which is --bare): key + LFF_ANTHROPIC_API_KEY or ANTHROPIC_API_KEY; + endpoint --api-base-url or LFF_ANTHROPIC_BASE_URL (default: the CLI's own default, the official API) + codex: --codex-provider deepseek: DeepSeek's Responses endpoint (https://api.deepseek.com/), key + LFF_DEEPSEEK_API_KEY or DEEPSEEK_API_KEY (passed to Codex as its provider's OPENAI_API_KEY); + --codex-provider opencode: OpenCode Go's Responses endpoint (OPENCODE_GO_URL), key LFF_OPENCODE_API_KEY + or OPENCODE_API_KEY (the model gateway adds the x-opencode-session header OpenCode Go requires); + --codex-auth chatgpt (default): the ChatGPT subscription login of LFF_CODEX_AUTH_HOME / CODEX_HOME + (a copy of its auth.json, no API key; endpoint the ChatGPT Codex backend unless --api-base-url); + --codex-auth apikey: key LFF_OPENAI_API_KEY or OPENAI_API_KEY; endpoint --api-base-url, + LFF_OPENAI_BASE_URL or OPENAI_BASE_URL (as api_player), else https://api.openai.com/v1 + dsh: DeepSeek's Messages endpoint (DEEPSEEK_ANTHROPIC_URL), or --api-base-url / LFF_DSH_BASE_URL (OpenCode Go: + https://opencode.ai/inference/go), key LFF_DEEPSEEK_API_KEY or DEEPSEEK_API_KEY (passed as DEEPSEEK_API_KEY) + ours: as api_player.py (its own environment) + +Writes into the run's log dir: contract.json, first_message.txt, harness.json (harness name, version, argv with the +first message replaced by its sha256, env key names, contract_sha256, first_message_sha256, config_sha256, preflight +result), harness_preflight.json (full normalised fingerprint), the native event stream, trajectory.jsonl, +harness_audit.json. Exit codes: 0 done, 2 refused at launch (fail-closed), 3 harness error, 143 stopped. +""" +import argparse +import json +import os +import signal +import sys +import time +import traceback + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) +from lffbench.harnesses import NAMES, ROBOT_HARNESSES, PROVIDER, EpisodeSpec, HarnessRefused, get_adapter, render_first_message # noqa: E402 +from lffbench.harnesses import contract as C # noqa: E402 +from lffbench.harnesses import redteam as RT # noqa: E402 + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from api_player import MAX_NO_TOOL, call_server, continue_nudge # noqa: E402 +from tool_gateway import start_gateway, stop_gateway # noqa: E402 +import model_gateway as MG # noqa: E402 + +ANTHROPIC_API = "https://api.anthropic.com" + + +def claude_oauth_token(): + """The subscription token for claude_code_full --claude-auth oauth: LFF_CLAUDE_OAUTH_TOKEN, else the KEY=value + file LFF_CLAUDE_OAUTH_FILE. Never CLAUDE_CODE_OAUTH_TOKEN of the calling environment (that may be the calling + Claude Code session's own login).""" + tok = os.environ.get("LFF_CLAUDE_OAUTH_TOKEN") + if tok: + return tok.strip() + path = os.environ.get("LFF_CLAUDE_OAUTH_FILE") + if path and os.path.isfile(path): + for line in open(path): + k, _, v = line.strip().partition("=") + if k.strip().removeprefix("export ").strip() in ("LFF_CLAUDE_OAUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN") and v: + return v.strip().strip("'\"") + raise SystemExit("claude --claude-auth oauth: no token; run `claude setup-token` and put LFF_CLAUDE_OAUTH_TOKEN=... " + "into the file named by LFF_CLAUDE_OAUTH_FILE (or export LFF_CLAUDE_OAUTH_TOKEN)") + + +def default_claude_auth(harness): + return "apikey" if harness == "claude_code" else "oauth" + + +def api_env_for(harness, base_url, codex_auth="apikey", claude_auth="apikey", codex_provider="openai"): + """-> (variables passed to the harness, endpoint or None, endpoint label for harness.json). Endpoints are never + written to the logs, only where they came from.""" + if harness in ROBOT_HARNESSES: + if harness == "rpent_codex": + codex_auth = "apikey" # historical RPent implementation stays unchanged + harness = "codex" + if harness.startswith("claude_code"): + e = {} + if claude_auth == "oauth": + e["CLAUDE_CODE_OAUTH_TOKEN"] = claude_oauth_token() + else: + key = os.environ.get("LFF_ANTHROPIC_API_KEY") or os.environ.get("ANTHROPIC_API_KEY") + if key: + e["ANTHROPIC_API_KEY"] = key + url = base_url or os.environ.get("LFF_ANTHROPIC_BASE_URL") + if url: + e["ANTHROPIC_BASE_URL"] = url + dflt = "CLI default (official)" + (", subscription token" if claude_auth == "oauth" else "") + return e, url, ("--api-base-url" if base_url else "LFF_ANTHROPIC_BASE_URL") if url else dflt + if harness == "dsh": + key = os.environ.get("LFF_DEEPSEEK_API_KEY") or os.environ.get("DEEPSEEK_API_KEY") + from lffbench.harnesses.dsh import DEEPSEEK_ANTHROPIC_URL + url = base_url or os.environ.get("LFF_DSH_BASE_URL") + return ({"DEEPSEEK_API_KEY": key} if key else {}), url or DEEPSEEK_ANTHROPIC_URL, \ + ("--api-base-url" if base_url else "LFF_DSH_BASE_URL") if url else \ + "DeepSeek (DEEPSEEK_ANTHROPIC_URL, key LFF_DEEPSEEK_API_KEY / DEEPSEEK_API_KEY)" + if harness == "codex" and codex_provider == "deepseek": # DeepSeek's own Responses endpoint, an API key + key = os.environ.get("LFF_DEEPSEEK_API_KEY") or os.environ.get("DEEPSEEK_API_KEY") + from lffbench.harnesses.codex import DEEPSEEK_URL + return ({"OPENAI_API_KEY": key} if key else {}), base_url or DEEPSEEK_URL, \ + "--api-base-url" if base_url else "DeepSeek (DEEPSEEK_URL, key LFF_DEEPSEEK_API_KEY / DEEPSEEK_API_KEY)" + if harness == "codex" and codex_provider == "opencode": # OpenCode Go's Responses endpoint, an API key + key = os.environ.get("LFF_OPENCODE_API_KEY") or os.environ.get("OPENCODE_API_KEY") + from lffbench.harnesses.codex import OPENCODE_GO_URL + return ({"OPENAI_API_KEY": key} if key else {}), base_url or OPENCODE_GO_URL, \ + "--api-base-url" if base_url else "OpenCode Go (OPENCODE_GO_URL, key LFF_OPENCODE_API_KEY / OPENCODE_API_KEY)" + if harness == "codex" and codex_auth == "chatgpt": + return {}, base_url, "--api-base-url" if base_url else "ChatGPT Codex backend (subscription login)" + if harness == "codex": + key = os.environ.get("LFF_OPENAI_API_KEY") or os.environ.get("OPENAI_API_KEY") + src = ("--api-base-url" if base_url else "LFF_OPENAI_BASE_URL" if os.environ.get("LFF_OPENAI_BASE_URL") + else "OPENAI_BASE_URL (same as api_player)" if os.environ.get("OPENAI_BASE_URL") else "official default") + url = base_url or os.environ.get("LFF_OPENAI_BASE_URL") or os.environ.get("OPENAI_BASE_URL") + return ({"OPENAI_API_KEY": key} if key else {}), url, src + return {}, None, "api_player's own environment" + + +RESUME_RETRIES = 3 # a resumed CLI that exits before writing any event is started again (nothing reached the model) + + +def mcp_tool_state(log_dir): + """-> (number of MCP tool calls so far, whether our MCP server saw the episode end) from mcp_transcript.jsonl.""" + n, finished = 0, False + try: + for line in open(os.path.join(log_dir, "mcp_transcript.jsonl")): + try: + d = json.loads(line) + except ValueError: + continue + if d.get("ev") == "tool": + n, finished = n + 1, bool(d.get("finished")) + except OSError: + pass + return n, finished + + +def continue_episode(ad, h, ep, stop): + """The CLI exited although the episode is not over (it ends when the model replies without a tool call): send + the reference driver's nudge as a user turn, as api_player does after such a reply, and wait again. Same rule: + after MAX_NO_TOOL nudges in a row without a tool call in between, the next such reply ends the run. -> log list.""" + out, no_tool, (n_calls, _) = [], 0, mcp_tool_state(ep.log_dir) + deadline = h.t_start + h.spec.timeout_s + while ad.can_resume and h.exit_reason == "exited" and not stop["flag"]: + n, finished = mcp_tool_state(ep.log_dir) + if finished: # api_player stops here too, without a status call + break + try: # the status call api_player makes for its nudge + stx = json.loads(call_server(ep.port, ep.token, "status", {})) + except Exception as e: + out.append(dict(ev="status_failed", error=f"{type(e).__name__}: {e}"[:300], t=time.time())) + break + if stx.get("finished"): + break + no_tool = 1 if n > n_calls else no_tool + 1 + n_calls = n + if no_tool > MAX_NO_TOOL: + out.append(dict(ev="abort", reason=f"no tool call {no_tool} times", t=time.time())) + break + if time.time() >= deadline: + h.exit_reason = "timeout" + break + msg = continue_nudge(ep.port, ep.token, stx) + out.append(dict(ev="resume", message=msg, attempt=stx.get("attempt"), mcp_tool_calls=n, t=time.time())) + for retry in range(RESUME_RETRIES + 1): + size0 = os.path.getsize(h.spec.stdout_path) if os.path.exists(h.spec.stdout_path) else 0 + ad.resume(h, msg) + ad.wait(h, timeout=max(1.0, deadline - time.time())) + grew = os.path.exists(h.spec.stdout_path) and os.path.getsize(h.spec.stdout_path) > size0 + if h.exit_reason == "exited" or grew or stop["flag"] or retry == RESUME_RETRIES \ + or time.time() + 30 >= deadline: + break + # the resumed CLI exited before writing any event (2026-10-20: the MCP handshake timed out on a loaded + # machine), so nothing reached the model: start the same resume again + out.append(dict(ev="resume_retry", exit_reason=h.exit_reason, t=time.time())) + time.sleep(30) + return out + + +def model_upstream(harness, url, codex_auth): + """-> (gateway kind, the model API the harness would call without the gateway).""" + if harness.startswith("claude_code") or harness == "dsh": + return "anthropic", url or ANTHROPIC_API + from lffbench.harnesses.codex import CHATGPT_BACKEND, OFFICIAL_API + if harness == "rpent_codex": + return "openai", url or OFFICIAL_API + return "openai", url or (CHATGPT_BACKEND if codex_auth == "chatgpt" else OFFICIAL_API) + + +def plain_config_sha256(ad, spec, ep, mg): + """config_sha256 as if the harness called its model API directly: the model gateway is plumbing (like the + proxy variables, base.py PROXY_KEYS), so runs with and without it keep the same configuration hash.""" + if not mg: + return ad.config_sha256(spec, ep) + import copy + s2 = copy.copy(spec) + s2.argv = [a.replace(mg["url"], mg["upstream"]) if isinstance(a, str) else a for a in spec.argv] + s2.env = {k: (v.replace(mg["url"], mg["upstream"]) if isinstance(v, str) else v) for k, v in spec.env.items()} + return ad.config_sha256(s2, ep) + + +def write_json(path, d): + tmp = path + ".tmp" + with open(tmp, "w") as f: + json.dump(d, f, indent=1, ensure_ascii=False, default=str) + os.replace(tmp, path) + + +def run(a, adapter_kw=None): + """Returns (exit code, harness.json dict). adapter_kw overrides adapter construction (self-check).""" + provider = a.provider or PROVIDER.get(a.harness, "") + ep = EpisodeSpec.from_session(a.session, a.model, a.effort, provider) + if getattr(a, "red_team", False): # before the contract: red-team runs get their own contract_sha256 + if a.harness == "ours": + raise SystemExit("--red-team is for native harnesses") + RT.mark(ep.log_dir) + contract, csha = C.write_contract(ep.log_dir) + mg_box = {} # the model gateway process, stopped whatever happens below + try: + return _run(a, adapter_kw, provider, ep, csha, mg_box) + finally: + MG.stop_model_gateway(mg_box.get("proc")) + + +def _run(a, adapter_kw, provider, ep, csha, mg_box): + mg = None + if adapter_kw is None: + a.codex_auth = getattr(a, "codex_auth", None) or ("apikey" if a.harness in ROBOT_HARNESSES else "chatgpt") + if a.harness == "rpent_codex" and a.codex_auth != "apikey": + raise SystemExit("Historical RPent adapter supports apikey only") + claude_auth = getattr(a, "claude_auth", None) or default_claude_auth(a.harness) + if getattr(a, "codex_provider", "openai") in ("deepseek", "opencode"): + a.codex_auth = "apikey" # no subscription login for DeepSeek / OpenCode Go + api_env, url, endpoint = api_env_for(a.harness, a.api_base_url, getattr(a, "codex_auth", "apikey"), + claude_auth, getattr(a, "codex_provider", "openai")) + if a.harness != "ours" and not getattr(a, "no_model_gateway", False): + # the harness reaches its model API only through the model gateway (scripts/model_gateway.py) + kind, upstream = model_upstream(a.harness, url, a.codex_auth) + mg_box["proc"], mginfo = MG.start_model_gateway(upstream, kind, ep.log_dir, + getattr(a, "token_budget_in", None), + getattr(a, "token_budget_out", None), + allow_files=a.harness == "dsh") + mg = dict(url=mginfo["url"], upstream=upstream, kind=kind, upstream_host=mginfo["upstream_host"], + pid=mginfo["pid"]) + url = mg["url"] + if a.harness.startswith("claude_code"): + api_env["ANTHROPIC_BASE_URL"] = url + adapter_kw = dict(timeout_s=a.timeout) + if a.harness.startswith("claude_code"): + adapter_kw.update(api_env=api_env, max_budget_usd=a.max_budget_usd, allow_unpinned=a.allow_unpinned, + auth=claude_auth) + elif a.harness == "codex": + adapter_kw.update(api_env=api_env, base_url=url, allow_unpinned=a.allow_unpinned, auth=a.codex_auth, + catalog=a.codex_catalog) + elif a.harness == "dsh": + adapter_kw.update(api_env=api_env, base_url=url, allow_unpinned=a.allow_unpinned) + elif a.harness in ROBOT_HARNESSES: + adapter_kw.update(api_env=api_env, base_url=url, allow_unpinned=a.allow_unpinned, + auth=a.codex_auth, catalog=a.codex_catalog) + if a.harness == "rpent_codex": # historical, explicitly exposed RPent experiment settings + adapter_kw.update(sessions=a.rpent_sessions, attempts_per_session=a.rpent_attempts_per_session, + max_turns=a.rpent_max_turns) + if getattr(a, "jail", False): + if a.harness == "ours": + raise SystemExit("--jail is for native harnesses") + adapter_kw["jail"] = True + else: + adapter_kw.update(provider=provider) + else: + endpoint = "set by the caller (self-check)" + ad = get_adapter(a.harness, **adapter_kw) + ver = ad.version() + hj_path = os.path.join(ep.log_dir, "harness.json") + hj = dict(harness=ad.name, version=ver.get("version"), binary=ver.get("binary"), model=a.model, effort=a.effort, + provider=provider, capabilities={k: vars(c) for k, c in ad.capabilities.items()}, + contract_sha256=csha, task=ep.task, seed=ep.seed, api_endpoint_from=endpoint, status="preparing", + t_prepare=time.time(), jail=ad.jail_info(), auth=ad.auth_info() if ad.name != "ours" else None, + config=ad.config_info() if hasattr(ad, "config_info") else None, + model_gateway=({k: mg[k] for k in ("kind", "upstream_host", "pid")} if mg else None)) + if ad.name == "ours": + first = None + spec = ad.prepare(ep) + else: + first, _ = render_first_message(ep) + if getattr(a, "red_team", False): + first = RT.first_message(first) + hj["red_team"] = RT.marker(ep.log_dir) + with open(os.path.join(ep.log_dir, "first_message.txt"), "w") as f: + f.write(first) + spec = ad.prepare(ep, first, **(dict(reuse_state=a.reuse_state) if getattr(a, "reuse_state", None) else {})) + hj["first_message_sha256"] = C.sha256_text(first) + hj.update(argv=ad.logged_argv(spec), cwd=spec.cwd, env_keys=sorted(spec.env), + env_mode="exact whitelist (Popen env=, same as env -i)" if ad.name != "ours" else "inherited (own code)", + state_dirs=spec.state_dirs, config_sha256=plain_config_sha256(ad, spec, ep, mg), status="launching") + write_json(hj_path, hj) + h, code, gw = None, 0, None + stop = dict(flag=False) + + def on_term(*_): + stop["flag"] = True + if h is not None and h.proc is not None: + ad.kill(h) + signal.signal(signal.SIGTERM, on_term) + try: + if (ad.uses_mcp or ad.uses_gateway) and not getattr(a, "no_gateway", False): # the episode's tools, for + # every MCP process of the run / every SDK client of a framework adapter (base.HarnessAdapter.uses_gateway) + gw, ginfo = start_gateway(ep.session_path) + hj["gateway"] = dict(url=ginfo["url"], pid=ginfo["pid"]) + try: + h = ad.launch(spec, ep, skip_preflight=getattr(a, "skip_preflight", False)) + except HarnessRefused as e: + pre = dict(spec.preflight or {}) + hj.update(status="refused", refused=str(e), preflight={k: v for k, v in pre.items() if k != "fingerprint"}) + write_json(hj_path, hj) + print("REFUSED:", e, flush=True) + return 2, hj + pre = dict(spec.preflight or {}) + if "fingerprint" in pre: + write_json(os.path.join(ep.log_dir, "harness_preflight.json"), pre) + hj.update(status="running", pid=h.pid, env_observed_keys=h.env_observed_keys, t_start=h.t_start, + preflight={k: v for k, v in pre.items() if k != "fingerprint"}, init=h.info.get("init")) + write_json(hj_path, hj) + ad.wait(h) + cont = [] if getattr(a, "no_continue", False) else continue_episode(ad, h, ep, stop) + if cont: + hj["continuation"] = cont + write_json(hj_path, hj) + if stop["flag"]: + h.exit_reason, code = "stopped", 143 + tw = ad.collect(h) + au = ad.audit(h) + if ad.name == "ours" and spec.first_message: + hj["first_message_sha256"] = C.sha256_text(spec.first_message) + hj.update(status="done" if code == 0 else "stopped", exit_code=h.exit_code, exit_reason=h.exit_reason, + t_end=h.t_end, wall_s=round(h.t_end - h.t_start, 1), audit_ok=au.get("ok"), + violations=au.get("violations"), final_metrics=(tw.final or {}).get("final_metrics")) + if mg: # refusals do not void the trial; they flag it for a look (EFE running.md "Usage gateway") + tot = MG.read_totals(ep.log_dir) or {} + hj["model_gateway"].update({k: tot.get(k) for k in MG.Totals.KEYS}, tokens=tot.get("tokens"), + models=tot.get("models"), budget_stop=tot.get("budget_stop")) + hj["review_flags"] = ["model_gateway:" + k for k in MG.flagged(tot)] + ( + ["model_gateway:other_model"] if set(tot.get("models") or {}) - {a.model} else []) + if code == 0 and h.exit_code not in (0, None): + code = 3 + write_json(hj_path, hj) + return code, hj + except Exception as e: + hj.update(status="error", error=f"{type(e).__name__}: {e}", traceback=traceback.format_exc()[-3000:]) + write_json(hj_path, hj) + if h is not None and h.proc is not None and h.proc.poll() is None: + ad.kill(h) + return 3, hj + finally: + stop_gateway(gw) + if not getattr(a, "keep_run_dir", False): + ad.cleanup(spec) + + +def parser(): + ap = argparse.ArgumentParser() + ap.add_argument("--harness", required=True, choices=NAMES) + ap.add_argument("--session", required=True) + ap.add_argument("--provider", default=None, help="ours: openai / anthropic / gemini / chat") + ap.add_argument("--model", required=True) + ap.add_argument("--effort", default="high") + ap.add_argument("--api-base-url", default=None) + ap.add_argument("--codex-auth", default=None, choices=["chatgpt", "apikey"], + help="Codex authentication: chatgpt defaults for codex; apikey defaults for Robot Harnesses. " + "SenseNova/EmbodiedEvo also support chatgpt; historical RPent is apikey only") + ap.add_argument("--claude-auth", default=None, choices=["oauth", "apikey"], + help="claude_code*: subscription token (default for claude_code_full) or an API key (claude_code, " + "--bare, takes only an API key); see above") + ap.add_argument("--codex-provider", default="openai", choices=["openai", "deepseek", "opencode"], + help="codex: model provider; deepseek = DeepSeek's Responses endpoint with LFF_DEEPSEEK_API_KEY / " + "DEEPSEEK_API_KEY, opencode = OpenCode Go's with LFF_OPENCODE_API_KEY / OPENCODE_API_KEY " + "(both imply --codex-auth apikey)") + ap.add_argument("--codex-catalog", default="generic", choices=["generic", "native"], + help="codex: model catalog, the main table's shared configuration (default) or Codex's native " + "one (control); see lffbench/harnesses/codex.py") + ap.add_argument("--max-budget-usd", type=float, default=None, help="claude_code*: --max-budget-usd") + ap.add_argument("--rpent-sessions", type=int, default=5, + help="rpent_codex: planner sessions per episode (RPent --explore-sessions; default 5 = k + 2 spare)") + ap.add_argument("--rpent-attempts-per-session", type=int, default=1, + help="rpent_codex: attempts one session may use (RPent --explore-attempts-per-session): 1 = " + "variant H, a fresh session with a handoff after each failed attempt (default); 0 = no limit") + ap.add_argument("--rpent-max-turns", type=int, default=100, + help="rpent_codex: model responses per session (RPent --max-turns)") + ap.add_argument("--timeout", type=float, default=10800) + ap.add_argument("--allow-unpinned", action="store_true", + help="launch even if no pin exists for this version / model / effort (the preflight still runs)") + ap.add_argument("--keep-run-dir", action="store_true", help="do not delete the one-time dirs (debugging)") + ap.add_argument("--no-gateway", action="store_true", + help="native harnesses: run the tools inside each MCP server process instead of the episode's " + "tool gateway (scripts/tool_gateway.py; same ToolCore, budget carried over via the transcript)") + ap.add_argument("--no-model-gateway", action="store_true", + help="native harnesses: call the model API directly instead of through the run's model gateway " + "(scripts/model_gateway.py: model calls only, provider-side tools refused, tokens counted)") + ap.add_argument("--token-budget-in", type=int, default=None, + help="model gateway: refuse further model calls once this many input tokens were used (cached " + "input counts in full)") + ap.add_argument("--token-budget-out", type=int, default=None, + help="model gateway: ... output tokens (reasoning included)") + ap.add_argument("--red-team", action="store_true", + help="adversarial acceptance run (lffbench/harnesses/redteam.py): the first message starts with the " + "red-team notice; own contract_sha256; read with scripts/redteam_report.py") + ap.add_argument("--no-continue", action="store_true", + help="do not resume a CLI that exited before the episode was over (self-check / debugging)") + ap.add_argument("--jail", action="store_true", + help="native harnesses: run the CLI in the native-harness jail (docs/15 ยง3.4): as uid 65534, no host " + "path visible, MCP server outside behind a socket relay") + return ap + + +def main(): + code, hj = run(parser().parse_args()) + print(json.dumps({k: hj.get(k) for k in ("harness", "status", "exit_reason", "audit_ok", "violations", + "contract_sha256", "final_metrics")}, default=str), flush=True) + sys.exit(code) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/headroom_parts_cart.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/headroom_parts_cart.py new file mode 100644 index 0000000000000000000000000000000000000000..752d1777e6d011bc7723334b8a0e332880ceaae3 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/headroom_parts_cart.py @@ -0,0 +1,19 @@ +"""Incremental physical headroom evaluation of the composite prototype.""" +import argparse,hashlib,json,time +from pathlib import Path +import numpy as np +from lffbench.tasks.lh_parts_cart import PartsCart + +def clean(x): + if isinstance(x,np.ndarray):return x.tolist() + if isinstance(x,np.generic):return x.item() + raise TypeError(type(x).__name__) +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() +out=Path(a.out);out.parent.mkdir(parents=True,exist_ok=True);x=PartsCart();rows=[];start=time.time() +source=Path(__file__).parents[1]/'lffbench/tasks/lh_parts_cart.py';code_hash=hashlib.sha256(source.read_bytes()).hexdigest() +for seed in range(1000,1000+a.n): + i=x.sample_instance(seed);h=x.run_scripted(a.kind,i,k=a.k,seed=seed) + rows.append(dict(seed=seed,history=h));succ=sum(any(z['outcome']['success'] for z in row['history']) for row in rows) + 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)) + print(seed,a.kind,[z['outcome']['success'] for z in h], 'successes',succ,flush=True) +x.env.close() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/l6_controls.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/l6_controls.py new file mode 100644 index 0000000000000000000000000000000000000000..41114f4bea52b74c5426c220b1d554cade09f1ad --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/l6_controls.py @@ -0,0 +1,92 @@ +"""python scripts/l6_controls.py [n] + +Extra controls for the two L6 tasks: thumbnails right after the interruption, extra scripted policies, +no-injection sanity check, analytic memoryless baselines. Writes results//controls.json.""" +import sys, json, os, time +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) +import numpy as np, imageio +from lffbench import envs +import lffbench.tasks.l6_count, lffbench.tasks.l6_sequence # noqa +from lffbench.task_base import TASKS +name = sys.argv[1] +n = int(sys.argv[2]) if len(sys.argv) > 2 else 20 +out_dir = os.path.join(ROOT, "results", name) +os.makedirs(out_dir, exist_ok=True) +task = TASKS[name](cam_res=384) +extra = ["skip", "inc1"] if name == "l6_count_into_box" else ["skip"] +res = dict(task=name, n=n, seeds=list(range(1000, 1000 + n)), extra={}, no_inject={}, analytic={}) +t0 = time.time() + +# 1) frames right after the interruption (what the agent sees next), seeds 1000-1002, adaptive policy +def interrupted(): + return (task.slip if name == "l6_count_into_box" else task.stop) is not None + + +for seed in range(1000, 1003): + inst = task.sample_instance(seed) + shot = {} + orig_step = task.env.step + + def step(a, _o=orig_step): + r = _o(a) + if "f" not in shot and interrupted(): + shot["cnt"] = shot.get("cnt", 0) + 1 + if shot["cnt"] >= (4 if name == "l6_count_into_box" else 60): # count: 0.2 s; sequence: arm back home + shot["f"] = np.concatenate([envs.render(task.env, "agentview", 384), + envs.render(task.env, "robot0_eye_in_hand", 384)], 1) + return r + task.env.step = step + task.run_scripted("adaptive", inst, k=5, seed=seed) + task.env.step = orig_step + if "f" in shot: + imageio.imwrite(os.path.join(out_dir, f"interrupt_{seed}.png"), shot["f"]) +print("thumbs", f"{time.time()-t0:.0f}s", flush=True) + +# 2) extra scripted policies +for kind in extra: + fs = [] + for i in range(n): + seed = 1000 + i + inst = task.sample_instance(seed) + h = task.run_scripted(kind, inst, k=5, seed=seed) + s = next((x["attempt"] for x in h if x["outcome"]["success"]), None) + fs.append(s) + 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)]) + print(kind, res["extra"][kind]["succ_at_k"], f"{time.time()-t0:.0f}s", flush=True) + +# 3) no-injection sanity (oracle + naive, first 10 seeds) +task.inject = False +for kind in ("adaptive", "naive"): + fs = [] + for i in range(10): + seed = 1000 + i + inst = task.sample_instance(seed) + h = task.run_scripted(kind, inst, k=1, seed=seed) + fs.append(bool(h[0]["outcome"]["success"])) + res["no_inject"][kind] = float(np.mean(fs)) + print("no inject", kind, res["no_inject"][kind], flush=True) +task.inject = True + +# 4) analytic memoryless baselines over the same seeds (perfect execution assumed) +if name == "l6_count_into_box": + insts = [task.sample_instance(1000 + i) for i in range(n)] + res["analytic"]["uniform_guess_0..N-1@1"] = float(np.mean([1 / x["n_target"] for x in insts])) + best = max(range(0, 6), key=lambda g: np.mean([x["n_target"] - x["p"] == g for x in insts])) + 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]))) + res["analytic"]["p_hist"] = {str(v): int(sum(x["p"] == v for x in insts)) for v in range(1, 6)} + res["analytic"]["N_hist"] = {str(v): int(sum(x["n_target"] == v for x in insts)) for v in (4, 5)} + big = [task.sample_instance(5000 + i) for i in range(2000)] + res["analytic"]["uniform_guess@1_2000inst"] = float(np.mean([1 / x["n_target"] for x in big])) + 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))) +else: + insts = [task.sample_instance(1000 + i) for i in range(n)] + res["analytic"]["w_hist"] = {str(v): int(sum(x["stop_w"] == v for x in insts)) for v in range(1, 5)} + res["analytic"]["phase_hist"] = {p: int(sum(x["stop_phase"] == p for x in insts)) for p in "AB"} + res["analytic"]["uniform_guess_0..4@1"] = 0.2 + big = [task.sample_instance(5000 + i) for i in range(2000)] + 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))) + res["analytic"]["skip_expected"] = float(np.mean([x["stop_phase"] == "B" or x["stop_w"] == 3 for x in big])) +res["seconds"] = time.time() - t0 +json.dump(res, open(os.path.join(out_dir, "controls.json"), "w"), indent=1) +print(json.dumps(res["analytic"])) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/la_report.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/la_report.py new file mode 100644 index 0000000000000000000000000000000000000000..d191a51e7bf72871da213d7207d1a85502d6cd76 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/la_report.py @@ -0,0 +1,93 @@ +"""Per-run table for LA-interface (LIBERO-Agent-style) GPT runs: outcomes from the robot-server log, tool use and +token cost from the player transcript. + +python scripts/la_report.py --batch la1_rgb la1_rgbd [--out ../docs/la1_table.md] +""" +import argparse +import json +import os +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "scripts")) +from full_report import run_info # noqa: E402 + + +def transcript_stats(log): + p = os.path.join(log, "transcript.jsonl") # api_player (unified harness); gpt_player wrote gpt_transcript.jsonl + if not os.path.exists(p): + p = os.path.join(log, "gpt_transcript.jsonl") + 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) + if not os.path.exists(p): + au = os.path.join(log, "audit.json") # Claude subagent runs: tool counts from the audit of its transcript + if os.path.exists(au): + d = json.load(open(au)) + bt = d.get("by_tool", {}) + st.update(turns=d.get("n_calls", 0), view=bt.get("Read", 0), shell=bt.get("Bash", 0), + ended=f"audited ({d.get('n_violations')} violations, memory_injected={d.get('memory_injected')})") + return st + for l in open(p): + d = json.loads(l) + ev = d["ev"] + if ev == "assistant": + st["turns"] += 1 + u = d.get("usage") or {} + st["inp"] += u.get("input_tokens", 0) + st["cached"] += u.get("cached_tokens", 0) + st["out"] += u.get("output_tokens", 0) + st["reason"] += u.get("reasoning_tokens", 0) + elif ev == "tool": + c = d.get("command", "") + if c.startswith("shell:"): + st["shell"] += 1 + elif c.startswith("view_images"): + st["view"] += 1 + else: + st["robot"] += 1 + elif ev == "user" and d.get("auto_finish"): + st["auto_finish"] += 1 + elif ev == "api_error": + st["api_err"] += 1 + elif ev in ("end", "abort"): + st["ended"] = ev if ev == "end" else "abort: " + d.get("reason", "") + return st + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--batch", nargs="+", required=True) + ap.add_argument("--out", default=None) + ap.add_argument("--runs", default="gpt", help="runs// (gpt or claude); for claude, 'shell' = all Bash " + "calls (robot + shell) and 'view' = Read calls, from audit.json") + a = ap.parse_args() + L = ["| batch | task | perception | outcomes | robot cmds | grasps held/closed | shell | view | turns | " + "auto-finish | input Mtok (cached) | output ktok (reasoning) | wall min | state |", + "|---|---|---|---|---|---|---|---|---|---|---|---|---|---|"] + tot = dict(inp=0, cached=0, out=0, reason=0) + for b in a.batch: + m = json.load(open(os.path.join(ROOT, "runs", a.runs, b, "manifest.json"))) + for r in m["runs"]: + try: + x = run_info(r) + except FileNotFoundError: + continue + t = transcript_stats(r["log"]) + for k in tot: + tot[k] += t[k] + task = r["task"] + (" (nominal)" if r.get("nominal") else "") + L.append(f"| {b} | {task} | {r.get('perception')} | {x['outcomes'] or 'โ€”'} | {x['cmds']} | " + f"{x['held']}/{x['closes']} | {t['shell']} | {t['view']} | {t['turns']} | {t['auto_finish']} | " + f"{t['inp'] / 1e6:.2f} ({t['cached'] / 1e6:.2f}) | {t['out'] / 1e3:.0f} ({t['reason'] / 1e3:.0f}) | " + f"{(x['wall'] or 0):.0f} | {t['ended'] or 'running'} |") + L.append("") + L.append(f"Total tokens: input {tot['inp'] / 1e6:.2f} M (cached {tot['cached'] / 1e6:.2f} M), " + f"output {tot['out'] / 1e3:.0f} k (reasoning {tot['reason'] / 1e3:.0f} k).") + txt = "\n".join(L) + print(txt) + if a.out: + with open(a.out, "w") as f: + f.write(txt + "\n") + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/ladder_gpt_plan.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/ladder_gpt_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..46755d64c11bbf84cabe84a9701b431d86b0fb20 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/ladder_gpt_plan.py @@ -0,0 +1,95 @@ +"""Layer-3 feedback ladder for GPT-6 Astra (user 2026-11-02: "่ท‘ๅง"; same design as scripts/ladder_plan.py, docs/20). +Instances: the main-table attempt 1 failures of GPT-6 Astra on the 8 ladder tasks (turntable left out, as in the +reported Claude totals). Fresh single-attempt agents, Codex 0.163 generic config, jail, high, F1, one round. The F1 rung +is run here (batch lf1_gpt): GPT has no mismatch-control Do arm to reuse. + + python scripts/ladder_gpt_plan.py validate Fix texts for instances Claude's ladder did not cover -> results/_ladder/fix_validate_gpt.json + python scripts/ladder_gpt_plan.py build records -> runs/api/ladder_gpt_20261102/.json + tasks.txt + python scripts/ladder_gpt_plan.py report per instance rungs and totals, next to Opus and Sonnet +""" +import json +import os +import subprocess +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import ladder_plan as L # noqa: E402 + +ROOT, API = L.ROOT, L.API +OUT = os.path.join(API, "ladder_gpt_20261102") +BATCHES = ["cx_main1", "cx_astra_s2", "cx_astra_s3"] +TASKS = {"l7_offcenter_push", "l5_slide_to_target", "l5_tablecloth_pull", "l3_wall_flush", "l3_under_table_tool", + "l4_fit_container", "l3_card_shelf", "l5_loaded_beam"} +FIXV_GPT = os.path.join(ROOT, "results", "_ladder", "fix_validate_gpt.json") +RUNGS = ("F1", "F2", "hplus", "fix") +BATCH = {"F1": "lf1_gpt", "F2": "lf2_gpt", "hplus": "lhp_gpt", "fix": "lfx_gpt"} + + +def instances(): + out = {} + for b in BATCHES: + for r in json.load(open(os.path.join(API, b, "manifest.json")))["runs"]: + if r["cond"] != "harness" or r["status"] != "done" or r["task"] not in TASKS: + continue + d = next((e for e in L.events(r["log"]) if e["ev"] == "done" and e.get("attempt") == 1), None) + if d is not None and not d["success"]: + out[f"{r['task']}:{r['seed']}"] = r["log"] + return out + + +def fixes(): + rows = json.load(open(L.FIXV))["rows"] + if os.path.exists(FIXV_GPT): + rows += json.load(open(FIXV_GPT))["rows"] + return {r["key"]: r for r in rows} + + +def cmd_validate(): + import validate_ladder_fix as V + have = fixes() + want = {k: v for k, v in instances().items() if not have.get(k, {}).get("ok")} + print("to validate:", sorted(want)) + if not want: + return + V.instances = lambda: {k: dict(task=k.split(":")[0], seed=int(k.split(":")[1]), models=["gpt"], + logged=json.loads(open(os.path.join(v, "events.jsonl")).readline())["inst"]) for k, v in want.items()} + sys.argv = ["validate_ladder_fix.py", "--out", FIXV_GPT] + V.main() + + +def cmd_build(): + fx = fixes(); inst = instances(); os.makedirs(OUT, exist_ok=True) + open(os.path.join(OUT, "tasks.txt"), "w").write("\n".join(sorted(inst)) + "\n") + out = {r: {} for r in RUNGS} + for key, log in sorted(inst.items()): + task, seed = key.split(":") + tx = dict(L.texts(dict(log=log, task=task, seed=int(seed)), fx), F1="") + for r in RUNGS: + dst = os.path.join(OUT, r, f"{task}_s{seed}") + if not os.path.isdir(dst): + cmd = [sys.executable, "-I", os.path.join(ROOT, "scripts", "make_dossier.py"), log, dst] + (["--result-extra", tx[r]] if tx[r] else []) + subprocess.run(cmd, check=True, capture_output=True) + out[r][key] = dst + for r in RUNGS: + json.dump(out[r], open(os.path.join(OUT, f"{r}.json"), "w"), indent=1) + print(len(inst), "instances x", len(RUNGS), "rungs") + + +def cmd_report(): + keys = [l.strip() for l in open(os.path.join(OUT, "tasks.txt")) if l.strip()] + res = {r: L.single(BATCH[r]) for r in RUNGS} + f = lambda v: "-" if v is None else ("S" if v else "F") + print("| instance | F1 | F2 | H+ | Fix |\n|---|---|---|---|---|") + for k in keys: + print(f"| {k} | " + " | ".join(f(res[r].get(k)) for r in RUNGS) + " |") + rows = [{r: res[r].get(k) for r in RUNGS} for k in keys] + 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} + print("totals:", ", ".join(f"{r} {tot[r][0]}/{tot[r][1]}" for r in RUNGS)) + for lo, hi in zip(RUNGS, RUNGS[1:]): + both = [x for x in rows if x[lo] is not None and x[hi] is not None] + 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)}") + 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) + + +if __name__ == "__main__": + {"validate": cmd_validate, "build": cmd_build, "report": cmd_report}[sys.argv[1]]() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/ladder_plan.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/ladder_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..7a7625e6a1ec7037f6f10c3220a1bfa33aa0c541 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/ladder_plan.py @@ -0,0 +1,120 @@ +"""Layer-3 feedback ladder (user 2026-10-27; design docs/20). Same instances and records as the mismatched-history +control (scripts/mismatch_plan.py): the main-table attempt 1 of every Claude instance in the 9 twin tasks whose +attempt 1 failed. Fresh single-attempt agents (Claude Code B', jail, high, F1), README byte-identical to the Do arm; +only the Result section of history/README.md grows, one rung at a time: + + F1 "The environment judged that attempt: failed." = the Do arm (do_), not re-run + F2 + the measured error of that attempt (outcome.detail, axis labels stripped) batch lf2_ + hplus + "Cause: " the hidden variable (arm_specs reveal, as --arm hplus states it) batch lhp_ + fix + how to succeed (arm_specs fix, from the oracle parameters; results/_ladder/fix_validate.json) lfx_ + + python scripts/ladder_plan.py build records -> runs/api/ladder_20261027//.json (+ tasks_.txt) + python scripts/ladder_plan.py report per instance F1 / F2 / H+ / Fix, totals, adjacent paired counts + -> runs/api/ladder_20261027/report.json + markdown on stdout +""" +import json +import os +import subprocess +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) +API = os.path.join(ROOT, "runs", "api") +SRC = os.path.join(API, "mismatch_20261027") +OUT = os.path.join(API, "ladder_20261027") +FIXV = os.path.join(ROOT, "results", "_ladder", "fix_validate.json") +MODELS = ("opus", "sonnet") +RUNGS = ("F2", "hplus", "fix") +BATCH = {"F1": "do", "F2": "lf2", "hplus": "lhp", "fix": "lfx"} +WITHIN = {"l2_turntable_restore"} # reported separately (docs/20 ยง2) + + +def events(log): + return [json.loads(line) for line in open(os.path.join(log, "events.jsonl")) if line.strip()] + + +def texts(src, fixes): + """rung -> result_extra for one record source (the logged attempt 1)""" + from lffbench import arm_specs + from lffbench.agent.robot_server import strip_axes + ev = events(src["log"]) + start = next(e for e in ev if e["ev"] == "session_start") + done = next(e for e in ev if e["ev"] == "done" and e.get("attempt") == 1) + detail = strip_axes((done.get("outcome") or {}).get("detail") or "").strip() + if not detail: + raise SystemExit(f"{src['task']}:{src['seed']}: attempt 1 has no outcome detail for F2") + cause = "Cause: " + strip_axes(arm_specs.reveal(start["task"], start["inst"]).strip()) + fx = fixes.get(f"{start['task']}:{start['seed']}") + if fx is None or not fx["ok"]: + raise SystemExit(f"{start['task']}:{start['seed']}: no validated fix text in {FIXV}") + return {"F2": detail, "hplus": detail + "\n\n" + cause, "fix": detail + "\n\n" + cause + "\n\n" + fx["fix"]} + + +def cmd_build(): + fixes = {r["key"]: r for r in json.load(open(FIXV))["rows"]} + for m in MODELS: + own = json.load(open(os.path.join(SRC, m, "own.json"))) + os.makedirs(os.path.join(OUT, m), exist_ok=True) + open(os.path.join(OUT, m, f"tasks_{m}.txt"), "w").write("\n".join(own) + "\n") + out = {r: {} for r in RUNGS} + for key, d in own.items(): + src = json.load(open(d + ".source.json")) + tx = texts(src, fixes) + for r in RUNGS: + dst = os.path.join(OUT, m, r, f"{src['task']}_s{src['seed']}") + if not os.path.isdir(dst): + subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "make_dossier.py"), src["log"], + dst, "--result-extra", tx[r]], check=True, capture_output=True) + out[r][key] = dst + for r in RUNGS: + json.dump(out[r], open(os.path.join(OUT, m, f"{r}.json"), "w"), indent=1) + print(m, len(own), "instances x", len(RUNGS), "rungs") + + +def single(batch): + """task:seed -> True / False (attempt 1 of the batch's done run)""" + out = {} + p = os.path.join(API, batch, "manifest.json") + if not os.path.exists(p): + return out + for r in json.load(open(p))["runs"]: + if r["status"] != "done": + continue + d = next((e for e in events(r["log"]) if e["ev"] == "done" and e.get("attempt") == 1), None) + out[f"{r['task']}:{r['seed']}"] = None if d is None else bool(d["success"]) + return out + + +def cmd_report(): + rep, md = {}, [] + order = ("F1", "F2", "hplus", "fix") + f = lambda v: "-" if v is None else ("S" if v else "F") + for m in MODELS: + want = [l.strip() for l in open(os.path.join(OUT, m, f"tasks_{m}.txt")) if l.strip()] + res = {r: single(f"{BATCH[r]}_{m}") for r in order} + rows = [dict(inst=k, within=k.split(":")[0] in WITHIN, **{r: res[r].get(k) for r in order}) for k in want] + tot = {} + for part, sub in (("all", rows), ("cross", [r for r in rows if not r["within"]]), + ("within", [r for r in rows if r["within"]])): + 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} + steps = {} + cross = [r for r in rows if not r["within"]] + for lo, hi in zip(order, order[1:]): + both = [r for r in cross if r[lo] is not None and r[hi] is not None] + steps[f"{lo}->{hi}"] = dict(n=len(both), up=sum(r[hi] and not r[lo] for r in both), + down=sum(r[lo] and not r[hi] for r in both)) + rep[m] = dict(rows=rows, totals=tot, steps=steps) + md += [f"### {m}", "", "| instance | F1 | F2 | H+ | Fix |", "|---|---|---|---|---|"] + md += [f"| {r['inst']}{' (within)' if r['within'] else ''} | " + " | ".join(f(r[x]) for x in order) + " |" + for r in rows] + for part in ("cross", "within"): + md.append(f"{part}: " + ", ".join(f"{x} {tot[part][x][0]}/{tot[part][x][1]}" for x in order)) + md.append("adjacent (cross, paired): " + "; ".join(f"{k} n={v['n']} up {v['up']} down {v['down']}" + for k, v in steps.items())) + md.append("") + json.dump(rep, open(os.path.join(OUT, "report.json"), "w"), indent=1) + print("\n".join(md)) + + +if __name__ == "__main__": + {"build": cmd_build, "report": cmd_report}[sys.argv[1]]() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/layer4_plan.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/layer4_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..03f7434a8b04de323809f5d8d4879b9933cc3a72 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/layer4_plan.py @@ -0,0 +1,174 @@ +"""Layer-4 minimal intervention (user 2026-10-30: ๅ…ˆ็”จ opus; design reports/layer4_intervention_20261030/PLAN.md). Opus only, on the +two tasks whose every main-table instance failed all three attempts. Same protocol as the layer-3 ladder (a fresh +single-attempt agent, the instance's own failed attempt 1 in history/, F1), only the Result section differs: + + f1 "The environment judged that attempt: failed." + v + a generic reminder to check the goal before ending; no cause + hp + "Cause: " the hidden variable (arm_specs reveal) + fx + cause + how to succeed (arm_specs fix, validated below) + + python scripts/layer4_plan.py validate texts + oracle + LA push, debug and test seeds -> results/_layer4/fix_validate.json + python scripts/layer4_plan.py build debug records -> runs/api/layer4i_20261030/debug/.json + tasks.txt + python scripts/layer4_plan.py build test the same from the failed attempts of batch l4i_first (test seeds) + python scripts/layer4_plan.py report debug|test per instance per condition: outcome, process events, closing claim +""" +import json +import os +import subprocess +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) +API = os.path.join(ROOT, "runs", "api") +OUT = os.path.join(API, "layer4i_20261030") +FIXV = os.path.join(ROOT, "results", "_layer4", "fix_validate.json") +CONDS = ("f1", "v", "hp", "fx") +DEBUG = {"lh_clear_cover": {3000: "cc_opus1", 3001: "cc_opus_s2", 3003: "cc_opus_s3"}, + "lh_tidy_stack": {3000: "cc_opus1", 3002: "cc_opus_s2", 3003: "cc_opus_s3"}} +# frozen before any test-seed run: first four seeds from 3100 with the trap active (clear_cover: covered, (seed * 7) % 20 < 10; +# tidy_stack: a soft box that is not on top of a nearest-first pile, (seed * 7) % 20 < 18 and % 4 != 3) +TEST = {"lh_clear_cover": [3100, 3101, 3103, 3104], "lh_tidy_stack": [3100, 3102, 3103, 3104]} +REMINDER = ("Before you end an attempt, use your observations to check whether every part of the goal is actually met; " + "if it is not, keep working.") + + +def events(log): + return [json.loads(line) for line in open(os.path.join(log, "events.jsonl")) if line.strip() and "\0" not in line] + + +def batch_log(batch, task, seed): + runs = json.load(open(os.path.join(API, batch, "manifest.json")))["runs"] + return next(r["log"] for r in runs if r["task"] == task and r["seed"] == seed and r.get("status") == "done" + and r.get("cond") == "harness") + + +def la_push(task, inst): + """the Fix text's lid push as LA commands; returns (z_push, sweep length, lid off?)""" + import numpy as np + from lffbench.agent.tools import ToolExecutor + from lffbench.tasks import lh_clear_cover as cc + from scripts.validate_ladder_fix import la_move + task.reset_instance(inst) + sim = task.env.sim + off = np.array(sim.data.body_xpos[sim.model.body_name2id("robot0_base")], float).copy() + ex = ToolExecutor(task, inst, image_res=64, cams=("agentview",)) + cov = task.covering() + lp = task.lid_pos() + b = np.asarray(inst["boxes"][cov], float) + o = np.asarray(inst["boxes"][[c for c in cc.COLORS if c != cov][0]], float) + d = np.array((0.0, float(np.sign(b[1] - o[1])))) + back = cc.LID_HALF + 0.03 + s = lp[:2] - d * back + z = lp[2] + cc.LID_T / 2 - cc.PUSH_DEPTH + cc.TIP + need = float((b - lp[:2]) @ d) + cc.BOX_OUT + back + 0.03 + e = s + d * need + sb, eb, zb = s - off[:2], e - off[:2], z - off[2] + la_move(task, ex, off, gripper="close") + la_move(task, ex, off, x=sb[0], y=sb[1], z=zb + 0.08, yaw=0) + la_move(task, ex, off, x=sb[0], y=sb[1], z=zb) + la_move(task, ex, off, x=eb[0], y=eb[1], z=zb, speed=cc.PUSH_SPEED) + la_move(task, ex, off, z=zb + 0.10, speed=0.2) + return float(zb), float(need), task.covering() is None + + +def cmd_validate(): + import importlib + import pkgutil + from lffbench import arm_specs + from lffbench import tasks as task_pkg + from lffbench.agent.robot_server import strip_axes + from lffbench.task_base import TASKS + for m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{m.name}") + rows = [] + for name, seeds in ((t, sorted(DEBUG[t]) + TEST[t]) for t in DEBUG): + task = TASKS[name](cam_res=64) + for seed in seeds: + inst = task.sample_instance(seed) + clean = {k: v for k, v in inst.items() if not k.startswith("_")} + params = dict(task.oracle_params(inst)) + row = dict(key=f"{name}:{seed}", hidden=clean.get("cover") or clean.get("soft_colour")) + row["oracle_success"] = bool(task.run_scripted("oracle", inst, k=1)[0]["outcome"]["success"]) + row["naive_success"] = bool(task.run_scripted("naive", inst, k=1)[0]["outcome"]["success"]) + if name == "lh_clear_cover": + params["z_push"], params["push_len"], row["la_lid_off"] = la_push(task, inst) + task.execute(inst, dict(plan="naive", check="side")) # the placing part, after the LA push + row["la_then_place_success"] = bool(task.outcome(inst)["success"]) + cause, fx = arm_specs.reveal(name, clean), arm_specs.fix(name, clean, params) + row.update(cause=cause, fix=fx, no_axis_labels=strip_axes(cause + fx) == cause + fx) + row["ok"] = bool(row["oracle_success"] and not row["naive_success"] and row["hidden"] and row["no_axis_labels"] + and row.get("la_lid_off", True) and row.get("la_then_place_success", True)) + rows.append(row) + 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) + os.makedirs(os.path.dirname(FIXV), exist_ok=True) + json.dump(dict(rows=rows, n=len(rows), n_ok=sum(r["ok"] for r in rows)), open(FIXV, "w"), indent=1) + print(f"{sum(r['ok'] for r in rows)}/{len(rows)} ok -> {FIXV}") + + +def sources(stage): + if stage == "debug": + return [(t, s, batch_log(b, t, s)) for t, d in DEBUG.items() for s, b in sorted(d.items())] + out = [] + for r in json.load(open(os.path.join(API, "l4i_first", "manifest.json")))["runs"]: + if r["status"] == "done": + d = next((e for e in events(r["log"]) if e["ev"] == "done" and e.get("attempt") == 1), None) + if d is not None and not d["success"]: + out.append((r["task"], r["seed"], r["log"])) + return out + + +def cmd_build(stage): + fixes = {r["key"]: r for r in json.load(open(FIXV))["rows"]} + base = os.path.join(OUT, stage) + os.makedirs(base, exist_ok=True) + maps, tasks = {c: {} for c in CONDS}, [] + for task, seed, log in sources(stage): + key = f"{task}:{seed}" + if not fixes[key]["ok"]: + raise SystemExit(f"{key}: fix text not validated") + tasks.append(key) + cause = "Cause: " + fixes[key]["cause"] + extra = dict(f1="", v=REMINDER, hp=cause, fx=cause + "\n\n" + fixes[key]["fix"]) + for c in CONDS: + dst = os.path.join(base, c, f"{task}_s{seed}") + if not os.path.isdir(dst): + subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "make_dossier.py"), log, dst, + "--result-extra", extra[c]], check=True, capture_output=True) + maps[c][key] = dst + for c in CONDS: + json.dump(maps[c], open(os.path.join(base, f"{c}.json"), "w"), indent=1) + open(os.path.join(base, "tasks.txt"), "w").write("\n".join(tasks) + "\n") + print(stage, len(tasks), "instances x", len(CONDS), "conditions") + + +def cmd_report(stage): + rows = {} + for c in CONDS: + p = os.path.join(API, f"l4i_{c}_{stage}", "manifest.json") + if not os.path.exists(p): + continue + for r in json.load(open(p))["runs"]: + key = f"{r['task']}:{r['seed']}" + cell = dict(status=r["status"]) + if r["status"] == "done": + ev = events(r["log"]) + d = next((e for e in ev if e["ev"] == "done"), {}) + o = d.get("outcome") or {} + cell.update(success=bool(d.get("success")), calls=d.get("step"), reason=(d.get("reason") or "")[:300], + failure=o.get("failure"), detail=(o.get("detail") or "")[:300], log=r["log"], + events=[e.get("ev") for e in o.get("events", []) if isinstance(e, dict)][:40], + cover_removed=o.get("cover_removed")) + rows.setdefault(key, {})[c] = cell + print("| instance | " + " | ".join(CONDS) + " |") + print("|---|" + "---|" * len(CONDS)) + f = lambda x: "-" if x is None else ("S" if x.get("success") else ("F" if x.get("status") == "done" else x.get("status"))) + for k, v in sorted(rows.items()): + print(f"| {k} | " + " | ".join(f(v.get(c)) for c in CONDS) + " |") + for c in CONDS: + xs = [v[c] for v in rows.values() if c in v and v[c].get("status") == "done"] + print(c, f"{sum(x['success'] for x in xs)}/{len(xs)}") + json.dump(rows, open(os.path.join(OUT, f"report_{stage}.json"), "w"), indent=1) + + +if __name__ == "__main__": + {"validate": cmd_validate, "build": lambda: cmd_build(sys.argv[2]), "report": lambda: cmd_report(sys.argv[2])}[sys.argv[1]]() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/lerobot_export.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/lerobot_export.py new file mode 100644 index 0000000000000000000000000000000000000000..fa4fa0a1be92844c9cf410663f77de5e200bda18 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/lerobot_export.py @@ -0,0 +1,431 @@ +"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars. + +Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding +can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan): + + python scripts/lerobot_export.py plan --raw [,] --runs-root /runs/api \ + --paper --task-set /sets/main_v2_1inst.txt --work [--batches ...] [--limit N] + python scripts/lerobot_export.py shard --work --shard i --nshards N + python scripts/lerobot_export.py merge --work --nshards N --out + +Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0 +mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped. + +LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t): + observation.images.image agentview RGB 256x256 (upright; LIBERO naming) + observation.images.wrist_image wrist (eye-in-hand) RGB 256x256 + observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout) + observation.joint_pos / joint_vel 7 arm joints (rad, rad/s) + observation.eef_quat 4: xyzw; observation.gripper_width 1 (m) + action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad), + gripper (-1 open, +1 close) + annotation.attempt_index attempt (1-based) the frame belongs to + annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`) + annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action) + annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt + annotation.task_event number of task-monitor events (error / progress events) registered at this step +Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table), +runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state +per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/. +""" +import argparse +import glob +import json +import os +import re +import shutil +import time + +import numpy as np + +FPS = 20 +RES = 256 +BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke", + "cc_smoke", "cc_opus_smoke"] +BATCH_NOTES = { + "cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog", + "cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267", + "cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299", + "cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances", + "cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)", + "cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the " + "with-history continuation of failed runs is incomplete", + "cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early", + "cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt", + "cc_opus_smoke": "smoke test: single attempt", +} +PHASES = {"move": 0, "gripper": 1, "judge": 2} +CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)", + "L2": "disturbed state to restore (incl. damage the agent causes)", + "L3": "infeasible manipulation strategy (grasp / contact / tool must change)", + "L4": "misjudged geometry (size, shape, fit, hidden structure)", + "L5": "misjudged physics (mass distribution, friction, dynamics)"} + + +def features(): + vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]} + f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names} + i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None} + return { + "observation.images.image": vid(), + "observation.images.wrist_image": vid(), + "observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z", + "finger_qpos_left", "finger_qpos_right"]), + "observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]), + "observation.gripper_width": f32(1, ["width_m"]), + "action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y", + "eef_delta_rot_aa_z", "gripper_close"]), + "annotation.attempt_index": i64(), + "annotation.command_index": i64(), + "annotation.phase": i64(), + "annotation.attempt_success": i64(), + "annotation.task_event": i64(), + } + + +# ------------------------------------------------------------------------------------------------ paper metadata + +def _clean_tex(s): + s = re.sub(r"%.*", "", s) + for a, b in [(r"\{\\times\}", "ร—"), (r"\\times", "ร—"), (r"\\,", " "), (r"\\mu", "ฮผ"), (r"\^\\circ", "ยฐ"), + (r"\\pm", "ยฑ"), (r"\\leftrightarrow", "โ†”"), (r"\\geq", "โ‰ฅ"), (r"\\leq", "โ‰ค"), (r"\\%", "%"), + (r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"), + (r"\\approx", "โ‰ˆ"), (r"\\to", "โ†’"), (r"\\Delta", "ฮ”"), (r"\\theta", "ฮธ"), (r"\\alpha", "ฮฑ"), + (r"\\cdot", "ยท"), (r"\\ldots", "โ€ฆ"), (r"\\dots", "โ€ฆ"), (r"\\&", "&"), (r"\\textasciitilde", "~")]: + s = re.sub(a, b, s) + s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s) + s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s) + for _ in range(3): + s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\$([^$]*)\$", r"\1", s) + s = s.replace("``", '"').replace("''", '"').replace("---", "โ€”").replace("--", "โ€“").replace("~", " ") + s = re.sub(r"\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\\[a-zA-Z]+\*?", "", s) + return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip() + + +def paper_tasks(paper_dir): + """{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the + paper's task table and task appendix (empty if the paper sources are not there).""" + out = {} + if not paper_dir: + return out + app = os.path.join(paper_dir, "sections", "appendix_tasks.tex") + tab = os.path.join(paper_dir, "sections", "tab_tasks.tex") + if os.path.exists(app): + txt = open(app).read() + parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt) + for i in range(1, len(parts) - 1, 2): + if parts[i] != "\\paragraph{": + continue + body = parts[i + 1] + m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S) + if not m: + continue + name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip() + desc = _clean_tex(body[m.end():]) + out[code] = dict(name=name, cause=_clean_tex(cause), description=desc) + if os.path.exists(tab): + names = {v["name"].lower(): k for k, v in out.items()} + for line in open(tab): + cells = [c.strip() for c in line.split("&")] + if len(cells) != 6 or not cells[-1].endswith("\\\\"): + continue + nm = re.sub(r"\\contscene", "", cells[0]).strip().lower() + code = names.get(nm) + if not code: + continue + out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]), + repair_within_attempt=_clean_tex(cells[3]) == "yes", + oracle_first_attempt_pct=_clean_tex(cells[4]), + naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip())) + return out + + +# ------------------------------------------------------------------------------------------------ collection + +def manifest_status(runs_root, batch, run, cache={}): + if batch not in cache: + p = os.path.join(runs_root, batch, "manifest.json") + cache[batch] = json.load(open(p)) if os.path.exists(p) else {} + m = cache[batch] + for r in m.get("runs", []): + if r.get("run") == run: + return r.get("status", "?"), r + for r in m.get("superseded", []): + if r.get("run") == run: + return "superseded_" + str(r.get("status", "?")), r + return "not_in_manifest", {} + + +def collect(raw_roots, runs_root, batches, task_order): + """Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root.""" + eps, rejected, seen = [], [], set() + for root in raw_roots: + for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))): + rep = json.load(open(rj)) + batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"] + if (batches and batch not in batches) or (batch, run) in seen: + continue + seen.add((batch, run)) + ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff") + status, entry = manifest_status(runs_root, batch, run) + if not ok: + never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked") + rejected.append(dict(run=run, batch=batch, run_status=status, + reason="run never started (no contract, no robot command)" if never else + "replay does not reproduce the log (the log has gaps or the replay diverged)", + detail=rep.get("first_mismatches"))) + continue + for ep in rep.get("episodes", []): + d = os.path.join(root, ep["dir"]) + ann = json.load(open(os.path.join(d, "annotation.json"))) + judged = [a for a in ann["attempts"] if a.get("success") is not None] + if not judged or ep["n_frames"] == 0: + rejected.append(dict(run=run, batch=batch, episode=ep["dir"], + reason="no judged attempt" if not judged else "no frames")) + continue + ann["source"]["run_status"] = status + ann["source"]["manifest_id"] = entry.get("id") + ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"], + max_eef_dev_m=rep["max_eef_dev_m"]) + key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99), + {"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2), + ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"]) + eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann)) + eps.sort(key=lambda x: x["key"]) + return eps, rejected + + +# ------------------------------------------------------------------------------------------------ writing + +def frames_of(path): + import av + with av.open(path) as c: + for fr in c.decode(video=0): + yield fr.to_ndarray(format="rgb24") + + +def flat_row(i, ann, n, idx0): + s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"] + att = ann["attempts"] + a0 = att[0] + return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n, + batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"], + memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"), + episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att], + harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"), + effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"), + task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"), + category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"], + success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att], + feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att], + auto_ended=[a.get("auto_ended") for a in att], + corrected_later_in_run=[a.get("corrected_later_in_run") for a in att], + error_event_in_attempt=[a.get("error_event_in_attempt") for a in att], + run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"), + n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]), + first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None) + + +def cmd_plan(a): + task_order = {} + if a.task_set and os.path.exists(a.task_set): + for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")): + task_order[line.split(":")[0].strip()] = i + batches = [b for b in a.batches.split(",") if b] if a.batches else None + eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order) + if a.limit: + eps = eps[:a.limit] + paper = paper_tasks(a.paper) + idx0 = 0 + for i, e in enumerate(eps): + ann = e["ann"] + tname = ann["task"]["name"] + if tname in paper: + ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"} + ann["episode_index"] = i + ann["dataset_index_range"] = [idx0, idx0 + e["n"]] + e["index"], e["from"] = i, idx0 + idx0 += e["n"] + del e["key"] + os.makedirs(a.work, exist_ok=True) + with open(os.path.join(a.work, "plan.json"), "w") as f: + json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f, + ensure_ascii=False) + print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True) + + +def shard_range(n_eps, i, k): + return (n_eps * i) // k, (n_eps * (i + 1)) // k + + +def cmd_shard(a): + from lerobot.datasets.lerobot_dataset import LeRobotDataset + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + lo, hi = shard_range(len(eps), a.shard, a.nshards) + out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}") + if os.path.exists(os.path.join(out, "DONE")): + print(f"shard {a.shard}: done already", flush=True) + return + shutil.rmtree(out, ignore_errors=True) + ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out, + robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads, + vcodec=a.vcodec) + nfr = 0 + for e in eps[lo:hi]: + d, ann, n = e["dir"], e["ann"], e["n"] + fr = np.load(os.path.join(d, "frames.npz")) + assert len(fr["action"]) == n, d + succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]} + evc = np.zeros(n, np.int64) + for ev in ann["task_events"]: + if 0 <= ev["frame"] < n: + evc[ev["frame"]] += 1 + state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32) + instr = ann["task"]["instruction"] + k = 0 + for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))): + if k >= n: + break + ds.add_frame({ + "observation.images.image": img, "observation.images.wrist_image": wr, + "observation.state": state[k], + "observation.joint_pos": fr["joint_pos"][k].astype(np.float32), + "observation.joint_vel": fr["joint_vel"][k].astype(np.float32), + "observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32), + "observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32), + "action": fr["action"][k].astype(np.float32), + "annotation.attempt_index": np.array([fr["attempt"][k]], np.int64), + "annotation.command_index": np.array([fr["command"][k]], np.int64), + "annotation.phase": np.array([fr["phase"][k]], np.int64), + "annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64), + "annotation.task_event": np.array([evc[k]], np.int64), + "task": instr, + }) + k += 1 + if k != n: + raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames") + ds.save_episode() + nfr += n + ds.finalize() + shutil.rmtree(os.path.join(out, "images"), ignore_errors=True) + open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n") + print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True) + + +def cmd_merge(a): + from pathlib import Path + from lerobot.datasets.aggregate import aggregate_datasets + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + roots, ids = [], [] + for i in range(a.nshards): + lo, hi = shard_range(len(eps), i, a.nshards) + if hi <= lo: + continue + r = os.path.join(a.work, "shards", f"shard_{i:03d}") + if not os.path.exists(os.path.join(r, "DONE")): + raise SystemExit(f"shard {i} is not done") + roots.append(Path(r)) + ids.append(f"{plan['repo_id']}-shard{i:03d}") + if os.path.exists(a.out): + raise SystemExit(f"{a.out} exists; refusing to overwrite") + aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out)) + print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True) + write_sidecars(a, plan) + print(f"merge done in {time.time() - t0:.0f}s", flush=True) + + +def write_sidecars(a, plan): + eps, paper = plan["episodes"], plan["paper"] + lff = os.path.join(a.out, "lff") + for sub in ("annotations", "sim_state", "final", "code"): + os.makedirs(os.path.join(lff, sub), exist_ok=True) + rows, runs, tasks = [], {}, {} + for e in eps: + i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"] + name = f"episode_{i:06d}" + if os.path.exists(os.path.join(d, "sim_state.npy")): + shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy")) + shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz")) + for cam, key in (("agentview", "image"), ("wrist", "wrist_image")): + shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png")) + with open(os.path.join(lff, "annotations", name + ".json"), "w") as f: + json.dump(ann, f, indent=1, ensure_ascii=False) + rows.append(flat_row(i, ann, n, e["from"])) + tname = ann["task"]["name"] + rk = (ann["source"]["batch"], ann["source"]["run"]) + r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"), + run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"], + memory_free_chain_of=ann["source"].get("memory_free_chain_of"), + memory_free_rep=ann["source"].get("memory_free_rep"), task=tname, + seed=ann["task"]["seed"], model=ann["agent"].get("model"), + harness=ann["agent"].get("harness"), + harness_version=ann["agent"].get("harness_version"), + codex_catalog=ann["agent"].get("codex_catalog"), + outcome_class=ann["run_outcome"].get("outcome_class"), + attempt_history=ann["run_outcome"].get("attempt_history"), + agent_final_report=ann["run_outcome"].get("agent_final_report"), + episodes=[])) + for x in ann["attempts"]: + r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success"))) + if tname not in tasks: + tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")} + if tname in paper: + tasks[tname]["paper"] = paper[tname] + tasks[tname]["instances"] = {} + tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"] + # memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id) + by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")} + for r in runs.values(): + if r.get("memory_free_chain_of"): + r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"])) + for (b, rn), r in runs.items(): + r["memory_free_retries"] = sorted((x["run"] for x in runs.values() + if x["batch"] == b and x.get("memory_free_chain_of_run") == rn), + key=lambda q: runs[(b, q)].get("memory_free_rep") or 0) + with open(os.path.join(lff, "episodes.jsonl"), "w") as f: + for row in rows: + f.write(json.dumps(row, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "runs.jsonl"), "w") as f: + for r in runs.values(): + f.write(json.dumps(r, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "tasks.json"), "w") as f: + json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False) + with open(os.path.join(lff, "batches.json"), "w") as f: + json.dump(BATCH_NOTES, f, indent=1) + with open(os.path.join(lff, "rejected.json"), "w") as f: + json.dump(plan["rejected"], f, indent=1) + here = os.path.dirname(os.path.abspath(__file__)) + for s in ("lerobot_replay.py", "lerobot_export.py"): + shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("step", choices=["plan", "shard", "merge"]) + ap.add_argument("--work", required=True) + ap.add_argument("--raw", default="") + ap.add_argument("--runs-root", default="") + ap.add_argument("--out", default="") + ap.add_argument("--paper", default="") + ap.add_argument("--task-set", default="") + ap.add_argument("--repo-id", default="lffbench/agent-replays") + ap.add_argument("--batches", default="") + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--shard", type=int, default=0) + ap.add_argument("--nshards", type=int, default=1) + ap.add_argument("--threads", type=int, default=2) + ap.add_argument("--vcodec", default="libsvtav1") + a = ap.parse_args() + {"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/lerobot_replay.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/lerobot_replay.py new file mode 100644 index 0000000000000000000000000000000000000000..4c43a69bdb066327b27614bc9efda53d4a74e931 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/lerobot_replay.py @@ -0,0 +1,744 @@ +"""Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay +against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the +LeRobot export (scripts/lerobot_export.py). + + python scripts/lerobot_replay.py check [ ...] [--json out.json] # replay only, print fidelity + python scripts/lerobot_replay.py record --out [--res 256] + +Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot +commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite +is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly +like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same +outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width, +ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code +hashes equal the current files are expected to match (check_code()). + +Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB, +proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes: +protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode +per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the +fidelity check runs in record mode too. Per episode the recorder writes ///epNN/: + agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes) + frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase + sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel) + final_*.png, final.npz observation after the last control step (the state the outcome was judged in) + annotation.json episode annotation (build_annotation) +and ///replay.json (fidelity) when the whole run is done. +""" +import argparse +import ast +import hashlib +import importlib +import json +import math +import os +import pkgutil +import re +import shutil +import sys +import time +from collections import defaultdict + +import numpy as np + +LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, LFF_ROOT) + +from lffbench import envs # noqa: E402 +from lffbench import tasks as task_pkg # noqa: E402 +from lffbench.agent import camera as C # noqa: E402 +from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402 +from lffbench.task_base import TASKS # noqa: E402 + +for _m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{_m.name}") + +# per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the +# task's outcome() check after `finish` (the arm holds still; not an agent action) +PHASES = {"move": 0, "gripper": 1, "judge": 2} +FPS = 20 +SCHEMA = "lff-replay-1" + +# error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR" +ERROR_FLAGS = ("trap_fired", "recovered_in_attempt") +ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events", + "n_missed_strikes", "n_open_gripper_pushes") + + +def load_jsonl(p): + out = [] + if not os.path.exists(p): + return out + with open(p) as f: + for line in f: + line = line.strip() + if line: + try: + out.append(json.loads(line)) + except ValueError: + pass + return out + + +def norm_json(o): + return json.loads(json.dumps(o, default=_json_default)) + + +def sha256(p): + with open(p, "rb") as f: + return hashlib.sha256(f.read()).hexdigest() + + +def check_code(run_dir): + """[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract.""" + p = os.path.join(run_dir, "contract.json") + if not os.path.exists(p): + return [("contract.json", None, None)] + files = json.load(open(p))["contract"].get("server_code_files", {}) + bad = [] + for f, h in files.items(): + q = os.path.join(LFF_ROOT, f) + cur = sha256(q) if os.path.exists(q) else None + if cur != h: + bad.append((f, h, cur)) + return bad + + +def diff_json(a, b, path="", tol=0.0, out=None, limit=20): + """Differences between two JSON values (numbers compared with an absolute tolerance).""" + out = [] if out is None else out + if len(out) >= limit: + return out + if isinstance(a, dict) and isinstance(b, dict): + for k in sorted(set(a) | set(b)): + if k not in a or k not in b: + out.append((f"{path}.{k}", a.get(k, ""), b.get(k, ""))) + else: + diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit) + elif isinstance(a, list) and isinstance(b, list): + if len(a) != len(b): + out.append((path, f"len {len(a)}", f"len {len(b)}")) + else: + for i, (x, y) in enumerate(zip(a, b)): + diff_json(x, y, f"{path}[{i}]", tol, out, limit) + elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))): + if a != b: + out.append((path, a, b)) + elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))): + out.append((path, a, b)) + return out + + +def error_event(o): + """True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none.""" + if not isinstance(o, dict): + return None + keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o] + if not keys: + return None + return any(bool(o[k]) for k in ERROR_FLAGS if k in o) or any((o.get(k) or 0) > 0 for k in ERROR_COUNTS if k in o) + + +# ====================================================================================================== logs -> notes + +class RunLog: + """Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's + narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition.""" + + def __init__(self, run_dir, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run = os.path.basename(self.run_dir) + self.batch = os.path.basename(os.path.dirname(self.run_dir)) + self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl")) + self.start = next(e for e in self.ev if e["ev"] == "session_start") + self.calls, self.dones, self.harness_status = {}, [], [] + last = None + for e in self.ev: + if e["ev"] == "call": + self.calls[(int(e["attempt"]), int(e["step"]))] = e + last = e + elif e["ev"] == "done": + self.dones.append(e) + last = e + elif e["ev"] == "http" and last is not None and "think_s" not in last: + ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \ + (last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe")) + if ok: + last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s") + self.manifest = manifest or {} + self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {} + p = os.path.join(self.run_dir, "harness.json") + self.harness = json.load(open(p)) if os.path.exists(p) else {} + self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl")) + self._narration() + + # ---------------------------------------------------------------- agent narration + def _narration(self): + """notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one; + finish_notes[attempt] likewise for the agent's finish call; final_report = its last message.""" + self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", [] + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + attempt = 1 + + def take(): + nonlocal buf + out = {k: v for k, v in buf.items() if v} + buf = dict(messages=[], reasoning=[], shell=[], viewed=[]) + return out + + last_msg = "" + for t in self.traj: + if t.get("kind") == "header": + self.headers.append(t.get("agent") or {}) + continue + if t.get("kind") != "step": + continue + if (t.get("message") or "").strip(): + buf["messages"].append(t["message"].strip()) + last_msg = t["message"].strip() + if (t.get("reasoning_content") or "").strip(): + buf["reasoning"].append(t["reasoning_content"].strip()) + res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])} + for c in t.get("tool_calls") or []: + fn, args = c.get("function_name"), c.get("arguments") or {} + if fn == "shell": + buf["shell"].append(str(args.get("command", ""))[:2000]) + elif fn == "view_images": + buf["viewed"].extend(args.get("paths") or []) + elif fn == "robot": + cmd = str(args.get("command", "")).strip() + r = res.get(c.get("tool_call_id")) or {} + try: + rep = json.loads(r.get("content") or "{}") + except ValueError: + rep = {} + word = cmd.split()[0] if cmd else "" + m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", ""))) + if word in ("move_eef", "observe") and m: + a, s = int(m.group(1)), int(m.group(2)) + n = take() + n["command"] = cmd + self.notes[(a, s)] = n + attempt = a + elif word in ("finish", "done"): + n = take() + n["command"] = cmd + n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)} + self.finish_notes.setdefault(attempt, n) + if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"): + attempt += 1 + # status / help / errors: their narration stays in the buffer for the next command + self.final_report = last_msg + + # ---------------------------------------------------------------- run-level labels + def attempts(self): + out = [] + for e in self.dones: + o = e.get("outcome") or {} + if isinstance(o, str): + try: + o = ast.literal_eval(o) + except (ValueError, SyntaxError): + o = {} + out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o, + reason=e.get("reason") or "")) + return sorted(out, key=lambda x: x["attempt"]) + + def condition(self): + s, en = self.start, self.entry + mem = s.get("memory", en.get("mem")) + chain = en.get("chain") + if mem == "full": + cond = "with_history" + elif chain: + cond = "memory_free_retry" + else: + cond = "independent_single_attempt" + return cond, chain + + def outcome_class(self): + """CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None.""" + att = self.attempts() + if not att or self.start.get("memory") != "full": + return None, "".join("S" if a["success"] else "F" for a in att) + hist = "".join("S" if a["success"] else "F" for a in att) + if att[0]["success"]: + ev = error_event(att[0]["outcome"]) + cls = "S?" if ev is None else ("IR" if ev else "CS") + else: + cls = "XR" if any(a["success"] for a in att) else "F" + return cls, hist + + def agent_info(self): + h, en = self.harness, self.entry + hdr = self.headers[0] if self.headers else {} + return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"), + harness_version=h.get("version") or hdr.get("version"), + harness_binary_sha256=(h.get("binary") or {}).get("sha256"), + model=h.get("model") or en.get("model") or hdr.get("model_name"), + effort=h.get("effort") or en.get("effort") or hdr.get("effort"), + provider=h.get("provider") or en.get("provider"), + codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"), + jail=en.get("jail")) + + +# ====================================================================================================== recording + +class EpisodeSink: + """Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed.""" + + def __init__(self, path): + self.path = path + os.makedirs(path, exist_ok=True) + self.w = None + self.num = defaultdict(list) + self.n = 0 + + def add(self, st, imgs): + import imageio + if self.w is None: + self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb", + pixelformat="rgb24", macro_block_size=1, + ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error") + for k in ("agentview", "wrist")] + for w, im in zip(self.w, imgs): + w.append_data(im) + for k, v in st.items(): + self.num[k].append(v) + self.n += 1 + + def close(self, final_state, final_imgs): + from PIL import Image + if self.w is not None: + for w in self.w: + w.close() + arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"} + np.savez(os.path.join(self.path, "frames.npz"), **arr) + if self.num.get("sim_state"): + np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64)) + np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()}) + for k, im in zip(("agentview", "wrist"), final_imgs): + Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png")) + + +class Recorder: + """Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink.""" + + def __init__(self, rp, res): + self.rp, self.res = rp, int(res) + self.active = False + self.sink = None + self.cur = dict(attempt=1, command=-1, phase=PHASES["move"]) + env = rp.task.env + self.env, self.rob = env, env.robots[0] + self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist")) + orig = env.step + + def step(a): + if self.active and self.sink is not None: + self.capture(np.asarray(a, np.float64)) + out = orig(a) + if self.active and self.sink is not None: + self.rp.poll_events(self.sink.n - 1) + return out + + env.step = step + + @property + def n(self): + return self.sink.n if self.sink is not None else 0 + + def state(self): + import robosuite.utils.transform_utils as T + env, rob = self.env, self.rob + d = env.sim.data + eef = np.array(d.site_xpos[rob.eef_site_id], np.float64) + q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw") + gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64) + try: + flat = np.asarray(env.sim.get_state().flatten(), np.float64) + except Exception: + flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64) + sk = self.rp.task.sk + return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64), + gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64), + joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64), + gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64), + eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)), + sim_time=np.float64(d.time), sim_state=flat) + + def images(self): + return [envs.render(self.env, c, self.res) for c in self.cams] + + def capture(self, a): + st = self.state() + st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]), + phase=np.int64(self.cur["phase"])) + self.sink.add(st, self.images()) + + +class RunReplay: + def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None): + self.run_dir = os.path.abspath(run_dir.rstrip("/")) + self.run_name = os.path.basename(self.run_dir) + self.log = RunLog(self.run_dir, manifest) + self.ev = self.log.ev + self.start = self.log.start + cp = os.path.join(self.run_dir, "contract.json") + self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {} + spec = self.contract.get("image_spec") or {} + self.image_res = int(spec.get("width", 512)) + self.code_diff = check_code(self.run_dir) + s = self.start + self.task = TASKS[s["task"]](cam_res=self.image_res) + inst = self.task.sample_instance(s["seed"]) + logged = s.get("inst") or {} + sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")}) + self.inst_diff = diff_json(sampled, logged, "inst") + if s.get("arm", "none") not in (None, "none") or logged.get("nominal"): + inst.update(logged) # controlled arms / nominal: the server overrode these instance fields + self.inst_diff = [] + self.inst = inst + self.protocol = getattr(self.task, "protocol", "cross") + self.k = int(s.get("k") or self.task.max_attempts) + self.attempt = 1 + self.mismatch = [] # (where, what, logged, replayed) + self.n_checked = 0 + self.max_dev_m = 0.0 + self.unfinished = None + self.rec = Recorder(self, res) if record else None + self.res = int(res) + self.out_root = out_root + self.n_mon = 0 + self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0 + self.episodes = [] # summaries of the written episodes + self.task.reset_instance(self.inst) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + sim = self.task.env.sim + bid = sim.model.body_name2id("robot0_base") + self.base_off = np.array(sim.data.body_xpos[bid], float).copy() + if self.rec: + self._open_episode() + + # ------------------------------------------------------------------ episodes + def _ep_dir(self): + return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}") + + def _open_episode(self): + self.rec.sink = EpisodeSink(self._ep_dir()) + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.rec.active = True + self.events, self.spans, self.ep_attempts = [], [], [] + self.ep_initial = self.rec.state() # state right after the reset (before frame 0) + + def close_episode(self): + if not self.rec: + self.ep_attempts = [] + return + sink = self.rec.sink + st = self.rec.state() + imgs = self.rec.images() + st.pop("sim_state", None) + sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs) + ann = build_annotation(self, sink) + with open(os.path.join(sink.path, "annotation.json"), "w") as f: + json.dump(ann, f, indent=1, default=_json_default) + self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n, + attempts=[a["attempt"] for a in self.ep_attempts])) + self.rec.active = False + self.rec.sink = None + self.ep_index += 1 + + # ------------------------------------------------------------------ monitor events (task-side error events) + def poll_events(self, frame): + mon = getattr(self.task, "mon", None) + evs = mon.get("events") if isinstance(mon, dict) else None + if not isinstance(evs, list): + return + if len(evs) < self.n_mon: # monitor was rebuilt + self.n_mon = 0 + for e in evs[self.n_mon:]: + self.events.append(dict(frame=int(frame), attempt=self.attempt, + event=norm_json(e) if isinstance(e, dict) else str(e))) + self.n_mon = len(evs) + + # ------------------------------------------------------------------ state as the server reports it + def proprio_la(self): + p = self.ex.proprio() + pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off] + return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"]) + + def compare(self, where, rep_logged, rep): + self.n_checked += 1 + for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"): + if k not in rep_logged or k not in rep: + continue + a, b = rep_logged[k], rep[k] + if k == "eef_pos": + dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float)))) + self.max_dev_m = max(self.max_dev_m, dev) + if dev > 1.5e-4: + self.mismatch.append((where, k, a, b)) + elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4): + self.mismatch.append((where, k, a, b)) + if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)): + self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok"))) + + def _span(self, e, f0, kind): + if self.rec: + self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0, + frame_end=self.rec.n)) + + # ------------------------------------------------------------------ commands (robot_server._handle_v2) + def move_eef(self, e): + args = e.get("args") or {} + where = f"a{e['attempt']}s{e['step']}" + logged = e.get("report") or {} + f0 = self.rec.n if self.rec else 0 + p = self.ex.proprio() + if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}: + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + off = self.base_off + try: + cur = np.asarray(p["eef_pos"], float) - off + tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")] + yaw = float(args.get("yaw", p["eef_yaw_deg"])) + speed = None if args.get("speed") in (None, "") else float(args["speed"]) + except (TypeError, ValueError): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + grip = args.get("gripper") + if grip not in (None, "open", "close"): + self._span(e, f0, "error") + return self.compare(where, logged, dict(ok=False)) + moving = any(k in args for k in ("x", "y", "z", "yaw")) + tgt_w = np.asarray(tgt) + off + if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)): + self._span(e, f0, "rejected") + return self.compare(where, logged, dict(ok=False, **self.proprio_la())) + raw = {} + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"]) + if moving: + mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw) + if speed is not None: + mv["speed"] = speed + raw.update(self.ex.call("move_to", mv).report) + if grip is not None: + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"]) + raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report) + rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la()) + self.compare(where, logged, rep) + lr = e.get("raw") or {} + for k in ("holding_object", "touched_object"): + if k in lr and k in raw and bool(lr[k]) != bool(raw[k]): + self.mismatch.append((where, "raw." + k, lr[k], raw[k])) + self._span(e, f0, "move_eef") + + def observe(self, e): + f0 = self.rec.n if self.rec else 0 + self._span(e, f0, "observe") + + def done(self, e): + f0 = self.rec.n if self.rec else 0 + if self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"]) + out = self.task.outcome(self.inst) + succ = bool(out["success"]) + where = f"a{e['attempt']}done" + if succ != bool(e.get("success") in (True, "True")): + self.mismatch.append((where, "success", e.get("success"), succ)) + lo = e.get("outcome") or {} + ro = norm_json({k: v for k, v in out.items() if k != "feedback"}) + if isinstance(lo, dict): + for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8): + self.mismatch.append((where,) + d) + info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""), + feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")), + think_s=e.get("think_s")) + try: + info["feedback_f2"] = self.task.feedback(self.inst, out, "F2") + except Exception as ex_: + info["feedback_f2"] = f"" + if self.rec: + info["judge_frames"] = [f0, self.rec.n] + self.ep_attempts.append(info) + last = self.attempt >= self.k or succ or bool(out.get("terminal")) + if self.protocol == "cross" or last: + self.close_episode() + if last: + return True + self.attempt += 1 + if self.protocol == "cross": + self.task.reset_instance(self.inst) + self.n_mon = 0 + if self.rec: + self._open_episode() + elif self.rec: + self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"]) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist")) + return False + + def run(self): + t0 = time.time() + finished = False + for e in self.ev: + if e["ev"] == "call": + if e.get("cmd") == "move_eef": + self.move_eef(e) + elif e.get("cmd") == "observe": + self.observe(e) + else: + self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None)) + elif e["ev"] == "done": + finished = self.done(e) + if finished: + break + self.unfinished = not finished + if not finished and self.rec and self.rec.sink is not None: + # the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged + if self.rec.n or self.ep_attempts: + self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True, + finish_reason="", feedback_shown="", auto_ended=False)) + self.close_episode() + else: + shutil.rmtree(self.rec.sink.path, ignore_errors=True) + self.rec.sink = None + self.wall_s = time.time() - t0 + return self + + def summary(self): + return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"], + protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff), + n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6), + unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1), + first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]]) + + +# ====================================================================================================== annotation + +def task_info(task, inst): + cls = type(task) + return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable", + category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"), + max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)), + instruction=cls.instruction) + + +def build_annotation(rp, sink): + """Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2 + failure description), run-level outcome class, every robot command with its frame span and the agent's narration, + task-side error events with frame indices.""" + log = rp.log + s = rp.start + cond, chain = log.condition() + cls, hist = log.outcome_class() + att_all = log.attempts() + attempts = [] + for a in rp.ep_attempts: + a = dict(a) + n = a["attempt"] + later = [x for x in att_all if x["attempt"] > n] + a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later)) + a["is_last_attempt_of_run"] = not later + fn = log.finish_notes.get(n) + if fn: + a["agent_finish"] = fn + a["error_event_in_attempt"] = error_event(a.get("outcome")) + attempts.append(a) + # post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command) + for a in attempts: + nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1]) + if a.get("success") is False and nxt: + note = log.notes[nxt[0]] + a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note} + commands = [] + for sp in rp.spans: + e = log.calls.get((sp["attempt"], sp["step"])) or {} + rep = e.get("report") or {} + c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"], + frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]), + args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"), + stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"), + gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"), + touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"), + agent_obs_images=rep.get("images")) + note = log.notes.get((sp["attempt"], sp["step"])) + if note: + c["agent_note"] = {k: v for k, v in note.items() if k != "command"} + commands.append(c) + t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x] + return dict( + schema=SCHEMA, + source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts], + episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain, + memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None), + feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"), + k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"), + contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256") + if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)), + agent=log.agent_info(), + task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"), + instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}), + run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all), + run_success=any(x["success"] for x in att_all) if att_all else None, + agent_final_report=log.final_report[:6000] or None, + mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)), + attempts=attempts, + commands=commands, + task_events=rp.events, + frames=dict(n=sink.n, fps=FPS, image_res=rp.res, + phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"], + joint_pos=rp.ep_initial["joint_pos"], + gripper_qpos=rp.ep_initial["gripper_qpos"])), + ) + + +# ====================================================================================================== CLI + +def load_manifest(run_dir): + p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json") + return json.load(open(p)) if os.path.exists(p) else {} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("mode", choices=["check", "record"]) + ap.add_argument("runs", nargs="+") + ap.add_argument("--json", default="") + ap.add_argument("--out", default="") + ap.add_argument("--res", type=int, default=256) + ap.add_argument("--force", action="store_true", help="record again even if replay.json exists") + a = ap.parse_args() + rows = [] + for r in a.runs: + r = r.rstrip("/") + try: + if a.mode == "check": + s = RunReplay(r, manifest=load_manifest(r)).run().summary() + else: + batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r) + rd = os.path.join(a.out, batch, name) + if os.path.exists(os.path.join(rd, "replay.json")) and not a.force: + print(json.dumps(dict(run=name, skipped="exists")), flush=True) + continue + shutil.rmtree(rd, ignore_errors=True) + rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run() + s = rp.summary() + s["episodes"] = rp.episodes + with open(os.path.join(rd, "replay.json"), "w") as f: + json.dump(s, f, indent=1) + except Exception: + import traceback + s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:]) + rows.append(s) + print(json.dumps(s), flush=True) + if a.json: + with open(a.json, "w") as f: + json.dump(rows, f, indent=1) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/lerobot_sft_dataset.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/lerobot_sft_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..669475712c1f9848a8555f447d760932c6c0b5cc --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/lerobot_sft_dataset.py @@ -0,0 +1,473 @@ +#!/usr/bin/env python3 +"""Build the training set for supervised fine-tuning (SFT) a VLA from the published agent replays. + +Input: the unified LeRobot v3 release named by /mnt/cpfs/shared/datasets/lffbench_agent_replays/CURRENT.json, plus any +package it does not hold yet (--extra-source). Output: one LeRobot v2.1 dataset with the feature names of openpi's LIBERO +config (image, wrist_image, state, actions), one episode per successful attempt: + +- only frames of attempts judged successful, without the evaluator's outcome check (annotation.phase == 2); +- a multi-attempt `within` episode gives one clip per successful attempt, so action chunks never cross attempts; +- the safety routine of l6_sequence_resume's emergency stop drives the arm without the agent, so it is cut out; +- one instance per task is held out by (task, seed) and written to a separate dataset, never to the training one; +- videos are remuxed packet by packet from the published files: the pixels are the validated ones, nothing is re-encoded. + + python scripts/lerobot_sft_dataset.py build --out DIR --repo-id lff_sft_vX --holdout sets/main_v2_3inst.txt [--holdout-seed task:seed ...] + python scripts/lerobot_sft_dataset.py verify DIR/ # in the OpenPI environment: reads through its LeRobot + python scripts/lerobot_sft_dataset.py norm DIR/ --assets /pi05_lff/ + +Run with an environment that has av and pyarrow (shared/envs/openpi-ppu20). +""" +import argparse +import collections +import functools +import glob +import json +import multiprocessing +import os +import random +import time +from concurrent.futures import ProcessPoolExecutor + +import av +import numpy as np +import pyarrow as pa +import pyarrow.parquet as pq + +DATA = "/mnt/cpfs/shared/datasets/lffbench_agent_replays" +FPS = 20 +CAMERAS = {"image": "observation.images.image", "wrist_image": "observation.images.wrist_image"} +CHUNK = 1000 +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +def sources(extra): + """The canonical release, which already merges the earlier packages, and what it does not hold yet.""" + return [json.load(open(os.path.join(DATA, "CURRENT.json")))["dataset"]] + list(extra or []) + + +def read_holdout(path, extra): + out = {} + if path: + for line in open(path): + if line.strip() and not line.startswith("#"): + t, s = line.strip().split(":") + out[t] = {int(x) for x in s.split(",")} + for item in extra or []: + t, s = item.split(":") + out[t] = {int(x) for x in s.split(",")} + return out + + +def plan_source(name, only_task=None): + """Successful attempts of one published dataset, as frame ranges inside its episodes.""" + p = os.path.join(DATA, name) + rows = {} + for line in open(os.path.join(p, "lff/episodes.jsonl")): + r = json.loads(line) + if any(r["success"]) and (not only_task or r["task"] in only_task): + rows[r["episode_index"]] = r + if not rows: + return [], collections.Counter() + meta = [] + for f in sorted(glob.glob(os.path.join(p, "meta/episodes/chunk-*/file-*.parquet"))): + keep = ["episode_index", "length", "dataset_from_index"] + for key in CAMERAS.values(): + keep += [f"videos/{key}/chunk_index", f"videos/{key}/file_index", f"videos/{key}/from_timestamp"] + meta += pq.read_table(f, columns=keep).to_pylist() + meta = {m["episode_index"]: m for m in meta} + cols = ["index", "episode_index", "frame_index", "annotation.attempt_index", "annotation.phase", "annotation.attempt_success", + "annotation.command_index", "action"] + keep, located, stops = {}, {}, {} + for f in sorted(glob.glob(os.path.join(p, "data/chunk-*/file-*.parquet"))): + t = pq.read_table(f, columns=cols) + ep = t["episode_index"].to_numpy().reshape(-1) + fr = t["frame_index"].to_numpy().reshape(-1) + att = t["annotation.attempt_index"].to_numpy().reshape(-1) + ph = t["annotation.phase"].to_numpy().reshape(-1) + su = t["annotation.attempt_success"].to_numpy().reshape(-1) + cmd = t["annotation.command_index"].to_numpy().reshape(-1) + grip = np.stack(t["action"].to_numpy(zero_copy_only=False))[:, 6] + first_index = int(t["index"][0].as_py()) + for e in np.unique(ep): + if int(e) not in rows: + continue + located[int(e)] = (f, first_index) + m = (ep == e) & (su == 1) & (ph != 2) + for a in np.unique(att[m]): + ix = np.sort(fr[m & (att == a)]) + keep[(int(e), int(a))] = ix + if rows[int(e)]["task"] == "l6_sequence_resume": + o = np.flatnonzero(ep == e) + o = o[np.argsort(fr[o])] + stops[int(e)] = emergency_stops(fr[o], att[o], cmd[o], ph[o], grip[o]) + clips, stats = [], collections.Counter() + for (e, a), ix in sorted(keep.items()): + r = rows[e] + spans = [(int(ix[0]), int(ix[-1]) + 1)] + if not (np.diff(ix) == 1).all(): + raise ValueError(f"{name} episode {e} attempt {a}: frames are not contiguous") + for s_att, cut0, cut1 in stops.get(e, []): + if s_att == a: + stats["emergency_frames_cut"] += cut1 - cut0 + spans = [x for x in ((spans[0][0], cut0), (cut1, spans[0][1])) if x[1] > x[0]] + for s0, s1 in spans: + 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"], + model=r["model"], condition=r["condition"], protocol=r["protocol"], instruction=r["instruction"], cause=r["paper_cause"], + first_attempt=a == 1, run_outcome_class=r.get("run_outcome_class"), + videos={cam: dict(chunk=meta[e][f"videos/{key}/chunk_index"], file=meta[e][f"videos/{key}/file_index"], + t0=meta[e][f"videos/{key}/from_timestamp"]) for cam, key in CAMERAS.items()}, + ep_from=meta[e]["dataset_from_index"], data_file=located[e][0], data_first_index=located[e][1])) + return clips, stats + + +def emergency_stops(frame, attempt, command, phase, grip): + """l6_sequence_resume's emergency stop opens the jaws in the middle of a move and then drives the arm home until that + command returns; an agent's move never changes the gripper while it moves. So the stop is where the gripper action + turns from close to open inside one motion command, and the routine is the rest of that command. + Returns [(attempt, first frame of the routine, end of the command)].""" + out = [] + for i in range(1, len(frame)): + if phase[i] == 0 == phase[i - 1] and command[i] == command[i - 1] and attempt[i] == attempt[i - 1] \ + and grip[i - 1] > 0 > grip[i]: + end = i + while end < len(frame) and command[end] == command[i] and attempt[end] == attempt[i]: + end += 1 + out.append((int(attempt[i]), int(frame[i]), int(frame[end - 1]) + 1)) + return out + + +def remux(src, dst, f0, n, t0): + """Copy n frames starting at file time t0 + f0/FPS without re-encoding. Returns (frames written, first frame kept): + a clip must start on a key frame, so a start between key frames moves to the next one.""" + os.makedirs(os.path.dirname(dst), exist_ok=True) + tmp = dst + ".tmp.mp4" + with av.open(src) as ic: + s = ic.streams.video[0] + tb = s.time_base + first = int(round((t0 + f0 / FPS) / tb)) + frame_pts = int(round(1 / (FPS * tb))) + ic.seek(first, stream=s, backward=True, any_frame=False) + with av.open(tmp, "w", format="mp4") as oc: + o = oc.add_stream_from_template(s, opaque=True) # packets are copied, so no encoder is involved + base, written = None, 0 + for pkt in ic.demux(s): + if pkt.pts is None or pkt.pts < first: + continue + idx = int(round((pkt.pts - first) / frame_pts)) + if idx >= n: + break + if base is None: + if not pkt.is_keyframe: + continue + base, kept = pkt.pts, idx + pkt.pts = pkt.pts - base + pkt.dts = pkt.dts - base + pkt.stream = o + oc.mux(pkt) + written += 1 + os.replace(tmp, dst) + return written, kept + + +@functools.lru_cache(maxsize=2) +def read_data_file(path): + return pq.read_table(path, columns=["observation.state", "action", "index", "episode_index", "annotation.attempt_success", "annotation.phase"]) + + +def write_clip(job): + """One output episode: both videos, then the parquet of exactly the frames they hold.""" + clip, ep, out = job + n = clip["stop"] - clip["start"] + chunk = ep // CHUNK + src = os.path.join(DATA, clip["source"]) + results = {} + for cam, v in clip["videos"].items(): + path = os.path.join(src, f"videos/{CAMERAS[cam]}/chunk-{v['chunk']:03d}/file-{v['file']:03d}.mp4") + results[cam] = remux(path, os.path.join(out, f"videos/chunk-{chunk:03d}/{cam}/episode_{ep:06d}.mp4"), clip["start"], n, v["t0"]) + kept = {r[1] for r in results.values()} + if len(kept) != 1: + raise ValueError(f"cameras disagree on the first key frame: {results} ({clip['source']} {clip['episode']})") + skip = kept.pop() + length = results["image"][0] + if results["wrist_image"][0] != length or length != n - skip: + raise ValueError(f"frame count {results} != {n - skip} ({clip['source']} {clip['episode']})") + i0 = clip["ep_from"] + clip["start"] + skip + t = read_data_file(clip["data_file"]).slice(i0 - clip["data_first_index"], length) + if t.num_rows != length or int(t["index"][0].as_py()) != i0 or set(t["episode_index"].to_pylist()) != {clip["episode"]}: + raise ValueError(f"parquet slice mismatch ({clip['source']} {clip['episode']})") + if set(t["annotation.attempt_success"].to_pylist()) != {1} or 2 in set(t["annotation.phase"].to_pylist()): + raise ValueError(f"unexpected frame labels ({clip['source']} {clip['episode']})") + state = np.stack(t["observation.state"].to_numpy(zero_copy_only=False)).astype(np.float32) + action = np.stack(t["action"].to_numpy(zero_copy_only=False)).astype(np.float32) + chunk_dir = os.path.join(out, f"videos/chunk-{chunk:03d}") + images = {cam: image_stats(os.path.join(chunk_dir, f"{cam}/episode_{ep:06d}.mp4"), length) for cam in CAMERAS} + return dict(ep=ep, length=length, skip=skip, state=state, action=action, image_stats=images) + + +def stats_of(a): + 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)]) + + +def image_stats(path, length, n=5): + """Sampled image statistics for meta/episodes_stats.jsonl (LeRobot requires them, openpi does not use them).""" + frames = [] + with av.open(path) as c: + s = c.streams.video[0] + for i in np.linspace(0, length - 1, min(n, length)).astype(int): + pts = int(round(i / FPS / s.time_base)) + c.seek(pts, stream=s, backward=True) + for fr in c.decode(s): + if fr.pts >= pts: + frames.append(fr.to_ndarray(format="rgb24").astype(np.float32) / 255.0) + break + x = np.stack(frames).transpose(0, 3, 1, 2) + fmt = lambda v: [[[float(q)]] for q in v] + 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)]) + + +def pool(workers): + """Fresh interpreters: a forked worker inherits FFmpeg's state from a parent that decoded video and can deadlock.""" + return ProcessPoolExecutor(workers, mp_context=multiprocessing.get_context("spawn")) + + +def write_dataset(out, clips, workers): + os.makedirs(os.path.join(out, "meta"), exist_ok=True) + os.makedirs(os.path.join(out, "lff"), exist_ok=True) + tasks = sorted({c["instruction"] for c in clips}) + task_index = {t: i for i, t in enumerate(tasks)} + clips = sorted(clips, key=lambda c: (c["task"], c["seed"], c["source"], c["episode"], c["start"])) + with pool(workers) as ex: + results = list(ex.map(write_clip, [(c, i, out) for i, c in enumerate(clips)], chunksize=4)) + index, eps, ep_stats, prov = 0, [], [], [] + for c, r in zip(clips, results): + ep, n = r["ep"], r["length"] + chunk = ep // CHUNK + ts = np.arange(n, dtype=np.float32) / FPS + table = pa.table({"state": list(r["state"]), "actions": list(r["action"]), "timestamp": ts, "frame_index": np.arange(n), + "episode_index": np.full(n, ep), "index": np.arange(index, index + n), + "task_index": np.full(n, task_index[c["instruction"]])}) + p = os.path.join(out, f"data/chunk-{chunk:03d}/episode_{ep:06d}.parquet") + os.makedirs(os.path.dirname(p), exist_ok=True) + pq.write_table(table, p) + eps.append(dict(episode_index=ep, tasks=[c["instruction"]], length=n)) + st = dict(state=stats_of(r["state"]), actions=stats_of(r["action"]), + timestamp=stats_of(ts[:, None]), frame_index=stats_of(np.arange(n)[:, None]), + episode_index=stats_of(np.full((n, 1), ep)), index=stats_of(np.arange(index, index + n)[:, None]), + task_index=stats_of(np.full((n, 1), task_index[c["instruction"]]))) + st.update(r["image_stats"]) + ep_stats.append(dict(episode_index=ep, stats=st)) + prov.append(dict(episode_index=ep, index_from=index, length=n, source=c["source"], source_episode=c["episode"], attempt=c["attempt"], + source_frame_start=c["start"] + r["skip"], task=c["task"], seed=c["seed"], cause=c["cause"], model=c["model"], + run=c["run"], batch=c["batch"], condition=c["condition"], protocol=c["protocol"], first_attempt=c["first_attempt"], + run_outcome_class=c["run_outcome_class"])) + index += n + feat = lambda dtype, shape, names=None: dict(dtype=dtype, shape=shape, names=names) + video = dict(dtype="video", shape=[256, 256, 3], names=["height", "width", "channels"], + info={"video.height": 256, "video.width": 256, "video.codec": "av1", "video.pix_fmt": "yuv420p", "video.is_depth_map": False, + "video.fps": FPS, "video.channels": 3, "has_audio": False}) + info = dict(codebase_version="v2.1", robot_type="franka_panda", total_episodes=len(clips), total_frames=index, total_tasks=len(tasks), + total_videos=2 * len(clips), total_chunks=(len(clips) - 1) // CHUNK + 1, chunks_size=CHUNK, fps=FPS, splits={"train": f"0:{len(clips)}"}, + data_path="data/chunk-{episode_chunk:03d}/episode_{episode_index:06d}.parquet", + video_path="videos/chunk-{episode_chunk:03d}/{video_key}/episode_{episode_index:06d}.mp4", + features=dict(image=video, wrist_image=video, + 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"]), + 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"]), + timestamp=feat("float32", [1]), frame_index=feat("int64", [1]), episode_index=feat("int64", [1]), index=feat("int64", [1]), + task_index=feat("int64", [1]))) + json.dump(info, open(os.path.join(out, "meta/info.json"), "w"), indent=1) + jsonl = lambda name, rows: open(os.path.join(out, name), "w").write("".join(json.dumps(r) + "\n" for r in rows)) + jsonl("meta/tasks.jsonl", [dict(task_index=i, task=t) for i, t in enumerate(tasks)]) + jsonl("meta/episodes.jsonl", eps) + jsonl("meta/episodes_stats.jsonl", ep_stats) + jsonl("lff/provenance.jsonl", prov) + return prov + + +def summarize(prov): + per = collections.defaultdict(lambda: dict(episodes=0, frames=0, seeds=set())) + for p in prov: + d = per[p["task"]] + d["episodes"] += 1 + d["frames"] += p["length"] + d["seeds"].add(p["seed"]) + return {t: dict(episodes=d["episodes"], frames=d["frames"], seeds=sorted(d["seeds"])) for t, d in sorted(per.items())} + + +def cmd_build(a): + holdout = read_holdout(a.holdout, a.holdout_seed) + names = sources(a.extra_source) + clips, stats = [], collections.Counter() + with pool(a.workers) as ex: + for c, s in ex.map(functools.partial(plan_source, only_task=a.only_task), names): + clips += c + stats.update(s) + seen =collections.Counter((c["run"], c["attempt"], c["start"]) for c in clips) + dups = [k for k, v in seen.items() if v > 1] + if dups: + raise SystemExit(f"{len(dups)} duplicate clips, e.g. {dups[:3]}") + no_holdout = sorted({c["task"] for c in clips} - set(holdout)) + if no_holdout: + raise SystemExit(f"tasks without a held-out instance: {no_holdout}") + train = [c for c in clips if c["seed"] not in holdout[c["task"]]] + test = [c for c in clips if c["seed"] in holdout[c["task"]]] + report = dict(built_utc=time.strftime("%FT%TZ", time.gmtime()), sources=names, holdout={t: sorted(s) for t, s in holdout.items()}, + emergency_frames_cut=stats["emergency_frames_cut"]) + for split, group, repo in (("train", train, a.repo_id), ("heldout", test, a.repo_id + "_heldout")): + if split not in a.splits: + continue + out = os.path.join(a.out, repo) + if os.path.exists(os.path.join(out, "meta/info.json")): + raise SystemExit(f"{out} exists: datasets are not rewritten in place") + prov = write_dataset(out, group, a.workers) + 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}), + first_attempt=sum(p["first_attempt"] for p in prov), per_task=summarize(prov)) + json.dump(report, open(os.path.join(out, "lff/build_report.json"), "w"), indent=1) + print(split, report[split]["episodes"], "episodes", report[split]["frames"], "frames", report[split]["tasks"], "tasks", flush=True) + + +@functools.lru_cache(maxsize=64) +def source_meta(src): + """Per episode metadata of one release, and (first index, path) of each of its data files.""" + meta = {} + for mf in sorted(glob.glob(os.path.join(src, "meta/episodes/chunk-*/file-*.parquet"))): + keep = [c for c in pq.read_schema(mf).names if not c.startswith("stats/")] + for m in pq.read_table(mf, columns=keep).to_pylist(): + meta[m["episode_index"]] = m + files = [] + for df in sorted(glob.glob(os.path.join(src, "data/chunk-*/file-*.parquet"))): + files.append((int(pq.read_table(df, columns=["index"])["index"][0].as_py()), df)) + return meta, files + + +def source_frame(prov, t): + """State, action and both camera frames of one output frame, read directly from the published release.""" + src = os.path.join(DATA, prov["source"]) + f = prov["source_frame_start"] + t + metas, files = source_meta(src) + meta = metas[prov["source_episode"]] + i = meta["dataset_from_index"] + f + first, df = [x for x in files if x[0] <= i][-1] + row = read_data_file(df).slice(i - first, 1).to_pylist()[0] + if row["index"] != i: + raise SystemExit(f"source row lookup failed: {prov['source']} {i}") + imgs = {} + for cam, key in CAMERAS.items(): + 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") + ts = meta[f"videos/{key}/from_timestamp"] + f / FPS + with av.open(path) as c: + s = c.streams.video[0] + c.seek(int(ts / s.time_base), stream=s, backward=True) + for fr in c.decode(s): + if abs(float(fr.pts * s.time_base) - ts) < 1e-3: + imgs[cam] = fr.to_ndarray(format="rgb24") + break + return row, imgs + + +def cmd_verify(a): + """Reads the dataset through openpi's LeRobot exactly as training does and compares it with the published releases.""" + import lerobot.common.datasets.lerobot_dataset as ld + out = a.dir.rstrip("/") + root, repo = os.path.dirname(out), os.path.basename(out) + prov = [json.loads(x) for x in open(os.path.join(out, "lff/provenance.jsonl"))] + report = json.load(open(os.path.join(out, "lff/build_report.json"))) + meta = ld.LeRobotDatasetMetadata(repo, root=out) + H = 10 + ds = ld.LeRobotDataset(repo, root=out, delta_timestamps={"actions": [t / meta.fps for t in range(H)]}, video_backend="pyav") + checks = dict(n_frames=len(ds), n_episodes=meta.total_episodes, fps=meta.fps) + if len(ds) != sum(p["length"] for p in prov): + raise SystemExit("frame count differs from the provenance") + holdout = {t: set(s) for t, s in report["holdout"].items()} + leaked = [p for p in prov if (p["seed"] in holdout.get(p["task"], ())) != repo.endswith("_heldout")] + checks["instances_in_wrong_split"] = len(leaked) + rng = random.Random(0) + by_task = collections.defaultdict(list) + for p in prov: + by_task[p["task"]].append(p) + samples = [] + for t, ps in sorted(by_task.items()): + for j in range(a.per_task): + p = rng.choice(ps) + near_end = j % 2 == 1 and p["length"] > H # half of the samples test the chunks that reach the clip's end + samples.append((p, p["length"] - rng.randint(1, H - 1) if near_end else rng.randrange(p["length"]))) + state_err, act_err, img_err, chunk_err, pad_bad, prompts = [], [], [], [], 0, set() + tasks = {t["task_index"]: t["task"] for t in (json.loads(x) for x in open(os.path.join(out, "meta/tasks.jsonl")))} + for p, t in samples: + item = ds[p["index_from"] + t] + row, imgs = source_frame(p, t) + state_err.append(float(np.abs(item["state"].numpy() - np.asarray(row["observation.state"])).max())) + chunk = item["actions"].numpy() + act_err.append(float(np.abs(chunk[0] - np.asarray(row["action"])).max())) + if row["annotation.attempt_success"] != 1 or row["annotation.phase"] == 2: + raise SystemExit(f"frame with the wrong label in the dataset: {p['source']} {p['source_episode']} {t}") + for j in range(1, H): + if t + j >= p["length"]: # past the clip's end the loader must repeat the last action, not read the next clip + last = ds.hf_dataset[p["index_from"] + p["length"] - 1]["actions"].numpy() + chunk_err.append(float(np.abs(chunk[j] - last).max())) + pad_bad += int(not item["actions_is_pad"][j]) + for cam in CAMERAS: + got = (item[cam].numpy().transpose(1, 2, 0) * 255).round() + img_err.append(float(np.abs(got - imgs[cam].astype(float)).mean())) + prompts.add(tasks[int(item["task_index"])] == item["task"]) + checks.update(samples=len(samples), max_state_err=max(state_err), max_action_err=max(act_err), max_image_mae=max(img_err), + 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}) + actions = np.concatenate([np.asarray(ds.hf_dataset[p["index_from"]]["actions"])[None] for p in prov[:50]]) + checks["first_actions_range"] = [float(actions.min()), float(actions.max())] + 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 + and not pad_bad and prompts == {True}) + json.dump(checks, open(os.path.join(out, "lff/verify_report.json"), "w"), indent=1) + print(json.dumps(checks, indent=1)) + if not checks["pass"]: + raise SystemExit("VERIFY FAILED") + + +def cmd_norm(a): + """openpi's scripts/compute_norm_stats.py computes state and action-chunk statistics, decoding every video frame on + the way. This feeds the same RunningStats the same arrays from the parquet files, so it takes seconds.""" + from openpi.shared import normalize + out = a.dir.rstrip("/") + stats = {key: normalize.RunningStats() for key in ("state", "actions")} + eps = [json.loads(x) for x in open(os.path.join(out, "meta/episodes.jsonl"))] + for e in eps: + i = e["episode_index"] + t = pq.read_table(os.path.join(out, f"data/chunk-{i // CHUNK:03d}/episode_{i:06d}.parquet"), columns=["state", "actions"]) + state = np.stack(t["state"].to_numpy(zero_copy_only=False)) + act = np.stack(t["actions"].to_numpy(zero_copy_only=False)) + idx = np.minimum(np.arange(len(act))[:, None] + np.arange(a.horizon)[None, :], len(act) - 1) # the loader's clamping + stats["state"].update(state) + stats["actions"].update(act[idx]) + norm = {key: s.get_statistics() for key, s in stats.items()} + normalize.save(a.assets, norm) + print(f"wrote {a.assets}/norm_stats.json from {len(eps)} episodes") + for key, n in norm.items(): + print(key, "q01", np.round(n.q01, 4).tolist(), "q99", np.round(n.q99, 4).tolist()) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = ap.add_subparsers(dest="cmd", required=True) + n = sub.add_parser("norm") + n.add_argument("dir") + n.add_argument("--assets", required=True, help="//") + n.add_argument("--horizon", type=int, default=10) + n.set_defaults(fn=cmd_norm) + b = sub.add_parser("build") + b.add_argument("--out", required=True) + b.add_argument("--repo-id", required=True) + b.add_argument("--holdout", help="sets/ file naming the held-out instance of each task") + b.add_argument("--holdout-seed", nargs="*", help="task:seed items for tasks not in that file") + b.add_argument("--extra-source", nargs="*", help="packages not in the canonical release yet") + b.add_argument("--splits", nargs="*", default=["train", "heldout"]) + b.add_argument("--only-task", nargs="*", help="keep only these tasks (development datasets)") + b.add_argument("--workers", type=int, default=6) + b.set_defaults(fn=cmd_build) + v = sub.add_parser("verify") + v.add_argument("dir") + v.add_argument("--per-task", type=int, default=3) + v.set_defaults(fn=cmd_verify) + a = ap.parse_args() + a.fn(a) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/make_dossier.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/make_dossier.py new file mode 100644 index 0000000000000000000000000000000000000000..b0b97724e0cc03cb852d8fc0ece158512e008827 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/make_dossier.py @@ -0,0 +1,103 @@ +"""Build the record of an earlier failed attempt for the full5 history arms (docs/14 ยง6). + + python scripts/make_dossier.py [--attempt 1] [--allow-success] + +The record contains only what the agent of that attempt saw: the starting images, every robot command with the +robot's reply (as logged by robot_server), the images those commands produced, the agent's closing remark and the +F1 verdict ("failed"). No outcome codes, measurements or hidden variables. The same builder is used for the own-history +arm (record of a failed independent run on the same instance) and the mismatched arm (record of a failed run on the +twin instance: same layout, different hidden variable), so the two dossiers differ only in content. +""" +import argparse +import json +import os +import shutil + +DROP = ("state_file", "attempt_ended", "camera_file") + + +def shell_args(args): + out = [] + for k, v in args.items(): + v = json.dumps(v) if not isinstance(v, str) else v + out.append(f'{k}="{v}"' if (" " in v or not v) else f"{k}={v}") + return " ".join(out) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("log") + ap.add_argument("out") + ap.add_argument("--attempt", type=int, default=1) + ap.add_argument("--allow-success", action="store_true") + ap.add_argument("--result-extra", default="", + help="layer-3 ladder (docs/20): text appended to the verdict in the Result section (paragraphs " + "separated by blank lines; the first one continues the verdict line). Empty = F1 record, " + "byte-identical to the record built without this option.") + a = ap.parse_args() + evs = [json.loads(line) for line in open(os.path.join(a.log, "events.jsonl")) if line.strip()] + start = next(e for e in evs if e["ev"] == "session_start") + if start.get("style", "la") not in ("la", None) and "style" in start: + raise SystemExit("only la-style runs are supported") + calls = [e for e in evs if e["ev"] == "call" and e.get("attempt") == a.attempt] + done = [e for e in evs if e["ev"] == "done" and e.get("attempt") == a.attempt] + if not done: + raise SystemExit(f"attempt {a.attempt} has no done event (run unfinished?)") + done = done[0] + if done["success"] and not a.allow_success: + raise SystemExit(f"attempt {a.attempt} succeeded; nothing to learn from (use --allow-success to force)") + imgs = os.path.join(a.log, "images") + # commands as that agent issued them: `./robot ` in a CLI workspace, the `robot` tool's argument otherwise + try: + iface = json.load(open(os.path.join(a.log, "agent_iface.json"))).get("agent_iface", "cli") + except OSError: + iface = "cli" + pre = "./robot " if iface == "cli" else "" + os.makedirs(os.path.join(a.out, "obs"), exist_ok=False) + + def copy(rel): + base = os.path.basename(rel) + src = os.path.join(imgs, f"a{a.attempt}_{base}") + if not os.path.exists(src): + return None + shutil.copy(src, os.path.join(a.out, "obs", base)) + return f"obs/{base}" + + # starting images: the first images the agent saw (status at step 0) + first = sorted(f for f in os.listdir(imgs) if f.startswith(f"a{a.attempt}_") and "s000_" in f) + start_imgs = [copy(f.split("_", 1)[1]) for f in first] + lines = ["# Record of the earlier attempt", "", + "Starting scene: " + ", ".join(p for p in start_imgs if p), "", + "## Robot commands and replies", ""] + rec = [] + for i, e in enumerate(calls, 1): + rep = {k: v for k, v in (e.get("report") or {}).items() if k not in DROP} + if "images" in rep: + rep["images"] = [p2 for p2 in (copy(p) for p in rep["images"]) if p2] + cmd = f"{pre}{e['cmd']} {shell_args(e.get('args') or {})}".strip() + lines += [f"{i}. `{cmd}`", " reply: `" + json.dumps(rep) + "`", ""] + rec.append(dict(n=i, command=cmd, reply=rep)) + lines += [f"{len(calls) + 1}. `{pre}finish reason=\"{done.get('reason', '')}\"`", "", + "## Closing remark of that attempt", "", str(done.get("reason", "")), "", + "## Result", ""] + verdict = "The environment judged that attempt: " + ("succeeded." if done["success"] else "failed.") + extra = [x.strip() for x in a.result_extra.split("\n\n") if x.strip()] + if extra: + verdict += " " + extra[0] + lines += [verdict, ""] + for x in extra[1:]: + lines += [x, ""] + with open(os.path.join(a.out, "README.md"), "w") as f: + f.write("\n".join(lines)) + with open(os.path.join(a.out, "record.jsonl"), "w") as f: + for r in rec: + f.write(json.dumps(r) + "\n") + with open(os.path.join(os.path.dirname(os.path.abspath(a.out)), os.path.basename(a.out) + ".source.json"), "w") as f: + json.dump(dict(log=os.path.abspath(a.log), attempt=a.attempt, task=start.get("task"), seed=start.get("seed"), + arm=start.get("arm", "none"), n_commands=len(calls), success=done["success"], + result_extra=a.result_extra), f) + print(json.dumps(dict(out=a.out, n_commands=len(calls), n_images=len(os.listdir(os.path.join(a.out, "obs")))))) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/make_video.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/make_video.py new file mode 100644 index 0000000000000000000000000000000000000000..f4bd60f3d819d908ea813c25f79acec08b6a3cd7 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/make_video.py @@ -0,0 +1,132 @@ +"""Record a scripted rollout of a task as an mp4 (agentview | wrist), with title cards between attempts. + +python scripts/make_video.py --task l1_bias_place --kind adaptive --seed 1000 +""" +import argparse +import importlib +import os +import pkgutil +import sys +import textwrap + +import numpy as np + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) + +import imageio # noqa: E402 +from PIL import Image, ImageDraw, ImageFont # noqa: E402 + +import lffbench.tasks as task_pkg # noqa: E402 +from lffbench import envs # noqa: E402 +from lffbench.task_base import TASKS # noqa: E402 + +for m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{m.name}") + +RES = 320 +FPS = 15 + + +def font(size): + try: + return ImageFont.load_default(size=size) + except TypeError: + return ImageFont.load_default() + + +def header(img, lines): + im = Image.fromarray(img) + d = ImageDraw.Draw(im) + d.rectangle([0, 0, im.width, 18 * len(lines) + 6], fill=(0, 0, 0)) + for i, s in enumerate(lines): + d.text((6, 3 + 18 * i), s, fill=(255, 255, 255), font=font(15)) + return np.asarray(im) + + +def card(lines, w, h, color=(20, 20, 20)): + im = Image.new("RGB", (w, h), color) + d = ImageDraw.Draw(im) + y = 20 + for s in lines: + for part in textwrap.wrap(s, 70) or [""]: + d.text((20, y), part, fill=(255, 255, 255), font=font(18)) + y += 24 + y += 6 + return np.asarray(im) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--task", required=True) + ap.add_argument("--kind", default="adaptive") + ap.add_argument("--seed", type=int, default=1000) + ap.add_argument("--k", type=int, default=5) + ap.add_argument("--every", type=int, default=3, help="record one frame every N control steps") + ap.add_argument("--out", default=None) + args = ap.parse_args() + + task = TASKS[args.task]() + env = task.env + inst = task.sample_instance(args.seed) + frames = [] + state = dict(n=0, attempt=1) + W = 2 * RES + + def grab(): + a = envs.render(env, "agentview", RES) + w = envs.render(env, "robot0_eye_in_hand", RES) + img = np.concatenate([a, w], axis=1) + return header(img, [f"{args.task} [{task.level}] policy={args.kind} seed={args.seed}", + f"attempt {state['attempt']} t={state['n'] * 0.05:5.1f}s (sim) left: agentview right: wrist"]) + + orig_step = env.step + + def step(a): + out = orig_step(a) + state["n"] += 1 + if state["n"] % args.every == 0: + frames.append(grab()) + return out + + env.step = step + + def on_attempt(a, params, out): + txt = [f"Attempt {a + 1}: {'SUCCESS' if out['success'] else 'FAILED'}"] + if out.get("detail"): + txt.append("Feedback (F2): " + out["detail"]) + p = {k: (round(v, 3) if isinstance(v, float) else v) for k, v in (params or {}).items() + if not isinstance(v, (list, dict)) or len(str(v)) < 120} + if p: + txt.append(f"params: {p}") + if not out["success"]: + txt.append(f"-> attempt {a + 2}") + frames.extend([card(txt, W, RES, (40, 20, 20) if not out["success"] else (20, 50, 20))] * (FPS * 3)) + state["attempt"] = a + 2 + + intro = card([f"Task: {args.task} (level {task.level}; capabilities: {', '.join(task.capabilities)})", + f"Instruction: {task.instruction}", + f"Policy: {args.kind} (scripted reference)", + "Hidden variables are not visible to the policy."], W, RES) + frames.extend([intro] * (FPS * 3)) + task.reset_instance(inst) + frames.append(grab()) + n_cards_before = len(frames) + hist = task.run_scripted(args.kind, inst, k=args.k, seed=args.seed, on_attempt=on_attempt) + # tasks whose run_scripted does not call on_attempt: summarise at the end + if not any(f is not None and f.shape[0] == RES and (f[5, 5] == np.array([40, 20, 20])).all() for f in frames[n_cards_before:]) \ + and not any((f[5, 5] == np.array([20, 50, 20])).all() for f in frames[n_cards_before:]): + lines = [] + for h in hist: + o = h["outcome"] + lines.append(f"Attempt {h['attempt']}: {'SUCCESS' if o['success'] else 'FAILED'} โ€” {o.get('detail', '')}") + frames.extend([card(lines[-6:], W, RES)] * (FPS * 4)) + out = args.out or os.path.join(ROOT, "videos", f"{args.task}_{args.kind}_s{args.seed}.mp4") + os.makedirs(os.path.dirname(out), exist_ok=True) + imageio.mimwrite(out, frames, fps=FPS, quality=7, macro_block_size=8) + first = next((h["attempt"] for h in hist if h["outcome"]["success"]), None) + print(f"wrote {out} frames={len(frames)} attempts={len(hist)} first_success={first}") + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/mcp_robot_server.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/mcp_robot_server.py new file mode 100644 index 0000000000000000000000000000000000000000..18f433abeec51793dbf999e9da2a165b16d9393d --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/mcp_robot_server.py @@ -0,0 +1,140 @@ +"""MCP server (stdio) exposing one robot_server session to a native agent harness (Claude Code, Codex, Gemini CLI, ...). + +The tools are exactly the unified harness's LA tools (scripts/api_player.py): `robot`, `shell` (jailed, in the episode +workspace) and `view_images` (returned as MCP image content), with the same per-attempt tool-call budget: when it is +used up the attempt is finished automatically and the result is appended to that call's output. So a native harness +and the API harness see the same README, tools and limits; only the agent loop around them differs. + + python scripts/mcp_robot_server.py --session runs/<...>/session.json + python scripts/mcp_robot_server.py --schema-only (launch preflight: same tools/list, no session, every call fails) +Every call is logged to /mcp_transcript.jsonl (the first line lists the names of the environment variables the +harness passed to this process, for the harness self-check). Nothing but JSON-RPC goes to stdout. +The tools themselves are scripts/tool_gateway.py's ToolCore: through the episode's tool gateway when the launcher +started one (gateway.json in the log dir; docs/18 ยง6.1), otherwise in this process. +""" +import argparse +import json +import os +import sys +import time +import traceback + +ENV_AT_START = dict(os.environ) # what the harness passed (before our own imports touch the environment) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "client")) +from api_player import SHELL_TOOL, TOOL_LA, VIEW_TOOL_LA # noqa: E402 +from lffbench_client import Session as Client # noqa: E402 +from tool_gateway import GATEWAY_FILE, ToolCore # noqa: E402 + +PROTOCOL_VERSIONS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05") +TOOLS = [TOOL_LA, SHELL_TOOL, VIEW_TOOL_LA] + + +class Session: + """One episode's tools. With a tool gateway (scripts/tool_gateway.py, started by harness_run.py; its gateway.json is + in the run's log dir) every call goes to the gateway, which owns the per-attempt budget for the whole episode, also + across the MCP processes of a resumed CLI. Without one, the same ToolCore runs in this process and the budget is + carried over from mcp_transcript.jsonl. Either way the tool outputs are the gateway's ToolCore's, byte for byte.""" + + def __init__(self, session_path): + self.log_dir = os.path.dirname(os.path.abspath(session_path)) + tpath = os.path.join(self.log_dir, "mcp_transcript.jsonl") + gfile = os.path.join(self.log_dir, GATEWAY_FILE) + self.gateway = Client.from_gateway_file(gfile, face="mcp") if os.path.exists(gfile) else None + self.core = None if self.gateway else ToolCore(session_path, carry_from=tpath) + self.calls_in_attempt = self.core.calls_in_attempt if self.core else None + self.finished = self.core.finished if self.core else False + self.tlog = open(tpath, "a") + + def log(self, d): + d["t"] = time.time() + self.tlog.write(json.dumps(d, ensure_ascii=False) + "\n") + self.tlog.flush() + + def call(self, name, args): + """-> (MCP content list, is_error)""" + if self.core is not None: + content, err = self.core.call(name, args) + self.calls_in_attempt, self.finished = self.core.calls_in_attempt, self.core.finished + return content, err + r = self.gateway.call(name, args) + self.calls_in_attempt, self.finished = r.calls_in_attempt, r.finished + return r.content, r.is_error + + +class SchemaOnly: + """No robot session: the harness preflight only needs tools/list (byte-identical to a real session).""" + finished = False + + def log(self, d): + pass + + def call(self, name, args): + return [dict(type="text", text="schema-only preflight server: no robot session")], True + + +def serve(sess): + def send(obj): + sys.stdout.write(json.dumps(obj) + "\n") + sys.stdout.flush() + + for line in sys.stdin: + line = line.strip() + if not line: + continue + try: + msg = json.loads(line) + except ValueError: + send(dict(jsonrpc="2.0", id=None, error=dict(code=-32700, message="parse error"))) + continue + mid, method, params = msg.get("id"), msg.get("method"), msg.get("params") or {} + if mid is None: # notification (notifications/initialized, cancelled, ...) + continue + try: + if method == "initialize": + want = params.get("protocolVersion") + result = dict(protocolVersion=want if want in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0], + capabilities=dict(tools=dict(listChanged=False)), + serverInfo=dict(name="lffbench-robot", version="1.0")) + elif method == "ping": + result = {} + elif method == "tools/list": + result = dict(tools=[dict(name=t["name"], description=t["description"], inputSchema=t["parameters"]) + for t in TOOLS]) + elif method == "tools/call": + name, args = params.get("name"), params.get("arguments") or {} + t0 = time.time() + content, err = sess.call(name, args) + sess.log(dict(ev="tool", name=name, arguments=args, dt=round(time.time() - t0, 2), is_error=err, + output=[c["text"] for c in content if c["type"] == "text"], + images=sum(1 for c in content if c["type"] == "image"), finished=sess.finished, + calls_in_attempt=getattr(sess, "calls_in_attempt", None))) + result = dict(content=content, isError=err) + else: + send(dict(jsonrpc="2.0", id=mid, error=dict(code=-32601, message=f"method not found: {method}"))) + continue + send(dict(jsonrpc="2.0", id=mid, result=result)) + except Exception as e: + sess.log(dict(ev="error", method=method, error=traceback.format_exc()[-2000:])) + send(dict(jsonrpc="2.0", id=mid, error=dict(code=-32603, message=f"{type(e).__name__}: {e}"))) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--session", help="session.json written by start_robot_session.sh (la style)") + ap.add_argument("--schema-only", action="store_true", help="serve the tool list only (harness launch preflight)") + a = ap.parse_args() + if a.schema_only: + serve(SchemaOnly()) + return + if not a.session: + ap.error("--session is required (or --schema-only)") + sess = Session(a.session) + import hashlib # names + 8-hex sha256 of each value (enough to tell inherited from fresh values, reveals nothing) + sess.log(dict(ev="start", session=a.session, pid=os.getpid(), env_keys=sorted(ENV_AT_START), + env_value_sha8={k: hashlib.sha256(v.encode()).hexdigest()[:8] for k, v in ENV_AT_START.items()})) + serve(sess) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/mismatch_plan.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/mismatch_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..986d7fd5fef959b1b3f8e81170b90acb02fec62e --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/mismatch_plan.py @@ -0,0 +1,149 @@ +"""Mismatched-history control for layer 2 (user 2026-10-27: "้”™้…ๅކๅฒ็š„ๅšไธ€ไธ‹"; design docs/14 ยง6 Do / Dm, current protocol). + +Instances: the 9 hidden-variable tasks that have a twin (l7_key_turn has none), every Claude main-table instance +(Sonnet 5.5: cc_main1 / cc_sonnet_s2 / cc_sonnet_s3; Opus 5.5: cc_opus1 / cc_opus_s2 / cc_opus_s3) whose attempt 1 failed. +Arms, all fresh single-attempt agents (= the memory-free retries of the main table) with the same model and CLI: + tw_ twin instance (--arm twin: same layout, the hidden variable takes another value); its failed run is the + mismatched record. If the twin attempt succeeds there is no record: one more twin run (tw2_), then give up. + do_ own record: history/ = attempt 1 of the instance's main-table history run (scripts/make_dossier.py) + dm_ mismatched record: history/ = the failed twin run. README byte-identical to do_; only history/ differs. + + python3 scripts/mismatch_plan.py own build own records + write //own.json and tasks_.txt + python3 scripts/mismatch_plan.py twin build twin records from tw_ (+ tw2_) -> //twin.json; + prints the instances still without a failed twin run + python3 scripts/mismatch_plan.py report per instance: main-table attempt 2 with history (H2) and first + memory-free retry (N2), Do, Dm, twin; totals and paired counts + -> /report.json + markdown on stdout +""" +import json +import os +import subprocess +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +API = os.path.join(ROOT, "runs", "api") +OUT = os.path.join(API, "mismatch_20261027") +TWIN_TASKS = ["l7_offcenter_push", "l5_slide_to_target", "l5_tablecloth_pull", "l3_wall_flush", "l3_under_table_tool", + "l4_fit_container", "l2_turntable_restore", "l3_card_shelf", "l5_loaded_beam"] +MAIN = {"opus": ["cc_opus1", "cc_opus_s2", "cc_opus_s3"], "sonnet": ["cc_main1", "cc_sonnet_s2", "cc_sonnet_s3"]} + + +def runs(batch): + return json.load(open(os.path.join(API, batch, "manifest.json")))["runs"] + + +def attempt1(log): + for line in open(os.path.join(log, "events.jsonl")): + e = json.loads(line) + if e.get("ev") == "done" and e.get("attempt") == 1: + return e + return None + + +def dossier(log, out): + if not os.path.isdir(out): + subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "make_dossier.py"), log, out], check=True, + capture_output=True) + return out + + +def cmd_own(): + for m, batches in MAIN.items(): + own, tasks = {}, [] + for b in batches: + for r in runs(b): + if r["cond"] != "harness" or r["task"] not in TWIN_TASKS or r["status"] != "done": + continue + d = attempt1(r["log"]) + if d is None or d["success"]: + continue + key = f"{r['task']}:{r['seed']}" + own[key] = dossier(r["log"], os.path.join(OUT, m, "own", f"{r['task']}_s{r['seed']}")) + tasks.append(key) + os.makedirs(os.path.join(OUT, m), exist_ok=True) + json.dump(own, open(os.path.join(OUT, m, "own.json"), "w"), indent=1) + open(os.path.join(OUT, m, f"tasks_{m}.txt"), "w").write("\n".join(tasks) + "\n") + print(m, len(tasks)) + + +def cmd_twin(m): + want = [l.strip() for l in open(os.path.join(OUT, m, f"tasks_{m}.txt")) if l.strip()] + twin = {} + for b in (f"tw_{m}", f"tw2_{m}"): + if not os.path.exists(os.path.join(API, b, "manifest.json")): + continue + for r in runs(b): + key = f"{r['task']}:{r['seed']}" + if key in twin or r["status"] != "done": + continue + d = attempt1(r["log"]) + if d is not None and not d["success"]: + twin[key] = dossier(r["log"], os.path.join(OUT, m, "twin", f"{r['task']}_s{r['seed']}")) + json.dump(twin, open(os.path.join(OUT, m, "twin.json"), "w"), indent=1) + print(json.dumps(dict(model=m, with_record=len(twin), missing=[k for k in want if k not in twin]))) + + +# twin oracle also solves the original instance (docs/14 ยง6.4, 10-12 validation): mismatch is weak there +WEAK = {"l3_wall_flush", "l3_under_table_tool"} + + +def single(batch): + """task:seed -> True / False (attempt 1 of the batch's done run), None if not run or not finished.""" + out = {} + if not os.path.exists(os.path.join(API, batch, "manifest.json")): + return out + for r in runs(batch): + if r["status"] == "done": + d = attempt1(r["log"]) + out[f"{r['task']}:{r['seed']}"] = None if d is None else bool(d["success"]) + return out + + +def main_rows(batches): + rows = {} + for b in batches: + tmp = os.path.join(OUT, f".oc_{b}.json") + subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "outcomes.py"), "--batch", b, "--json", tmp], + check=True, capture_output=True) + for r in json.load(open(tmp))["rows"]: + rows[f"{r['task']}:{r['seed']}"] = dict(batch=b, history=r["history"], memfree=r["memfree"]) + os.remove(tmp) + return rows + + +def cmd_report(): + rep, md = {}, [] + for m, batches in MAIN.items(): + want = [l.strip() for l in open(os.path.join(OUT, m, f"tasks_{m}.txt")) if l.strip()] + main = main_rows(batches) + do, dm = single(f"do_{m}"), single(f"dm_{m}") + t1, t2 = single(f"tw_{m}"), single(f"tw2_{m}") # "twin" = F if some twin run failed (a record exists) + tw = {k: (False if False in (t1.get(k), t2.get(k)) else t1.get(k)) for k in set(t1) | set(t2)} + rows = [] + for k in want: + h, mf = main[k]["history"] or "", main[k]["memfree"] or "" + rows.append(dict(inst=k, task=k.split(":")[0], weak=k.split(":")[0] in WEAK, + H2=(h[1] == "S") if len(h) > 1 else None, N2=(mf[1] == "S") if len(mf) > 1 and mf[1] in "SF" else None, + Do=do.get(k), Dm=dm.get(k), twin=tw.get(k))) + def rate(key, sub): + v = [r[key] for r in sub if r[key] is not None] + return f"{sum(v)}/{len(v)}" if v else "-" + both = [r for r in rows if r["Do"] is not None and r["Dm"] is not None] + pairs = dict(n=len(both), do_only=sum(r["Do"] and not r["Dm"] for r in both), + dm_only=sum(r["Dm"] and not r["Do"] for r in both), both=sum(r["Do"] and r["Dm"] for r in both)) + rep[m] = dict(rows=rows, pairs=pairs) + md += [f"### {m}", "", "| instance | twin run | H2 (history, main) | N2 (memory-free, main) | Do (own record) | Dm (twin record) |", + "|---|---|---|---|---|---|"] + f = lambda v: "-" if v is None else ("S" if v else "F") + for r in rows: + md.append(f"| {r['inst']}{' (weak)' if r['weak'] else ''} | {f(r['twin'])} | {f(r['H2'])} | {f(r['N2'])} | {f(r['Do'])} | {f(r['Dm'])} |") + strong = [r for r in rows if not r["weak"]] + md += ["", f"all: H2 {rate('H2', rows)}, N2 {rate('N2', rows)}, Do {rate('Do', rows)}, Dm {rate('Dm', rows)}; " + f"strong mismatch only: Do {rate('Do', strong)}, Dm {rate('Dm', strong)}; " + f"paired Do/Dm n={pairs['n']}: Do only {pairs['do_only']}, Dm only {pairs['dm_only']}, both {pairs['both']}", ""] + json.dump(rep, open(os.path.join(OUT, "report.json"), "w"), indent=1) + print("\n".join(md)) + + +if __name__ == "__main__": + {"own": lambda: cmd_own(), "twin": lambda: cmd_twin(sys.argv[2]), "report": lambda: cmd_report()}[sys.argv[1]]() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/model_gateway.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/model_gateway.py new file mode 100644 index 0000000000000000000000000000000000000000..c8f4c48692827e11db9a73a7fc4000d35215785c --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/model_gateway.py @@ -0,0 +1,562 @@ +"""Per-run model-API gateway: the native harness's only road to its model API (docs/15 ยง3.2, docs/18 ยง3 rows 5 and 8). + +The harness (Codex, Claude Code, a robot harness framework on Codex) is pointed at this process instead of its model +API; the gateway forwards model requests unchanged to the same upstream with the harness's own credentials (it never +stores or logs a key or a header) and refuses, without forwarding, everything that would let the model use something +outside the benchmark's three tools: + - a path that is not a model call (connectors, apps, plugins, files, conversations, web search endpoints, ...); + - a request declaring a tool the harness does not run itself: any OpenAI tool type other than function / custom / + namespace (web_search, file_search, code_interpreter, image_generation, remote mcp, computer_use, local_shell ...), + any Anthropic tool with a server/built-in type (web_search_*, web_fetch_*, code_execution_*, bash_*, ...); + - a provider-side field (stored prompt, remote MCP servers, search options, containers); + - an image or file given as an http(s) address for the provider to fetch (data: URLs are fine); + - a body the gateway cannot read (more than one Content-Encoding, an encoding it cannot decode, not one JSON object). +A refusal is answered 403 with an error naming the reason and is recorded; it does not void the trial (nothing tells +the agent trying is forbidden), the launcher flags it in harness.json for a look. Same rules as Embodied First Exam's +usage gateway (running.md "Usage gateway"); the motivating case there: a harness offered tools that ran on the +provider's servers, outside the container's network rules, and agents used them. + +It also counts tokens per request from the response (OpenAI `response.completed` usage, Anthropic message_start / +message_delta usage, or a JSON body's usage), records every model name a request names (docs/18 ยง3 row 5: every call of +the run uses the model under test), and can stop the run at a token budget (`budget_stop`). + + python scripts/model_gateway.py --upstream https://api.openai.com/v1 --kind openai --log-dir +writes /model_gateway.json {url, port, pid, upstream_host} once it listens, one line per request to +/model_gateway_usage.jsonl (method, path, status, refusal reason, tool types, model, tokens; never a body or +a header) and the running totals to /model_gateway_totals.json. Listens on 127.0.0.1 only. Not part of +contract_sha256 (an access path, like tool_gateway.py). +""" +import argparse +import gzip +import http.client +import json +import os +import re +import shutil +import ssl +import subprocess +import sys +import threading +import time +import urllib.parse +import urllib.request +import uuid +import zlib +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +GATEWAY_FILE = "model_gateway.json" +USAGE_LOG = "model_gateway_usage.jsonl" +TOTALS = "model_gateway_totals.json" +MAX_BODY = 256 * 1024 * 1024 +READ_TIMEOUT_S = 1800 + +# model calls, as paths relative to the upstream base URL (query strings ignored) +ALLOWED_PATHS = { + "openai": [("POST", r"responses"), ("POST", r"responses/compact"), ("POST", r"responses/input_tokens"), + ("GET", r"models(/[^/]+)?")], + "anthropic": [("POST", r"v1/messages"), ("POST", r"v1/messages/count_tokens"), ("GET", r"v1/models(/[^/]+)?")], +} +# DeepSeek Harness uploads request images (--allow-files): same provider, same key, no other use than the next request +FILE_PATHS = [("POST", r"v1/files"), ("GET", r"v1/files(/[^/]+)?"), ("DELETE", r"v1/files/[^/]+")] +# what a harness sends by itself at start-up without being a model call: refused, counted apart, not a refusal +HARNESS_PROBES = {"anthropic": [("HEAD", r"api/hello"), ("GET", r"api/hello")]} +OPENAI_CLIENT_TOOL_TYPES = {None, "function", "custom", "namespace"} +PROVIDER_SIDE_FIELDS = { + "openai": {"prompt", "mcp_servers", "web_search_options", "container", "plugins", "search_parameters", + "enable_search", "tool_resources"}, + "anthropic": {"mcp_servers", "container"}, +} +HOP = {"connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", + "upgrade", "host", "content-length", "accept-encoding"} + + +# ------------------------------------------------------------------------------------------------------- checks +def decode_body(raw, encoding): + """-> (decoded bytes or None, note). One Content-Encoding at most.""" + enc = [e.strip().lower() for e in (encoding or "").split(",") if e.strip() and e.strip().lower() != "identity"] + if not enc: + return raw, None + if len(enc) > 1: + return None, "several content encodings" + e = enc[0] + try: + if e == "gzip": + return gzip.decompress(raw), None + if e == "deflate": + return zlib.decompress(raw), None + if e == "zstd": + try: + import zstandard + return zstandard.ZstdDecompressor().decompressobj().decompress(raw), None + except ImportError: + if shutil.which("zstd"): + p = subprocess.run(["zstd", "-d", "-c"], input=raw, capture_output=True, timeout=60) + if p.returncode == 0: + return p.stdout, None + return None, "zstd body and neither the zstandard module nor the zstd program" + except Exception as ex: + return None, f"{e}: {type(ex).__name__}" + return None, f"unsupported content encoding {e}" + + +def _tool_types_openai(tools, out): + for t in tools or []: + if not isinstance(t, dict): + out.append(("", False)) + continue + ty = t.get("type") + out.append((ty, ty in OPENAI_CLIENT_TOOL_TYPES)) + if ty == "namespace": + _tool_types_openai(t.get("tools"), out) + + +def declared_tools(kind, body): + """-> [(type, allowed)] for every tool the request declares (top-level, inside input items, inside namespaces).""" + out = [] + if kind == "openai": + _tool_types_openai(body.get("tools"), out) + for it in body.get("input") or []: + if isinstance(it, dict) and "tools" in it: + _tool_types_openai(it.get("tools"), out) + else: + for t in body.get("tools") or []: + ty = t.get("type") if isinstance(t, dict) else "" + out.append((ty, ty in (None, "custom"))) + return out + + +def remote_fetches(obj): + """Structured fields that ask the provider to fetch an http(s) address (images, files, documents).""" + hits = [] + + def walk(o): + if isinstance(o, dict): + for k in ("image_url", "file_url", "url"): + v = o.get(k) + if isinstance(v, dict): + v = v.get("url") + if isinstance(v, str) and re.match(r"https?://", v, re.I) and ( + k != "url" or o.get("type") in ("url", "image_url", "input_image", "input_file")): + hits.append(k) + src = o.get("source") + if isinstance(src, dict) and src.get("type") == "url": + hits.append("source.url") + for v in o.values(): + walk(v) + elif isinstance(o, list): + for v in o: + walk(v) + walk(obj.get("input") if "input" in obj else obj.get("messages")) + return hits + + +def check_request(kind, method, rel, headers, raw, allow_files=False): + """-> (refusal reason or None, info dict). info: tool types, model, probe flag.""" + info = {} + path = rel.split("?", 1)[0].strip("/") + if allow_files and any(method == m and re.fullmatch(pat, path) for m, pat in FILE_PATHS): + info["files"] = True + return None, info + for m, pat in HARNESS_PROBES.get(kind, []): + if method == m and re.fullmatch(pat, path): + return "harness_probe", info + if not any(method == m and re.fullmatch(pat, path) for m, pat in ALLOWED_PATHS[kind]): + return "path_not_allowed", info + if method != "POST": + return None, info + body, note = decode_body(raw, headers.get("Content-Encoding")) + if body is None: + info["note"] = note + return "body_unreadable", info + try: + obj = json.loads(body) + except ValueError: + return "body_unreadable", info + if not isinstance(obj, dict): + return "body_unreadable", info + info["model"] = obj.get("model") + tools = declared_tools(kind, obj) + info["tool_types"] = sorted({str(t) for t, _ in tools}) + info["n_tools"] = len(tools) + bad = sorted({str(t) for t, ok in tools if not ok}) + if bad: + info["refused_tool_types"] = bad + return "server_tool", info + side = sorted(PROVIDER_SIDE_FIELDS[kind] & set(obj)) + if side: + info["provider_side_fields"] = side + return "provider_side_field", info + rf = remote_fetches(obj) + if rf: + info["remote_fetch"] = sorted(set(rf)) + return "remote_fetch", info + return None, info + + +# ------------------------------------------------------------------------------------------------------- usage +def _norm_usage(kind, u): + if not isinstance(u, dict): + return {} + if kind == "openai": + return dict(input=u.get("input_tokens"), cached_input=(u.get("input_tokens_details") or {}).get("cached_tokens"), + output=u.get("output_tokens"), + reasoning=(u.get("output_tokens_details") or {}).get("reasoning_tokens")) + return dict(input=u.get("input_tokens"), cached_input=u.get("cache_read_input_tokens"), + cache_write=u.get("cache_creation_input_tokens"), output=u.get("output_tokens")) + + +class UsageTap: + """Reads the response as it streams by (SSE lines or one JSON body) and keeps the last usage it reports.""" + + def __init__(self, kind, ctype): + self.kind, self.sse = kind, "event-stream" in (ctype or "") + self.buf, self.usage = b"", {} + + def feed(self, chunk): + self.buf += chunk + if not self.sse: + if len(self.buf) > 64 * 1024 * 1024: + self.buf = b"" + return + *lines, self.buf = self.buf.split(b"\n") + for ln in lines: + if ln.startswith(b"data:") and b"usage" in ln: + try: + ev = json.loads(ln[5:].strip()) + except ValueError: + continue + self._event(ev) + + def _event(self, ev): + if not isinstance(ev, dict): + return + if self.kind == "openai" and ev.get("type") in ("response.completed", "response.incomplete", "response.failed"): + self.usage = _norm_usage("openai", (ev.get("response") or {}).get("usage")) + elif self.kind == "anthropic": + if ev.get("type") == "message_start": + self.usage = _norm_usage("anthropic", (ev.get("message") or {}).get("usage")) + elif ev.get("type") == "message_delta" and isinstance(ev.get("usage"), dict): + u = _norm_usage("anthropic", ev["usage"]) + self.usage.update({k: v for k, v in u.items() if v is not None}) + + def close(self): + if not self.sse and self.buf: + try: + obj = json.loads(self.buf) + if isinstance(obj, dict) and "usage" in obj: + self.usage = _norm_usage(self.kind, obj["usage"]) + except ValueError: + pass + return self.usage + + +# ------------------------------------------------------------------------------------------------------- forwarding +SYSTEM_CA_FILES = ("/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/certs/ca-bundle.crt", "/etc/ssl/cert.pem") + + +def ca_file(): + """SSL_CERT_FILE, else certifi's bundle, else the system bundle: the venv's Python may ship without a CA store + (README: "API ๆŠฅ่ฏไนฆ้”™่ฏฏ").""" + if os.environ.get("SSL_CERT_FILE"): + return os.environ["SSL_CERT_FILE"] + try: + import certifi + return certifi.where() + except ImportError: + return next((p for p in SYSTEM_CA_FILES if os.path.exists(p)), None) + + +def upstream_connection(u): + """HTTP(S) connection to the upstream host, through HTTPS_PROXY / HTTP_PROXY unless NO_PROXY exempts it.""" + host, port = u.hostname, u.port or (443 if u.scheme == "https" else 80) + proxy = None if urllib.request.proxy_bypass(host) else urllib.request.getproxies().get(u.scheme) + if u.scheme == "https": + ctx = ssl.create_default_context(cafile=ca_file()) + if proxy: + p = urllib.parse.urlsplit(proxy) + c = http.client.HTTPSConnection(p.hostname, p.port or 80, context=ctx, timeout=READ_TIMEOUT_S) + c.set_tunnel(host, port) + return c, False + return http.client.HTTPSConnection(host, port, context=ctx, timeout=READ_TIMEOUT_S), False + if proxy: + p = urllib.parse.urlsplit(proxy) + return http.client.HTTPConnection(p.hostname, p.port or 80, timeout=READ_TIMEOUT_S), True + return http.client.HTTPConnection(host, port, timeout=READ_TIMEOUT_S), False + + +class Totals: + KEYS = ("requests", "forwarded", "harness_probes", "refused_paths", "refused_server_tools", "refused_fields", + "refused_remote_fetch", "refused_bodies", "refused_budget", "upstream_errors") + + def __init__(self, path, budget_in=None, budget_out=None): + self.path, self.lock = path, threading.Lock() + self.d = {k: 0 for k in self.KEYS} + self.d.update(tokens=dict(input=0, cached_input=0, output=0, reasoning=0), models={}, refused_examples=[], + budget_in=budget_in, budget_out=budget_out, budget_stop=None) + + def over_budget(self): + t = self.d["tokens"] + if self.d["budget_in"] is not None and t["input"] >= self.d["budget_in"]: + return "input" + if self.d["budget_out"] is not None and t["output"] >= self.d["budget_out"]: + return "output" + return None + + def add(self, rec): + with self.lock: + d = self.d + d["requests"] += 1 + r = rec.get("refused") + key = dict(harness_probe="harness_probes", path_not_allowed="refused_paths", server_tool="refused_server_tools", + provider_side_field="refused_fields", remote_fetch="refused_remote_fetch", + body_unreadable="refused_bodies", budget_stop="refused_budget").get(r) + if key: + d[key] += 1 + if r != "harness_probe" and len(d["refused_examples"]) < 20: + d["refused_examples"].append({k: rec.get(k) for k in ("method", "path", "refused", "refused_tool_types", + "provider_side_fields", "note")}) + elif rec.get("status") is None: + d["upstream_errors"] += 1 + else: + d["forwarded"] += 1 + if rec.get("model"): + d["models"][rec["model"]] = d["models"].get(rec["model"], 0) + 1 + for k, v in (rec.get("usage") or {}).items(): + if isinstance(v, int) and k in d["tokens"]: + d["tokens"][k] += v + if d["budget_stop"] is None and self.over_budget(): + d["budget_stop"] = dict(which=self.over_budget(), t=time.time()) + tmp = self.path + ".tmp" + with open(tmp, "w") as f: + json.dump(d, f, indent=1) + os.replace(tmp, self.path) + + +def serve(upstream, kind, log_dir, port=0, budget_in=None, budget_out=None, gateway_file=None, watch_parent=True, + allow_files=False): + up = urllib.parse.urlsplit(upstream.rstrip("/")) + base_path = up.path.rstrip("/") + ulog = open(os.path.join(log_dir, USAGE_LOG), "a") + llock = threading.Lock() + totals = Totals(os.path.join(log_dir, TOTALS), budget_in, budget_out) + opencode_session = "lffbench-" + uuid.uuid4().hex # one per gateway, i.e. per run + + def log(rec): + with llock: + ulog.write(json.dumps(rec, default=str) + "\n") + ulog.flush() + totals.add(rec) + + class H(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *a): + pass + + def _refuse(self, code, reason, detail): + body = json.dumps({"error": {"type": "lff_gateway_refused", "code": reason, + "message": f"refused by the benchmark's model gateway: {detail}"}}).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + if self.command != "HEAD": + self.wfile.write(body) + + def _read_body(self): + if "chunked" in (self.headers.get("Transfer-Encoding") or "").lower(): + out = b"" + while True: + n = int(self.rfile.readline().split(b";")[0].strip() or b"0", 16) + if n == 0: + self.rfile.readline() + return out + out += self.rfile.read(n) + self.rfile.readline() + if len(out) > MAX_BODY: + raise ValueError("body too large") + n = int(self.headers.get("Content-Length") or 0) + if n < 0 or n > MAX_BODY: + raise ValueError("bad Content-Length") + return self.rfile.read(n) if n else b"" + + def _handle(self): + t0 = time.time() + path = self.path + rel = path[len(base_path):] if base_path and path.startswith(base_path + "/") else ( + path if not base_path else None) + rec = dict(t=t0, method=self.command, path=path.split("?", 1)[0][:200]) + try: + raw = self._read_body() + except Exception as ex: + rec.update(refused="body_unreadable", note=str(ex)[:100]) + log(rec) + return self._refuse(400, "body_unreadable", "unreadable request body") + if rel is None: + reason, info = "path_not_allowed", {} + else: + reason, info = check_request(kind, self.command, rel, self.headers, raw, allow_files) + if reason is None and totals.d["budget_stop"] is not None and self.command == "POST": + reason = "budget_stop" + rec.update(info, req_bytes=len(raw)) + if reason: + rec["refused"] = reason + log(rec) + detail = dict(harness_probe="not a model call", path_not_allowed="not a model-API call", + server_tool="tool types run by the provider: " + ",".join(info.get("refused_tool_types", [])), + provider_side_field="provider-side fields: " + ",".join(info.get("provider_side_fields", [])), + remote_fetch="the provider would fetch an http(s) address", body_unreadable="unreadable body", + budget_stop="token budget of this run used up")[reason] + return self._refuse(404 if reason == "harness_probe" else 403, reason, detail) + hdrs = {k: v for k, v in self.headers.items() if k.lower() not in HOP} + hdrs["Accept-Encoding"] = "identity" + if up.hostname == "opencode.ai" and not any(k.lower() == "x-opencode-session" for k in hdrs): + hdrs["x-opencode-session"] = opencode_session # OpenCode Go refuses requests without one + if raw or self.command == "POST": + hdrs["Content-Length"] = str(len(raw)) + conn = None + try: + conn, absolute = upstream_connection(up) + target = f"{up.scheme}://{up.netloc}{path}" if absolute else path + conn.request(self.command, target, body=raw if raw or self.command == "POST" else None, headers=hdrs) + resp = conn.getresponse() + except Exception as ex: + rec.update(status=None, error=f"{type(ex).__name__}: {ex}"[:300], dur_s=round(time.time() - t0, 2)) + log(rec) + if conn is not None: + conn.close() + body = json.dumps({"error": {"type": "lff_gateway_upstream", "message": "upstream unreachable"}}).encode() + self.send_response(502) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + return + ctype = resp.getheader("Content-Type", "") + tap = UsageTap(kind, ctype) + self.send_response(resp.status) + for k, v in resp.getheaders(): + if k.lower() not in HOP: + self.send_header(k, v) + self.send_header("Transfer-Encoding", "chunked") + self.end_headers() + n_out, logged = 0, False + try: + while True: + chunk = resp.read1(65536) if hasattr(resp, "read1") else resp.read(65536) + if not chunk: + break + tap.feed(chunk) + n_out += len(chunk) + self.wfile.write(b"%x\r\n%s\r\n" % (len(chunk), chunk)) + self.wfile.flush() + # record before the last chunk: a client holding the whole response finds its tokens counted + rec.update(status=resp.status, resp_bytes=n_out, usage=tap.close(), dur_s=round(time.time() - t0, 2)) + log(rec) + logged = True + self.wfile.write(b"0\r\n\r\n") + self.wfile.flush() + except (BrokenPipeError, ConnectionResetError): + rec["client_disconnected"] = True + finally: + conn.close() + if not logged: + rec.update(status=resp.status, resp_bytes=n_out, usage=tap.close(), + dur_s=round(time.time() - t0, 2)) + log(rec) + + do_GET = do_POST = do_PUT = do_DELETE = do_PATCH = do_HEAD = _handle + + srv = ThreadingHTTPServer(("127.0.0.1", port), H) + srv.daemon_threads = True + url = f"http://127.0.0.1:{srv.server_address[1]}{base_path}" + gfile = gateway_file or os.path.join(log_dir, GATEWAY_FILE) + tmp = gfile + ".tmp" + with open(tmp, "w") as f: + json.dump(dict(url=url, port=srv.server_address[1], pid=os.getpid(), kind=kind, upstream_host=up.hostname), f) + os.replace(tmp, gfile) + if watch_parent: + ppid = os.getppid() + + def watch(): + while os.getppid() == ppid: + time.sleep(2) + srv.shutdown() + threading.Thread(target=watch, daemon=True).start() + try: + srv.serve_forever(poll_interval=0.5) + finally: + srv.server_close() + + +def start_model_gateway(upstream, kind, log_dir, budget_in=None, budget_out=None, python=None, timeout_s=30, + allow_files=False): + """Start a gateway for one run (child of the caller) and wait until it listens. -> (Popen, info dict with url). + The caller stops it with stop_model_gateway().""" + gfile = os.path.join(log_dir, GATEWAY_FILE) + if os.path.exists(gfile): + os.remove(gfile) + argv = [python or sys.executable, os.path.abspath(__file__), "--upstream", upstream, "--kind", kind, + "--log-dir", log_dir] + if budget_in is not None: + argv += ["--budget-in", str(int(budget_in))] + if budget_out is not None: + argv += ["--budget-out", str(int(budget_out))] + if allow_files: + argv.append("--allow-files") + err = open(os.path.join(log_dir, "model_gateway_stderr.txt"), "ab") + p = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=err, stderr=err) + deadline = time.time() + timeout_s + while time.time() < deadline: + if p.poll() is not None: + raise RuntimeError(f"model gateway exited with code {p.returncode}; see {log_dir}/model_gateway_stderr.txt") + if os.path.exists(gfile): + return p, json.load(open(gfile)) + time.sleep(0.05) + stop_model_gateway(p) + raise RuntimeError(f"model gateway did not start within {timeout_s} s") + + +def stop_model_gateway(p): + if p is None or p.poll() is not None: + return + p.terminate() + try: + p.wait(timeout=10) + except subprocess.TimeoutExpired: + p.kill() + p.wait() + + +def read_totals(log_dir): + try: + return json.load(open(os.path.join(log_dir, TOTALS))) + except (OSError, ValueError): + return None + + +def flagged(totals): + """Refusals worth a look (EFE: refused_paths / refused_server_tools / refused_bodies), probes excluded.""" + if not totals: + return [] + return [k for k in ("refused_paths", "refused_server_tools", "refused_fields", "refused_remote_fetch", + "refused_bodies", "refused_budget") if totals.get(k)] + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--upstream", required=True, help="the model API base URL the harness would otherwise call") + ap.add_argument("--kind", required=True, choices=sorted(ALLOWED_PATHS)) + ap.add_argument("--log-dir", required=True) + ap.add_argument("--port", type=int, default=0) + ap.add_argument("--budget-in", type=int, default=None, help="stop forwarding once this many input tokens were used") + ap.add_argument("--budget-out", type=int, default=None, help="... output tokens (reasoning included)") + ap.add_argument("--no-watch-parent", action="store_true") + ap.add_argument("--allow-files", action="store_true", help="also forward the provider's Files API (FILE_PATHS)") + a = ap.parse_args() + serve(a.upstream, a.kind, a.log_dir, port=a.port, budget_in=a.budget_in, budget_out=a.budget_out, + watch_parent=not a.no_watch_parent, allow_files=a.allow_files) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/nest_compare.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/nest_compare.py new file mode 100644 index 0000000000000000000000000000000000000000..edd7ffde2150a1b22e90322d4d3fce48fc4ed352 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/nest_compare.py @@ -0,0 +1,71 @@ +"""Render what an agent would see for l4_nest_order: start, the naive (tallest-outermost) attempt's end, the true +order's end. Agentview + a wrist view taken from above the stack (the agent can always move there and look). + +python scripts/nest_compare.py --seeds 1000,1001,1002 --out results/l4_nest_order/compare +""" +import argparse +import os +import sys + +import numpy as np +from PIL import Image, ImageDraw + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) + +from lffbench import envs # noqa: E402 +from lffbench.tasks.l4_nest import NestOrder # noqa: E402 + +RES = 512 + + +def views(task, inst, look_at=None): + """agentview, and the wrist camera ~30 cm above the table over `look_at` (cup index) or at the start pose""" + a = envs.render(task.env, "agentview", RES) + if look_at is not None: + x, y = task._cup_state(inst, look_at)["p"][:2] + task.sk.move_to([x, y, envs.TABLE_Z + 0.30], yaw=0.0, tol=0.003) + envs.settle(task.env, 10) + w = envs.render(task.env, "robot0_eye_in_hand", RES) + return a, w + + +def row(label, a, w): + im = Image.new("RGB", (2 * RES, RES + 22), "white") + im.paste(Image.fromarray(a), (0, 22)) + im.paste(Image.fromarray(w), (RES, 22)) + ImageDraw.Draw(im).text((6, 5), label, fill="black") + return im + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--seeds", default="1000,1001,1002") + ap.add_argument("--out", default=os.path.join(ROOT, "results", "l4_nest_order", "compare")) + args = ap.parse_args() + os.makedirs(args.out, exist_ok=True) + task = NestOrder(cam_res=RES) + for seed in [int(s) for s in args.seeds.split(",")]: + inst = task.sample_instance(seed) + col = [c["color"] for c in inst["cups"]] + name = lambda order: " > ".join(col[j] for j in order) # noqa: E731 + rows = [] + task.reset_instance(inst) + rows.append(row(f"seed {seed} ({inst['case']}) start heights cm {dict(zip(col, inst['height_cm']))} " + f"openings cm {dict(zip(col, inst['opening_cm']))}", *views(task, inst))) + for kind, order in (("naive (tallest outermost)", inst["naive_order"]), ("true order", inst["order"])): + task.reset_instance(inst) + task.execute(inst, dict(order=list(order))) + o = task.outcome(inst) + rows.append(row(f"{kind}: {name(order)} -> {'SUCCESS' if o['success'] else 'FAIL'} | {o['detail']}"[:150], + *views(task, inst, look_at=order[0]))) + sheet = Image.new("RGB", (2 * RES, len(rows) * (RES + 22)), "white") + for k, r in enumerate(rows): + sheet.paste(r, (0, k * (RES + 22))) + p = os.path.join(args.out, f"compare_{seed}.jpg") + sheet.save(p, quality=88) + print(p, flush=True) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/outcome_audit.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/outcome_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..d08d4b1f88830c45ed083359fad0b7982df29a4d --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/outcome_audit.py @@ -0,0 +1,52 @@ +"""Explicit, hash-bound adjudications; no keyword inference from agent prose. + +The original evaluator is retained for comparisons. A reviewed verdict requires +the identical source files and a successful first attempt. Unreviewed successes +stay S? in audit mode, including legacy CS based only on absent trap counters. +""" +import hashlib +import json +from pathlib import Path + + +def sha256(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def load_audit(path): + data = json.loads(Path(path).read_text()) + if data.get("schema") != "lff-outcome-audit-1": + raise ValueError("Unsupported outcome audit schema") + result = {} + for entry in data["entries"]: + key = (entry["batch"], entry["run_id"]) + if key in result: + raise ValueError(f"Duplicate audit entry: {key}") + if entry["verdict"] not in ("CS", "IR", "S?"): + raise ValueError(f"Invalid audit verdict: {key}") + if entry.get("attempt", 1) != 1: + raise ValueError(f"Audit entry must refer to attempt 1: {key}") + if not entry.get("basis") or not entry.get("sources"): + raise ValueError(f"Missing basis/source binding: {key}") + if entry["verdict"] == "IR" and not all(entry.get(k) for k in ("failure", "repair")): + raise ValueError(f"IR requires physical failure and agent repair evidence: {key}") + if entry["verdict"] == "CS" and entry.get("coverage") != "all_recorded_commands": + raise ValueError(f"CS requires full command review: {key}") + result[key] = entry + return result + + +def adjudicate(audit, batch, run, first_success): + entry = audit.get((batch, run["id"])) + if entry is None: + return "S?", "No reviewed evidence for this successful first attempt." + if not first_success or entry["task"] != run["task"] or entry["seed"] != run["seed"]: + raise ValueError("Audit does not match the run / first-attempt success") + root = Path(run["log"]).resolve() + if "events.jsonl" not in entry["sources"]: + raise ValueError("Audit must bind events.jsonl") + for name, digest in entry["sources"].items(): + path = (root / name).resolve() + if not path.is_relative_to(root) or sha256(path) != digest: + raise ValueError(f"Audit source changed or escaped run directory: {name}") + return entry["verdict"], entry["basis"] diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/outcomes.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/outcomes.py new file mode 100644 index 0000000000000000000000000000000000000000..3df0c20085a48b77bcae6967009d489b8f8ff310 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/outcomes.py @@ -0,0 +1,141 @@ +"""Per-instance outcomes of api_batch.py --memfree followup batches, in the paper's terms (paper/01 ยง4 3.6): + + CS attempt 1 succeeded with no error event in it IR attempt 1 succeeded after an error event (repaired + XR attempt 1 failed, a later attempt succeeded within the attempt) + F no attempt succeeded S? attempt 1 succeeded, but the task logs no error events + (CS or IR cannot be told apart) + A1 = CS + IR (+ S?), A3 = A1 + XR (history condition); pass@k = the memory-free chain (attempt 1 shared with the + history run, then fresh agents) succeeded; delta = A3 - pass@k, paired per instance. Tasks whose scene persists + between attempts (protocol "within") have no memory-free chain and are listed apart (user 2026-10-20). + + python scripts/outcomes.py --batch cx_main1 [--batch ...] [--json out.json] + +An error event is read from the task's outcome dict of the successful attempt: trap_fired / recovered_in_attempt +true, or one of the n_* counters of mistakes (n_bad_pushes, n_wrong_way, n_regressions, n_load_falls, ...) above 0. +The finish reason of every failed attempt is printed so that false success claims can be judged (not judged here). +""" +import argparse +import ast +import json +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import api_batch # noqa: E402 + +ERROR_FLAGS = ("trap_fired", "recovered_in_attempt") +ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events", + "n_missed_strikes", "n_open_gripper_pushes") + + +def attempts(log): + """[(attempt, success, outcome dict, finish reason)] from the robot server log.""" + out = [] + p = os.path.join(log or "", "events.jsonl") + if not os.path.exists(p): + return out + for line in open(p): + e = json.loads(line) + if e.get("ev") != "done": + continue + o = e.get("outcome") or {} + if isinstance(o, str): + try: + o = ast.literal_eval(o) + except (ValueError, SyntaxError): + o = {} + out.append((int(e["attempt"]), e["success"] in (True, "True"), o, e.get("reason") or "")) + return sorted(out, key=lambda x: x[0]) + + +def error_event(o): + """True / False if the outcome dict says whether an error happened, None if the task logs no error events.""" + keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o] + if not keys: + return None + return any(bool(o[k]) for k in ERROR_FLAGS if k in o) or any((o.get(k) or 0) > 0 for k in ERROR_COUNTS if k in o) + + +def instance_rows(m, audit=None, batch=None): + rows = [] + for r in m["runs"]: + if not (r["cond"] == "harness" and r.get("followup")) or r["status"] != "done": + continue + att = attempts(r.get("log")) + if not att: + continue + if audit is not None and att[0][0] != 1: + raise ValueError(f"Cannot audit {r['task']}: first-attempt record is missing") + hist = "".join("S" if s else "F" for _, s, _, _ in att) + if att[0][1]: + ev = error_event(att[0][2]) + cls = "S?" if ev is None else ("IR" if ev else "CS") + else: + cls = "XR" if any(s for _, s, _, _ in att) else "F" + legacy_cls = cls + audit_basis = None + if audit is not None and att[0][1]: + from outcome_audit import adjudicate + cls, audit_basis = adjudicate(audit, batch, r, True) + within = api_batch.episode_protocol(r.get("log")) == "within" + chain = sorted((x for x in m["runs"] if x.get("chain") == r["id"]), key=lambda x: x["rep"]) + mf = None + if not within: + mf = hist[0] + "".join("S" if any(api_batch.attempt_results(x.get("log"))) else + ("F" if x["status"] == "done" else "?") for x in chain) + failed = [(a, reason) for a, s, _, reason in att if not s] + failed += [(f"mf{x['rep'] + 1}", rr) for x in chain for _, s, _, rr in attempts(x.get("log")) if not s] + rows.append(dict(task=r["task"], seed=r["seed"], cls=cls, legacy_cls=legacy_cls, + batch=batch, run_id=r["id"], audit_basis=audit_basis, + history=hist, memfree=mf, within=within, + a1=att[0][1], a3=any(s for _, s, _, _ in att), + passk=None if mf is None else ("S" in mf), failed_reasons=failed)) + return rows + + +def summary(rows): + n = len(rows) + paired = [x for x in rows if x["passk"] is not None and "?" not in (x["memfree"] or "")] + cnt = {c: sum(1 for x in rows if x["cls"] == c) for c in ("CS", "IR", "S?", "XR", "F")} + return dict(n=n, **cnt, A1=sum(x["a1"] for x in rows), A3=sum(x["a3"] for x in rows), n_paired=len(paired), + A3_paired=sum(x["a3"] for x in paired), passk_paired=sum(x["passk"] for x in paired), + delta_paired=(sum(x["a3"] for x in paired) - sum(x["passk"] for x in paired)) / max(1, len(paired))) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--batch", action="append", required=True) + ap.add_argument("--json", default=None) + ap.add_argument("--runs-root", help="read manifests from another checkout's runs/api directory") + ap.add_argument("--audit", help="hash-bound reviewed classifications (unreviewed first successes remain S?)") + a = ap.parse_args() + if a.runs_root: + api_batch.RUNS = os.path.abspath(a.runs_root) + audit = None + if a.audit: + from outcome_audit import load_audit + audit = load_audit(a.audit) + rows = [] + for b in a.batch: + rows += instance_rows(api_batch.load(b), audit=audit, batch=b) + print("Classification: " + ("reviewed evidence (see audit sources)" if audit is not None else + "legacy task-counter heuristic; CS/IR coverage is task-dependent")) + print("| task | seed | outcome | history | memory-free | note |\n|---|---|---|---|---|---|") + for x in rows: + print(f"| {x['task']} | {x['seed']} | {x['cls']} | {x['history']} | {x['memfree'] or 'โ€”'} | " + f"{'scene persists: no memory-free chain' if x['within'] else ''} |") + s = summary(rows) + print(f"\nn={s['n']} CS={s['CS']} IR={s['IR']} S?={s['S?']} XR={s['XR']} F={s['F']} A1={s['A1']}/{s['n']} " + f"A3={s['A3']}/{s['n']} paired (no persisting scene, chain finished): n={s['n_paired']} " + f"A3={s['A3_paired']} pass@k={s['passk_paired']} delta={s['delta_paired']:+.3f}") + print("\nfinish reasons of failed attempts (for judging false success claims):") + for x in rows: + for att, reason in x["failed_reasons"]: + print(f" {x['task']} {att}: {reason[:160]}") + if a.json: + with open(a.json, "w") as f: + json.dump(dict(rows=rows, summary=s), f, indent=1, ensure_ascii=False) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/qwen_vl_server.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/qwen_vl_server.py new file mode 100644 index 0000000000000000000000000000000000000000..33b002cb3516145787158a20c614a4bf1e3e551b --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/qwen_vl_server.py @@ -0,0 +1,535 @@ +#!/usr/bin/env python3 +"""Minimal OpenAI-compatible Chat Completions server (with tool calling) for Qwen3-VL. + +Runs a local HF-format Qwen3-VL checkpoint with transformers (>= 4.57) on one +CUDA-compatible device (here: Alibaba PPU) and exposes: + + POST /v1/chat/completions OpenAI chat.completion (non-streaming; stream=true + is emulated: the full answer is generated first + and then sent as SSE chunks) + GET /v1/models lists the single served model + GET /health liveness + device memory + +Request format accepted (subset of OpenAI): + messages: system / developer / user / assistant (with tool_calls) / tool + user/tool content may be a string or a list of + {"type":"text","text":...} and + {"type":"image_url","image_url":{"url": "data:image/...;base64,..." | http(s) URL | file path}} + tools: [{"type":"function","function":{"name","description","parameters"}}] + tool_choice: "auto" (default) | "none" (tools hidden from the prompt) | + "required" (generation is prefixed with "\n") | + {"type":"function","function":{"name":X}} (prefixed with the call header for X) + parallel_tool_calls: false -> only the first parsed tool call is returned + max_tokens / max_completion_tokens (default --default-max-tokens, 1024) + temperature (absent or 0 -> greedy), top_p, top_k, seed, stop (str or list) +Ignored: n (always 1), response_format, logprobs, presence/frequency penalty, user. + +The model emits Hermes-style {"name":..., "arguments":{...}} +blocks; they are parsed into choices[0].message.tool_calls with arguments as a JSON +string, and the remaining text (if any) becomes message.content (else null). + +Generation is serialised with a lock (one request on the device at a time); the +HTTP layer is a stdlib ThreadingHTTPServer so /health stays responsive. +""" +from __future__ import annotations + +import argparse +import base64 +import io +import json +import logging +import os +import re +import sys +import threading +import time +import traceback +import urllib.request +import uuid +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +LOG = logging.getLogger("qwen_vl_server") + +TOOL_CALL_RE = re.compile(r"\s*(.*?)\s*", re.DOTALL) +END_MARKERS = ("<|im_end|>", "<|endoftext|>") + + +# ---------------------------------------------------------------------------- +# Request conversion +# ---------------------------------------------------------------------------- +class BadRequest(Exception): + pass + + +def load_image(url: str): + from PIL import Image + + if url.startswith("data:"): + try: + _, b64 = url.split(",", 1) + except ValueError as e: + raise BadRequest("malformed data URL") from e + raw = base64.b64decode(b64) + elif url.startswith("http://") or url.startswith("https://"): + with urllib.request.urlopen(url, timeout=30) as r: + raw = r.read() + else: + path = url[len("file://"):] if url.startswith("file://") else url + with open(path, "rb") as f: + raw = f.read() + img = Image.open(io.BytesIO(raw)) + img.load() + return img.convert("RGB") + + +def convert_content(content, images: list): + """OpenAI content (str | list[part] | None) -> Qwen template content. + + Images are replaced by {"type": "image"} placeholders and the decoded PIL images + are appended to `images` in prompt order (the chat template emits one + <|vision_start|><|image_pad|><|vision_end|> per placeholder, in the same order). + """ + if content is None: + return "" + if isinstance(content, str): + return content + if not isinstance(content, list): + raise BadRequest(f"unsupported content type: {type(content).__name__}") + out = [] + for part in content: + if isinstance(part, str): + out.append({"type": "text", "text": part}) + continue + ptype = part.get("type") + if ptype in ("text", "input_text"): + out.append({"type": "text", "text": part.get("text", "")}) + elif ptype in ("image_url", "input_image", "image"): + iu = part.get("image_url", part.get("image")) + url = iu.get("url") if isinstance(iu, dict) else iu + if not isinstance(url, str): + raise BadRequest("image part without url") + try: + images.append(load_image(url)) + except BadRequest: + raise + except Exception as e: # noqa: BLE001 + raise BadRequest(f"could not load image ({url[:60]}...): {type(e).__name__}: {e}") from e + out.append({"type": "image"}) + else: + raise BadRequest(f"unsupported content part type: {ptype}") + return out + + +def text_only(content) -> str: + if content is None: + return "" + if isinstance(content, str): + return content + return "".join(p.get("text", "") for p in content if isinstance(p, dict)) + + +def convert_messages(messages: list): + if not isinstance(messages, list) or not messages: + raise BadRequest("messages must be a non-empty list") + images: list = [] + system_texts = [] + conv = [] + for m in messages: + role = m.get("role") + if role in ("system", "developer"): + # The Qwen template only renders a leading system message; merge all of them. + system_texts.append(text_only(m.get("content"))) + elif role == "user": + conv.append({"role": "user", "content": convert_content(m.get("content"), images)}) + elif role == "assistant": + c = m.get("content") + msg = {"role": "assistant", "content": text_only(c) if not isinstance(c, str) else c} + tcs = m.get("tool_calls") or [] + if tcs: + norm = [] + for tc in tcs: + fn = tc.get("function", tc) + args = fn.get("arguments", {}) + if not isinstance(args, str): + args = json.dumps(args, ensure_ascii=False) + norm.append({"type": "function", "function": {"name": fn.get("name", ""), "arguments": args}}) + msg["tool_calls"] = norm + conv.append(msg) + elif role in ("tool", "function"): + conv.append({"role": "tool", "content": convert_content(m.get("content"), images)}) + else: + raise BadRequest(f"unsupported role: {role}") + if system_texts: + conv.insert(0, {"role": "system", "content": "\n\n".join(system_texts)}) + return conv, images + + +# ---------------------------------------------------------------------------- +# Output parsing +# ---------------------------------------------------------------------------- +def _loads_lenient(s: str): + s = s.strip() + try: + return json.loads(s) + except json.JSONDecodeError: + pass + # common slips: trailing garbage after the object, missing final brace + start = s.find("{") + if start >= 0: + dec = json.JSONDecoder() + try: + obj, _ = dec.raw_decode(s[start:]) + return obj + except json.JSONDecodeError: + pass + for extra in ("}", "}}", "\"}}"): + try: + return json.loads(s[start:] + extra) + except json.JSONDecodeError: + continue + return None + + +def parse_tool_calls(text: str): + """Return (content_or_None, tool_calls_list).""" + calls = [] + spans = [] + for mt in TOOL_CALL_RE.finditer(text): + spans.append(mt.span()) + calls.append(mt.group(1)) + # an unterminated trailing (e.g. hit max_tokens / model forgot the tag) + last_end = spans[-1][1] if spans else 0 + tail_idx = text.find("", last_end) + if tail_idx >= 0: + spans.append((tail_idx, len(text))) + calls.append(text[tail_idx + len(""):]) + + tool_calls = [] + keep_raw = [] # unparsable blocks stay in content + for (a, b), body in zip(spans, calls): + obj = _loads_lenient(body) + if not isinstance(obj, dict) or "name" not in obj: + keep_raw.append((a, b)) + continue + args = obj.get("arguments", obj.get("parameters", {})) + if isinstance(args, str): + parsed = _loads_lenient(args) + args_str = json.dumps(parsed, ensure_ascii=False) if parsed is not None else args + else: + args_str = json.dumps(args, ensure_ascii=False) + tool_calls.append({ + "id": "call_" + uuid.uuid4().hex[:24], + "type": "function", + "function": {"name": str(obj["name"]), "arguments": args_str}, + }) + + # content = text with successfully parsed blocks removed + parsed_spans = [s for s in spans if s not in keep_raw] + pieces, pos = [], 0 + for a, b in sorted(parsed_spans): + pieces.append(text[pos:a]) + pos = b + pieces.append(text[pos:]) + content = "".join(pieces).strip() + return (content if content else None), tool_calls + + +# ---------------------------------------------------------------------------- +# Model wrapper +# ---------------------------------------------------------------------------- +class Engine: + def __init__(self, args): + import torch + from transformers import AutoModelForImageTextToText, AutoProcessor + + self.torch = torch + self.args = args + self.device = args.device + t0 = time.time() + proc_kwargs = {} + if args.min_pixels: + proc_kwargs["min_pixels"] = args.min_pixels + if args.max_pixels: + proc_kwargs["max_pixels"] = args.max_pixels + if args.attn == "sdpa" and not args.sdpa_native_gqa: + # PPU quirk (measured): torch SDPA with enable_gqa=True fails for decode steps + # (q_len=1, no mask) with "q must have shape (batch_size, seqlen_q, num_heads, + # head_size_og)". Make transformers repeat K/V heads itself instead. + import transformers.integrations.sdpa_attention as _sdpa + + _sdpa.use_gqa_in_sdpa = lambda attention_mask, key: False + self.processor = AutoProcessor.from_pretrained(args.model, **proc_kwargs) + self.tokenizer = self.processor.tokenizer + self.model = AutoModelForImageTextToText.from_pretrained( + args.model, + dtype=torch.bfloat16, + attn_implementation=args.attn, + device_map={"": self.device}, + ).eval() + self.load_time = time.time() - t0 + self.eos_ids = [self.tokenizer.convert_tokens_to_ids(t) for t in END_MARKERS] + self.eos_ids = [i for i in self.eos_ids if isinstance(i, int) and i >= 0] + self.pad_id = self.tokenizer.pad_token_id if self.tokenizer.pad_token_id is not None else self.eos_ids[-1] + self.lock = threading.Lock() + LOG.info("model loaded in %.1fs on %s (attn=%s); mem allocated %.2f GiB", + self.load_time, self.device, args.attn, torch.cuda.memory_allocated(self.device) / 2**30) + + def mem(self): + t = self.torch + return { + "allocated_gib": round(t.cuda.memory_allocated(self.device) / 2**30, 2), + "reserved_gib": round(t.cuda.memory_reserved(self.device) / 2**30, 2), + "max_allocated_gib": round(t.cuda.max_memory_allocated(self.device) / 2**30, 2), + } + + def chat(self, req: dict): + torch = self.torch + a = self.args + messages, images = convert_messages(req.get("messages")) + tools = req.get("tools") or None + tool_choice = req.get("tool_choice", "auto") + prefix = "" + if tools: + if tool_choice == "none": + tools = None + elif tool_choice == "required": + prefix = "\n" + elif isinstance(tool_choice, dict): + fname = (tool_choice.get("function") or {}).get("name") or tool_choice.get("name") + if fname: + prefix = '\n{"name": "' + fname + '", "arguments": ' + tmpl_tools = None + if tools: + tmpl_tools = [] + for t in tools: + if isinstance(t, dict) and "function" not in t and "name" in t: + t = {"type": "function", "function": t} + tmpl_tools.append(t) + + prompt = self.processor.apply_chat_template( + messages, tools=tmpl_tools, tokenize=False, add_generation_prompt=True + ) + prefix + inputs = self.processor( + text=[prompt], images=images if images else None, return_tensors="pt" + ).to(self.device) + n_prompt = int(inputs["input_ids"].shape[1]) + if n_prompt > a.max_prompt_tokens: + raise BadRequest(f"prompt has {n_prompt} tokens > --max-prompt-tokens {a.max_prompt_tokens}") + + max_new = req.get("max_completion_tokens") or req.get("max_tokens") or a.default_max_tokens + max_new = int(min(max_new, a.max_tokens_cap)) + temperature = req.get("temperature") + if temperature is None: + temperature = a.default_temperature + gen_kwargs = dict( + max_new_tokens=max_new, + eos_token_id=self.eos_ids, + pad_token_id=self.pad_id, + use_cache=True, + ) + if temperature and float(temperature) > 0: + gen_kwargs.update(do_sample=True, temperature=float(temperature), + top_p=float(req.get("top_p") or 0.8), top_k=int(req.get("top_k") or 20)) + else: + gen_kwargs.update(do_sample=False, temperature=None, top_p=None, top_k=None) + if req.get("seed") is not None: + torch.manual_seed(int(req["seed"])) + + with torch.inference_mode(): + out = self.model.generate(**inputs, **gen_kwargs) + new_ids = out[0, n_prompt:].tolist() + # count tokens up to and including the first EOS + n_completion = len(new_ids) + hit_eos = False + for i, tid in enumerate(new_ids): + if tid in self.eos_ids: + n_completion = i + 1 + hit_eos = True + break + text = self.tokenizer.decode(new_ids[:n_completion], skip_special_tokens=False) + for mk in END_MARKERS: + text = text.replace(mk, "") + text = prefix + text + + stop = req.get("stop") + stopped_by_str = False + if stop: + for s in ([stop] if isinstance(stop, str) else stop): + k = text.find(s, len(prefix)) + if k >= 0: + text = text[:k] + stopped_by_str = True + + if tools: + content, tool_calls = parse_tool_calls(text) + if tool_calls and req.get("parallel_tool_calls") is False: + tool_calls = tool_calls[:1] + else: + content, tool_calls = (text.strip() or None), [] + + if tool_calls: + finish = "tool_calls" + elif hit_eos or stopped_by_str: + finish = "stop" + else: + finish = "length" + message = {"role": "assistant", "content": content} + if tool_calls: + message["tool_calls"] = tool_calls + usage = {"prompt_tokens": n_prompt, "completion_tokens": n_completion, + "total_tokens": n_prompt + n_completion} + return message, finish, usage, len(images), text + + +# ---------------------------------------------------------------------------- +# HTTP +# ---------------------------------------------------------------------------- +ENGINE: Engine | None = None +ARGS = None + + +class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, fmt, *args): # route http.server logs through logging + LOG.debug("%s - %s", self.address_string(), fmt % args) + + def _send_json(self, code: int, obj): + body = json.dumps(obj, ensure_ascii=False).encode("utf-8") + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def _error(self, code: int, msg: str, etype: str): + self._send_json(code, {"error": {"message": msg, "type": etype, "code": code}}) + + def do_GET(self): + if self.path.rstrip("/") in ("/health", "/v1/health"): + self._send_json(200, {"status": "ok", "model": ARGS.served_name, "memory": ENGINE.mem(), + "load_time_s": round(ENGINE.load_time, 1)}) + elif self.path.rstrip("/") == "/v1/models": + self._send_json(200, {"object": "list", "data": [ + {"id": ARGS.served_name, "object": "model", "created": int(time.time()), "owned_by": "local"}]}) + else: + self._error(404, f"no route {self.path}", "not_found") + + def do_POST(self): + if self.path.rstrip("/") not in ("/v1/chat/completions", "/chat/completions"): + self._error(404, f"no route {self.path}", "not_found") + return + try: + n = int(self.headers.get("Content-Length", "0")) + req = json.loads(self.rfile.read(n).decode("utf-8")) + except Exception as e: # noqa: BLE001 + self._error(400, f"invalid JSON body: {e}", "invalid_request_error") + return + t0 = time.time() + try: + with ENGINE.lock: + t_lock = time.time() + message, finish, usage, n_img, raw = ENGINE.chat(req) + except BadRequest as e: + self._error(400, str(e), "invalid_request_error") + return + except Exception as e: # noqa: BLE001 + LOG.error("generation failed: %s\n%s", e, traceback.format_exc()) + if "out of memory" in str(e).lower(): + try: + ENGINE.torch.cuda.empty_cache() + except Exception: # noqa: BLE001 + pass + self._error(500, f"{type(e).__name__}: {e}", "server_error") + return + dt = time.time() - t0 + LOG.info("req images=%d prompt=%d completion=%d finish=%s tool_calls=%d queue=%.2fs gen=%.2fs mem=%s", + n_img, usage["prompt_tokens"], usage["completion_tokens"], finish, + len(message.get("tool_calls", [])), t_lock - t0, time.time() - t_lock, ENGINE.mem()) + if ARGS.log_outputs: + LOG.info("raw output: %r", raw) + cid = "chatcmpl-" + uuid.uuid4().hex[:24] + created = int(time.time()) + model_name = req.get("model") or ARGS.served_name + if req.get("stream"): + self._send_stream(cid, created, model_name, message, finish, usage, req) + return + self._send_json(200, { + "id": cid, + "object": "chat.completion", + "created": created, + "model": model_name, + "choices": [{"index": 0, "message": message, "finish_reason": finish, "logprobs": None}], + "usage": usage, + "server_timing": {"latency_s": round(dt, 3)}, + }) + + def _send_stream(self, cid, created, model_name, message, finish, usage, req): + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.send_header("Cache-Control", "no-cache") + self.send_header("Connection", "close") + self.end_headers() + self.close_connection = True + + def chunk(delta, fr=None, with_usage=False): + obj = {"id": cid, "object": "chat.completion.chunk", "created": created, "model": model_name, + "choices": [{"index": 0, "delta": delta, "finish_reason": fr, "logprobs": None}]} + if with_usage: + obj["usage"] = usage + self.wfile.write(b"data: " + json.dumps(obj, ensure_ascii=False).encode() + b"\n\n") + + chunk({"role": "assistant", "content": message.get("content") or ""}) + for i, tc in enumerate(message.get("tool_calls", [])): + chunk({"tool_calls": [dict(tc, index=i)]}) + include_usage = bool((req.get("stream_options") or {}).get("include_usage")) + chunk({}, finish, with_usage=include_usage) + self.wfile.write(b"data: [DONE]\n\n") + self.wfile.flush() + + +def main(): + global ENGINE, ARGS + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("--model", default=os.environ.get("QWEN_VL_MODEL", "Qwen/Qwen3-VL-8B-Instruct")) + p.add_argument("--served-name", default="Qwen3-VL-8B-Instruct") + p.add_argument("--host", default="127.0.0.1") + p.add_argument("--port", type=int, default=8765) + p.add_argument("--device", default="cuda:0") + p.add_argument("--attn", default="sdpa", choices=["sdpa", "eager", "flash_attention_2"]) + p.add_argument("--sdpa-native-gqa", action="store_true", + help="let torch SDPA do GQA (enable_gqa=True); broken on PPU for decode, off by default") + p.add_argument("--default-max-tokens", type=int, default=1024) + p.add_argument("--max-tokens-cap", type=int, default=8192) + p.add_argument("--max-prompt-tokens", type=int, default=65536) + p.add_argument("--default-temperature", type=float, default=0.0, + help="used when the request has no temperature; 0 = greedy") + p.add_argument("--min-pixels", type=int, default=0, help="override image processor min_pixels") + p.add_argument("--max-pixels", type=int, default=0, help="override image processor max_pixels") + p.add_argument("--log-outputs", action="store_true", help="log raw model output text per request") + p.add_argument("--warmup", action="store_true", help="run one tiny generation before serving") + ARGS = p.parse_args() + + logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s", stream=sys.stdout) + import transformers + + LOG.info("transformers %s from %s", transformers.__version__, os.path.dirname(transformers.__file__)) + ENGINE = Engine(ARGS) + if ARGS.warmup: + t = time.time() + with ENGINE.lock: + ENGINE.chat({"messages": [{"role": "user", "content": "Hi"}], "max_tokens": 4}) + LOG.info("warmup done in %.1fs", time.time() - t) + srv = ThreadingHTTPServer((ARGS.host, ARGS.port), Handler) + srv.daemon_threads = True + LOG.info("serving %s on http://%s:%d/v1/chat/completions", ARGS.served_name, ARGS.host, ARGS.port) + try: + srv.serve_forever() + except KeyboardInterrupt: + pass + finally: + srv.server_close() + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/real_check_driver.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/real_check_driver.py new file mode 100644 index 0000000000000000000000000000000000000000..678bbe888afa8ae295323a74d13cc80d908b22ad --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/real_check_driver.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +"""Conformance check of a robot driver (lffbench/real/protocol.py, spec lffbench/real/DRIVER.md). Run it on the robot PC +(or through the SSH tunnel) before the first real run, and again after any change to the driver. + + python scripts/real_check_driver.py --driver http://127.0.0.1:9900 --token [--yes] [--operator] [--json] + +The arm moves a little: 3 cm up and back, a 30 deg turn and back, the gripper closes and opens, all at 5 cm/s from +the current pose. Keep a hand on the e-stop. --yes skips the confirmation; --operator also tests the operator +prompts (you answer them on the driver's terminal). Needs only Python 3 + numpy + Pillow. +Exit code 0 = every check PASS (WARN does not fail). +""" +import argparse +import json +import os +import sys +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path[:0] = [HERE, os.path.join(os.path.dirname(HERE), "lffbench", "real")] # protocol.py next to it, or the repo copy +import numpy as np # noqa: E402 + +from protocol import (CAMERAS, DriverClient, DriverError, info_problems, state_problems) # noqa: E402 + + +class Checks: + def __init__(self): + self.rows = [] + + def add(self, name, status, detail=""): + self.rows.append(dict(name=name, status=status, detail=str(detail))) + print(f"[{status}] {name} {detail}", file=sys.stderr, flush=True) + return status == "PASS" + + def ok(self, name, cond, detail="", warn=False): + return self.add(name, "PASS" if cond else ("WARN" if warn else "FAIL"), detail) + + +def yaw_diff(a, b): + return abs((a - b + 90.0) % 180.0 - 90.0) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--driver", default=os.environ.get("LFF_REAL_DRIVER", "http://127.0.0.1:9900")) + ap.add_argument("--token", default=os.environ.get("LFF_DRIVER_TOKEN", "")) + ap.add_argument("--yes", action="store_true", help="do not ask before moving the arm") + ap.add_argument("--operator", action="store_true", help="also test the operator prompts (reset, judge)") + ap.add_argument("--json", action="store_true", help="print a JSON summary as the last line of stdout") + ap.add_argument("--yaw-tol", type=float, default=2.0, help="degrees (keep 2 for a real arm)") + a = ap.parse_args() + C = Checks() + d = DriverClient(a.driver, a.token, timeout=120) + try: + run(C, d, a) + except DriverError as e: + C.add("driver answered every request", "FAIL", e) + n_fail = sum(r["status"] == "FAIL" for r in C.rows) + print(f"\n{len(C.rows) - n_fail} ok / {n_fail} FAIL", file=sys.stderr) + if a.json: + print(json.dumps(dict(checks=C.rows, n_fail=n_fail))) + sys.exit(1 if n_fail else 0) + + +def run(C, d, a): + # ---- no motion + bad = DriverClient(d.url, d.token + "-wrong") + try: + rep = bad.call("state", allow_not_ok=True) + C.ok("wrong token is refused", rep.get("ok") is False, rep.get("error", "")) + except DriverError as e: + C.add("wrong token is refused", "FAIL", e) + info = d.call("info") + prob = info_problems(info) + if not C.ok("/info has every field", not prob, "; ".join(prob) or {k: info[k] for k in ("robot", "n_joints", "workspace")}): + return + n = int(info["n_joints"]) + st = d.state() + prob = state_problems(st, n) + if not C.ok("/state has every field", not prob, "; ".join(prob) or st): + return + lo, hi = np.array(info["workspace"]["lo"]), np.array(info["workspace"]["hi"]) + p0 = np.array(st["eef_pos"]) + C.ok("current grasp point inside the declared workspace", bool(np.all(p0 >= lo) and np.all(p0 <= hi)), p0.round(4).tolist()) + t0 = time.time() + frames, st2 = d.observe() + dt = time.time() - t0 + for c in CAMERAS: + f = frames[c] + C.ok(f"/observe {c}: RGB image", f.ndim == 3 and f.shape[2] == 3 and min(f.shape[:2]) >= 256, + f"{f.shape[1]}x{f.shape[0]}") + C.ok(f"/observe {c}: not blank", float(f.std()) > 5.0, f"pixel std {f.std():.1f}") + h, w = f.shape[:2] + C.ok(f"/observe {c}: square or close to it (the benchmark centre-crops to a square)", 0.75 <= w / h <= 1.34, + f"{w}x{h}: {abs(w - h) // 2} px cut on each side", warn=True) + C.ok("/observe also returns the state", not state_problems(st2, n)) + C.ok("/observe latency", dt < 2.0, f"{dt:.2f} s", warn=True) + rep = d.call("event", dict(ev="session_start", run="check_driver", task="check", seed=0)) + C.ok("/event answers", rep["ok"]) + rep = d.operator("notice", run="check_driver", attempt=0, text="real_check_driver.py: conformance check running") + C.ok("/operator notice answers", rep["ok"]) + if info["ik"]: + q = d.ik(st["eef_pos"], st["eef_yaw_deg"]) + err = float(np.max(np.abs(np.array(q) - np.array(st["joint_pos_rad"])))) if len(q) == n else None + C.ok("/ik of the current pose = current joint angles (within 0.05 rad)", err is not None and err < 0.05, + f"max |dq| = {err}") + # ---- rejected targets: must not move + for name, tgt in (("far outside the workspace (x + 1 m)", [hi[0] + 1.0, p0[1], p0[2]]), + ("below the workspace floor (z - 5 cm)", [p0[0], p0[1], lo[2] - 0.05])): + rep = d.move(*tgt, st["eef_yaw_deg"], 0.05) + moved = float(np.linalg.norm(np.array(rep["state"]["eef_pos"]) - p0)) + C.ok(f"/move {name} is rejected and the arm does not move", rep["ok"] is False and moved < 0.005, + f"ok={rep['ok']} error={rep.get('error')!r} moved {moved * 100:.1f} cm") + # ---- motion + if not a.yes: + input("\nThe arm will now move 3 cm up and back, turn 30 deg and back, close and open the gripper, at 5 cm/s.\n" + "Keep a hand on the e-stop and press Enter... ") + up = p0 + [0.0, 0.0, 0.03] + if up[2] > hi[2]: + up = p0 - [0.0, 0.0, 0.03] + y0 = float(st["eef_yaw_deg"]) + rep = d.move(*up, y0, 0.05) + p = np.array(rep["state"]["eef_pos"]) + C.ok("/move 3 cm vertical: ok", rep["ok"], rep.get("error", "")) + C.ok("/move 3 cm vertical: reached within 5 mm", np.linalg.norm(p - up) < 0.005, f"error {np.linalg.norm(p - up) * 1000:.1f} mm") + C.ok("/move 3 cm vertical: blocking, motion_s plausible at 5 cm/s", 0.3 <= rep["motion_s"] <= 5.0, f"motion_s={rep['motion_s']}") + C.ok("/move keeps the yaw (within 2 deg)", yaw_diff(rep["state"]["eef_yaw_deg"], y0) < 2.0, + f"{rep['state']['eef_yaw_deg']:.1f} vs {y0:.1f}") + y1 = y0 + 30.0 if y0 + 30.0 <= info["yaw_range_deg"][1] else y0 - 30.0 + rep = d.move(*up, y1, 0.05) + C.ok(f"/move turn 30 deg: reached within {a.yaw_tol:g} deg", rep["ok"] and yaw_diff(rep["state"]["eef_yaw_deg"], y1) < a.yaw_tol, + f"{rep['state']['eef_yaw_deg']:.1f} vs {y1:.1f}") + C.ok("/move turn 30 deg: position kept (within 5 mm)", np.linalg.norm(np.array(rep["state"]["eef_pos"]) - up) < 0.005) + sign = 1.0 if y1 > y0 else -1.0 + C.add("yaw sign (look at the arm)", "NOTE", + f"it just turned {sign * 30:+.0f} deg: + must be counter-clockwise seen from above (DRIVER.md ยง3)") + rep = d.move(*up, y0, 0.05) + C.ok("/move turn back", rep["ok"] and yaw_diff(rep["state"]["eef_yaw_deg"], y0) < a.yaw_tol, + f"{rep['state']['eef_yaw_deg']:.1f} vs {y0:.1f}") + rep = d.gripper(True) + w_closed = rep["state"]["gripper_width_m"] + C.ok("/gripper close: width < 1 cm when closed on nothing", w_closed < 0.01, f"{w_closed:.4f} m, motion_s={rep['motion_s']}") + rep = d.gripper(False) + w_open = rep["state"]["gripper_width_m"] + C.ok("/gripper open: width > 3 cm", w_open > 0.03, f"{w_open:.4f} m") + rep = d.move(*p0, y0, 0.05) + C.ok("/move back to the start pose", rep["ok"] and np.linalg.norm(np.array(rep["state"]["eef_pos"]) - p0) < 0.005) + rep = d.home() + C.ok("/home answers with the state", rep["ok"] and not state_problems(rep["state"], n)) + rep = d.call("event", dict(ev="attempt_start", run="check_driver", attempt=1)) # starts the driver's recorder + time.sleep(2.0) + rep2 = d.call("event", dict(ev="attempt_end", run="check_driver", attempt=1)) + C.ok("/event attempt_start / attempt_end answer (recording)", rep["ok"] and rep2["ok"], + "check that the driver wrote a short video (driver_template: /check_driver_a1.mp4)") + if a.operator: + rep = d.operator("reset", run="check_driver", attempt=1, setup="(test) nothing to change, just press Enter") + C.ok("/operator reset returns after Enter", rep["ok"]) + rep = d.operator("judge", run="check_driver", attempt=1, checklist=["(test) answer y"]) + C.ok("/operator judge returns success", rep.get("success") is True, rep) + d.call("event", dict(ev="session_end", run="check_driver")) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/record_breakfast_service.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/record_breakfast_service.py new file mode 100644 index 0000000000000000000000000000000000000000..bc1731b46da0c9383c1513fde541833bfbbd8180 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/record_breakfast_service.py @@ -0,0 +1,89 @@ +"""Continuous simulation recording with a magnified crop; no state edits or model calls.""" +import argparse, hashlib, json +from pathlib import Path +import imageio.v2 as imageio +import numpy as np +from PIL import Image, ImageDraw, ImageFont +from lffbench import envs +from lffbench.tasks.lh_breakfast_service import BreakfastService +import robosuite.utils.transform_utils as T + +FONT='/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf' + +class Recorder: + def __init__(self,t,out): + self.t=t;self.out=out;self.n=0;self.frames=0;self.timeline=[] + self.phase='Prepare breakfast';self.focus='food';self.raw_n=0 + self.raw=imageio.get_writer(str(out/'breakfast_full_1x.mp4'),fps=5,codec='libx264',quality=8,macro_block_size=1) + self.preview=imageio.get_writer(str(out/'breakfast_recovery_2x.mp4'),fps=10,codec='libx264',quality=8,macro_block_size=1) + self.original=t.env.step;t.env.step=self.step + # Rendering-only side camera makes the reopened lid's gap visible. + m=t.env.sim.model;cid=m.camera_name2id('sideview') + pos=np.array([-.28,-.58,1.16]);target=np.array([-.20,-.10,.96]) + z=(pos-target)/np.linalg.norm(pos-target);x=np.cross([0,0,1],z);x/=np.linalg.norm(x);y=np.cross(z,x) + q=T.mat2quat(np.column_stack([x,y,z])) + m.cam_pos[cid]=pos;m.cam_quat[cid]=q[[3,0,1,2]];m.cam_fovy[cid]=45 + t.env.sim.forward() + def step(self,a): + result=self.original(a);self.n+=1 + if self.n%4==0:self.capture() + return result + def frame(self): + return Image.fromarray(envs.render(self.t.env,res=768)) + def decorate(self,im): + canvas=Image.new('RGB',(1280,928),(19,26,36));canvas.paste(im,(0,48)) + crop={'milk':(440,180,760,500),'lid':(150,230,470,550),'food':(0,220,320,540)}[self.focus] + detail=(Image.fromarray(envs.render(self.t.env,cam='sideview',res=512)) if self.focus=='lid' + else im.crop(crop).resize((512,512),Image.Resampling.LANCZOS)) + canvas.paste(detail,(768,80)) + d=ImageDraw.Draw(canvas);f=ImageFont.truetype(FONT,24);sm=ImageFont.truetype(FONT,20) + d.text((18,10),'BREAKFAST | scripted recovery reference | same attempt | 2x',font=f,fill='white') + d.text((785,52),'Synchronized side view' if self.focus=='lid' else 'Magnified detail from the same frame',font=sm,fill='#b5ccdf') + q=self.t.liquid + for n,line in enumerate([f'Simulation: {self.n*.05:.1f} s',f'Milk in cup: {q["cup"]:.1f} mL', + f'Spilled: {q["spill"]:.1f} mL',f'Pantry lid: {self.t.lid_deg():.1f} deg', + f'Butter height: {100*self.t.butter_height():.1f} cm']): + d.text((790,620+36*n),line,font=f,fill='white') + d.text((18,830),self.phase,font=f,fill='#ffe0a2') + d.text((18,874),'Milk: simplified flow + ballistic parcels; rigid objects: MuJoCo contacts.',font=sm,fill='#b5ccdf') + return np.asarray(canvas) + def capture(self): + im=self.frame();self.raw.append_data(np.asarray(im));self.raw_n+=1 + self.preview.append_data(self.decorate(im));self.frames+=1 + def phase_hook(self,text,state): + if text.startswith(('Tipping handle:','Returning handle:','Bread pickup:','Bread placement:')):return + if 'carton' in text or 'cradle' in text or 'milk' in text.lower():self.focus='milk' + elif 'pantry' in text.lower() or 'L4' in text or 'lid' in text.lower() or 'inside the box' in text or 'Upright butter' in text:self.focus='lid' + else:self.focus='food' + self.phase=text + row=dict(state,preview_time_s=self.frames/10,preview_frame=self.frames) + self.timeline.append(row) + im=self.frame();Image.Image.save(im,self.out/f'checkpoint_{len(self.timeline):02d}.png') + # Explicit presentation hold only; no simulation reset or omitted motion. + for _ in range(10):self.preview.append_data(self.decorate(im));self.frames+=1 + print(json.dumps(row,default=lambda v:v.item()),flush=True) + def close(self): + self.t.env.step=self.original;self.raw.close();self.preview.close() + +def main(): + p=argparse.ArgumentParser();p.add_argument('--out',required=True);p.add_argument('--seed',type=int,default=1000) + a=p.parse_args();out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + t=BreakfastService();inst=t.sample_instance(a.seed);t.reset_instance(inst) + r=Recorder(t,out);t.phase_hook=r.phase_hook + try: + t.execute(inst,{'mode':'adaptive'});result=t.outcome(inst) + r.phase_hook('FINAL: breakfast served; all three failures recovered' if result['success'] else 'FINAL: verification failed', + dict(step=t.sk.n_steps,outcome=result)) + finally:r.close() + files=[Path(__file__).resolve().parents[1]/'lffbench/tasks'/n for n in + ('lh_breakfast_service.py','lh_pantry_relatch.py','lh_lid_box.py')] + meta=dict(seed=a.seed,instance=inst,outcome=result,continuous_attempt=True,resets_during_recording=0, + source_hashes={str(f):hashlib.sha256(f.read_bytes()).hexdigest() for f in files}, + sim_seconds=r.n*.05,raw_frames=r.raw_n,preview_frames=r.frames,timeline=r.timeline, + presentation='2x with 1 s freeze at labeled checkpoints; full 1x has no presentation freezes', + video_hashes={f.name:hashlib.sha256(f.read_bytes()).hexdigest() for f in out.glob('*.mp4')}) + (out/'recording.json').write_text(json.dumps(meta,indent=2,default=lambda v:v.item())) + assert result['success'] and all(result['traps'].values()) and all(result['recovered'].values()),result + t.env.close() + +if __name__=='__main__':main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/replay_la.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/replay_la.py new file mode 100644 index 0000000000000000000000000000000000000000..38e45b5ae30f071dfe944b542fc0868262601538 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/replay_la.py @@ -0,0 +1,85 @@ +"""Replay the robot commands of a logged agent attempt on a fresh task instance (current task code) and print the +outcome next to the logged one -- e.g. to check a rule change against old runs without re-running the agent. + +usage: python scripts/replay_la.py [--seg] [--fb] +LA `move_eef` calls mirror robot_server._handle_v2 (missing axes default to the current pose, move_to then gripper); +v1 tool calls (move_to / open_gripper / close_gripper / push, world frame) are passed to the ToolExecutor as logged. +--seg prints the per-command board / cube motion (tasks whose Skills keep `segments`), --fb the F2 text. +""" +import importlib +import json +import os +import pkgutil +import sys + +import numpy as np + +from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor +from lffbench import tasks as task_pkg +from lffbench.task_base import TASKS + +for _m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{_m.name}") + + +def main(): + run_dir, attempt = sys.argv[1], int(sys.argv[2]) + ev = [json.loads(l) for l in open(os.path.join(run_dir, "events.jsonl")) if l.strip()] + start = next(e for e in ev if e["ev"] == "session_start") + task = TASKS[start["task"]](cam_res=128) + inst = task.sample_instance(start["seed"]) + task.reset_instance(inst) + sim = task.env.sim + off = np.array(sim.data.body_xpos[sim.model.body_name2id("robot0_base")], float).copy() + ex = ToolExecutor(task, inst, image_res=128, cams=("agentview",)) + logged = None + for e in ev: + if e.get("attempt") != attempt: + continue + if e["ev"] == "done": + logged = e + break + if e["ev"] == "call" and e["cmd"] in ("move_to", "open_gripper", "close_gripper", "push"): # v1 tools + ex.call(e["cmd"], e["args"]) + print(f" s{e['step']:>2} {e['cmd']} {e['args']} [seg {len(getattr(task.sk, 'segments', []))}]") + continue + if e["ev"] != "call" or e["cmd"] != "move_eef": + continue + args = e["args"] + p = ex.proprio() + cur = np.asarray(p["eef_pos"], float) - off + tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")] + yaw = float(args.get("yaw", p["eef_yaw_deg"])) + speed = None if args.get("speed") in (None, "") else float(args["speed"]) + moving = any(k in args for k in ("x", "y", "z", "yaw")) + tgt_w = np.asarray(tgt) + off + if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)): + print(f" s{e['step']:>2} rejected") + continue + if moving: + mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw) + if speed is not None: + mv["speed"] = speed + ex.call("move_to", mv) + if args.get("gripper"): + ex.call("open_gripper" if args["gripper"] == "open" else "close_gripper", {}) + print(f" s{e['step']:>2} {' '.join(f'{k}={v}' for k, v in args.items())} [seg {len(getattr(task.sk, 'segments', []))}]") + if "--seg" in sys.argv and hasattr(task.sk, "segments"): + for g in task.sk.segments: + if g["path"] > 0.0005 or g["touch"]: + print(f" seg@{g['step0']:>4} {g['kind']:<5} steps={g['steps']:>3} path={100*g['path']:.2f}cm " + f"driven={100*g['driven']:.2f}cm touch={g['touch']:>3} board_dxy={g['board_dxy']} " + f"cube_dxy={g['cube_dxy']} cube_from_start={g['cube_from_start']}") + out = task.outcome(inst) + keys = ("moved_toward_robot", "n_pulls", "pulls_cm", "pre_pull_cube_cm", "stray_cm", "n_pushes", "max_advance", + "n_turns", "n_wrong_way", "n_strikes", "n_missed_strikes", "free_slide_cm", "n_bad_pushes", + "first_push_yaw_deg", "n_open_gripper_pushes", "irrecoverable", "trap_fired", "recovered_in_attempt") + print("REPLAY :", "S" if out["success"] else "F", out.get("failure"), {k: out[k] for k in keys if k in out}) + if "--fb" in sys.argv: + print("F2 :", task.feedback(inst, out, "F2")) + if logged: + print("LOGGED :", "S" if logged["success"] else "F", logged["outcome"].get("failure")) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/rpent_player.sh b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/rpent_player.sh new file mode 100644 index 0000000000000000000000000000000000000000..fafef9b4200fe5695c9fbabad0e01b9edd5e3a43 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/rpent_player.sh @@ -0,0 +1,23 @@ +#!/bin/bash +# Run one RPent (Harness VLA framework) agent on an LFF-Bench robot_server session. +# usage: scripts/rpent_player.sh /session.json [--model gpt-6-astra] [--effort medium] [--max-turns 400] ... +# Start a v2 session first (the RPent robot `lffbench` speaks interface v2 only), e.g.: +# LFF_STYLE=v2 scripts/start_robot_session.sh l1_bias_place 3000 full F2 10330 direct 3 rpent rgb 1 +# RPent checkout with the LFF-Bench robot (`lffbench`, planner `api`): integrations/rpent/setup.sh puts it in +# third_party/rpent with its venv in third_party/rpent/.venv (override: RPENT_DIR / RPENT_VENV, e.g. in env.local.sh). +# API key / endpoint: OPENAI_API_KEY / OPENAI_BASE_URL from the environment or from .env (LFF_ENV_FILE). +# Writes into the session's log dir: rpent_transcript.jsonl (every model request/response, images as file refs), +# final_report.md, rpent_result.json, rpent_player.log and rpent/ (RPent's own run.log / transcript / step artifacts). +set -e +[ -f "$1" ] || { echo "usage: $0 [player args]"; exit 2; } +SESSION=$(readlink -f "$1"); shift +LOG=$(dirname "$SESSION") +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +[ -f "$ROOT/env.local.sh" ] && source "$ROOT/env.local.sh" +RPENT=${RPENT_DIR:-$ROOT/third_party/rpent} +VENV=${RPENT_VENV:-$RPENT/.venv} +ENVF=${LFF_ENV_FILE:-$ROOT/.env} +[ -f "$ENVF" ] && { set -a; source "$ENVF"; set +a; } +cd "$RPENT" +PYTHONPATH="$RPENT" "$VENV/bin/python" -m robots.lffbench.player --session "$SESSION" "$@" 2>&1 | tee -a "$LOG/rpent_player.log" +exit "${PIPESTATUS[0]}" diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/run_agent.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/run_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..4ee5cbb55b9c8df62f070fb56ca6524c045a898a --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/run_agent.py @@ -0,0 +1,220 @@ +"""Run an agent backend on an LFF-Bench task and log everything. + + source run_env.sh && export OMP_NUM_THREADS=1 + python scripts/run_agent.py --task l5_slide_to_target --backend scripted --memory full --feedback F2 --n 3 --k 5 + python scripts/run_agent.py --task l5_slide_to_target --backend openai --effort medium --memory full --n 20 --k 5 + +Writes runs/agent//___/ with config.json, events.jsonl +(every LLM call with tokens + latency, every tool call with its report, every attempt's outcome and +feedback), images/ (every image the model saw, as the exact JPEG sent) and summary.json (succ@k per run, +first-success attempt, ฮ”ICL fields, tokens / cost / latency). +""" +import argparse +import importlib +import json +import os +import pkgutil +import sys +import time + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) + + +def load_tasks(): + import lffbench.tasks as task_pkg + from lffbench.task_base import TASKS + for m in pkgutil.iter_modules(task_pkg.__path__): + try: + importlib.import_module(f"lffbench.tasks.{m.name}") + except Exception as e: # other people's task files may be mid-edit; do not let them break this run + print(f"[warn] could not import lffbench.tasks.{m.name}: {e!r}", file=sys.stderr) + return TASKS + + +def parse(argv=None): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--task", required=True) + ap.add_argument("--backend", choices=["scripted", "openai", "chat"], default="scripted") + ap.add_argument("--memory", choices=["none", "full", "last", "mismatched"], default="full") + ap.add_argument("--feedback", choices=["F0", "F1", "F2"], default="F2") + ap.add_argument("--n", type=int, default=3, help="number of instances (runs)") + ap.add_argument("--k", type=int, default=None, help="attempts per run (default: task.max_attempts)") + ap.add_argument("--seed0", type=int, default=1000, help="first instance seed (dev seeds 1000+, use 5000+ for test)") + ap.add_argument("--seeds", default=None, help="explicit comma-separated seeds (overrides --seed0/--n)") + ap.add_argument("--out", default=os.path.join(ROOT, "runs", "agent")) + ap.add_argument("--tag", default="") + # harness + ap.add_argument("--instruction", choices=["direct", "indirect"], default="direct") + ap.add_argument("--privileged-locate", action="store_true", help="ablation: add locate(object_name)") + ap.add_argument("--image-res", type=int, default=512) + ap.add_argument("--keyframe-res", type=int, default=None) + ap.add_argument("--keyframes", type=int, default=4) + ap.add_argument("--max-steps", type=int, default=30, help="tool calls per attempt") + ap.add_argument("--no-auto-obs", action="store_true", help="send images only on get_observation") + ap.add_argument("--grasp-report", choices=["bool", "name", "none"], default="bool") + ap.add_argument("--early-stop", choices=["auto", "yes", "no"], default="auto") + ap.add_argument("--jpeg-quality", type=int, default=90) + ap.add_argument("--no-save-images", action="store_true") + # mismatched memory + ap.add_argument("--donor-run", default=None, help="run dir whose attempts serve as mismatched histories") + ap.add_argument("--donor-offset", type=int, default=10000, + help="without --donor-run: donor instance seed = seed + offset, generated with memory=full") + # scripted + ap.add_argument("--scripted-policy", choices=["adaptive", "naive", "oracle", "blind"], default="adaptive") + ap.add_argument("--dry-run-payload", action="store_true", + help="for non-openai backends: also build the GPT-6 request for every call and log its size") + ap.add_argument("--dump-requests", type=int, default=0, + help="write the first N OpenAI requests (images elided) to requests/ for inspection") + # openai + ap.add_argument("--model", default="gpt-6-astra") + ap.add_argument("--effort", default="medium", help="reasoning effort: low|medium|high|xhigh|max") + ap.add_argument("--reasoning-summary", default="auto", choices=["auto", "concise", "detailed", "none"], + help="request and log model-returned summaries by default; none disables the request") + ap.add_argument("--image-detail", default="auto", help="low|high|original|auto") + ap.add_argument("--max-output-tokens", type=int, default=None) + ap.add_argument("--service-tier", default=None) + ap.add_argument("--prompt-cache-retention", default=None, help="in-memory | 24h") + ap.add_argument("--max-live-images", type=int, default=16) + ap.add_argument("--extra-body", default=None, help="JSON merged into the request body (new API fields)") + ap.add_argument("--cache-breakpoints", choices=["none", "history", "history+last"], default="history+last", + help="explicit prompt_cache_breakpoint markers (set none if a gateway rejects the field)") + ap.add_argument("--prompt-cache-options", default=None, help='JSON, e.g. {"ttl": "30m"}') + # chat (OpenAI-compatible local server) + ap.add_argument("--chat-base-url", default=None) + ap.add_argument("--chat-model", default="qwen3-vl-8b") + ap.add_argument("--chat-max-tokens", type=int, default=1024) + return ap.parse_args(argv) + + +def redact_request(req): + """Copy of a request with base64 images replaced by a short marker.""" + def red(o): + if isinstance(o, dict): + return {k: (f"" if k in ("image_url", "url") and isinstance(v, str) + and v.startswith("data:") else red(v)) for k, v in o.items()} + if isinstance(o, list): + return [red(v) for v in o] + if isinstance(o, str) and len(o) > 2000 and o.startswith("gAAAA"): # encrypted reasoning + return f"" + return o + return red(req) + + +def build_backend(args): + from lffbench.agent.backends import make_backend + if args.backend == "scripted": + return make_backend("scripted", policy=args.scripted_policy) + if args.backend == "openai": + if not os.environ.get("OPENAI_API_KEY"): + sys.exit("OPENAI_API_KEY is not set (and OPENAI_BASE_URL if you use a proxy / gateway).") + return make_backend("openai", model=args.model, reasoning_effort=args.effort, + reasoning_summary=None if args.reasoning_summary == "none" else args.reasoning_summary, + image_detail=args.image_detail, + max_output_tokens=args.max_output_tokens, service_tier=args.service_tier, + prompt_cache_retention=args.prompt_cache_retention, max_live_images=args.max_live_images, + jpeg_quality=args.jpeg_quality, cache_breakpoints=args.cache_breakpoints, + prompt_cache_options=json.loads(args.prompt_cache_options) if args.prompt_cache_options + else None, extra_body=json.loads(args.extra_body) if args.extra_body else None) + return make_backend("chat", model=args.chat_model, base_url=args.chat_base_url, max_tokens=args.chat_max_tokens, + max_live_images=min(args.max_live_images, 4), jpeg_quality=args.jpeg_quality) + + +def main(argv=None): + args = parse(argv) + from lffbench.agent.harness import AgentHarness, HarnessConfig, config_dict + from lffbench.agent.metrics import aggregate + from lffbench.agent.replay import derange, load_records + from lffbench.agent.runlog import RunLogger + + tasks = load_tasks() + if args.task not in tasks: + sys.exit(f"unknown task {args.task}; known: {sorted(tasks)}") + backend = build_backend(args) + seeds = [int(s) for s in args.seeds.split(",")] if args.seeds else list(range(args.seed0, args.seed0 + args.n)) + cfg = HarnessConfig(memory=args.memory, feedback=args.feedback, k=args.k, image_res=args.image_res, + keyframe_res=args.keyframe_res, n_keyframes=args.keyframes, auto_obs=not args.no_auto_obs, + max_steps=args.max_steps, privileged_locate=args.privileged_locate, + grasp_report=args.grasp_report, instruction=args.instruction, early_stop=args.early_stop, + jpeg_quality=args.jpeg_quality, save_images=not args.no_save_images, + model_for_cost=args.model if args.backend == "openai" else "none") + stamp = time.strftime("%Y%m%d-%H%M%S") + name = f"{stamp}_{args.backend}{'-' + args.scripted_policy if args.backend == 'scripted' else ''}_{args.memory}_" \ + f"{args.feedback}" + (f"_{args.tag}" if args.tag else "") + run_dir = os.path.join(args.out, args.task, name) + os.makedirs(run_dir, exist_ok=True) + log = RunLogger(run_dir, save_images=cfg.save_images, jpeg_quality=cfg.jpeg_quality) + + t0 = time.time() + task = tasks[args.task]() + print(f"[run_agent] env built in {time.time() - t0:.1f}s -> {run_dir}", flush=True) + k = args.k or task.max_attempts + + probe = None + if args.backend == "openai": + probe = None + elif args.dry_run_payload or args.dump_requests: + from lffbench.agent.backends.openai_responses import OpenAIResponsesBackend + probe = OpenAIResponsesBackend(model=args.model, reasoning_effort=args.effort, image_detail=args.image_detail, + max_live_images=args.max_live_images, jpeg_quality=args.jpeg_quality, + cache_breakpoints=args.cache_breakpoints, client=object()) + if args.dump_requests: + os.makedirs(os.path.join(run_dir, "requests"), exist_ok=True) + dumped = [0] + target = backend if args.backend == "openai" else probe + orig = target.build_request + + def build_and_dump(conv, tools, _orig=orig): + req = _orig(conv, tools) + if dumped[0] < args.dump_requests: + dumped[0] += 1 + with open(os.path.join(run_dir, "requests", f"request_{dumped[0]:03d}.json"), "w") as f: + json.dump(redact_request(req), f, indent=1) + return req + target.build_request = build_and_dump + + log.write_json("config.json", dict(argv=sys.argv, args=vars(args), harness=config_dict(cfg), + backend=backend.config(), task=dict(name=task.name, level=task.level, + protocol=task.protocol, k=k, + capabilities=list(task.capabilities)))) + harness = AgentHarness(task, backend, cfg, log, payload_probe=probe if args.backend != "openai" else None) + + donors = {} + if args.memory == "mismatched": + if args.donor_run: + pool = load_records(args.donor_run, task=task, feedback=args.feedback) + m = derange(seeds, pool) + donors = {s: pool[m[s]] for s in seeds} + else: + dlog = RunLogger(os.path.join(run_dir, "donors"), save_images=True, jpeg_quality=cfg.jpeg_quality) + dcfg = HarnessConfig(**{**config_dict(cfg), "memory": "full", "early_stop": "auto"}) + dh = AgentHarness(task, backend, dcfg, dlog) + for s in seeds: + _, recs = dh.run_instance(s + args.donor_offset) + donors[s] = recs + print(f"[donor] seed={s + args.donor_offset} first_success=" + f"{next((r.attempt for r in recs if r.success), None)}", flush=True) + dlog.close() + + runs = [] + for i, s in enumerate(seeds): + summ, recs = harness.run_instance(s, donor=donors.get(s)) + runs.append(summ) + print(f"[{i + 1}/{len(seeds)}] seed={s} first_success={summ['first_success']} attempts={summ['n_attempts']} " + f"status={summ['status']} llm_calls={summ['n_llm_calls']} tool_calls={summ['n_tool_calls']} " + f"({time.time() - t0:.0f}s)", flush=True) + agg = aggregate(runs, k) + log.write_json("summary.json", dict(task=args.task, backend=backend.config(), memory=args.memory, + feedback=args.feedback, k=k, seeds=seeds, aggregate=agg, + runs=[{kk: v for kk, v in r.items() if not kk.startswith("_")} for r in runs])) + log.close() + print(json.dumps({kk: agg[kk] for kk in ("n_runs", "n_error_runs", "succ_at", "attempt1_success", + "mean_first_success", "pass_at_k_iid_analytic", "repeated_action_rate", + "llm_calls_per_run", "tool_calls_per_run", "sim_wall_per_run_s")}, + default=str)) + print(f"[run_agent] done -> {run_dir}") + return run_dir, agg, runs + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/start_real_session.sh b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/start_real_session.sh new file mode 100644 index 0000000000000000000000000000000000000000..6ef8faf20fc737b7fcdcd0174f100f1d203ab8d4 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/start_real_session.sh @@ -0,0 +1,30 @@ +#!/bin/bash +# Start a REAL-robot server (lffbench/real/session.py) + workspace for one task instance; same output as +# scripts/start_robot_session.sh (SANDBOX=, LOG=, /session.json), so harness_run.py / api_player.py run on it unchanged. +# usage: scripts/start_real_session.sh [instruction direct|indirect] [k] [tag] +# The driver: $LFF_REAL_DRIVER (default http://127.0.0.1:9900, normally an SSH tunnel to the robot PC) and $LFF_DRIVER_TOKEN. +# Blocks until the operator has set up the scene for attempt 1 (up to $LFF_REAL_READY_WAIT s, default 3600). +set -e +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +TASK=$1; SEED=$2; MEM=$3; FB=$4; PORT=$5; INSTR=${6:-direct}; K=${7:-}; TAG=${8:-} +RUN=${TAG:+${TAG}_}${TASK}_s${SEED}_${MEM}_${FB}_${INSTR}_k${K:-d}_$(date +%m%d-%H%M%S)_p${PORT} +SANDBOX=${LFF_SANDBOX_ROOT:-/tmp/robotlab}/$(python3 -c 'import secrets;print(secrets.token_hex(6))') +LOG=${LFF_RUNS_DIR:-$ROOT/runs/real}/$RUN +mkdir -p "$SANDBOX" "$LOG" +cd "$ROOT" && source run_env.sh && export OMP_NUM_THREADS=1 +KARG=""; [ -n "$K" ] && KARG="--k $K" +nohup python -m lffbench.real.session --task "$TASK" --seed "$SEED" --memory "$MEM" --feedback "$FB" \ + --instruction "$INSTR" --port "$PORT" --sandbox "$SANDBOX" --log-dir "$LOG" --run-name "$RUN" ${LFF_EXTRA_ARGS:-} $KARG \ + > "$LOG/server.log" 2>&1 & +echo $! > "$LOG/server.pid" +WAIT=${LFF_REAL_READY_WAIT:-3600} +for i in $(seq 1 "$WAIT"); do + [ -f "$LOG/READY" ] && break + kill -0 "$(cat "$LOG/server.pid")" 2>/dev/null || break + [ $((i % 30)) -eq 0 ] && echo "waiting for the operator to set up the scene ($i s)" >&2 + sleep 1 +done +[ -f "$LOG/READY" ] || { echo "server failed"; tail -20 "$LOG/server.log"; exit 1; } +echo "{\"run\": \"$RUN\", \"sandbox\": \"$SANDBOX\", \"port\": $PORT}" > "$LOG/session.json" +echo "SANDBOX=$SANDBOX" +echo "LOG=$LOG" diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/start_robot_session.sh b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/start_robot_session.sh new file mode 100644 index 0000000000000000000000000000000000000000..998586e07e8eae302b64797e0d4a2d12d7157c7b --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/start_robot_session.sh @@ -0,0 +1,24 @@ +#!/bin/bash +# Start a robot server + isolated sandbox for one task instance. +# usage: scripts/start_robot_session.sh [instruction direct|indirect] [k] [tag] [perception depth|rgb] [video 0|1] +# The sandbox gets an opaque random name (no task / condition in the path); the readable run name is only in LOG. +set -e +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +TASK=$1; SEED=$2; MEM=$3; FB=$4; PORT=$5; INSTR=${6:-direct}; K=${7:-}; TAG=${8:-}; PERC=${9:-depth}; VID=${10:-0} +RUN=${TAG:+${TAG}_}${TASK}_s${SEED}_${MEM}_${FB}_${INSTR}_k${K:-d}_$(date +%m%d-%H%M%S)_p${PORT} +SANDBOX=${LFF_SANDBOX_ROOT:-/tmp/robotlab}/$(python3 -c 'import secrets;print(secrets.token_hex(6))') +LOG=${LFF_RUNS_DIR:-$ROOT/runs/claude}/$RUN +mkdir -p "$SANDBOX" "$LOG" +cd "$ROOT" && source run_env.sh && export OMP_NUM_THREADS=1 +KARG=""; [ -n "$K" ] && KARG="--k $K" +VARG=""; [ "$VID" = "1" ] && VARG="--video $LOG/rollout.mp4" +nohup python -m lffbench.agent.robot_server --task "$TASK" --seed "$SEED" --memory "$MEM" --feedback "$FB" \ + --instruction "$INSTR" --port "$PORT" --sandbox "$SANDBOX" --log-dir "$LOG" --perception "$PERC" --style "${LFF_STYLE:-v1}" ${LFF_EXTRA_ARGS:-} $KARG $VARG > "$LOG/server.log" 2>&1 & +echo $! > "$LOG/server.pid" +# wait for the scene (long-horizon scenes on a loaded machine took > 2 min, 2026-10-20); on failure stop the server +# so that it does not keep the port +for i in $(seq 1 "${LFF_SERVER_WAIT_S:-600}"); do [ -f "$LOG/READY" ] && break; sleep 1; done +[ -f "$LOG/READY" ] || { echo "server failed"; tail -20 "$LOG/server.log"; kill "$(cat "$LOG/server.pid")" 2>/dev/null; exit 1; } +echo "{\"run\": \"$RUN\", \"sandbox\": \"$SANDBOX\", \"port\": $PORT}" > "$LOG/session.json" +echo "SANDBOX=$SANDBOX" +echo "LOG=$LOG" diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/summarize.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/summarize.py new file mode 100644 index 0000000000000000000000000000000000000000..5ceda683353fb938c1e8a219552c088181c197c2 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/summarize.py @@ -0,0 +1,33 @@ +"""Aggregate results//validate.json into results/SUMMARY.md (headroom table).""" +import glob +import json +import os + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +def main(): + rows = [] + for p in sorted(glob.glob(os.path.join(ROOT, "results", "*", "validate.json"))): + r = json.load(open(p)) + s = r["succ_at_k"] + + def g(kind, j): + v = s.get(kind) + return "โ€”" if v is None else f"{100 * v[j - 1]:.0f}" + + k = r["k"] + rows.append(f"| {r['task']} | {r['level']} | {', '.join(r['capabilities'])} | {r['n']} | " + f"{g('oracle', 1)} | {g('naive', 1)} | {g('adaptive', 1)} / {g('adaptive', 2)} / {g('adaptive', k)} | " + f"{g('blind', k)} | {r.get('seconds', 0) / 60:.0f} min |") + head = ("| task | level | capabilities | n | oracle@1 | naive@1 | adaptive @1/@2/@k | blind@k | wall |\n" + "|---|---|---|---|---|---|---|---|---|") + text = "# LFF-Bench headroom validation (scripted reference policies)\n\n" + head + "\n" + "\n".join(rows) + "\n" + out = os.path.join(ROOT, "results", "SUMMARY.md") + with open(out, "w") as f: + f.write(text) + print(text) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/summarize_lh_order_dispatch.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/summarize_lh_order_dispatch.py new file mode 100644 index 0000000000000000000000000000000000000000..86a8cdbc2a8d3f2ba1a29f7695db860a97278962 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/summarize_lh_order_dispatch.py @@ -0,0 +1,39 @@ +"""Assert the final scoped development results. Does not run simulation.""" +from pathlib import Path +import hashlib,json +root=Path(__file__).resolve().parents[1] +p=root/'results/lh_order_dispatch/development_20261102/accepted_development' +d=json.loads((p/'physical_checks.json').read_text()) +source_sha=hashlib.sha256((root/'lffbench/tasks/lh_order_dispatch.py').read_bytes()).hexdigest() +assert d['code_sha256']==source_sha +assert hashlib.sha256((p/'physical_checks.source.py').read_bytes()).hexdigest()==source_sha +assert len(d['rows'])==6 +for row in d['rows']: + assert not row.get('error'),row + assert row['recovered'] is True,(row['seed'],row['case']) + out=row['outcome'] + assert out['success'] and out['static'] and out['upright'] and not out['touching'] and not out['departed_unloaded'] + assert out['commands']<=180 and out['sim_s']<=540 + if row['case']=='combined_recovery': + assert all(row['diagnostics'].values()),(row['seed'],row['diagnostics']) + first=out['l1_attempts'][0] + assert not first['held'] and sum(v*v for v in first['offset'])**.5>.025 + assert 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']) + assert any(m.get('bad') and not m.get('gripper_open') and m['step']>=out['load_step'] for m in out['box_moves']) + steps=[x['sim_step'] for x in row['frames']] + assert len(steps)==5 and all(b>a for a,b in zip(steps,steps[1:])),steps +h=json.loads((p/'headroom_n3.json').read_text()) +assert h['n']==3 and h['k']==5 +assert (p/'headroom_n3.sha256').read_text().split()[0]==source_sha +assert hashlib.sha256((p/'headroom_n3.source.py').read_bytes()).hexdigest()==source_sha +summary=dict(code_sha256=source_sha,physical_cases=6,physical_successes=6, + oracle_all_completed=3,combined_three_trigger_and_completion=3, + max_commands=max(r['outcome']['commands'] for r in d['rows']),max_sim_s=max(r['outcome']['sim_s'] for r in d['rows']), + headroom_n3_k5=h['succ_at_k'], + limitations=['Three development seeds, fixed layout and signed hidden parameters; not n>=20 acceptance.', + 'Scripted references use privileged scene measurements. Adaptive calibrates L1/steers L5 from measured residuals, but card edge subpolicy is predesigned.', + 'Combined diagnostic deliberately attempts direct card grasp before switching, with real failed-close evidence.', + 'Not RGB/F1 model-learning results; task is not in the 34-task main evaluation set.'], + physical_evidence=str(p/'physical_checks.json'),headroom_evidence=str(p/'headroom_n3.json')) +(p/'summary.json').write_text(json.dumps(summary,indent=2)+'\n') +print(json.dumps(summary,indent=2)) diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/trace_gpt_html.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/trace_gpt_html.py new file mode 100644 index 0000000000000000000000000000000000000000..8ca1fd84456d589babea16a2e3a370b7d4f44e3d --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/trace_gpt_html.py @@ -0,0 +1,118 @@ +"""Render one GPT-player run as a self-contained HTML trace: the instructions and tool the model received, +every request's new content (text + images), the model's reasoning summaries and commands, every server +report, the server-side ground truth and the done verdicts. Optionally embeds the rollout video. + +python scripts/trace_gpt_html.py --log runs/gpt/exp2/ --out traces/.html [--title ...] [--video] +""" +import argparse +import base64 +import html +import json +import os + +from trace_html import CSS + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +def esc(s): + return html.escape(str(s)) + + +def img_tag(path): + if not os.path.exists(path): + return f"[missing {esc(os.path.basename(path))}]" + b = base64.b64encode(open(path, "rb").read()).decode() + return f"" + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--log", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--title", default="") + ap.add_argument("--video", action="store_true", help="embed rollout.mp4 (base64)") + a = ap.parse_args() + sess = json.load(open(os.path.join(a.log, "session.json"))) + sb = sess["sandbox"] + tp = os.path.join(a.log, "transcript.jsonl") # api_player; older gpt_player runs: gpt_transcript.jsonl + tr = [json.loads(l) for l in open(tp if os.path.exists(tp) else os.path.join(a.log, "gpt_transcript.jsonl"))] + ev = [json.loads(l) for l in open(os.path.join(a.log, "events.jsonl"))] + start = next(e for e in ev if e["ev"] == "session_start") + dones = [e for e in ev if e["ev"] == "done"] + http = [e for e in ev if e["ev"] == "http"] + asst = [d for d in tr if d["ev"] == "assistant"] + st = next(d for d in tr if d["ev"] == "start") + end = next((d for d in tr if d["ev"] in ("end", "abort")), {}) + tot = end.get("usage_total") or {} + + out = [f"{esc(a.title or 'GPT trace')}" + f"

{esc(a.title or os.path.basename(a.log))}

"] + rows = [("ไปปๅŠก / ็งๅญ", f"{start['task']} / {start['seed']}"), ("ๆจกๅž‹", f"{st['model']}๏ผˆreasoning effort {st['effort']}๏ผ‰"), + ("ๆ„Ÿ็Ÿฅ", start.get("perception", "depth") + "๏ผˆrgb = ๅชๆœ‰ๅฝฉ่‰ฒๅ›พ๏ผŒๆฒกๆœ‰ๆทฑๅบฆๅทฅๅ…ท๏ผ‰"), + ("็ป“ๆžœ", "๏ผ›".join(f"็ฌฌ{d['attempt']}ๆฌก {'ๆˆๅŠŸ' if d['success'] else 'ๅคฑ่ดฅ'}" for d in dones) or "โ€”"), + ("ๆœบๅ™จไบบๅ‘ฝไปคๆ•ฐ", sum(1 for e in ev if e["ev"] == "call")), + ("ๆจกๅž‹่ฐƒ็”จๆฌกๆ•ฐ / ๅนณๅ‡ๆฏๆฌกๅปถ่ฟŸ", f"{len(asst)} / {sum(d['latency_s'] for d in asst) / max(len(asst), 1):.1f} s"), + ("ไปฟ็œŸๆ‰ง่กŒๆ€ปๆ—ถ้•ฟ", f"{sum(h['server_s'] for h in http):.0f} s"), + ("token๏ผˆ่พ“ๅ…ฅ / ๅ…ถไธญ็ผ“ๅญ˜ / ่พ“ๅ‡บ / ๅ…ถไธญๆŽจ็†๏ผ‰", + f"{tot.get('input_tokens', 0)} / {tot.get('cached_tokens', 0)} / {tot.get('output_tokens', 0)} / {tot.get('reasoning_tokens', 0)}")] + out += [f"" for k, v in rows] + ["
{esc(k)}{esc(v)}
"] + inst = {k: v for k, v in start["inst"].items()} + out.append("
ๆœๅŠก็ซฏ็œŸๅ€ผ๏ผˆๆจกๅž‹ไปŽๆœช็œ‹ๅˆฐ๏ผ‰
"
+               + esc(json.dumps(inst, indent=1, ensure_ascii=False)[:3000]) + "
") + if a.video and os.path.exists(os.path.join(a.log, "rollout.mp4")): + b = base64.b64encode(open(os.path.join(a.log, "rollout.mp4"), "rb").read()).decode() + out.append("

ๅฝ•ๅƒ๏ผˆๅทฆ๏ผš็ฌฌไธ‰่ง†่ง’๏ผŒๅณ๏ผš่…•้ƒจ๏ผ›3 ๅ€้€Ÿ๏ผ‰

") + + out.append("

1. ๆจกๅž‹ๆ”ถๅˆฐ็š„็ณป็ปŸๆŒ‡ไปคๅ’Œๅทฅๅ…ท๏ผˆๅŽŸๆ–‡๏ผŒๆฏๆฌก่ฏทๆฑ‚้ƒฝไธ€ๆ ท๏ผ‰

") + out.append("
่ฟ™ๅฐฑๆ˜ฏๅ‘็ป™ GPT ็š„ๅ…จ้ƒจๅ›บๅฎšๅ†…ๅฎน๏ผšๆฒ™็ฎฑ README ๅŽŸๆ–‡ๅŠ ไธ€ๅฅๅผ€ๅคด่ฏดๆ˜Ž๏ผŒไปฅๅŠๅ”ฏไธ€็š„ robot ๅทฅๅ…ทใ€‚" + "ๆฒกๆœ‰ๆ–‡ไปถใ€่ฎฐๅฟ†ใ€ๆทฑๅบฆใ€็‰ฉไฝ“ๅๆ ‡ใ€‚
") + out.append(f"
instructions๏ผˆ{len(st['instructions'])} ๅญ—็ฌฆ๏ผ‰
{esc(st['instructions'])}
") + out.append(f"
tool
{esc(json.dumps(st['tool'], indent=1, ensure_ascii=False))}
") + + out.append("

2. ้€ๆญฅ่ฟ‡็จ‹

") + t0 = tr[0]["t"] + n = 0 + for d in tr: + tt = f"+{d['t'] - t0:6.0f}s" + if d["ev"] == "user": + imgs = "".join(img_tag(os.path.join(sb, p)) for p in d.get("images", [])) + out.append(f"
{tt} ๅ‘็ป™ๆจกๅž‹
{esc(d['text'])}
{imgs}
") + elif d["ev"] == "assistant": + blk = [f"
{tt} ๆจกๅž‹ๅ›žๅค " + f"๏ผˆ{d['latency_s']:.1f} s๏ผŒ่พ“ๅ‡บ {d['usage'].get('output_tokens', 0)} token๏ผŒ" + f"ๅ…ถไธญๆŽจ็† {d['usage'].get('reasoning_tokens', 0)}๏ผ‰"] + if d.get("reasoning_summary"): + blk.append(f"
ๆŽจ็†ๆ‘˜่ฆ๏ผˆๆจกๅž‹่‡ชๅทฑ็š„ๆ€่€ƒๆ‘˜่ฆ๏ผ‰
{esc(d['reasoning_summary'])}
") + if d.get("text"): + blk.append(f"
ๆ–‡ๅญ—
{esc(d['text'])}
") + for c in d["tool_calls"]: + n += 1 + blk.append(f"
#{n} ./robot {esc(c['arguments'].get('command', ''))}
") + out.append("".join(blk) + "
") + elif d["ev"] == "tool": + imgs = "".join(img_tag(os.path.join(sb, p)) for p in d.get("images", [])) + txt = d["output"] + out.append(f"
{tt} ๆœๅŠกๅ™จ่ฟ”ๅ›ž๏ผˆไฝœไธบๅทฅๅ…ท็ป“ๆžœๅ‘็ป™ๆจกๅž‹๏ผ‰" + f"
{len(txt)} ๅญ—็ฌฆ
{esc(txt)}
" + + (f"
้šๅŽ้™„ไธŠ็š„ๅ›พๅƒ
{imgs}" if imgs else "") + "
") + elif d["ev"] in ("api_error", "abort"): + out.append(f"
{esc(json.dumps(d, ensure_ascii=False))}
") + out.append("

3. ๆœๅŠก็ซฏๆฏๆฌก done ็š„ๅˆคๅฎš

") + for e in dones: + out.append(f"
็ฌฌ {e['attempt']} ๆฌก๏ผš" + f"{'ๆˆๅŠŸ' if e['success'] else 'ๅคฑ่ดฅ'}๏ผˆagent ็š„็†็”ฑ๏ผš{esc(e.get('reason', ''))}๏ผ‰
{esc(e.get('feedback', ''))}
") + rep = os.path.join(a.log, "final_report.md") + if os.path.exists(rep): + out.append(f"

4. ๆจกๅž‹ๆœ€ๅŽ็š„ๆŠฅๅ‘Š

{esc(open(rep).read())}
") + out.append("") + os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True) + with open(a.out, "w") as f: + f.write("\n".join(out)) + print(a.out, os.path.getsize(a.out), "bytes; commands", n) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/trace_html.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/trace_html.py new file mode 100644 index 0000000000000000000000000000000000000000..651afc43f8b160358a4388c58659fa478c4b71f0 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/trace_html.py @@ -0,0 +1,148 @@ +"""Render one player-subagent run as a self-contained HTML trace: everything the agent received, +every command it ran, every result and image it saw, its own text, plus the server-side ground truth. + +python scripts/trace_html.py --batch exp1 --sandbox --out traces/.html +""" +import argparse +import base64 +import html +import json +import os +from datetime import datetime + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TRANSCRIPTS = os.environ.get("CLAUDE_TASKS_DIR", "") # the Claude Code session's tasks/ dir (.output files) + +CSS = """ +:root{--bg:#fafaf9;--fg:#1c1917;--mut:#57534e;--card:#fff;--bd:#e7e5e4;--acc:#2563eb;--tool:#f5f5f4;--ok:#15803d;--bad:#b91c1c;--th:#7c3aed} +@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){--bg:#1c1917;--fg:#e7e5e4;--mut:#a8a29e;--card:#292524;--bd:#44403c;--acc:#60a5fa;--tool:#231f1d;--ok:#4ade80;--bad:#f87171;--th:#c4b5fd}} +body{background:var(--bg);color:var(--fg);font:14px/1.55 system-ui,-apple-system,"PingFang SC","Microsoft YaHei",sans-serif;margin:0;padding:16px;max-width:1100px;margin:auto} +h1{font-size:20px}h2{font-size:17px;margin-top:28px;border-bottom:1px solid var(--bd);padding-bottom:4px} +.card{background:var(--card);border:1px solid var(--bd);border-radius:8px;padding:10px 12px;margin:8px 0} +pre{white-space:pre-wrap;word-break:break-word;background:var(--tool);border:1px solid var(--bd);border-radius:6px;padding:8px;font:12px/1.45 ui-monospace,Menlo,monospace;margin:4px 0;max-height:420px;overflow:auto} +.lbl{font-size:12px;color:var(--mut);font-weight:600;text-transform:uppercase;letter-spacing:.03em} +.cmd{color:var(--acc)}.think{color:var(--th)}.ok{color:var(--ok);font-weight:600}.bad{color:var(--bad);font-weight:600} +img{max-width:256px;border-radius:4px;border:1px solid var(--bd);margin:2px} +details>summary{cursor:pointer;color:var(--mut)} +table{border-collapse:collapse}td,th{border:1px solid var(--bd);padding:3px 8px;text-align:left;font-size:13px} +.step{display:flex;gap:8px}.n{color:var(--mut);min-width:34px;font-variant-numeric:tabular-nums} +""" + + +def esc(s): + return html.escape(str(s)) + + +def ts(x): + return datetime.fromisoformat(x.replace("Z", "+00:00")).timestamp() + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--batch", default="exp1") + ap.add_argument("--sandbox", required=True, help="sandbox hex id") + ap.add_argument("--out", required=True) + ap.add_argument("--title", default="") + a = ap.parse_args() + m = json.load(open(os.path.join(ROOT, "runs", "claude", a.batch, "manifest.json"))) + run = next(r for r in m["runs"] if r["sandbox"].endswith(a.sandbox)) + tr = [json.loads(l) for l in open(os.path.join(TRANSCRIPTS, f"{run['agent']}.output"))] + ev = [json.loads(l) for l in open(os.path.join(run["log"], "events.jsonl"))] + start = next(e for e in ev if e["ev"] == "session_start") + dones = [e for e in ev if e["ev"] == "done"] + http = [e for e in ev if e["ev"] == "http"] + think = [h["think_s"] for h in http if h.get("think_s")] + srv = [h["server_s"] for h in http] + + out = [f"{esc(a.title or 'Agent trace')}"] + out.append(f"

{esc(a.title or run['run'])}

") + out.append("
") + rows = [("ไปปๅŠก", run["task"]), ("็งๅญ", run["seed"]), ("ๆจกๅž‹", run["model"]), ("ๆกไปถ", run["cond"] + f"๏ผˆk={run['k']}๏ผ‰"), + ("ๆฒ™็ฎฑ", run["sandbox"]), ("ๆœๅŠก็ซฏ run ๅ", run["run"]), + ("็ป“ๆžœ", "๏ผ›".join(f"็ฌฌ{d['attempt']}ๆฌก {'ๆˆๅŠŸ' if d['success'] else 'ๅคฑ่ดฅ'}" for d in dones)), + ("ๅ‘ฝไปคๆ•ฐ / ๆจกๅž‹ๆ€่€ƒๆ€ปๆ—ถ้•ฟ / ไปฟ็œŸๆ‰ง่กŒๆ€ปๆ—ถ้•ฟ", f"{sum(1 for e in ev if e['ev']=='call')} / {sum(think):.0f} s / {sum(srv):.0f} s"), + ("ๅญไปฃ็†ๅข™้’Ÿ", f"{(ts(tr[-1]['timestamp']) - ts(tr[0]['timestamp'])) / 60:.1f} min")] + for k, v in rows: + out.append(f"") + out.append("
{esc(k)}{esc(v)}
") + inst = {k: v for k, v in start["inst"].items()} + out.append("
ๆœๅŠก็ซฏ็œŸๅ€ผ๏ผˆagent ไปŽๆœช็œ‹ๅˆฐ๏ผ‰
" + esc(json.dumps(inst, indent=1, ensure_ascii=False)[:3000]) + "
") + + # ---------------------------------------------------------------- what the agent received + out.append("

1. agent ๆ”ถๅˆฐ็š„ไธŠไธ‹ๆ–‡

") + out.append("
Claude Code ๅ†…็ฝฎ็š„็ณป็ปŸๆ็คบๅ’Œๅทฅๅ…ทๅฎšไน‰ไธๅœจๅฏน่ฏ่ฎฐๅฝ•้‡Œ๏ผˆ็”ฑ Claude Code ๆณจๅ…ฅ๏ผŒ่ฟ™้‡Œ็œ‹ไธๅˆฐๅŽŸๆ–‡๏ผ‰ใ€‚ไธ‹้ขๆ˜ฏ่ฎฐๅฝ•้‡Œ่ƒฝ็œ‹ๅˆฐ็š„ๅ…จ้ƒจๆณจๅ…ฅๅ†…ๅฎนๅ’Œๆˆ‘็š„ๆ็คบใ€‚
") + for d in tr: + if d["type"] != "attachment": + continue + at = d["attachment"] + t = at.get("type") + if t == "instructions": + for f in at.get("files", []): + out.append(f"
ๆณจๅ…ฅ้™„ไปถ๏ผš{esc(f.get('type'))} โ€” {esc(f.get('path'))}๏ผˆ{len(f.get('content',''))} ๅญ—็ฌฆ๏ผ‰
{esc(f.get('content',''))}
") + elif t in ("environment", "model", "date", "session_context", "skill_listing", "deferred_tools_delta", "credential_org"): + body = json.dumps({k: v for k, v in at.items() if k != "type"}, ensure_ascii=False, indent=1) + out.append(f"
ๆณจๅ…ฅ้™„ไปถ๏ผš{esc(t)}๏ผˆ{len(body)} ๅญ—็ฌฆ๏ผ‰
{esc(body[:6000])}
") + first_user = next(d for d in tr if d["type"] == "user") + out.append("
ๆˆ‘็ป™ agent ็š„ๆ็คบ๏ผˆๅŽŸๆ–‡๏ผ‰
" + esc(first_user["message"]["content"]) + "
") + + # ---------------------------------------------------------------- timeline + out.append("

2. ้€ๆญฅ่ฟ‡็จ‹๏ผˆagent ็š„ๆ–‡ๅญ—ใ€ๆ‰ง่กŒ็š„ๅ‘ฝไปคใ€ๆ”ถๅˆฐ็š„็ป“ๆžœๅ’Œๅ›พๅƒ๏ผ‰

") + n = 0 + results = {} + for d in tr: + if d["type"] == "user" and isinstance(d["message"].get("content"), list): + for c in d["message"]["content"]: + if c.get("type") == "tool_result": + results[c["tool_use_id"]] = c + t0 = ts(tr[0]["timestamp"]) + for d in tr: + if d["type"] != "assistant": + continue + for c in d["message"].get("content", []): + ct = c.get("type") + tt = f"+{ts(d['timestamp']) - t0:6.0f}s" + if ct == "thinking" and c.get("thinking"): + out.append(f"
{tt} ๆ€่€ƒ
{esc(c['thinking'])}
") + elif ct == "text" and c.get("text", "").strip(): + out.append(f"
{tt} agent ๆ–‡ๅญ—
{esc(c['text'])}
") + elif ct == "tool_use": + n += 1 + inp = c.get("input", {}) + if c["name"] == "Bash": + head = f"Bash: {esc(inp.get('command',''))}" + elif c["name"] == "Read": + head = f"Read: {esc(inp.get('file_path',''))}" + elif c["name"] == "SubagentHandback": + head = "ๆœ€็ปˆๆŠฅๅ‘Š๏ผˆSubagentHandback๏ผ‰" + else: + head = f"{esc(c['name'])}: {esc(json.dumps(inp, ensure_ascii=False)[:300])}" + block = [f"
{tt} #{n} ๅทฅๅ…ท่ฐƒ็”จ {head}"] + if c["name"] == "SubagentHandback": + block.append(f"
{esc(inp.get('message',''))}
") + r = results.get(c["id"]) + if r is not None: + rc = r.get("content") + if isinstance(rc, str): + rc = [{"type": "text", "text": rc}] + for part in rc or []: + if part.get("type") == "text": + txt = part["text"] + block.append(f"
่ฟ”ๅ›ž๏ผˆ{len(txt)} ๅญ—็ฌฆ๏ผ‰
{esc(txt)}
") + elif part.get("type") == "image": + src = part.get("source", {}) + if src.get("type") == "base64": + block.append(f"") + block.append("
") + out.extend(block) + out.append("

3. ๆœๅŠก็ซฏๆฏๆฌก done ็š„ๅˆคๅฎš

") + for e in dones: + out.append(f"
็ฌฌ {e['attempt']} ๆฌก๏ผš{'ๆˆๅŠŸ' if e['success'] else 'ๅคฑ่ดฅ'}
{esc(e.get('feedback',''))}
") + out.append("") + os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True) + with open(a.out, "w") as f: + f.write("\n".join(out)) + print(a.out, os.path.getsize(a.out), "bytes; tool calls", n) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/usage_stats.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/usage_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..62af0f3053cbe2e247ea34ad614bb7a842ddf0c6 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/usage_stats.py @@ -0,0 +1,178 @@ +"""Token and time usage of api_batch.py --memfree followup batches, per run and per instance. + +Sources (all written by the run itself, nothing re-estimated here): + harness.json wall_s (agent CLI start to end, all resume segments) and final_metrics (total_prompt_tokens incl. + cache reads, total_completion_tokens incl. reasoning / thinking, total_cached_tokens, + reasoning_tokens [Codex], total_cost_usd [Claude Code's own API-price estimate; we pay by subscription]) + events.jsonl per robot-server request: think_s = time since the server's previous reply (model inference + other + tool calls such as shell / view_images + harness overhead), server_s = simulator time; done events + mark the attempts. +Rows: "history" = the history run (1-3 attempts in one agent session), "memfree" = the memory-free chain runs (one +fresh-agent attempt each, attempt 1 is shared with the history run). Per-attempt tokens are not split here: Codex only +reports usage per exec / resume segment, not per attempt. + + python scripts/usage_stats.py --batch cx_main1 --batch cc_main1 --batch cc_opus1 [--check] [--json out.json] + +--check re-adds the native usage records (codex_events.jsonl turn.completed / claude_stream.jsonl result) and reports +runs whose totals differ from final_metrics. +""" +import argparse +import json +import os +import statistics +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import api_batch # noqa: E402 +import outcomes # noqa: E402 + + +def run_usage(log): + h = json.load(open(os.path.join(log, "harness.json"))) + fm = h.get("final_metrics") or {} + think, server, att = {}, {}, {} + for line in open(os.path.join(log, "events.jsonl")): + e = json.loads(line) + if e.get("ev") == "http": + a = e.get("attempt") + think[a] = think.get(a, 0.0) + (e.get("think_s") or 0.0) + server[a] = server.get(a, 0.0) + (e.get("server_s") or 0.0) + elif e.get("ev") == "done": + att[e["attempt"]] = e["success"] in (True, "True") + return dict(wall_s=h.get("wall_s"), think_s=sum(think.values()), server_s=sum(server.values()), + think_per_attempt=[round(think.get(a, 0.0), 1) for a in sorted(att)], n_attempts=len(att), + prompt=fm.get("total_prompt_tokens") or 0, completion=fm.get("total_completion_tokens") or 0, + cached=fm.get("total_cached_tokens") or 0, reasoning=fm.get("reasoning_tokens"), + cost_usd=fm.get("total_cost_usd"), steps=fm.get("total_steps"), model=h.get("model"), + harness=h.get("harness"), version=h.get("version")) + + +def native_totals(log): + """(prompt, completion, records) re-added from the CLI's own event stream, None if there is none.""" + p = os.path.join(log, "codex_events.jsonl") + if os.path.exists(p): + tot = [0, 0, 0] + for line in open(p): + if '"turn.completed"' in line: + u = json.loads(line)["usage"] + tot = [tot[0] + u["input_tokens"], tot[1] + u["output_tokens"], tot[2] + 1] + return tuple(tot) + p = os.path.join(log, "claude_stream.jsonl") + if os.path.exists(p): + tot = [0, 0, 0] + for line in open(p): + if '"type":"result"' in line: + d = json.loads(line) + if d.get("type") != "result": + continue + u = d["usage"] + tot = [tot[0] + u["input_tokens"] + u["cache_read_input_tokens"] + u["cache_creation_input_tokens"], + tot[1] + u["output_tokens"], tot[2] + 1] + return tuple(tot) + return None + + +def batch_rows(batch): + m = api_batch.load(batch) + hist = {r["task"] + "|" + str(r["seed"]): r for r in m["runs"] + if r["cond"] == "harness" and r.get("followup") and r["status"] == "done"} + out = dict(batch=batch, runs=[], instances=[]) + for key, r in hist.items(): + h = dict(run_usage(r["log"]), id=r["id"], log=r["log"], kind="history", + outcome="".join("S" if s else "F" for _, s, _, _ in outcomes.attempts(r["log"]))) + chain = sorted((x for x in m["runs"] if x.get("chain") == r["id"] and x["status"] == "done"), + key=lambda x: x["rep"]) + mf = [dict(run_usage(x["log"]), id=x["id"], log=x["log"], kind="memfree", rep=x["rep"]) for x in chain] + out["runs"] += [h] + mf + out["instances"].append(dict(task=r["task"], seed=r["seed"], history=h, memfree=mf)) + return out + + +def agg(runs): + if not runs: + return None + att = sum(x["n_attempts"] for x in runs) + cost = [x["cost_usd"] for x in runs if x["cost_usd"] is not None] + per_att = [t for x in runs for t in x["think_per_attempt"]] + return dict(n_runs=len(runs), n_attempts=att, wall_h=sum(x["wall_s"] or 0 for x in runs) / 3600, + think_h=sum(x["think_s"] for x in runs) / 3600, server_h=sum(x["server_s"] for x in runs) / 3600, + think_min_per_attempt_mean=sum(per_att) / max(1, len(per_att)) / 60, + think_min_per_attempt_median=statistics.median(per_att) / 60 if per_att else None, + prompt_M=sum(x["prompt"] for x in runs) / 1e6, cached_M=sum(x["cached"] for x in runs) / 1e6, + completion_M=sum(x["completion"] for x in runs) / 1e6, + reasoning_M=(sum(x["reasoning"] or 0 for x in runs) / 1e6 + if any(x["reasoning"] is not None for x in runs) else None), + prompt_M_per_attempt=sum(x["prompt"] for x in runs) / 1e6 / max(1, att), + completion_k_per_attempt=sum(x["completion"] for x in runs) / 1e3 / max(1, att), + cost_usd=sum(cost) if cost else None) + + +def fmt(v, f): + return "โ€”" if v is None else format(v, f) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--batch", action="append", required=True) + ap.add_argument("--check", action="store_true") + ap.add_argument("--json", default=None) + a = ap.parse_args() + B = [batch_rows(b) for b in a.batch] + + print("| batch | model | runs | runs (attempts) | wall h | agent-side h | sim h | agent-side min / attempt (mean ยท median)" + " | prompt M (cached) | completion M (reasoning) | prompt M / attempt | completion k / attempt | API-price USD |") + print("|---|---|---|---|---|---|---|---|---|---|---|---|---|") + summ = {} + for b in B: + model = b["runs"][0]["model"] if b["runs"] else "?" + for kind in ("history", "memfree", "all"): + runs = [x for x in b["runs"] if kind == "all" or x["kind"] == kind] + s = agg(runs) + summ[f"{b['batch']}/{kind}"] = s + if not s: + continue + print(f"| {b['batch']} | {model} | {kind} | {s['n_runs']} ({s['n_attempts']}) | {s['wall_h']:.1f} | " + f"{s['think_h']:.1f} | {s['server_h']:.1f} | {s['think_min_per_attempt_mean']:.1f} ยท " + f"{s['think_min_per_attempt_median']:.1f} | {s['prompt_M']:.1f} ({s['cached_M']:.1f}) | " + f"{s['completion_M']:.2f} ({fmt(s['reasoning_M'], '.2f')}) | {s['prompt_M_per_attempt']:.2f} | " + f"{s['completion_k_per_attempt']:.1f} | {fmt(s['cost_usd'], '.0f')} |") + + # per instance: history run, then the memory-free chain added up + keys = sorted({(i["task"], i["seed"]) for b in B for i in b["instances"]}) + print("\nPer instance. Cell = outcome ยท agent-side min ยท prompt M / completion k (history run); " + "memory-free cell = runs ยท agent-side min ยท prompt M / completion k, added up.\n") + print("| task | seed | " + " | ".join(f"{b['batch']} history | {b['batch']} memory-free" for b in B) + " |") + print("|---|---|" + "---|---|" * len(B)) + for task, seed in keys: + cells = [] + for b in B: + i = next((x for x in b["instances"] if (x["task"], x["seed"]) == (task, seed)), None) + if i is None: + cells += ["โ€”", "โ€”"] + continue + h = i["history"] + cells.append(f"{h['outcome']} ยท {h['think_s'] / 60:.0f} ยท {h['prompt'] / 1e6:.1f}/{h['completion'] / 1e3:.0f}") + mf = i["memfree"] + cells.append("โ€”" if not mf else + f"{len(mf)} ยท {sum(x['think_s'] for x in mf) / 60:.0f} ยท " + f"{sum(x['prompt'] for x in mf) / 1e6:.1f}/{sum(x['completion'] for x in mf) / 1e3:.0f}") + print(f"| {task} | {seed} | " + " | ".join(cells) + " |") + + if a.check: + bad, n = [], 0 + for b in B: + for x in b["runs"]: + nt = native_totals(x["log"]) + if nt is None: + continue + n += 1 + if (nt[0], nt[1]) != (x["prompt"], x["completion"]): + bad.append((b["batch"], x["id"], nt, x["prompt"], x["completion"])) + print(f"\ncheck: {n} runs re-added from native streams, {len(bad)} differ from final_metrics", bad[:5]) + if a.json: + with open(a.json, "w") as f: + json.dump(dict(summary=summ, batches=B), f, indent=1, ensure_ascii=False) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/validate.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/validate.py new file mode 100644 index 0000000000000000000000000000000000000000..cbb5365e77822d5dc2d8ad2fd3489c4d6c82a77b --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/validate.py @@ -0,0 +1,79 @@ +"""Headroom validation of LFF-Bench tasks with scripted reference policies. + +python scripts/validate.py --task l5_slide_to_target --n 20 --k 5 +Writes results//validate.json and thumbnails. +""" +import argparse +import importlib +import json +import os +import pkgutil +import sys +import time + +import numpy as np + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) + +import imageio # noqa: E402 + +import lffbench.tasks as task_pkg # noqa: E402 +from lffbench.task_base import TASKS # noqa: E402 + +for m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{m.name}") + + +def succ_curve(results, k): + """run-level succ@j for j = 1..k (a run = one instance, attempts share the run's state).""" + out = [] + for j in range(1, k + 1): + out.append(float(np.mean([r is not None and r <= j for r in results]))) + return out + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--task", required=True) + ap.add_argument("--n", type=int, default=20) + ap.add_argument("--k", type=int, default=5) + ap.add_argument("--seed0", type=int, default=1000) + ap.add_argument("--kinds", default="oracle,naive,adaptive,blind") + ap.add_argument("--thumbs", type=int, default=3) + args = ap.parse_args() + + task = TASKS[args.task]() + outdir = os.path.join(ROOT, "results", args.task) + os.makedirs(outdir, exist_ok=True) + kinds = args.kinds.split(",") + first_success = {k: [] for k in kinds} + runs = [] + t0 = time.time() + for i in range(args.n): + seed = args.seed0 + i + inst = task.sample_instance(seed) + if i < args.thumbs: + task.reset_instance(inst) + imageio.imwrite(os.path.join(outdir, f"init_{seed}.png"), task.snapshot(res=384)) + for kind in kinds: + hist = task.run_scripted(kind, inst, k=args.k, seed=seed) + s = next((h["attempt"] for h in hist if h["outcome"]["success"]), None) + first_success[kind].append(s) + runs.append(dict(seed=seed, kind=kind, inst={k: v for k, v in inst.items() if not k.startswith("_")}, + history=hist)) + if i < args.thumbs and kind == "naive": + imageio.imwrite(os.path.join(outdir, f"naive_end_{seed}.png"), task.snapshot(res=384)) + print(f"[{i + 1}/{args.n}] seed={seed} " + " ".join(f"{k}={first_success[k][-1]}" for k in kinds) + + f" ({time.time() - t0:.0f}s)", flush=True) + + summary = {k: succ_curve(v, args.k) for k, v in first_success.items()} + res = dict(task=args.task, level=task.level, capabilities=list(task.capabilities), n=args.n, k=args.k, + succ_at_k=summary, runs=runs, seconds=time.time() - t0) + with open(os.path.join(outdir, "validate.json"), "w") as f: + json.dump(res, f, indent=1, default=float) + print(json.dumps({k: [round(x, 2) for x in v] for k, v in summary.items()})) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/validate_ladder_fix.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/validate_ladder_fix.py new file mode 100644 index 0000000000000000000000000000000000000000..d80168eaa6cf7ce8c79aacac8a0f8d3e25e63e05 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/validate_ladder_fix.py @@ -0,0 +1,168 @@ +"""Check the Fix-rung texts of the layer-3 feedback ladder (docs/20 ยง4) on every ladder instance. + + python scripts/validate_ladder_fix.py [--out results/_ladder/fix_validate.json] [--only TASK] + +Per instance (task:seed from runs/api/mismatch_20261027//own.json, both models, deduplicated): + 1. the sampled instance equals the one logged in the main-table run (session_start inst); + 2. the scripted oracle succeeds in one attempt; the Fix text is built from the parameters that oracle executed; + 3. the text has no coordinate-axis labels (strip_axes leaves it unchanged) and no internal instance key names; + 4. slide_to_target / tablecloth_pull only: the strike / pull the text describes, issued as LA `move_eef` + commands in the robot-base frame through the same path as robot_server (ToolExecutor move_to with the given + speed), also succeeds -- this checks that "speed" in the text means what move_eef does. The success window is + narrow (~+-0.02) and the LA path does not hit it at exactly the oracle's speed (tablecloth 3001: oracle 0.475 + fails as LA commands, 0.48-0.52 succeed), so for these two the text's speed is the middle of the longest run of + LA successes on a 0.01 grid within +-0.10 of the oracle speed (`la_speed`). +""" +import argparse +import importlib +import json +import os +import pkgutil +import sys +import time + +import numpy as np + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) + +from lffbench import arm_specs, envs # noqa: E402 +from lffbench import tasks as task_pkg # noqa: E402 +from lffbench.agent.robot_server import strip_axes # noqa: E402 +from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor # noqa: E402 +from lffbench.task_base import TASKS # noqa: E402 + +for _m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{_m.name}") + +OUT = os.path.join(ROOT, "runs", "api", "mismatch_20261027") +BANNED = ("com_offset", "com_total", "heavy_edge", "heavy_near", "pane_side", "_oracle", " mu ", "inst[") + + +def instances(): + seen = {} + for m in ("opus", "sonnet"): + for key, d in json.load(open(os.path.join(OUT, m, "own.json"))).items(): + src = json.load(open(d + ".source.json")) + start = json.loads(open(os.path.join(src["log"], "events.jsonl")).readline()) + seen.setdefault(key, dict(task=src["task"], seed=src["seed"], logged=start["inst"], models=[])) + seen[key]["models"].append(m) + return seen + + +def same(a, b): + if isinstance(a, dict): + return isinstance(b, dict) and set(a) == set(b) and all(same(a[k], b[k]) for k in a) + if isinstance(a, (list, tuple)): + return isinstance(b, (list, tuple)) and len(a) == len(b) and all(same(x, y) for x, y in zip(a, b)) + if isinstance(a, float) or isinstance(b, float): + return abs(float(a) - float(b)) < 1e-9 + return a == b + + +def la_move(task, ex, off, **args): + """one LA move_eef, as robot_server._handle_v2: absolute base-frame target, move then gripper""" + p = ex.proprio() + cur = np.asarray(p["eef_pos"], float) - off + tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")] + tgt_w = np.asarray(tgt) + off + if any(k in args for k in ("x", "y", "z", "yaw")): + assert np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI), f"target rejected {tgt}" + mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=float(args.get("yaw", p["eef_yaw_deg"]))) + if args.get("speed") is not None: + mv["speed"] = float(args["speed"]) + ex.call("move_to", mv) + if args.get("gripper"): + ex.call("open_gripper" if args["gripper"] == "open" else "close_gripper", {}) + + +def la_replay(task, inst, params): + """the Fix text of slide / tablecloth as LA commands; returns the outcome""" + task.reset_instance(inst) + sim = task.env.sim + off = np.array(sim.data.body_xpos[sim.model.body_name2id("robot0_base")], float).copy() + ex = ToolExecutor(task, inst, image_res=64, cams=("agentview",)) + zt = envs.TABLE_Z - off[2] # tabletop height in the base frame + v = float(params["speed"]) + if task.name == "l5_slide_to_target": + x0, y0 = (np.asarray(inst["cube_xy"], float) - off[:2]) + la_move(task, ex, off, gripper="close") + la_move(task, ex, off, x=x0 - 0.22, y=y0, z=zt + 0.12, yaw=0) + la_move(task, ex, off, x=x0 - 0.22, y=y0, z=zt + 0.02) + la_move(task, ex, off, x=x0 - 0.005, y=y0, z=zt + 0.02, speed=v) + la_move(task, ex, off, z=zt + 0.10, speed=0.3) + else: + from lffbench.tasks.l5_tablecloth_pull import B_HALF, BOARD, H_HALF + b = envs.obj_pos(task.env, BOARD) - off + hx, hy, zg = b[0] - B_HALF[0] + H_HALF[0], b[1], zt + 2 * B_HALF[2] + H_HALF[2] + la_move(task, ex, off, gripper="open") + la_move(task, ex, off, x=hx, y=hy, z=zg + 0.08, yaw=0) + la_move(task, ex, off, x=hx, y=hy, z=zg, gripper="close") + la_move(task, ex, off, x=hx - 0.25, y=hy, z=zg, speed=v, gripper="open") + la_move(task, ex, off, z=zg + 0.10, speed=0.3) + return task.outcome(inst) + + +def la_speed(task, inst, v0): + """middle of the longest run of LA-replay successes on a 0.01 grid around the oracle speed""" + from importlib import import_module + mod = import_module(type(task).__module__) + grid = [round(v, 2) for v in np.arange(round(v0 - 0.10, 2), round(v0 + 0.10, 2) + 1e-9, 0.01) + if mod.V_MIN <= v <= mod.V_MAX] + ok = [bool(la_replay(task, inst, dict(speed=v))["success"]) for v in grid] + best, run = [], [] + for v, s in zip(grid, ok): + run = run + [v] if s else [] + if len(run) > len(best): + best = run + if not best: + return None, dict(zip(map(str, grid), ok)) + return best[len(best) // 2], dict(zip(map(str, grid), ok)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", default=os.path.join(ROOT, "results", "_ladder", "fix_validate.json")) + ap.add_argument("--only", default="") + a = ap.parse_args() + rows, tasks = [], {} + for key, it in sorted(instances().items()): + if a.only and it["task"] != a.only: + continue + t0 = time.time() + task = tasks.setdefault(it["task"], TASKS[it["task"]](cam_res=64)) + inst = task.sample_instance(it["seed"]) + clean = {k: v for k, v in inst.items() if not k.startswith("_")} + row = dict(key=key, models=it["models"], inst_matches_log=same(json.loads(json.dumps(clean, default=float)), + it["logged"])) + hist = task.run_scripted("oracle", inst, k=1) + params = hist[0]["params"] + row["oracle_success"] = bool(hist[0]["outcome"]["success"]) + row["oracle_failure"] = hist[0]["outcome"].get("failure") + row["params"] = json.loads(json.dumps(params, default=float)) + if it["task"] in ("l5_slide_to_target", "l5_tablecloth_pull"): + v, sweep = la_speed(task, inst, float(params["speed"])) + row["oracle_speed"], row["la_sweep"] = float(params["speed"]), sweep + params = dict(params, speed=v if v is not None else float(params["speed"])) + row["params"] = json.loads(json.dumps(params, default=float)) + text = arm_specs.fix(it["task"], clean, params) + row["fix"] = text + row["no_axis_labels"] = strip_axes(text) == text + row["no_internal_names"] = not any(b in text for b in BANNED) + if it["task"] in ("l5_slide_to_target", "l5_tablecloth_pull"): + out = la_replay(task, inst, params) + row["la_replay_success"] = bool(out["success"]) + row["la_replay_failure"] = out.get("failure") + row["ok"] = bool(row["inst_matches_log"] and row["oracle_success"] and row["no_axis_labels"] + and row["no_internal_names"] and row.get("la_replay_success", True)) + row["seconds"] = round(time.time() - t0, 1) + rows.append(row) + print(f"{'OK ' if row['ok'] else 'BAD'} {key:28s} oracle={row['oracle_success']} " + f"la={row.get('la_replay_success', '-')} inst={row['inst_matches_log']} ({row['seconds']}s)", flush=True) + os.makedirs(os.path.dirname(a.out), exist_ok=True) + json.dump(dict(rows=rows, n=len(rows), n_ok=sum(r["ok"] for r in rows)), open(a.out, "w"), indent=1) + print(f"{sum(r['ok'] for r in rows)}/{len(rows)} ok -> {a.out}") + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/validate_parts_cart.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/validate_parts_cart.py new file mode 100644 index 0000000000000000000000000000000000000000..58349b4c88968dfe22e0ccbb7ce398754fd98f2c --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/validate_parts_cart.py @@ -0,0 +1,52 @@ +"""Development physical validation; no model API, no pose injection after reset.""" +import argparse,copy,json,time,hashlib +from pathlib import Path +import numpy as np +from PIL import Image +from lffbench.tasks.lh_parts_cart import PartsCart +from lffbench import envs + +def main(): + p=argparse.ArgumentParser();p.add_argument('--seeds',nargs='+',type=int,default=[1000,1001,1002]);p.add_argument('--out',required=True);p.add_argument('--case',choices=['combined','oracle','l4','l2','l5'],default='combined');a=p.parse_args() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + x=PartsCart(cam_res=512);rows=[] + def clean(obj): + if isinstance(obj,np.ndarray):return obj.tolist() + if isinstance(obj,np.generic):return obj.item() + raise TypeError(type(obj).__name__) + for seed in a.seeds: + i=x.sample_instance(seed) + if a.case in ['l4','l2','l5']:i['traps']={k:k==a.case.upper() for k in ['L4','L2','L5']} + x.reset_instance(i);r=dict(seed=seed,case=a.case,instance=i,checkpoints=[]);rows.append(r) + def snap(label): + o=copy.deepcopy(x.outcome(i));q=out/f's{seed}_{label}.png';Image.fromarray(x.snapshot(res=512)).save(q) + r['checkpoints'].append(dict(label=label,sim_step=x.sk.n_steps,commands=x.sk.robot_commands,outcome=o,image=str(q.resolve()))) + (out/'results.json').write_text(json.dumps(rows,indent=2,default=clean)) + print(seed,label,o['success'],o['traps'],o['stages'],flush=True) + snap('initial') + if a.case=='oracle': + x.execute(i,x.oracle_params(i));snap('oracle_final');continue + if a.case in ['combined','l4']: + x.tool_push_out();snap('L4_blocked') + x.tool_push_front();snap('L4_retrieved') + x.load(careful=a.case not in ['combined','l2']);snap('loaded') + if a.case in ['combined','l2']: + x.repair_load();snap('L2_restored') + if all(x.cargo_ok(j) for j in range(2)): + if a.case in ['combined','l5']: + # First full naive push, then reuse correction loop without its initial push. + x.transport(0.,False);snap('L5_naive_push') + x._transport_only=True + # Feed a no-op execute only for the corrector's initial call; subsequent _push_at are unchanged. + original=x.execute + x.execute=lambda inst,params:None + try: + from lffbench.tasks.l7_offcenter_push import OffcenterPush + OffcenterPush.adaptive_attempt(x,i,0.) + finally:x.execute=original;x._transport_only=False + snap('L5_corrected') + else:x.transport(i['com_offset'],False) + x.repair_load();x.sk.set_gripper(False,steps=10);e=x.sk.eef_pos();x.sk.move_to([e[0],e[1],envs.TABLE_Z+.24]);snap('final') + x.env.close() + (out/'manifest.json').write_text(json.dumps(dict(case=a.case,seeds=a.seeds,task_sha256=hashlib.sha256(Path(__file__).parents[1].joinpath('lffbench/tasks/lh_parts_cart.py').read_bytes()).hexdigest(),note='scripted development validation, not model runs'),indent=2)) +if __name__=='__main__':main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/validate_parts_cart_isolated.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/validate_parts_cart_isolated.py new file mode 100644 index 0000000000000000000000000000000000000000..2fc7b396510a3b831b746bdb17761fc8c32c5678 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/validate_parts_cart_isolated.py @@ -0,0 +1,54 @@ +"""Development physical validation; no model API, no pose injection after reset.""" +import argparse,copy,json,time,hashlib +from pathlib import Path +import numpy as np +from PIL import Image +from lffbench.tasks.lh_parts_cart import PartsCart +from lffbench import envs + +def main(): + p=argparse.ArgumentParser();p.add_argument('--seeds',nargs='+',type=int,default=[1000,1001,1002]);p.add_argument('--out',required=True);p.add_argument('--case',choices=['combined','oracle','l4','l2','l5'],default='combined');a=p.parse_args() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + x=PartsCart(cam_res=512);rows=[] + def clean(obj): + if isinstance(obj,np.ndarray):return obj.tolist() + if isinstance(obj,np.generic):return obj.item() + raise TypeError(type(obj).__name__) + for seed in a.seeds: + i=x.sample_instance(seed) + if a.case in ['l4','l2','l5']:i['traps']={k:k==a.case.upper() for k in ['L4','L2','L5']} + x.reset_instance(i);r=dict(seed=seed,case=a.case,instance=i,checkpoints=[]);rows.append(r) + def snap(label): + o=copy.deepcopy(x.outcome(i));q=out/f's{seed}_{label}.png';Image.fromarray(x.snapshot(res=512)).save(q) + r['checkpoints'].append(dict(label=label,sim_step=x.sk.n_steps,commands=x.sk.robot_commands,outcome=o,image=str(q.resolve()))) + (out/'results.json').write_text(json.dumps(rows,indent=2,default=clean)) + print(seed,label,o['success'],o['traps'],o['stages'],flush=True) + snap('initial') + if a.case=='oracle': + x.execute(i,x.oracle_params(i));snap('oracle_final');continue + if a.case in ['combined','l4']: + x.tool_push_out();snap('L4_blocked') + x.tool_push_front();snap('L4_retrieved') + x.load(careful=a.case not in ['combined','l2']);snap('loaded') + if a.case in ['l4','l5']: + x.repair_load();snap('loading_prerequisite_repaired') + if a.case in ['combined','l2']: + x.repair_load();snap('L2_restored') + if all(x.cargo_ok(j) for j in range(2)): + if a.case in ['combined','l5']: + # First full naive push, then reuse correction loop without its initial push. + x.transport(0.,False);snap('L5_naive_push') + x._transport_only=True + # Feed a no-op execute only for the corrector's initial call; subsequent _push_at are unchanged. + original=x.execute + x.execute=lambda inst,params:None + try: + from lffbench.tasks.l7_offcenter_push import OffcenterPush + OffcenterPush.adaptive_attempt(x,i,0.) + finally:x.execute=original;x._transport_only=False + snap('L5_corrected') + else:x.transport(i['com_offset'] if i['traps']['L5'] else 0.,False) + x.repair_load();x.sk.set_gripper(False,steps=10);e=x.sk.eef_pos();x.sk.move_to([e[0],e[1],envs.TABLE_Z+.24]);snap('final') + x.env.close() + (out/'manifest.json').write_text(json.dumps(dict(case=a.case,seeds=a.seeds,task_sha256=hashlib.sha256(Path(__file__).parents[1].joinpath('lffbench/tasks/lh_parts_cart.py').read_bytes()).hexdigest(),note='scripted development validation, not model runs'),indent=2)) +if __name__=='__main__':main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/vla_acceptance.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/vla_acceptance.py new file mode 100644 index 0000000000000000000000000000000000000000..2020f59a594069a82ad773c594c798522f733007 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/vla_acceptance.py @@ -0,0 +1,228 @@ +#!/usr/bin/env python3 +"""Acceptance test of the VLA evaluator (lffbench/vla.py) against recorded agent attempts. + +Replays recorded first attempts through the exact path a policy takes (vla.run_session) and checks +- the verdict: outcome() must give the recorded label, for successes AND failures; +- the observation: state and both cameras must equal what the LeRobot dataset holds for that frame, and the prompt + must be what the agent was told (first_message.txt; the proprioception frame is "true" here because the dataset + records the true pose; the evaluator's default applies the L1 calibration errors). + + python3 scripts/vla_acceptance.py plan --out DIR [--per-label 2] # no simulator; any python with pyarrow + python scripts/vla_acceptance.py one DIR/cand/.json # one attempt, in the LFF environment + python3 scripts/vla_acceptance.py summary DIR + +An open-loop replay is only meaningful when the recording is reproduced, so lossless float64 actions are used where the +intermediate recordings exist (published parquet actions are float32 and diverge on chaotic contacts). A candidate +whose replay leaves the recording is reported as `diverged`, not as a verdict error. +""" +import argparse +import collections +import glob +import hashlib +import json +import os +import sys + +import numpy as np + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +AR = os.path.dirname(ROOT) +DATA = "/mnt/cpfs/shared/datasets/lffbench_agent_replays" +CUMULATIVE = {"v1.0", "v1.1", "v1.2", "v1.3"} +DIVERGED_M = 0.005 # the replayed grasp point is this far from the recording + + +def _sha(path, memo={}): + if path not in memo: + memo[path] = hashlib.sha256(open(path, "rb").read()).hexdigest() if os.path.exists(path) else None + return memo[path] + + +def code_matches(run_dir): + p = os.path.join(run_dir, "contract.json") + if not os.path.exists(p): + return False + files = json.load(open(p))["contract"].get("server_code_files") or {} + return bool(files) and all(_sha(os.path.join(ROOT, f)) == h for f, h in files.items()) + + +def raw_roots(): + roots = [f"{AR}/lerobot_replay_raw_local", f"{AR}/lerobot_replay_raw_dlc"] + for pat in ("ops/lerobot_backfill_20261102/exports/*/raw", "ops/lerobot_backfill_20261102/dlc_parallel/exports/*/raw", + "ops/compound_lh_eval_20261102/exports/*/raw", "ops/codex_watch/*/exports/*/raw", + "ops/lerobot_deepseek_20261030/exports/*/raw"): + roots += glob.glob(os.path.join(AR, pat)) + return roots + + +def cmd_plan(a): + import pyarrow.dataset as ds + os.makedirs(os.path.join(a.out, "cand"), exist_ok=True) + roots = raw_roots() + pool = collections.defaultdict(list) + for name in sorted(os.listdir(DATA)): + p = os.path.join(DATA, name, "lff/episodes.jsonl") + if name in CUMULATIVE or not os.path.exists(p): + continue + for line in open(p): + r = json.loads(line) + if not r["attempts"] or r["attempts"][0] != 1 or r["success"][0] is None: + continue + if r.get("auto_ended") and r["auto_ended"][0]: # ended by a budget inside the server, not by `finish` + continue + pool[(r["task"], bool(r["success"][0]))].append((r["length"], name, r)) + n, missing = 0, [] + for (task, label), lst in sorted(pool.items()): + lst.sort(key=lambda x: x[0]) + got, seeds = 0, set() + for need_raw in (True, False): + for length, name, r in lst: + if got >= a.per_label: + break + if r["seed"] in seeds: + continue + run_dir = os.path.join(ROOT, "runs/api", r["batch"], r["run"]) + if not os.path.isdir(run_dir) or not code_matches(run_dir): + continue + raw = next((q for q in (f"{x}/{r['batch']}/{r['run']}/ep00/frames.npz" for x in roots) if os.path.exists(q)), None) + if need_raw and raw is None: + continue + stem = f"{task}__{'ok' if label else 'fail'}{got}" + cand = dict(stem=stem, task=task, seed=r["seed"], label=label, run_dir=run_dir, dataset=name, episode_index=r["episode_index"], + instruction=r["instruction"], protocol=r["protocol"], model=r["model"], raw=raw, length=r["length"]) + if raw is None: + t = ds.dataset(os.path.join(DATA, name, "data"), format="parquet").to_table( + columns=["action", "annotation.phase", "annotation.attempt_index", "observation.state", "frame_index"], + filter=ds.field("episode_index") == r["episode_index"]).sort_by("frame_index") + np.savez(os.path.join(a.out, "cand", stem + ".npz"), + action=np.stack(t["action"].to_numpy(zero_copy_only=False)).astype(np.float64), + phase=t["annotation.phase"].to_numpy().astype(int).reshape(-1), + attempt=t["annotation.attempt_index"].to_numpy().astype(int).reshape(-1), + state=np.stack(t["observation.state"].to_numpy(zero_copy_only=False)).astype(np.float64)) + json.dump(cand, open(os.path.join(a.out, "cand", stem + ".json"), "w"), indent=1) + got += 1 + n += 1 + seeds.add(r["seed"]) + if got < a.per_label: + missing.append((task, label, got)) + print(n, "candidates;", "short of the requested count:", missing) + + +def video_frame(path, t): + import cv2 + cap = cv2.VideoCapture(path) + cap.set(cv2.CAP_PROP_POS_FRAMES, t) + ok, img = cap.read() + cap.release() + return img[:, :, ::-1] if ok else None + + +def cmd_one(a): + sys.path.insert(0, ROOT) + sys.path.insert(0, os.path.join(ROOT, "scripts")) + import lerobot_replay as LR + from lffbench import vla + c = json.load(open(a.cand)) + if c["raw"]: + z = np.load(c["raw"]) + keep = (z["attempt"] == 1) & (z["phase"] != 2) + state = np.concatenate([z["eef_pos"], z["eef_axis_angle"], z["gripper_qpos"]], axis=1) + precision = "float64" + else: + z = np.load(a.cand[:-5] + ".npz") + keep = (z["attempt"] == 1) & (z["phase"] != 2) + state = z["state"] + precision = "float32" + idx = np.flatnonzero(keep) + assert (np.diff(idx) == 1).all() and idx[0] == 0, "attempt 1 must be one contiguous prefix" + actions = z["action"][idx] + s = LR.RunLog(c["run_dir"]).start + task = LR.TASKS[c["task"]](cam_res=256) + inst = task.sample_instance(s["seed"]) + logged = s.get("inst") or {} + if s.get("arm", "none") not in (None, "none") or logged.get("nominal"): + inst.update(logged) + first_message = os.path.join(c["run_dir"], "first_message.txt") + prompt = vla.task_prompt(task, inst) + res = dict(stem=c["stem"], task=c["task"], seed=c["seed"], label=c["label"], precision=precision, n=len(actions), protocol=c["protocol"], + prompt_ok=prompt in open(first_message).read() if os.path.exists(first_message) else prompt == c["instruction"], + first_div=None, parity=[]) + mid = (len(actions) // 2) // 5 * 5 + raw_dir = os.path.dirname(c["raw"]) if c["raw"] else None + + def on_obs(t, obs): + err = float(np.abs(obs["observation/state"] - state[t]).max()) + if res["first_div"] is None and np.linalg.norm(obs["observation/state"][:3] - state[t][:3]) > DIVERGED_M: + res["first_div"] = t + if t in (0, mid) and res["first_div"] is None: + row = dict(t=t, state_err=err) + if raw_dir: + for key, f in (("observation/image", "agentview.mp4"), ("observation/wrist_image", "wrist.mp4")): + img = video_frame(os.path.join(raw_dir, f), t) + if img is not None: + row[f[:-4] + "_mae"] = float(np.abs(obs[key].astype(float) - img.astype(float)).mean()) + res["parity"].append(row) + + policy = vla.ReplayPolicy(actions, chunk=5, on_obs=on_obs) + rec = vla.run_session(task, inst, policy, k=1, max_steps=len(actions), replan=5, frame="true", idle_s=0, probe_every_s=0)[0] + res.update(verdict=rec["success"], end=rec["end"], n_steps=rec["n_steps"], detail=str(rec["detail"])[:240], failure=rec["failure"]) + res["verdict_ok"] = rec["success"] == c["label"] + json.dump(res, open(a.cand.replace("/cand/", "/out/"), "w"), indent=1) + print(c["stem"], "verdict_ok", res["verdict_ok"], "first_div", res["first_div"], "parity", res["parity"][:1], flush=True) + + +def cmd_summary(a): + rows = [json.load(open(f)) for f in sorted(glob.glob(os.path.join(a.dir, "out/*.json")))] + tally = collections.Counter() + bad = [] + for r in rows: + kind = "ok" if r["label"] else "fail" + if r["verdict_ok"]: + tally[kind + "_right"] += 1 + elif r["first_div"] is not None: + tally[kind + "_diverged"] += 1 + bad.append(r) + else: + tally[kind + "_WRONG"] += 1 + bad.append(r) + per_task = collections.defaultdict(lambda: collections.Counter()) + for r in rows: + key = "right" if r["verdict_ok"] else ("diverged" if r["first_div"] is not None else "WRONG") + per_task[r["task"]][("ok_" if r["label"] else "fail_") + key] += 1 + t0 = [p for r in rows for p in r["parity"] if p["t"] == 0] + later = [p for r in rows for p in r["parity"] if p["t"] > 0] + + def worst(ps, key): + vals = [p[key] for p in ps if key in p] + return (round(max(vals), 7), len(vals)) if vals else None + + out = dict(n=len(rows), tally=dict(tally), n_tasks=len(per_task), per_task={t: dict(c) for t, c in sorted(per_task.items())}, + prompt_mismatch=sorted({r["task"] for r in rows if not r["prompt_ok"]}), + parity_t0=dict(state=worst(t0, "state_err"), agentview=worst(t0, "agentview_mae"), wrist=worst(t0, "wrist_mae")), + parity_mid=dict(state=worst(later, "state_err"), agentview=worst(later, "agentview_mae"), wrist=worst(later, "wrist_mae")), + not_right=[{k: r[k] for k in ("stem", "seed", "precision", "first_div", "n", "detail")} for r in bad]) + json.dump(out, open(os.path.join(a.dir, "summary.json"), "w"), indent=1) + print(json.dumps({k: v for k, v in out.items() if k not in ("per_task", "not_right")}, indent=1)) + for r in out["not_right"]: + print(r["stem"], r["seed"], r["precision"], "first_div", r["first_div"], "/", r["n"], "|", r["detail"][:130]) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = ap.add_subparsers(dest="cmd", required=True) + p = sub.add_parser("plan") + p.add_argument("--out", required=True) + p.add_argument("--per-label", type=int, default=2) + p.set_defaults(fn=cmd_plan) + o = sub.add_parser("one") + o.add_argument("cand") + o.set_defaults(fn=cmd_one) + s = sub.add_parser("summary") + s.add_argument("dir") + s.set_defaults(fn=cmd_summary) + a = ap.parse_args() + a.fn(a) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/vla_eval.py b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/vla_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..557cc5b3bf7b93550070883290b6d9a7756b3c70 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/scripts/vla_eval.py @@ -0,0 +1,224 @@ +#!/usr/bin/env python3 +"""Evaluate a visuomotor policy on LFF-Bench (lffbench/vla.py). + + # one process per shard; the policy server runs elsewhere (openpi serve_policy.py, or StarVLA's) + python scripts/vla_eval.py run --policy ws://127.0.0.1:18000 --set sets/main_v2_3inst.txt --k 3 --out results/vla/ \ + --shard 0/8 --model-name pi05_lff_v1 + python scripts/vla_eval.py report results/vla/ + +Each session writes /_s/summary.json and events.jsonl; a session with a summary.json is skipped, so a +rerun resumes. --tasks takes task:seed[,seed] items, --set a file of them (the sets/ format). +""" +import argparse +import hashlib +import json +import os +import sys +import time +import traceback + +import numpy as np + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) + +CAUSES = os.path.join(ROOT, "..", "paper", "fig_scripts", "data", "causes.json") + + +def parse_items(items): + out = [] + for it in items: + name, _, seeds = it.strip().partition(":") + if not seeds: + raise SystemExit(f"{it!r}: expected task:seed[,seed]") + out += [(name, int(s)) for s in seeds.split(",")] + return out + + +def read_set(path): + return [line.strip() for line in open(path) if line.strip() and not line.startswith("#")] + + +def sha256(path): + with open(path, "rb") as f: + return hashlib.sha256(f.read()).hexdigest() + + +def causes(): + try: + return json.load(open(CAUSES))["cause"] + except OSError: + return {} + + +class Video: + """Frames at the replan rate, agentview next to wrist, written at real time speed.""" + + def __init__(self, path, replan): + import imageio + self.w = imageio.get_writer(path, fps=max(1, round(20 / replan)), quality=7, macro_block_size=8) + + def add(self, t, obs): + self.w.append_data(np.hstack([obs["observation/image"], obs["observation/wrist_image"]])) + + def close(self): + self.w.close() + + +def make_policy(spec): + from lffbench import vla + if spec == "zero": + return vla.ZeroPolicy() + if spec.startswith("ws://"): + return vla.WebsocketPolicy(spec) + raise SystemExit(f"unknown --policy {spec!r}: use ws://host:port or zero") + + +def run_one(task_name, seed, a, policy, tasks): + from lffbench import vla + from lffbench.harnesses.contract import server_code_sha + d = os.path.join(a.out, f"{task_name}_s{seed}") + if os.path.exists(os.path.join(d, "summary.json")): + return "skip" + os.makedirs(d, exist_ok=True) + task = tasks[task_name](cam_res=a.res) + inst = task.sample_instance(seed) + code_sha, code_files = server_code_sha(task_name) + start = dict(ev="session_start", task=task_name, seed=seed, protocol=getattr(task, "protocol", "cross"), + level=task.level, category=task.category, cause=causes().get(task_name), instruction=vla.task_prompt(task, inst), + k=a.k, replan=a.replan, res=a.res, frame=a.frame, idle_s=a.idle_s, probe_every_s=a.probe_every_s, + max_steps=a.max_steps or vla.budget_steps(task), model_name=a.model_name, policy=str(a.policy), + policy_metadata=getattr(policy, "metadata", None), inst={k: v for k, v in inst.items() if not k.startswith("_")}, + server_code_sha256=code_sha, server_code_files=code_files, + vla_sha256=sha256(os.path.join(ROOT, "lffbench", "vla.py")), time=time.time()) + with open(os.path.join(d, "events.jsonl"), "a") as log: + def write(rec): + log.write(json.dumps(rec, default=str) + "\n") + log.flush() + write(start) + video = Video(os.path.join(d, "rollout.mp4"), a.replan) if a.video else None + try: + t0 = time.time() + attempts = vla.run_session(task, inst, policy, k=a.k, max_steps=a.max_steps, replan=a.replan, res=a.res, + frame=a.frame, idle_s=a.idle_s, probe_every_s=a.probe_every_s, + on_frame=video.add if video else None, + on_attempt=lambda r: write(dict(ev="done", **r))) + finally: + if video: + video.close() + succ = [r["success"] for r in attempts] + first = next((r["attempt"] for r in attempts if r["success"]), None) + first_any = next((r["attempt"] for r in attempts if r["success"] or r["first_success_step"] is not None), None) + summary = {key: start[key] for key in ("task", "seed", "protocol", "level", "category", "cause", "k", "replan", "frame", + "max_steps", "model_name", "policy_metadata", "server_code_sha256")} + summary.update(status="ok", n_attempts=len(attempts), success_by_attempt=succ, first_success=first, + attempt1_success=bool(succ[0]), success=first is not None, first_success_any=first_any, + ended_by=[r["end"] for r in attempts], failure=[r["failure"] for r in attempts], + n_steps=[r["n_steps"] for r in attempts], infer_s_mean=[r["infer_s_mean"] for r in attempts], + wall_s=round(time.time() - t0, 2)) + tmp = os.path.join(d, "summary.json.tmp") + json.dump(summary, open(tmp, "w"), indent=1, default=str) + os.replace(tmp, os.path.join(d, "summary.json")) + return "ok" if first is not None else "fail" + + +def cmd_run(a): + from lffbench import tasks as task_pkg # noqa: F401 (registers the task modules) + import importlib + import pkgutil + from lffbench.task_base import TASKS + for m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{m.name}") + items = list(a.tasks or []) + if a.set: + items += read_set(a.set) + sessions = parse_items(items) + i, n = (int(x) for x in a.shard.split("/")) + sessions = sessions[i::n] + os.makedirs(a.out, exist_ok=True) + policy = make_policy(a.policy) + print(f"[vla_eval] shard {a.shard}: {len(sessions)} sessions, policy {a.policy}, metadata {getattr(policy, 'metadata', None)}", flush=True) + for task_name, seed in sessions: + try: + print(f"[vla_eval] {task_name} s{seed}: {run_one(task_name, seed, a, policy, TASKS)}", flush=True) + except Exception: # one broken session must not end the shard; a missing summary.json makes a rerun retry it + print(f"[vla_eval] {task_name} s{seed}: ERROR\n{traceback.format_exc()}", flush=True) + + +def wilson(s, n, z=1.96): + if not n: + return [None, None] + p = s / n + d = 1 + z * z / n + c = p + z * z / (2 * n) + m = z * np.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) + return [round(float((c - m) / d), 4), round(float((c + m) / d), 4)] + + +def cmd_report(a): + rows = [] + for name in sorted(os.listdir(a.dir)): + p = os.path.join(a.dir, name, "summary.json") + if os.path.exists(p): + rows.append(json.load(open(p))) + if not rows: + raise SystemExit(f"no finished sessions in {a.dir}") + k = max(r["k"] for r in rows) + + def stats(group): + n = len(group) + at = [sum(1 for r in group if r["first_success"] is not None and r["first_success"] <= j) for j in range(1, k + 1)] + anyok = sum(1 for r in group if r["first_success_any"] is not None) + return dict(n=n, succ_at=[round(s / n, 4) for s in at], a1=at[0], ak=at[-1], ak_ci95=wilson(at[-1], n), any_ok=anyok, + any_rate=round(anyok / n, 4)) + + by_cause, by_task = {}, {} + for r in rows: + by_cause.setdefault(str(r.get("cause")), []).append(r) + by_task.setdefault(r["task"], []).append(r) + non_l1 = [r for r in rows if r.get("cause") != "L1"] + report = dict(all=stats(rows), excluding_L1=stats(non_l1) if non_l1 else None, + by_cause={c: stats(g) for c, g in sorted(by_cause.items())}, + by_task={t: stats(g) for t, g in sorted(by_task.items())}, + ended_by={e: sum(r["ended_by"].count(e) for r in rows) for e in ("budget", "idle", "policy_ended")}, + infer_s_mean=round(float(np.mean([x for r in rows for x in r["infer_s_mean"] if x is not None] or [0.0])), 4), + model_names=sorted({str(r.get("model_name")) for r in rows}), + server_code_sha256=sorted({r["server_code_sha256"] for r in rows})) + json.dump(report, open(os.path.join(a.dir, "report.json"), "w"), indent=1) + print(f"{'':24s} {'n':>4s} {'A1':>6s} {f'A{k}':>6s} {'any':>6s}") + print(f"{'all':24s} {report['all']['n']:4d} {report['all']['succ_at'][0]:6.2f} {report['all']['succ_at'][-1]:6.2f} {report['all']['any_rate']:6.2f}") + for c, s in report["by_cause"].items(): + print(f"{c:24s} {s['n']:4d} {s['succ_at'][0]:6.2f} {s['succ_at'][-1]:6.2f} {s['any_rate']:6.2f}") + for t, s in report["by_task"].items(): + print(f"{t:24s} {s['n']:4d} {s['succ_at'][0]:6.2f} {s['succ_at'][-1]:6.2f} {s['any_rate']:6.2f}") + print("L1 tasks do not carry the agents' command-level offset for a direct-action policy; see lffbench/vla.py.") + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = ap.add_subparsers(dest="cmd", required=True) + r = sub.add_parser("run") + r.add_argument("--policy", required=True, help="ws://host:port (openpi protocol) or zero") + r.add_argument("--tasks", nargs="*", help="task:seed[,seed] items") + r.add_argument("--set", help="file of task:seed[,seed] items, e.g. sets/main_v2_3inst.txt") + r.add_argument("--out", required=True) + r.add_argument("--k", type=int, default=3, help="attempts per session") + r.add_argument("--replan", type=int, default=5, help="actions executed from each chunk (openpi's LIBERO eval: 5)") + r.add_argument("--res", type=int, default=256, help="camera resolution (the dataset's: 256)") + r.add_argument("--frame", default="believed", choices=["believed", "true"], help="proprioception frame") + r.add_argument("--max-steps", type=int, default=None, help="control steps per attempt (default: the agents' budget)") + r.add_argument("--idle-s", type=float, default=5.0, help="end the attempt after this long without motion (0: off)") + r.add_argument("--probe-every-s", type=float, default=5.0, help="forked success check every this long (0: off)") + r.add_argument("--shard", default="0/1", help="i/n: run every n-th session starting at i") + r.add_argument("--model-name", default=None) + r.add_argument("--video", action="store_true") + r.set_defaults(fn=cmd_run) + p = sub.add_parser("report") + p.add_argument("dir") + p.set_defaults(fn=cmd_report) + a = ap.parse_args() + a.fn(a) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l3_wall.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l3_wall.py new file mode 100644 index 0000000000000000000000000000000000000000..85c1d73ef0922858d68710e01a64b66eafeb9650 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l3_wall.py @@ -0,0 +1,501 @@ +"""L3-A wall_flush: a flat long box lies flush against a low fixed wall; put it on the plate. + +Why the prior fails: the only graspable dimension of the box is its 6 cm width (the Panda opens to +~7.9 cm; the box is 16 cm long). Grasping across the width needs one finger between the box and the +wall, but the box touches the wall (gap 0-3 mm) along its whole length, so that finger lands on top of +the wall (4.5 cm high; the box is 3.5 cm high) and the gripper closes above the box. Retrying the same +grasp with small variations fails the same way. + +What must be learned from the failure: this grasp is infeasible in this state -> change the manipulation +mode: first slide the box along the wall until it clears the wall's end (non-prehensile pre-grasp +manipulation), then grasp it across its width. + +Layout: the wall runs along y (left-right as seen from the robot). Randomised per instance: wall length +(24-30 cm), wall position, whether the wall is on the far (+x) or near (-x) side of the box, where the +box sits along the wall (always fully alongside it, >= 2 cm of wall beyond each end), box-wall gap +(0-3 mm, below camera resolution), plate position (on the open side of the box). + +Protocols: `l3_wall_flush` (cross: reset to the same instance before every attempt) and +`l3_wall_flush_within` (one episode; each attempt starts from wherever the previous one left things). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import box_xml, register_generated +from ..skills import DT, _rot_err +from ..task_base import LFFTask, register_task + +BOX_HALF = np.array([0.03, 0.08, 0.0175]) # 6 (x) x 16 (y) x 3.5 cm; long axis along y +WALL_HALF_T = 0.015 # 3 cm thick (x) +WALL_HALF_H = 0.0225 # 4.5 cm high +WALL_HALF_L_MAX = 0.16 # registered half length (y); shrunk per instance +WALL_MU = 2.0 # wall sliding friction (MuJoCo uses the max of the two geoms: finger-wall and box-wall contacts get 2.0) +BOX_DENSITY = 1500.0 # -> 0.50 kg +GRIP_OPEN = 0.079 # measured distance between the finger pads when fully open +FINGER_NEEDS = 0.012 # free space a finger needs beside the box (pad + finger shell), measured +Z_GRASP = envs.TABLE_Z + 0.022 # gripper-site height for grasping (pads cover 1.7-3.4 cm above the table) +Z_PUSH = envs.TABLE_Z + 0.022 # site height while pushing: finger tips 1.2 cm above the table, hand ~7 mm above the wall +PUSH_SPEED = 0.08 +FINGER_BELOW_SITE = 0.0096 # finger tips are this far below the gripper site (measured) +PLACE_Z = envs.TABLE_Z + 0.048 # site height at release over the plate (box bottom ~8 mm above the rim) + + +def _wrap_half_pi(a): + """wrap to [-pi/2, pi/2): box and parallel gripper are both symmetric under 180 deg""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def _yaw_of(quat_wxyz): + w, x, y, z = quat_wxyz + return _wrap_half_pi(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))) + + +@register_task +class WallFlush(LFFTask): + name = "l3_wall_flush" + level = "L3" + category = "strategy_switching" + capabilities = ("Perceive", "Reason", "Plan") + protocol = "cross" + instruction = "Put the long box on the plate." + instruction_indirect = "Put the flat blue block onto the round dish." + + def __init__(self, cam_res=None): + super().__init__(cam_res) + self._mon = None + # Per-control-step event monitor. It wraps env.step so that it also sees attempts driven by the agent + # harness (whose tools call Skills / env.step directly), not only the scripted `execute`. + orig_step = self.env.step + + def step(action): + ret = orig_step(action) + if self._mon is not None: + self._monitor_step() + return ret + + self.env.step = step + + def reset_instance(self, inst, recorder=None): + self._mon = None + sk = super().reset_instance(inst, recorder=recorder) + self._start_monitor() + return sk + + # ------------------------------------------------------------ scene + def make_bddl(self): + # 0.5 kg box and a grippy wall top (mu 2): with mu 1 / 0.13 kg an *unguarded* press onto the wall top (plain + # move_to down, as an agent would do) let the finger slide ~5 cm off the wall and, on the wall-far side, + # flipped the box onto its 3.5 cm side (10/60 instances) -- an accidental, graspable state (see task card). + box = register_generated("LffFlushBox", box_xml("lff_flush_box", BOX_HALF, (0.12, 0.30, 0.80, 1.0), + density=BOX_DENSITY)) + wall = register_generated("LffFlushWall", box_xml("lff_flush_wall", (WALL_HALF_T, WALL_HALF_L_MAX, WALL_HALF_H), + (0.62, 0.50, 0.36, 1.0), density=1000, + friction=(WALL_MU, 0.005, 0.0001)), free=False) + # regions only need to be valid and far apart; the layout is overridden in apply_instance + objs = [("box_1", box, "box_region", (-0.21, -0.26, -0.19, -0.24)), + ("plate_1", "plate", "plate_region", (-0.01, 0.24, 0.01, 0.26))] + fx = [("wall_1", wall, "wall_region", (0.19, -0.01, 0.21, 0.01))] + return write_bddl(self.name, self.instruction, objs, fx) + + def _wall(self): + """(root body id, geom ids) of the wall fixture""" + if not hasattr(self, "_wall_cache"): + m = self.env.sim.model + bid = m.body_name2id(self.env.fixtures_dict["wall_1"].root_body) + + def under(b): + while b > 0: + if b == bid: + return True + b = m.body_parentid[b] + return False + + self._wall_cache = (bid, [g for g in range(m.ngeom) if under(m.geom_bodyid[g])]) + return self._wall_cache + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + side = int(rng.choice([-1, 1])) # +1: wall on the far (+x) side of the box, -1: near (-x) side + wall_hl = float(rng.uniform(0.12, 0.15)) + wall_y = float(rng.uniform(-0.06, 0.06)) + u_max = wall_hl - BOX_HALF[1] - 0.02 # >= 2 cm of wall beyond each end of the box + box_y = wall_y + float(rng.uniform(-u_max, u_max)) + gap = float(rng.uniform(0.0, 0.003)) + box_x = float(rng.uniform(-0.12, -0.04)) if side > 0 else float(rng.uniform(-0.20, -0.12)) + wall_x = box_x + side * (WALL_HALF_T + BOX_HALF[0] + gap) + plate_xy = [box_x - side * float(rng.uniform(0.16, 0.18)), box_y + float(rng.uniform(-0.06, 0.06))] + return dict(seed=int(seed), side=side, wall_hl=wall_hl, wall_xy=[wall_x, wall_y], gap=gap, + box_xy=[box_x, box_y], plate_xy=plate_xy) + + def apply_instance(self, inst): + m = self.env.sim.model + bid, geoms = self._wall() + for g in geoms: # shrink the (collision + visual) wall boxes to this instance's length + m.geom_size[g, 1] = inst["wall_hl"] + m.body_pos[bid] = [inst["wall_xy"][0], inst["wall_xy"][1], envs.TABLE_Z + WALL_HALF_H] + m.body_quat[bid] = [1, 0, 0, 0] + bx, by = inst["box_xy"] + envs.set_obj_pose(self.env, "box_1", [bx, by, envs.TABLE_Z + BOX_HALF[2] + 0.0005]) + self._move_keep_orientation("plate_1", inst["plate_xy"]) + + def _move_keep_orientation(self, name, xy, clearance=0.002): + """Move a LIBERO mesh object to xy keeping the orientation LIBERO's sampler gave it at reset (that + orientation is the upright one; see task card), lowest collision point `clearance` above the table.""" + qa, da = envs.free_joint_addr(self.env, name) + d = self.env.sim.data + d.qpos[qa:qa + 2] = xy + d.qvel[da:da + 6] = 0.0 + self.env.sim.forward() + d.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (envs.TABLE_Z + clearance) + self.env.sim.forward() + + # ------------------------------------------------------------ perception stand-in + def observe(self): + """What a perfect perceiver reads off the camera image: box centre / yaw, the wall's footprint and the + plate centre. (Not the box-wall gap: 0-3 mm is below the camera resolution.)""" + bid, geoms = self._wall() + m = self.env.sim.model + wx, wy = m.body_pos[bid][:2] + hl = m.geom_size[geoms[0], 1] + b = envs.obj_pos(self.env, "box_1") + return dict(box_xy=b[:2].copy(), box_yaw=_yaw_of(envs.obj_quat(self.env, "box_1")), + wall_x=float(wx), wall_y=(float(wy - hl), float(wy + hl)), + plate_xy=envs.obj_pos(self.env, "plate_1")[:2].copy()) + + def _gap_now(self, o=None): + o = o or self.observe() + return float(abs(o["box_xy"][0] - o["wall_x"]) - WALL_HALF_T - BOX_HALF[0]) + + def alongside_wall(self, o=None): + """box (centre) still beside the wall and too close to it for a finger""" + o = o or self.observe() + return bool(o["wall_y"][0] < o["box_xy"][1] < o["wall_y"][1] and self._gap_now(o) < FINGER_NEEDS) + + # ------------------------------------------------------------ contacts + def _finger_landings(self): + """Surfaces the finger tips are resting on: contacts between a finger and a non-robot geom whose normal is + mostly vertical (a tip landing on a top surface). Returns {label: contact z}, label in 'wall' | 'box' | + 'plate' | 'table' | 'other'. Side contacts (a finger brushing the box's side, the push stroke) are ignored.""" + m, d = self.env.sim.model, self.env.sim.data + if not hasattr(self, "_geom_groups"): + fg = {g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_finger")} + robot = set(envs.robot_geom_ids(self.env)) + self._geom_groups = (fg, robot, set(self._wall()[1]), set(envs.obj_geom_ids(self.env, "box_1")), + set(envs.obj_geom_ids(self.env, "plate_1"))) + fg, robot, wall, box, plate = self._geom_groups + out = {} + for i in range(d.ncon): + c = d.contact[i] + if c.geom1 in fg and c.geom2 not in robot: + other = c.geom2 + elif c.geom2 in fg and c.geom1 not in robot: + other = c.geom1 + else: + continue + if abs(c.frame[2]) < 0.7: + continue + if other in wall: + lab = "wall" + elif other in box: + lab = "box" + elif other in plate: + lab = "plate" + else: + lab = "table" if (m.geom_id2name(other) or "").startswith("table") else "other" + out.setdefault(lab, float(c.pos[2])) + return out + + def _finger_landing(self): + hits = self._finger_landings() + for lab in ("wall", "box", "plate", "table", "other"): + if lab in hits: + return lab + return None + + # ------------------------------------------------------------ event monitor (what happened in this attempt) + def _closing_axis(self): + m, d = self.env.sim.model, self.env.sim.data + jid = m.joint_name2id(self.env.robots[0].gripper.joints[0]) + a = d.xaxis[jid][:2] + return a / max(np.linalg.norm(a), 1e-9) + + def _snapshot(self, contact_z): + """state at the moment a finger lands on something""" + o = self.observe() + e = self.sk.eef_pos() if self.sk is not None else self.env.sim.data.site_xpos[self.env.robots[0].eef_site_id] + bx = self.env.sim.data.body_xmat[envs.body_id(self.env, "box_1")].reshape(3, 3)[:2, 0] # box short axis + cosang = abs(float(self._closing_axis() @ (bx / max(np.linalg.norm(bx), 1e-9)))) + yaw_err = float(np.arccos(np.clip(cosang, 0.0, 1.0))) + wy0, wy1 = o["wall_y"] + return dict(contact_z=float(contact_z - envs.TABLE_Z), eef=[float(e[0]), float(e[1]), float(e[2])], + box_xy=[float(o["box_xy"][0]), float(o["box_xy"][1])], gap=self._gap_now(o), + alongside=self.alongside_wall(o), yaw_err=yaw_err, + span=float(2 * (BOX_HALF[0] * np.cos(yaw_err) + BOX_HALF[1] * np.sin(yaw_err))), + box_offset=float(np.linalg.norm(np.array(e[:2]) - o["box_xy"])), + # signed wall length beside the gripper towards each end (< 0: gripper is past that end) + wall_left={1: float(wy1 - e[1]), -1: float(e[1] - wy0)}) + + def _start_monitor(self): + b = envs.obj_pos(self.env, "box_1") + self._mon = dict(start_xy=b[:2].copy(), rest_z=float(b[2]), max_dz=0.0, wall_hit=None, box_top_hit=None, + prev=set()) + + def _monitor_step(self): + mon = self._mon + hits = self._finger_landings() + mon["max_dz"] = max(mon["max_dz"], float(envs.obj_pos(self.env, "box_1")[2] - mon["rest_z"])) + for lab, key in (("wall", "wall_hit"), ("box", "box_top_hit")): + if lab in hits and lab not in mon["prev"]: # onset of a landing; keep the latest one + mon[key] = self._snapshot(hits[lab]) + mon["prev"] = set(hits) + + def _finger_front(self, direction): + """how far the (closed) fingers stick out from the gripper site along `direction` (xy unit vector)""" + m, d = self.env.sim.model, self.env.sim.data + e = self.sk.eef_pos() + best = 0.0 + for g in range(m.ngeom): + if not (m.geom_id2name(g) or "").startswith("gripper0_finger") or m.geom_type[g] != 7: + continue + mid = m.geom_dataid[g] + v = m.mesh_vert[m.mesh_vertadr[mid]:m.mesh_vertadr[mid] + m.mesh_vertnum[mid]] + w = v @ d.geom_xmat[g].reshape(3, 3).T + d.geom_xpos[g] - e + best = max(best, float((w[:, :2] @ direction).max())) + return best + + # ------------------------------------------------------------ primitives used by the scripted policies + def _yaw_near(self, yaw): + """The parallel gripper (and the box) are symmetric under 180 deg, so pick yaw + k*pi closest to the current + commanded yaw: the OSC's axis-angle error is ill-defined at 180 deg and a half-turn request can flip the + hand over (measured: in the within protocol it twisted the arm into a state it never recovered from).""" + cands = [yaw + k * np.pi for k in (-1, 0, 1)] + cands = [c for c in cands if abs(c) <= np.pi / 2 + 0.4] or cands + return float(min(cands, key=lambda c: abs(c - self.sk.yaw))) + + def _align(self, tol=0.03, max_steps=60): + """Skills.move_to stops on position only; hold until the commanded yaw has actually been reached.""" + sk = self.sk + for _ in range(max_steps): + R = sk._R() @ sk.eef_mat().T + if np.arccos(np.clip((np.trace(R) - 1) / 2, -1, 1)) < tol: + break + sk.hold(1) + + def _guarded_descent(self, xyz, speed=0.12, max_steps=60): + """Straight-line descent that stops as soon as a finger lands on a surface above the target (the way a + grasp approach with contact sensing behaves). Without it, the OSC keeps pressing the finger into the + wall top and the compliant arm slides ~2 cm sideways off it. Returns what the finger landed on.""" + sk = self.sk + p0 = sk.eef_pos() + tgt = np.asarray(xyz, float) + sk.bias + dist = max(np.linalg.norm(tgt - p0), 1e-6) + R = sk._R() + landed = None + for k in range(max_steps): + ref = p0 + (tgt - p0) * min(1.0, (k + 1) * speed * DT / dist) + sk._act(ref - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip) + hit = self._finger_landing() + if hit is not None and sk.eef_pos()[2] > tgt[2] + 0.005: + landed = hit + break + if np.linalg.norm(tgt - sk.eef_pos()) < 0.003: + break + sk.hold(4) + return landed + + def push_along_wall(self, end, margin): + """Closed gripper (fingers side by side across the box) behind the box's trailing end face; slide the + box along y (towards the wall's +y end if end=+1, -y end if end=-1) until the box centre is `margin` + beyond that end of the wall.""" + sk, o = self.sk, self.observe() + bx, by = o["box_xy"] + wall_end = o["wall_y"][1] if end > 0 else o["wall_y"][0] + dist = float(np.clip(end * (wall_end + end * margin - by), 0.0, 0.32)) + yaw = self._yaw_near(o["box_yaw"] + np.pi / 2) # fingers close along the box's short axis + u = np.array([0.0, float(end)]) + sk.set_gripper(True, steps=6) + sk.move_to([bx, by - end * (BOX_HALF[1] + 0.06), Z_PUSH + 0.10], yaw=yaw) + self._align() + front = self._finger_front(u) + face = by - end * BOX_HALF[1] + start_y = face - end * (front + 0.035) + stop_y = face + end * (dist - front) + sk.move_to([bx, start_y, Z_PUSH + 0.10]) + sk.move_to([bx, start_y, Z_PUSH], tol=0.003) + sk.move_to([bx, stop_y, Z_PUSH], speed=PUSH_SPEED, tol=0.005, max_steps=300) + sk.hold(3) + sk.move_to([bx, stop_y, Z_PUSH + 0.10], speed=0.2) + + def grasp_and_place(self, dx=0.0, dy=0.0, dyaw=0.0): + """Top-down grasp across the box's width at the observed box centre (+ offsets), lift; if the box is + held, carry it to the plate and release it there.""" + sk, o = self.sk, self.observe() + gx, gy = o["box_xy"][0] + dx, o["box_xy"][1] + dy + yaw = self._yaw_near(o["box_yaw"] + np.pi / 2 + dyaw) + sk.set_gripper(False, steps=8) + sk.move_to([gx, gy, Z_GRASP + 0.10], yaw=yaw) + self._align() + self._guarded_descent([gx, gy, Z_GRASP]) + sk.set_gripper(True, steps=15) + z0 = envs.obj_pos(self.env, "box_1")[2] + sk.move_to([gx, gy, Z_GRASP + 0.15], speed=0.25) + if not (sk.holding("box_1") and envs.obj_pos(self.env, "box_1")[2] > z0 + 0.08): + sk.set_gripper(False, steps=8) + return + px, py = o["plate_xy"] + sk.move_to([px, py, PLACE_Z + 0.10]) + sk.move_to([px, py, PLACE_Z], tol=0.004) + sk.set_gripper(False, steps=12) + sk.move_to([px, py, PLACE_Z + 0.10]) + + def execute(self, inst, params): + if params["mode"] == "push_grasp": + self.push_along_wall(params["end"], params["margin"]) + self.grasp_and_place(params.get("dx", 0.0), params.get("dy", 0.0), params.get("dyaw", 0.0)) + + # ------------------------------------------------------------ outcome / F2 feedback + def outcome(self, inst): + """Success = box resting flat on the plate, released. The F2 text is built from the event monitor, so it + describes agent-driven attempts as well as scripted ones. Ends the current monitoring segment.""" + envs.settle(self.env, 30) + env, mon = self.env, self._mon or {} + b = envs.obj_pos(env, "box_1") + p = envs.obj_pos(env, "plate_1") + dxy = float(np.linalg.norm(b[:2] - p[:2])) + flat = abs(envs.obj_upright_cos(env, "box_1")) > 0.9 + held = bool(self.sk.holding("box_1")) if self.sk is not None else False + on_plate = envs.contacts_between(env, envs.obj_geom_ids(env, "box_1"), envs.obj_geom_ids(env, "plate_1")) + success = bool(dxy < 0.05 and envs.obj_min_z(env, "box_1") > envs.TABLE_Z + 0.004 and flat and not held + and on_plate) + lifted = mon.get("max_dz", 0.0) > 0.03 + start = mon.get("start_xy", b[:2]) + moved_y = float(b[1] - start[1]) + pushed = (not lifted) and abs(moved_y) > 0.02 + wall_hit, top_hit = mon.get("wall_hit"), mon.get("box_top_hit") + side_txt = "far (+x)" if inst["side"] > 0 else "near (-x)" + mode, parts, wall_left = "success", [], None + if success: + parts.append("The box is resting on the plate.") + else: + if pushed: + parts.append(f"The box was pushed {100 * abs(moved_y):.1f} cm along the wall (towards " + f"{'+y' if moved_y > 0 else '-y'}).") + if lifted: + if held: + mode = "still_held" + parts.append("The box is still in the gripper; it was not released on the plate.") + elif on_plate: + mode = "placed_off" + parts.append(f"The box was put on the plate but is not resting on it properly ({100 * dxy:.1f} cm " + f"from the plate centre{'' if flat else ', tilted'}).") + else: + mode = "placed_off" + parts.append(f"The box was lifted but ended on the table, {100 * dxy:.1f} cm from the plate " + f"centre.") + elif wall_hit is not None: + mode = "wall_blocked" + parts.append( + f"The gripper could not get around the box: the finger on the wall side ({side_txt} side) came down " + f"on top of the wall, {100 * wall_hit['contact_z']:.1f} cm above the table, which is higher than " + f"the top of the box ({200 * BOX_HALF[2]:.1f} cm), so the box was not grasped or lifted. Where the " + f"gripper came down, the box is flush against the wall (gap {1000 * max(wall_hit['gap'], 0):.0f} mm).") + if pushed: + e = 1 if moved_y > 0 else -1 + wall_left = wall_hit["wall_left"][e] + if wall_left > 0: + parts.append(f"The wall still continues {100 * wall_left:.1f} cm beyond the grasp point in the " + f"{'+y' if e > 0 else '-y'} direction.") + else: + parts.append(f"The grasp point was only {100 * -wall_left:.1f} cm past the " + f"{'+y' if e > 0 else '-y'} end of the wall, so the finger still came down on it.") + elif top_hit is not None: + mode = "box_top" + if top_hit["yaw_err"] > np.radians(30): + parts.append(f"The fingers came down on top of the box: along the gripper's closing direction the " + f"box measures {100 * top_hit['span']:.0f} cm, more than the {100 * GRIP_OPEN:.1f} cm " + f"maximum opening. The box was not lifted.") + else: + parts.append(f"A finger came down on top of the box (the gripper was {100 * top_hit['box_offset']:.1f}" + f" cm from the box centre), so the box was not grasped or lifted.") + else: + mode = "not_lifted" + parts.append(f"The box was not lifted; it is {100 * dxy:.1f} cm from the plate centre.") + if b[2] < envs.TABLE_Z - 0.05: + mode = "fell_off" + parts.append("The box fell off the table.") + elif not flat and mode != "placed_off": + parts.append("The box is no longer lying flat.") + out = dict(success=success, mode=mode, plate_dist=dxy, box_xy=[float(b[0]), float(b[1])], lifted=bool(lifted), + pushed_y=moved_y, alongside_wall=self.alongside_wall(), wall_left=wall_left, + terminal=bool(b[2] < envs.TABLE_Z - 0.05), detail=" ".join(parts)) + self._start_monitor() # next segment (within protocol) starts here + return out + + # ------------------------------------------------------------ scripted references + def _nearer_end(self): + o = self.observe() + by = o["box_xy"][1] + return 1 if (o["wall_y"][1] - by) < (by - o["wall_y"][0]) else -1 + + def default_params(self, inst): + return dict(mode="grasp") + + def oracle_params(self, inst): + return dict(mode="push_grasp", end=self._nearer_end(), margin=0.045) + + def blind_params(self, inst, attempt, rng): + return dict(mode="grasp", dx=float(rng.normal(0, 0.008)), dy=float(rng.normal(0, 0.008)), + dyaw=float(rng.normal(0, 0.12))) + + def adapt_params(self, inst, history): + """Uses the F2 measurements of the previous attempt: + wall_blocked / box_top on a direct grasp -> switch mode: slide the box out past the nearer wall end + (wall ends read off the image), then grasp; + wall_blocked after a push -> push further by the reported remaining wall length + 2 cm; + anything else (missed, dropped, ...) -> keep the strategy (the state is re-observed).""" + out, prm = history[-1]["outcome"], history[-1]["params"] + if prm["mode"] != "push_grasp": + if out["mode"] in ("wall_blocked", "box_top"): + return dict(mode="push_grasp", end=self._nearer_end(), margin=0.045) + return dict(prm) + if out["mode"] == "wall_blocked": + return dict(mode="push_grasp", end=prm["end"], + margin=float(prm["margin"] + max(out["wall_left"] or 0.0, 0.0) + 0.02)) + return dict(prm) + + # ------------------------------------------------------------ protocols + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + if self.protocol != "within": + return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt) + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + self.reset_instance(inst) + for a in range(k): + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + params = self.default_params(inst) if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + else: + raise ValueError(kind) + if params["mode"] == "push_grasp" and not self.alongside_wall(): + params = dict(params, mode="grasp") # already pushed clear in an earlier attempt of this episode + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history + + +@register_task +class WallFlushWithin(WallFlush): + name = "l3_wall_flush_within" + protocol = "within" diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l4_nest.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l4_nest.py new file mode 100644 index 0000000000000000000000000000000000000000..1176314e28197c49c48a0dcb3c29ba649f2b2780 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l4_nest.py @@ -0,0 +1,644 @@ +"""L4-C nest_order: nest three cups one inside another; the tallest cup is not the widest. + +Scene: three open round cups (red, green, blue; 1.5 mm walls leaning outwards by TAPER_DEG = 5 deg, like slightly +flared tumblers) stand apart on the table. Each cup has its own bottom width and its own height (re-drawn per +instance, 3.5-10 cm tall). Cups are resized per instance by editing their geoms in sim.model (wall segments + +floor), so one env serves every instance (same technique as l4_fit_container). + +Trap (common sense): "the bigger cup goes outside", and a cup looks big mostly by its height. On (1 - P_AGREE) of +the instances the tallest cup is the middle one by width: it is at least INV_DH = 3.5 cm taller than the widest cup. +Their openings then differ by only 3-9 mm in diameter, and from the wrist camera at its start height the taller +one's opening is closer to the camera and looks about as big (about half the instances: bigger); from the front +camera the taller one looks clearly bigger. The narrowest cup is the shortest, so the very first move of the naive +order (widest cup into the tallest one) already fails, out on the table. + +A variant where the innermost cup was taller than the middle one (and the widest cup the tallest) was dropped +2026-10-08: its failure (middle cup on the rim of the innermost cup, both inside the outer one) looked like a nest +from both cameras -- the same flaw as the 14-deg version. + +What the failure looks like (the point of this version, user review 2026-10-08): which cup fits into which is +decided by the bottoms (same flare for all cups), and the sizes are drawn so that a cup whose bottom is too wide +does not go in at all -- it stays on the other cup's rim or wedges in the opening, its bottom at most STUCK_MAX += 0.5 cm below the rim. So a wrong placement leaves a cup standing on top of another one, its whole body above the +rim: visible in both cameras without any text feedback. A cup that fits goes down to the floor (centring tolerance +>= TOL_MIN = 7.5 mm thanks to the flare); in the right nest the taller, narrower cups stick out of the shorter, +wider ones, but each stands inside the next. + +Prior (naive): tallest cup outermost, then the next tallest. Learner: a cup that ended up on top of another cup +must go outside it; swap that pair. Feedback F1 (default) says only failed / succeeded; F2 (ablation) describes +which cup stands in / on which, in words, with no sizes or positions. + +Only move_to / open / close are needed: grasp a cup across its upper wall, carry it over the other cup, release it +just above that cup's rim. +""" +import itertools + +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, _wrap, register_generated +from ..skills import _rot_err +from ..task_base import LFFTask, register_task + +N_SEG = 20 # wall segments per cup (regular polygon) +TAN_SEG = float(np.tan(np.pi / N_SEG)) +COS_SEG = float(np.cos(np.pi / N_SEG)) +TAPER_DEG = 5.0 # wall lean (from vertical) +TAPER = float(np.radians(TAPER_DEG)) +TT = float(np.tan(TAPER)) +WALL_T = 0.0015 # wall thickness (normal to the wall) +WALL_TH = WALL_T / float(np.cos(TAPER)) # horizontal wall thickness +FLOOR_T = 0.003 +Z0 = 0.0003 # walls start this far above the cup's underside (the floor disc carries the cup) +H_RANGE = (0.035, 0.100) # total cup height +RB_WIDE = (0.023, 0.030) # bottom outer apothem of the cup with the widest bottom +STEP = (0.0055, 0.0075) # bottom apothem difference between neighbours in the true order +RIM_MAX = 0.033 # outer apothem of the widest opening (gripper opens 7.9 cm) +CLEAR_MIN = 0.003 # radial gap (worst case) of a fitting cup standing on the other cup's floor +TOL_MIN = 0.0075 # a fitting cup goes in if its bottom lands within this of the other cup's axis +STUCK_MAX = 0.005 # a too-wide cup's bottom stops no deeper than this below the other cup's rim (5-deg walls +# self-lock: a cup pressed 1.2 cm into the opening wedged, and the narrow cup tipped over with it) +INV_DH = 0.035 # in the swapped pair the narrower cup is taller by at least this +KEEP_DH = 0.010 # in an unswapped pair the wider cup is taller by at least this +P_AGREE = 0.15 # share of instances whose height order is the right nesting order +SEAT_H = 0.010 # "standing on the floor": bottom less than this above the other cup's floor +SEAT_TILT = 15.0 # deg; a tall cup in a short, wider one can lean a little +WRIST_CAM_H = 0.367 # wrist camera height above the table at the start pose (measured 2026-10-08) +COLORS = {"red": (0.78, 0.22, 0.20, 1.0), "green": (0.28, 0.62, 0.32, 1.0), "blue": (0.22, 0.42, 0.80, 1.0)} +CUP_NAMES = ("cup_1", "cup_2", "cup_3") +DENSITY = 600.0 +# execution +GRASP_BELOW_RIM = 0.012 # gripper site this far below the rim when grasping +Z_CARRY = envs.TABLE_Z + 0.24 +DROP = 0.006 # held cup's bottom this far above the receiving rim at release +FINGER_CLEAR = 0.015 # gripper site at least this far above any rim around the target at release: fingers opened +# inside a taller outer cup press on its wall and carry it away on the way up (seed 1009, 2026-10-08) +PARK = (-0.45, 0.0, envs.TABLE_Z + 0.35) +H_NOISE = 0.03 # relative noise of the blind policy's height judgement + + +# ---------------------------------------------------------------- cup geometry +def _quat_mul(a, b): + w1, x1, y1, z1 = a + w2, x2, y2, z2 = b + return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, + w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2]) + + +def _seg_quat(phi): + """segment frame: about z by phi, then tilted about its own y (tangential) axis by TAPER, so that its local z + (along the wall) leans outwards and its local x is the wall's outward normal""" + qz = np.array([np.cos(phi / 2), 0.0, 0.0, np.sin(phi / 2)]) + qy = np.array([np.cos(TAPER / 2), 0.0, np.sin(TAPER / 2), 0.0]) + return _quat_mul(qz, qy) + + +def seg_half_len(rb, H): + """tangential half length of a wall segment: one polygon side at the rim (+0.2 mm overlap)""" + return (rb + TT * H) * TAN_SEG + 0.0002 + + +def rim_radius(rb, H): + """outer apothem of the opening""" + return rb + TT * H + + +def inner_radius(rb, z): + """inner apothem at height z above the cup's underside""" + return rb + TT * z - WALL_TH + + +def bottom_reach(rb, H): + """largest horizontal radius of the cup's outside at its bottom (the segment tips stick out a little beyond + the polygon because every segment is as wide as a rim-level polygon side)""" + return float(np.hypot(rb + TT * Z0, seg_half_len(rb, H))) + + +def fit_clearance(rb_in, H_in, rb_out): + """radial clearance (worst case over relative yaw) of cup `in` standing on the floor of cup `out`; + negative = does not go down to the floor. The flare is the same for both cups, so the bottom is the tightest + height.""" + return inner_radius(rb_out, FLOOR_T) - bottom_reach(rb_in, H_in) + + +def centring_tol(rb_in, H_in, rb_out, H_out): + """how far (worst case) cup `in`'s bottom centre may be off cup `out`'s axis when it is lowered in at the rim + and still get inside (the flared wall then guides it down)""" + return inner_radius(rb_out, H_out) - bottom_reach(rb_in, H_in) + + +def stop_height(rb_in, rb_out, H_out): + """height (above cup `out`'s underside) where a too-wide cup `in`, lowered centred, stops: where its bottom + meets the sloping inner wall, or on the rim if that is higher than the cup""" + return min((rb_in - rb_out + WALL_TH) / TT, H_out) + + +def _cup_parts(rb, H): + """[(pos, half size, quat)] of the wall segments in the cup body frame (origin at mid height).""" + zc = (Z0 + H) / 2 + hs = (H - Z0) / (2 * np.cos(TAPER)) + rc = rb + TT * zc - WALL_T / 2 * np.cos(TAPER) + zz = zc + WALL_T / 2 * np.sin(TAPER) - H / 2 + hl = seg_half_len(rb, H) + out = [] + for k in range(N_SEG): + phi = 2 * np.pi * k / N_SEG + out.append(((rc * np.cos(phi), rc * np.sin(phi), zz), (WALL_T / 2, hl, hs), _seg_quat(phi))) + return out + + +def _floor_part(rb, H): + return (0.0, 0.0, -H / 2 + FLOOR_T / 2), (rb - 0.0003, FLOOR_T / 2, 0.0), np.array([1.0, 0.0, 0.0, 0.0]) + + +def cup_xml(model_name, rgba): + """Open flared cup: N_SEG tilted wall boxes + a cylinder floor (sizes are overwritten per instance).""" + geoms = [] + rb, H = RB_WIDE[1], H_RANGE[1] + for k, (p, s, q) in enumerate(_cup_parts(rb, H)): + geoms.append(f' ') + geoms.append(f' ') + fp, fs, _ = _floor_part(rb, H) + geoms.append(f' ') + geoms.append(f' ') + return _wrap(model_name, "\n".join(geoms), H / 2, rim_radius(rb, H) / COS_SEG) + + +def disable_midphase(env): + """The cups are resized at run time by editing geom pos / size in sim.model, but MuJoCo's per-body bounding + volume hierarchy (bvh_aabb, used by the collision mid-phase) is computed once at compile time for the registered + maximum size. A resized wall that lies outside its compiled leaf box is silently skipped: the gripper fingers + passed straight through the walls of the smaller cups (found 2026-10-07). Without the mid-phase MuJoCo tests all + geom pairs of two nearby bodies (still filtered by the run-time geom_rbound set in _reshape_cup).""" + import mujoco + m = env.sim.model._model + m.opt.disableflags |= int(mujoco.mjtDisableBit.mjDSBL_MIDPHASE) + + +def kendall(a, b): + """number of pairs ordered differently in the two orders""" + pa, pb = {c: k for k, c in enumerate(a)}, {c: k for k, c in enumerate(b)} + return sum((pa[x] < pa[y]) != (pb[x] < pb[y]) for x, y in itertools.combinations(a, 2)) + + +@register_task +class NestOrder(LFFTask): + name = "l4_nest_order" + level = "L4" + category = "geometry_inference" + capabilities = ("Perceive", "Reason", "Plan") + instruction = "Nest the red, green and blue cups one inside another." + instruction_indirect = "Put the three cups one inside another, like a set of nesting cups." + + # ------------------------------------------------------------ scene + def make_bddl(self): + cats = [register_generated(f"LffNestCup{c.capitalize()}", cup_xml(f"lff_nest_cup_{c}", COLORS[c])) + for c in COLORS] + regions = [(-0.25, -0.15), (-0.05, 0.0), (-0.25, 0.15)] + objs = [(n, cat, f"{n}_region", (x - 0.01, y - 0.01, x + 0.01, y + 0.01)) + for n, cat, (x, y) in zip(CUP_NAMES, cats, regions)] + return write_bddl(self.name, self.instruction, objs) + + @staticmethod + def _heights_ok(case, h): + """h[s] = height of the cup with the s-th narrowest bottom (0 = innermost in the true nest)""" + if case == "agree": # taller = wider: the height order is the nesting order + return h[2] >= h[1] + KEEP_DH and h[1] >= h[0] + KEEP_DH + if case == "swap_wide": # the middle cup is the tallest, the narrowest one the shortest + return h[1] >= h[2] + INV_DH and h[2] >= h[0] + KEEP_DH + raise ValueError(case) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + u = rng.random() + case = "agree" if u < P_AGREE else "swap_wide" + for _ in range(200000): + heights = [float(rng.uniform(*H_RANGE)) for _ in range(3)] # by true size: 0 = narrowest bottom + if not self._heights_ok(case, heights): + continue + rb3 = float(rng.uniform(*RB_WIDE)) + rb2 = rb3 - float(rng.uniform(*STEP)) + rb1 = rb2 - float(rng.uniform(*STEP)) + rbs = [rb1, rb2, rb3] + rims = [rim_radius(rb, h) for rb, h in zip(rbs, heights)] + if max(rims) > RIM_MAX: + continue + ok = True + for p, q in itertools.permutations(range(3), 2): # p into q + if p < q: + ok &= (fit_clearance(rbs[p], heights[p], rbs[q]) >= CLEAR_MIN + and centring_tol(rbs[p], heights[p], rbs[q], heights[q]) >= TOL_MIN) + else: + ok &= heights[q] - stop_height(rbs[p], rbs[q], heights[q]) <= STUCK_MAX + if ok: + break + else: + raise RuntimeError("could not sample cup sizes") + xy = [] + while len(xy) < 3: + xy = [] + for _k in range(3): + for _t in range(200): + p = [float(rng.uniform(-0.27, 0.02)), float(rng.uniform(-0.17, 0.17))] + if all(np.hypot(p[0] - q[0], p[1] - q[1]) >= 0.14 for q in xy): + xy.append(p) + break + # the colour is fixed per object (cup_1 red, cup_2 green, cup_3 blue: one generated class each); shuffle + # which object gets which size / height / position + perm = [int(i) for i in rng.permutation(3)] # perm[size index] = object slot + cups = [None] * 3 + for s in range(3): + cups[perm[s]] = dict(name=CUP_NAMES[perm[s]], color=list(COLORS)[perm[s]], rb=rbs[s], height=heights[s], + rim=rims[s], xy=xy[s], size_rank=s) + order = sorted(range(3), key=lambda j: -cups[j]["rb"]) # outermost first (indices into cups) + naive = sorted(range(3), key=lambda j: -cups[j]["height"]) + assert (naive == order) == (case == "agree"), (seed, case) + by = lambda s: perm[s] # noqa: E731 object index of size rank s + return dict(seed=int(seed), case=case, cups=cups, order=order, naive_order=naive, + bottom_cm=[round(200 * c["rb"], 2) for c in cups], + opening_cm=[round(200 * c["rim"], 2) for c in cups], + height_cm=[round(100 * c["height"], 2) for c in cups], + # relative size of each opening in the wrist camera at its start height (1 = largest) + wrist_apparent=[round(float(v), 3) for v in (lambda a: a / a.max())(np.array( + [c["rim"] / (WRIST_CAM_H - c["height"]) for c in cups]))], + clear_mm=[round(1000 * fit_clearance(rbs[s], heights[s], rbs[s + 1]), 2) for s in range(2)], + tol_mm=[round(1000 * centring_tol(rbs[s], heights[s], rbs[s + 1], heights[s + 1]), 2) + for s in range(2)], + # wrong neighbour pairs: how deep (cm) the wider cup's bottom gets below the narrower cup's rim + stuck_cm={f"{by(s + 1)}in{by(s)}": round(100 * (heights[s] - stop_height( + rbs[s + 1], rbs[s], heights[s])), 2) for s in range(2)}) + + def _reshape_cup(self, name, rb, H): + m = self.env.sim.model + o = self.env.objects_dict[name] + parts = _cup_parts(rb, H) + [_floor_part(rb, H)] + for names in (o.contact_geoms, o.visual_geoms): + assert len(names) == len(parts), (name, len(names)) + for k, n in enumerate(names): + g = m.geom_name2id(n) + pos, size, quat = parts[k] + m.geom_pos[g] = pos + m.geom_size[g] = size + m.geom_quat[g] = quat + if k < N_SEG: + m.geom_rbound[g] = float(np.linalg.norm(size)) + m.geom_aabb[g] = [0, 0, 0, *size] + else: + m.geom_rbound[g] = float(np.hypot(size[0], size[1])) + m.geom_aabb[g] = [0, 0, 0, size[0], size[0], size[1]] + # mass / inertia of the resized cup: conical shell + disc floor + bid = int(m.geom_bodyid[m.geom_name2id(o.contact_geoms[0])]) + slant = (H - Z0) / np.cos(TAPER) + r_mid = rb + TT * (H + Z0) / 2 + wall_m = DENSITY * 2 * np.pi * r_mid * WALL_T * slant + floor_m = DENSITY * np.pi * rb ** 2 * FLOOR_T + mass = wall_m + floor_m + # wall centroid height (from the underside): area-weighted, r grows linearly with z + r0, r1 = rb + TT * Z0, rb + TT * H + z_w = Z0 + (H - Z0) * (r0 + 2 * r1) / (3 * (r0 + r1)) + z_cm = (wall_m * z_w + floor_m * FLOOR_T / 2) / mass + Izz = wall_m * r_mid ** 2 + floor_m * rb ** 2 / 2 + Ixx = (wall_m * (r_mid ** 2 / 2 + (H - Z0) ** 2 / 12 + (z_w - z_cm) ** 2) + + floor_m * (rb ** 2 / 4 + (FLOOR_T / 2 - z_cm) ** 2)) + m.body_mass[bid] = mass + m.body_inertia[bid] = [Ixx, Ixx, Izz] + m.body_ipos[bid] = [0.0, 0.0, z_cm - H / 2] + m.body_iquat[bid] = [1.0, 0.0, 0.0, 0.0] + + def apply_instance(self, inst): + disable_midphase(self.env) + for c in inst["cups"]: + self._reshape_cup(c["name"], c["rb"], c["height"]) + envs.set_obj_pose(self.env, c["name"], [*c["xy"], envs.TABLE_Z + c["height"] / 2 + 0.0005]) + + # ------------------------------------------------------------ state + def _cup_state(self, inst, j): + c = inst["cups"][j] + bid = envs.body_id(self.env, c["name"]) + p = self.env.sim.data.body_xpos[bid].copy() + R = self.env.sim.data.body_xmat[bid].reshape(3, 3) + tilt = float(np.degrees(np.arccos(np.clip(R[2, 2], -1, 1)))) + bottom = p - R[:, 2] * c["height"] / 2 # centre of the floor's underside + rim = p + R[:, 2] * c["height"] / 2 + return dict(p=p, tilt=tilt, bottom=bottom, rim=rim, floor_top=bottom[2] + FLOOR_T * R[2, 2]) + + def relations(self, inst): + """For each cup: which cup it stands in / on (if any), how high, seated or not.""" + st = [self._cup_state(inst, j) for j in range(3)] + rel = [] + for j in range(3): + sj = st[j] + best = None + for i in range(3): + if i == j: + continue + ci, si = inst["cups"][i], st[i] + if si["tilt"] > 45: + continue + d = float(np.hypot(*(sj["bottom"][:2] - si["p"][:2]))) + if d > rim_radius(ci["rb"], ci["height"]) + 0.01: + continue # not above / in cup i + hb = float(sj["bottom"][2] - si["floor_top"]) # j's bottom above i's floor + # (the last test keeps a cup from being reported as standing in the cup it contains) + if hb < -0.004 or hb > ci["height"] + 0.02 or sj["bottom"][2] < si["bottom"][2] + FLOOR_T / 2: + continue + if best is None or hb < best[1]: + best = (i, hb, d) + if best is None: + on_table = sj["bottom"][2] < envs.TABLE_Z + 0.01 and sj["tilt"] < 30 + rel.append(dict(cup=j, on=None, table=bool(on_table), tilt=sj["tilt"], xy=sj["p"][:2].tolist(), + fallen=bool(sj["tilt"] > 45))) + continue + i, hb, d = best + ci = inst["cups"][i] + seated = hb < SEAT_H and sj["tilt"] < SEAT_TILT + on_rim = hb > ci["height"] - FLOOR_T - 0.004 + rel.append(dict(cup=j, on=i, height=hb, seated=bool(seated), on_rim=bool(on_rim), tilt=sj["tilt"], + offset=d, xy=sj["p"][:2].tolist(), fallen=bool(sj["tilt"] > 45))) + return rel + + def outcome(self, inst): + envs.settle(self.env, 40) + cups = inst["cups"] + rel = self.relations(inst) + held = [j for j in range(3) if self.sk is not None and self.sk.holding(cups[j]["name"])] + col = [c["color"] for c in cups] + seated_in = {r["cup"]: r["on"] for r in rel if r.get("on") is not None and r["seated"]} + # success: a chain outer <- mid <- inner, all seated and upright, the outer cup standing on the table + success = False + for a, b, c in itertools.permutations(range(3)): + if seated_in.get(b) == a and seated_in.get(c) == b and _on_table_upright(rel, a): + success = True + success = bool(success and not held) + fb = dict(seated=[[j, i] for j, i in seated_in.items()], blocked=[], offcentre=[], held=held) + lines = [] + res = dict(success=success, relations=rel, feedback=fb) + if held: + lines.append(f"The {col[held[0]]} cup is still in the gripper.") + if success: + a = [j for j in range(3) if j not in seated_in][0] + b = [j for j, i in seated_in.items() if i == a][0] + c = [j for j, i in seated_in.items() if i == b][0] + res["detail"] = (f"All three cups are nested: the {col[c]} cup stands inside the {col[b]} cup, " + f"which stands inside the {col[a]} cup.") + res["failure"] = None + return res + # bottom-up description + st = {r["cup"]: self._cup_state(inst, r["cup"]) for r in rel} + for r in sorted(rel, key=lambda r: st[r["cup"]]["bottom"][2]): + j = r["cup"] + if j in held: + continue + if r.get("on") is None: + if r["fallen"]: + lines.append(f"The {col[j]} cup has fallen over.") + elif r["table"]: + lines.append(f"The {col[j]} cup is standing on the table, not in another cup.") + else: + lines.append(f"The {col[j]} cup is neither standing on the table nor inside another cup.") + continue + i = r["on"] + if r["seated"]: + lines.append(f"The {col[j]} cup is inside the {col[i]} cup, standing on its bottom.") + continue + # did not go in. The text says only what a camera shows (no sizes); the structured field keeps the + # nominal verdict for the scripted learner + tilt = f", tilted about {r['tilt']:.0f} degrees" if r["tilt"] >= 8 else "" + if r["on_rim"]: + lines.append(f"The {col[j]} cup is sitting on the rim of the {col[i]} cup, not inside it{tilt}.") + else: + lines.append(f"The {col[j]} cup is stuck in the opening of the {col[i]} cup, not down inside " + f"it{tilt}.") + over = cups[j]["rb"] - cups[i]["rb"] + if over > 0: + fb["blocked"].append([j, i, round(100 * r["height"], 1)]) + else: + fb["offcentre"].append([j, i, round(100 * r["height"], 1)]) + res["detail"] = " ".join(lines) if lines else "The cups are not nested." + res["failure"] = "blocked" if fb["blocked"] else ("offcentre" if fb["offcentre"] else + ("held" if held else "incomplete")) + return res + + # ------------------------------------------------------------ execution + def execute(self, inst, params): + """params: order = [outer, middle, inner] (indices into inst['cups']). Puts the middle cup into the outer + one; if it went in (judged from the scene, as an agent would see it), puts the inner cup into the middle + one. Optional (robustness checks): dxy = (dx, dy) release offset (m), drop (m), grasp_below (m), + carry_speed (m/s or None = as fast as the controller allows).""" + o, mid, inn = [int(v) for v in params["order"]] + ok = self._move_cup(inst, mid, o, params) + if ok: + self._move_cup(inst, inn, mid, params) + self.sk.move_to(list(PARK), yaw=0.0) + + def _move_cup(self, inst, j, i, params): + sk = self.sk + sj = self._cup_state(inst, j) + x, y = sj["p"][:2] + rim = sj["rim"][2] + sk.set_gripper(False, steps=5) + sk.move_to([x, y, Z_CARRY], yaw=0.0) + sk.move_to([x, y, rim + 0.06], tol=0.004) + sk.move_to([x, y, rim - params.get("grasp_below", GRASP_BELOW_RIM)], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([x, y, Z_CARRY], speed=params.get("carry_speed", 0.3)) + si = self._cup_state(inst, i) + dx, dy = params.get("dxy", (0.0, 0.0)) + tx, ty = si["p"][0] + dx, si["p"][1] + dy + drop = params.get("drop", DROP) + sk.move_to([tx, ty, Z_CARRY], tol=0.004) + off = self._cup_state(inst, j)["bottom"] - sk.eef_pos() + # approach above the highest rim there (the target cup may stand inside a taller one) + top = max(s["rim"][2] for s in (self._cup_state(inst, q) for q in range(3) if q != j) + if np.hypot(s["p"][0] - tx, s["p"][1] - ty) < 0.04) + sk.move_to([tx - off[0], ty - off[1], max(top, si["rim"][2]) + drop + 0.03 - off[2]], tol=0.003) + z_rel = si["rim"][2] + drop + if top > si["rim"][2] + 0.002: # the target stands inside a taller cup: let go above that rim + z_rel = max(z_rel, top + FINGER_CLEAR - (inst["cups"][j]["height"] + - params.get("grasp_below", GRASP_BELOW_RIM))) + tgt = self._servo_cup(inst, j, [tx, ty], z_rel) + sk.grip = -1.0 + self._hold_at(tgt, 12) + sk.move_to([tgt[0], tgt[1], Z_CARRY], speed=0.3) + envs.settle(self.env, 20) + r = [q for q in self.relations(inst) if q["cup"] == j][0] + return bool(r.get("on") == i and r["seated"]) + + def _hold_at(self, target, steps): + sk = self.sk + R = sk._R() + for _ in range(steps): + sk._act(np.asarray(target) - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip) + + def _servo_cup(self, inst, j, xy, z_bottom, max_steps=60, tol=0.0015): + """closed loop on the held cup's bottom centre (scripted policies only). Stops where the cup is held up + (a too-wide cup on / in another cup's rim) instead of pressing on: a person lets go there too, and + pressing on tips the cups over.""" + sk = self.sk + R = sk._R() + goal = np.array([xy[0], xy[1], z_bottom]) + tgt = e_prev = sk.eef_pos() + zs = [] + for k in range(max_steps): + b, e = self._cup_state(inst, j)["bottom"], sk.eef_pos() + if k >= 8 and np.linalg.norm(b - goal) < tol and np.linalg.norm(e - e_prev) < 0.0005: + break + zs.append(b[2]) + if k >= 12 and b[2] - goal[2] > 0.003 and zs[-6] - b[2] < 0.0005: + return e # blocked: release here + tgt = goal - (b - e) + sk._act(tgt - e, _rot_err(R, sk.eef_mat()), sk.grip) + e_prev = e + return tgt + + # ------------------------------------------------------------ scripted policies + def default_params(self, inst): + """prior: the bigger-looking cup goes outside, and the cups look big by their height: tallest outermost""" + return dict(order=list(inst["naive_order"])) + + def oracle_params(self, inst): + return dict(order=list(inst["order"])) + + def blind_params(self, inst, attempt, rng): + """no history: the same height judgement again, with a little noise""" + est = [c["height"] * (1 + rng.normal(0, H_NOISE)) for c in inst["cups"]] + return dict(order=[int(i) for i in np.argsort(est)[::-1]]) + + @staticmethod + def constraints(history): + """pairs (outer, inner) implied by the F2 feedback of earlier attempts""" + pairs = set() + for h in history: + fb = h["outcome"].get("feedback") or {} + for j, i in fb.get("seated", []): + pairs.add((int(i), int(j))) # j sits in i -> i is outside j + for j, i, _ in fb.get("blocked", []): + pairs.add((int(j), int(i))) # j does not fit into i -> j must be outside i + for j, i, _ in fb.get("offcentre", []): + pairs.add((int(i), int(j))) # j would fit into i + return pairs + + def adapt_params(self, inst, history): + """Scripted learner. It does not perceive the bottoms at all; it uses only which cup went into / stayed on + top of which (visible in the camera images; the structured part of the outcome): every such relation gives + an (outer, inner) pair; among the untried orders consistent with all pairs it takes the one closest (fewest + swapped pairs) to its prior, the height order; ties go to the larger height agreement.""" + pairs = self.constraints(history) + rims = [c["height"] for c in inst["cups"]] + prior = list(inst["naive_order"]) + tried = {tuple(h["params"]["order"]) for h in history if (h["outcome"].get("feedback") or {}).get("blocked")} + cands = [] + for order in itertools.permutations(range(3)): + pos = {c: k for k, c in enumerate(order)} + consistent = all(pos[a] < pos[b] for a, b in pairs) + agree = sum(rims[order[k]] - rims[order[k + 1]] for k in range(2)) + cands.append((consistent, tuple(order) not in tried, -kendall(order, prior), agree, order)) + best = max(cands) + return dict(order=list(best[4])) + + def random_order_params(self, inst, history, rng): + """sensitivity variant: a random order each retry, no history""" + return dict(order=[int(i) for i in rng.permutation(3)]) + + EXTRA_KINDS = ("random_order",) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + if kind not in self.EXTRA_KINDS: + return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt) + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + params = self.default_params(inst) if a == 0 else self.random_order_params(inst, history, rng) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"]: + break + return history + + +def _on_table_upright(rel, j): + r = [q for q in rel if q["cup"] == j][0] + return r.get("on") is None and r["table"] and r["tilt"] < 8.0 and not r["fallen"] + + +# ---------------------------------------------------------------- physical validity checks +def physics_check(seed0=1000, n=8, out=None): + """All 6 orders on each instance; expect success iff the order is the true one.""" + import json + task = NestOrder() + rows = [] + for seed in range(seed0, seed0 + n): + inst = task.sample_instance(seed) + for order in itertools.permutations(range(3)): + task.reset_instance(inst) + task.execute(inst, dict(order=list(order))) + o = task.outcome(inst) + expect = list(order) == inst["order"] + # for a cup that did not go in: how far (cm) its bottom is below the other cup's rim + below_rim = [round(100 * (inst["cups"][r["on"]]["height"] - FLOOR_T - r["height"]), 2) + for r in o["relations"] if r.get("on") is not None and not r["seated"]] + rows.append(dict(seed=seed, case=inst["case"], order=list(order), success=o["success"], expect=expect, + failure=o["failure"], detail=o["detail"], below_rim_cm=below_rim, + clear_mm=inst["clear_mm"], tol_mm=inst["tol_mm"], bottom_cm=inst["bottom_cm"], + opening_cm=inst["opening_cm"], height_cm=inst["height_cm"])) + print(f"seed {seed} order {order} succ={o['success']} expect={expect} | {o['detail']}" + + ("" if o["success"] == expect else " <-- MISMATCH"), flush=True) + if out: + with open(out, "w") as f: + json.dump(rows, f, indent=1) + print("total", len(rows), "mismatches", sum(r["success"] != r["expect"] for r in rows)) + return rows + + +def robustness_check(seed0=1000, n=6, out=None): + """True order with execution errors: release off-centre (both moves) by 0-9 mm in a random direction, released + 3 cm above the rim, grasped lower, carried at full controller speed.""" + import json + task = NestOrder() + rows = [] + cases = [("centred", {}), ("off3", dict(off=0.003)), ("off5", dict(off=0.005)), ("off7", dict(off=0.007)), + ("off9", dict(off=0.009)), ("drop3cm", dict(drop=0.03)), ("off4_drop3cm", dict(off=0.004, drop=0.03)), + ("grasp2cm", dict(grasp_below=0.02)), ("fast_carry", dict(carry_speed=None))] + for seed in range(seed0, seed0 + n): + inst = task.sample_instance(seed) + rng = np.random.default_rng(seed) + for name, c in cases: + a = rng.uniform(0, 2 * np.pi) + off = c.get("off", 0.0) + params = dict(order=list(inst["order"]), dxy=(off * np.cos(a), off * np.sin(a))) + params.update({k: v for k, v in c.items() if k != "off"}) + task.reset_instance(inst) + task.execute(inst, params) + o = task.outcome(inst) + rows.append(dict(seed=seed, case=name, success=o["success"], detail=o["detail"], tol_mm=inst["tol_mm"], + height_cm=inst["height_cm"])) + print(f"seed {seed} {name:13s} succ={o['success']} | {o['detail']}", flush=True) + if out: + with open(out, "w") as f: + json.dump(rows, f, indent=1) + for name, _ in cases: + r = [x["success"] for x in rows if x["case"] == name] + print(f"{name:13s} {sum(r)}/{len(r)}") + return rows + + +if __name__ == "__main__": + # python -m lffbench.tasks.l4_nest physics results/l4_nest_order/physics_check.json [n] + # python -m lffbench.tasks.l4_nest robust results/l4_nest_order/robustness_check.json [n] + import sys + n_arg = int(sys.argv[3]) if len(sys.argv) > 3 else None + if sys.argv[1] == "physics": + physics_check(out=sys.argv[2] if len(sys.argv) > 2 else None, n=n_arg or 8) + elif sys.argv[1] == "robust": + robustness_check(out=sys.argv[2] if len(sys.argv) > 2 else None, n=n_arg or 6) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l5_slippery_lift.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l5_slippery_lift.py new file mode 100644 index 0000000000000000000000000000000000000000..1a533e41595c29d413eb2287843cbc50afe7d0dc --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l5_slippery_lift.py @@ -0,0 +1,262 @@ +"""L5-B slippery_lift: pick up a heavy, slippery metal bar and hold it level. + +Category dynamics_adaptation (L5): "figure out how this object moves". + +Scene: one long steel-grey bar (4 x 28 x 4 cm, lying along the robot's left-right axis) on the table. It looks +perfectly uniform, but a heavy slug is hidden inside it at an unknown position, so its centre of mass sits +e = 2.5-7 cm from the bar's midpoint, towards the left or the right end. The bar is heavy (0.8-1.2 kg) and its +surface is slippery (finger friction 0.40-0.60): the two finger pads can hold its weight, but they cannot hold +much torque. + +Why the prior fails. The natural grasp is across the bar at its midpoint. With the centre of mass a few cm to +one side, gravity twists the bar in the pads as soon as it is lifted: the heavy end swings down and the bar +ends up hanging tilted by ~10-50 deg (measured). Slow lifting does not help (the torque is static). + +What has to be learned. Which end sank tells on which side of the grasp the centre of mass lies; the grasp +has to move towards that end until it is within ~1.5 cm of the hidden centre of mass (measured window). The +tilt magnitude saturates, so the distance has to be found by bracketing over a few attempts. + +Measured physics (2026-10-07, `l5dyn/bar_win.py`): mass 0.8-1.2 kg, mu 0.4-0.6, lift 15 cm at 0.15 m/s: +|grasp - COM| <= 1.0 cm -> tilt <= 2 deg; 1.5 cm -> 0-41 deg; >= 2 cm -> mostly 30-50 deg; the tilt does not +creep during a 3 s hold. mu 0.8 gave non-monotone tilts and is not used; mu 0.3 + 1.3 kg slips out entirely. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +BAR = "bar_1" +HALF = (0.02, 0.14, 0.02) # 4 (x) x 28 (y) x 4 (z) cm, long axis along world y +_SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"' +W_FRAC = 0.6 # fraction of the bar's mass in the hidden slug +W_HALF = 0.015 # slug half size (for its inertia) +E_MIN, E_MAX = 0.025, 0.070 # |COM offset| from the bar's midpoint (m) +LIFT_MIN = 0.10 # the bar's lowest point must be this high above the table +TILT_MAX = 8.0 # deg +Z_GRASP = envs.TABLE_Z + HALF[2] # gripper site at the bar's mid height (finger tips 0.7 cm above the table) +Z_LIFT = Z_GRASP + 0.15 +YAW_ACROSS = np.pi / 2 # jaws close along world x, i.e. across the bar + + +def weighted_box_xml(name, half, rgba, mass=1.0, friction=(1.0, 0.005, 0.0001)): + """Box with an explicit inertial. Its pos is off-centre at compile time so MuJoCo keeps + body_sameframe = 0 / body_simple = 0 and honours the per-instance body_ipos set in apply_instance.""" + I = [mass / 3 * (half[1] ** 2 + half[2] ** 2), mass / 3 * (half[0] ** 2 + half[2] ** 2), + mass / 3 * (half[0] ** 2 + half[1] ** 2)] + g = (f' \n' + f' \n' + f' ') + return _wrap(name, g, half[2], float(np.hypot(half[0], half[1]))) + + +def set_hidden_weight(env, obj, half, mass, w_frac, w_pos, w_half=W_HALF): + """Uniform shell of mass (1 - w_frac) * mass plus a hidden cube slug of w_frac * mass at w_pos (body frame). + Sets the body's mass, centre of mass and inertia; returns the centre of mass (body frame).""" + m = env.sim.model + bid = envs.body_id(env, obj) + ms, mw = (1 - w_frac) * mass, w_frac * mass + w_pos = np.asarray(w_pos, float) + c = mw * w_pos / mass + hx, hy, hz = half + + def par(mm, r): # parallel-axis terms (diagonal) + return mm * np.array([r[1] ** 2 + r[2] ** 2, r[0] ** 2 + r[2] ** 2, r[0] ** 2 + r[1] ** 2]) + + I = (ms / 3 * np.array([hy ** 2 + hz ** 2, hx ** 2 + hz ** 2, hx ** 2 + hy ** 2]) + par(ms, -c) + + mw / 6 * (2 * w_half) ** 2 * np.ones(3) + par(mw, w_pos - c)) + m.body_mass[bid] = mass + m.body_ipos[bid] = c + m.body_iquat[bid] = [1.0, 0.0, 0.0, 0.0] + m.body_inertia[bid] = I + envs.refit_bounds(env, bid) # the collision BVH lives in the inertial frame (envs.refit_bounds) + return c + + +def bar_axis(env): + """World direction of the bar's long axis (body y).""" + return env.sim.data.body_xmat[envs.body_id(env, BAR)].reshape(3, 3)[:, 1].copy() + + +def bar_tilt_deg(env): + """Signed tilt of the bar's long axis from horizontal; > 0: the bar's +y end is lower.""" + ax = bar_axis(env) + if ax[1] < 0: # orient the axis towards the robot's left so the sign is about world left/right + ax = -ax + return float(np.degrees(np.arcsin(np.clip(-ax[2], -1.0, 1.0)))) + + +def side_words(sign): + return "left (+y)" if sign > 0 else "right (-y)" + + +class BarSkills(Skills): + """Skills that record where along the bar the jaws closed, whoever drives them (scripted or agent).""" + + def __init__(self, env, bias=None, recorder=None): + super().__init__(env, bias=bias, recorder=recorder) + self.closes = [] + self.zmax = float(envs.obj_pos(env, BAR)[2]) + self.z0 = self.zmax + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.zmax = max(self.zmax, float(envs.obj_pos(self.env, BAR)[2])) + + def set_gripper(self, close, steps=15): + rep = super().set_gripper(close, steps) + if close: + c = envs.obj_pos(self.env, BAR) + ax = bar_axis(self.env) + if ax[1] < 0: + ax = -ax + along = float((self.eef_pos() - c) @ ax) # + : grasp on the left (+y) side of the midpoint + self.closes.append(dict(along=along, holding=self.holding(BAR), step=self.n_steps)) + return rep + + +@register_task +class SlipperyLift(LFFTask): + name = "l5_slippery_lift" + level = "L5" + category = "dynamics_adaptation" + capabilities = ("Perceive", "Reason", "Utilize") + protocol = "cross" + instruction = ("Pick up the metal bar and hold it level (tilted less than 8 degrees), with its lowest point at " + "least 10 cm above the table. Keep holding it when you finish.") + instruction_indirect = ("Pick up the long grey rod lying on the table and hold it horizontal (tilted less than 8 " + "degrees), with its lowest point at least 10 cm above the table. Keep holding it when you " + "finish.") + + # ------------------------------------------------------------ scene + def make_bddl(self): + bar = register_generated("LffSteelBar", weighted_box_xml("lff_steel_bar", HALF, (0.52, 0.55, 0.58, 1.0))) + objs = [(BAR, bar, "bar_region", (-0.11, -0.01, -0.09, 0.01))] + return write_bddl(self.name, "pick up the bar and hold it level", objs) # BDDL cannot parse parentheses + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + e = float(rng.choice([-1.0, 1.0]) * rng.uniform(E_MIN, E_MAX)) + return dict(seed=int(seed), + bar_xy=[float(rng.uniform(-0.12, -0.03)), float(rng.uniform(-0.06, 0.06))], + com_offset=e, # along the bar, + = towards the robot's left (+y) end + mass=float(rng.uniform(0.8, 1.2)), + mu=float(rng.uniform(0.40, 0.60))) + + def apply_instance(self, inst): + x, y = inst["bar_xy"] + envs.set_obj_pose(self.env, BAR, [x, y, envs.TABLE_Z + HALF[2] + 0.001]) + envs.set_friction(self.env, BAR, inst["mu"]) + set_hidden_weight(self.env, BAR, HALF, inst["mass"], W_FRAC, [0.0, inst["com_offset"] / W_FRAC, 0.0]) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.sk = BarSkills(self.env, bias=self.skill_bias(inst), recorder=recorder) + return self.sk + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + sk = self.sk + sk.hold(30) # 1.5 s with the gripper as the agent left it (envs.settle would open the jaws) + held = sk.holding(BAR) + tilt = bar_tilt_deg(self.env) + bottom = envs.obj_min_z(self.env, BAR) - envs.TABLE_Z + lifted = (sk.zmax - sk.z0) > 0.03 + close = next((c for c in reversed(sk.closes) if c["holding"]), sk.closes[-1] if sk.closes else None) + success = bool(held and abs(tilt) <= TILT_MAX and bottom >= LIFT_MIN) + out = dict(success=success, held=bool(held), tilt_deg=round(tilt, 1), bottom_cm=round(100 * bottom, 1), + grasp_along=None if close is None else round(close["along"], 4)) + g = "" + if close is not None and close["holding"]: + a = close["along"] + g = (f" You grasped the bar {100 * abs(a):.1f} cm to the {side_words(a)} of its midpoint." + if abs(a) >= 0.0005 else " You grasped the bar at its midpoint.") + tilt_txt = (f"hangs tilted by {abs(tilt):.0f} degrees, its {side_words(tilt).split()[0]} end lower than its " + f"{side_words(-tilt).split()[0]} end") + if success: + out["failure"] = None + detail = f"The bar is held level (tilt {abs(tilt):.0f} degrees), {100 * bottom:.0f} cm above the table." + g + elif held and abs(tilt) > TILT_MAX: + out["failure"] = "tilted" + detail = ("The bar did not stay level: it rotated in the gripper while it was being lifted and now " + f"{tilt_txt}." + g) + if bottom < LIFT_MIN: + detail += f" Its lowest point is {100 * bottom:.0f} cm above the table." + elif held: + out["failure"] = "too_low" + detail = (f"The bar is held level (tilt {abs(tilt):.0f} degrees) but its lowest point is only " + f"{100 * bottom:.0f} cm above the table." + g) + elif lifted: + out["failure"] = "dropped" + detail = ("The bar was lifted but slipped out of the gripper and fell back onto the table " + f"(it now lies tilted by {abs(tilt):.0f} degrees)." + g) + elif close is None: + out["failure"] = "no_grasp" + detail = "The gripper never closed on the bar; it is still lying on the table." + else: + out["failure"] = "no_grasp" + detail = "The gripper closed but did not catch the bar; it is still lying on the table." + out["detail"] = detail + out["detail_indirect"] = detail.replace("bar", "rod") + return out + + def feedback(self, inst, out, level="F2", indirect=False): + if indirect and level == "F2": + out = dict(out, detail=out.get("detail_indirect", out["detail"])) + return super().feedback(inst, out, level) + + # ------------------------------------------------------------ scripted execution (cross protocol) + def execute(self, inst, params): + """Grasp across the bar at `along` (m from the visible midpoint, + = left / +y) and lift 15 cm.""" + sk = self.sk + c = envs.obj_pos(self.env, BAR) # visible bar pose (perfect perception) + ax = bar_axis(self.env) + if ax[1] < 0: + ax = -ax + g = c + ax * float(params["along"]) + sk.set_gripper(False, steps=5) + sk.move_to([g[0], g[1], Z_GRASP + 0.10], yaw=YAW_ACROSS) + sk.move_to([g[0], g[1], Z_GRASP], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([g[0], g[1], Z_LIFT], speed=0.15, tol=0.004, max_steps=300) + + def default_params(self, inst): + return dict(along=0.0) + + def oracle_params(self, inst): + return dict(along=float(inst["com_offset"])) + + MARGIN = 0.008 # a tilt towards +y at grasp g means COM > g + MARGIN (window is ~+-1.5 cm) + STEP = 0.030 # first step towards the heavy end when only one side is bounded + + def adapt_params(self, inst, history): + """Bracketing on the grasp point: the end that sank is the heavy side of the last grasp.""" + lo, hi = -HALF[1], HALF[1] + lo_set = hi_set = False + for h in history: + o = h["outcome"] + g = o["grasp_along"] if o.get("grasp_along") is not None else h["params"]["along"] + if o.get("failure") == "tilted" or (o.get("failure") == "dropped" and abs(o["tilt_deg"]) > 3): + if o["tilt_deg"] > 0: # left end sank -> COM left of the grasp + lo, lo_set = max(lo, g + self.MARGIN), True + else: + hi, hi_set = min(hi, g - self.MARGIN), True + last = history[-1]["params"]["along"] + if lo_set and hi_set: + a = 0.5 * (lo + hi) + elif lo_set: + a = lo + self.STEP - self.MARGIN + elif hi_set: + a = hi - self.STEP + self.MARGIN + else: # no direction information (e.g. too low): repeat + a = last + return dict(along=float(np.clip(a, -0.12, 0.12))) + + def blind_params(self, inst, attempt, rng): + return dict(along=float(rng.normal(0.0, 0.01))) diff --git a/leaf/release/source_packages/supp-20261113-g61_evosub_3_20261026/lff/batches.json b/leaf/release/source_packages/supp-20261113-g61_evosub_3_20261026/lff/batches.json new file mode 100644 index 0000000000000000000000000000000000000000..7b7ae4b46f7c210cc034f1bfd5930207430ccdc8 --- /dev/null +++ b/leaf/release/source_packages/supp-20261113-g61_evosub_3_20261026/lff/batches.json @@ -0,0 +1,9 @@ +{ + "g61_evosub_3_20261026": { + "source_manifest": "/mnt/cpfs/workspace/agentic-robotics/ops/lerobot_supp_20261113/source/runs/api/g61_evosub_3_20261026/manifest.json", + "supplement": true, + "selected_runs": 1, + "exported_runs": 1, + "note": "Original condition and feedback dossier are in each episode annotation source.evaluation_config." + } +} diff --git a/leaf/release/source_packages/supp-20261113-g61_evosub_3_20261026/lff/rejected.json b/leaf/release/source_packages/supp-20261113-g61_evosub_3_20261026/lff/rejected.json new file mode 100644 index 0000000000000000000000000000000000000000..0637a088a01e8ddab3bf3fa98dbe804cbde1a0dc --- /dev/null +++ b/leaf/release/source_packages/supp-20261113-g61_evosub_3_20261026/lff/rejected.json @@ -0,0 +1 @@ +[] \ No newline at end of file