TRACE-VLA code snapshot 2026-11-22 11:47 +07: 456 canonical files + SHA256 manifest + sync report
b4396f0 verified Download code/sera_v4/tools/build_oracle_demos.py from phammminhhieu/trace-vla-code: direct link, hf CLI and curl.
- Browser
- Download file 25.9 kB
-
https://huggingface.co/phammminhhieu/trace-vla-code/resolve/main/code/sera_v4/tools/build_oracle_demos.py
- Command line
-
hf download hf://phammminhhieu/trace-vla-code/code/sera_v4/tools/build_oracle_demos.py
-
curl -L -o build_oracle_demos.py https://huggingface.co/phammminhhieu/trace-vla-code/resolve/main/code/sera_v4/tools/build_oracle_demos.py
25.9 kB
| #!/usr/bin/env python3 | |
| """E1 variant F: scripted-oracle demos for the 6 LIBERO-Skill tasks (SPEC). | |
| Privileged sim state (body/joint positions) drives a Cartesian PD | |
| scripted controller. Every demo is VERIFIED by the BDDL goal | |
| predicate at termination (goal_atoms, same as rollout_skill_v4.py); | |
| only verified demos are kept. Demo init states are fresh BDDL-sampled | |
| resets (init_state_id >= 10); the 10 test init states (0..9) are | |
| NEVER used as demos (preregistration rule). | |
| Demo format (npz, one file per demo): images [T,2,256,256,3] uint8 | |
| @10 Hz, states [T,8] raw ([ee_pos(3), euler_xyz(3), gripper_qpos(2)] | |
| — the dataset layout, verified against parquet), actions [T,7] raw, | |
| instruction str. SOURCE (scripted oracle) is declared in all reports. | |
| Sub-skills (from the BDDL goal_state, executed in order): | |
| Open/Close <cabinet>_<level>_region -> drawer pull/push. The | |
| cabinet is rotated 180 deg about Z (world slide axis (0,-1,0)); | |
| OPEN = pull the handle bar +Y in world (qpos ~ -0.13..-0.16), | |
| CLOSE = push -Y (qpos ~ 0.0). The handle bar is located by its | |
| geom_xpos (0.008x0.008x0.044 box on the drawer body), never by | |
| body_pos + an assumed body-frame offset. | |
| On <obj> <surface> -> pick obj, place on surface | |
| Open/Close microwave_1 -> door pull/push (hinge [0,0,1]; | |
| open qpos ~ -1.7, closed ~ 0.0) | |
| Turnoff flat_stove_1 -> grasp knob, rotate wrist until the | |
| Turnoff atom verifies (button hinge [0,0,1]). | |
| Action convention (verified): 7-dim OSC deltas [dx,dy,dz,droll, | |
| dpitch,dyaw,gripper]; gripper +1 = close, -1 = open; position gain | |
| ~0.008 m per unit action per step (calibrated 2026-11-18). | |
| """ | |
| import argparse | |
| import json | |
| import sys | |
| import time | |
| from pathlib import Path | |
| import numpy as np | |
| sys.path.insert(0, str(Path.home() / "sera_v4_experiments" / "tools")) | |
| import rollout_skill_v4 as rs | |
| HOME = Path.home() | |
| EXP = HOME / "sera_v4_experiments" | |
| DEMO_DIR = EXP / "quest_probe" / "demos" | |
| TASKS = rs.TASKS # manifest order; (bddl stem, language) | |
| TASK_IDS = (1, 3, 4, 6, 7, 8) # audited unseen-composition set | |
| TEST_EPS = set(range(10)) # NEVER used as demo init states | |
| # NOTE (2026-11-18): the cabinet bodies are rotated 180 deg about Z | |
| # (base xmat = diag(-1,-1,1)), so body-frame offsets do NOT map to | |
| # world offsets by identity. The drawer handle is located by its | |
| # geom (drawer_handle_geom, size ~0.008x0.008x0.044) and the world | |
| # slide axis is (0,-1,0): opening (qpos -> -0.15) moves the handle | |
| # +Y in world. A body_pos + relpos handle was WRONG by ~0.20 m in Y | |
| # and pulled the wrong way — the cause of dry runs 1-7 failing. | |
| def resize256(img): | |
| from PIL import Image | |
| return np.asarray(Image.fromarray(img).resize((256, 256), | |
| Image.BILINEAR)) | |
| def state8(eef_pos, eef_quat, grip_qpos): | |
| from scipy.spatial.transform import Rotation | |
| eul = Rotation.from_quat(np.asarray(eef_quat).reshape(-1)[:4]).as_euler("xyz") | |
| return np.concatenate([np.asarray(eef_pos).reshape(-1)[:3], eul, | |
| np.asarray(grip_qpos).reshape(-1)[:2]]).astype(np.float32) | |
| class DemoRunner: | |
| """One env + scripted controller; records (images, states, actions).""" | |
| def __init__(self, tid, init_id, verbose=False): | |
| from lerobot.envs import make_env | |
| from lerobot.envs.configs import LiberoEnv as LiberoEnvConfig | |
| self.tid = tid | |
| self.verbose = verbose | |
| ecfg = LiberoEnvConfig(task=rs.SUITE, task_ids=[tid]) | |
| envs = make_env(ecfg, n_envs=1, use_async_envs=False) | |
| self.vec = envs[rs.SUITE][tid] | |
| self.sub = self.vec.envs[0] | |
| self.sub.init_state_id = init_id | |
| self.sub._reset_stride = 0 | |
| self.obs, _ = self.vec.reset(seed=0) | |
| self.raw = self.sub._env.env | |
| self.images, self.states, self.actions = [], [], [] | |
| self.log(f"reset tid={tid} init={init_id} " | |
| f"goal={self.raw.parsed_problem['goal_state']}") | |
| def sim(self): | |
| # Fresh access: the env recreates the sim on auto-reset past the | |
| # horizon, and a cached MjSim loses its .data (AttributeError | |
| # seen 2026-11-18 in place_on after ~500 steps). | |
| return self.raw.sim | |
| def log(self, *a): | |
| if self.verbose: | |
| print("[DEMO]", *a, flush=True) | |
| def close(self): | |
| try: | |
| self.vec.close() | |
| except Exception: | |
| pass | |
| # ---- sim access (privileged state) ---- | |
| def body_id(self, name): | |
| names = list(self.sim.model.body_names) | |
| hits = [i for i, b in enumerate(names) if b == name or b.startswith(name)] | |
| assert hits, f"body not found: {name}" | |
| return hits[0] | |
| def body_pos(self, name): | |
| return np.asarray(self.sim.data.body_xpos[self.body_id(name)]).copy() | |
| def joint_qpos(self, name): | |
| j = self.sim.model.joint_name2id(name) | |
| return float(self.sim.data.qpos[self.sim.model.jnt_qposadr[j]]) | |
| def joint_axis(self, name): | |
| j = self.sim.model.joint_name2id(name) | |
| return np.asarray(self.sim.model.jnt_axis[j]).copy() | |
| def eef_pos(self): | |
| return np.asarray(self.obs["robot_state"]["eef"]["pos"]).reshape(-1)[:3].copy() | |
| # ---- recording + stepping ---- | |
| def _record(self, action): | |
| pix = self.obs["pixels"] | |
| img1 = resize256(np.asarray(pix["image"])[0]) | |
| img2 = resize256(np.asarray(pix["image2"])[0]) | |
| self.images.append(np.stack([img1, img2])) | |
| rs_ = self.obs["robot_state"] | |
| self.states.append(state8(rs_["eef"]["pos"], rs_["eef"]["quat"], | |
| rs_["gripper"]["qpos"])) | |
| self.actions.append(np.asarray(action, dtype=np.float32).copy()) | |
| def step(self, action): | |
| """Issue one action (7,), record (obs, action), advance.""" | |
| action = np.asarray(action, dtype=np.float64).reshape(7) | |
| self._record(action) | |
| self.obs, _, _, _, _ = self.vec.step(action[None, :]) | |
| return self.obs | |
| def hold(self, gripper, n=12): | |
| for _ in range(n): | |
| a = np.zeros(7) | |
| a[6] = gripper | |
| self.step(a) | |
| def move_to(self, target, gripper=0.0, tol=0.02, max_steps=200, | |
| k=4.0, amax=0.7): | |
| """Closed-loop Cartesian move; returns (reached, steps). | |
| tol=0.02: the PD creeps the last ~1 cm very slowly (action | |
| shrinks with the error), so a tight tolerance burns hundreds | |
| of steps for nothing; the primitives tolerate 2 cm. k=8 / | |
| amax=1.0 destabilised the OSC controller (dry run 4, EE went | |
| wild); k=4 / amax=0.7 is stable. | |
| """ | |
| target = np.asarray(target, dtype=np.float64).reshape(3) | |
| """Closed-loop Cartesian move; returns (reached, steps).""" | |
| target = np.asarray(target, dtype=np.float64).reshape(3) | |
| for i in range(max_steps): | |
| err = target - self.eef_pos() | |
| if np.linalg.norm(err) < tol: | |
| return True, i | |
| a = np.zeros(7) | |
| a[:3] = np.clip(k * err, -amax, amax) | |
| # Action floor: the PD creeps as the error shrinks, so keep | |
| # a minimum drive until inside tolerance (fixes the slow-Z | |
| # tail that burned the step budget in dry runs 3-5). | |
| for j in range(3): | |
| if abs(err[j]) > tol and abs(a[j]) < 0.3: | |
| a[j] = 0.3 * np.sign(err[j]) | |
| a[6] = gripper | |
| self.step(a) | |
| self.log(f"move_to timeout target={np.round(target, 3)} " | |
| f"eef={np.round(self.eef_pos(), 3)}") | |
| return False, max_steps | |
| def eef_euler(self): | |
| from scipy.spatial.transform import Rotation | |
| q = np.asarray(self.obs["robot_state"]["eef"]["quat"]).reshape(-1)[:4] | |
| return Rotation.from_quat(q).as_euler("xyz") | |
| def rotate_yaw(self, delta, rate=0.15, max_steps=100, gripper=-1.0): | |
| """Rotate the gripper about world Z by delta radians. | |
| Adaptive: reads the EE euler and stops when the yaw has moved | |
| by delta (sign probed live, so the action-frame convention | |
| does not matter). Holds the EE position while rotating. | |
| """ | |
| y0 = self.eef_euler()[2] | |
| p0 = self.eef_pos() | |
| sign = 1.0 if delta >= 0 else -1.0 | |
| for _ in range(5): | |
| a = np.zeros(7) | |
| a[5] = sign * rate | |
| a[6] = gripper | |
| a[:3] = np.clip(8.0 * (p0 - self.eef_pos()), -1.0, 1.0) | |
| self.step(a) | |
| y1 = self.eef_euler()[2] | |
| moved = (y1 - y0 + np.pi) % (2 * np.pi) - np.pi | |
| if moved * delta < 0: | |
| sign = -sign | |
| for _ in range(max_steps): | |
| y = self.eef_euler()[2] | |
| total = (y - y0 + np.pi) % (2 * np.pi) - np.pi | |
| if total * delta > 0 and abs(total) >= abs(delta) - 0.05: | |
| break | |
| if total * delta < 0 and abs(total) > 0.2: | |
| sign = -sign | |
| a = np.zeros(7) | |
| a[5] = sign * rate | |
| a[6] = gripper | |
| a[:3] = np.clip(8.0 * (p0 - self.eef_pos()), -1.0, 1.0) | |
| self.step(a) | |
| yf = self.eef_euler()[2] | |
| total = (yf - y0 + np.pi) % (2 * np.pi) - np.pi | |
| self.log(f"rotate_yaw delta={delta:.2f} achieved={total:.2f}") | |
| return total | |
| # ---- primitives ---- | |
| def pick(self, obj_body): | |
| p = self.body_pos(obj_body) | |
| self.log(f"pick {obj_body} at {np.round(p, 3)}") | |
| hi = np.array([p[0], p[1], max(self.eef_pos()[2], p[2] + 0.30)]) | |
| self.move_to(hi, gripper=-1.0) | |
| self.move_to(p + np.array([0, 0, 0.15]), gripper=-1.0) | |
| self.move_to(p + np.array([0, 0, 0.015]), gripper=-1.0) | |
| self.hold(1.0, 15) | |
| gq = np.asarray(self.obs["robot_state"]["gripper"]["qpos"]).reshape(-1) | |
| p2 = self.body_pos(obj_body) | |
| self.log(f"pick grasp gripper_qpos={np.round(gq, 4)} " | |
| f"obj_z={p2[2]:.3f} (was {p[2]:.3f})") | |
| self.move_to(p + np.array([0, 0, 0.15]), gripper=1.0) | |
| p3 = self.body_pos(obj_body) | |
| self.log(f"pick lift obj={np.round(p3, 3)} eef={np.round(self.eef_pos(), 3)}") | |
| return True | |
| def place_on(self, surface_body, release_h=0.06): | |
| p = self.body_pos(surface_body) | |
| self.log(f"place_on {surface_body} at {np.round(p, 3)}") | |
| hi = np.array([p[0], p[1], max(self.eef_pos()[2], p[2] + 0.30)]) | |
| self.move_to(hi, gripper=1.0) | |
| self.move_to(p + np.array([0, 0, 0.15]), gripper=1.0) | |
| self.move_to(p + np.array([0, 0, release_h]), gripper=1.0) | |
| self.hold(-1.0, 15) | |
| self.move_to(p + np.array([0, 0, 0.15]), gripper=-1.0) | |
| return True | |
| def drawer_body(self, prefix, level): | |
| # drawer front body, e.g. wooden_cabinet_1_cabinet_top | |
| return f"{prefix}_cabinet_{level}" | |
| def geom_pos(self, name): | |
| gi = self.sim.model.geom_name2id(name) | |
| return np.asarray(self.sim.data.geom_xpos[gi]).copy() | |
| def drawer_handle_geom(self, prefix, level): | |
| """Name of the handle-bar geom on the drawer body. | |
| The handle is the vertical box ~0.008 x 0.008 x 0.044 on the | |
| drawer body. Found by size (model-independent), NOT by a | |
| hardcoded geom index. Its geom_xpos is the true world | |
| position — body-frame offsets are WRONG here because the | |
| cabinet bodies are rotated 180 deg about Z (base xmat = | |
| diag(-1,-1,1), probe 2026-11-18). | |
| """ | |
| body = self.drawer_body(prefix, level) | |
| bi = self.sim.model.body_name2id(body) | |
| for gi in range(self.sim.model.ngeom): | |
| if self.sim.model.geom_bodyid[gi] != bi: | |
| continue | |
| sz = np.asarray(self.sim.model.geom_size[gi]) | |
| if np.allclose(sz, [0.008, 0.008, 0.044], atol=0.002): | |
| return self.sim.model.geom_id2name(gi) | |
| raise RuntimeError(f"handle geom not found on {body}") | |
| def _geom_aabb(self, gi): | |
| """World-frame AABB (lo, hi) of a geom, from xmat + size.""" | |
| pos = np.asarray(self.sim.data.geom_xpos[gi]).copy() | |
| R = np.asarray(self.sim.data.geom_xmat[gi]).reshape(3, 3) | |
| wh = np.abs(R) @ np.asarray(self.sim.model.geom_size[gi]) | |
| return pos - wh, pos + wh | |
| def _slide_open_dir(self, prefix, level): | |
| """World unit vector the handle moves along when the drawer | |
| OPENS (qpos -> negative), measured by perturbing the joint | |
| qpos +-0.05 and forward-kinematics (state restored after). | |
| Per-cabinet: the white cabinet faces the opposite way from | |
| the wooden one (task-3 dry run: pushing -Y opened it).""" | |
| jname = f"{prefix}_{level}_level" | |
| j = self.sim.model.joint_name2id(jname) | |
| adr = self.sim.model.jnt_qposadr[j] | |
| hg = self.drawer_handle_geom(prefix, level) | |
| q0 = float(self.sim.data.qpos[adr]) | |
| p0 = self.geom_pos(hg) | |
| dq = -0.05 if q0 > -0.08 else 0.05 | |
| self.sim.data.qpos[adr] = q0 + dq | |
| self.sim.forward() | |
| p1 = self.geom_pos(hg) | |
| self.sim.data.qpos[adr] = q0 | |
| self.sim.forward() | |
| d = p1 - p0 | |
| if dq > 0: | |
| d = -d # perturbed toward closed; opening is the reverse | |
| n = np.linalg.norm(d) | |
| assert n > 1e-4, f"slide probe: no handle motion for {jname}" | |
| return d / n | |
| def _front_plate(self, prefix, level): | |
| """AABB of the drawer front's tall collision plate nearest | |
| the handle (g11-class: contype=1, z-span > 0.15). The plate | |
| TOP EDGE is the grip target for the plate-top grip.""" | |
| body = self.drawer_body(prefix, level) | |
| bi = self.sim.model.body_name2id(body) | |
| hp = self.geom_pos(self.drawer_handle_geom(prefix, level)) | |
| best, best_d = None, 1e9 | |
| for gi in range(self.sim.model.ngeom): | |
| if self.sim.model.geom_bodyid[gi] != bi: | |
| continue | |
| if self.sim.model.geom_contype[gi] != 1: | |
| continue | |
| lo, hi = self._geom_aabb(gi) | |
| if hi[2] - lo[2] < 0.15: | |
| continue | |
| c = (lo + hi) / 2 | |
| d = float(np.linalg.norm(c - hp)) | |
| if d < best_d: | |
| best, best_d = (lo, hi), d | |
| assert best is not None, f"no front plate found on {body}" | |
| return best | |
| def _grip_drawer_front(self, prefix, level): | |
| """Yaw 90 deg (fingers separate in X), descend onto the | |
| drawer front plates' top edge, close the pads onto the | |
| plates' x-faces. Returns (grip_point, open_dir) or None. | |
| Why: the handle bar itself is ungrippable (see WORKLOG — | |
| 0.014 gap behind the bar vs 0.028 finger thickness; bar | |
| longer than the open finger span in X; cabinet plate g9 | |
| blocks the back finger's descend). The front plates' top | |
| edge (z ~ handle_z + 0.107) is clear of g9 (z <= 1.128) | |
| and the yawed fingers descend beside the plates in X. | |
| Pad-travel balance: pads sit at EE_x +0.036 / -0.044 when | |
| open, so EE_x = plate_centre_x + 0.004 equalises the two | |
| travels (~0.036 each) onto the plates' x-faces. | |
| """ | |
| lo, hi = self._front_plate(prefix, level) | |
| open_dir = self._slide_open_dir(prefix, level) | |
| grip = np.array([(lo[0] + hi[0]) / 2 + 0.004, | |
| (lo[1] + hi[1]) / 2, | |
| hi[2] - 0.008]) | |
| self.log(f"drawer front plate x[{lo[0]:.3f},{hi[0]:.3f}] " | |
| f"y[{lo[1]:.3f},{hi[1]:.3f}] z[{lo[2]:.3f},{hi[2]:.3f}] " | |
| f"grip={np.round(grip, 3)} open_dir={np.round(open_dir, 3)}") | |
| self.move_to(grip + np.array([0, 0, 0.14]), gripper=-1.0) | |
| self.rotate_yaw(np.pi / 2) | |
| reached, _ = self.move_to(grip, gripper=-1.0, tol=0.005) | |
| if not reached and np.linalg.norm(self.eef_pos() - grip) > 0.08: | |
| self.log("drawer grip: too far from the plates, aborting") | |
| self.rotate_yaw(-np.pi / 2) | |
| return None | |
| self.hold(1.0, 15) | |
| gq = np.asarray(self.obs["robot_state"]["gripper"]["qpos"]).reshape(-1) | |
| self.log(f"drawer grip gripper_qpos={np.round(gq, 4)} " | |
| f"eef={np.round(self.eef_pos(), 3)}") | |
| return grip, open_dir | |
| def _release_drawer(self, grip): | |
| self.hold(-1.0, 10) | |
| self.move_to(grip + np.array([0, 0, 0.12]), gripper=-1.0) | |
| self.rotate_yaw(-np.pi / 2) | |
| def open_drawer(self, prefix, level): | |
| jname = f"{prefix}_{level}_level" | |
| self.log(f"open_drawer {prefix} {level} " | |
| f"qpos0={self.joint_qpos(jname):.3f}") | |
| got = self._grip_drawer_front(prefix, level) | |
| if got is None: | |
| return False | |
| grip, open_dir = got | |
| for _ in range(200): | |
| a = np.zeros(7) | |
| a[:3] = open_dir * 0.3 | |
| a[6] = 1.0 | |
| self.step(a) | |
| if self.joint_qpos(jname) < -0.13: | |
| break | |
| q = self.joint_qpos(jname) | |
| self.log(f"open_drawer done qpos={q:.3f}") | |
| self._release_drawer(grip) | |
| return q < -0.10 | |
| def close_drawer(self, prefix, level): | |
| jname = f"{prefix}_{level}_level" | |
| self.log(f"close_drawer {prefix} {level} " | |
| f"qpos0={self.joint_qpos(jname):.3f}") | |
| got = self._grip_drawer_front(prefix, level) | |
| if got is None: | |
| return False | |
| grip, open_dir = got | |
| for _ in range(200): | |
| a = np.zeros(7) | |
| a[:3] = -open_dir * 0.3 | |
| a[6] = 1.0 | |
| self.step(a) | |
| if self.joint_qpos(jname) > -0.02: | |
| break | |
| q = self.joint_qpos(jname) | |
| self.log(f"close_drawer done qpos={q:.3f}") | |
| self._release_drawer(grip) | |
| return q > -0.05 | |
| def microwave_edge(self): | |
| """Current free-edge grasp point of the microwave door.""" | |
| root = self.body_pos("microwave_1_microdoorroot") | |
| # door panel extends ~+0.32 in +X from the hinge root when closed; | |
| # rotate the offset by the current hinge angle about Z. | |
| q = self.joint_qpos("microwave_1_microjoint") | |
| off = np.array([0.30, 0.0, 0.0]) | |
| c, s = np.cos(q), np.sin(q) | |
| rot = np.array([c * off[0] - s * off[1], s * off[0] + c * off[1], 0.0]) | |
| edge = root + rot | |
| return edge + np.array([0, -0.05, 0.0]), edge | |
| def open_microwave(self): | |
| jname = "microwave_1_microjoint" | |
| grasp, _ = self.microwave_edge() | |
| self.log(f"open_microwave grasp={np.round(grasp, 3)} " | |
| f"qpos0={self.joint_qpos(jname):.3f}") | |
| self.move_to(grasp + np.array([0, 0, 0.10]), gripper=-1.0) | |
| self.move_to(grasp, gripper=-1.0) | |
| self.hold(1.0, 15) | |
| for _ in range(200): | |
| grasp, _ = self.microwave_edge() | |
| # pull the edge toward -Y (door swings open about Z) | |
| target = grasp + np.array([0, -0.08, 0]) | |
| err = target - self.eef_pos() | |
| a = np.zeros(7) | |
| a[:3] = np.clip(2.5 * err, -0.3, 0.3) | |
| a[6] = 1.0 | |
| self.step(a) | |
| if self.joint_qpos(jname) < -1.5: | |
| break | |
| q = self.joint_qpos(jname) | |
| self.log(f"open_microwave done qpos={q:.3f}") | |
| return q < -1.2 | |
| def close_microwave(self): | |
| jname = "microwave_1_microjoint" | |
| self.log(f"close_microwave qpos0={self.joint_qpos(jname):.3f}") | |
| for _ in range(200): | |
| _, edge = self.microwave_edge() | |
| target = edge + np.array([0, 0.06, 0]) | |
| err = target - self.eef_pos() | |
| a = np.zeros(7) | |
| a[:3] = np.clip(2.5 * err, -0.3, 0.3) | |
| a[6] = 1.0 | |
| self.step(a) | |
| if self.joint_qpos(jname) > -0.05: | |
| break | |
| q = self.joint_qpos(jname) | |
| self.log(f"close_microwave done qpos={q:.3f}") | |
| return q > -0.15 | |
| def turn_off_stove(self): | |
| jname = "flat_stove_1_button" | |
| knob = self.body_pos("flat_stove_1_button") | |
| self.log(f"turn_off_stove knob={np.round(knob, 3)} " | |
| f"qpos0={self.joint_qpos(jname):.3f}") | |
| self.move_to(knob + np.array([0, 0, 0.10]), gripper=-1.0) | |
| self.move_to(knob + np.array([0, 0, 0.012]), gripper=-1.0) | |
| self.hold(1.0, 15) | |
| # rotate the wrist; sign found adaptively (qpos must decrease) | |
| sign = -1.0 | |
| q0 = self.joint_qpos(jname) | |
| for i in range(120): | |
| a = np.zeros(7) | |
| a[5] = sign * 0.12 # dyaw | |
| a[6] = 1.0 | |
| # hold position over the knob | |
| err = (knob + np.array([0, 0, 0.012])) - self.eef_pos() | |
| a[:3] = np.clip(2.5 * err, -0.2, 0.2) | |
| self.step(a) | |
| if i == 15: | |
| q1 = self.joint_qpos(jname) | |
| if q1 > q0 + 0.02: | |
| sign = 1.0 | |
| self.log("turn_off: flipped rotation sign") | |
| if self.joint_qpos(jname) < 0.05: | |
| break | |
| q = self.joint_qpos(jname) | |
| self.log(f"turn_off_stove done qpos={q:.3f}") | |
| self.hold(-1.0, 10) | |
| return q < 0.15 | |
| # ---- subgoal dispatch ---- | |
| def run_subgoal(self, atom): | |
| pred = atom[0] | |
| if pred in ("open", "close"): | |
| target = atom[1] | |
| if "microwave" in target: | |
| return self.open_microwave() if pred == "open" else self.close_microwave() | |
| # "<prefix>_<level>_region" -> drawer | |
| parts = target.replace("_region", "").rsplit("_", 1) | |
| prefix, level = parts[0], parts[1] | |
| return self.open_drawer(prefix, level) if pred == "open" else self.close_drawer(prefix, level) | |
| if pred == "on": | |
| obj, surface = atom[1], atom[2] | |
| self.pick(obj + "_main" if not obj.endswith("_main") else obj) | |
| return self.place_on(surface + "_main" if not surface.endswith("_main") else surface) | |
| if pred == "turnoff": | |
| return self.turn_off_stove() | |
| raise ValueError(f"unknown predicate {pred} in {atom}") | |
| def run_task(self): | |
| """Execute goal_state atoms in order; verify at the end.""" | |
| for atom in self.raw.parsed_problem["goal_state"]: | |
| self.log("subgoal", atom) | |
| ok = self.run_subgoal(atom) | |
| self.log("subgoal done", atom, "ok=", ok) | |
| atoms = rs.goal_atoms(self.sub) | |
| verified = all(a.get("true") for a in atoms) | |
| self.log("verify:", atoms, "VERIFIED" if verified else "FAILED") | |
| return verified, atoms | |
| def save(self, path, instruction): | |
| path = Path(path) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| np.savez_compressed( | |
| path, | |
| images=np.stack(self.images).astype(np.uint8), | |
| states=np.stack(self.states).astype(np.float32), | |
| actions=np.stack(self.actions).astype(np.float32), | |
| instruction=np.array(instruction), | |
| ) | |
| return len(self.images) | |
| def build(tid, n_demos=5, start_init=10, max_attempts=8, verbose=False, | |
| dry_run=False): | |
| stem, lang = TASKS[tid] | |
| out_dir = DEMO_DIR / stem | |
| made, attempts = 0, 0 | |
| init_id = start_init | |
| report = {"task_id": tid, "stem": stem, "demos": [], "attempts": 0} | |
| while made < n_demos and attempts < max_attempts: | |
| attempts += 1 | |
| init_id += 1 | |
| if (init_id - 1) in TEST_EPS: | |
| continue | |
| r = DemoRunner(tid, init_id - 1, verbose=verbose) | |
| try: | |
| verified, atoms = r.run_task() | |
| except Exception as e: | |
| import traceback | |
| traceback.print_exc() | |
| print(f"task {tid} init {init_id - 1}: ERROR {type(e).__name__}: {e}", flush=True) | |
| verified, atoms = False, [] | |
| finally: | |
| n_frames = len(r.images) | |
| if verified and n_frames > 500: | |
| # The env auto-resets past its ~520-step horizon; a demo | |
| # longer than that contains a reset and is invalid. | |
| print(f"task {tid} init {init_id - 1}: REJECTED " | |
| f"(too long: {n_frames} frames)", flush=True) | |
| verified = False | |
| if verified: | |
| p = out_dir / f"demo_{made:02d}.npz" | |
| r.save(p, lang) | |
| report["demos"].append({"file": str(p), "init_id": init_id - 1, | |
| "frames": n_frames}) | |
| print(f"task {tid} demo {made}: KEPT init={init_id - 1} " | |
| f"frames={n_frames} -> {p}", flush=True) | |
| made += 1 | |
| else: | |
| print(f"task {tid} init {init_id - 1}: REJECTED " | |
| f"(atoms={atoms})", flush=True) | |
| r.close() | |
| if dry_run: | |
| break | |
| report["attempts"] = attempts | |
| report["kept"] = made | |
| return report | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--tasks", default="1,3,4,6,7,8") | |
| ap.add_argument("--demos-per-task", type=int, default=5) | |
| ap.add_argument("--start-init", type=int, default=10) | |
| ap.add_argument("--max-attempts", type=int, default=8) | |
| ap.add_argument("--dry-run", action="store_true", | |
| help="one attempt per task, verbose, no keep requirement") | |
| ap.add_argument("--verbose", action="store_true") | |
| args = ap.parse_args() | |
| rs.install_assets_and_register() | |
| DEMO_DIR.mkdir(parents=True, exist_ok=True) | |
| all_reports = {} | |
| for tid in [int(x) for x in args.tasks.split(",") if x]: | |
| rep = build(tid, n_demos=args.demos_per_task, | |
| start_init=args.start_init, | |
| max_attempts=args.max_attempts, | |
| verbose=args.verbose or args.dry_run, | |
| dry_run=args.dry_run) | |
| all_reports[tid] = rep | |
| print("TASK_REPORT " + json.dumps(rep), flush=True) | |
| (DEMO_DIR / "build_report.json").write_text(json.dumps(all_reports, indent=2)) | |
| print("DEMOS_DONE", flush=True) | |
| if __name__ == "__main__": | |
| main() | |