"""One RL run as one file (netherite configs/speedrun-grpo.yaml; Elliot, 2026-09-30: "two parts there. sim and policy. with all the settings/hparams for each"). The grammar is netherite config.yaml's header, a strict YAML subset read here line for line as native/src/worldconf.c and java WorldConf.java read it (stdlib only): sim: the world and the envs: netherite's registry (config.yaml lists every key at its default); world: the C side (libnwrl, given the same file) reads and checks these values itself seed: 1 policy: the trainer's: POLICY below, every key with its default (nw_grpo's flag defaults) grpo: lr: 1e-05 A file without parts (configs/speedrun.yaml) is sim's sections alone and takes every policy default. Paths in policy (model.ckpt, action.gui_head, out.dir) are under this checkout; sim.pipeline.start is under the netherite tree (configs/'s parent). A key left out keeps its default; an unknown one is an error. uv run --no-project python -m mcsr.runconf FILE [key=value ...] # the resolved run file, every key """ import dataclasses import os import re import sys ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) NETHERITE = os.path.expanduser(os.environ.get("NETHERITE", "~/dev/netherite-v2")) HEADER = re.compile(r"([a-z][a-z0-9_]*):( +#.*| *)$") SECTION2 = re.compile(r" ([a-z][a-z0-9_]*):( +#.*| *)$") ENTRY = re.compile(r" ([a-z][a-z0-9_]*): ([A-Za-z0-9_./+,-]+)( +#.*| *)$") ENTRY4 = re.compile(r" ([a-z][a-z0-9_]*): ([A-Za-z0-9_./+,-]+)( +#.*| *)$") SYNTAX = "expected a part (sim: or policy:), a section (name:) or an entry (key: value) at its indent" class ConfError(ValueError): pass def parse(text, name="-"): """{part: {section: {key: value}}} in file order; a file without parts is {"sim": ...}""" out = {} parts, part, section = None, None, None seen = set() for n, line in enumerate(text.split("\n"), 1): where = f"{name}:{n}" if line.endswith("\r"): line = line[:-1] if "\t" in line: raise ConfError(f"{where}: a tab (indent with spaces)") t = line.strip() if not t or t.startswith("#"): continue m = HEADER.match(line) head = m is not None if head: h = m.group(1) is_part = h in ("sim", "policy") if parts is None: parts = is_part if not parts: part = "sim" out["sim"] = {} if parts: if not is_part: raise ConfError(f"{where}: unknown part {h} (sim or policy)") if h in out: raise ConfError(f"{where}: part {h} twice") part, section = h, None out[h] = {} continue elif parts: m = SECTION2.match(line) head = m is not None if head: section = m.group(1) if section in out[part]: raise ConfError(f"{where}: section {section} twice") out[part][section] = {} continue m = (ENTRY4 if parts else ENTRY).match(line) if not m: raise ConfError(f"{where}: {SYNTAX}") if section is None: raise ConfError(f"{where}: an entry before any section") k = m.group(1) if k in out[part][section]: raise ConfError(f"{where}: {part}.{section}.{k} twice") out[part][section][k] = m.group(2) return out # ---- sim: netherite's registry, as config.yaml lists it (worldconf_check holds config.yaml to the C table) def sim_defaults(netherite=None): path = os.path.join(netherite or NETHERITE, "config.yaml") with open(path) as f: return parse(f.read(), path)["sim"] # ---- policy: every key, its default (today's nw_grpo flag defaults) and its type @dataclasses.dataclass class Model: ckpt: str = "data/play_export/fast-D-s20000.pt" edits: str = "none" # version | none mode: str = "graph" compile: str = "default" @dataclasses.dataclass class Placement: cards: str = "1" # the policy cards; the first also learns (learner shared) learner: str = "shared" # shared (the first policy card; nw_grpo: its model) | a card (an ordinal: a model # of its own there) | card (nw_grpo's old --learner card: the next unused ordinal) @dataclasses.dataclass class Action: gui: str = "macro" # macro | head gui_head: str = "none" # the inventory head's checkpoint (gui head) gui_pointer: str = "slot" # slot | item | move | recipe gui_decide: str = "every_tick" # every_tick | on_op ops_per_step: int = 1 camera: str = "mulaw41" # mulaw41 | target (needs sim.actions.look_target on; lane/moveact) attack: str = "press" # press | hold (needs sim.actions.hold_attack on; lane/moveact) act_every: int = 1 # the policy acts every K-th step, the steps between hold its keys; one tick a # step, every frame into its context, its own samples fed back (lane/moveact) @dataclasses.dataclass class Grpo: objective: str = "logs" iters: int = 40 lr: float = 3e-6 beta: float = 0.04 clip: float = 0.2 epochs: int = 1 mb: int = 16 stale: int = 0 # lane rlasync's one-update-stale learner: 0 or 1 max_hours: float = 6.0 seed: str = "none" # none (today's: the policy's draws from torch's generator) or an int: every draw a # function of (seed, env, step) (lane rlasync's mcsr.rl.arollout.seed_sync_runner) @dataclasses.dataclass class Reward: """each term's weight, or "objective": the weight mcsr.rl.reward.OBJECTIVES[grpo.objective] gives it""" items: str = "objective" logs: str = "objective" chest: str = "objective" progress: str = "objective" ach: str = "objective" death: str = "objective" milestone: str = "objective" looted: str = "objective" @dataclasses.dataclass class Out: dir: str = "none" # required (here or --out) @dataclasses.dataclass class Policy: model: Model = dataclasses.field(default_factory=Model) placement: Placement = dataclasses.field(default_factory=Placement) action: Action = dataclasses.field(default_factory=Action) grpo: Grpo = dataclasses.field(default_factory=Grpo) reward: Reward = dataclasses.field(default_factory=Reward) out: Out = dataclasses.field(default_factory=Out) ENUMS = {"model.edits": ("version", "none"), "action.gui": ("macro", "head"), "action.gui_pointer": ("slot", "item", "move", "recipe"), "action.gui_decide": ("every_tick", "on_op"), "action.camera": ("mulaw41", "target"), "action.attack": ("press", "hold"), "grpo.stale": (0, 1)} # what is not implemented yet: a key at another value is refused (lanes guiact and moveact replace these lines); # lane/guiact's gui_pointer (move, item, recipe), gui_decide and ops_per_step (1 to 8) are mcsr.rl.guirollout's UNIMPLEMENTED = {} def _typed(typ, v, key): try: return typ(v) except ValueError: raise ConfError(f"policy.{key} takes a {typ.__name__}, not {v}") from None def _check_reward(key, v): if v != "objective": try: float(v) except ValueError: raise ConfError(f"policy.{key} takes a number or objective, not {v}") from None @dataclasses.dataclass class Run: sim: dict # {section: {key: value}}: every sim key, as strings (the C side types them) policy: Policy path: str = "" # the file read ("" none) # sim's RL keys, typed @property def worlds(self): return int(self.sim["pipeline"]["worlds"]) @property def groups(self): return int(self.sim["pipeline"]["groups"]) @property def sim_cards(self): return [int(c) for c in self.sim["pipeline"]["cards"].split(",")] @property def episode_seconds(self): return int(self.sim["pipeline"]["episode_seconds"]) def get(self, key): """part.section.key""" part, section, k = key.split(".") if part == "sim": return self.sim[section][k] return getattr(getattr(self.policy, section), k) def set(self, key, v): """part.section.key=value: refused for a key the file's registry does not have""" part, _, rest = key.partition(".") section, _, k = rest.partition(".") if part == "sim": if section not in self.sim or k not in self.sim[section]: raise ConfError(f"unknown key {key}") self.sim[section][k] = str(v) return if part != "policy" or not hasattr(self.policy, section) or not hasattr(getattr(self.policy, section), k): raise ConfError(f"unknown key {key}") sec = getattr(self.policy, section) f = {f.name: f for f in dataclasses.fields(sec)}[k] if section == "reward": v = str(v) _check_reward(f"{section}.{k}", v) else: v = _typed(f.type, v, f"{section}.{k}") if f.type is not str else str(v) if f"{section}.{k}" == "grpo.seed" and v != "none" and not re.fullmatch(r"-?[0-9]{1,19}", v): raise ConfError(f"policy.grpo.seed takes none or an integer, not {v}") if f"{section}.{k}" == "placement.learner" and v not in ("shared", "card") and not re.fullmatch(r"[0-9]{1,2}", v): raise ConfError(f"policy.placement.learner takes shared, card or a card's ordinal, not {v}") allowed = ENUMS.get(f"{section}.{k}") if allowed and v not in allowed: raise ConfError(f"policy.{section}.{k} takes {'|'.join(map(str, allowed))}, not {v}") setattr(sec, k, v) def check_implemented(self): for k, want in UNIMPLEMENTED.items(): if self.get("policy." + k) != want: raise ConfError(f"policy.{k}: not implemented yet ({want}, the default, is today's behaviour)") # lane/moveact: a policy action the engine's lever compiles for k, val, lever in (("action.attack", "hold", "hold_attack"), ("action.camera", "target", "look_target")): if self.get("policy." + k) == val and self.sim.get("actions", {}).get(lever) != "on": raise ConfError(f"policy.{k} {val} needs sim.actions.{lever} on") if self.policy.action.act_every < 1 or (self.policy.action.act_every > 1 and self.sim.get("client", {}).get("ticks_per_step") != "1"): raise ConfError("policy.action.act_every takes 1, or K > 1 with sim.client.ticks_per_step 1") def reward_weights(self, objectives): """the reward's weights: OBJECTIVES[grpo.objective] with this file's numbers over it""" w = dict(objectives[self.policy.grpo.objective]) for f in dataclasses.fields(self.policy.reward): v = getattr(self.policy.reward, f.name) if v != "objective": w[f.name] = float(v) return w def root(self): """the netherite tree the sim part's relative paths are under: the file's directory, configs/'s parent""" d = os.path.dirname(os.path.abspath(self.path)) if self.path else NETHERITE return os.path.dirname(d) if os.path.basename(d) == "configs" else d def policy_path(self, p): """a policy path under this checkout; "none" is none""" if p in ("none", ""): return "" return p if os.path.isabs(p) else os.path.join(ROOT, p) def text(self): """the resolved run file: both parts, every key""" lines = [f"# resolved by mcsr.runconf from {self.path or '(defaults)'}", "", "sim:"] for section, kv in self.sim.items(): lines.append(f" {section}:") lines += [f" {k}: {v}" for k, v in kv.items()] lines += ["", "policy:"] for sf in dataclasses.fields(self.policy): lines.append(f" {sf.name}:") sec = getattr(self.policy, sf.name) for f in dataclasses.fields(sec): v = getattr(sec, f.name) lines.append(f" {f.name}: {v!r}" if isinstance(v, float) else f" {f.name}: {v}") return "\n".join(lines) + "\n" def load(path, netherite=None): """the run file at path (either form) over every default; ConfError names the file and line""" with open(path) as f: parts = parse(f.read(), path) sim = sim_defaults(netherite) for section, kv in parts.get("sim", {}).items(): if section not in sim: raise ConfError(f"{path}: unknown section sim.{section}") for k, v in kv.items(): if k not in sim[section]: raise ConfError(f"{path}: unknown key sim.{section}.{k}") sim[section][k] = v run = Run(sim=sim, policy=Policy(), path=os.path.abspath(path)) for section, kv in parts.get("policy", {}).items(): if not hasattr(run.policy, section): raise ConfError(f"{path}: unknown section policy.{section}") for k, v in kv.items(): try: run.set(f"policy.{section}.{k}", v) except ConfError as e: raise ConfError(f"{path}: {e}") from None return run def resolve(a, flags, netherite=None, old=None, name="nw_grpo"): """a driver's run: the run file (a.run, else a.config, else NETHERITE/configs/speedrun.yaml) under every flag given (a.FLAG not None; flags maps a flag to its key, None for --config), printed as an override when there is a run file. Without a run file a flag not given takes the driver's old default (old: {flag: value}), so the flags alone run as they did. --n is a sim card's share of sim.pipeline.worlds: the cards are set first. Exits with the message on any error.""" if a.run and a.config: sys.exit(f"{name}: --run FILE is the config too (its sim part); drop --config") path = a.run or a.config or os.path.join(netherite or NETHERITE, "configs/speedrun.yaml") try: run = load(path, netherite) if not a.run: for k, v in (old or {}).items(): if getattr(a, k) is None: setattr(a, k, v) given = {k: v for k, v in vars(a).items() if flags.get(k) and v is not None} for k in sorted(given, key=lambda k: k != "sims"): v = given[k] if k == "n": v = v * len(run.sim_cards) elif k == "seconds": if v != int(v): sys.exit(f"{name}: --seconds {v}: sim.pipeline.episode_seconds is whole seconds") v = int(v) elif k in ("edits", "gui_head", "learner"): v = v or ("shared" if k == "learner" else "none") elif k in ("start", "out", "ckpt"): v = os.path.abspath(v) if a.run: print(f"{name}: override {flags[k]} = {v} (--{k.replace('_', '-')})", flush=True) run.set(flags[k], v) run.check_implemented() except ConfError as e: sys.exit(f"{name}: {e}") if run.worlds % len(run.sim_cards): sys.exit(f"{name}: sim.pipeline.worlds {run.worlds} is not a whole number a card of {run.sim_cards}") if run.policy.out.dir == "none": sys.exit(f"{name}: no out dir (policy.out.dir or --out)") return run def main(): if len(sys.argv) < 2: sys.exit(__doc__) try: run = load(sys.argv[1]) for kv in sys.argv[2:]: k, _, v = kv.partition("=") run.set(k, v) except ConfError as e: sys.exit(f"runconf: {e}") sys.stdout.write(run.text()) if __name__ == "__main__": main()