File size: 10,843 Bytes
d8e9a5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
"""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()