"""The policy acting in netherite, closed loop: an Env (mcsr.nwrl, the simulator on its render card) and the KV-cached batched policy (mcsr.kvstep.Stepper, on a policy card), with the action map, the macros and the reward. The envs are split into groups, one Stepper each (its CUDA graph at the group's batch): a group's policy step runs as soon as every env of the group has its result, while the other groups' envs are still in the simulator, so the sim and the policy overlap (lane/rlsplit's projection: a closed loop needs about twice the worlds in flight). A group's envs run their episodes in lockstep (same length), so a group resets together. Frames reach the policy card by a peer copy of the gathered [B, h, w, 3] batch. Per episode it reports the numbers mcsr's eval harness reports for the real client (scripts/macro_report.py): net distance at 60 s and at the end, logs, blocks mined, deaths, chests opened and items looted, the time standing still, iron; and it can record what GRPO learns from (the frame embeddings, the sampled actions, their log-probabilities, which steps the policy drove, the rewards). """ import math import time import numpy as np import torch import torch.nn.functional as F from mcsr import nwrl from mcsr.kvstep import Stepper, load_policy from mcsr.rl.actmap import to_acts, DEAD_KEYS from mcsr.rl.macros import Macros, MACRO_NAMES, M_NONE from mcsr.rl.reward import Reward, inv_value LIVE_KEYS = [k for k in range(14) if k not in DEAD_KEYS] def logp_of(cl, al, cam, keys, temperature=1.0): """log-probability of the sampled action (camera bins [B,2], keys [B,14]) under logits cl [B,2,41], al [B,14]: both camera axes and the keys that do something in 1.7.10""" lc = F.log_softmax(cl.float() / max(temperature, 1e-6), -1).gather(-1, cam.long()[..., None])[..., 0].sum(-1) k = keys.float()[:, LIVE_KEYS] a = al.float()[:, LIVE_KEYS] lk = (k * F.logsigmoid(a) + (1 - k) * F.logsigmoid(-a)).sum(-1) return lc + lk class Runner: def __init__(self, env, model, policy_dev, groups=2, edits=None, macros=True, mode="graph", compile_mode="default", temperature=1.0, ep_len=3600, objective="full", record=False, log=print): self.env, self.n, self.G = env, env.n, groups assert self.n % groups == 0 self.gs = self.n // groups self.dev = torch.device(policy_dev) self.model = model self.log = log t0 = time.time() self.st = [Stepper(model, self.gs, mode=mode, compile_mode=compile_mode, edits=edits) for _ in range(groups)] for s in self.st: s.p.temperature = temperature self.t_build = time.time() - t0 self.temperature = temperature self.ep_len = ep_len self.macros = Macros(self.n, **({} if macros is True else dict(craft=False, loot=False, mine=False, surface=False) if not macros else macros)) self.rew = Reward(self.n, objective) self.record = record D = model.c.d_t if record: L = ep_len self.E = torch.zeros(self.n, L, D, dtype=torch.bfloat16, device=self.dev) self.CAM = torch.zeros(self.n, L, 2, dtype=torch.int8, device=self.dev) self.KEY = torch.zeros(self.n, L, 14, dtype=torch.bool, device=self.dev) self.LOGP = torch.zeros(self.n, L, dtype=torch.float32, device=self.dev) self.MASK = np.zeros((self.n, L), bool) self.REW = np.zeros((self.n, L), np.float32) self.prev_hold = np.zeros(self.n, np.uint32) self.te = np.zeros(self.n, np.int64) # steps into the episode (the next result's index) self.episodes = [] self.M = {k: np.zeros(self.n, np.float64) for k in ("x0", "z0", "lx", "lz", "path", "still", "steps", "net60", "deaths", "ret", "t_items", "t_logs", "t_chest", "t_progress", "t_ach", "t_death")} self.macro_n = np.zeros((self.n, len(MACRO_NAMES)), np.int64) self._ep_reset(np.arange(self.n)) def _ep_reset(self, ids): M = self.M for k in M: M[k][ids] = 0 M["x0"][ids] = np.nan def _metrics(self, res, rew, terms): ids = res["id"].astype(np.int64) M = self.M x, z = res["x"], res["z"] first = np.isnan(M["x0"][ids]) M["x0"][ids] = np.where(first, x, M["x0"][ids]) M["z0"][ids] = np.where(first, z, M["z0"][ids]) M["lx"][ids] = np.where(first, x, M["lx"][ids]) M["lz"][ids] = np.where(first, z, M["lz"][ids]) step = np.hypot(x - M["lx"][ids], z - M["lz"][ids]) M["path"][ids] += step M["still"][ids] += step < 0.01 M["lx"][ids], M["lz"][ids] = x, z M["steps"][ids] += 1 at60 = self.te[ids] == 1200 M["net60"][ids] = np.where(at60, np.hypot(x - M["x0"][ids], z - M["z0"][ids]), M["net60"][ids]) M["deaths"][ids] += (res["flags"] & nwrl.PF_DIED) != 0 M["ret"][ids] += rew for k, v in terms.items(): M["t_" + k][ids] += v def _finish(self, res): M = self.M for q in range(len(res)): r, e = res[q], int(res["id"][q]) s = r["st"] inv = s["inv"] iron = int(sum(int(c) for it, c in zip(inv["item"], inv["count"]) if int(it) in (15, 265))) self.episodes.append(dict( env=e, steps=int(M["steps"][e]), net60=float(M["net60"][e]), net=float(math.hypot(r["x"] - M["x0"][e], r["z"] - M["z0"][e])), path=float(M["path"][e]), still=float(M["still"][e] / max(1, M["steps"][e])), deaths=int(M["deaths"][e]), logs=int(s["mined_logs"]), chests_known=int(s["chests_known"]), chests=int(s["chests_opened"]), looted=int(s["chest_items_taken"]), iron=iron, ach=bin(int(s["ach"])).count("1"), crafted=int(s["crafted"]), value=float(inv_value(np.array([s]))[0]), ret=float(M["ret"][e]), terms={k[2:]: float(M[k][e]) for k in M if k.startswith("t_")}, macro={MACRO_NAMES[i]: int(v) for i, v in enumerate(self.macro_n[e])}, mined=sum(1 for ev in self.macros.events[e] if ev[1] == "mined"), y=float(r["y"]), dim=int(r["dim"]))) # -- the loop ------------------------------------------------------------------------------------------------- def _null_step(self, ids): a = nwrl.Env.acts(len(ids)) self.env.step(ids, a) def _reset_group(self, g): ids = np.arange(g * self.gs, (g + 1) * self.gs) self.env.reset(ids) self.st[g].reset(list(range(self.gs))) self.macros.reset(ids) self.rew.reset(ids) self.prev_hold[ids] = 0 self.te[ids] = 0 self._ep_reset(ids) self.macro_n[ids] = 0 if self.record: self.MASK[ids] = False self.REW[ids] = 0 def run(self, episodes=1, on_episode_end=None, max_seconds=None, reset=False): """every group plays `episodes` episodes of ep_len steps (reset: every group from the start first); on_episode_end(g) after a group's episode (before its reset: a learner reads the group's record there). Returns env-steps/s of the loop.""" env, n, G, gs = self.env, self.n, self.G, self.gs if reset: for g in range(G): self._reset_group(g) done_eps = np.zeros(G, np.int64) buf = [[] for _ in range(G)] have = np.zeros(G, np.int64) self._null_step(np.arange(n)) steps, t0 = 0, time.time() self.t_policy = self.t_macro = self.t_poll = self.t_step = 0.0 active = np.ones(G, bool) while active.any(): tp = time.time() res = env.poll(n) self.t_poll += time.time() - tp if len(res) == 0: break gid = res["id"] // gs for g in np.unique(gid): buf[g].append(res[gid == g]) have[g] += int((gid == g).sum()) for g in np.flatnonzero(have == gs): R = np.concatenate(buf[g]) R = R[np.argsort(R["id"])] buf[g], have[g] = [], 0 steps += gs ids = R["id"].astype(np.int64) rew, terms = self.rew.step(R) te = int(self.te[ids[0]]) if self.record and te > 0: self.REW[ids, te - 1] = rew # the reward of the action taken at te - 1 self._metrics(R, rew, terms) if te >= self.ep_len or (max_seconds and time.time() - t0 > max_seconds): self._finish(R) done_eps[g] += 1 if on_episode_end: on_episode_end(g) if done_eps[g] >= episodes or (max_seconds and time.time() - t0 > max_seconds): active[g] = False continue self._reset_group(g) self._null_step(ids) continue self._act(g, R, ids, te) self.wall = time.time() - t0 return steps / self.wall def _act(self, g, R, ids, te): env, st = self.env, self.st[g] tp = time.time() frames = env.frames(R) rgb = frames.to(self.dev, non_blocking=True) cl, al, cs, asmp = st.step(rgb) both = torch.cat([cs.float(), asmp], 1).cpu().numpy() # one host sync cam, keys = both[:, :2].astype(np.int64), both[:, 2:] if self.record: self.E[ids, te] = st.p.e_out self.CAM[ids, te] = cs.to(torch.int8) self.KEY[ids, te] = asmp > 0.5 self.LOGP[ids, te] = logp_of(cl, al, cs, asmp, self.temperature) self.t_policy += time.time() - tp tm = time.time() acts, hold = to_acts(cam, keys, self.prev_hold[ids]) self.prev_hold[ids] = hold attack = (hold >> nwrl.PK["attack"]) & 1 > 0 kind = self.macros.apply(R, acts, attack) np.add.at(self.macro_n, (ids, kind.astype(np.int64)), 1) if self.record: self.MASK[ids, te] = kind == M_NONE self.te[ids] += 1 self.t_macro += time.time() - tm ts = time.time() env.step(ids, acts) self.t_step += time.time() - ts def summarize(eps): """the per-episode means (and totals) of a list of Runner.episodes""" if not eps: return {} k = len(eps) mean = lambda f: sum(e[f] for e in eps) / k out = dict(episodes=k, net60=mean("net60"), net=mean("net"), path=mean("path"), still=mean("still"), deaths=sum(e["deaths"] for e in eps), died_eps=sum(e["deaths"] > 0 for e in eps), logs=sum(e["logs"] for e in eps), logs_mean=mean("logs"), eps_with_log=sum(e["logs"] > 0 for e in eps), mined=mean("mined"), chests_known=mean("chests_known"), chests=sum(e["chests"] for e in eps), looted=sum(e["looted"] for e in eps), iron=sum(e["iron"] for e in eps), ach=mean("ach"), crafted=mean("crafted"), ret=mean("ret")) macro = {} for e in eps: for n_, v in e["macro"].items(): macro[n_] = macro.get(n_, 0) + v tot = sum(macro.values()) or 1 out["macro_share"] = {n_: round(v / tot, 4) for n_, v in macro.items()} return out