diff --git a/tasks/glue-bead-bc2-2478/environment/world/assets/wrist_roll_follower_so101_gripper_v1.stl b/tasks/glue-bead-bc2-2478/environment/world/assets/wrist_roll_follower_so101_gripper_v1.stl new file mode 100644 index 0000000000000000000000000000000000000000..26c5e4ac019e573c6c53b69116720529fbd159d5 --- /dev/null +++ b/tasks/glue-bead-bc2-2478/environment/world/assets/wrist_roll_follower_so101_gripper_v1.stl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:65f32debcf265420c0160afe004f8befc5df4b3e578fd59ebaa62eade0371224 +size 741684 diff --git a/tasks/glue-bead-bc2-2478/environment/world/assets/wrist_roll_follower_so101_v1.stl b/tasks/glue-bead-bc2-2478/environment/world/assets/wrist_roll_follower_so101_v1.stl new file mode 100644 index 0000000000000000000000000000000000000000..9a5fa8fe2d7d8e59cd4a30d4dba0ca337513ab4a --- /dev/null +++ b/tasks/glue-bead-bc2-2478/environment/world/assets/wrist_roll_follower_so101_v1.stl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4b17b410a12d64ec39554abc3e8054d8a97384b2dc4a8d95a5ecb2a93670f5f4 +size 1439884 diff --git a/tasks/glue-bead-bc2-2478/environment/world/assets/wrist_roll_pitch_so101_v2.stl b/tasks/glue-bead-bc2-2478/environment/world/assets/wrist_roll_pitch_so101_v2.stl new file mode 100644 index 0000000000000000000000000000000000000000..2f531712f88ec01d09824ee8e27c791a4616516f --- /dev/null +++ b/tasks/glue-bead-bc2-2478/environment/world/assets/wrist_roll_pitch_so101_v2.stl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c7ec5525b4d8b9e397a30ab4bb0037156a5d5f38a4adf2c7d943d6c56eda5ae +size 2699784 diff --git a/tasks/glue-bead-bc2-2478/environment/world/benchcell/__init__.py b/tasks/glue-bead-bc2-2478/environment/world/benchcell/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/glue-bead-bc2-2478/environment/world/benchcell/cell.py b/tasks/glue-bead-bc2-2478/environment/world/benchcell/cell.py new file mode 100644 index 0000000000000000000000000000000000000000..109d787aa7dcedf676ee4c49ddcb14dc135a415d --- /dev/null +++ b/tasks/glue-bead-bc2-2478/environment/world/benchcell/cell.py @@ -0,0 +1,364 @@ +"""Bench cell BC-2 simulator (Reactive Labs, Apache 2.0). + +One SO-101 follower arm (MuJoCo Menagerie model, Apache 2.0) on a work table with a fixed overhead camera and a wrist +camera. The simulator is built from a *unit file*: a JSON dict of the as-built parameters of one physical unit +(servo zero offsets, servo gains and friction, command latency, arm mount pose, camera pose and field of view, +object masses and friction). Missing keys take the drawing values in NOMINAL. + +Conventions +- Joints, in order: shoulder_pan, shoulder_lift, elbow_flex, wrist_flex, wrist_roll, gripper. Radians. +- Reading frame: what the servo encoders report and what commands are written in, as on the real bus. + reading = true joint angle + joint_offset (then quantised to 4096 counts a turn, plus encoder noise). + A command c moves the servo towards true angle c - joint_offset. +- Control runs at 30 Hz (Cell.DT). A command written at step k takes effect at step k + latency_steps. +- World frame: origin on the table top below the drawing position of the arm base, +x forward, +y left, +z up. +""" +import copy +import json +import os + +import mujoco +import numpy as np + +HERE = os.path.dirname(os.path.abspath(__file__)) +SCENE = os.path.join(os.path.dirname(HERE), "scene.xml") +JOINTS = ["shoulder_pan", "shoulder_lift", "elbow_flex", "wrist_flex", "wrist_roll", "gripper"] +OBJECTS = ["cube_red", "cube_blue", "cube_green", "puck", "block"] +COUNTS = 4096 +TICK = 2 * np.pi / COUNTS + +NOMINAL = { + "unit": "drawing", + "joint_offset": [0.0] * 6, + "kp": [998.22] * 6, + "kv": [2.731] * 6, + "damping": [0.60] * 6, + "frictionloss": [0.052] * 6, + "armature": [0.028] * 6, + "force_limit": [2.94] * 6, + "latency_steps": 0, + "encoder_noise": 0.0, + "base": [0.0, 0.0, 0.0, 0.0], # x, y, z (m) and yaw (rad) of the arm mount + "overhead_cam": {"pos": [0.22, 0.0, 0.62], "rpy": [0.0, 0.0, 0.0], "fovy": 58.0, "k1": 0.0, "k2": 0.0}, + "table_friction": 0.6, + "cube_mass": 0.012, "cube_friction": 0.7, + "puck_mass": 0.020, "puck_friction": 0.3, + "block_mass": 0.030, "block_friction": 0.5, + "backlash": [0.0] * 6, # gear play per joint (rad, total width) + "latency_jitter": 0.0, # chance per tick that the bus delivers no new command + "table_tilt": [0.0, 0.0], # table top tilt about world x and y (rad) + "image_gain": 1.0, # overhead camera exposure (multiplies pixel values) + "image_noise": 0.0, # overhead camera pixel noise (std, 0-255 units) + "payload_mass": 0.0, # extra mass clamped in the jaws (kg), added to the jaw housing body + "tray": [0.20, 0.17, 0.0], # x, y, yaw + "pad": [0.30, -0.12], +} + +PARK = {"cube_red": (1.0, 0.0), "cube_blue": (1.0, 0.1), "cube_green": (1.0, 0.2), "puck": (1.0, 0.5), + "block": (1.0, 0.7)} +HALF_H = {"cube_red": 0.0125, "cube_blue": 0.0125, "cube_green": 0.0125, "puck": 0.006, "block": 0.015} +ARM_RGBA = np.array([0.93, 0.78, 0.12, 1.0]) +JAW_RGBA = np.array([0.18, 0.18, 0.20, 1.0]) + + +def load_unit(u): + """A unit dict from a path or dict, completed with NOMINAL values.""" + if isinstance(u, str): + with open(u) as f: + u = json.load(f) + out = copy.deepcopy(NOMINAL) + for k, v in (u or {}).items(): + if isinstance(v, dict) and isinstance(out.get(k), dict): + out[k].update(v) + else: + out[k] = v + return out + + +def _rpy_quat(r, p, y): + q = np.zeros(4) + mujoco.mju_euler2Quat(q, np.array([r, p, y], float), "xyz") + return q + + +def cam_quat(rpy): + """Overhead camera orientation: the drawing orientation (looking straight down, image up = +x) turned by + roll/pitch/yaw (rad) about the world x, y, z axes (applied in that order, extrinsic).""" + base = np.array([0.0, 0.0, 0.0, 0.0]) + # drawing: xyaxes="0 -1 0 1 0 0" + mat = np.array([[0, 1, 0], [-1, 0, 0], [0, 0, 1]], float) # columns: cam x, cam y, cam z in world + mujoco.mju_mat2Quat(base, mat.flatten()) + turn = np.zeros(4) + mujoco.mju_euler2Quat(turn, np.array(rpy, float), "XYZ") + q = np.zeros(4) + mujoco.mju_mulQuat(q, turn, base) + return q + + +_BASE_MODEL = None + + +def build_model(unit=None): + """Compile the scene and apply a unit's parameters. Returns (model, unit dict).""" + global _BASE_MODEL + unit = load_unit(unit) + if _BASE_MODEL is None: + _BASE_MODEL = mujoco.MjModel.from_xml_path(SCENE) + m = copy.deepcopy(_BASE_MODEL) + for i, j in enumerate(JOINTS): + jid = m.joint(j).id + dof = m.jnt_dofadr[jid] + a = m.actuator(j).id + kp, kv = float(unit["kp"][i]), float(unit["kv"][i]) + m.actuator_gainprm[a, 0] = kp + m.actuator_biasprm[a, 1] = -kp + m.actuator_biasprm[a, 2] = -kv + fl = float(unit["force_limit"][i]) + m.actuator_forcerange[a] = [-fl, fl] + m.dof_damping[dof] = float(unit["damping"][i]) + m.dof_frictionloss[dof] = float(unit["frictionloss"][i]) + m.dof_armature[dof] = float(unit["armature"][i]) + bx, by, bz, byaw = unit["base"] + b = m.body("base").id + m.body_pos[b] = [bx, by, bz] + m.body_quat[b] = _rpy_quat(0, 0, byaw) + c = m.camera("overhead").id + m.cam_pos[c] = unit["overhead_cam"]["pos"] + m.cam_quat[c] = cam_quat(unit["overhead_cam"]["rpy"]) + m.cam_fovy[c] = float(unit["overhead_cam"]["fovy"]) + rx, ry = unit.get("table_tilt", [0.0, 0.0]) + if rx or ry: + R = np.zeros(9) + mujoco.mju_quat2Mat(R, _rpy_quat(-rx, -ry, 0.0)) + m.opt.gravity[:] = R.reshape(3, 3) @ np.array([0.0, 0.0, -9.81]) + m.geom("table_top").friction[0] = float(unit["table_friction"]) + for name in ("cube_red", "cube_blue", "cube_green"): + m.body(name).mass[0] = float(unit["cube_mass"]) + m.geom(name).friction[0] = float(unit["cube_friction"]) + for name in ("puck", "block"): + m.body(name).mass[0] = float(unit[name + "_mass"]) + m.geom(name).friction[0] = float(unit[name + "_friction"]) + # inertia scaled with mass for the objects whose mass changed + for name in OBJECTS: + bid = m.body(name).id + m0 = _BASE_MODEL.body_mass[bid] + if m0 > 0: + m.body_inertia[bid] = _BASE_MODEL.body_inertia[bid] * (m.body_mass[bid] / m0) + if unit.get("payload_mass", 0.0): + g = m.body("moving_jaw_so101_v1").id + gb = m.body("gripper").id + m.body_mass[gb] += float(unit["payload_mass"]) + del g + tx, ty, tyaw = unit["tray"] + m.body_pos[m.body("tray").id] = [tx, ty, 0.0] + m.body_quat[m.body("tray").id] = _rpy_quat(0, 0, tyaw) + px, py = unit["pad"] + m.body_pos[m.body("pad").id] = [px, py, 0.0] + # the camera draws the arm from its collision shapes: colour them like the real arm + for g in range(m.ngeom): + if m.geom_group[g] == 3 and m.geom_bodyid[g] != 0: + jaw = m.geom_condim[g] == 6 + m.geom_rgba[g] = JAW_RGBA if jaw else ARM_RGBA + # masses, inertias and armature changed above: recompute the derived constants (invweight0 etc.) + mujoco.mj_setConst(m, mujoco.MjData(m)) + return m, unit + + +class Cell: + """One unit of the bench cell, stepped at 30 Hz. + + obs = cell.reset(layout) layout: {"objects": {name: [x, y, yaw(, z lift)]}, "fixtures": {name: [x, y, yaw]}, + "q0": [6 readings]}, all optional. Objects not named are parked off the table; + fixtures ("jig", "tray", "pad") not named keep their unit pose. + obs = cell.step(command) command: 6 joint targets in the reading frame (rad) + obs keys: "t" (s), "joints" (6 readings, rad), and one image per camera in `cameras` (H x W x 3 uint8). + cell.state() returns privileged simulator state (true joint angles, object poses); not available on a real unit. + """ + DT = 1.0 / 30.0 + + def __init__(self, unit=None, cameras=("overhead",), size=(96, 128), wrist_size=(72, 96), seed=0): + self.model, self.unit = build_model(unit) + self.data = mujoco.MjData(self.model) + self.nsub = int(round(self.DT / self.model.opt.timestep)) + self.cameras = tuple(cameras) + self.size, self.wrist_size = size, wrist_size + self._renderers = {} + self._maps = {} + self.rng = np.random.default_rng(seed) + self.offset = np.array(self.unit["joint_offset"], float) + self.lat = int(self.unit["latency_steps"]) + self.qadr = np.array([self.model.jnt_qposadr[self.model.joint(j).id] for j in JOINTS]) + self.vadr = np.array([self.model.jnt_dofadr[self.model.joint(j).id] for j in JOINTS]) + self.act = np.array([self.model.actuator(j).id for j in JOINTS]) + self._vopt = mujoco.MjvOption() + self._vopt.geomgroup[:] = [1, 1, 0, 1, 0, 0] + + # -- setup ------------------------------------------------------------------------------------------------- + def reset(self, layout=None, seed=None): + layout = layout or {} + if seed is not None: + self.rng = np.random.default_rng(seed) + m, d = self.model, self.data + mujoco.mj_resetData(m, d) + q0 = np.array(layout.get("q0", [0.0, -1.57, 1.57, 0.75, 1.57, 0.0]), float) # readings + qt = q0 - self.offset + d.qpos[self.qadr] = qt + d.ctrl[self.act] = qt + for name, pose in layout.get("fixtures", {}).items(): # static fixtures: "jig", "tray", "pad" + b = m.body(name).id + m.body_pos[b] = [pose[0], pose[1], pose[3] if len(pose) > 3 else 0.0] + m.body_quat[b] = _rpy_quat(0, 0, pose[2] if len(pose) > 2 else 0.0) + objs = layout.get("objects", {}) + for name in OBJECTS: + if name in objs: + x, y, yaw = objs[name][:3] + z = HALF_H[name] + (objs[name][3] if len(objs[name]) > 3 else 0.0) + else: + x, y = PARK[name] + yaw, z = 0.0, -0.75 + HALF_H[name] + self.set_object(name, x, y, z, yaw) + mujoco.mj_forward(m, d) + self.queue = [qt.copy() for _ in range(self.lat)] + self.bl = np.array(self.unit.get("backlash", [0.0] * 6), float) + self.jit = float(self.unit.get("latency_jitter", 0.0)) + self.out = qt.copy() # target after gear play + self.last = qt.copy() # last target delivered by the bus + self.t = 0.0 + self.k = 0 + # settle 0.2 s with the arm holding q0 + for _ in range(6): + self._advance(qt) + self.t, self.k = 0.0, 0 + return self.obs() + + def set_object(self, name, x, y, z, yaw=0.0): + j = self.model.joint(name).id + a = self.model.jnt_qposadr[j] + self.data.qpos[a:a + 3] = [x, y, z] + self.data.qpos[a + 3:a + 7] = _rpy_quat(0, 0, yaw) + v = self.model.jnt_dofadr[j] + self.data.qvel[v:v + 6] = 0.0 + + # -- stepping ---------------------------------------------------------------------------------------------- + def _advance(self, target_true): + lo = self.model.actuator_ctrlrange[self.act, 0] + hi = self.model.actuator_ctrlrange[self.act, 1] + self.data.ctrl[self.act] = np.clip(target_true, lo, hi) + for _ in range(self.nsub): + mujoco.mj_step(self.model, self.data) + + def step(self, command): + c = np.asarray(command, float).reshape(6) + if not np.all(np.isfinite(c)): + raise ValueError("command must be 6 finite numbers") + tgt = c - self.offset + if self.lat: + self.queue.append(tgt) + tgt = self.queue.pop(0) + if self.jit and self.rng.random() < self.jit: + tgt = self.last # the bus dropped this tick's command: the servos keep the last one + self.last = tgt + if np.any(self.bl): + h = self.bl / 2 + self.out = np.where(tgt - self.out > h, tgt - h, np.where(tgt - self.out < -h, tgt + h, self.out)) + tgt = self.out + self._advance(tgt) + self.k += 1 + self.t = self.k * self.DT + return self.obs() + + # -- sensing ----------------------------------------------------------------------------------------------- + def readings(self): + q = self.data.qpos[self.qadr] + self.offset + n = float(self.unit["encoder_noise"]) + if n > 0: + q = q + self.rng.normal(0.0, n, 6) + return np.round(q / TICK) * TICK + + def render(self, cam="overhead", size=None): + size = size or (self.wrist_size if cam == "wrist_cam" else self.size) + key = (cam, size) + r = self._renderers.get(key) + if r is None: + r = mujoco.Renderer(self.model, size[0], size[1]) + self._renderers[key] = r + r.update_scene(self.data, cam, scene_option=self._vopt) + img = r.render().copy() + return self._distort(img, lens=(cam == "overhead")) + + def _distort(self, img, lens=True): + """Camera effects of a unit: radial lens distortion (overhead camera only), exposure gain, pixel noise.""" + c = self.unit["overhead_cam"] + k1, k2 = (float(c.get("k1", 0.0)), float(c.get("k2", 0.0))) if lens else (0.0, 0.0) + g, n = float(self.unit.get("image_gain", 1.0)), float(self.unit.get("image_noise", 0.0)) + if k1 or k2: + H, W = img.shape[:2] + key = (H, W, k1, k2) + mp = self._maps.get(key) + if mp is None: + f = 0.5 * H / np.tan(np.radians(float(c["fovy"])) / 2) + v, u = np.mgrid[0:H, 0:W].astype(float) + xd, yd = (u + 0.5 - W / 2) / f, (v + 0.5 - H / 2) / f + xu, yu = xd.copy(), yd.copy() + for _ in range(20): # invert x_d = x_u (1 + k1 r^2 + k2 r^4) + r2 = xu * xu + yu * yu + s_ = 1 + k1 * r2 + k2 * r2 * r2 + xu, yu = xd / s_, yd / s_ + su = np.clip(xu * f + W / 2 - 0.5, 0, W - 1) + sv = np.clip(yu * f + H / 2 - 0.5, 0, H - 1) + mp = (su, sv) + self._maps[key] = mp + su, sv = mp + u0, v0 = np.floor(su).astype(int), np.floor(sv).astype(int) + u1, v1 = np.minimum(u0 + 1, W - 1), np.minimum(v0 + 1, H - 1) + a, b = (su - u0)[..., None], (sv - v0)[..., None] + im = img.astype(float) + img = ((1 - a) * (1 - b) * im[v0, u0] + a * (1 - b) * im[v0, u1] + (1 - a) * b * im[v1, u0] + + a * b * im[v1, u1]) + if g != 1.0 or n > 0: + img = img.astype(float) * g + if n > 0: + img = img + self.rng.normal(0.0, n, img.shape) + return np.clip(np.round(img), 0, 255).astype(np.uint8) if img.dtype != np.uint8 else img + + def render_depth(self, cam="overhead", size=None): + """Metric depth (m along the view axis) from a camera, H x W float32.""" + size = size or (self.wrist_size if cam == "wrist_cam" else self.size) + key = (cam, size, "depth") + r = self._renderers.get(key) + if r is None: + r = mujoco.Renderer(self.model, size[0], size[1]) + r.enable_depth_rendering() + self._renderers[key] = r + r.update_scene(self.data, cam, scene_option=self._vopt) + return r.render().astype(np.float32).copy() + + def obs(self): + o = {"t": self.t, "joints": self.readings()} + for cam in self.cameras: + o[cam] = self.render(cam) + return o + + # -- privileged -------------------------------------------------------------------------------------------- + def state(self): + d = self.data + out = {"t": self.t, "q": d.qpos[self.qadr].copy(), "qd": d.qvel[self.vadr].copy(), + "tip": d.site("gripperframe").xpos.copy(), "tip_mat": d.site("gripperframe").xmat.reshape(3, 3).copy()} + for name in OBJECTS: + j = self.model.joint(name).id + a = self.model.jnt_qposadr[j] + out[name] = d.qpos[a:a + 7].copy() + return out + + def close(self): + for r in self._renderers.values(): + try: + r.close() + except Exception: + pass + self._renderers = {} + + +def yaw_of(quat): + w, x, y, z = quat + return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))) diff --git a/tasks/glue-bead-bc2-2478/environment/world/benchcell/deploy.py b/tasks/glue-bead-bc2-2478/environment/world/benchcell/deploy.py new file mode 100644 index 0000000000000000000000000000000000000000..375350be80986c7b2e260586cea1210abbfaf675 --- /dev/null +++ b/tasks/glue-bead-bc2-2478/environment/world/benchcell/deploy.py @@ -0,0 +1,218 @@ +"""Runs a deployed policy in its own process, exactly as the acceptance run does (Reactive Labs, Apache 2.0). + +A policy is a directory holding policy.py, which defines + + class Policy: + def __init__(self, policy_dir: str): ... # load weights etc. (INIT_TIMEOUT, 120 s) + def reset(self, info: dict) -> None: ... # start of an episode (task info, e.g. the target colour) + def act(self, obs: dict) -> sequence of 6 floats # joint commands in the reading frame, 30 times a second + +The policy runs in a child process: as user nobody when started as root, in a fresh working directory, with one +thread for numpy and torch, and without the simulator. It sees only the deployment observation: "t", "joints" +(encoder readings) and the camera images the task names. Observations go to the child pickled; the child answers +with raw float64 bytes, so nothing from the policy is unpickled on this side. + +Time limits: the cell waits for each act() answer (simulated time does not run while the policy thinks, so a +slow grading host cannot change a result), but a call that takes longer than HARD_TIMEOUT s of wall time, raises, +or returns anything but 6 finite numbers ends the episode as a failure, and an episode whose act() calls take +more than EPISODE_POLICY_S s in total fails too. Policy.__init__ has INIT_TIMEOUT s. Plan for about 30 ms a call. +An acceptance run may also set a budget for the whole run (set_run_budget): the act() time of all its episodes +together. Once it is used up, the episode in progress and every later one fail. Each task states its budget. + +When started as root, PolicyProcess also makes the directory of the running grader script readable by root only, +so the policy process cannot read the acceptance run's files. +""" +import os +import pickle +import select +import shutil +import struct +import subprocess +import sys +import tempfile +import time + +import numpy as np + +HARD_TIMEOUT = 2.0 +EPISODE_POLICY_S = 60.0 +INIT_TIMEOUT = 120.0 +_RUN = {"budget": None, "spent": 0.0} + + +def set_run_budget(seconds): + """Total act() wall time allowed over all later run_episode calls in this process (None: no budget).""" + _RUN["budget"], _RUN["spent"] = (None if seconds is None else float(seconds)), 0.0 + + +def run_policy_s(): + """act() wall time used so far under the run budget.""" + return _RUN["spent"] + +RUNNER = r''' +import os, pickle, struct, sys, types +proto_in = os.fdopen(0, "rb", buffering=0) +proto_out = os.fdopen(os.dup(1), "wb", buffering=0) +os.dup2(2, 1) +def read_exact(n): + buf = b"" + while len(buf) < n: + chunk = proto_in.read(n - len(buf)) + if not chunk: + sys.exit(0) + buf += chunk + return buf +def send(kind, payload=b""): + proto_out.write(struct.pack("