"""The chess simulator as an RL environment for a chunked policy (SmolVLA): one step = one chunk. Scenes, rendering and the success judgement are those of eval_policy.py: episode (seed, i) is the same scene, move, camera look and policy noise seed as `eval_policy.py --seed seed`, episode i. Only the frames the policy sees are rendered (the first frame of each chunk); the images do not depend on the skipped renders in the baseline profile (no camera noise). Reward (per chunk, summed over its frames): +1.0 the move is complete when the episode ends (eval_policy's success: the piece within 6 mm of the target square, upright, no other piece moved more than 2 mm) +0.2 once, when the marked piece is first lifted cleanly (more than 8 mm, tilted under 20 deg) -0.5 another piece moved more than 2 mm (the move can no longer succeed; the episode ends) -0.3 the marked piece toppled (tilt over 45 deg; the episode ends) Episodes also end as in eval_policy (the move done and the arm back near rest) or at the time limit. With `early_stop=False` only eval_policy's endings apply, so an episode runs exactly as eval_policy.py runs it. VecChessEnv runs several environments in worker processes (rendering with EGL there); the policy stays in the main process and samples one batch per chunk boundary. """ from __future__ import annotations import multiprocessing as mp import sys from pathlib import Path HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) LIFT_M = 0.008 # as eval_policy.LIFT_M CLEAN_LIFT_TILT = 20.0 TOPPLED_TILT = 45.0 REWARD = dict(success=1.0, clean_lift=0.2, disturbed=-0.5, toppled=-0.3) class ChessEnv: def __init__(self, cfg: dict, seconds: float = 20.0, per_set: int = 5): import numpy as np from episode import EpisodeRunner from lerobot_export import video_settings from piece_sets import sample_piece_set assert cfg["piece_sets"].get("fixed"), "one runner per worker assumes a fixed piece set (baseline profile)" self.cfg, self.per_set = cfg, per_set self.crf, self.pix_fmt = video_settings(cfg) self.fps = cfg["dataset"]["fps"] self.max_frames = int(seconds * self.fps) self.runner = EpisodeRunner(cfg, sample_piece_set(np.random.default_rng(0), cfg, "rl"), render=True) self.site = self.runner.m.site("gripperframe").id self.home = np.array(cfg["expert"]["home"]) # ------------------------------------------------------------------ episode def reset(self, seed: int, index: int, check_expert: bool = True, early_stop: bool = True, measure: bool = True) -> tuple[dict, dict]: """Episode `index` of `seed`, as eval_policy.py builds it. Returns (observation, info); info["torch_seed"] is eval_policy's per-episode seed for the policy's sampling noise. `check_expert=False` skips eval_policy's check that the teacher can do the move (every move of the baseline profile is doable, so the same first episode seed is kept). `measure=False` skips planning the teacher's grasp, which only serves the closing-error measurement.""" import mujoco import numpy as np from lerobot_export import Recorder r = self.runner erng = np.random.default_rng([seed, index]) for _ in range(20 if check_expert else 1): ep_seed = int(erng.integers(2**62)) task = r.setup(np.random.default_rng(ep_seed)) if not check_expert or r.run(task, ep_seed).success: break task = r.setup(np.random.default_rng(ep_seed)) d, w, ex = r.d, r.w, r.expert # The teacher's planned grasp (not executed), as eval_policy measures the closing error against it. saved = (d.qpos.copy(), d.qvel.copy(), d.act.copy(), d.ctrl.copy(), d.time) self.plan = None if measure: try: self.plan = ex.plan_pick(d, task.target, np.random.default_rng(ep_seed)) except Exception: self.plan = None d.qpos[:], d.qvel[:], d.act[:], d.ctrl[:] = saved[:4] d.time = saved[4] mujoco.mj_forward(r.m, d) self.task, self.early_stop = task, early_stop self.rec = Recorder(self.cfg, None) self.rec.begin(r, task, np.random.default_rng(ep_seed ^ 0x5EED)) self.start = {p: w.base_pos(d, p) for p in w.pieces} self.watched = [p for p in task.squares.values() if p != task.target] self.src = w.square_center(task.source) self.f, self.placed_at, self.done = 0, None, False self.lifted, self.clean_lift, self.closest = False, False, np.inf self.close = None self.open_max = 0.0 torch_seed = int(erng.integers(2**31)) info = dict(seed=seed, index=index, ep_seed=ep_seed, torch_seed=torch_seed, piece=w.kind[task.target], source=task.source, destination=task.dest.square or "bin") return self.observe(), info def observe(self) -> dict: from camera_effects import training_look r = self.runner over, wrist = (training_look(self.rec.observe(r, c), self.crf, self.pix_fmt) for c in ("overhead", "wrist")) return {"observation.images.overhead": over, "observation.images.wrist": wrist, "observation.state": r.to_lerobot(r.d.qpos[r.qadr])} def step(self, chunk) -> tuple[dict | None, float, bool, dict]: """Execute an action chunk (n x 6, LeRobot units) frame by frame, as eval_policy's drive() does, until it ends or the episode does.""" import mujoco import numpy as np from eval_policy import CLOSING, OPEN r, task = self.runner, self.task d, w = r.d, r.w lo, hi = r.grip_range reward, events = 0.0, [] for a in np.asarray(chunk, dtype=np.float32): # float32 like eval_policy's actions: radians rounded the same way f = self.f d.ctrl[:5] = np.radians(a[:5]) d.ctrl[5] = lo + np.clip(a[5], 0, 100) / 100 * (hi - lo) for _ in range(r.n_sub): mujoco.mj_step(r.m, d) self.f += 1 g = d.site_xpos[self.site] self.closest = min(self.closest, float(np.linalg.norm(g[:2] - self.src[:2]))) rise = w.base_pos(d, task.target)[2] - self.start[task.target][2] tilt = w.tilt_deg(d, task.target) self.lifted |= bool(rise > LIFT_M) if not self.clean_lift and rise > LIFT_M and tilt < CLEAN_LIFT_TILT: self.clean_lift = True reward += REWARD["clean_lift"] events.append("clean_lift") if self.plan is not None and self.close is None: # eval_policy's closing measurement self.open_max = max(self.open_max, float(a[5])) if self.open_max > OPEN and a[5] < CLOSING: pnt, _ = r.expert.kin.pose(d.qpos[r.expert.kin.qadr].copy(), self.plan.offset) self.close = round(1000 * float(np.linalg.norm((pnt - self.plan.grasp_point)[:2])), 1) end = None if self.early_stop: moved = max((float(np.linalg.norm(w.base_pos(d, p) - self.start[p])) for p in self.watched), default=0.0) if moved * 1000 > self.cfg["validation"]["disturb_mm"]: reward += REWARD["disturbed"] end = "disturbed" elif tilt > TOPPLED_TILT: reward += REWARD["toppled"] end = "toppled" if end is None and f % 15 == 0 and f > 60: # eval_policy: done once placed and back near rest res = r._judge(task, self.start, self.watched, {}, self.f, 0.0) near_home = np.abs(d.qpos[r.expert.kin.qadr] - self.home).max() < 0.35 if res.success and self.placed_at is None: self.placed_at = f if self.placed_at is not None and near_home: end = "done" if end is None and self.f >= self.max_frames: end = "time" if end is not None: events.append(end) self.done = True break info = dict(events=events) if self.done: res = r._judge(task, self.start, self.watched, {}, self.f, 0.0) if res.success: reward += REWARD["success"] info.update(success=bool(res.success), reason=res.reason, frames=self.f, lifted=self.lifted, clean_lift=self.clean_lift, disturbed=bool(res.disturbed), closest_mm=round(1000 * self.closest, 1), close_lateral_mm=self.close, end=events[-1]) return None, reward, True, info return self.observe(), reward, False, info # ---------------------------------------------------------------------- worker processes def _worker(conn, cfg, seconds): import warnings warnings.filterwarnings("ignore") env = ChessEnv(cfg, seconds) while True: cmd, arg = conn.recv() if cmd == "reset": conn.send(env.reset(**arg)) elif cmd == "step": conn.send(env.step(arg)) elif cmd == "close": env.runner.close() conn.close() return class VecChessEnv: """n ChessEnv in worker processes. reset(i, ...) and step(i, chunk) are sent to worker i; step_many sends chunks to several workers and collects their results.""" def __init__(self, n: int, cfg: dict, seconds: float = 20.0): ctx = mp.get_context("spawn") self.conns, self.procs = [], [] for _ in range(n): a, b = ctx.Pipe() p = ctx.Process(target=_worker, args=(b, cfg, seconds), daemon=True) p.start() self.conns.append(a) self.procs.append(p) self.n = n def reset_many(self, jobs: dict) -> dict: """jobs: {worker: dict(seed=, index=, check_expert=, early_stop=)} -> {worker: (obs, info)}""" for i, arg in jobs.items(): self.conns[i].send(("reset", arg)) return {i: self.conns[i].recv() for i in jobs} def step_many(self, chunks: dict) -> dict: """chunks: {worker: chunk} -> {worker: (obs or None, reward, done, info)}""" for i, c in chunks.items(): self.conns[i].send(("step", c)) return {i: self.conns[i].recv() for i in chunks} def close(self): for c in self.conns: try: c.send(("close", None)) except (BrokenPipeError, OSError): pass for p in self.procs: p.join(timeout=10) if p.is_alive(): p.terminate()