diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3c03f632e33cb69e557072813e6e683be79f0b50 --- /dev/null +++ b/README.md @@ -0,0 +1,70 @@ +--- +license: apache-2.0 +language: +- en +tags: +- decision-model +- reinforcement-learning +- snake +- minijev +library_name: minijev +--- + +# MiniJEV · Snake + +A **tiny decision model** (≈0.5M parameters, 2 MB) that plays Snake on a 10×10 board. +It is not a language model and generates no text. At each step it scores the +available choices (`move up`, `move down`, `move left`, `move right`) and returns a +**calibrated probability** for each one. + +It is the first benchmark of **MiniJEV**. The same core (state + question + +dynamic list of choices → choice + calibrated confidence) is used for text decisions +in [`markuz89/minijev-general`](https://huggingface.co/markuz89/minijev-general). + +## Results (200 games, 10×10, max score 97) + +| metric | value | +|---|---| +| average score | **88.6** | +| median score | 97 (board filled) | +| games won (board filled) | **73.5 %** | +| deaths | 19 % | +| stopped for starvation | 7.5 % | +| fatal moves | 0.02 % of decisions | + +For comparison, the search-based oracle the model was first distilled from scores +95 on average and wins 38 % of games. The model wins more often but has a lower +average score. + +Training pipeline: +1. Supervised distillation from the oracle. +2. DAgger. +3. PPO (two rounds, γ = 0.995, on an RTX 4090). +4. The choices were then renamed from `UP/DOWN/…` to `move up/…` without retraining. Only the choice encoder was re-fit, and the probabilities are identical (max difference 4e-7). + +## Usage + +```bash +git clone https://huggingface.co/markuz89/minijev-snake && cd minijev-snake/code +pip install -e ".[train]" # needs torch; ONNX export is available for torch-free inference +``` + +```python +from minijev.inference.runtime import MiniJEV + +dec = MiniJEV.load("..") # the cloned repo folder (or the repo id) +state = dec.task.example_states(1)[0] # {"body": [...], "food": (x, y), "direction": ...} +d = dec.decide(state) # question and choices default to the Snake task +print(d.choice, d.confidence, d.scores) # e.g. "move left" 0.999 {...} +``` + +## Files + +- `model.safetensors`: weights (no pickle) +- `config.json`: architecture, task config, calibration temperature, metrics +- `code/`: the `minijev` package and the Snake environment needed to run it + +## Limits + +The model was trained only on 10×10 boards. Inputs are the grid channels of the +MiniJEV Snake environment, and it is not a general game-playing agent. diff --git a/code/environments/__init__.py b/code/environments/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code/environments/__pycache__/__init__.cpython-314.pyc b/code/environments/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b43945d8ba226a01cfd69357addf75d114915d34 Binary files /dev/null and b/code/environments/__pycache__/__init__.cpython-314.pyc differ diff --git a/code/environments/snake/__init__.py b/code/environments/snake/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code/environments/snake/__pycache__/__init__.cpython-314.pyc b/code/environments/snake/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..032d72eb158294cb9e48d6cd6eb55a775910cb52 Binary files /dev/null and b/code/environments/snake/__pycache__/__init__.cpython-314.pyc differ diff --git a/code/environments/snake/__pycache__/agents.cpython-314.pyc b/code/environments/snake/__pycache__/agents.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea4ac1d394ebbb4390a6e1611b74c57c7c21abf5 Binary files /dev/null and b/code/environments/snake/__pycache__/agents.cpython-314.pyc differ diff --git a/code/environments/snake/__pycache__/encoder.cpython-314.pyc b/code/environments/snake/__pycache__/encoder.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8cef1b6f96aa10ef1da9ab2ecc17be7d37720bd3 Binary files /dev/null and b/code/environments/snake/__pycache__/encoder.cpython-314.pyc differ diff --git a/code/environments/snake/__pycache__/env.cpython-314.pyc b/code/environments/snake/__pycache__/env.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4ddf5a7c5ad1e12f5fcb48c7427702fd26cc1a5 Binary files /dev/null and b/code/environments/snake/__pycache__/env.cpython-314.pyc differ diff --git a/code/environments/snake/__pycache__/task.cpython-314.pyc b/code/environments/snake/__pycache__/task.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..832d5648dfdb7cd3bd4fb4860a6694fe15bb46d3 Binary files /dev/null and b/code/environments/snake/__pycache__/task.cpython-314.pyc differ diff --git a/code/environments/snake/agents.py b/code/environments/snake/agents.py new file mode 100644 index 0000000000000000000000000000000000000000..d0ffc02cd82ca45585fa91783c6986f69f239032 --- /dev/null +++ b/code/environments/snake/agents.py @@ -0,0 +1,264 @@ +"""Scripted Snake agents: the oracle used for supervision and the baselines. + +All agents implement `act(state: SnakeState) -> str`. + +Path search is *time-aware*: a body cell at index i (head=0) of a snake of +length L becomes free after L - i moves, so a path may pass where the tail +currently is if it arrives late enough. This makes BFS paths exact as long as +no food is eaten along the way (food is only ever the final cell). +""" +from __future__ import annotations + +from collections import deque +from functools import lru_cache + +import numpy as np + +from .env import ACTIONS, DELTAS, SnakeState + + +@lru_cache(maxsize=16) +def _neighbors(h: int, w: int) -> tuple[tuple[tuple[int, str], ...], ...]: + out = [] + for cell in range(h * w): + r, c = divmod(cell, w) + nb = [] + for a in ACTIONS: + dr, dc = DELTAS[a] + nr, nc = r + dr, c + dc + if 0 <= nr < h and 0 <= nc < w: + nb.append((nr * w + nc, a)) + out.append(tuple(nb)) + return tuple(out) + + +def _flat(state: SnakeState) -> tuple[list[int], int]: + w = state.width + body = [r * w + c for r, c in state.body] + food = state.food[0] * w + state.food[1] if state.food is not None else -1 + return body, food + + +def _free_times(body: list[int], area: int) -> list[int]: + ft = [0] * area + L = len(body) + for i, cell in enumerate(body): + ft[cell] = L - i + return ft + + +def _bfs(nbrs, area: int, start: int, ft: list[int], goal: int = -1): + dist = [-1] * area + parent = [-1] * area + dist[start] = 0 + q = deque([start]) + while q: + u = q.popleft() + du = dist[u] + 1 + for v, _ in nbrs[u]: + if dist[v] < 0 and du >= ft[v]: + dist[v] = du + parent[v] = u + if v == goal: + return dist, parent + q.append(v) + return dist, parent + + +def _reachable_count(nbrs, area: int, start: int, ft: list[int]) -> int: + dist, _ = _bfs(nbrs, area, start, ft) + return sum(1 for d in dist if d > 0) + + +def _tail_reachable(nbrs, area: int, body: list[int]) -> tuple[bool, int]: + if len(body) < 2: + return True, 0 + ft = _free_times(body, area) + tail = body[-1] + dist, _ = _bfs(nbrs, area, body[0], ft, goal=tail) + return dist[tail] > 0, dist[tail] + + +def safe_moves(state: SnakeState) -> list[str]: + """Moves that do not die on the very next step.""" + body, _ = _flat(state) + nbrs = _neighbors(state.height, state.width) + ft = _free_times(body, state.height * state.width) + return [a for v, a in nbrs[body[0]] if ft[v] <= 1] + + +class Agent: + name = "agent" + + def act(self, state: SnakeState) -> str: # pragma: no cover - interface + raise NotImplementedError + + def reset(self, seed: int | None = None) -> None: + pass + + +class RandomAgent(Agent): + name = "random" + + def __init__(self, seed: int = 0): + self.rng = np.random.default_rng(seed) + + def reset(self, seed=None): + if seed is not None: + self.rng = np.random.default_rng(seed) + + def act(self, state): + return ACTIONS[int(self.rng.integers(4))] + + +class GreedyFoodAgent(Agent): + """Minimise Manhattan distance to food; avoid *immediately* fatal moves when possible.""" + name = "greedy" + + def act(self, state): + safe = safe_moves(state) or list(ACTIONS) + hr, hc = state.body[0] + fr, fc = state.food if state.food else (hr, hc) + return min(safe, key=lambda a: abs(hr + DELTAS[a][0] - fr) + abs(hc + DELTAS[a][1] - fc)) + + +class BFSAgent(Agent): + """Shortest (time-aware) path to food, no look-ahead; else the safe move with most space.""" + name = "bfs" + + def act(self, state): + h, w = state.height, state.width + area = h * w + nbrs = _neighbors(h, w) + body, food = _flat(state) + ft = _free_times(body, area) + if food >= 0: + path = _path_to(nbrs, area, body[0], ft, food) + if path: + return _direction(w, body[0], path[0]) + return _max_space_move(nbrs, area, body) or ACTIONS[0] + + +class SurvivalAgent(Agent): + """Flood-fill heuristic: maximise reachable space, break ties by distance to food.""" + name = "survival" + + def act(self, state): + h, w = state.height, state.width + area = h * w + nbrs = _neighbors(h, w) + body, food = _flat(state) + ft = _free_times(body, area) + best, best_key = None, None + fr, fc = divmod(food, w) if food >= 0 else divmod(body[0], w) + for v, a in nbrs[body[0]]: + if ft[v] > 1: + continue + nb = [v] + (body if v == food else body[:-1]) + space = _reachable_count(nbrs, area, v, _free_times(nb, area)) + r, c = divmod(v, w) + key = (min(space, len(nb) + 1), -(abs(r - fr) + abs(c - fc))) + if best_key is None or key > best_key: + best, best_key = a, key + return best or ACTIONS[0] + + +class OracleAgent(Agent): + """Strong teacher: eat only if the snake can still reach its tail afterwards, + otherwise chase the tail along the longest safe route, otherwise maximise space. + + `analyze` also returns the *set* of equally good moves. Ties are broken by a fixed + priority (UP > DOWN > LEFT > RIGHT) instead of BFS queue order, so the hard label + is a learnable function of the state (and this rule also scored best: 95.0 vs + 91.5-92.1 for "close the larger/smaller axis gap first", 60 games 10x10). + """ + name = "oracle" + + def act(self, state): + return self.analyze(state)[0] + + def analyze(self, state) -> tuple[str, list[str], str]: + """-> (move, optimal_moves, mode) with mode in {eat, tail, space, dead}.""" + h, w = state.height, state.width + area = h * w + nbrs = _neighbors(h, w) + body, food = _flat(state) + L = len(body) + ft = _free_times(body, area) + head = body[0] + safe = [(v, a) for v, a in nbrs[head] if ft[v] <= 1] + if not safe: + return ACTIONS[0], list(ACTIONS), "dead" + if food >= 0: + dist, _ = _bfs(nbrs, area, head, ft, goal=food) + d = dist[food] + if d > 0: + good = [] + for v, a in safe: + if v == food: + virtual = [v] + body + else: + nb = [v] + body[:-1] + path = _path_to(nbrs, area, v, _free_times(nb, area), food) + if len(path) != d - 1: + continue + virtual = (path[::-1] + nb)[: L + 1] + if len(virtual) >= area or _tail_reachable(nbrs, area, virtual)[0]: + good.append(a) + if good: + return good[0], good, "eat" + # tail chasing: keep an escape route, prefer the move farthest from the tail + cands = [] + for v, a in safe: + nb = [v] + (body if v == food else body[:-1]) + ok, dt = _tail_reachable(nbrs, area, nb) + if ok: + cands.append((dt, a)) + if cands: + best = max(dt for dt, _ in cands) + good = [a for dt, a in cands if dt == best] + return good[0], good, "tail" + spaces = [] + for v, a in safe: + nb = [v] + (body if v == food else body[:-1]) + spaces.append((_reachable_count(nbrs, area, v, _free_times(nb, area)), a)) + best = max(sp for sp, _ in spaces) + good = [a for sp, a in spaces if sp == best] + return good[0], good, "space" + + +def _path_to(nbrs, area, start, ft, goal) -> list[int]: + dist, parent = _bfs(nbrs, area, start, ft, goal) + if dist[goal] <= 0: + return [] + path = [goal] + while parent[path[-1]] != start: + path.append(parent[path[-1]]) + return path[::-1] + + +def _direction(w: int, a: int, b: int) -> str: + ar, ac = divmod(a, w) + br, bc = divmod(b, w) + return {(-1, 0): "UP", (1, 0): "DOWN", (0, -1): "LEFT", (0, 1): "RIGHT"}[(br - ar, bc - ac)] + + +def _max_space_move(nbrs, area, body) -> str | None: + ft = _free_times(body, area) + best, best_space = None, -1 + for v, a in nbrs[body[0]]: + if ft[v] > 1: + continue + nb = [v] + body[:-1] + space = _reachable_count(nbrs, area, v, _free_times(nb, area)) + if space > best_space: + best, best_space = a, space + return best + + +AGENTS = {c.name: c for c in (RandomAgent, GreedyFoodAgent, BFSAgent, SurvivalAgent, OracleAgent)} + + +def make_agent(name: str, seed: int = 0) -> Agent: + cls = AGENTS[name] + return cls(seed) if cls is RandomAgent else cls() diff --git a/code/environments/snake/dagger.py b/code/environments/snake/dagger.py new file mode 100644 index 0000000000000000000000000000000000000000..b0dc173a6e98f683d95e2f3a504806de9bfcc986 --- /dev/null +++ b/code/environments/snake/dagger.py @@ -0,0 +1,80 @@ +"""DAgger for Snake (Ross et al., 2011). + +Behaviour cloning only sees states the oracle visits; once the student makes a +mistake it lands in states it never trained on and errors compound. DAgger lets +the student play, labels *its* states with the oracle, aggregates them with the +original data and fine-tunes. Cheap (no reward engineering, the oracle is +free) and directly targets the student's own failure modes. +""" +from __future__ import annotations + +import copy +import json +import shutil +from pathlib import Path + +from minijev.datasets.decision_data import DecisionData +from minijev.inference.runtime import TorchDecider +from minijev.training.supervised import train + +from .dataset import QUESTION, collect_with_policy + + +def run_dagger(cfg: dict, checkpoint: str, iterations: int = 2, samples: int = 100_000, + run_dir: str | None = None) -> list[dict]: + import torch + + # model/training settings come from the checkpoint (DAgger fine-tunes *that* model); + # the dagger config only contributes its `dagger`, `env` and `eval` sections + ck_cfg = torch.load(checkpoint, map_location="cpu", weights_only=False)["config"] + cfg = {**copy.deepcopy(ck_cfg), **{k: cfg[k] for k in ("dagger", "env", "eval") if k in cfg}} + device = "cuda" if torch.cuda.is_available() else "cpu" + root = Path(run_dir or f"runs/{ck_cfg.get('name', 'snake')}-dagger") + root.mkdir(parents=True, exist_ok=True) + base_dir = Path(cfg["data"]["dir"]) + agg = DecisionData.load(base_dir / "train.npz") + dcfg = cfg.get("dagger", {}) + board_sizes = cfg["data"].get("generate", {}).get("board_sizes", [cfg.get("env", {}).get("board_size", 10)]) + history = json.loads((root / "dagger.json").read_text()) if (root / "dagger.json").exists() else [] + for rec in history: # resume: finished iterations are kept, their data is rebuilt below + checkpoint = rec["checkpoint"] + if history: + agg = DecisionData.load(root / f"data-it{history[-1]['iteration']}" / "train.npz") + print(f"[dagger] resuming after iteration {history[-1]['iteration']}") + for it in range(len(history) + 1, iterations + 1): + dec = TorchDecider(checkpoint, threads=4, device=device) + # probs are aligned with ACTIONS order whatever the labels ("UP" or "move up") + policy = lambda states: dec.probs(states, QUESTION, list(dec.task.default_choices)) # noqa: E731 + print(f"[dagger] iteration {it}: collecting {samples:,} student states ...") + new = collect_with_policy(policy, samples, seed=1000 + it, board_sizes=board_sizes, + keep_prob=dcfg.get("keep_prob", 0.2), explore_eps=dcfg.get("explore_eps", 0.02), + env_cfg={k: v for k, v in cfg.get("env", {}).items() if k != "board_size"}, + game_id_base=10**9 * it, parallel=256) + agg = DecisionData.concat([agg, new]) + data_dir = root / f"data-it{it}" + data_dir.mkdir(exist_ok=True) + agg.save(data_dir / "train.npz") + for split in ("val", "test"): # evaluation splits stay the original, untouched ones + shutil.copy(base_dir / f"{split}.npz", data_dir / f"{split}.npz") + c = copy.deepcopy(cfg) + c["name"] = f"{cfg.get('name', 'snake')}-dagger{it}" + c["data"] = {"dir": str(data_dir)} + c["training"]["init_checkpoint"] = checkpoint + c["training"]["epochs"] = dcfg.get("epochs", 1) + c["training"]["lr"] = dcfg.get("lr", cfg["training"].get("lr", 1e-3) * 0.5) + c["training"]["warmup_steps"] = 100 + it_dir = root / f"it{it}" + summary = train(c, run_dir=it_dir, resume=(it_dir / "checkpoints" / "last.pt").exists()) + checkpoint = summary["final_checkpoint"] + from .evaluate import model_policy, play_games + games = play_games(model_policy(TorchDecider(checkpoint, threads=4, device=device)), + cfg.get("eval", {}).get("games", 200), cfg.get("env", {}), parallel=200) + (root / f"it{it}" / "games.json").write_text(json.dumps(games, indent=2)) + rec = {"iteration": it, "rows": len(agg), "new_rows": len(new), "checkpoint": checkpoint, + "test_acc": summary["test_calibrated"]["accuracy"], "test_ece": summary["test_calibrated"]["ece"], + "avg_score": games["avg_score"], "fatal_move_rate": games["fatal_move_rate"]} + print(f"[dagger] it {it}: avg score {games['avg_score']:.1f} | test acc {rec['test_acc']:.4f} " + f"| fatal-move {games['fatal_move_rate']:.4%}") + history.append(rec) + (root / "dagger.json").write_text(json.dumps(history, indent=2)) + return history diff --git a/code/environments/snake/dataset.py b/code/environments/snake/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..803bacfa9ec94e0cc581c9b899ff5bed2c9d50ad --- /dev/null +++ b/code/environments/snake/dataset.py @@ -0,0 +1,196 @@ +"""Oracle-labelled Snake datasets. + +Games are played by a behaviour policy (oracle + a little exploration), every +visited state is labelled with the oracle's move, and a random subset of states +(`keep_prob`) is kept so a dataset of N rows spans many independent games. +Rows carry their game id (`group`) for leakage-free splits and an exact state +hash to drop train/test duplicates (e.g. near-identical opening positions). +""" +from __future__ import annotations + +import json +import multiprocessing as mp +import os +import sys +from concurrent.futures import ProcessPoolExecutor +from pathlib import Path + +import numpy as np + +from minijev.datasets.decision_data import DecisionData, split_by_group + +from .agents import make_agent, safe_moves +from .env import ACTIONS, SnakeConfig, SnakeEnv, SnakeState +from .task import SnakeTask + +QUESTION = SnakeTask.default_question + + +def state_hash(s: SnakeState) -> int: + return hash((s.height, s.width, tuple(s.body), s.food)) + + +def play_and_label(n_samples: int, seed: int, board_sizes=(10,), keep_prob: float = 0.1, + explore_eps: float = 0.05, env_cfg: dict | None = None, + behaviour=None, labeler: str = "oracle", game_id_base: int = 0): + """Collect `n_samples` labelled states. `behaviour(state, rng) -> action` (default: the + labeler itself with epsilon-random safe moves). Returns (states, labels, groups).""" + rng = np.random.default_rng(seed) + oracle = make_agent(labeler) + states, labels, groups, optimal = [], [], [], [] + game = 0 + while len(states) < n_samples: + size = int(board_sizes[game % len(board_sizes)]) + cfg = SnakeConfig.from_dict({**(env_cfg or {}), "height": size, "width": size}) + gid = game_id_base + game + env = SnakeEnv(cfg, seed=int(rng.integers(2**31))) + while not env.done and len(states) < n_samples: + s = env.state() + label, good, _ = oracle.analyze(s) + if rng.random() < keep_prob: + states.append(s) + labels.append(label) + groups.append(gid) + optimal.append(good) + if behaviour is not None: + action = behaviour(s, rng) + elif rng.random() < explore_eps: + safe = safe_moves(s) + action = safe[int(rng.integers(len(safe)))] if safe else label + else: + action = label + env.step(action) + game += 1 + return states, labels, groups, optimal + + +def _worker(args): + n, seed, sizes, keep, eps, env_cfg, gbase = args + return play_and_label(n, seed, sizes, keep, eps, env_cfg, game_id_base=gbase) + + +def to_decision_data(states, labels, groups, optimal=None, meta: dict | None = None) -> DecisionData: + """`soft` = uniform distribution over the oracle's equally-optimal moves: used for the + "optimal-move accuracy" metric and available as a soft-label training target.""" + task = SnakeTask() + lab = {a: i for i, a in enumerate(ACTIONS)} + n = len(states) + soft = None + if optimal is not None: + soft = np.zeros((n, 4), np.float32) + for i, good in enumerate(optimal): + soft[i, [lab[a] for a in good]] = 1.0 / len(good) + return DecisionData( + task="snake", + state=task.states_to_arrays(states), + questions=[QUESTION], + question_idx=np.zeros(n, np.int32), + choices=list(ACTIONS), + choice_idx=np.tile(np.arange(4, dtype=np.int32), (n, 1)), + target=np.array([lab[a] for a in labels], np.int64), + group=np.array(groups, np.int64), + hash=np.array([state_hash(s) for s in states], np.int64), + soft=soft, + meta=meta or {}, + ) + + +def generate(n_samples: int, seed: int = 0, board_sizes=(10,), keep_prob: float = 0.1, + explore_eps: float = 0.05, env_cfg: dict | None = None, workers: int | None = None) -> DecisionData: + workers = workers or max(1, (os.cpu_count() or 2) - 1) + workers = min(workers, max(1, n_samples // 2000)) + per = [n_samples // workers + (1 if i < n_samples % workers else 0) for i in range(workers)] + jobs = [(per[i], seed * 1000 + i, tuple(board_sizes), keep_prob, explore_eps, env_cfg, i * 10_000_000) + for i in range(workers)] + if workers == 1: + results = [_worker(jobs[0])] + else: + ctx = mp.get_context("fork") if sys.platform == "linux" else None + with ProcessPoolExecutor(workers, mp_context=ctx) as ex: + results = list(ex.map(_worker, jobs)) + states = [s for r in results for s in r[0]] + labels = [a for r in results for a in r[1]] + groups = [g for r in results for g in r[2]] + optimal = [o for r in results for o in r[3]] + meta = {"generator": "oracle", "board_sizes": list(board_sizes), "keep_prob": keep_prob, + "explore_eps": explore_eps, "seed": seed, "env": env_cfg or {}} + return to_decision_data(states, labels, groups, optimal, meta) + + +def generate_splits(out_dir: str | Path, n_samples: int, seed: int = 0, fractions=(0.9, 0.05, 0.05), + preview: int = 50, **kw) -> dict: + data = generate(n_samples, seed=seed, **kw) + splits = split_by_group(data, fractions, seed=seed) + out = Path(out_dir) + out.mkdir(parents=True, exist_ok=True) + summary = {} + for name, d in splits.items(): + d.save(out / f"{name}.npz") + summary[name] = {"rows": len(d), "games": int(len(np.unique(d.group))), + "dropped_duplicates": d.meta.get("dropped_duplicates", 0), + "label_distribution": {a: int((d.target == i).sum()) for i, a in enumerate(ACTIONS)}} + (out / "meta.json").write_text(json.dumps({"task": "snake", **data.meta, "splits": summary}, indent=2)) + if preview: + export_jsonl(splits["train"], out / "preview.jsonl", limit=preview) + return summary + + +def export_jsonl(data: DecisionData, path: str | Path, limit: int | None = None) -> None: + """Human-readable export in the canonical {state, question, choices, target} format.""" + from minijev.tasks import ragged_take + + n = len(data) if limit is None else min(limit, len(data)) + with open(path, "w") as f: + for i in range(n): + w = int(data.state["width"][i]) + cells, _ = ragged_take(data.state["body"], data.state["body_offsets"], np.array([i])) + food = int(data.state["food"][i]) + state = {"height": int(data.state["height"][i]), "width": w, + "body": [list(divmod(int(c), w)) for c in cells], + "food": list(divmod(food, w)) if food >= 0 else None, + "direction": ACTIONS[int(data.state["direction"][i])]} + choices = data.row_choices(i) + f.write(json.dumps({"state": state, "question": data.questions[data.question_idx[i]], + "choices": choices, "target": choices[data.target[i]]}) + "\n") + + +def collect_with_policy(policy_probs, n_samples: int, seed: int = 0, board_sizes=(10,), keep_prob: float = 0.2, + explore_eps: float = 0.0, env_cfg: dict | None = None, parallel: int = 64, + game_id_base: int = 0) -> DecisionData: + """DAgger collection: the *student* drives (`policy_probs(states) -> (B, 4) probs`), + the oracle labels every kept state. Games run `parallel` at a time for batched inference.""" + rng = np.random.default_rng(seed) + oracle = make_agent("oracle") + states, labels, groups, optimal = [], [], [], [] + next_game = 0 + + def spawn(): + nonlocal next_game + size = int(board_sizes[next_game % len(board_sizes)]) + cfg = SnakeConfig.from_dict({**(env_cfg or {}), "height": size, "width": size}) + env = SnakeEnv(cfg, seed=int(rng.integers(2**31))) + env.gid = game_id_base + next_game + next_game += 1 + return env + + envs = [spawn() for _ in range(parallel)] + while len(states) < n_samples: + cur = [e.state() for e in envs] + probs = policy_probs(cur) + for i, (env, s) in enumerate(zip(envs, cur)): + if rng.random() < keep_prob and len(states) < n_samples: + label, good, _ = oracle.analyze(s) + states.append(s) + labels.append(label) + groups.append(env.gid) + optimal.append(good) + if rng.random() < explore_eps: + safe = safe_moves(s) or list(ACTIONS) + action = safe[int(rng.integers(len(safe)))] + else: + action = ACTIONS[int(probs[i].argmax())] + env.step(action) + if env.done: + envs[i] = spawn() + return to_decision_data(states, labels, groups, optimal, + {"generator": "dagger", "keep_prob": keep_prob, "seed": seed}) diff --git a/code/environments/snake/demo/__init__.py b/code/environments/snake/demo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code/environments/snake/demo/server.py b/code/environments/snake/demo/server.py new file mode 100644 index 0000000000000000000000000000000000000000..8b1459c8e9eeef3b2c747299a0231d8cfe11698c --- /dev/null +++ b/code/environments/snake/demo/server.py @@ -0,0 +1,184 @@ +"""Snake demo: a background thread plays the game, the browser renders snapshots. + +Stdlib only (http.server). The simulation runs independently of rendering, so +"max" speed is limited by the agent, not by the browser. + + minijev snake demo --model runs/.../final.onnx + minijev snake play # you play with the arrow keys +""" +from __future__ import annotations + +import json +import threading +import time +import webbrowser +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +from ..agents import AGENTS, make_agent +from ..env import ACTIONS, OPPOSITE, SnakeConfig, SnakeEnv + +STATIC = Path(__file__).parent / "static" +SPEEDS = {"realtime": 8.0, "fast": 60.0, "max": None} +QUESTION = "Choose the next move" + + +class Session: + def __init__(self, model: str | None, board_size: int, agent: str): + self.lock = threading.Lock() + self.decider = None + if model: + from minijev.inference.runtime import MiniJEV + self.decider = MiniJEV.load(model, threads=1) + self.model_path = model + self.board_size = board_size + self.agent_name = agent if (agent != "minijev" or self.decider) else "oracle" + self.agent = None if self.agent_name in ("minijev", "human") else make_agent(self.agent_name) + self.speed = "realtime" + self.seed = 1 + self.env = SnakeEnv(SnakeConfig.from_dict({"board_size": board_size}), seed=self.seed) + self.human_dir = self.env.direction + self.last = {"choice": None, "scores": {}, "confidence": None, "latency_ms": None} + self.lat_avg = None + self.games: list[int] = [] + self.best = 0 + self.last_end = None + self.steps_total = 0 + self.rate_t, self.rate_n, self.sim_rate = time.perf_counter(), 0, 0.0 + self.pause_until = 0.0 + self.running = True + + # ------------------------------------------------------------- control + def control(self, msg: dict) -> None: + with self.lock: + if msg.get("speed") in SPEEDS: + self.speed = msg["speed"] + if "agent" in msg: + a = msg["agent"] + if a == "minijev" and not self.decider: + pass + elif a in AGENTS or a in ("minijev", "human"): + self.agent_name = a + self.agent = None if a in ("minijev", "human") else make_agent(a) + self._reset(clear_stats=True) + if msg.get("key") in ACTIONS: + k = msg["key"] + if not (len(self.env.body) > 1 and k == OPPOSITE[self.env.direction]): + self.human_dir = k + if msg.get("reset"): + self._reset() + if "board_size" in msg: + self.board_size = int(msg["board_size"]) + self._reset(clear_stats=True) + + def _reset(self, clear_stats: bool = False): + self.seed += 1 + self.env = SnakeEnv(SnakeConfig.from_dict({"board_size": self.board_size}), seed=self.seed) + self.human_dir = self.env.direction + if clear_stats: + self.games, self.best = [], 0 + + # ----------------------------------------------------------------- loop + def decide(self): + s = self.env.state() + t = time.perf_counter() + if self.agent_name == "minijev": + task = self.decider.task + d = self.decider.decide(s, QUESTION, list(task.default_choices)) + choice, conf = task.action_of(d.choice), d.confidence + scores = {task.action_of(k): v for k, v in d.scores.items()} + elif self.agent_name == "human": + choice, scores, conf = self.human_dir, {a: float(a == self.human_dir) for a in ACTIONS}, None + else: + choice = self.agent.act(s) + scores, conf = {a: float(a == choice) for a in ACTIONS}, None + lat = (time.perf_counter() - t) * 1000 + self.lat_avg = lat if self.lat_avg is None else 0.9 * self.lat_avg + 0.1 * lat + self.last = {"choice": choice, "scores": scores, "confidence": conf, "latency_ms": lat} + return choice + + def run(self): + while self.running: + now = time.perf_counter() + if now < self.pause_until: + time.sleep(0.02) + continue + with self.lock: + choice = self.decide() + self.env.step(choice) + self.steps_total += 1 + self.rate_n += 1 + if self.env.done: + self.games.append(self.env.score) + self.best = max(self.best, self.env.score) + self.last_end = {"score": self.env.score, "reason": self.env.end_reason, "steps": self.env.steps} + self._reset() + if self.speed != "max": + self.pause_until = time.perf_counter() + 0.8 + if now - self.rate_t > 0.5: + self.sim_rate = self.rate_n / (now - self.rate_t) + self.rate_t, self.rate_n = now, 0 + speed = SPEEDS[self.speed] if self.agent_name != "human" else min(SPEEDS[self.speed] or 12, 12) + if speed: + time.sleep(max(0.0, 1.0 / speed - (time.perf_counter() - now))) + else: + time.sleep(0) # yield to the HTTP threads + + def snapshot(self) -> dict: + with self.lock: + s = self.env.state() + g = self.games + return {"height": s.height, "width": s.width, "body": s.body, "food": s.food, "direction": s.direction, + "score": self.env.score, "step": self.env.steps, "agent": self.agent_name, "speed": self.speed, + "decision": self.last, "latency_avg_ms": self.lat_avg, "sim_steps_per_sec": self.sim_rate, + "games_played": len(g), "avg_score": sum(g) / len(g) if g else None, "best_score": self.best, + "last_game": self.last_end, "has_model": self.decider is not None, + "model": Path(self.model_path).name if self.model_path else None, + "agents": ["minijev"] * bool(self.decider) + list(AGENTS) + ["human"]} + + +def serve(model: str | None = None, board_size: int = 10, port: int = 8765, agent: str = "minijev", + open_browser: bool = True): + session = Session(model, board_size, agent) + threading.Thread(target=session.run, daemon=True).start() + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def _send(self, body: bytes, ctype: str, code: int = 200): + self.send_response(code) + self.send_header("Content-Type", ctype) + self.send_header("Cache-Control", "no-store") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + if self.path.startswith("/api/state"): + self._send(json.dumps(session.snapshot()).encode(), "application/json") + elif self.path in ("/", "/index.html"): + self._send((STATIC / "index.html").read_bytes(), "text/html; charset=utf-8") + else: + self._send(b"not found", "text/plain", 404) + + def do_POST(self): + if self.path.startswith("/api/control"): + n = int(self.headers.get("Content-Length", 0)) + session.control(json.loads(self.rfile.read(n) or b"{}")) + self._send(b"{}", "application/json") + else: + self._send(b"not found", "text/plain", 404) + + httpd = ThreadingHTTPServer(("127.0.0.1", port), Handler) + url = f"http://127.0.0.1:{port}/" + print(f"MiniJEV Snake demo on {url} (agent={session.agent_name}, model={model}) Ctrl-C to stop") + if open_browser: + threading.Timer(0.5, lambda: webbrowser.open(url)).start() + try: + httpd.serve_forever() + except KeyboardInterrupt: + pass + finally: + session.running = False + httpd.server_close() diff --git a/code/environments/snake/demo/static/index.html b/code/environments/snake/demo/static/index.html new file mode 100644 index 0000000000000000000000000000000000000000..97d8b2145016e1bd161edcf67d6d4e4a982d9a84 --- /dev/null +++ b/code/environments/snake/demo/static/index.html @@ -0,0 +1,128 @@ + + + + + +MiniJEV Snake + + + +
+ +
+

MiniJEV · Snake decision demo

+
+
Score
0
+
Step
0
+
Decision latency
–
+
Sim steps/s · FPS
–
+
Games · avg
0
+
Best
0
+
+
Question: “Choose the next move” — choice: –, + confidence –
+
+
+ + + +
+
+ + + +
+
+
+
+
+ + + diff --git a/code/environments/snake/encoder.py b/code/environments/snake/encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..4afb6a594e375d31c04e8979356d9faba3cf747d --- /dev/null +++ b/code/environments/snake/encoder.py @@ -0,0 +1,13 @@ +"""SnakeStateEncoder: the Snake board (8 channels, see task.py) -> core tokens. + +A thin, Snake-specific configuration of the generic GridStateEncoder: the Snake +featurisation lives in `task.encode_grid`, the learnable part is generic. +""" +from minijev.encoders.grid import GridStateEncoder + +from .task import N_CHANNELS + + +class SnakeStateEncoder(GridStateEncoder): + def __init__(self, d: int, in_channels: int = N_CHANNELS, **kw): + super().__init__(d, in_channels=in_channels, **kw) diff --git a/code/environments/snake/env.py b/code/environments/snake/env.py new file mode 100644 index 0000000000000000000000000000000000000000..108040ccb9a8058433465a256cce94457e72a590 --- /dev/null +++ b/code/environments/snake/env.py @@ -0,0 +1,222 @@ +"""Headless, deterministic Snake. + +Cells are flattened indices `r * width + c`. The body is stored head-first in a +deque plus a bytearray occupancy grid, so a step is O(1) and thousands of games +run without any rendering. +""" +from __future__ import annotations + +from collections import deque +from dataclasses import dataclass, field + +import numpy as np + +ACTIONS = ("UP", "DOWN", "LEFT", "RIGHT") +DELTAS = {"UP": (-1, 0), "DOWN": (1, 0), "LEFT": (0, -1), "RIGHT": (0, 1)} +OPPOSITE = {"UP": "DOWN", "DOWN": "UP", "LEFT": "RIGHT", "RIGHT": "LEFT"} + + +@dataclass +class RewardConfig: + food: float = 1.0 + death: float = -1.0 + step: float = 0.0 # small survival bonus; keep tiny, starvation limit prevents stalling exploits + win: float = 1.0 + + @classmethod + def from_dict(cls, d: dict | None) -> "RewardConfig": + return cls(**(d or {})) + + +@dataclass +class SnakeConfig: + height: int = 10 + width: int = 10 + initial_length: int = 3 + # "die": reversing into the neck is a collision (every choice has a distinct outcome) + # "ignore": reversal keeps the current heading (classic arcade behaviour) + reverse_action: str = "die" + starvation_steps: int | None = None # None -> 2 * area + max_steps: int | None = None + reward: RewardConfig = field(default_factory=RewardConfig) + + @classmethod + def from_dict(cls, d: dict | None) -> "SnakeConfig": + d = dict(d or {}) + board = d.pop("board_size", None) + if board is not None: + d["height"] = d["width"] = int(board) + d["reward"] = RewardConfig.from_dict(d.get("reward")) + return cls(**d) + + @property + def starvation_limit(self) -> int: + return self.starvation_steps or 2 * self.height * self.width + + +@dataclass +class SnakeState: + """Immutable-ish snapshot, the `state` MiniJEV receives for Snake.""" + height: int + width: int + body: list[tuple[int, int]] # head first + food: tuple[int, int] | None + direction: str + steps_since_food: int = 0 + + def to_dict(self) -> dict: + return {"height": self.height, "width": self.width, "body": [list(p) for p in self.body], + "food": list(self.food) if self.food else None, "direction": self.direction, + "steps_since_food": self.steps_since_food} + + @classmethod + def from_dict(cls, d: dict) -> "SnakeState": + return cls(d["height"], d["width"], [tuple(p) for p in d["body"]], + tuple(d["food"]) if d.get("food") else None, d["direction"], d.get("steps_since_food", 0)) + + +class SnakeEnv: + def __init__(self, config: SnakeConfig | None = None, seed: int | None = None): + self.cfg = config or SnakeConfig() + self.h, self.w = self.cfg.height, self.cfg.width + self.area = self.h * self.w + self.rng = np.random.default_rng(seed) + self.body: deque[int] = deque() + self.occ = bytearray(self.area) + self.reset() + + # ------------------------------------------------------------------ core + def seed(self, seed: int) -> None: + self.rng = np.random.default_rng(seed) + + def reset(self, seed: int | None = None) -> SnakeState: + if seed is not None: + self.seed(seed) + self.body.clear() + self.occ = bytearray(self.area) + self.direction = ACTIONS[int(self.rng.integers(4))] + dr, dc = DELTAS[self.direction] + L = min(self.cfg.initial_length, min(self.h, self.w) // 2) + # place head so the body (trailing behind it) fits on the board + r = int(self.rng.integers(L, self.h - L)) if self.h > 2 * L else self.h // 2 + c = int(self.rng.integers(L, self.w - L)) if self.w > 2 * L else self.w // 2 + for i in range(L): + cell = (r - dr * i) * self.w + (c - dc * i) + self.body.append(cell) + self.occ[cell] = 1 + self.score = 0 + self.steps = 0 + self.steps_since_food = 0 + self.done = False + self.end_reason: str | None = None + self._place_food() + return self.state() + + def _place_food(self) -> None: + free = self.area - len(self.body) + if free <= 0: + self.food = -1 + return + # k-th free cell, found by scanning; cheap versus rejection sampling on full boards + k = int(self.rng.integers(free)) + if free > self.area // 4: + while True: + cell = int(self.rng.integers(self.area)) + if not self.occ[cell]: + self.food = cell + return + for cell in range(self.area): + if not self.occ[cell]: + if k == 0: + self.food = cell + return + k -= 1 + + def step(self, action: str | int) -> tuple[float, bool]: + """Returns (reward, done). Call `state()` for the observation.""" + if self.done: + raise RuntimeError("step() on finished game; call reset()") + if not isinstance(action, str): + action = ACTIONS[int(action)] + if self.cfg.reverse_action == "ignore" and len(self.body) > 1 and action == OPPOSITE[self.direction]: + action = self.direction + rw = self.cfg.reward + dr, dc = DELTAS[action] + head = self.body[0] + r, c = divmod(head, self.w) + nr, nc = r + dr, c + dc + self.direction = action + self.steps += 1 + self.steps_since_food += 1 + if not (0 <= nr < self.h and 0 <= nc < self.w): + return self._finish("wall", rw.death) + cell = nr * self.w + nc + eating = cell == self.food + tail = self.body[-1] + if self.occ[cell] and not (cell == tail and not eating): + return self._finish("body", rw.death) + if not eating: + self.body.pop() + self.occ[tail] = 0 + self.body.appendleft(cell) + self.occ[cell] = 1 + reward = rw.step + if eating: + self.score += 1 + self.steps_since_food = 0 + reward += rw.food + if len(self.body) == self.area: + return self._finish("win", reward + rw.win) + self._place_food() + if self.steps_since_food >= self.cfg.starvation_limit: + return self._finish("starvation", rw.death) + if self.cfg.max_steps and self.steps >= self.cfg.max_steps: + self.done, self.end_reason = True, "max_steps" + return reward, True + return reward, False + + def _finish(self, reason: str, reward: float) -> tuple[float, bool]: + self.done, self.end_reason = True, reason + return reward, True + + # --------------------------------------------------------------- views + def state(self) -> SnakeState: + w = self.w + return SnakeState(self.h, self.w, [divmod(b, w) for b in self.body], + divmod(self.food, w) if self.food >= 0 else None, + self.direction, self.steps_since_food) + + def render_ascii(self) -> str: + grid = [["." for _ in range(self.w)] for _ in range(self.h)] + for i, b in enumerate(self.body): + r, c = divmod(b, self.w) + grid[r][c] = "H" if i == 0 else "o" + if self.food >= 0: + r, c = divmod(self.food, self.w) + grid[r][c] = "*" + return "\n".join("".join(row) for row in grid) + + +class VectorSnakeEnv: + """N independent games stepped together (auto-reset); used for batched + inference in RL/evaluation. Deterministic given `seed`.""" + + def __init__(self, n: int, config: SnakeConfig | None = None, seed: int = 0): + self.envs = [SnakeEnv(config, seed=seed + i) for i in range(n)] + self.next_seed = seed + n + self.n = n + + def states(self) -> list[SnakeState]: + return [e.state() for e in self.envs] + + def step(self, actions) -> tuple[np.ndarray, np.ndarray, list[dict]]: + rewards = np.zeros(self.n, dtype=np.float32) + dones = np.zeros(self.n, dtype=bool) + infos: list[dict] = [{} for _ in range(self.n)] + for i, (env, a) in enumerate(zip(self.envs, actions)): + rewards[i], dones[i] = env.step(a) + if dones[i]: + infos[i] = {"score": env.score, "steps": env.steps, "end_reason": env.end_reason} + env.reset(seed=self.next_seed) + self.next_seed += 1 + return rewards, dones, infos diff --git a/code/environments/snake/evaluate.py b/code/environments/snake/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..68ff37cd48bd85fad3e3e23e8d7fa9500c416a7c --- /dev/null +++ b/code/environments/snake/evaluate.py @@ -0,0 +1,101 @@ +"""Play full Snake games with any policy and report game-level metrics.""" +from __future__ import annotations + +import time +from typing import Callable, Sequence + +import numpy as np + +from .agents import Agent, make_agent, safe_moves +from .env import ACTIONS, SnakeConfig, SnakeEnv, SnakeState + +BatchPolicy = Callable[[Sequence[SnakeState]], Sequence[str]] + + +def agent_policy(agent: Agent) -> BatchPolicy: + return lambda states: [agent.act(s) for s in states] + + +def model_policy(decider, question: str = "Choose the next move", choices=None) -> BatchPolicy: + """Greedy MiniJEV policy; choices default to the model's own labels (legacy "UP" or "move up").""" + task = decider.task + choices = list(choices) if choices is not None else list(task.default_choices) + actions = [task.action_of(c) for c in choices] + + def policy(states): + probs = decider.probs(states, question, choices) + return [actions[i] for i in probs.argmax(1)] + return policy + + +def play_games(policy: BatchPolicy, n_games: int = 100, env_cfg: dict | None = None, seed: int = 12345, + parallel: int = 64, max_decisions: int | None = None) -> dict: + """Run `n_games` complete games (`parallel` at a time, batched decisions). + + Game seeds are fixed (seed + i), so all agents are compared on identical games. + """ + cfg = SnakeConfig.from_dict(env_cfg) + results = [] + next_game = 0 + active: list[SnakeEnv] = [] + fatal = decisions = 0 + t0 = time.perf_counter() + policy_time = 0.0 + + def spawn(): + nonlocal next_game + env = SnakeEnv(cfg, seed=seed + next_game) + next_game += 1 + return env + + while next_game < min(parallel, n_games): + active.append(spawn()) + while active: + states = [e.state() for e in active] + tp = time.perf_counter() + actions = policy(states) + policy_time += time.perf_counter() - tp + still = [] + for env, s, a in zip(active, states, actions): + decisions += 1 + if a not in safe_moves(s): + fatal += 1 + env.step(a) + if env.done: + results.append({"score": env.score, "steps": env.steps, "end": env.end_reason}) + if next_game < n_games: + still.append(spawn()) + else: + still.append(env) + active = still + if max_decisions and decisions >= max_decisions: + break + wall = time.perf_counter() - t0 + scores = np.array([r["score"] for r in results]) if results else np.zeros(1) + steps = np.array([r["steps"] for r in results]) if results else np.zeros(1) + ends: dict[str, int] = {} + for r in results: + ends[r["end"]] = ends.get(r["end"], 0) + 1 + n = max(1, len(results)) + return { + "games": len(results), + "board": f"{cfg.height}x{cfg.width}", + "avg_score": float(scores.mean()), "median_score": float(np.median(scores)), + "max_score": int(scores.max()), "min_score": int(scores.min()), + "avg_survival_steps": float(steps.mean()), "food_collected": int(scores.sum()), + "max_possible_score": cfg.height * cfg.width - cfg.initial_length, + "win_rate": ends.get("win", 0) / n, + "death_rate": (ends.get("wall", 0) + ends.get("body", 0)) / n, # collisions + "starvation_rate": ends.get("starvation", 0) / n, + "end_reasons": ends, + "decisions": decisions, + "fatal_move_rate": fatal / max(1, decisions), # chose a move that dies immediately + "policy_seconds": round(policy_time, 3), + "wall_seconds": round(wall, 3), + } + + +def baseline_suite(n_games: int = 100, env_cfg: dict | None = None, seed: int = 12345, + agents: Sequence[str] = ("random", "greedy", "bfs", "survival", "oracle")) -> dict: + return {name: play_games(agent_policy(make_agent(name, seed)), n_games, env_cfg, seed, parallel=1) + for name in agents} diff --git a/code/environments/snake/rl.py b/code/environments/snake/rl.py new file mode 100644 index 0000000000000000000000000000000000000000..2d159ae329447017f560325b4980935d4cc41508 --- /dev/null +++ b/code/environments/snake/rl.py @@ -0,0 +1,158 @@ +"""PPO fine-tuning of a supervised MiniJEV Snake policy (Phase 2). + +Rollouts: `n_envs` games stepped together, batched inference, sampled actions. +Reward comes from `env.reward` in the config (food +, death -, tiny/zero per +step). The value head is warmed up first (it was never trained by behaviour +cloning), and a KL penalty to the frozen supervised policy keeps early updates +from destroying what imitation learned. Resumable from `rl_last.pt`. +""" +from __future__ import annotations + +import copy +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from minijev.calibration.metrics import calibration_report, fit_temperature +from minijev.datasets.batching import BatchEncoder +from minijev.datasets.decision_data import DecisionData +from minijev.inference.runtime import TorchDecider +from minijev.runs import RunLogger, environment_info +from minijev.tokenizer import encode_batch +from minijev.training.ppo import gae, ppo_update +from minijev.training.supervised import make_model, predict_logits + +from .env import SnakeConfig, VectorSnakeEnv +from .evaluate import model_policy, play_games +from .task import SnakeTask + +QUESTION = SnakeTask.default_question + + +def train_ppo(cfg: dict, checkpoint: str, run_dir: str | None = None, resume: bool = False) -> dict: + rl = cfg.get("rl", {}) + seed = int(cfg.get("seed", 0)) + torch.manual_seed(seed) + torch.set_num_threads(int(rl.get("threads", 8))) + ck = torch.load(checkpoint, map_location="cpu", weights_only=False) + base_cfg = ck["config"] + task = SnakeTask(base_cfg.get("task", {})) # the checkpoint decides the choice labels + model = make_model(base_cfg, task) + model.load_state_dict(ck["model"]) + model.log_temperature.zero_() + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model.to(device) + ref = copy.deepcopy(model).eval() + for p in ref.parameters(): + p.requires_grad_(False) + + run_dir = Path(run_dir or f"runs/{cfg.get('name', 'snake')}-ppo") + log = RunLogger(run_dir, {**cfg, "init_checkpoint": checkpoint}, resume=resume) + opt = torch.optim.AdamW(model.parameters(), lr=rl.get("lr", 1e-4), weight_decay=0.0) + env_cfg = SnakeConfig.from_dict(cfg.get("env", {})) + n_envs, T = int(rl.get("n_envs", 64)), int(rl.get("rollout", 128)) + total_updates = int(rl.get("total_env_steps", 1_000_000)) // (n_envs * T) + start, best = 0, -1.0 + last_ck = run_dir / "checkpoints" / "rl_last.pt" + if resume and last_ck.exists(): + st = torch.load(last_ck, weights_only=False) + model.load_state_dict(st["model"]) + opt.load_state_dict(st["optimizer"]) + start, best = st["update"], st["best"] + print(f"[rl] resumed at update {start}") + envs = VectorSnakeEnv(n_envs, env_cfg, seed=seed * 7919 + start * n_envs) + mcfg = base_cfg["model"] + q = torch.as_tensor(encode_batch([QUESTION], mcfg.get("max_question_len", 32)), device=device).repeat(n_envs, 1) + c = torch.as_tensor(encode_batch(list(task.default_choices), mcfg.get("max_choice_len", 16)), + device=device)[None].repeat(n_envs, 1, 1) + gamma, lam = rl.get("gamma", 0.99), rl.get("gae_lambda", 0.95) + warm = int(rl.get("value_warmup_updates", 5)) + eval_every = int(rl.get("eval_every", 10)) + log.write_json("env.json", {"env": environment_info(), "updates": total_updates, "n_envs": n_envs, "rollout": T}) + ep_scores: list[int] = [] + t0 = time.time() + print(f"[rl] PPO: {total_updates} updates x {n_envs * T} steps, reward={cfg.get('env', {}).get('reward')}") + for upd in range(start, total_updates): + obs, acts, logps, vals, rews, dns = [], [], [], [], [], [] + model.eval() + for _ in range(T): + x = torch.as_tensor(task.encode_states(envs.states())["state_grid"], device=device) + with torch.no_grad(): + out = model({"state_grid": x}, q, c) + dist = torch.distributions.Categorical(logits=out["logits"]) + a = dist.sample() + r, d, infos = envs.step(a.cpu().tolist()) + ep_scores += [i["score"] for i in infos if i] + obs.append(x) + acts.append(a) + logps.append(dist.log_prob(a)) + vals.append(out["value"].cpu()) + rews.append(r) + dns.append(d.astype(np.float32)) + with torch.no_grad(): + x = torch.as_tensor(task.encode_states(envs.states())["state_grid"], device=device) + last_v = model({"state_grid": x}, q, c)["value"].cpu().numpy() + V = torch.stack(vals).numpy() + adv, ret = gae(np.stack(rews), V, np.stack(dns), last_v, gamma, lam) + adv_t = torch.as_tensor(adv.reshape(-1), device=device) + data = {"state": {"state_grid": torch.cat(obs)}, "question_ids": q.repeat(T, 1), + "choice_ids": c.repeat(T, 1, 1), "actions": torch.cat(acts), "old_logp": torch.cat(logps), + "adv": (adv_t - adv_t.mean()) / (adv_t.std() + 1e-8), "ret": torch.as_tensor(ret.reshape(-1), device=device)} + stats = ppo_update(model, opt, data, rl, ref_model=ref, policy_coef=0.0 if upd < warm else 1.0) + recent = ep_scores[-200:] + log.log(upd + 1, env_steps=(upd + 1) * n_envs * T, train_avg_score=float(np.mean(recent)) if recent else 0.0, + episodes=len(ep_scores), **{k: round(v, 5) for k, v in stats.items()}) + print(f" update {upd + 1}/{total_updates} | sampled-policy avg score {np.mean(recent) if recent else 0:.1f} " + f"| entropy {stats['entropy']:.3f} kl_ref {stats['kl_ref']:.4f} vf {stats['vf']:.4f} " + f"| {time.time() - t0:.0f}s", flush=True) + if (upd + 1) % eval_every == 0 or upd + 1 == total_updates: + dec = TorchDecider(model=model, cfg=base_cfg, device=str(device)) + g = play_games(model_policy(dec), int(rl.get("eval_games", 100)), cfg.get("env", {}), seed=777) + log.log(upd + 1, eval_avg_score=g["avg_score"], eval_fatal=g["fatal_move_rate"]) + print(f" [eval] greedy avg score {g['avg_score']:.2f} median {g['median_score']} " + f"fatal-move {g['fatal_move_rate']:.4%}", flush=True) + if g["avg_score"] > best: + best = g["avg_score"] + model.to(device) # TorchDecider may have moved it + torch.save({"model": model.state_dict(), "config": base_cfg, "update": upd + 1, "eval": g}, + run_dir / "checkpoints" / "rl_best.pt") + torch.save({"model": model.state_dict(), "optimizer": opt.state_dict(), "update": upd + 1, + "best": best}, last_ck) + return finalize_rl(cfg, base_cfg, run_dir, log) + + +def finalize_rl(cfg, base_cfg, run_dir: Path, log) -> dict: + """Re-calibrate the best RL policy on the validation split and evaluate it.""" + task = SnakeTask(base_cfg.get("task", {})) + best = torch.load(run_dir / "checkpoints" / "rl_best.pt", weights_only=False) + model = make_model(base_cfg, task) + model.load_state_dict(best["model"]) + data_dir = Path(base_cfg["data"]["dir"]) + mc = base_cfg["model"] + kw = dict(max_question_len=mc.get("max_question_len", 32), max_choice_len=mc.get("max_choice_len", 16)) + val = BatchEncoder(DecisionData.load(data_dir / "val.npz"), task, **kw) + test = BatchEncoder(DecisionData.load(data_dir / "test.npz"), task, **kw) + vl, vt = predict_logits(model, val, "cpu") + tl, tt = predict_logits(model, test, "cpu") + T = fit_temperature(vl, vt) + model.log_temperature.fill_(float(np.log(T))) + acc_ok = test.data.soft > 0 if test.data.soft is not None else None + rep = calibration_report(tl, tt, T, acceptable=acc_ok) + torch.save({"model": model.state_dict(), "config": base_cfg, "temperature": T}, run_dir / "checkpoints" / "final.pt") + games = play_games(model_policy(TorchDecider(run_dir / "checkpoints" / "final.pt", threads=4)), + cfg.get("eval", {}).get("games", 200), cfg.get("env", {})) + (run_dir / "games.json").write_text(json.dumps(games, indent=2)) + summary = {"params": model.num_parameters(), "temperature": T, "test_calibrated": rep, + "test_raw": calibration_report(tl, tt, 1.0, acceptable=acc_ok), "games": games, + "final_checkpoint": str(run_dir / "checkpoints" / "final.pt")} + log.write_json("summary.json", summary) + log.close() + print(f"[rl] final: avg score {games['avg_score']:.2f} | oracle-agreement {rep['accuracy']:.4f} " + f"| ECE vs oracle {rep['ece']:.4f} (T={T:.3f})") + return summary + + +__all__ = ["train_ppo"] diff --git a/code/environments/snake/task.py b/code/environments/snake/task.py new file mode 100644 index 0000000000000000000000000000000000000000..4de1629e4e3f1559dcd40e977abb2d3e011fa918 --- /dev/null +++ b/code/environments/snake/task.py @@ -0,0 +1,124 @@ +"""Snake as a MiniJEV task: SnakeState -> multi-channel board image. + +Channels (board padded by a 1-cell wall border; smaller boards in a batch are +padded with more wall, which is semantically exact): + + 0 wall 1 head 2 body (excl. head) 3 tail 4 food + 5 time-until-free: (L - i) / area for body segment i (head=0) + 6 row offset from the head (r - r_head) / max(H, W) + 7 col offset from the head (c - c_head) / max(H, W) + +Channel 5 lets the model reason about which cells will open up as the snake +moves - the same information the oracle's time-aware search uses. Channels 6-7 +make every cell egocentric ("the food is 3 up, 2 left"), which removes the +long learning plateau of discovering relative geometry from absolute positions. +""" +from __future__ import annotations + +from typing import Sequence + +import numpy as np + +from minijev.tasks import Task, ragged_pack, ragged_take + +from .env import ACTIONS, SnakeState + +N_CHANNELS = 8 +DIRS = {a: i for i, a in enumerate(ACTIONS)} + + +SEMANTIC_CHOICES = {"UP": "move up", "DOWN": "move down", "LEFT": "move left", "RIGHT": "move right"} + + +class SnakeTask(Task): + """task.choice_style: "semantic" -> choices "move up/down/left/right" (v2 models); + "legacy" (default, what pre-v2 checkpoints were trained with) -> "UP/DOWN/LEFT/RIGHT".""" + + name = "snake" + state_encoder = "grid" + default_question = "Choose the next move" + + @property + def choice_alias(self) -> dict[str, str]: + return SEMANTIC_CHOICES if self.cfg.get("choice_style", "legacy") == "semantic" else {} + + @property + def default_choices(self) -> tuple[str, ...]: + return tuple(self.model_label(a) for a in ACTIONS) + + def encoder_class(self): + from .encoder import SnakeStateEncoder + return SnakeStateEncoder + + def encoder_config(self) -> dict: + return {"in_channels": N_CHANNELS} + + def states_to_arrays(self, states: Sequence[SnakeState]) -> dict[str, np.ndarray]: + bodies = [[r * s.width + c for r, c in s.body] for s in states] + flat, offsets = ragged_pack(bodies, np.int16) + return { + "body": flat, + "body_offsets": offsets, + "food": np.array([s.food[0] * s.width + s.food[1] if s.food else -1 for s in states], np.int16), + "height": np.array([s.height for s in states], np.uint8), + "width": np.array([s.width for s in states], np.uint8), + "direction": np.array([DIRS[s.direction] for s in states], np.uint8), + } + + def example_states(self, n=4, seed=0): + from .agents import OracleAgent + from .env import SnakeConfig, SnakeEnv + + states, oracle = [], OracleAgent() + env = SnakeEnv(SnakeConfig.from_dict({"board_size": self.cfg.get("board_size", 10)}), seed=seed) + while len(states) < n: + states.append(env.state()) + for _ in range(7): # spread samples along the game + env.step(oracle.act(env.state())) + if env.done: + env.reset() + return states + + def encode_arrays(self, arrays, idx): + return {"state_grid": encode_grid(arrays, np.asarray(idx))} + + +def encode_grid(arrays: dict[str, np.ndarray], idx: np.ndarray) -> np.ndarray: + B = len(idx) + hs = arrays["height"][idx].astype(np.int64) + ws = arrays["width"][idx].astype(np.int64) + H, W = int(hs.max()) + 2, int(ws.max()) + 2 + x = np.zeros((B, N_CHANNELS, H, W), dtype=np.float32) + x[:, 0] = 1.0 + for h, w in set(zip(hs.tolist(), ws.tolist())): + sel = np.nonzero((hs == h) & (ws == w))[0] + x[sel, 0, 1:h + 1, 1:w + 1] = 0.0 + + cells, lengths = ragged_take(arrays["body"], arrays["body_offsets"], idx) + cells = cells.astype(np.int64) + sample = np.repeat(np.arange(B), lengths) + pos = np.arange(len(cells)) - np.repeat(np.cumsum(lengths) - lengths, lengths) # index from head + Ls = np.repeat(lengths, lengths) + w_s = ws[sample] + r, c = cells // w_s + 1, cells % w_s + 1 + head = pos == 0 + x[sample[head], 1, r[head], c[head]] = 1.0 + x[sample[~head], 2, r[~head], c[~head]] = 1.0 + tail = pos == Ls - 1 + x[sample[tail], 3, r[tail], c[tail]] = 1.0 + x[sample, 5, r, c] = (Ls - pos) / (hs[sample] * w_s) + + hr, hc = np.zeros(B, np.int64), np.zeros(B, np.int64) + hr[sample[head]], hc[sample[head]] = r[head], c[head] + scale = np.maximum(hs, ws).astype(np.float32)[:, None, None] + x[:, 6] = (np.arange(H)[None, :, None] - hr[:, None, None]) / scale + x[:, 7] = (np.arange(W)[None, None, :] - hc[:, None, None]) / scale + + food = arrays["food"][idx].astype(np.int64) + has = np.nonzero(food >= 0)[0] + x[has, 4, food[has] // ws[has] + 1, food[has] % ws[has] + 1] = 1.0 + return x + + +def make_task(cfg: dict) -> SnakeTask: + return SnakeTask(cfg) diff --git a/code/minijev/__init__.py b/code/minijev/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5ae7c542c51b3471093eb671a836fe42ec6f05de --- /dev/null +++ b/code/minijev/__init__.py @@ -0,0 +1,14 @@ +"""MiniJEV: a tiny, general decision model (state + question + choices -> calibrated choice).""" +from minijev.types import BooleanDecision, Decision, DecisionRequest + +__version__ = "0.1.0" + + +def __getattr__(name): # lazy: `import minijev` must not pull in torch/onnxruntime + if name == "MiniJEV": + from minijev.inference.runtime import MiniJEV + return MiniJEV + raise AttributeError(name) + + +__all__ = ["MiniJEV", "BooleanDecision", "Decision", "DecisionRequest", "__version__"] diff --git a/code/minijev/__pycache__/__init__.cpython-314.pyc b/code/minijev/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1bdff0361de7948e265bbfa63dc283b13c49b5ff Binary files /dev/null and b/code/minijev/__pycache__/__init__.cpython-314.pyc differ diff --git a/code/minijev/__pycache__/device.cpython-314.pyc b/code/minijev/__pycache__/device.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55aac519106b700cd6114f3233b5f102e866f00d Binary files /dev/null and b/code/minijev/__pycache__/device.cpython-314.pyc differ diff --git a/code/minijev/__pycache__/hub.cpython-314.pyc b/code/minijev/__pycache__/hub.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d02fa861c851af073f0b4c1ddbe892aaa08003fd Binary files /dev/null and b/code/minijev/__pycache__/hub.cpython-314.pyc differ diff --git a/code/minijev/__pycache__/keys.cpython-314.pyc b/code/minijev/__pycache__/keys.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df6ec80f7b55187ef841676c9508fa6c09545453 Binary files /dev/null and b/code/minijev/__pycache__/keys.cpython-314.pyc differ diff --git a/code/minijev/__pycache__/runs.cpython-314.pyc b/code/minijev/__pycache__/runs.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..068f8efacaf9d2ad087411ad38534053723b6909 Binary files /dev/null and b/code/minijev/__pycache__/runs.cpython-314.pyc differ diff --git a/code/minijev/__pycache__/tasks.cpython-314.pyc b/code/minijev/__pycache__/tasks.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4829f7b066b5b4cd30d8e564dfa1c1e59d3aec9f Binary files /dev/null and b/code/minijev/__pycache__/tasks.cpython-314.pyc differ diff --git a/code/minijev/__pycache__/text_task_utils.cpython-314.pyc b/code/minijev/__pycache__/text_task_utils.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7dd8e7b34a467de3f639d34dce4b562ab2a3971c Binary files /dev/null and b/code/minijev/__pycache__/text_task_utils.cpython-314.pyc differ diff --git a/code/minijev/__pycache__/tokenizer.cpython-314.pyc b/code/minijev/__pycache__/tokenizer.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a001f2be380d3ac28f029677e2dab246adec582 Binary files /dev/null and b/code/minijev/__pycache__/tokenizer.cpython-314.pyc differ diff --git a/code/minijev/__pycache__/tokenizers.cpython-314.pyc b/code/minijev/__pycache__/tokenizers.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b184e8b33445542484116f484b44b35f2ae0f2cf Binary files /dev/null and b/code/minijev/__pycache__/tokenizers.cpython-314.pyc differ diff --git a/code/minijev/__pycache__/types.cpython-314.pyc b/code/minijev/__pycache__/types.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74b740b061ac2b69ca1fb824c7cec7d1ca8b3e18 Binary files /dev/null and b/code/minijev/__pycache__/types.cpython-314.pyc differ diff --git a/code/minijev/benchmark/__init__.py b/code/minijev/benchmark/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code/minijev/benchmark/perf.py b/code/minijev/benchmark/perf.py new file mode 100644 index 0000000000000000000000000000000000000000..c6e021404cd9a7d81b8f32553a96cc55c4f115f6 --- /dev/null +++ b/code/minijev/benchmark/perf.py @@ -0,0 +1,131 @@ +"""Inference performance: latency percentiles, max throughput, paced-rate CPU/RAM cost. + +Latency is end-to-end `decide()` (state encoding + tokenisation + model), the +number an embedding application actually pays. Max throughput is measured +unthrottled; the paced tests (1..1000 decisions/s) show what a given decision +rate costs in CPU, which is what matters when MiniJEV lives inside other software. +""" +from __future__ import annotations + +import os +import time +from pathlib import Path + +import numpy as np +import psutil + + +def _pct(xs: list[float]) -> dict: + a = np.array(xs) * 1000 + return {"p50_ms": round(float(np.percentile(a, 50)), 4), "p95_ms": round(float(np.percentile(a, 95)), 4), + "p99_ms": round(float(np.percentile(a, 99)), 4), "mean_ms": round(float(a.mean()), 4)} + + +def latency(decider, states, question, choices, n: int = 2000, warmup: int = 100) -> dict: + for i in range(warmup): + decider.decide(states[i % len(states)], question, choices) + xs = [] + for i in range(n): + t = time.perf_counter() + decider.decide(states[i % len(states)], question, choices) + xs.append(time.perf_counter() - t) + # model-only latency (pre-encoded input), to separate pre-processing cost + enc = [decider.encode([s]) for s in states[:64]] + ys = [] + for i in range(n): + t = time.perf_counter() + decider.probs(None, question, choices, encoded=enc[i % len(enc)]) + ys.append(time.perf_counter() - t) + return {"end_to_end": _pct(xs), "model_only": _pct(ys), + "max_decisions_per_sec_batch1": round(1.0 / float(np.mean(xs)), 1)} + + +def batched_throughput(decider, states, question, choices, batch: int = 64, seconds: float = 3.0) -> dict: + enc = decider.encode(states[:batch]) + decider.probs(None, question, choices, encoded=enc) + n, t0 = 0, time.perf_counter() + while time.perf_counter() - t0 < seconds: + decider.probs(None, question, choices, encoded=enc) + n += len(enc) + return {"batch": len(enc), "decisions_per_sec": round(n / (time.perf_counter() - t0), 1)} + + +def paced(decider, states, question, choices, rate: float, seconds: float = 3.0) -> dict: + """Issue decisions at a fixed rate; measure achieved rate, latency and process CPU.""" + proc = psutil.Process(os.getpid()) + period = 1.0 / rate + n_target = max(3, int(rate * seconds)) + lat = [] + proc.cpu_percent(None) + cpu_t0 = proc.cpu_times() + t0 = time.perf_counter() + next_t = t0 + for i in range(n_target): + now = time.perf_counter() + if next_t > now: + time.sleep(next_t - now) + t = time.perf_counter() + decider.decide(states[i % len(states)], question, choices) + lat.append(time.perf_counter() - t) + next_t += period + wall = max(time.perf_counter() - t0, n_target * period) # a paced run lasts n_target periods + cpu_t1 = proc.cpu_times() + cpu_s = (cpu_t1.user - cpu_t0.user) + (cpu_t1.system - cpu_t0.system) + achieved = n_target / wall + return {"target_per_sec": rate, "achieved_per_sec": round(achieved, 1), + "sustained": achieved >= 0.95 * rate, **_pct(lat), + "cpu_percent_of_one_core": round(100 * cpu_s / wall, 1), + "rss_mb": round(proc.memory_info().rss / 2**20, 1)} + + +def benchmark_decider(path: str | Path, task=None, threads: int = 1, rates=(1, 10, 100, 500, 1000), + n_latency: int = 2000, quick: bool = False) -> dict: + from minijev.inference.runtime import MiniJEV + + proc = psutil.Process(os.getpid()) + rss0 = proc.memory_info().rss + dec = MiniJEV.load(path, threads=threads) + rss1 = proc.memory_info().rss + task = task or dec.task + states = task.example_states(256, seed=3) + q, ch = task.default_question, list(task.default_choices) + res = {"model": str(path), "file_size_mb": round(Path(path).stat().st_size / 2**20, 3), "threads": threads, + "model_load_rss_mb": round((rss1 - rss0) / 2**20, 1)} + if hasattr(dec, "model"): + res["params"] = dec.model.num_parameters() + elif hasattr(dec, "meta"): + res["params"] = dec.meta.get("params") + res["latency"] = latency(dec, states, q, ch, n=200 if quick else n_latency) + res["batched"] = batched_throughput(dec, states, q, ch, seconds=1.0 if quick else 3.0) + max_rate = res["latency"]["max_decisions_per_sec_batch1"] + res["paced"] = [] + for r in rates: + secs = 2.0 if quick else (5.0 if r <= 10 else 3.0) + if r > 1.5 * max_rate: + res["paced"].append({"target_per_sec": r, "achieved_per_sec": None, "sustained": False, + "note": f"above measured max ({max_rate}/s)"}) + continue + if r == 1 and quick: + secs = 3.0 + res["paced"].append(paced(dec, states, q, ch, r, secs)) + res["process_rss_mb"] = round(proc.memory_info().rss / 2**20, 1) + return res + + +def format_perf(res: dict) -> str: + L = res["latency"] + lines = [f"{res['model']} ({res['file_size_mb']} MB, params={res.get('params')}, threads={res['threads']})", + f" latency end-to-end p50 {L['end_to_end']['p50_ms']:.3f} ms p95 {L['end_to_end']['p95_ms']:.3f} ms " + f"p99 {L['end_to_end']['p99_ms']:.3f} ms", + f" latency model-only p50 {L['model_only']['p50_ms']:.3f} ms p95 {L['model_only']['p95_ms']:.3f} ms " + f"p99 {L['model_only']['p99_ms']:.3f} ms", + f" max decisions/s: batch=1 {L['max_decisions_per_sec_batch1']:,.0f} " + f"batch={res['batched']['batch']} {res['batched']['decisions_per_sec']:,.0f}", + " paced: target achieved p50ms p99ms cpu%(1 core) rss MB"] + for p in res["paced"]: + if p.get("achieved_per_sec") is None: + lines.append(f" {p['target_per_sec']:>6} -- {p['note']}") + else: + lines.append(f" {p['target_per_sec']:>6} {p['achieved_per_sec']:>8} {p['p50_ms']:>6.3f} " + f"{p['p99_ms']:>6.3f} {p['cpu_percent_of_one_core']:>12} {p['rss_mb']:>6}") + return "\n".join(lines) diff --git a/code/minijev/calibration/__init__.py b/code/minijev/calibration/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code/minijev/calibration/__pycache__/__init__.cpython-314.pyc b/code/minijev/calibration/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60126aab00a07b000f2e29f07cca6b50d18175ff Binary files /dev/null and b/code/minijev/calibration/__pycache__/__init__.cpython-314.pyc differ diff --git a/code/minijev/calibration/__pycache__/metrics.cpython-314.pyc b/code/minijev/calibration/__pycache__/metrics.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4383d8ea350ed644bbd79fbcfa778bae4ca858b Binary files /dev/null and b/code/minijev/calibration/__pycache__/metrics.cpython-314.pyc differ diff --git a/code/minijev/calibration/metrics.py b/code/minijev/calibration/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..b06647ba2de747b04b0072f29f021d081bd288f4 --- /dev/null +++ b/code/minijev/calibration/metrics.py @@ -0,0 +1,155 @@ +"""Calibration metrics and post-hoc calibrators (numpy only). + +All functions take logits of shape (n, N) where absent choices hold a very +negative value (they get probability 0), and integer targets. +""" +from __future__ import annotations + +import numpy as np + + +def softmax(logits: np.ndarray, temperature: float = 1.0) -> np.ndarray: + z = logits / temperature + z = z - z.max(1, keepdims=True) + e = np.exp(z) + return e / e.sum(1, keepdims=True) + + +def nll(probs: np.ndarray, targets: np.ndarray) -> float: + p = probs[np.arange(len(targets)), targets] + return float(-np.log(np.clip(p, 1e-12, 1.0)).mean()) + + +def brier(probs: np.ndarray, targets: np.ndarray) -> float: + """Multi-class Brier score: mean over rows of sum_k (p_k - y_k)^2 (0 = perfect, 2 = worst).""" + y = np.zeros_like(probs) + y[np.arange(len(targets)), targets] = 1.0 + return float(((probs - y) ** 2).sum(1).mean()) + + +def reliability_bins(confidence: np.ndarray, correct: np.ndarray, n_bins: int = 15) -> list[dict]: + edges = np.linspace(0.0, 1.0, n_bins + 1) + ids = np.clip(np.digitize(confidence, edges[1:-1], right=True), 0, n_bins - 1) + bins = [] + for b in range(n_bins): + m = ids == b + n = int(m.sum()) + bins.append({"lo": float(edges[b]), "hi": float(edges[b + 1]), "count": n, + "confidence": float(confidence[m].mean()) if n else None, + "accuracy": float(correct[m].mean()) if n else None}) + return bins + + +def ece(confidence: np.ndarray, correct: np.ndarray, n_bins: int = 15) -> float: + """Expected Calibration Error (top-label, equal-width bins).""" + total = len(confidence) + return float(sum(b["count"] / total * abs(b["accuracy"] - b["confidence"]) + for b in reliability_bins(confidence, correct, n_bins) if b["count"])) + + +def calibration_report(logits: np.ndarray, targets: np.ndarray, temperature: float = 1.0, + n_bins: int = 15, acceptable: np.ndarray | None = None) -> dict: + """`acceptable` (n, N) bool: choices that are also correct (e.g. equally optimal moves).""" + probs = softmax(logits, temperature) + pred = probs.argmax(1) + conf = probs.max(1) + correct = (pred == targets).astype(np.float64) + extra = {} + if acceptable is not None: + ok = acceptable[np.arange(len(pred)), pred].astype(np.float64) + extra = {"acceptable_accuracy": float(ok.mean()), + "acceptable_ece": ece(conf, ok, n_bins), + "mean_acceptable_choices": float(acceptable.sum(1).mean())} + return {**extra, + "n": int(len(targets)), + "accuracy": float(correct.mean()), + "nll": nll(probs, targets), + "brier": brier(probs, targets), + "ece": ece(conf, correct, n_bins), + "mean_confidence": float(conf.mean()), + "temperature": float(temperature), + "reliability": reliability_bins(conf, correct, n_bins), + } + + +# ------------------------------------------------------------------- calibrators +def fit_temperature(logits: np.ndarray, targets: np.ndarray, lo: float = -3.0, hi: float = 3.0, + iters: int = 60) -> float: + """Temperature scaling: argmin_T NLL(softmax(logits / T)) by golden-section search on log T. + + One scalar -> cannot overfit a validation set, preserves the argmax (accuracy + unchanged) and works for any number of choices; the natural fit for MiniJEV. + """ + f = lambda lt: nll(softmax(logits, float(np.exp(lt))), targets) # noqa: E731 + g = (np.sqrt(5) - 1) / 2 + a, b = lo, hi + c, d = b - g * (b - a), a + g * (b - a) + fc, fd = f(c), f(d) + for _ in range(iters): + if fc < fd: + b, d, fd = d, c, fc + c = b - g * (b - a) + fc = f(c) + else: + a, c, fc = c, d, fd + d = a + g * (b - a) + fd = f(d) + return float(np.exp((a + b) / 2)) + + +class IsotonicConfidence: + """Top-label isotonic regression (pool-adjacent-violators) on confidence. + + Maps raw confidence -> calibrated confidence. More flexible than temperature + scaling but needs more validation data and only recalibrates the top choice; + reported as a comparison, temperature scaling stays the default. + """ + + def fit(self, confidence: np.ndarray, correct: np.ndarray) -> "IsotonicConfidence": + order = np.argsort(confidence) + x, y = confidence[order], correct[order].astype(np.float64) + vals, wts, xs = [], [], [] + for xi, yi in zip(x, y): + vals.append(yi) + wts.append(1.0) + xs.append(xi) + while len(vals) > 1 and vals[-2] > vals[-1]: + w = wts[-2] + wts[-1] + v = (vals[-2] * wts[-2] + vals[-1] * wts[-1]) / w + vals[-2:], wts[-2:], xs[-2:] = [v], [w], [xs[-1]] + self.x, self.y = np.array(xs), np.array(vals) + return self + + def __call__(self, confidence: np.ndarray) -> np.ndarray: + return np.interp(confidence, self.x, self.y) + + +def reliability_svg(bins: list[dict], title: str = "Reliability diagram", size: int = 360) -> str: + """Dependency-free SVG reliability diagram (accuracy vs confidence per bin).""" + pad = 40 + inner = size - 2 * pad + X = lambda v: pad + v * inner # noqa: E731 + Y = lambda v: size - pad - v * inner # noqa: E731 + total = sum(b["count"] for b in bins) or 1 + parts = [f'', + f'', + f'{title}', + f''] + for b in bins: + if not b["count"]: + continue + w = (b["hi"] - b["lo"]) * inner + parts.append(f'') + parts.append(f'') + parts.append(f'') + for v in (0, 0.25, 0.5, 0.75, 1): + parts.append(f'{v:g}') + parts.append(f'{v:g}') + parts.append(f'') + parts.append(f'confidence ' + f'(blue = accuracy, grey = share of samples)') + parts.append("") + return "\n".join(parts) diff --git a/code/minijev/choices/__init__.py b/code/minijev/choices/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7ce8b77dbc81c2e38e87b1c18069946c7466c2c0 --- /dev/null +++ b/code/minijev/choices/__init__.py @@ -0,0 +1,3 @@ +from .encoder import ChoiceEncoder, EmbeddingCache + +__all__ = ["ChoiceEncoder", "EmbeddingCache"] diff --git a/code/minijev/choices/__pycache__/__init__.cpython-314.pyc b/code/minijev/choices/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92ac24f9007028a9b19dd8cefbe1b3f633a0023b Binary files /dev/null and b/code/minijev/choices/__pycache__/__init__.cpython-314.pyc differ diff --git a/code/minijev/choices/__pycache__/encoder.cpython-314.pyc b/code/minijev/choices/__pycache__/encoder.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..340e133bbf794c855d2c0910f726a1a914edb937 Binary files /dev/null and b/code/minijev/choices/__pycache__/encoder.cpython-314.pyc differ diff --git a/code/minijev/choices/encoder.py b/code/minijev/choices/encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..30ac33bf02e7939296d61876d20f903376591ed7 --- /dev/null +++ b/code/minijev/choices/encoder.py @@ -0,0 +1,66 @@ +"""ChoiceEncoder: choice label -> semantic embedding in the core space. + +Choices are *inputs*: "yes", "no", "database", "move up" are encoded from their +text, so the same weights serve 2, 4 or 10 options and unseen labels. With a +pretrained text encoder the choice embedding comes from the same backbone as the +question (shared weights), so "sì" and "yes" start close together. + +`EmbeddingCache` memoises backbone outputs per string. With a frozen backbone a +question or a choice label is encoded once, ever: Snake's 4 moves and a fixed +question cost nothing at inference, only the core runs. +""" +from __future__ import annotations + +from collections import OrderedDict + +import torch +from torch import nn + +from minijev.encoders.text import Projection, TextPooler + + +class ChoiceEncoder(nn.Module): + def __init__(self, d: int, embed: nn.Embedding | None = None, max_len: int = 16, d_text: int | None = None): + super().__init__() + self.byte = embed is not None + if self.byte: + self.pooler = TextPooler(embed, d, max_len) + else: + self.proj = Projection(d_text, d, hidden=2 * d) + + def forward(self, ids=None, pooled=None): + """byte: ids (..., L) -> (..., d); pretrained: backbone pooled (..., d_text) -> (..., d).""" + return self.pooler(ids) if self.byte else self.proj(pooled) + + +class EmbeddingCache: + """LRU cache: text -> backbone output (tokens, mask, pooled) as CPU tensors.""" + + def __init__(self, max_items: int = 4096): + self.max_items = max_items + self.data: OrderedDict[str, tuple] = OrderedDict() + self.hits = self.misses = 0 + + def get_many(self, texts, compute): + """compute(list[str]) -> (tok (n, L, dt), mask (n, L), pooled (n, dt)) for the missing texts.""" + missing = [t for t in dict.fromkeys(texts) if t not in self.data] + self.hits += len(texts) - len(missing) + self.misses += len(missing) + if missing: + tok, mask, pooled = compute(missing) + for i, t in enumerate(missing): + n = int(mask[i].sum()) + self.data[t] = (tok[i, :n].detach().cpu(), pooled[i].detach().cpu()) + if len(self.data) > self.max_items: + self.data.popitem(last=False) + for t in texts: + self.data.move_to_end(t) + rows = [self.data[t] for t in texts] + L = max(1, max(r[0].shape[0] for r in rows)) + dt = rows[0][1].shape[-1] + tok = torch.zeros(len(rows), L, dt) + mask = torch.zeros(len(rows), L, dtype=torch.bool) + for i, (t, _) in enumerate(rows): + tok[i, : t.shape[0]] = t + mask[i, : t.shape[0]] = True + return tok, mask, torch.stack([r[1] for r in rows]) diff --git a/code/minijev/cli.py b/code/minijev/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..bf70466b2b602c60a40b3761640806463a01d39b --- /dev/null +++ b/code/minijev/cli.py @@ -0,0 +1,416 @@ +"""`minijev` command line. + + minijev hardware + minijev train --config configs/snake-small.yaml [--resume RUN_DIR] [--set key=value ...] + minijev evaluate --checkpoint RUN/checkpoints/final.pt [--games 200] + minijev benchmark --checkpoint RUN/checkpoints/final.pt [--onnx] + minijev export --checkpoint RUN/checkpoints/final.pt --format onnx + minijev estimate --config configs/vast/vast-small.yaml --gpu-hourly-cost 0.20 + minijev compare RUN_DIR [RUN_DIR ...] + minijev runs annotate RUN_DIR --actual-cost 0.42 + minijev export-hf --checkpoint X.pt --out hf/name (checkpoint may then be a folder or a hub repo id) + minijev relabel --checkpoint X.pt --out Y.pt --map UP="move up" ... [--set task.choice_style=semantic] + minijev ask --checkpoint X.pt --state hotdog --question "Is this food?" --choices yes no + minijev bench-jsonl --checkpoint X.pt --data data/general_qa/benchmark.jsonl + minijev snake generate|baselines|demo|play|dagger|rl ... + minijev sentiment prepare ... +""" +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + + +def _cfg(args): + from minijev.config import load_config + return load_config(args.config, getattr(args, "set", None) or []) + + +# ------------------------------------------------------------------ generic +def cmd_hardware(args): + import torch + + from minijev.device import resolve_runtime + prof = resolve_runtime({"batch_size": args.batch_size}, args.params) + print(json.dumps({"torch": torch.__version__, **prof.to_dict()}, indent=2)) + + +def cmd_train(args): + from minijev.training.supervised import train + cfg = _cfg(args) + run_dir = args.resume or args.run_dir + s = train(cfg, run_dir=run_dir, resume=bool(args.resume), max_steps=args.max_steps, max_minutes=args.max_minutes) + print(json.dumps({k: v for k, v in s.items() if not k.startswith("test_")}, indent=2, default=str)) + if cfg["task"]["name"] == "snake" and s.get("final_checkpoint") and not args.no_games: + _snake_eval(s["final_checkpoint"], cfg, Path(s["run_dir"])) + + +def _snake_eval(ckpt, cfg, run_dir: Path, games: int | None = None): + from environments.snake.evaluate import model_policy, play_games + from minijev.inference.runtime import MiniJEV + dec = MiniJEV.load(ckpt, threads=4) + env = cfg.get("env", {}) + n = games or cfg.get("eval", {}).get("games", 200) + res = play_games(model_policy(dec), n, env, parallel=cfg.get("eval", {}).get("parallel", 64)) + print(f"[games] {res['games']} games on {res['board']}: avg {res['avg_score']:.1f} median {res['median_score']:.0f} " + f"max {res['max_score']} / {res['max_possible_score']} | win {res['win_rate']:.2%} " + f"collision {res['death_rate']:.2%} starvation {res['starvation_rate']:.2%} | " + f"fatal-move rate {res['fatal_move_rate']:.4%}") + (run_dir / "games.json").write_text(json.dumps(res, indent=2)) + return res + + +def cmd_evaluate(args): + import numpy as np + + from minijev.calibration.metrics import calibration_report + from minijev.datasets.batching import BatchEncoder + from minijev.datasets.decision_data import DecisionData + from minijev.inference.runtime import MiniJEV + dec = MiniJEV.load(args.checkpoint, threads=args.threads) + import torch + cfg = torch.load(args.checkpoint, weights_only=False)["config"] if args.checkpoint.endswith(".pt") else None + data_dir = Path(args.data or (cfg["data"]["dir"] if cfg else "")) + out = {"checkpoint": args.checkpoint} + split = data_dir / f"{args.split}.npz" + if split.exists(): + data = DecisionData.load(split) + enc = BatchEncoder(data, dec.task, dec.max_question_len, dec.max_choice_len) + logits = [] + for i in range(0, len(data), 1024): + b = enc(np.arange(i, min(len(data), i + 1024))) + logits.append(dec._run(next(v for k, v in b.items() if k.startswith("state_")), + b["question_ids"], b["choice_ids"])[1]) + acceptable = data.soft > 0 if data.soft is not None else None + rep = calibration_report(np.concatenate(logits), data.target, acceptable=acceptable) # T already applied + out["calibration"] = {k: v for k, v in rep.items() if k != "reliability"} + out["reliability"] = rep["reliability"] + print(f"[{args.split}] n={rep['n']} acc {rep['accuracy']:.4f} ECE {rep['ece']:.4f} " + f"NLL {rep['nll']:.4f} Brier {rep['brier']:.4f}" + + (f" acceptable-acc {rep['acceptable_accuracy']:.4f}" if acceptable is not None else "")) + if dec.task.name == "snake" and args.games: + from environments.snake.evaluate import model_policy, play_games + env = (cfg or {}).get("env", {}) + if args.board_size: + env = {**env, "board_size": args.board_size} + res = play_games(model_policy(dec), args.games, env) + out["games"] = res + print(f"[games] avg {res['avg_score']:.2f} median {res['median_score']} max {res['max_score']} " + f"win {res['win_rate']:.2%} collisions {res['death_rate']:.2%} fatal-move {res['fatal_move_rate']:.4%}") + if args.out: + Path(args.out).write_text(json.dumps(out, indent=2)) + + +def cmd_benchmark(args): + from minijev.benchmark.perf import benchmark_decider, format_perf + paths = [args.checkpoint] + if args.onnx: + p = Path(args.checkpoint) + for cand in (p.with_suffix(".onnx"), p.with_name(p.stem + ".int8.onnx")): + if cand.exists(): + paths.append(str(cand)) + results = [] + for path in paths: + r = benchmark_decider(path, threads=args.threads, quick=args.quick) + print(format_perf(r)) + results.append(r) + if args.out: + Path(args.out).write_text(json.dumps(results, indent=2)) + + +def cmd_export(args): + from minijev.export.onnx_export import export_onnx + if args.format != "onnx": + sys.exit("only --format onnx is supported") + r = export_onnx(args.checkpoint, args.out, quantize=not args.no_quantize) + print(json.dumps({k: v for k, v in r.items() if k != "meta"}, indent=2)) + + +def cmd_estimate(args): + from minijev.estimate import estimate + estimate(_cfg(args), args.gpu_hourly_cost, throughput=args.throughput, bench_seconds=args.bench_seconds, + gpu_name=args.gpu_name, budget=args.budget) + + +def cmd_relabel(args): + from minijev.config import _parse_value + from minijev.training.relabel import relabel_checkpoint + mapping = dict(m.split("=", 1) for m in args.map) + updates = {k: _parse_value(v) for k, v in (kv.split("=", 1) for kv in (args.set or []))} + print(json.dumps(relabel_checkpoint(args.checkpoint, args.out, mapping, updates, steps=args.steps), indent=2)) + + +def cmd_export_hf(args): + from minijev.hub import save_pretrained + print(save_pretrained(args.checkpoint, args.out)) + + +def cmd_ask(args): + from minijev.inference.runtime import MiniJEV + dec = MiniJEV.load(args.checkpoint, threads=args.threads, **({"task": args.task} if args.task else {})) + d = dec.decide(args.state, args.question, args.choices) + print(json.dumps(d.to_dict(), ensure_ascii=False, indent=2)) + + +def cmd_bench_jsonl(args): + """Accuracy + calibration of a model on a JSONL decision file, row by row.""" + import numpy as np + + from minijev.calibration.metrics import calibration_report + from minijev.datasets.jsonl import read_jsonl + from minijev.inference.runtime import MiniJEV + dec = MiniJEV.load(args.checkpoint, threads=args.threads, **({"task": args.task} if args.task else {})) + rows = read_jsonl(args.data) + ok, logits, targets, out = 0, [], [], [] + for r in rows: + d = dec.decide(r.get("state") or "", r["question"], r["choices"]) + tgt = r["target"] if isinstance(r["target"], str) else r["choices"][r["target"]] + hit = d.choice == tgt + ok += hit + n = max(len(x["choices"]) for x in rows) + logits.append(np.pad(np.array(d.logits), (0, n - len(d.logits)), constant_values=-1e9)) + targets.append(r["choices"].index(tgt)) + out.append({**r, "pred": d.choice, "confidence": round(d.confidence, 4), "correct": bool(hit)}) + if args.verbose: + print(f"{'OK ' if hit else 'XX '} {d.confidence:.2f} {r.get('state') or '-':>10} | {r['question']} " + f"-> {d.choice} (gold {tgt})") + rep = calibration_report(np.stack(logits), np.array(targets)) # logits are already calibrated + print(f"[{args.data}] {ok}/{len(rows)} = {ok / len(rows):.3f} | ECE {rep['ece']:.4f} NLL {rep['nll']:.4f} " + f"Brier {rep['brier']:.4f}") + if args.out: + Path(args.out).write_text(json.dumps({"accuracy": ok / len(rows), "ece": rep["ece"], "nll": rep["nll"], + "brier": rep["brier"], "rows": out}, indent=2, ensure_ascii=False)) + + +def cmd_compare(args): + from minijev.report import compare_runs + print(compare_runs(args.runs, out=args.out)) + + +def cmd_runs_annotate(args): + p = Path(args.run) / "summary.json" + s = json.loads(p.read_text()) + s.setdefault("cost", {}) + if args.actual_cost is not None: + s["cost"]["actual_cost"] = args.actual_cost + if args.gpu: + s["cost"]["gpu"] = args.gpu + if args.note: + s["note"] = args.note + p.write_text(json.dumps(s, indent=2)) + print(json.dumps(s.get("cost"), indent=2)) + + +# -------------------------------------------------------------------- snake +def cmd_snake_generate(args): + from environments.snake.dataset import generate_splits + sizes = [int(x) for x in str(args.board_size).split(",")] + out = args.out or f"data/snake{'-'.join(map(str, sizes))}-{_short(args.samples)}" + s = generate_splits(out, args.samples, seed=args.seed, board_sizes=sizes, keep_prob=args.keep_prob, + explore_eps=args.explore_eps, workers=args.workers) + if args.jsonl: + from environments.snake.dataset import export_jsonl + from minijev.datasets.decision_data import DecisionData + for split in ("train", "val", "test"): + export_jsonl(DecisionData.load(Path(out) / f"{split}.npz"), Path(out) / f"{split}.jsonl") + print(json.dumps(s, indent=2)) + print(f"-> {out}") + + +def _short(n: int) -> str: + return f"{n // 1_000_000}m" if n >= 1_000_000 and n % 1_000_000 == 0 else (f"{n // 1000}k" if n >= 1000 else str(n)) + + +def cmd_snake_baselines(args): + from environments.snake.evaluate import baseline_suite + res = baseline_suite(args.games, {"board_size": args.board_size}, seed=args.seed) + print(f"{'agent':10} {'avg':>7} {'median':>7} {'max':>5} {'win':>6} {'collide':>8} {'starve':>7} {'fatal%':>8}") + for name, r in res.items(): + print(f"{name:10} {r['avg_score']:7.1f} {r['median_score']:7.0f} {r['max_score']:5d} {r['win_rate']:6.1%} " + f"{r['death_rate']:8.1%} {r['starvation_rate']:7.1%} {r['fatal_move_rate']:8.3%}") + if args.out: + Path(args.out).write_text(json.dumps(res, indent=2)) + + +def cmd_snake_demo(args, human=False): + from environments.snake.demo.server import serve + serve(model=args.model, board_size=args.board_size, port=args.port, agent="human" if human else args.agent, + open_browser=not args.no_browser) + + +def cmd_snake_dagger(args): + from environments.snake.dagger import run_dagger + run_dagger(_cfg(args), args.checkpoint, iterations=args.iterations, samples=args.samples, run_dir=args.run_dir) + + +def cmd_snake_rl(args): + from environments.snake.rl import train_ppo + train_ppo(_cfg(args), args.checkpoint, run_dir=args.run_dir, resume=args.resume) + + +def cmd_sentiment_prepare(args): + from environments.sentiment.dataset import prepare + print(json.dumps(prepare(args.out, source=args.source), indent=2)) + + +# --------------------------------------------------------------------- main +def build_parser() -> argparse.ArgumentParser: + p = argparse.ArgumentParser(prog="minijev", description="MiniJEV: tiny calibrated decision model") + sub = p.add_subparsers(dest="cmd", required=True) + + s = sub.add_parser("hardware", help="show detected device and runtime profile") + s.add_argument("--batch-size", type=int, default=256) + s.add_argument("--params", type=int, default=1_000_000) + s.set_defaults(fn=cmd_hardware) + + s = sub.add_parser("train", help="supervised / distillation training") + s.add_argument("--config", required=True) + s.add_argument("--set", nargs="*", help="override config values, e.g. training.lr=5e-4") + s.add_argument("--run-dir") + s.add_argument("--resume", help="run directory to resume from (uses checkpoints/last.pt)") + s.add_argument("--max-steps", type=int) + s.add_argument("--max-minutes", type=float, help="stop cleanly (checkpoint saved) after this wall time") + s.add_argument("--no-games", action="store_true", help="skip game evaluation after training") + s.set_defaults(fn=cmd_train) + + s = sub.add_parser("evaluate", help="calibration on a split + (snake) full games") + s.add_argument("--checkpoint", required=True) + s.add_argument("--data", help="dataset dir (default: from checkpoint config)") + s.add_argument("--split", default="test") + s.add_argument("--games", type=int, default=200) + s.add_argument("--board-size", type=int) + s.add_argument("--threads", type=int, default=4) + s.add_argument("--out") + s.set_defaults(fn=cmd_evaluate) + + s = sub.add_parser("benchmark", help="latency / throughput / CPU / RAM") + s.add_argument("--checkpoint", required=True, help=".pt or .onnx") + s.add_argument("--onnx", action="store_true", help="also benchmark sibling .onnx and .int8.onnx files") + s.add_argument("--threads", type=int, default=1) + s.add_argument("--quick", action="store_true") + s.add_argument("--out") + s.set_defaults(fn=cmd_benchmark) + + s = sub.add_parser("export", help="export to ONNX (+ INT8) and verify parity") + s.add_argument("--checkpoint", required=True) + s.add_argument("--format", default="onnx") + s.add_argument("--out") + s.add_argument("--no-quantize", action="store_true") + s.set_defaults(fn=cmd_export) + + s = sub.add_parser("estimate", help="estimate training time and cost (measures real throughput)") + s.add_argument("--config", required=True) + s.add_argument("--set", nargs="*") + s.add_argument("--gpu-hourly-cost", type=float, default=0.0) + s.add_argument("--gpu-name") + s.add_argument("--throughput", type=float, help="samples/s; skip the measurement") + s.add_argument("--bench-seconds", type=float, default=60) + s.add_argument("--budget", type=float, help="warn if the estimate exceeds this amount") + s.set_defaults(fn=cmd_estimate) + + s = sub.add_parser("compare", help="results table across runs") + s.add_argument("runs", nargs="+") + s.add_argument("--out", help="write markdown table here") + s.set_defaults(fn=cmd_compare) + + runs = sub.add_parser("runs", help="run bookkeeping").add_subparsers(dest="runs_cmd", required=True) + s = runs.add_parser("annotate") + s.add_argument("run") + s.add_argument("--actual-cost", type=float) + s.add_argument("--gpu") + s.add_argument("--note") + s.set_defaults(fn=cmd_runs_annotate) + + snake = sub.add_parser("snake", help="Snake environment tools").add_subparsers(dest="snake_cmd", required=True) + s = snake.add_parser("generate", help="generate an oracle-labelled dataset") + s.add_argument("--samples", type=int, default=100_000) + s.add_argument("--board-size", default="10", help="e.g. 10 or 10,20") + s.add_argument("--out") + s.add_argument("--seed", type=int, default=0) + s.add_argument("--keep-prob", type=float, default=0.1) + s.add_argument("--explore-eps", type=float, default=0.05) + s.add_argument("--workers", type=int) + s.add_argument("--jsonl", action="store_true", help="also write full JSONL exports") + s.set_defaults(fn=cmd_snake_generate) + + s = snake.add_parser("baselines", help="play the scripted baselines") + s.add_argument("--games", type=int, default=100) + s.add_argument("--board-size", type=int, default=10) + s.add_argument("--seed", type=int, default=12345) + s.add_argument("--out") + s.set_defaults(fn=cmd_snake_baselines) + + for name, human in (("demo", False), ("play", True)): + s = snake.add_parser(name, help="web UI: watch MiniJEV/baselines" if not human else "web UI: play yourself") + s.add_argument("--model", help=".onnx or .pt") + s.add_argument("--agent", default="minijev", help="minijev | oracle | bfs | survival | greedy | random | human") + s.add_argument("--board-size", type=int, default=10) + s.add_argument("--port", type=int, default=8765) + s.add_argument("--no-browser", action="store_true") + s.set_defaults(fn=lambda a, h=human: cmd_snake_demo(a, h)) + + s = snake.add_parser("dagger", help="DAgger: label the model's own states with the oracle, retrain") + s.add_argument("--config", required=True) + s.add_argument("--set", nargs="*") + s.add_argument("--checkpoint", required=True) + s.add_argument("--iterations", type=int, default=2) + s.add_argument("--samples", type=int, default=100_000) + s.add_argument("--run-dir") + s.set_defaults(fn=cmd_snake_dagger) + + s = snake.add_parser("rl", help="PPO fine-tuning from a supervised checkpoint") + s.add_argument("--config", required=True) + s.add_argument("--set", nargs="*") + s.add_argument("--checkpoint", required=True) + s.add_argument("--run-dir") + s.add_argument("--resume", action="store_true") + s.set_defaults(fn=cmd_snake_rl) + + s = sub.add_parser("relabel", help="rename choice labels of a trained model (fits the ChoiceEncoder only)") + s.add_argument("--checkpoint", required=True) + s.add_argument("--out", required=True) + s.add_argument("--map", nargs="+", required=True, help='OLD="new label" ...') + s.add_argument("--set", nargs="*", help="config updates stored in the new checkpoint") + s.add_argument("--steps", type=int, default=3000) + s.set_defaults(fn=cmd_relabel) + + s = sub.add_parser("export-hf", help="write a pickle-free folder (safetensors + JSON) for Hugging Face") + s.add_argument("--checkpoint", required=True) + s.add_argument("--out", required=True) + s.set_defaults(fn=cmd_export_hf) + + s = sub.add_parser("ask", help="one decision from the command line") + s.add_argument("--checkpoint", required=True) + s.add_argument("--state", default="") + s.add_argument("--question", required=True) + s.add_argument("--choices", nargs="+", required=True) + s.add_argument("--task") + s.add_argument("--threads", type=int, default=1) + s.set_defaults(fn=cmd_ask) + + s = sub.add_parser("bench-jsonl", help="accuracy/calibration on a JSONL decision file") + s.add_argument("--checkpoint", required=True) + s.add_argument("--data", required=True) + s.add_argument("--task") + s.add_argument("--threads", type=int, default=4) + s.add_argument("--out") + s.add_argument("-v", "--verbose", action="store_true") + s.set_defaults(fn=cmd_bench_jsonl) + + sent = sub.add_parser("sentiment", help="sentiment task tools").add_subparsers(dest="sent_cmd", required=True) + s = sent.add_parser("prepare", help="download / build the sentiment dataset") + s.add_argument("--out", default="data/sentiment") + s.add_argument("--source", default="tweet_eval") + s.set_defaults(fn=cmd_sentiment_prepare) + return p + + +def main(argv=None): + args = build_parser().parse_args(argv) + args.fn(args) + + +if __name__ == "__main__": + main() diff --git a/code/minijev/config.py b/code/minijev/config.py new file mode 100644 index 0000000000000000000000000000000000000000..cffe0241d10cda654286f62527985b4139065560 --- /dev/null +++ b/code/minijev/config.py @@ -0,0 +1,62 @@ +"""YAML configs with `extends:` inheritance and dotted CLI overrides.""" +from __future__ import annotations + +import copy +from pathlib import Path +from typing import Any + +import yaml + + +def deep_merge(base: dict, override: dict) -> dict: + out = copy.deepcopy(base) + for k, v in override.items(): + if isinstance(v, dict) and isinstance(out.get(k), dict): + out[k] = deep_merge(out[k], v) + else: + out[k] = copy.deepcopy(v) + return out + + +def _load(path: Path) -> dict: + cfg = yaml.safe_load(path.read_text()) or {} + parent = cfg.pop("extends", None) + return deep_merge(_load(path.parent / parent), cfg) if parent else cfg + + +def load_config(path: str | Path, overrides: list[str] | None = None) -> dict: + path = Path(path) + raw = yaml.safe_load(path.read_text()) or {} + cfg = _load(path) + cfg["name"] = raw.get("name", path.stem) + for ov in overrides or []: + key, _, val = ov.partition("=") + set_dotted(cfg, key.strip(), _parse_value(val)) + return cfg + + +def _parse_value(val: str) -> Any: + v = yaml.safe_load(val) + if isinstance(v, str): # YAML 1.1 reads "3e-4" as a string + try: + return float(v) + except ValueError: + pass + return v + + +def set_dotted(cfg: dict, key: str, value: Any) -> None: + node = cfg + parts = key.split(".") + for p in parts[:-1]: + node = node.setdefault(p, {}) + node[parts[-1]] = value + + +def get_dotted(cfg: dict, key: str, default: Any = None) -> Any: + node = cfg + for p in key.split("."): + if not isinstance(node, dict) or p not in node: + return default + node = node[p] + return node diff --git a/code/minijev/core/__init__.py b/code/minijev/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9ed891c68a32f8cad5362a1d43146a89ba2c05da --- /dev/null +++ b/code/minijev/core/__init__.py @@ -0,0 +1,3 @@ +from .core import NEG, SCORERS, MiniJEVCore + +__all__ = ["MiniJEVCore", "NEG", "SCORERS"] diff --git a/code/minijev/core/__pycache__/__init__.cpython-314.pyc b/code/minijev/core/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02e1df140c21d6396fa465a6c6779f7d36fbc023 Binary files /dev/null and b/code/minijev/core/__pycache__/__init__.cpython-314.pyc differ diff --git a/code/minijev/core/__pycache__/core.cpython-314.pyc b/code/minijev/core/__pycache__/core.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e9a01e11b1c7670be4a458b43a359b739e12fc0 Binary files /dev/null and b/code/minijev/core/__pycache__/core.cpython-314.pyc differ diff --git a/code/minijev/core/__pycache__/layers.cpython-314.pyc b/code/minijev/core/__pycache__/layers.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..946ac725cdfed3c8b900294d5e3f695a4df20380 Binary files /dev/null and b/code/minijev/core/__pycache__/layers.cpython-314.pyc differ diff --git a/code/minijev/core/core.py b/code/minijev/core/core.py new file mode 100644 index 0000000000000000000000000000000000000000..3fa1b7baf01c18b7009becd675e02317b1f94462 --- /dev/null +++ b/code/minijev/core/core.py @@ -0,0 +1,88 @@ +"""MiniJEV Core: the domain-agnostic decision network. + +It only sees vectors in a shared latent space of width `d`: + + state_tokens (B, S, d) + state_mask (B, S) from any StateEncoder (grid, text, numeric, ...) + question_tokens (B, Q, d) + question_mask (B, Q) from the question encoder + choice_emb (B, N, d) + choice_mask (B, N) from the ChoiceEncoder (N is dynamic) + +and returns one logit per choice (+ value, scalar score and the CLS embedding). +It knows nothing about Snake, text, bytes or tokenizers. + + [CLS] + question tokens + state tokens ──► Transformer ──► context H + │ + scorer "cross": choices cross-attend H, then self-attend each other ─► Linear ─► logit_i + scorer "bi": logit_i = MLP([h, c_i, h*c_i]) (light cross scorer on pooled h = CLS) + scorer "fixed_head": Linear(CLS) -> max_choices logits (ablation: ignores choice meaning) + +"cross" and "bi" are permutation-equivariant over choices (no positional information). +""" +from __future__ import annotations + +import torch +from torch import nn + +from .layers import DecisionBlock, EncoderBlock + +NEG = -1e9 +SCORERS = ("cross", "bi", "fixed_head") + + +class MiniJEVCore(nn.Module): + def __init__(self, d: int, n_layers: int, n_heads: int = 4, mlp_ratio: float = 4.0, dropout: float = 0.0, + n_decision_layers: int = 1, scorer: str = "cross", max_choices: int = 16): + super().__init__() + if scorer not in SCORERS: + raise ValueError(f"scorer must be one of {SCORERS}, got {scorer!r}") + self.d, self.scorer = d, scorer + self.cls = nn.Parameter(torch.zeros(1, 1, d)) + self.type_emb = nn.Parameter(torch.zeros(3, d)) # cls / question / state + nn.init.normal_(self.type_emb, std=0.02) + self.blocks = nn.ModuleList(EncoderBlock(d, n_heads, mlp_ratio, dropout) for _ in range(n_layers)) + self.ln_ctx = nn.LayerNorm(d) + if scorer == "cross": + self.decision = nn.ModuleList(DecisionBlock(d, n_heads, mlp_ratio, dropout) + for _ in range(n_decision_layers)) + self.choice_head = nn.Sequential(nn.LayerNorm(d), nn.Linear(d, 1)) + elif scorer == "bi": + self.ln_h, self.ln_c = nn.LayerNorm(d), nn.LayerNorm(d) + self.choice_head = nn.Sequential(nn.Linear(3 * d, d), nn.GELU(), nn.Linear(d, 1)) + else: + self.choice_head = nn.Sequential(nn.LayerNorm(d), nn.Linear(d, max_choices)) + self.value_head = nn.Sequential(nn.LayerNorm(d), nn.Linear(d, d), nn.GELU(), nn.Linear(d, 1)) + # continuous 0..1 score for `model.score(state, question)` (trained with BCE when rows carry `score`) + self.scalar_head = nn.Sequential(nn.LayerNorm(d), nn.Linear(d, 1)) + + def encode_context(self, state_tokens, state_mask, question_tokens, question_mask): + B = question_tokens.shape[0] + parts = [self.cls.expand(B, -1, -1) + self.type_emb[0], question_tokens + self.type_emb[1]] + masks = [torch.ones(B, 1, dtype=torch.bool, device=question_tokens.device), question_mask] + if state_tokens is not None: + parts.append(state_tokens + self.type_emb[2]) + masks.append(state_mask) + x, mask = torch.cat(parts, 1), torch.cat(masks, 1) + for blk in self.blocks: + x = blk(x, key_mask=mask) + return self.ln_ctx(x), mask + + def score_choices(self, ctx, ctx_mask, choice_emb, choice_mask): + if self.scorer == "cross": + c = choice_emb + for blk in self.decision: + c = blk(c, ctx, ctx_mask, choice_mask) + logits = self.choice_head(c).squeeze(-1) + elif self.scorer == "bi": + h = self.ln_h(ctx[:, :1]).expand(-1, choice_emb.shape[1], -1) + c = self.ln_c(choice_emb) + logits = self.choice_head(torch.cat([h, c, h * c], -1)).squeeze(-1) + else: + logits = self.choice_head(ctx[:, 0])[:, : choice_emb.shape[1]] + return logits.float().masked_fill(~choice_mask, NEG) + + def forward(self, state_tokens, state_mask, question_tokens, question_mask, choice_emb, choice_mask): + ctx, ctx_mask = self.encode_context(state_tokens, state_mask, question_tokens, question_mask) + cls = ctx[:, 0] + return {"logits": self.score_choices(ctx, ctx_mask, choice_emb, choice_mask), + "value": self.value_head(cls).squeeze(-1).float(), + "score": self.scalar_head(cls).squeeze(-1).float(), # logit; sigmoid -> 0..1 + "embedding": cls, "choice_mask": choice_mask} diff --git a/code/minijev/core/layers.py b/code/minijev/core/layers.py new file mode 100644 index 0000000000000000000000000000000000000000..26879e1f9181037380e72fd1b5e420a7a2d49ef9 --- /dev/null +++ b/code/minijev/core/layers.py @@ -0,0 +1,76 @@ +from __future__ import annotations + +import torch +import torch.nn.functional as F +from torch import nn + + +class Attention(nn.Module): + """Multi-head (self or cross) attention on top of SDPA; `key_mask` is bool (B, S), True = valid.""" + + def __init__(self, d: int, heads: int, dropout: float = 0.0): + super().__init__() + assert d % heads == 0, "d_model must be divisible by n_heads" + self.h, self.dh = heads, d // heads + self.q = nn.Linear(d, d) + self.kv = nn.Linear(d, 2 * d) + self.o = nn.Linear(d, d) + self.dropout = dropout + + def forward(self, x, ctx=None, key_mask=None): + ctx = x if ctx is None else ctx + B, T, D = x.shape + S = ctx.shape[1] + q = self.q(x).view(B, T, self.h, self.dh).transpose(1, 2) + kv = self.kv(ctx).view(B, S, 2, self.h, self.dh).permute(2, 0, 3, 1, 4) + mask = key_mask[:, None, None, :] if key_mask is not None else None + out = F.scaled_dot_product_attention(q, kv[0], kv[1], attn_mask=mask, + dropout_p=self.dropout if self.training else 0.0) + return self.o(out.transpose(1, 2).reshape(B, T, D)) + + +class MLP(nn.Module): + def __init__(self, d: int, ratio: float = 4.0, dropout: float = 0.0): + super().__init__() + hidden = int(d * ratio) + self.net = nn.Sequential(nn.Linear(d, hidden), nn.GELU(), nn.Linear(hidden, d), nn.Dropout(dropout)) + + def forward(self, x): + return self.net(x) + + +class EncoderBlock(nn.Module): + """Pre-LN transformer block.""" + + def __init__(self, d, heads, mlp_ratio=4.0, dropout=0.0): + super().__init__() + self.ln1, self.ln2 = nn.LayerNorm(d), nn.LayerNorm(d) + self.attn = Attention(d, heads, dropout) + self.mlp = MLP(d, mlp_ratio, dropout) + + def forward(self, x, key_mask=None): + h = self.ln1(x) + x = x + self.attn(h, key_mask=key_mask) + return x + self.mlp(self.ln2(x)) + + +class DecisionBlock(nn.Module): + """Choices read the context (cross-attn), then compare with each other (self-attn). + + No positional information over choices -> the block is permutation-equivariant: + reordering the choices reorders the scores, nothing else. + """ + + def __init__(self, d, heads, mlp_ratio=4.0, dropout=0.0): + super().__init__() + self.ln_q, self.ln_ctx = nn.LayerNorm(d), nn.LayerNorm(d) + self.cross = Attention(d, heads, dropout) + self.ln_s = nn.LayerNorm(d) + self.self_attn = Attention(d, heads, dropout) + self.ln_m = nn.LayerNorm(d) + self.mlp = MLP(d, mlp_ratio, dropout) + + def forward(self, c, ctx, ctx_mask, choice_mask): + c = c + self.cross(self.ln_q(c), self.ln_ctx(ctx), key_mask=ctx_mask) + c = c + self.self_attn(self.ln_s(c), key_mask=choice_mask) + return c + self.mlp(self.ln_m(c)) diff --git a/code/minijev/datasets/__init__.py b/code/minijev/datasets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code/minijev/datasets/__pycache__/__init__.cpython-314.pyc b/code/minijev/datasets/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4743c5e06a820c7df2e7e34273ca3c583d93e786 Binary files /dev/null and b/code/minijev/datasets/__pycache__/__init__.cpython-314.pyc differ diff --git a/code/minijev/datasets/__pycache__/batching.cpython-314.pyc b/code/minijev/datasets/__pycache__/batching.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72bccfd598517d3b818b66d73fbd8fa23abc67e7 Binary files /dev/null and b/code/minijev/datasets/__pycache__/batching.cpython-314.pyc differ diff --git a/code/minijev/datasets/__pycache__/decision_data.cpython-314.pyc b/code/minijev/datasets/__pycache__/decision_data.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6d9e42fd71f75bda14980182c1e43ece7e6e91a Binary files /dev/null and b/code/minijev/datasets/__pycache__/decision_data.cpython-314.pyc differ diff --git a/code/minijev/datasets/batching.py b/code/minijev/datasets/batching.py new file mode 100644 index 0000000000000000000000000000000000000000..7d0f7320bccbb9e10783296e3001293306283983 --- /dev/null +++ b/code/minijev/datasets/batching.py @@ -0,0 +1,155 @@ +"""Turn rows of a DecisionData into model-ready numpy batches (+ torch loaders). + +Questions and choice labels are tokenised once per *vocabulary entry* (a dataset +has few distinct questions/choices). With a frozen pretrained backbone a +`BackboneTable` goes further and stores the backbone output per vocabulary entry, +so training never re-runs the text encoder on questions or choices. +""" +from __future__ import annotations + +import numpy as np + +from minijev.tokenizers import ByteTokenizer +from minijev.tasks import Task + +from .decision_data import DecisionData + +NEG = -1e9 + + +class BackboneTable: + """Frozen-backbone outputs for a list of strings: tok (V, L, dt) fp16, mask (V, L), pooled (V, dt).""" + + def __init__(self, texts: list[str], model, tokenizer, max_len: int, batch: int = 256): + import torch + + dev = next(model.parameters()).device + toks, masks, pooled = [], [], [] + L = 1 + with torch.inference_mode(): + for i in range(0, len(texts), batch): + ids = torch.as_tensor(tokenizer.encode_batch(texts[i:i + batch], max_len, dynamic=True), device=dev) + t, m, p = model.backbone(ids) + toks.append(t.half().cpu().numpy()) + masks.append(m.cpu().numpy()) + pooled.append(p.float().cpu().numpy()) + L = max(L, t.shape[1]) + dt = pooled[0].shape[1] if pooled else 1 + self.tok = np.zeros((len(texts) + 1, L, dt), np.float16) # + one empty row for "absent" + self.mask = np.zeros((len(texts) + 1, L), bool) + k = 0 + for t, m in zip(toks, masks): + self.tok[k:k + len(t), : t.shape[1]] = t + self.mask[k:k + len(t), : m.shape[1]] = m + k += len(t) + self.pooled = np.concatenate(pooled + [np.zeros((1, dt), np.float32)]) + + +class BatchEncoder: + def __init__(self, data: DecisionData, task: Task, max_question_len: int = 32, max_choice_len: int = 16, + choice_dropout: float = 0.0, seed: int = 0, tokenizer=None, + question_table: BackboneTable | None = None, choice_table: BackboneTable | None = None): + self.data, self.task = data, task + self.tok = tokenizer or getattr(task, "tokenizer", None) or ByteTokenizer() + self.dynamic = self.tok.kind != "byte" # byte keeps the original fixed-width layout + self.q_tok = self.tok.encode_batch(data.questions, max_question_len, dynamic=self.dynamic) + labels = [task.model_label(c) for c in data.choices] + c_tok = self.tok.encode_batch(labels, max_choice_len, dynamic=self.dynamic) + # extra all-pad row so choice index -1 maps to "no choice" + self.c_tok = np.concatenate([c_tok, np.full((1, c_tok.shape[1]), self.tok.pad_id, np.int64)]) + self.q_table, self.c_table = question_table, choice_table + self.choice_dropout = choice_dropout + self.seed = seed + + def _trim(self, ids: np.ndarray) -> np.ndarray: + if not self.dynamic: + return ids + n = int((ids != self.tok.pad_id).any(tuple(range(ids.ndim - 1))).nonzero()[0].max(initial=0)) + 1 + return ids[..., :n] + + def __call__(self, idx: np.ndarray, rng: np.random.Generator | None = None) -> dict[str, np.ndarray]: + d = self.data + idx = np.asarray(idx) + batch = dict(self.task.encode_arrays(d.state, idx)) + ci = d.choice_idx[idx].astype(np.int64) + present = ci >= 0 + target = d.target[idx].astype(np.int64) + soft = d.soft[idx].astype(np.float32) if d.soft is not None else None + teacher = d.teacher_logits[idx].astype(np.float32) if d.teacher_logits is not None else None + if self.choice_dropout > 0 and rng is not None: + # randomly hide non-target choices so the model sees 2..N options (variable-N training) + drop = (rng.random(ci.shape) < self.choice_dropout) & present + drop[np.arange(len(idx)), target.clip(0)] &= target < 0 + keep_count = (present & ~drop).sum(1) + drop[keep_count < 2] = False + present = present & ~drop + ci = np.where(present, ci, -1) + if soft is not None: + soft = np.where(present, soft, 0.0) + soft /= np.maximum(soft.sum(1, keepdims=True), 1e-8) + if teacher is not None: + teacher = np.where(present, teacher, NEG) + qi = d.question_idx[idx] + if self.q_table is not None: + qt = self.q_table + L = max(1, int(qt.mask[qi].any(0).nonzero()[0].max(initial=0)) + 1) + batch.update(question_bb_tok=qt.tok[qi, :L].astype(np.float32), question_bb_mask=qt.mask[qi, :L], + question_bb_pooled=qt.pooled[qi]) + else: + batch["question_ids"] = self._trim(self.q_tok[qi]) + if self.c_table is not None: + batch.update(choice_bb_pooled=self.c_table.pooled[ci], choice_bb_mask=ci >= 0) + else: + batch["choice_ids"] = self._trim(self.c_tok[ci]) # -1 -> last (all-pad) row + batch["target"] = target + if soft is not None: + batch["soft"] = soft + if teacher is not None: + batch["teacher_logits"] = teacher + if d.score is not None: + batch["score_target"] = d.score[idx].astype(np.float32) + return batch + + +def model_inputs(b: dict) -> dict: + """Batch (torch tensors) -> keyword arguments of MiniJEVNet.forward.""" + kw = {"state": {k: v for k, v in b.items() if k.startswith("state_")}} + if "question_bb_pooled" in b: + kw["question_bb"] = (b["question_bb_tok"], b["question_bb_mask"], b["question_bb_pooled"]) + else: + kw["question_ids"] = b["question_ids"] + if "choice_bb_pooled" in b: + kw["choice_bb"] = (b["choice_bb_pooled"], b["choice_bb_mask"]) + else: + kw["choice_ids"] = b["choice_ids"] + return kw + + +class EpochBatches: + """Map-style dataset of *batches* (use with DataLoader(batch_size=None)). + + The order is a deterministic permutation of (seed, epoch), so a resumed run + can skip exactly the batches it already consumed. + """ + + def __init__(self, encoder: BatchEncoder, batch_size: int, shuffle: bool, seed: int = 0, epoch: int = 0, + start_batch: int = 0, drop_last: bool = False, augment: bool = True): + self.encoder, self.bs, self.augment = encoder, batch_size, augment + n = len(encoder.data) + self.seed, self.epoch = seed, epoch + order = np.random.default_rng((seed, epoch)).permutation(n) if shuffle else np.arange(n) + nb = n // batch_size if drop_last else (n + batch_size - 1) // batch_size + self.batches = [order[i * batch_size:(i + 1) * batch_size] for i in range(start_batch, nb)] + + def __len__(self): + return len(self.batches) + + def __getitem__(self, i): + rng = np.random.default_rng((self.seed, self.epoch, i, 7)) if self.augment else None + return self.encoder(self.batches[i], rng) + + +def to_torch(batch: dict[str, np.ndarray], device, non_blocking: bool = False) -> dict: + import torch + + return {k: torch.as_tensor(v).to(device, non_blocking=non_blocking) for k, v in batch.items()} diff --git a/code/minijev/datasets/decision_data.py b/code/minijev/datasets/decision_data.py new file mode 100644 index 0000000000000000000000000000000000000000..805103e4b871b66b6b1f78007ac028c8a970ab9b --- /dev/null +++ b/code/minijev/datasets/decision_data.py @@ -0,0 +1,155 @@ +"""Generic on-disk dataset of decisions, independent of the task. + +Each row: a task-specific state (stored by the task plugin as numpy arrays, +ragged arrays as `X` + `X_offsets`), a question, a variable-size list of +choices and a supervision signal: + + target hard label (index into the row's choices), -1 if none + soft optional soft labels (n, Nmax) -> soft-label training + teacher_logits optional teacher logits (n, Nmax) -> knowledge distillation + group episode / document id: splits are made by group (no leakage) + hash optional exact-state hash to drop duplicates across splits + score optional continuous target in [0, 1] (NaN = none) for `model.score()` +""" +from __future__ import annotations + +import json +from dataclasses import dataclass, field +from pathlib import Path + +import numpy as np + +from minijev.tasks import ragged_take + +OPTIONAL = ("soft", "teacher_logits", "hash", "score") + + +@dataclass +class DecisionData: + task: str + state: dict[str, np.ndarray] + questions: list[str] + question_idx: np.ndarray + choices: list[str] + choice_idx: np.ndarray # (n, Nmax) int32, -1 = no choice + target: np.ndarray + group: np.ndarray + soft: np.ndarray | None = None + teacher_logits: np.ndarray | None = None + hash: np.ndarray | None = None + score: np.ndarray | None = None # (n,) float in [0, 1], NaN = none -> trains the scalar score head + meta: dict = field(default_factory=dict) + + def __len__(self) -> int: + return len(self.target) + + # ------------------------------------------------------------------ io + def save(self, path: str | Path) -> None: + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + arrays = {f"state/{k}": v for k, v in self.state.items()} + arrays.update(question_idx=self.question_idx, choice_idx=self.choice_idx, + target=self.target, group=self.group) + for k in OPTIONAL: + if getattr(self, k) is not None: + arrays[k] = getattr(self, k) + header = {"task": self.task, "questions": self.questions, "choices": self.choices, "meta": self.meta} + arrays["header"] = np.frombuffer(json.dumps(header).encode(), dtype=np.uint8) + np.savez(path, **arrays) + + @classmethod + def load(cls, path: str | Path) -> "DecisionData": + z = np.load(path) + header = json.loads(bytes(z["header"]).decode()) + state = {k[6:]: z[k] for k in z.files if k.startswith("state/")} + opt = {k: z[k] for k in OPTIONAL if k in z.files} + return cls(header["task"], state, header["questions"], z["question_idx"], header["choices"], + z["choice_idx"], z["target"], z["group"], meta=header.get("meta", {}), **opt) + + # ------------------------------------------------------------ slicing + def subset(self, idx: np.ndarray) -> "DecisionData": + idx = np.asarray(idx, dtype=np.int64) + state = {} + for k, v in self.state.items(): + if k.endswith("_offsets"): + continue + if f"{k}_offsets" in self.state: + flat, lengths = ragged_take(v, self.state[f"{k}_offsets"], idx) + offs = np.zeros(len(idx) + 1, dtype=np.int64) + np.cumsum(lengths, out=offs[1:]) + state[k], state[f"{k}_offsets"] = flat, offs + else: + state[k] = v[idx] + opt = {k: getattr(self, k)[idx] for k in OPTIONAL if getattr(self, k) is not None} + return DecisionData(self.task, state, self.questions, self.question_idx[idx], self.choices, + self.choice_idx[idx], self.target[idx], self.group[idx], meta=dict(self.meta), **opt) + + @classmethod + def concat(cls, parts: list["DecisionData"]) -> "DecisionData": + """Rows of several datasets of the same task; question/choice vocabularies are merged.""" + first = parts[0] + questions = list(dict.fromkeys(q for p in parts for q in p.questions)) + choices = list(dict.fromkeys(c for p in parts for c in p.choices)) + qmap = {q: i for i, q in enumerate(questions)} + cmap = {c: i for i, c in enumerate(choices)} + nmax = max(p.choice_idx.shape[1] for p in parts) + qi, ci = [], [] + for p in parts: + qi.append(np.array([qmap[q] for q in p.questions], np.int32)[p.question_idx]) + clut = np.array([cmap[c] for c in p.choices] + [-1], np.int32) # index -1 -> -1 + pad = np.full((len(p), nmax), -1, np.int32) + pad[:, : p.choice_idx.shape[1]] = clut[p.choice_idx] + ci.append(pad) + state = {} + for k in first.state: + if k.endswith("_offsets"): + continue + if f"{k}_offsets" in first.state: + offs, base = [np.zeros(1, np.int64)], 0 + for p in parts: + offs.append(p.state[f"{k}_offsets"][1:] + base) + base += int(p.state[f"{k}_offsets"][-1]) + state[f"{k}_offsets"] = np.concatenate(offs) + state[k] = np.concatenate([p.state[k] for p in parts]) + opt = {} + for k in OPTIONAL: + if getattr(first, k) is None: + continue + vals = [] + for p in parts: + v = getattr(p, k) + if v.ndim == 2 and v.shape[1] < nmax: + fill = -1e9 if k == "teacher_logits" else 0.0 + v = np.pad(v, ((0, 0), (0, nmax - v.shape[1])), constant_values=fill) + vals.append(v) + opt[k] = np.concatenate(vals) + return cls(first.task, state, questions, np.concatenate(qi), choices, np.concatenate(ci), + np.concatenate([p.target for p in parts]), np.concatenate([p.group for p in parts]), + meta=dict(first.meta), **opt) + + def row_choices(self, i: int) -> list[str]: + return [self.choices[j] for j in self.choice_idx[i] if j >= 0] + + +def split_by_group(data: DecisionData, fractions=(0.9, 0.05, 0.05), seed: int = 0, + dedupe: bool = True) -> dict[str, DecisionData]: + """Group-level split (whole episodes/documents go to one split), then drop + val/test rows whose exact state also appears in train.""" + groups = np.unique(data.group) + rng = np.random.default_rng(seed) + rng.shuffle(groups) + n_val = max(1, int(round(len(groups) * fractions[1]))) + n_test = max(1, int(round(len(groups) * fractions[2]))) + sets = {"val": groups[:n_val], "test": groups[n_val:n_val + n_test], "train": groups[n_val + n_test:]} + out, dropped = {}, {} + for name in ("train", "val", "test"): + idx = np.nonzero(np.isin(data.group, sets[name]))[0] + if dedupe and name != "train" and data.hash is not None: + keep = ~np.isin(data.hash[idx], data.hash[out["train_idx"]]) + dropped[name] = int((~keep).sum()) + idx = idx[keep] + out[f"{name}_idx"] = idx + splits = {name: data.subset(out[f"{name}_idx"]) for name in ("train", "val", "test")} + for name, s in splits.items(): + s.meta.update(split=name, dropped_duplicates=dropped.get(name, 0)) + return splits diff --git a/code/minijev/datasets/jsonl.py b/code/minijev/datasets/jsonl.py new file mode 100644 index 0000000000000000000000000000000000000000..db8ca7b4bad9ccb2f250abdac8f150c8ce208d65 --- /dev/null +++ b/code/minijev/datasets/jsonl.py @@ -0,0 +1,109 @@ +"""General decision datasets in JSONL, one decision per line: + + {"state": "hotdog", "question": "Is this food?", "choices": ["yes", "no"], "target": "yes"} + +Optional fields: + teacher_distribution {"yes": 0.97, "no": 0.03} soft labels from a teacher (LLM, oracle, ...) + teacher_probs [0.97, 0.03] same, aligned with `choices` + score 0.83 continuous target for the score head + group any id; splits and dedupe work per group (entity, document, episode) + +`target` may be the choice text or its index; it may be missing when only a +teacher distribution is given. The teacher is only needed to *build* the data: +distillation stores its probabilities, the deployed model never calls it. +""" +from __future__ import annotations + +import json +import zlib +from pathlib import Path +from typing import Iterable + +import numpy as np + +from .decision_data import DecisionData + +NEG = -1e9 + + +def read_jsonl(path: str | Path) -> list[dict]: + with open(path, encoding="utf-8") as f: + return [json.loads(line) for line in f if line.strip()] + + +def write_jsonl(path: str | Path, rows: Iterable[dict]) -> None: + Path(path).parent.mkdir(parents=True, exist_ok=True) + with open(path, "w", encoding="utf-8") as f: + for r in rows: + f.write(json.dumps(r, ensure_ascii=False) + "\n") + + +def _gid(v) -> int: + if isinstance(v, (int, np.integer)): + return int(v) + return zlib.crc32(str(v).encode()) + + +def teacher_probs(row: dict) -> list[float] | None: + if row.get("teacher_probs") is not None: + p = [float(x) for x in row["teacher_probs"]] + elif row.get("teacher_distribution") is not None: + td = row["teacher_distribution"] + p = [float(td.get(c, 0.0)) for c in row["choices"]] + else: + return None + s = sum(p) + if len(p) != len(row["choices"]) or s <= 0: + raise ValueError(f"bad teacher distribution for row {row.get('question')!r}") + return [x / s for x in p] + + +def rows_to_data(rows: list[dict], task: str = "text", task_cfg: dict | None = None) -> DecisionData: + from minijev.tasks import get_task + + t = get_task(task, task_cfg or {}) + n = len(rows) + nmax = max((len(r.get("choices") or []) for r in rows), default=1) or 1 + qvocab, cvocab = {}, {} + qi = np.zeros(n, np.int32) + ci = np.full((n, nmax), -1, np.int32) + target = np.full(n, -1, np.int64) + teacher = np.full((n, nmax), NEG, np.float32) + score = np.full(n, np.nan, np.float32) + has_teacher = has_score = False + for i, r in enumerate(rows): + qi[i] = qvocab.setdefault(r.get("question", ""), len(qvocab)) + ch = list(r.get("choices") or []) + if len(set(ch)) != len(ch): + raise ValueError(f"duplicate choices in row {i}: {ch}") + for j, c in enumerate(ch): + ci[i, j] = cvocab.setdefault(c, len(cvocab)) + tg = r.get("target") + if tg is not None: + target[i] = tg if isinstance(tg, int) else ch.index(tg) + p = teacher_probs(r) + if p is not None: + has_teacher = True + teacher[i, : len(p)] = np.log(np.maximum(np.array(p, np.float32), 1e-8)) + if r.get("score") is not None: + has_score = True + score[i] = float(r["score"]) + groups = np.array([_gid(r.get("group", r.get("state") or r.get("question", ""))) for r in rows], np.int64) + hashes = np.array([_gid(f"{r.get('state') or ''}\x00{r.get('question', '')}") for r in rows], np.int64) + return DecisionData(task=task, state=t.states_to_arrays([r.get("state") or "" for r in rows]), + questions=list(qvocab), question_idx=qi, choices=list(cvocab), choice_idx=ci, + target=target, group=groups, teacher_logits=teacher if has_teacher else None, + hash=hashes, score=score if has_score else None, + meta={"source": "jsonl", "rows": n}) + + +def generate_splits(out_dir: str | Path, samples: int = 0, source: str | None = None, seed: int = 0, + fractions=(0.9, 0.05, 0.05), task: str = "text", **_) -> dict: + """`data.generate: {source: file.jsonl}` -> group-split train/val/test .npz.""" + from .decision_data import split_by_group + + data = rows_to_data(read_jsonl(source), task=task) + splits = split_by_group(data, fractions, seed=seed) + for k, v in splits.items(): + v.save(Path(out_dir) / f"{k}.npz") + return {k: len(v) for k, v in splits.items()} diff --git a/code/minijev/device.py b/code/minijev/device.py new file mode 100644 index 0000000000000000000000000000000000000000..b1df5570b4cec9b69f32417e9f5fbfe4f5a152ac --- /dev/null +++ b/code/minijev/device.py @@ -0,0 +1,94 @@ +"""Hardware detection and automatic runtime profile (CUDA / Apple MPS / CPU). + +The *effective* batch size is part of the experiment (it changes results); the +micro-batch that fits in memory and the gradient accumulation to reach the +effective batch are hardware details chosen here, so the same config gives +comparable results on a laptop and on a rented GPU. +""" +from __future__ import annotations + +import os +import platform +from dataclasses import asdict, dataclass + +import torch + + +@dataclass +class RuntimeProfile: + device: str + device_name: str + vram_gb: float | None + amp_dtype: str | None # "bf16" | "fp16" | None + micro_batch: int + grad_accum: int + num_workers: int + compile: bool + threads: int + + def to_dict(self) -> dict: + return asdict(self) + + +def detect_device(prefer: str = "auto") -> str: + if prefer != "auto": + return prefer + if torch.cuda.is_available(): + return "cuda" + if getattr(torch.backends, "mps", None) is not None and torch.backends.mps.is_available(): + return "mps" + return "cpu" + + +def resolve_runtime(train_cfg: dict, model_params: int | None = None) -> RuntimeProfile: + hw = train_cfg.get("hardware", {}) or {} + device = detect_device(hw.get("device", "auto")) + eff = int(train_cfg.get("batch_size", 256)) + vram = None + name = platform.processor() or platform.machine() + if device == "cuda": + props = torch.cuda.get_device_properties(0) + vram = props.total_memory / 1024**3 + name = props.name + # activations dominate for these tiny models; ~1 GB per 4k samples of a ~5M model is a + # conservative rule of thumb. `max_micro_batch` in the config always wins. + per_gb = hw.get("samples_per_gb", 2048 if (model_params or 0) > 3e6 else 8192) + cap = int(max(64, (vram - 1.5) * per_gb)) + elif device == "mps": + cap = 1024 + else: + cap = 512 + cap = min(cap, int(hw.get("max_micro_batch", cap))) + micro = eff + while micro > cap and micro % 2 == 0: + micro //= 2 + accum = max(1, eff // micro) + + amp = hw.get("amp", "auto") + if amp == "auto": + if device == "cuda": + amp = "bf16" if torch.cuda.is_bf16_supported() else "fp16" + else: + amp = None # CPU autocast rarely helps small models; MPS fp16 is flaky for training + elif amp in ("none", False): + amp = None + + cpus = os.cpu_count() or 2 + workers = hw.get("num_workers", "auto") + if workers == "auto": + workers = min(8, max(0, cpus // 2 - 1)) if device != "cpu" else min(4, max(0, cpus // 4)) + threads = hw.get("threads", "auto") + if threads == "auto": + threads = max(1, cpus - int(workers)) if device == "cpu" else max(1, min(4, cpus)) + compile_ = hw.get("compile", "auto") + if compile_ == "auto": + compile_ = device == "cuda" # launch-overhead bound tiny models gain most on GPU + return RuntimeProfile(device, name, round(vram, 1) if vram else None, amp, micro, accum, + int(workers), bool(compile_), int(threads)) + + +def autocast(profile: RuntimeProfile): + if profile.amp_dtype is None: + return torch.autocast(device_type="cpu", enabled=False) + dtype = torch.bfloat16 if profile.amp_dtype == "bf16" else torch.float16 + return torch.autocast(device_type=profile.device, dtype=dtype) diff --git a/code/minijev/encoders/__init__.py b/code/minijev/encoders/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4861f2c0cd96813ba2b54cf9a3874d386e93eb0e --- /dev/null +++ b/code/minijev/encoders/__init__.py @@ -0,0 +1,40 @@ +"""State encoders (modality -> tokens (B, S, d) + mask in the shared latent space). + + kind input key class + grid state_grid GridStateEncoder (Snake uses it via environments/snake/encoder.py) + text state_ids ByteTextStateEncoder | PretrainedTextStateEncoder (shares the text backbone) + numeric state_x NumericStateEncoder + log state_log_ids text encoder on normalised logs (see numeric.normalise_log) +""" +from __future__ import annotations + +from torch import nn + +from .grid import GridStateEncoder +from .numeric import NumericStateEncoder +from minijev.text_task_utils import normalise_log +from .text import (ByteTextStateEncoder, PretrainedTextBackbone, PretrainedTextStateEncoder, Projection, + QuestionEncoder, TextPooler, TextStateEncoder) + +from minijev.keys import STATE_INPUTS # noqa: E402 + + +def build_state_encoder(kind: str, d: int, cfg: dict, embed: nn.Embedding | None = None, + d_text: int | None = None, cls=None) -> nn.Module: + cfg = dict(cfg or {}) + if cls is not None: + return cls(d, **cfg) + if kind == "grid": + return GridStateEncoder(d, **cfg) + if kind in ("text", "log"): + if d_text is not None: # pretrained text backbone + return PretrainedTextStateEncoder(d, d_text, **cfg) + return ByteTextStateEncoder(embed, d, **cfg) + if kind == "numeric": + return NumericStateEncoder(d, **cfg) + raise ValueError(f"unknown state encoder {kind!r}") + + +__all__ = ["STATE_INPUTS", "build_state_encoder", "GridStateEncoder", "NumericStateEncoder", "normalise_log", + "ByteTextStateEncoder", "TextStateEncoder", "PretrainedTextBackbone", "PretrainedTextStateEncoder", + "Projection", "QuestionEncoder", "TextPooler"] diff --git a/code/minijev/encoders/__pycache__/__init__.cpython-314.pyc b/code/minijev/encoders/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..960822c13bae89b9e0396b8e1093c5e92130f682 Binary files /dev/null and b/code/minijev/encoders/__pycache__/__init__.cpython-314.pyc differ diff --git a/code/minijev/encoders/__pycache__/grid.cpython-314.pyc b/code/minijev/encoders/__pycache__/grid.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4ede77df1572cc5a52406eec7bfa5409f3152d3 Binary files /dev/null and b/code/minijev/encoders/__pycache__/grid.cpython-314.pyc differ diff --git a/code/minijev/encoders/__pycache__/numeric.cpython-314.pyc b/code/minijev/encoders/__pycache__/numeric.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3940f6ae9635a05090e52fb6484a06d4c37b25d5 Binary files /dev/null and b/code/minijev/encoders/__pycache__/numeric.cpython-314.pyc differ diff --git a/code/minijev/encoders/__pycache__/text.cpython-314.pyc b/code/minijev/encoders/__pycache__/text.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a0eaa8b65b22c111ce33995f3f9946519101a38 Binary files /dev/null and b/code/minijev/encoders/__pycache__/text.cpython-314.pyc differ diff --git a/code/minijev/encoders/grid.py b/code/minijev/encoders/grid.py new file mode 100644 index 0000000000000000000000000000000000000000..b6a89c38034c567d972ae8f6f8af6abe3a164862 --- /dev/null +++ b/code/minijev/encoders/grid.py @@ -0,0 +1,52 @@ +"""Grid state encoder: multi-channel 2-D board -> tokens in the core space.""" +from __future__ import annotations + +import torch +import torch.nn.functional as F +from torch import nn + + +class GridStateEncoder(nn.Module): + """Multi-channel board -> tokens. + + A small conv stem sees local 3x3/5x5 neighbourhoods (collisions, corridors), + optional patching (stride p) shrinks the token count for big boards, and the + transformer downstream does the global reasoning (connectivity, space). + Factorised row/col embeddings are sliced to the actual board size, so one + model can play several board sizes. + """ + + uses_backbone = False + + def __init__(self, d: int, in_channels: int, stem_channels: int = 32, patch_size: int = 1, + max_grid: int = 34, crop_border: int = 1, **_): + super().__init__() + self.p = patch_size + # the stem already "sees" the wall border; dropping its tokens afterwards cuts the + # sequence (10x10: 144 -> 100 tokens) and attention cost without losing information + self.crop = crop_border + self.stem = nn.Sequential( + nn.Conv2d(in_channels, stem_channels, 3, padding=1), nn.GELU(), + nn.Conv2d(stem_channels, stem_channels, 3, padding=1), nn.GELU(), + ) + self.patch = nn.Conv2d(stem_channels, d, patch_size, stride=patch_size) + n = (max_grid + patch_size - 1) // patch_size + self.row = nn.Parameter(torch.zeros(n, d)) + self.col = nn.Parameter(torch.zeros(n, d)) + nn.init.normal_(self.row, std=0.02) + nn.init.normal_(self.col, std=0.02) + + def forward(self, grid): # (B, C, H, W) + x = self.stem(grid) + if self.crop: + x = x[:, :, self.crop:-self.crop, self.crop:-self.crop] + if self.p > 1: + H, W = x.shape[-2:] + ph, pw = (-H) % self.p, (-W) % self.p + if ph or pw: + x = F.pad(x, (0, pw, 0, ph)) + x = self.patch(x) # (B, d, h, w) + B, D, h, w = x.shape + x = x + (self.row[:h, None, :] + self.col[None, :w, :]).permute(2, 0, 1) + tokens = x.flatten(2).transpose(1, 2) + return tokens, torch.ones(tokens.shape[:2], dtype=torch.bool, device=tokens.device) diff --git a/code/minijev/encoders/numeric.py b/code/minijev/encoders/numeric.py new file mode 100644 index 0000000000000000000000000000000000000000..ebd409c1a75c64b0026aeab74c87a68fc9e1bdb2 --- /dev/null +++ b/code/minijev/encoders/numeric.py @@ -0,0 +1,33 @@ +"""Numeric and log state encoders. + +NumericStateEncoder: a fixed-length feature vector (metrics, sensor readings, a +tabular row) -> one token per feature (value * feature embedding + feature id), +so the core can attend to individual features. Missing values are NaN -> masked. + +LogStateEncoder: a text state encoder for logs. Logs are text, so it reuses the +text encoder; it only normalises volatile tokens (hex ids, numbers, timestamps) +and keeps the last `max_lines` lines before tokenisation (see minijev.text_task_utils). +""" +from __future__ import annotations + +import torch +from torch import nn + + +class NumericStateEncoder(nn.Module): + uses_backbone = False + + def __init__(self, d: int, n_features: int, **_): + super().__init__() + self.feat = nn.Parameter(torch.zeros(n_features, d)) + self.scale = nn.Parameter(torch.zeros(n_features, d)) + nn.init.normal_(self.feat, std=0.02) + nn.init.normal_(self.scale, std=0.02) + self.mlp = nn.Sequential(nn.LayerNorm(d), nn.Linear(d, d), nn.GELU(), nn.Linear(d, d)) + + def forward(self, x): # (B, F) float, NaN = missing + valid = ~torch.isnan(x) + v = torch.nan_to_num(x).unsqueeze(-1) + tok = self.feat + v * self.scale + tok = tok + self.mlp(tok) + return tok, valid diff --git a/code/minijev/encoders/text.py b/code/minijev/encoders/text.py new file mode 100644 index 0000000000000000000000000000000000000000..98de29f51dbff05526080680876f6fe3c535240e --- /dev/null +++ b/code/minijev/encoders/text.py @@ -0,0 +1,194 @@ +"""Text encoders: question, choice labels and text states -> the shared latent space. + +Two backends behind the same interface: + +* `byte` (original MiniJEV): byte embeddings + a tiny pooler, trained from scratch. + ~0 params, no files, but knows nothing about language (see reports: sentiment failed). +* `pretrained`: a small pretrained sentence encoder (MiniLM / E5 / ...) through + `transformers`, frozen, top-k fine-tuned or fully fine-tuned. Its native width + (e.g. 384) is projected to the core width `d` (e.g. 384 -> 128). + +The backbone returns (tokens, mask, pooled) in its native width; each consumer +(question, choice, text state) owns its own projection, so the backbone can be +shared and frozen while the projections train. +""" +from __future__ import annotations + +import torch +import torch.nn.functional as F +from torch import nn + +from minijev.tokenizer import PAD + + +# ------------------------------------------------------------------------ byte +class TextPooler(nn.Module): + """Short text (question or one choice label) -> one vector. + + Byte embeddings + learned positions, a per-token MLP, masked mean-pool. + Positions make it order-aware ("ON" != "NO") at negligible cost. + """ + + def __init__(self, embed: nn.Embedding, d: int, max_len: int): + super().__init__() + self.embed = embed + self.pos = nn.Parameter(torch.zeros(max_len, d)) + nn.init.normal_(self.pos, std=0.02) + self.ln = nn.LayerNorm(d) + self.mlp = nn.Sequential(nn.Linear(d, 2 * d), nn.GELU(), nn.Linear(2 * d, d)) + self.out = nn.Sequential(nn.LayerNorm(d), nn.Linear(d, d)) + + def forward(self, ids): # (..., L) -> (..., d) + L = ids.shape[-1] + x = self.embed(ids) + self.pos[:L] + x = x + self.mlp(self.ln(x)) + m = (ids != PAD).unsqueeze(-1).to(x.dtype) + pooled = (x * m).sum(-2) / m.sum(-2).clamp(min=1.0) + return self.out(pooled) + + +class ByteTextStateEncoder(nn.Module): + """Byte sequence -> tokens. A depthwise-separable conv builds sub-word features; + `stride` > 1 shortens long texts before the transformer.""" + + uses_backbone = False + + def __init__(self, embed: nn.Embedding, d: int, max_len: int = 256, stride: int = 2, kernel: int = 5, **_): + super().__init__() + self.embed = embed + self.stride = stride + self.pos = nn.Parameter(torch.zeros(max_len, d)) + nn.init.normal_(self.pos, std=0.02) + self.dw = nn.Conv1d(d, d, kernel, stride=stride, padding=kernel // 2, groups=d) + self.pw = nn.Sequential(nn.GELU(), nn.Conv1d(d, d, 1)) + + def forward(self, ids): # (B, L) + L = ids.shape[1] + valid = ids != PAD + x = (self.embed(ids) + self.pos[:L]) * valid.unsqueeze(-1).to(self.pos.dtype) + x = self.pw(self.dw(x.transpose(1, 2))).transpose(1, 2) + if self.stride > 1: + valid = F.max_pool1d(valid.float().unsqueeze(1), self.stride, self.stride, + ceil_mode=True).squeeze(1)[:, : x.shape[1]] > 0 + return x, valid + + +TextStateEncoder = ByteTextStateEncoder # legacy name + + +# ------------------------------------------------------------------ pretrained +class PretrainedTextBackbone(nn.Module): + """A Hugging Face encoder -> (tokens (B, L, dt), mask (B, L), pooled (B, dt)). + + finetune: "frozen" | "full" | int k (train only the top-k transformer layers). + Pooling is the masked mean (what sentence-transformers / E5 models are trained with). + """ + + def __init__(self, name: str, finetune="frozen", pad_id: int = 0, dtype: str | None = None, **_): + super().__init__() + from transformers import AutoModel + + self.name = name + self.model = AutoModel.from_pretrained(name) + self.dim = int(self.model.config.hidden_size) + self.pad_id = pad_id + self.finetune = finetune + self._apply_finetune(finetune) + + def _apply_finetune(self, finetune): + for p in self.model.parameters(): + p.requires_grad_(finetune == "full") + if isinstance(finetune, int) and finetune > 0: + layers = self._layers() + for layer in layers[-finetune:]: + for p in layer.parameters(): + p.requires_grad_(True) + + def _layers(self): + for path in ("encoder.layer", "layers", "transformer.layer"): + obj = self.model + try: + for part in path.split("."): + obj = getattr(obj, part) + return list(obj) + except AttributeError: + continue + raise ValueError(f"cannot find transformer layers in {type(self.model).__name__}") + + @property + def frozen(self) -> bool: + return self.finetune == "frozen" + + def train(self, mode: bool = True): + super().train(mode) + if self.frozen: # frozen backbone: no dropout, deterministic embeddings (cacheable) + self.model.eval() + return self + + def forward(self, ids): + mask = ids != self.pad_id + with torch.set_grad_enabled(torch.is_grad_enabled() and not self.frozen): + tok = self.model(input_ids=ids, attention_mask=mask.long()).last_hidden_state + m = mask.unsqueeze(-1).to(tok.dtype) + pooled = (tok * m).sum(1) / m.sum(1).clamp(min=1.0) + return tok, mask, pooled + + +class Projection(nn.Module): + """Native encoder width -> core width (e.g. 384 -> 128).""" + + def __init__(self, d_in: int, d: int, hidden: int | None = None): + super().__init__() + self.net = (nn.Sequential(nn.LayerNorm(d_in), nn.Linear(d_in, d)) if not hidden else + nn.Sequential(nn.LayerNorm(d_in), nn.Linear(d_in, hidden), nn.GELU(), nn.Linear(hidden, d))) + + def forward(self, x): + return self.net(x) + + +class QuestionEncoder(nn.Module): + """Question -> question tokens for the core. + + byte: 1 pooled token (original MiniJEV) + pretrained: [pooled] + projected contextual tokens (so the core can attend to "food" vs "animal") + """ + + def __init__(self, d: int, embed: nn.Embedding | None = None, max_len: int = 32, d_text: int | None = None, + tokens: bool = True): + super().__init__() + self.byte = embed is not None + if self.byte: + self.pooler = TextPooler(embed, d, max_len) + else: + self.tokens = tokens + self.proj_pooled = Projection(d_text, d, hidden=2 * d) + self.proj_tokens = Projection(d_text, d) if tokens else None + + def forward(self, ids=None, backbone_out=None): + if self.byte: + q = self.pooler(ids).unsqueeze(1) + return q, torch.ones(q.shape[:2], dtype=torch.bool, device=q.device) + tok, mask, pooled = backbone_out + q = self.proj_pooled(pooled).unsqueeze(1) + ones = torch.ones(q.shape[:2], dtype=torch.bool, device=q.device) + if not self.tokens: + return q, ones + return torch.cat([q, self.proj_tokens(tok)], 1), torch.cat([ones, mask], 1) + + +class PretrainedTextStateEncoder(nn.Module): + """Text state (document, log, entity, ...) -> projected backbone tokens.""" + + uses_backbone = True + + def __init__(self, d: int, d_text: int, **_): + super().__init__() + self.proj_pooled = Projection(d_text, d, hidden=2 * d) + self.proj_tokens = Projection(d_text, d) + + def forward(self, backbone_out): + tok, mask, pooled = backbone_out + p = self.proj_pooled(pooled).unsqueeze(1) + # rows with an empty state (all pad) get no valid state token at all + has = mask.any(1, keepdim=True) + return torch.cat([p, self.proj_tokens(tok)], 1), torch.cat([has, mask], 1) diff --git a/code/minijev/estimate.py b/code/minijev/estimate.py new file mode 100644 index 0000000000000000000000000000000000000000..4a43bd6269d680df7b2390097546b9c4b5306c20 --- /dev/null +++ b/code/minijev/estimate.py @@ -0,0 +1,118 @@ +"""Pre-flight training time / cost estimate from a *measured* throughput. + +Runs the real training loop (same data pipeline, model, micro-batch, AMP, +compile) for `bench_seconds` on the current machine, takes the steady-state +samples/s (first logging window dropped: compile / warm-up), then extrapolates. +Run it on the rented instance itself for GPU numbers - measuring locally and +dividing by a guessed speed-up is exactly the kind of invented number to avoid. +""" +from __future__ import annotations + +import csv +import copy +import tempfile +import time +from pathlib import Path + +from minijev.model import human_params + + +def measure_throughput(cfg: dict, seconds: float = 60.0) -> dict: + from minijev.training.supervised import train + + cfg = copy.deepcopy(cfg) + data_dir = Path(cfg["data"]["dir"]) + tmp = Path(tempfile.mkdtemp(prefix="minijev-est-")) + if not (data_dir / "train.npz").exists(): + # same generator settings, small size: per-row encoding cost is identical + gen = dict(cfg["data"].get("generate", {})) + gen["samples"] = 30_000 + cfg["data"] = {"dir": str(tmp / "data"), "generate": gen} + tcfg = cfg["training"] + tcfg["log_every"] = 10 + tcfg["eval_every"] = 10**9 + tcfg["checkpoint_every"] = 10**9 + s = train(cfg, run_dir=tmp / "run", max_minutes=seconds / 60, quiet=True, final_eval=False) + rows = list(csv.DictReader(open(tmp / "run" / "metrics.csv"))) + rates = [float(r["samples_per_sec"]) for r in rows if r.get("samples_per_sec")] + steady = rates[1:] or rates + sps = sorted(steady)[len(steady) // 2] if steady else s["throughput_samples_per_sec"] + return {"samples_per_sec": sps, "runtime": s["runtime"], "params": s["params"], "train_rows": s["train_rows"], + "windows": len(rates)} + + +def measure_generation(cfg: dict, n: int = 5000) -> float | None: + """Rows/s of oracle data generation on this machine (all cores).""" + gen = cfg["data"].get("generate") + if not gen: + return None + import importlib + mod = importlib.import_module(f"environments.{cfg['task']['name']}.dataset") + g = {k: v for k, v in gen.items() if k not in ("samples", "seed")} + t = time.time() + mod.generate(n, **g) + return n / (time.time() - t) + + +def estimate(cfg: dict, hourly_cost: float, throughput: float | None = None, bench_seconds: float = 60, + gpu_name: str | None = None, budget: float | None = None, overhead_minutes: float = 3.0) -> dict: + from minijev.device import resolve_runtime + from minijev.tasks import get_task + from minijev.training.supervised import make_model + + task = get_task(cfg["task"]["name"], cfg["task"]) + params = make_model(cfg, task).num_parameters() + data_dir = Path(cfg["data"]["dir"]) + if (data_dir / "train.npz").exists(): + import numpy as np + rows = int(len(np.load(data_dir / "train.npz")["target"])) + gen_rows = 0 + else: + total = int(cfg["data"].get("generate", {}).get("samples", 0)) + rows, gen_rows = int(total * 0.9), total + if cfg["data"].get("train_limit"): + rows = min(rows, int(cfg["data"]["train_limit"])) + epochs = float(cfg["training"].get("epochs", 1)) + prof = resolve_runtime(cfg["training"], params) + measured = throughput is None + if measured: + print(f"[estimate] measuring real throughput for {bench_seconds:.0f}s on {prof.device} ({prof.device_name}) ...") + m = measure_throughput(cfg, bench_seconds) + throughput = m["samples_per_sec"] + gen_rate = measure_generation(cfg) if gen_rows else None + train_s = rows * epochs / throughput + evals = max(1, int(rows * epochs / cfg["training"].get("batch_size", 256) / cfg["training"].get("eval_every", 1000))) + eval_rows = min(cfg["training"].get("eval_max_rows", 20000), int(rows / 18)) + eval_s = evals * eval_rows / (3 * throughput) # inference ~3x cheaper than a training step + gen_s = gen_rows / gen_rate if gen_rate else 0.0 + total_s = train_s + eval_s + gen_s + overhead_minutes * 60 + hours = total_s / 3600 + cost = hours * hourly_cost + out = {"model": cfg.get("name"), "params": params, "train_rows": rows, "epochs": epochs, + "device": gpu_name or prof.device_name, "throughput_samples_per_sec": round(throughput, 1), + "throughput_measured": measured, "train_minutes": round(train_s / 60, 1), + "data_generation_minutes": round(gen_s / 60, 1), "eval_minutes": round(eval_s / 60, 1), + "overhead_minutes": overhead_minutes, "total_minutes": round(total_s / 60, 1), + "gpu_hours": round(hours, 3), "hourly_cost": hourly_cost, "estimated_cost": round(cost, 3)} + print() + print(f"Model: MiniJEV {cfg.get('name')}") + print(f"Parameters: {human_params(params)}") + print(f"Dataset: {rows:,} training examples" + (f" (+ generating {gen_rows:,})" if gen_rows else "")) + print(f"Epochs: {epochs:g}") + print() + print(f"Device: {out['device']} (micro-batch {prof.micro_batch} x accum {prof.grad_accum}, amp={prof.amp_dtype})") + print(f"{'Measured' if measured else 'Given'} throughput: {throughput:,.0f} samples/sec") + print() + print(f"Estimated duration: {_fmt_min(total_s / 60)} (train {_fmt_min(train_s / 60)}, " + f"data gen {_fmt_min(gen_s / 60)}, eval {_fmt_min(eval_s / 60)}, overhead {overhead_minutes:g} min)") + print(f"Estimated GPU hours: {hours:.3f}") + print(f"Estimated cost: €{cost:.2f} (at €{hourly_cost:.3f}/h)") + if budget is not None and cost > budget: + scale = budget / cost + print(f"\n!! Over budget (€{budget:.2f}). Reduce e.g. epochs to {epochs * scale:.2f} " + f"or train rows to {int(rows * scale):,}.") + return out + + +def _fmt_min(m: float) -> str: + return f"{m:.1f} min" if m < 120 else f"{m / 60:.1f} h" diff --git a/code/minijev/export/__init__.py b/code/minijev/export/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code/minijev/export/onnx_export.py b/code/minijev/export/onnx_export.py new file mode 100644 index 0000000000000000000000000000000000000000..7888fd4df845f6a342dee253c0d3f353adf67d3d --- /dev/null +++ b/code/minijev/export/onnx_export.py @@ -0,0 +1,107 @@ +"""PyTorch checkpoint -> ONNX (+ parity check, + optional INT8 dynamic quantization). + +The exported graph takes (state, question_ids, choice_ids) with dynamic batch, +number of choices and state size, and returns (probs, logits, embedding); the +calibration temperature is baked in. Everything the runtime needs to +pre-process inputs is stored in the model's metadata (key "minijev"). +""" +from __future__ import annotations + +import json +from pathlib import Path + +import numpy as np +import torch + +from minijev.inference.runtime import META_KEY, OnnxDecider, TorchDecider +from minijev.model import STATE_INPUTS, ExportWrapper + + +def export_onnx(checkpoint: str | Path, out: str | Path | None = None, opset: int = 18, + verify: bool = True, quantize: bool = True) -> dict: + import onnx + + checkpoint = Path(checkpoint) + out = Path(out) if out else checkpoint.with_suffix(".onnx") + torch_dec = TorchDecider(checkpoint) + model, cfg, task = torch_dec.model, torch_dec.cfg, torch_dec.task + state_key = STATE_INPUTS[task.state_encoder] + wrapper = ExportWrapper(model, state_key).eval() + + states = task.example_states(4) + question = task.default_question + choices = list(task.default_choices) + x = torch_dec.encode(states) + q, c = torch_dec._tokens(question, tuple(choices)) + B = len(states) + args = (torch.as_tensor(x), torch.as_tensor(np.repeat(q, B, 0)), torch.as_tensor(np.repeat(c, B, 0))) + + state_axes = {0: "batch", 2: "height", 3: "width"} if x.ndim == 4 else {0: "batch", 1: "length"} + dynamic_axes = {state_key: state_axes, "question_ids": {0: "batch"}, + "choice_ids": {0: "batch", 1: "n_choices"}, + "probs": {0: "batch", 1: "n_choices"}, "logits": {0: "batch", 1: "n_choices"}, + "embedding": {0: "batch"}} + # TorchScript-based exporter: mature, handles SDPA with masks and dynamic axes well + torch.onnx.export(wrapper, args, str(out), input_names=[state_key, "question_ids", "choice_ids"], + output_names=["probs", "logits", "embedding"], dynamic_axes=dynamic_axes, + opset_version=opset, dynamo=False) + meta = {"task": task.name, "task_cfg": cfg["task"], "state_input": state_key, + "max_question_len": torch_dec.max_question_len, "max_choice_len": torch_dec.max_choice_len, + "temperature": model.temperature, "params": model.num_parameters(), "config_name": cfg.get("name"), + "default_question": question, "default_choices": choices} + m = onnx.load(str(out)) + entry = m.metadata_props.add() + entry.key, entry.value = META_KEY, json.dumps(meta) + onnx.save(m, str(out)) + report = {"onnx": str(out), "size_mb": round(out.stat().st_size / 2**20, 3), "meta": meta} + if verify: + report["parity_fp32"] = parity(torch_dec, OnnxDecider(out), task) + if quantize: + q_out = out.with_name(out.stem + ".int8.onnx") + quantize_int8(out, q_out) + report["onnx_int8"] = str(q_out) + report["size_int8_mb"] = round(q_out.stat().st_size / 2**20, 3) + if verify: + report["parity_int8"] = parity(torch_dec, OnnxDecider(q_out), task) + return report + + +def parity(ref, other, task, n: int = 256, seed: int = 1) -> dict: + """Compare probabilities on real states, including 2- and 3-choice subsets.""" + states = task.example_states(n, seed=seed) + choices = list(task.default_choices) + res = {} + for name, ch in (("all", choices), ("subset", choices[: max(2, len(choices) - 1)])): + p_ref = ref.probs(states, task.default_question, ch) + p_oth = other.probs(states, task.default_question, ch) + res[name] = {"max_abs_diff": float(np.abs(p_ref - p_oth).max()), + "argmax_agreement": float((p_ref.argmax(1) == p_oth.argmax(1)).mean())} + return res + + +def quantize_int8(src: str | Path, dst: str | Path) -> None: + """Dynamic INT8 quantization of MatMul/Gemm weights (activations stay float). + + Conv layers are left in fp32: dynamic ConvInteger kernels are slow on most + CPUs and the stem is a small share of the compute. + """ + from onnxruntime.quantization import QuantType, quantize_dynamic + from onnxruntime.quantization.shape_inference import quant_pre_process + + pre = Path(str(dst) + ".pre.onnx") + try: + quant_pre_process(str(src), str(pre), skip_symbolic_shape=True) + source = pre + except Exception: + source = Path(src) + quantize_dynamic(str(source), str(dst), weight_type=QuantType.QInt8, op_types_to_quantize=["MatMul", "Gemm"]) + if pre.exists(): + pre.unlink() + import onnx + m = onnx.load(str(dst)) + src_meta = {p.key: p.value for p in onnx.load(str(src)).metadata_props} + del m.metadata_props[:] + for k, v in src_meta.items(): + e = m.metadata_props.add() + e.key, e.value = k, v + onnx.save(m, str(dst)) diff --git a/code/minijev/hub.py b/code/minijev/hub.py new file mode 100644 index 0000000000000000000000000000000000000000..b1bb0ec5e78f2fc9464a79127543826cbcb61b3a --- /dev/null +++ b/code/minijev/hub.py @@ -0,0 +1,95 @@ +"""Self-contained, pickle-free model folders (for Hugging Face Hub or local use). + + out/ + config.json MiniJEV config + calibration temperatures + model.safetensors MiniJEV weights (without the text encoder) + text_encoder/ pretrained text encoder (fine-tuned weights if it was trained) + tokenizer + + minijev export-hf --checkpoint runs/x/checkpoints/final.pt --out hf/minijev-general + dec = TorchDecider.from_pretrained("markuz89/minijev-general") # or a local folder + +Loading never unpickles anything: weights are safetensors, the config is JSON. +""" +from __future__ import annotations + +import copy +import json +import shutil +from pathlib import Path + +FORMAT = "minijev-v2" + + +def save_pretrained(checkpoint: str | Path, out: str | Path, extra: dict | None = None) -> Path: + import torch + from safetensors.torch import save_file + + from minijev.training.supervised import make_model + + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + ck = torch.load(checkpoint, map_location="cpu", weights_only=False) + cfg = copy.deepcopy(ck["config"]) + model = make_model(cfg) + model.load_state_dict(ck["model"]) + te = cfg["model"].get("text_encoder") or {} + if model.backbone is not None: + enc_dir = out / "text_encoder" + model.backbone.model.save_pretrained(enc_dir, safe_serialization=True) + tok_src = _tokenizer_file(te.get("tokenizer") or te["name"]) + shutil.copy(tok_src, enc_dir / "tokenizer.json") + cfg["model"]["text_encoder"] = {**te, "name": "text_encoder", "tokenizer": "text_encoder"} + sd, seen = {}, set() + for k, v in model.state_dict().items(): + if k.startswith("backbone.") or v.data_ptr() in seen: # tied weights (shared byte embedding) once + continue + seen.add(v.data_ptr()) + sd[k] = v.detach().cpu().contiguous() + save_file(sd, out / "model.safetensors", metadata={"format": FORMAT}) + meta = {"format": FORMAT, "config": cfg, "temperature": float(model.log_temperature.exp()), + "task_temperatures": ck.get("task_temperatures") or {}, **(extra or {})} + (out / "config.json").write_text(json.dumps(meta, indent=2, ensure_ascii=False, default=str)) + return out + + +def _tokenizer_file(name: str) -> Path: + p = Path(name) + if p.is_dir(): + return p / "tokenizer.json" + from huggingface_hub import hf_hub_download + return Path(hf_hub_download(name, "tokenizer.json")) + + +def resolve(path_or_repo: str | Path) -> Path: + p = Path(path_or_repo) + if p.is_dir(): + return p + from huggingface_hub import snapshot_download + return Path(snapshot_download(str(path_or_repo))) + + +def load_pretrained(path_or_repo: str | Path, device: str = "cpu"): + """-> (model, cfg, task_temperatures) with local paths filled in.""" + from safetensors.torch import load_file + + from minijev.training.supervised import make_model + + root = resolve(path_or_repo) + meta = json.loads((root / "config.json").read_text()) + if meta.get("format") != FORMAT: + raise ValueError(f"{root} is not a {FORMAT} folder") + cfg = meta["config"] + te = cfg["model"].get("text_encoder") or {} + if te.get("type") == "pretrained": + cfg["model"]["text_encoder"] = {**te, "name": str(root / te["name"]), + "tokenizer": str(root / te.get("tokenizer", te["name"]))} + model = make_model(cfg) + weights = load_file(root / "model.safetensors", device="cpu") + res = model.load_state_dict(weights, strict=False) + ptr = {v.data_ptr() for k, v in model.state_dict().items() if k in weights} + full = model.state_dict() + missing = [k for k in res.missing_keys if not k.startswith(("backbone.", "core.scalar_head.")) + and full[k].data_ptr() not in ptr] # tied to a loaded tensor + if missing or res.unexpected_keys: + raise RuntimeError(f"weights mismatch: missing={missing[:10]} unexpected={res.unexpected_keys[:10]}") + return model.to(device).eval(), cfg, meta.get("task_temperatures") or {} diff --git a/code/minijev/inference/__init__.py b/code/minijev/inference/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code/minijev/inference/__pycache__/__init__.cpython-314.pyc b/code/minijev/inference/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ea07c4c1796198ac31ba922303ccfa6715ec181 Binary files /dev/null and b/code/minijev/inference/__pycache__/__init__.cpython-314.pyc differ diff --git a/code/minijev/inference/__pycache__/runtime.cpython-314.pyc b/code/minijev/inference/__pycache__/runtime.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c14623f9540f7c05ecd4f9cb3195483360eec839 Binary files /dev/null and b/code/minijev/inference/__pycache__/runtime.cpython-314.pyc differ diff --git a/code/minijev/inference/runtime.py b/code/minijev/inference/runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..1520f0be265c9927d6ea1adbcee37a36139fc227 --- /dev/null +++ b/code/minijev/inference/runtime.py @@ -0,0 +1,234 @@ +"""Deployment API: the same `decide()` over an ONNX model (numpy + onnxruntime +only, no torch) or a PyTorch checkpoint. + + from minijev import MiniJEV + model = MiniJEV.load("model.onnx") + decision = model.decide(state=state, question="Choose the next move", + choices=["UP", "DOWN", "LEFT", "RIGHT"]) + decision.choice, decision.confidence, decision.scores +""" +from __future__ import annotations + +import json +from functools import lru_cache +from pathlib import Path +from typing import Any, Sequence + +import numpy as np + +from minijev.keys import STATE_INPUTS +from minijev.tokenizers import ByteTokenizer +from minijev.tasks import Task, get_task +from minijev.types import BooleanDecision, Decision + +META_KEY = "minijev" + + +class Decider: + """Common front-end: tokenisation, state encoding, Decision objects. + + `run` returns *calibrated* probabilities/logits (logits / T); the raw, uncalibrated + distribution is softmax(logits * T) and is reported next to it in every Decision. + """ + + task: Task + tokenizer = ByteTokenizer() + max_question_len: int = 32 + max_choice_len: int = 16 + temperature: float = 1.0 + + # -- to implement: probs, logits, embedding from model-ready arrays + def _run(self, state: np.ndarray, question_ids: np.ndarray, choice_ids: np.ndarray): + raise NotImplementedError + + @lru_cache(maxsize=256) + def _tokens(self, question: str, choices: tuple[str, ...]): + dyn = self.tokenizer.kind != "byte" + q = self.tokenizer.encode_batch([question], self.max_question_len, dynamic=dyn) + c = self.tokenizer.encode_batch(list(choices), self.max_choice_len, dynamic=dyn)[None] + return q, c + + def encode(self, states: Sequence[Any]) -> np.ndarray: + enc = self.task.encode_states(states) + return next(iter(enc.values())) + + def probs(self, states: Sequence[Any], question: str, choices: Sequence[str], + encoded: np.ndarray | None = None) -> np.ndarray: + return self.run(states, question, choices, encoded)[0] + + def run(self, states, question, choices, encoded=None): + q, c = self._tokens(question, tuple(choices)) + x = self.encode(states) if encoded is None else encoded + B = x.shape[0] + return self._run(x, np.repeat(q, B, 0), np.repeat(c, B, 0)) + + def decide_batch(self, states: Sequence[Any], question: str, choices: Sequence[str], + return_embedding: bool = False) -> list[Decision]: + if len(set(choices)) != len(choices): + raise ValueError(f"duplicate choices: {list(choices)}") + probs, logits, emb = self.run(states, question, choices) + raw = _softmax(logits * self.temperature) + out = [] + for i in range(len(probs)): + k = int(probs[i].argmax()) + out.append(Decision(choice=choices[k], index=k, confidence=float(probs[i, k]), + scores={ch: float(p) for ch, p in zip(choices, probs[i])}, + logits=[float(v) for v in logits[i]], + embedding=emb[i].tolist() if return_embedding else None, + raw_scores={ch: float(p) for ch, p in zip(choices, raw[i])}, + temperature=self.temperature)) + return out + + def decide(self, state: Any, question: str | None = None, choices: Sequence[str] | None = None, + return_embedding: bool = False) -> Decision: + question = question if question is not None else self.task.default_question + choices = list(choices) if choices is not None else list(self.task.default_choices) + return self.decide_batch([state], question, choices, return_embedding)[0] + + def choice(self, state: Any, question: str, choices: Sequence[str]) -> str: + return self.decide(state, question, choices).choice + + def boolean(self, state: Any, question: str, labels: tuple[str, str] = ("yes", "no")) -> BooleanDecision: + """Yes/no question, answered internally as a 2-choice decision.""" + d = self.decide(state, question, list(labels)) + p_yes = d.scores[labels[0]] + return BooleanDecision(answer=p_yes >= 0.5, confidence=max(p_yes, 1 - p_yes), p_yes=p_yes, + raw_p_yes=d.raw_scores[labels[0]]) + + +def _softmax(x: np.ndarray) -> np.ndarray: + z = x - x.max(-1, keepdims=True) + e = np.exp(z) + return e / e.sum(-1, keepdims=True) + + +class OnnxDecider(Decider): + def __init__(self, path: str | Path, threads: int = 1, providers: list[str] | None = None): + import onnxruntime as ort + + so = ort.SessionOptions() + so.intra_op_num_threads = threads + so.inter_op_num_threads = 1 + so.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL + self.session = ort.InferenceSession(str(path), so, providers=providers or ["CPUExecutionProvider"]) + meta = json.loads(self.session.get_modelmeta().custom_metadata_map[META_KEY]) + self.meta = meta + self.task = get_task(meta["task"], meta.get("task_cfg", {})) + self.max_question_len = meta["max_question_len"] + self.max_choice_len = meta["max_choice_len"] + self.state_input = meta["state_input"] + self.path = str(path) + + def _run(self, state, question_ids, choice_ids): + probs, logits, emb = self.session.run(None, {self.state_input: state, "question_ids": question_ids, + "choice_ids": choice_ids}) + return probs, logits, emb + + +class TorchDecider(Decider): + def __init__(self, checkpoint: str | Path | None = None, model=None, cfg: dict | None = None, + device: str = "cpu", threads: int | None = None, task: str | None = None): + import torch + + from minijev.choices import EmbeddingCache + from minijev.tokenizers import make_tokenizer + from minijev.training.supervised import make_model, make_task_for, task_specs + + if threads: + torch.set_num_threads(threads) + task_T = {} + if model is None: + ck = torch.load(checkpoint, map_location=device, weights_only=False) + cfg = ck["config"] + task_T = ck.get("task_temperatures") or {} + model = make_model(cfg) + model.load_state_dict(ck["model"]) + self.specs = {s["key"]: s["task"] for s in task_specs(cfg)} + self.tokenizer = make_tokenizer(cfg["model"].get("text_encoder")) + self.torch, self.model, self.cfg, self.device = torch, model.to(device).eval(), cfg, device + self.max_question_len = cfg["model"].get("max_question_len", 32) + self.max_choice_len = cfg["model"].get("max_choice_len", 16) + self.global_temperature = float(model.log_temperature.exp()) + self.task_temperatures = task_T + self.cache = EmbeddingCache() if model.backbone is not None and model.backbone.frozen else None + self._make_task = lambda key: make_task_for(cfg, self.specs[key]) + self.use_task(task or next(iter(self.specs))) + + @classmethod + def from_pretrained(cls, path_or_repo: str | Path, device: str = "cpu", threads: int | None = None, + task: str | None = None) -> "TorchDecider": + """Load a folder written by `minijev export-hf` (local path or Hugging Face repo id).""" + from minijev.hub import load_pretrained + + model, cfg, task_T = load_pretrained(path_or_repo, device) + dec = cls(model=model, cfg=cfg, device=device, threads=threads, task=task) + dec.task_temperatures = task_T + return dec.use_task(dec.task_key) + + def use_task(self, key: str) -> "TorchDecider": + """Switch the state format (and per-task temperature) for a multi-task model.""" + self.task_key = key + self.task = self._make_task(key) + self.state_key = STATE_INPUTS[self.task.state_encoder] + self.temperature = float(self.task_temperatures.get(key, self.global_temperature)) + return self + + def _bb(self, texts: list[str], max_len: int): + torch = self.torch + dev = self.device + + def compute(missing): + ids = torch.as_tensor(self.tokenizer.encode_batch(missing, max_len, dynamic=True), device=dev) + return self.model.backbone(ids) + tok, mask, pooled = self.cache.get_many(texts, compute) + return tok.to(dev), mask.to(dev), pooled.to(dev) + + def forward(self, states, question: str, choices: Sequence[str], encoded=None): + torch = self.torch + x = self.encode(states) if encoded is None else encoded + B = x.shape[0] + state = {self.state_key: torch.as_tensor(x, device=self.device)} + with torch.inference_mode(): + if self.cache is not None: # frozen backbone: each question / label is encoded once, ever + qt, qm, qp = self._bb([question], self.max_question_len) + _, _, cp = self._bb(list(choices), self.max_choice_len) + cm = torch.ones(B, len(choices), dtype=torch.bool, device=self.device) + return self.model(state, question_bb=(qt.expand(B, -1, -1), qm.expand(B, -1), qp.expand(B, -1)), + choice_bb=(cp[None].expand(B, -1, -1), cm)) + q, c = self._tokens(question, tuple(choices)) + return self.model(state, torch.as_tensor(np.repeat(q, B, 0), device=self.device), + torch.as_tensor(np.repeat(c, B, 0), device=self.device)) + + def run(self, states, question, choices, encoded=None): + torch = self.torch + out = self.forward(states, question, choices, encoded) + logits = out["logits"] / self.temperature + probs = torch.softmax(logits, -1) + return probs.cpu().numpy(), logits.cpu().numpy(), out["embedding"].float().cpu().numpy() + + def _run(self, state, question_ids, choice_ids): # kept for callers passing model-ready arrays + torch = self.torch + with torch.inference_mode(): + out = self.model({self.state_key: torch.as_tensor(state, device=self.device)}, + torch.as_tensor(question_ids, device=self.device), + torch.as_tensor(choice_ids, device=self.device)) + logits = out["logits"] / self.temperature + return torch.softmax(logits, -1).cpu().numpy(), logits.cpu().numpy(), out["embedding"].float().cpu().numpy() + + def score(self, state: Any, question: str) -> float: + """Continuous 0..1 score from the scalar head (meaningful once trained with `score` targets).""" + out = self.forward([state], question, ["yes", "no"]) + return float(self.torch.sigmoid(out["score"])[0]) + + +class MiniJEV: + """Entry point: `MiniJEV.load(path)` for .onnx or .pt files.""" + + @staticmethod + def load(path: str | Path, threads: int = 1, **kw) -> Decider: + p = Path(path) + if p.suffix == ".onnx": + return OnnxDecider(p, threads=threads, **kw) + if p.suffix == ".pt": + return TorchDecider(p, threads=threads, **kw) + return TorchDecider.from_pretrained(path, threads=threads, **kw) # export-hf folder or hub repo id diff --git a/code/minijev/keys.py b/code/minijev/keys.py new file mode 100644 index 0000000000000000000000000000000000000000..5b85201c05a24b5d59a11e9499bf8f09b082a56c --- /dev/null +++ b/code/minijev/keys.py @@ -0,0 +1,2 @@ +"""Model input names per state-encoder kind (torch-free, shared by training, runtime and ONNX).""" +STATE_INPUTS = {"grid": "state_grid", "text": "state_ids", "log": "state_log_ids", "numeric": "state_x"} diff --git a/code/minijev/model/__init__.py b/code/minijev/model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0ae0171a6d788488c05a26f34db45aba0a8c85e4 --- /dev/null +++ b/code/minijev/model/__init__.py @@ -0,0 +1,3 @@ +from .minijev import STATE_INPUTS, ExportWrapper, MiniJEVNet, build_model, human_params, upgrade_state_dict + +__all__ = ["MiniJEVNet", "ExportWrapper", "build_model", "human_params", "STATE_INPUTS", "upgrade_state_dict"] diff --git a/code/minijev/model/__pycache__/__init__.cpython-314.pyc b/code/minijev/model/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a7346a19df232e3c26a3d93fdd4133fc9dc7f2b Binary files /dev/null and b/code/minijev/model/__pycache__/__init__.cpython-314.pyc differ diff --git a/code/minijev/model/__pycache__/minijev.cpython-314.pyc b/code/minijev/model/__pycache__/minijev.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0d29259cb5d13fac32f0793ade62be71da6cfd2 Binary files /dev/null and b/code/minijev/model/__pycache__/minijev.cpython-314.pyc differ diff --git a/code/minijev/model/encoders.py b/code/minijev/model/encoders.py new file mode 100644 index 0000000000000000000000000000000000000000..5ec98852d95ac66fae7480aaa8ed246333afeed6 --- /dev/null +++ b/code/minijev/model/encoders.py @@ -0,0 +1,5 @@ +"""Moved to `minijev.encoders` (kept so old imports keep working).""" +from minijev.encoders import GridStateEncoder, TextPooler, TextStateEncoder # noqa: F401 +from minijev.tokenizer import VOCAB_SIZE # noqa: F401 + +__all__ = ["TextPooler", "GridStateEncoder", "TextStateEncoder", "VOCAB_SIZE"] diff --git a/code/minijev/model/layers.py b/code/minijev/model/layers.py new file mode 100644 index 0000000000000000000000000000000000000000..eb4c09b69e7dcd9cc3f6dcf04322c5c632808863 --- /dev/null +++ b/code/minijev/model/layers.py @@ -0,0 +1,2 @@ +from minijev.core.layers import * # noqa: F401,F403 (moved; kept for old imports) +from minijev.core.layers import Attention, DecisionBlock, EncoderBlock, MLP # noqa: F401 diff --git a/code/minijev/model/minijev.py b/code/minijev/model/minijev.py new file mode 100644 index 0000000000000000000000000000000000000000..ac80063e8875f3175f1bec048ce5726a2551f129 --- /dev/null +++ b/code/minijev/model/minijev.py @@ -0,0 +1,210 @@ +"""MiniJEV network = input representation + MiniJEV Core + ChoiceEncoder (+ calibration). + + state ──StateEncoder (grid | text | numeric | log)──► state tokens ┐ + question ──QuestionEncoder──────────────────────────► question tok ├─► MiniJEVCore ─► logit per choice + choice_i ──ChoiceEncoder────────────────────────────► c_i ┘ (+ value, score, embedding) + +All encoders project into the same latent space of width `d_model`; the core +only sees vectors. The text backend is either `byte` (the original from-scratch +tokenizer, used by the Snake checkpoints) or a `pretrained` sentence encoder +shared by question, choices and text states (see minijev/encoders/text.py). + +`forward(state, question_ids, choice_ids)` keeps the original signature. With a +frozen pretrained backbone, callers may instead pass precomputed backbone +outputs (`question_bb`, `choice_bb`) so the backbone runs once per string. +""" +from __future__ import annotations + +import torch +from torch import nn + +from minijev.choices import ChoiceEncoder +from minijev.core import NEG, MiniJEVCore +from minijev.encoders import STATE_INPUTS, PretrainedTextBackbone, QuestionEncoder, build_state_encoder +from minijev.tokenizer import PAD, VOCAB_SIZE + +# pre-v2 checkpoints: flat module names -> new modular names +_LEGACY_PREFIXES = [("question.", "question_encoder.pooler."), ("choice.", "choice_encoder.pooler."), + ("blocks.", "core.blocks."), ("ln_ctx.", "core.ln_ctx."), ("decision.", "core.decision."), + ("score.", "core.choice_head."), ("value.", "core.value_head."), + ("cls", "core.cls"), ("type_emb", "core.type_emb")] + + +def upgrade_state_dict(sd: dict) -> dict: + if not any(k.startswith("blocks.") for k in sd): + return sd + out = {} + for k, v in sd.items(): + for old, new in _LEGACY_PREFIXES: + if k.startswith(old): + k = new + k[len(old):] + break + out[k] = v + return out + + +class MiniJEVNet(nn.Module): + def __init__(self, cfg: dict, encoder_classes: dict | None = None): + super().__init__() + self.cfg = cfg + d = cfg["d_model"] + tcfg = dict(cfg.get("text_encoder") or {"type": "byte"}) + self.text_type = tcfg.get("type", "byte") + if self.text_type == "byte": + self.embed = nn.Embedding(VOCAB_SIZE, d, padding_idx=PAD) + self.backbone, d_text, embed = None, None, self.embed + self.pad_id = PAD + else: + from minijev.tokenizers import make_tokenizer + self.pad_id = make_tokenizer(tcfg).pad_id + self.backbone = PretrainedTextBackbone(tcfg["name"], tcfg.get("finetune", "frozen"), self.pad_id) + d_text, embed = self.backbone.dim, None + self.state_encoders = nn.ModuleDict({ + kind: build_state_encoder(kind, d, enc_cfg, embed=embed, d_text=d_text, + cls=(encoder_classes or {}).get(kind)) + for kind, enc_cfg in cfg["state_encoders"].items() + }) + self.question_encoder = QuestionEncoder(d, embed, cfg.get("max_question_len", 32), d_text, + tokens=tcfg.get("question_tokens", True)) + self.choice_encoder = ChoiceEncoder(d, embed, cfg.get("max_choice_len", 16), d_text) + self.core = MiniJEVCore(d, cfg["n_layers"], cfg.get("n_heads", 4), cfg.get("mlp_ratio", 4.0), + cfg.get("dropout", 0.0), cfg.get("n_decision_layers", 1), + cfg.get("scorer", "cross"), cfg.get("max_choices", 16)) + # post-hoc calibration: logits are divided by T = exp(log_temperature) at inference + self.register_buffer("log_temperature", torch.zeros(())) + for name, m in self.named_children(): + if name != "backbone": + m.apply(self._init) + + @staticmethod + def _init(m): + if isinstance(m, nn.Linear): + nn.init.trunc_normal_(m.weight, std=0.02) + if m.bias is not None: + nn.init.zeros_(m.bias) + + @property + def temperature(self) -> float: + return float(self.log_temperature.exp()) + + # ----------------------------------------------------------- checkpoints + def _frozen_backbone(self) -> bool: + return self.backbone is not None and self.backbone.frozen + + def state_dict(self, *a, **kw): + sd = super().state_dict(*a, **kw) + if self._frozen_backbone(): # frozen weights are reloaded from the hub/cache by name + for k in [k for k in sd if k.startswith("backbone.")]: + del sd[k] + return sd + + def load_state_dict(self, sd, strict: bool = True, assign: bool = False): + sd = upgrade_state_dict(dict(sd)) + res = super().load_state_dict(sd, strict=False, assign=assign) + missing = [k for k in res.missing_keys + if not k.startswith("core.scalar_head.") # added in v2, untrained in old checkpoints + and not (self._frozen_backbone() and k.startswith("backbone."))] + if strict and (missing or res.unexpected_keys): + raise RuntimeError(f"state_dict mismatch: missing={missing[:10]} unexpected={res.unexpected_keys[:10]}") + return res + + # --------------------------------------------------------------- encoders + def run_backbone(self, ids): + """Backbone on the unique rows of ids (..., L) -> (tok, mask, pooled) shaped like ids.""" + shape = ids.shape[:-1] + flat = ids.reshape(-1, ids.shape[-1]) + uniq, inv = torch.unique(flat, dim=0, return_inverse=True) + tok, mask, pooled = self.backbone(uniq) + return (tok[inv].reshape(*shape, *tok.shape[1:]), mask[inv].reshape(*shape, mask.shape[-1]), + pooled[inv].reshape(*shape, pooled.shape[-1])) + + def encode_state(self, state: dict): + for kind, enc in self.state_encoders.items(): + key = STATE_INPUTS[kind] + if key in state: + x = state[key] + if getattr(enc, "uses_backbone", False): + x = state.get("state_bb") or self.backbone(x) + return enc(x) + if not state or "state_none" in state: + return None, None + raise ValueError(f"no state input for encoders {list(self.state_encoders)}; got {list(state)}") + + def encode_question(self, question_ids=None, question_bb=None): + if self.backbone is None: + return self.question_encoder(question_ids) + return self.question_encoder(backbone_out=question_bb or self.run_backbone(question_ids)) + + def encode_choices(self, choice_ids=None, choice_bb=None, choice_mask=None): + """-> (emb (B, N, d), mask (B, N)). choice_bb = (pooled (B, N, dt), mask (B, N)) precomputed.""" + if self.backbone is None: + return self.choice_encoder(choice_ids), (choice_ids != PAD).any(-1) + if choice_bb is not None: + pooled, choice_mask = choice_bb + else: + choice_mask = (choice_ids != self.pad_id).any(-1) + pooled = self.run_backbone(choice_ids)[2] + return self.choice_encoder(pooled=pooled), choice_mask + + def forward(self, state: dict, question_ids=None, choice_ids=None, question_bb=None, choice_bb=None): + """choice_ids: (B, N, Lc); all-pad rows are absent choices. Returns raw (uncalibrated) logits.""" + s_tok, s_mask = self.encode_state(state) + q_tok, q_mask = self.encode_question(question_ids, question_bb) + c_emb, c_mask = self.encode_choices(choice_ids, choice_bb) + return self.core(s_tok, s_mask, q_tok, q_mask, c_emb, c_mask) + + # ------------------------------------------------------------ accounting + def num_parameters(self) -> int: + return sum(p.numel() for p in self.parameters()) + + def param_breakdown(self) -> dict: + """Unique parameter counts per stage (shared byte embeddings counted once, in `text`).""" + seen, out = set(), {} + groups = [("text", ["embed", "backbone"]), ("question_encoder", ["question_encoder"]), + ("choice_encoder", ["choice_encoder"]), ("state_encoders", ["state_encoders"]), + ("core", ["core"])] + for g, prefixes in groups: + n = 0 + for name, p in self.named_parameters(remove_duplicate=False): + if name.split(".")[0] in prefixes and id(p) not in seen: + seen.add(id(p)) + n += p.numel() + out[g] = n + out["trainable"] = sum(p.numel() for p in self.parameters() if p.requires_grad) + out["total"] = sum(v for k, v in out.items() if k != "trainable") + out["core_total"] = out["total"] - out["text"] # everything but the (shared) text backbone + return out + + +class ExportWrapper(nn.Module): + """Flat-signature module for ONNX: calibrated probabilities + logits + embedding.""" + + def __init__(self, model: MiniJEVNet, state_key: str): + super().__init__() + self.model, self.state_key = model, state_key + + def forward(self, state, question_ids, choice_ids): + out = self.model({self.state_key: state}, question_ids, choice_ids) + logits = out["logits"] / self.model.log_temperature.exp() + return torch.softmax(logits, -1), logits, out["embedding"] + + +def build_model(model_cfg: dict, task_encoder_cfgs: dict[str, dict] | None = None, + encoder_classes: dict | None = None) -> MiniJEVNet: + cfg = dict(model_cfg) + encs = {k: dict(v or {}) for k, v in cfg.get("state_encoders", {}).items()} + if task_encoder_cfgs is not None: + # model-side overrides (e.g. stem width) apply only to modalities the task actually uses + encs = {kind: {**(extra or {}), **encs.get(kind, {})} for kind, extra in task_encoder_cfgs.items()} + cfg["state_encoders"] = encs + return MiniJEVNet(cfg, encoder_classes) + + +def human_params(n: int) -> str: + if n >= 1e6: + return f"{n / 1e6:.2f}M" + return f"{n / 1e3:.0f}K" if n >= 1e3 else str(n) + + +__all__ = ["MiniJEVNet", "ExportWrapper", "build_model", "human_params", "STATE_INPUTS", "NEG", + "upgrade_state_dict"] diff --git a/code/minijev/report.py b/code/minijev/report.py new file mode 100644 index 0000000000000000000000000000000000000000..57746846f0d5be6e4e1f648845453eb16054cc52 --- /dev/null +++ b/code/minijev/report.py @@ -0,0 +1,64 @@ +"""Cross-run comparison table (markdown) from files each run writes.""" +from __future__ import annotations + +import json +from pathlib import Path + + +def _load(p: Path): + return json.loads(p.read_text()) if p.exists() else None + + +def run_row(run: str | Path) -> dict: + run = Path(run) + s = _load(run / "summary.json") or {} + g = _load(run / "games.json") or {} + b = _load(run / "benchmark.json") or [] + cal = s.get("test_calibrated", {}) + row = {"run": run.name, "model": (_load(run / "env.json") or {}).get("task", ""), + "params": s.get("params_human"), "acc": cal.get("accuracy"), "ece": cal.get("ece"), + "ece_raw": s.get("test_raw", {}).get("ece"), "nll": cal.get("nll"), "brier": cal.get("brier"), + "avg_score": g.get("avg_score"), "median": g.get("median_score"), "max": g.get("max_score"), + "win": g.get("win_rate"), "fatal": g.get("fatal_move_rate"), + "train_min": round(s["train_seconds"] / 60, 1) if s.get("train_seconds") else None, + "cost": (s.get("cost") or {}).get("actual_cost", (s.get("cost") or {}).get("estimated_cost"))} + for r in b: + kind = "int8" if ".int8." in r["model"] else ("onnx" if r["model"].endswith(".onnx") else "torch") + row[f"{kind}_mb"] = r["file_size_mb"] + row[f"{kind}_p50"] = r["latency"]["end_to_end"]["p50_ms"] + row[f"{kind}_p99"] = r["latency"]["end_to_end"]["p99_ms"] + row[f"{kind}_dps"] = r["latency"]["max_decisions_per_sec_batch1"] + return row + + +COLUMNS = [("run", "run"), ("params", "params"), ("onnx_mb", "onnx MB"), ("int8_mb", "int8 MB"), + ("onnx_p50", "p50 ms"), ("onnx_p99", "p99 ms"), ("onnx_dps", "dec/s"), ("acc", "acc"), + ("ece_raw", "ECE raw"), ("ece", "ECE"), ("brier", "Brier"), ("avg_score", "avg score"), + ("median", "median"), ("max", "max"), ("win", "win"), ("fatal", "fatal-move"), + ("train_min", "train min"), ("cost", "cost €")] + + +def _fmt(v, key): + if v is None: + return "-" + if key in ("acc", "win"): + return f"{v:.1%}" + if key == "fatal": + return f"{v:.3%}" + if key in ("ece", "ece_raw", "brier", "nll"): + return f"{v:.4f}" + if isinstance(v, float): + return f"{v:.2f}" if v < 100 else f"{v:,.0f}" + return str(v) + + +def compare_runs(runs, out: str | None = None) -> str: + rows = [run_row(r) for r in runs] + cols = [(k, h) for k, h in COLUMNS if any(r.get(k) is not None for r in rows)] + lines = ["| " + " | ".join(h for _, h in cols) + " |", "|" + "---|" * len(cols)] + for r in rows: + lines.append("| " + " | ".join(_fmt(r.get(k), k) for k, _ in cols) + " |") + table = "\n".join(lines) + if out: + Path(out).write_text(table + "\n") + return table diff --git a/code/minijev/runs.py b/code/minijev/runs.py new file mode 100644 index 0000000000000000000000000000000000000000..72386651e20ae107858103497b751f00309139f7 --- /dev/null +++ b/code/minijev/runs.py @@ -0,0 +1,98 @@ +"""Lightweight experiment tracking: one directory per run under `runs/`. + + runs/-/ + config.yaml resolved config + env.json git commit, hardware, library versions, runtime profile + metrics.csv step-level training/validation metrics + tb/ TensorBoard events (if tensorboard is installed) + summary.json final metrics, timings, cost + checkpoints/ last.pt (resumable), best.pt, final.pt (calibrated) +""" +from __future__ import annotations + +import csv +import json +import platform +import subprocess +import time +from pathlib import Path + +import yaml + + +def git_commit() -> str | None: + try: + out = subprocess.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True, timeout=5, + cwd=Path(__file__).resolve().parent) + dirty = subprocess.run(["git", "status", "--porcelain"], capture_output=True, text=True, timeout=5, + cwd=Path(__file__).resolve().parent).stdout.strip() + return (out.stdout.strip() + ("-dirty" if dirty else "")) if out.returncode == 0 else None + except Exception: + return None + + +def environment_info() -> dict: + import numpy + info = {"python": platform.python_version(), "platform": platform.platform(), + "processor": platform.processor(), "numpy": numpy.__version__, "git_commit": git_commit()} + try: + import torch + info["torch"] = torch.__version__ + info["cuda"] = torch.version.cuda + if torch.cuda.is_available(): + info["gpu"] = torch.cuda.get_device_name(0) + except ImportError: + pass + return info + + +class RunLogger: + def __init__(self, run_dir: str | Path, cfg: dict | None = None, resume: bool = False): + self.dir = Path(run_dir) + self.dir.mkdir(parents=True, exist_ok=True) + (self.dir / "checkpoints").mkdir(exist_ok=True) + if cfg is not None and not (resume and (self.dir / "config.yaml").exists()): + (self.dir / "config.yaml").write_text(yaml.safe_dump(cfg, sort_keys=False)) + self._csv_path = self.dir / "metrics.csv" + self._fields: list[str] | None = None + if resume and self._csv_path.exists(): + with open(self._csv_path) as f: + self._fields = next(csv.reader(f), None) + self.tb = None + try: + from torch.utils.tensorboard import SummaryWriter + self.tb = SummaryWriter(str(self.dir / "tb")) + except Exception: + pass + + def write_json(self, name: str, obj) -> None: + (self.dir / name).write_text(json.dumps(obj, indent=2, default=str)) + + def log(self, step: int, **metrics) -> None: + row = {"step": step, "time": round(time.time(), 1), **metrics} + if self._fields is None: + self._fields = list(row) + with open(self._csv_path, "w", newline="") as f: + csv.writer(f).writerow(self._fields) + for k in row: + if k not in self._fields: # new metric: rewrite header + self._fields.append(k) + rows = list(csv.DictReader(open(self._csv_path))) + with open(self._csv_path, "w", newline="") as f: + w = csv.DictWriter(f, self._fields) + w.writeheader() + w.writerows(rows) + with open(self._csv_path, "a", newline="") as f: + csv.DictWriter(f, self._fields).writerow(row) + if self.tb is not None: + for k, v in metrics.items(): + if isinstance(v, (int, float)): + self.tb.add_scalar(k, v, step) + + def close(self) -> None: + if self.tb is not None: + self.tb.close() + + +def new_run_dir(name: str, root: str | Path = "runs") -> Path: + return Path(root) / f"{time.strftime('%Y%m%d-%H%M%S')}-{name}" diff --git a/code/minijev/tasks.py b/code/minijev/tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..6d49ad0d094d41f86757b782abd1809b6dac0f04 --- /dev/null +++ b/code/minijev/tasks.py @@ -0,0 +1,92 @@ +"""Task plugin interface: the only place where MiniJEV touches a domain. + +A task turns its native states into (a) compact arrays for storage and +(b) model inputs for one of MiniJEV's state encoders. Everything else (model, +training, calibration, export, runtime) is task-agnostic. + +Plugins live in `environments//task.py` and expose `make_task(cfg)`. +""" +from __future__ import annotations + +import importlib +from typing import Any, Sequence + +import numpy as np + + +class Task: + name: str = "task" + #: which MiniJEV state encoder consumes this task's inputs ("grid", "text", ...) + state_encoder: str = "grid" + default_question: str = "" + default_choices: tuple[str, ...] = () + + def __init__(self, cfg: dict | None = None): + self.cfg = cfg or {} + + # labels ----------------------------------------------------------------- + #: stored label -> label shown to the model (e.g. Snake "UP" -> "move up"); empty = identity + @property + def choice_alias(self) -> dict[str, str]: + return {} + + def model_label(self, label: str) -> str: + return self.choice_alias.get(label, label) + + def action_of(self, label: str) -> str: + """Model-facing label -> native action (inverse of choice_alias).""" + inv = {v: k for k, v in self.choice_alias.items()} + return inv.get(label, label) + + # storage format -------------------------------------------------------- + def states_to_arrays(self, states: Sequence[Any]) -> dict[str, np.ndarray]: + raise NotImplementedError + + def encode_arrays(self, arrays: dict[str, np.ndarray], idx: np.ndarray) -> dict[str, np.ndarray]: + """Model inputs for rows `idx` of stored arrays (vectorised numpy).""" + raise NotImplementedError + + # convenience ------------------------------------------------------------ + def encode_states(self, states: Sequence[Any]) -> dict[str, np.ndarray]: + arrays = self.states_to_arrays(states) + return self.encode_arrays(arrays, np.arange(len(states))) + + def encoder_class(self): + """Optional task-specific StateEncoder class (must keep the generic encoder's parameters).""" + return None + + def encoder_config(self) -> dict: + """Hyper-parameters the state encoder needs from the task (channels, ...).""" + return {} + + def example_states(self, n: int = 4, seed: int = 0) -> list[Any]: + """A few valid states (used for ONNX export tracing and parity checks).""" + raise NotImplementedError + + +BUILTIN = {"text": "minijev.text_task", "log": "minijev.text_task"} + + +def get_task(name: str, cfg: dict | None = None) -> Task: + mod = importlib.import_module(BUILTIN.get(name) or f"environments.{name.replace('-', '_')}.task") + return mod.make_task(cfg or {}) + + +# ----------------------------------------------------------------- ragged utils +def ragged_pack(seqs: Sequence[Sequence[int]] | Sequence[np.ndarray], dtype=np.int32) -> tuple[np.ndarray, np.ndarray]: + lengths = np.fromiter((len(s) for s in seqs), dtype=np.int64, count=len(seqs)) + offsets = np.zeros(len(seqs) + 1, dtype=np.int64) + np.cumsum(lengths, out=offsets[1:]) + flat = np.concatenate([np.asarray(s, dtype=dtype) for s in seqs]) if len(seqs) else np.zeros(0, dtype) + return flat.astype(dtype, copy=False), offsets + + +def ragged_take(flat: np.ndarray, offsets: np.ndarray, idx: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Gather rows `idx` of a ragged array; returns (flat, lengths).""" + starts = offsets[idx] + lengths = offsets[idx + 1] - starts + total = int(lengths.sum()) + if total == 0: + return flat[:0], lengths + rel = np.arange(total) - np.repeat(np.cumsum(lengths) - lengths, lengths) + return flat[np.repeat(starts, lengths) + rel], lengths diff --git a/code/minijev/text_task.py b/code/minijev/text_task.py new file mode 100644 index 0000000000000000000000000000000000000000..7f20260a4347ec2b74690d345b7c994675af3b3e --- /dev/null +++ b/code/minijev/text_task.py @@ -0,0 +1,70 @@ +"""Generic text decision task: the state is a string (document, entity, log, ...) +or empty. Used by general QA, sentiment and any JSONL decision dataset. + +States are stored as ragged UTF-8 bytes and tokenised at batch time with the +model's tokenizer (`task.tokenizer`: byte-level or the pretrained encoder's), so +one stored dataset works for every text backend. +""" +from __future__ import annotations + +from typing import Sequence + +import numpy as np + +from minijev.text_task_utils import normalise_log +from minijev.tokenizers import ByteTokenizer +from minijev.tasks import Task, ragged_pack, ragged_take + + +class TextDecisionTask(Task): + name = "text" + state_encoder = "text" + default_question = "" + default_choices: tuple[str, ...] = () + + def __init__(self, cfg: dict | None = None): + super().__init__(cfg) + self.tokenizer = ByteTokenizer() + + @property + def max_len(self) -> int: + return int(self.cfg.get("max_len", 256)) + + def preprocess(self, text: str) -> str: + return normalise_log(text, int(self.cfg.get("max_lines", 20))) if self.state_encoder == "log" else text + + def states_to_arrays(self, states: Sequence[str | None]) -> dict[str, np.ndarray]: + flat, offsets = ragged_pack([np.frombuffer(self.preprocess(s or "").encode("utf-8"), np.uint8) + for s in states], np.uint8) + return {"text": flat, "text_offsets": offsets} + + def texts(self, arrays, idx) -> list[str]: + flat, lengths = ragged_take(arrays["text"], arrays["text_offsets"], np.asarray(idx)) + out, pos = [], 0 + for n in lengths.tolist(): + out.append(bytes(flat[pos:pos + n]).decode("utf-8", "replace")) + pos += n + return out + + def encode_arrays(self, arrays, idx): + texts = self.texts(arrays, idx) + ids = self.tokenizer.encode_batch(texts, self.max_len, dynamic=True) + return {"state_ids": ids} + + def example_states(self, n=4, seed=0): + base = ["hotdog", "whale", "Python", "", "The support was terrible and nobody answered me.", + "Great update, everything works now!", "Redis", "balena"] + rng = np.random.default_rng(seed) + return [base[i] for i in rng.integers(0, len(base), n)] + + +class LogDecisionTask(TextDecisionTask): + name = "log" + state_encoder = "log" + + def encode_arrays(self, arrays, idx): + return {"state_log_ids": super().encode_arrays(arrays, idx)["state_ids"]} + + +def make_task(cfg: dict) -> TextDecisionTask: + return LogDecisionTask(cfg) if cfg.get("name") == "log" else TextDecisionTask(cfg) diff --git a/code/minijev/text_task_utils.py b/code/minijev/text_task_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..20cdd7f56faadd8cc175267b8472213b7d900636 --- /dev/null +++ b/code/minijev/text_task_utils.py @@ -0,0 +1,18 @@ +"""Torch-free text helpers.""" +from __future__ import annotations + +import re + +_HEX = re.compile(r"\b0x[0-9a-fA-F]+\b|\b[0-9a-f]{8,}\b") +_TS = re.compile(r"\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:[.,]\d+)?Z?") +_NUM = re.compile(r"\b\d+(?:\.\d+)?\b") + + +def normalise_log(text: str, max_lines: int = 20) -> str: + lines = text.strip().splitlines()[-max_lines:] + out = [] + for ln in lines: + ln = _TS.sub("", ln) + ln = _HEX.sub("", ln) + out.append(_NUM.sub("", ln)) + return "\n".join(out) diff --git a/code/minijev/tokenizer.py b/code/minijev/tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..e6b49f73599c5e35a9a25189ca0dcfbbf5c0d44a --- /dev/null +++ b/code/minijev/tokenizer.py @@ -0,0 +1,41 @@ +"""Byte-level tokenizer shared by questions, choices and text states. + +No vocabulary file, no training, works for any language and for arbitrary +choice labels ("UP", "ticket:billing", "negative", ...). ids: 0=pad, 1..3 reserved, +byte b -> b + 4. Pure numpy so the ONNX runtime path needs no torch. +""" +from __future__ import annotations + +from typing import Sequence + +import numpy as np + +PAD = 0 +OFFSET = 4 +VOCAB_SIZE = 256 + OFFSET + + +def encode(text: str, max_len: int) -> np.ndarray: + b = text.encode("utf-8")[:max_len] + out = np.zeros(max_len, dtype=np.int64) + if b: + out[: len(b)] = np.frombuffer(b, dtype=np.uint8).astype(np.int64) + OFFSET + return out + + +def encode_batch(texts: Sequence[str], max_len: int) -> np.ndarray: + out = np.zeros((len(texts), max_len), dtype=np.int64) + for i, t in enumerate(texts): + b = t.encode("utf-8")[:max_len] + if b: + out[i, : len(b)] = np.frombuffer(b, dtype=np.uint8).astype(np.int64) + OFFSET + return out + + +def encode_choice_sets(choice_sets: Sequence[Sequence[str]], max_len: int) -> np.ndarray: + """(B, Nmax, L) int64; padded choices are all-zero rows (masked by the model).""" + n = max(len(c) for c in choice_sets) + out = np.zeros((len(choice_sets), n, max_len), dtype=np.int64) + for i, cs in enumerate(choice_sets): + out[i, : len(cs)] = encode_batch(cs, max_len) + return out diff --git a/code/minijev/tokenizers.py b/code/minijev/tokenizers.py new file mode 100644 index 0000000000000000000000000000000000000000..e6c863306ff2450de9eb3c726ce23d430ac89f71 --- /dev/null +++ b/code/minijev/tokenizers.py @@ -0,0 +1,85 @@ +"""Text tokenizers behind one interface (numpy only, no torch): + + tok.encode_batch(texts, max_len, dynamic=False) -> (n, L) int64, padded with tok.pad_id + tok.encode_choice_sets(choice_sets, max_len) -> (B, N, L); absent choices are all-pad rows + +`ByteTokenizer` is the original MiniJEV byte-level tokenizer (vocab 260, pad 0). +`HFTokenizer` wraps a pretrained encoder's `tokenizer.json` through the Rust +`tokenizers` package (no transformers/torch needed at inference). +""" +from __future__ import annotations + +from pathlib import Path +from typing import Sequence + +import numpy as np + +from minijev import tokenizer as byte_tok + + +class ByteTokenizer: + kind = "byte" + pad_id = byte_tok.PAD + vocab_size = byte_tok.VOCAB_SIZE + + def encode_batch(self, texts: Sequence[str], max_len: int, dynamic: bool = False) -> np.ndarray: + out = byte_tok.encode_batch(texts, max_len) + if dynamic: + n = int((out != self.pad_id).sum(1).max()) if len(out) else 1 + out = out[:, : max(1, n)] + return out + + def encode_choice_sets(self, choice_sets, max_len): + return byte_tok.encode_choice_sets(choice_sets, max_len) + + +class HFTokenizer: + kind = "hf" + + def __init__(self, name_or_path: str): + from tokenizers import Tokenizer + + p = Path(name_or_path) + if p.is_dir(): + p = p / "tokenizer.json" + if not p.exists(): + from huggingface_hub import hf_hub_download + p = Path(hf_hub_download(name_or_path, "tokenizer.json")) + self.path = str(p) + self.tok = Tokenizer.from_file(str(p)) + self.tok.no_padding() + self.tok.no_truncation() + pad = self.tok.token_to_id("") + self.pad_id = int(pad if pad is not None else (self.tok.token_to_id("[PAD]") or 0)) + self.vocab_size = self.tok.get_vocab_size() + + def encode_batch(self, texts: Sequence[str], max_len: int, dynamic: bool = False) -> np.ndarray: + encs = self.tok.encode_batch(list(texts)) + L = max_len + if dynamic: + L = max(1, min(max_len, max((len(e.ids) for e in encs), default=1))) + out = np.full((len(texts), L), self.pad_id, np.int64) + for i, e in enumerate(encs): + ids = e.ids + if len(ids) > L: # keep the final special token ( / [SEP]) + ids = ids[: L - 1] + ids[-1:] + out[i, : len(ids)] = ids + return out + + def encode_choice_sets(self, choice_sets, max_len): + n = max(len(c) for c in choice_sets) + flat = [c for cs in choice_sets for c in cs] + enc = self.encode_batch(flat, max_len, dynamic=True) + out = np.full((len(choice_sets), n, enc.shape[1]), self.pad_id, np.int64) + k = 0 + for i, cs in enumerate(choice_sets): + out[i, : len(cs)] = enc[k:k + len(cs)] + k += len(cs) + return out + + +def make_tokenizer(text_cfg: dict | None): + text_cfg = text_cfg or {} + if text_cfg.get("type", "byte") == "byte": + return ByteTokenizer() + return HFTokenizer(text_cfg.get("tokenizer") or text_cfg["name"]) diff --git a/code/minijev/training/__init__.py b/code/minijev/training/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code/minijev/training/__pycache__/__init__.cpython-314.pyc b/code/minijev/training/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ad86cb9431e4d68749e3378d93a2ab7514d80c7 Binary files /dev/null and b/code/minijev/training/__pycache__/__init__.cpython-314.pyc differ diff --git a/code/minijev/training/__pycache__/losses.cpython-314.pyc b/code/minijev/training/__pycache__/losses.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d381d1468ae352c2a0af72ba5a83a4f6736769c8 Binary files /dev/null and b/code/minijev/training/__pycache__/losses.cpython-314.pyc differ diff --git a/code/minijev/training/__pycache__/supervised.cpython-314.pyc b/code/minijev/training/__pycache__/supervised.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7a1417408d7a31c1ad3cf6940feba7d080e3231 Binary files /dev/null and b/code/minijev/training/__pycache__/supervised.cpython-314.pyc differ diff --git a/code/minijev/training/losses.py b/code/minijev/training/losses.py new file mode 100644 index 0000000000000000000000000000000000000000..d941a10b0098d05125962ceb2f3a9a6aa226833b --- /dev/null +++ b/code/minijev/training/losses.py @@ -0,0 +1,70 @@ +"""Decision losses over a variable number of choices (absent choices are masked). + + hard cross-entropy vs. the target index (optional label smoothing over *present* choices) + soft cross-entropy vs. a soft label distribution + kd Hinton distillation: T^2 * KL(teacher_T || student_T) from teacher logits + score BCE of the scalar score head vs a continuous target in [0, 1] + +`distillation: {enabled: true, alpha: 0.7, temperature: 2.0}` is shorthand for +hard_weight = 1 - alpha, kd_weight = alpha, kd_temperature = temperature. + +Any combination can be active; rows without a given signal are ignored. +""" +from __future__ import annotations + +import torch +import torch.nn.functional as F + + +def resolve_loss_cfg(cfg: dict | None) -> dict: + """`distillation: {enabled, alpha, temperature}` -> hard weight (1 - alpha), KD weight alpha, KD T.""" + cfg = dict(cfg or {}) + dist = cfg.get("distillation") or {} + if dist.get("enabled"): + a = float(dist.get("alpha", 0.5)) + cfg.update(hard_weight=1.0 - a, kd_weight=a, kd_temperature=float(dist.get("temperature", 2.0))) + return cfg + + +def decision_loss(logits: torch.Tensor, choice_mask: torch.Tensor, batch: dict, cfg: dict | None = None, + score_logit: torch.Tensor | None = None): + cfg = resolve_loss_cfg(cfg) + logp = F.log_softmax(logits, -1) + terms: dict[str, torch.Tensor] = {} + total = logits.new_zeros(()) + w_hard = cfg.get("hard_weight", 1.0) + if w_hard and "target" in batch: + target = batch["target"] + valid = target >= 0 + if valid.any(): + eps = cfg.get("label_smoothing", 0.0) + tgt = F.one_hot(target.clamp(min=0), logits.shape[-1]).float() + if eps > 0: + m = choice_mask.float() + tgt = (1 - eps) * tgt + eps * m / m.sum(-1, keepdim=True) + ce = -(tgt * logp.masked_fill(~choice_mask, 0.0)).sum(-1) + terms["hard"] = ce[valid].mean() + total = total + w_hard * terms["hard"] + w_soft = cfg.get("soft_weight", 1.0) + if w_soft and "soft" in batch: + soft = batch["soft"] + terms["soft"] = -(soft * logp.masked_fill(~choice_mask, 0.0)).sum(-1).mean() + total = total + w_soft * terms["soft"] + w_kd = cfg.get("kd_weight", 1.0) + if w_kd and "teacher_logits" in batch: + T = cfg.get("kd_temperature", 2.0) + t = F.log_softmax(batch["teacher_logits"] / T, -1) + s = F.log_softmax(logits / T, -1) + kl = (t.exp() * (t - s)).masked_fill(~choice_mask, 0.0).sum(-1) + has = batch["teacher_logits"].max(-1).values > -1e8 # rows without a teacher are all -1e9 + if has.any(): + terms["kd"] = kl[has].mean() * T * T + total = total + w_kd * terms["kd"] + w_score = cfg.get("score_weight", 1.0) + if w_score and score_logit is not None and "score_target" in batch: + y = batch["score_target"] + ok = ~torch.isnan(y) + if ok.any(): + terms["score"] = F.binary_cross_entropy_with_logits(score_logit[ok], y[ok]) + total = total + w_score * terms["score"] + return total, {k: float(v.detach()) for k, v in terms.items()} diff --git a/code/minijev/training/ppo.py b/code/minijev/training/ppo.py new file mode 100644 index 0000000000000000000000000000000000000000..45156e6d6147f7c2441abd154bd877ab78ed594f --- /dev/null +++ b/code/minijev/training/ppo.py @@ -0,0 +1,75 @@ +"""Task-agnostic PPO update for MiniJEV (actor = choice logits, critic = CLS value head). + +Why PPO (and not DQN) for MiniJEV: + * the model already outputs a distribution over *dynamic* choices; PPO trains + exactly that distribution, DQN would turn scores into Q-values and lose the + probabilistic reading that calibration relies on; + * it starts cleanly from the supervised policy (same head), with a KL anchor to + the supervised reference so early noisy advantages do not wreck it; + * on-policy + vectorised envs keeps it simple and stable at small scale. +""" +from __future__ import annotations + +import numpy as np +import torch +import torch.nn.functional as F + + +def gae(rewards: np.ndarray, values: np.ndarray, dones: np.ndarray, last_value: np.ndarray, + gamma: float, lam: float) -> tuple[np.ndarray, np.ndarray]: + """rewards/values/dones: (T, N). Returns (advantages, returns).""" + T = rewards.shape[0] + adv = np.zeros_like(rewards) + last = np.zeros_like(last_value) + for t in reversed(range(T)): + nv = last_value if t == T - 1 else values[t + 1] + nonterminal = 1.0 - dones[t] + delta = rewards[t] + gamma * nv * nonterminal - values[t] + last = delta + gamma * lam * nonterminal * last + adv[t] = last + return adv, adv + values + + +def ppo_update(model, opt, data: dict, cfg: dict, ref_model=None, policy_coef: float = 1.0) -> dict: + """data: state (dict of tensors), question_ids, choice_ids, actions, old_logp, adv, ret (flattened).""" + n = len(data["actions"]) + mb = int(cfg.get("minibatch", 1024)) + clip = cfg.get("clip", 0.2) + stats = {"pg": 0.0, "vf": 0.0, "entropy": 0.0, "kl_ref": 0.0, "approx_kl": 0.0, "clipfrac": 0.0} + count = 0 + model.train() + for _ in range(int(cfg.get("epochs", 2))): + perm = torch.randperm(n, device=data["actions"].device) + for i in range(0, n, mb): + idx = perm[i:i + mb] + state = {k: v[idx] for k, v in data["state"].items()} + out = model(state, data["question_ids"][idx], data["choice_ids"][idx]) + logp_all = F.log_softmax(out["logits"], -1) + logp = logp_all.gather(1, data["actions"][idx, None]).squeeze(1) + ratio = (logp - data["old_logp"][idx]).exp() + adv = data["adv"][idx] + pg = -torch.min(ratio * adv, ratio.clamp(1 - clip, 1 + clip) * adv).mean() + vf = 0.5 * (out["value"] - data["ret"][idx]).pow(2).mean() + p = logp_all.exp() + ent = -(p * logp_all.masked_fill(~out["choice_mask"], 0.0)).sum(-1).mean() + loss = policy_coef * pg + cfg.get("vf_coef", 0.5) * vf - cfg.get("ent_coef", 0.001) * ent + kl_ref = torch.zeros(()) + if ref_model is not None and cfg.get("kl_ref_coef", 0.0) > 0: + with torch.no_grad(): + ref_logp = F.log_softmax(ref_model(state, data["question_ids"][idx], + data["choice_ids"][idx])["logits"], -1) + kl_ref = (ref_logp.exp() * (ref_logp - logp_all)).masked_fill(~out["choice_mask"], 0.0).sum(-1).mean() + loss = loss + cfg["kl_ref_coef"] * kl_ref + opt.zero_grad(set_to_none=True) + loss.backward() + torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.get("grad_clip", 0.5)) + opt.step() + with torch.no_grad(): + stats["pg"] += float(pg) + stats["vf"] += float(vf) + stats["entropy"] += float(ent) + stats["kl_ref"] += float(kl_ref) + stats["approx_kl"] += float((data["old_logp"][idx] - logp).mean()) + stats["clipfrac"] += float(((ratio - 1).abs() > clip).float().mean()) + count += 1 + return {k: v / max(1, count) for k, v in stats.items()} diff --git a/code/minijev/training/relabel.py b/code/minijev/training/relabel.py new file mode 100644 index 0000000000000000000000000000000000000000..be9194195a34c18eab993cf8ef38da368bd1a1b6 --- /dev/null +++ b/code/minijev/training/relabel.py @@ -0,0 +1,77 @@ +"""Rename a trained model's choice labels without retraining the policy. + +The core only sees choice *embeddings*. To move a model from "UP" to "move up" +we fit the ChoiceEncoder (not the shared embeddings, not the core) so that the +new label produces the vector the old label produced. The decision function is +then unchanged up to the fit error, which is verified on real states. + + minijev relabel --checkpoint runs/x/final.pt --out runs/x/final-semantic.pt \\ + --map UP="move up" DOWN="move down" LEFT="move left" RIGHT="move right" \\ + --set task.choice_style=semantic +""" +from __future__ import annotations + +import copy + +import numpy as np +import torch + + +def relabel_checkpoint(checkpoint: str, out: str, mapping: dict[str, str], cfg_updates: dict | None = None, + steps: int = 3000, lr: float = 3e-3, anchors: list[str] | None = None) -> dict: + from minijev.inference.runtime import TorchDecider + from minijev.training.supervised import make_model + + ck = torch.load(checkpoint, map_location="cpu", weights_only=False) + cfg = copy.deepcopy(ck["config"]) + model = make_model(cfg) + model.load_state_dict(ck["model"]) + model.eval() + old_dec = TorchDecider(model=copy.deepcopy(model), cfg=cfg) + tok, max_len = old_dec.tokenizer, old_dec.max_choice_len + old, new = list(mapping), list(mapping.values()) + anchors = list(anchors or []) + + def emb(labels): + if model.backbone is None: + ids = torch.as_tensor(tok.encode_batch(labels, max_len)) + return model.choice_encoder(ids) + ids = torch.as_tensor(tok.encode_batch(labels, max_len, dynamic=True)) + return model.choice_encoder(pooled=model.backbone(ids)[2]) + + with torch.no_grad(): + target = emb(old + anchors).detach() + shared = {id(p) for n, p in model.named_parameters() if not n.startswith("choice_encoder.")} + params = [p for p in model.choice_encoder.parameters() if id(p) not in shared] + for p in model.parameters(): + p.requires_grad_(False) + for p in params: + p.requires_grad_(True) + opt = torch.optim.Adam(params, lr=lr) + sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, steps) + for _ in range(steps): + loss = (emb(new + anchors) - target).pow(2).mean() / target.pow(2).mean() + opt.zero_grad() + loss.backward() + opt.step() + sched.step() + for p in model.parameters(): + p.requires_grad_(True) + + for k, v in (cfg_updates or {}).items(): + node = cfg + parts = k.split(".") + for part in parts[:-1]: + node = node.setdefault(part, {}) + node[parts[-1]] = v + new_dec = TorchDecider(model=model, cfg=cfg) + new_dec.temperature = old_dec.temperature + states = new_dec.task.example_states(256, seed=123) + p_old = old_dec.probs(states, new_dec.task.default_question or "", old) + p_new = new_dec.probs(states, new_dec.task.default_question or "", new) + report = {"rel_mse": float(loss.detach()), "max_abs_prob_diff": float(np.abs(p_old - p_new).max()), + "argmax_agreement": float((p_old.argmax(1) == p_new.argmax(1)).mean()), "states": len(states)} + torch.save({**{k: v for k, v in ck.items() if k not in ("model", "config", "optimizer")}, + "model": model.state_dict(), "config": cfg, "relabel": {"from": checkpoint, "map": mapping, **report}}, + out) + return report diff --git a/code/minijev/training/supervised.py b/code/minijev/training/supervised.py new file mode 100644 index 0000000000000000000000000000000000000000..015505c8caba6ae743a92e3e4e31e6b62b21239b --- /dev/null +++ b/code/minijev/training/supervised.py @@ -0,0 +1,466 @@ +"""Supervised / distillation training loop. + +Resumable (last.pt holds model, optimizer, scheduler, scaler, data position and +RNG), stops cleanly on SIGINT/SIGTERM or a time budget, and ends with +temperature calibration on the validation split and a test-set report. +""" +from __future__ import annotations + +import math +import os +import random +import signal +import sys +import time +from pathlib import Path + +import numpy as np +import torch + +from minijev.calibration.metrics import (IsotonicConfidence, calibration_report, fit_temperature, + reliability_svg, softmax) +from minijev.datasets.batching import BackboneTable, BatchEncoder, EpochBatches, model_inputs, to_torch +from minijev.datasets.decision_data import DecisionData +from minijev.device import RuntimeProfile, autocast, resolve_runtime +from minijev.model import build_model, human_params +from minijev.runs import RunLogger, environment_info, new_run_dir +from minijev.tokenizers import make_tokenizer +from minijev.tasks import get_task + +from .losses import decision_loss + + +def seed_everything(seed: int) -> None: + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + + +def task_specs(cfg: dict) -> list[dict]: + """Single task (`task:` + `data:`) or multi-task (`tasks: [{key, task, data, weight}]`).""" + if cfg.get("tasks"): + sampling = cfg.get("sampling") or {} + out = [] + for t in cfg["tasks"]: + t = dict(t) + t.setdefault("key", t["task"]["name"]) + t["weight"] = float(sampling.get(t["key"], t.get("weight", 1.0))) + out.append(t) + return out + return [{"key": cfg["task"]["name"], "task": cfg["task"], "data": cfg["data"], "weight": 1.0}] + + +def make_task_for(cfg: dict, task_cfg: dict): + """Task plugin with the model's text tokenizer attached (byte or pretrained).""" + task = get_task(task_cfg["name"], task_cfg) + task.tokenizer = make_tokenizer(cfg["model"].get("text_encoder")) + return task + + +def load_splits(cfg: dict) -> dict[str, DecisionData]: + dcfg = cfg["data"] + d = Path(dcfg["dir"]) + if not (d / "train.npz").exists(): + gen = dcfg.get("generate") + if not gen: + raise FileNotFoundError(f"{d}/train.npz missing and no data.generate section") + import importlib + mod = importlib.import_module(dcfg.get("generator") or f"environments.{cfg['task']['name']}.dataset") + gen = dict(gen) + n = gen.pop("samples") + print(f"[data] generating {n:,} samples into {d} ...") + mod.generate_splits(d, n, **gen) + splits = {k: DecisionData.load(d / f"{k}.npz") for k in ("train", "val", "test")} + lim = dcfg.get("train_limit") + if lim and lim < len(splits["train"]): + splits["train"] = splits["train"].subset(np.arange(lim)) + return splits + + +def make_model(cfg: dict, task=None): + """task: one task, a list of tasks (multi-task: one state encoder per modality), or None (from cfg).""" + tasks = task if isinstance(task, (list, tuple)) else [task] if task is not None else \ + [make_task_for(cfg, t["task"]) for t in task_specs(cfg)] + encs, classes = {}, {} + for t in tasks: + encs.setdefault(t.state_encoder, t.encoder_config()) + if t.encoder_class(): + classes[t.state_encoder] = t.encoder_class() + return build_model(cfg["model"], encs, classes or None) + + +def param_groups(model, wd: float, lr: float | None = None, backbone_lr: float | None = None): + """AdamW groups: no decay on norms/biases/embeddings; a pretrained backbone can use its own (lower) lr.""" + groups = {} + for n, p in model.named_parameters(): + if not p.requires_grad: + continue + nd = p.ndim < 2 or "embed" in n or n.endswith((".pos", ".row", ".col", "cls", "type_emb")) + bb = backbone_lr is not None and n.startswith("backbone.") + groups.setdefault((nd, bb), []).append(p) + out = [] + for (nd, bb), ps in groups.items(): + g = {"params": ps, "weight_decay": 0.0 if nd else wd} + if bb: + g["lr"] = backbone_lr + elif lr is not None: + g["lr"] = lr + out.append(g) + return out + + +def lr_lambda(warmup: int, total: int, min_ratio: float): + def f(step): + if step < warmup: + return (step + 1) / max(1, warmup) + prog = min(1.0, (step - warmup) / max(1, total - warmup)) + return min_ratio + (1 - min_ratio) * 0.5 * (1 + math.cos(math.pi * prog)) + return f + + +@torch.no_grad() +def predict_logits(model, encoder: BatchEncoder, device, batch_size: int = 1024, max_rows: int | None = None, + profile: RuntimeProfile | None = None) -> tuple[np.ndarray, np.ndarray]: + model.eval() + n = len(encoder.data) if max_rows is None else min(max_rows, len(encoder.data)) + outs, tg = [], [] + for i in range(0, n, batch_size): + b = to_torch(encoder(np.arange(i, min(n, i + batch_size))), device) + with autocast(profile) if profile else torch.autocast("cpu", enabled=False): + out = model(**model_inputs(b)) + outs.append(out["logits"].float().cpu().numpy()) + tg.append(b["target"].cpu().numpy()) + return np.concatenate(outs), np.concatenate(tg) + + +def _acceptable(encoder: BatchEncoder, n: int): + """Rows' acceptable choices (soft label > 0), if the dataset has soft labels.""" + soft = encoder.data.soft + return None if soft is None else soft[:n] > 0 + + +class _Stop: + def __init__(self): + self.flag = False + self._prev = {} + + def __enter__(self): + for s in (signal.SIGINT, signal.SIGTERM): + try: + self._prev[s] = signal.signal(s, self._handle) + except ValueError: # not in main thread + pass + return self + + def _handle(self, *_): + if self.flag: + raise KeyboardInterrupt + print("\n[train] stop requested - saving checkpoint (Ctrl-C again to abort)") + self.flag = True + + def __exit__(self, *a): + for s, h in self._prev.items(): + signal.signal(s, h) + + +class MultiTaskBatches: + """Batches for multi-task training: each batch comes from ONE task (its own state + encoder / choice set), picked with the configured sampling weights. Deterministic + in (seed, epoch, i), so resume skips exactly the consumed batches.""" + + def __init__(self, encoders: dict, weights: dict, batch_size: int, n_batches: int, seed: int, epoch: int, + start_batch: int = 0): + self.keys = list(encoders) + w = np.array([weights[k] for k in self.keys], float) + self.p = w / w.sum() + self.encoders, self.bs, self.seed, self.epoch = encoders, batch_size, seed, epoch + self.range = range(start_batch, n_batches) + + def __len__(self): + return len(self.range) + + def __getitem__(self, i): + rng = np.random.default_rng((self.seed, self.epoch, self.range[i], 11)) + enc = self.encoders[self.keys[rng.choice(len(self.keys), p=self.p)]] + n = len(enc.data) + return enc(rng.choice(n, self.bs, replace=n < self.bs), rng) + + +def make_encoders(cfg: dict, model, task, split: DecisionData, choice_dropout: float = 0.0, seed: int = 0): + """BatchEncoder for one split; with a frozen pretrained backbone, questions and + choice labels are encoded once per vocabulary entry (BackboneTable).""" + mcfg = cfg["model"] + kw = dict(max_question_len=mcfg.get("max_question_len", 32), max_choice_len=mcfg.get("max_choice_len", 16)) + tables = {} + bb = getattr(model, "backbone", None) + if bb is not None and bb.frozen and cfg["training"].get("cache_text", True): + tok = task.tokenizer + tables = {"question_table": BackboneTable(split.questions, model, tok, kw["max_question_len"]), + "choice_table": BackboneTable([task.model_label(c) for c in split.choices], model, tok, + kw["max_choice_len"])} + return BatchEncoder(split, task, choice_dropout=choice_dropout, seed=seed, tokenizer=task.tokenizer, + **kw, **tables) + + +def train(cfg: dict, run_dir: str | Path | None = None, resume: bool = False, max_steps: int | None = None, + max_minutes: float | None = None, quiet: bool = False, final_eval: bool = True) -> dict: + tcfg = cfg["training"] + seed = int(cfg.get("seed", 0)) + seed_everything(seed) + specs = task_specs(cfg) + tasks = {s["key"]: make_task_for(cfg, s["task"]) for s in specs} + splits = {s["key"]: load_splits({**cfg, "task": s["task"], "data": s["data"]}) for s in specs} + weights = {s["key"]: s["weight"] for s in specs} + multi = len(specs) > 1 + model = make_model(cfg, list(tasks.values())) + if tcfg.get("init_checkpoint") and not resume: + ck = torch.load(tcfg["init_checkpoint"], map_location="cpu", weights_only=False) + model.load_state_dict(ck["model"]) + model.log_temperature.zero_() # re-calibrated at the end of this run + print(f"[train] initialised from {tcfg['init_checkpoint']}") + n_params = model.num_parameters() + prof = resolve_runtime(tcfg, n_params) + torch.set_num_threads(prof.threads) + device = torch.device(prof.device) + model.to(device) + + run_dir = Path(run_dir) if run_dir else new_run_dir(cfg.get("name", "run")) + ckpt_dir = run_dir / "checkpoints" + log = RunLogger(run_dir, cfg, resume=resume) + encs = {} + for k, sp in splits.items(): + encs[k] = {"train": make_encoders(cfg, model, tasks[k], sp["train"], tcfg.get("choice_dropout", 0.0), seed), + "val": make_encoders(cfg, model, tasks[k], sp["val"]), + "test": make_encoders(cfg, model, tasks[k], sp["test"])} + train_enc = {k: e["train"] for k, e in encs.items()} + + eff_bs = int(tcfg.get("batch_size", 256)) + epochs = float(tcfg.get("epochs", 1)) + n_train = sum(len(sp["train"]) for sp in splits.values()) + batches_per_epoch = max(1, n_train // prof.micro_batch) + steps_per_epoch = max(1, batches_per_epoch // prof.grad_accum) + total_steps = max(1, int(steps_per_epoch * epochs)) + if max_steps: + total_steps = min(total_steps, max_steps) + lr = tcfg.get("lr", 1e-3) + opt = torch.optim.AdamW(param_groups(model, tcfg.get("weight_decay", 0.05), lr, tcfg.get("backbone_lr")), lr=lr, + betas=(0.9, 0.98), fused=prof.device == "cuda") + warmup = int(tcfg.get("warmup_steps", min(500, total_steps // 20))) + sched = torch.optim.lr_scheduler.LambdaLR(opt, lr_lambda(warmup, total_steps, tcfg.get("min_lr_ratio", 0.05))) + scaler = torch.amp.GradScaler(enabled=prof.amp_dtype == "fp16") + fwd = torch.compile(model) if prof.compile else model + + step, epoch, batch_pos, best, elapsed_prev = 0, 0, 0, -1.0, 0.0 + samples_seen = 0 + session_samples = 0 + last = ckpt_dir / "last.pt" + if resume and last.exists(): + ck = torch.load(last, map_location=device, weights_only=False) + model.load_state_dict(ck["model"]) + opt.load_state_dict(ck["optimizer"]) + sched.load_state_dict(ck["scheduler"]) + scaler.load_state_dict(ck["scaler"]) + step, epoch, batch_pos, best = ck["step"], ck["epoch"], ck["batch_pos"], ck["best"] + elapsed_prev, samples_seen = ck.get("elapsed", 0.0), ck.get("samples_seen", 0) + torch.set_rng_state(ck["torch_rng"]) + print(f"[train] resumed from {last} at step {step} (epoch {epoch}, batch {batch_pos})") + + breakdown = model.param_breakdown() + info = {"task": "+".join(tasks) if multi else next(iter(tasks.values())).name, "tasks": list(tasks), + "params": n_params, "params_human": human_params(n_params), "params_breakdown": breakdown, + "train_rows": n_train, "val_rows": sum(len(sp["val"]) for sp in splits.values()), + "test_rows": sum(len(sp["test"]) for sp in splits.values()), + "effective_batch": eff_bs, "total_steps": total_steps, "runtime": prof.to_dict(), + "env": environment_info()} + log.write_json("env.json", info) + if not quiet: + print(f"[train] {cfg.get('name')} | {human_params(n_params)} params (core+heads " + f"{human_params(breakdown['core_total'])}, text {human_params(breakdown['text'])}, trainable " + f"{human_params(breakdown['trainable'])}) | {prof.device} ({prof.device_name}) " + f"amp={prof.amp_dtype} micro={prof.micro_batch}x{prof.grad_accum} | " + f"{n_train:,} train rows ({', '.join(tasks)}) | {total_steps:,} steps") + + def save(path, extra=None): + tmp = Path(str(path) + ".tmp") + torch.save({"model": model.state_dict(), "optimizer": opt.state_dict(), "scheduler": sched.state_dict(), + "scaler": scaler.state_dict(), "step": step, "epoch": epoch, "batch_pos": batch_pos, + "best": best, "elapsed": elapsed_prev + (time.time() - t_start), "samples_seen": samples_seen, + "torch_rng": torch.get_rng_state(), "config": cfg, **(extra or {})}, tmp) + os.replace(tmp, path) + + def validate(): + reps = {} + for k, e in encs.items(): + lg, tg = predict_logits(model, e["val"], device, max_rows=eval_rows, profile=prof) + reps[k] = calibration_report(lg, tg, acceptable=_acceptable(e["val"], len(tg))) + w = np.array([weights[k] for k in reps]) + acc = float(np.dot(w / w.sum(), [r["accuracy"] for r in reps.values()])) + return acc, reps + + loss_cfg = cfg.get("loss", {}) + eval_every = int(tcfg.get("eval_every", 1000)) + ckpt_every = int(tcfg.get("checkpoint_every", 1000)) + log_every = int(tcfg.get("log_every", 50)) + eval_rows = tcfg.get("eval_max_rows", 20000) + grad_clip = tcfg.get("grad_clip", 1.0) + t_start = time.time() + t_train = 0.0 + run_loss, run_n, window_samples, window_t = 0.0, 0, 0, time.time() + stopped_early = False + + with _Stop() as stop: + while step < total_steps and not stop.flag: + if multi: + ds = MultiTaskBatches(train_enc, weights, prof.micro_batch, batches_per_epoch, seed, epoch, batch_pos) + else: + ds = EpochBatches(next(iter(train_enc.values())), prof.micro_batch, shuffle=True, seed=seed, + epoch=epoch, start_batch=batch_pos, drop_last=True) + loader = torch.utils.data.DataLoader(ds, batch_size=None, shuffle=False, num_workers=prof.num_workers, + pin_memory=prof.device == "cuda", + prefetch_factor=4 if prof.num_workers else None, + # fork shares the in-memory dataset with workers instead of pickling it + multiprocessing_context="fork" if prof.num_workers and sys.platform == "linux" else None) + model.train() + micro = 0 + for batch in loader: + t0 = time.time() + b = to_torch(batch, device, non_blocking=True) + with autocast(prof): + out = fwd(**model_inputs(b)) + loss, terms = decision_loss(out["logits"], out["choice_mask"], b, loss_cfg, out.get("score")) + scaler.scale(loss / prof.grad_accum).backward() + micro += 1 + batch_pos += 1 + n_b = len(batch["target"]) + samples_seen += n_b + session_samples += n_b + window_samples += n_b + run_loss += float(loss.detach()) + run_n += 1 + if micro % prof.grad_accum: + t_train += time.time() - t0 + continue + if grad_clip: + scaler.unscale_(opt) + torch.nn.utils.clip_grad_norm_(model.parameters(), grad_clip) + scaler.step(opt) + scaler.update() + opt.zero_grad(set_to_none=True) + sched.step() + step += 1 + t_train += time.time() - t0 + if step % log_every == 0: + now = time.time() + sps = window_samples / max(1e-9, now - window_t) + log.log(step, train_loss=run_loss / run_n, lr=sched.get_last_lr()[0], + samples_per_sec=round(sps, 1), epoch=epoch, **{f"loss_{k}": v for k, v in terms.items()}) + if not quiet: + print(f" step {step:6d}/{total_steps} loss {run_loss / run_n:.4f} " + f"lr {sched.get_last_lr()[0]:.2e} {sps:,.0f} samples/s") + run_loss, run_n, window_samples, window_t = 0.0, 0, 0, now + if step % eval_every == 0 or step == total_steps: + acc, reps = validate() + first = next(iter(reps.values())) + extra = {"val_acceptable_acc": first["acceptable_accuracy"]} \ + if not multi and "acceptable_accuracy" in first else {} + per_task = {f"val_acc_{k}": r["accuracy"] for k, r in reps.items()} if multi else {} + log.log(step, val_acc=acc, val_nll=first["nll"], val_ece=first["ece"], + val_brier=first["brier"], **extra, **per_task) + if not quiet: + detail = " ".join(f"{k} {r['accuracy']:.4f}" for k, r in reps.items()) if multi else \ + f"nll {first['nll']:.4f} ece {first['ece']:.4f}" + print(f" [val] step {step} acc {acc:.4f} {detail}" + + (f" acceptable {first['acceptable_accuracy']:.4f}" if extra else "")) + if acc > best: + best = acc + torch.save({"model": model.state_dict(), "config": cfg, "step": step, + "val_accuracy": best}, ckpt_dir / "best.pt") + model.train() + if step % ckpt_every == 0: + save(last) + if max_minutes and (time.time() - t_start) / 60 > max_minutes: + print(f"[train] time budget of {max_minutes} min reached") + stopped_early = True + stop.flag = True + if step >= total_steps or stop.flag: + break + else: + epoch += 1 + batch_pos = 0 + continue + if batch_pos >= batches_per_epoch: + epoch, batch_pos = epoch + 1, 0 + save(last) + interrupted = stop.flag and not stopped_early and step < total_steps + + train_seconds = elapsed_prev + (time.time() - t_start) + summary = {**{k: v for k, v in info.items() if k != "env"}, "steps_done": step, "samples_seen": samples_seen, + "train_seconds": round(train_seconds, 1), + "throughput_samples_per_sec": round(session_samples / max(t_train, 1e-9), 1), + "best_val_accuracy": best, "complete": step >= total_steps, "run_dir": str(run_dir)} + hourly = cfg.get("cost", {}).get("gpu_hourly_cost") or os.environ.get("MINIJEV_GPU_HOURLY_COST") + if hourly: + summary["cost"] = {"gpu_hourly_cost": float(hourly), + "estimated_cost": round(float(hourly) * train_seconds / 3600, 4)} + if final_eval and not interrupted: + summary.update(finalize(cfg, model, run_dir, {k: e["val"] for k, e in encs.items()}, + {k: e["test"] for k, e in encs.items()}, device, prof)) + log.write_json("summary.json", summary) + log.close() + return summary + + +def _pad_logits(parts: list[np.ndarray]) -> np.ndarray: + n = max(p.shape[1] for p in parts) + return np.concatenate([np.pad(p, ((0, 0), (0, n - p.shape[1])), constant_values=-1e9) for p in parts]) + + +def finalize(cfg, model, run_dir: Path, val_encs, test_encs, device, prof) -> dict: + """Best checkpoint -> temperature fitted on val (global + per task) -> calibrated test report -> final.pt.""" + from minijev.calibration.metrics import ece as ece_fn + + if not isinstance(val_encs, dict): # single-encoder call (old signature) + val_encs, test_encs = {"task": val_encs}, {"task": test_encs} + ckpt_dir = run_dir / "checkpoints" + best = ckpt_dir / "best.pt" + if best.exists(): + model.load_state_dict(torch.load(best, map_location=device, weights_only=False)["model"]) + cal = cfg.get("calibration", {}) + per_task, V, VT, TL, TT = {}, [], [], [], [] + for k in val_encs: + vl, vt = predict_logits(model, val_encs[k], device, profile=prof) + tl, tt = predict_logits(model, test_encs[k], device, profile=prof) + Tk = fit_temperature(vl, vt) if cal.get("method", "temperature") == "temperature" else 1.0 + acc_ok = _acceptable(test_encs[k], len(tt)) + per_task[k] = {"temperature": Tk, "test_raw": calibration_report(tl, tt, 1.0, acceptable=acc_ok), + "test_calibrated": calibration_report(tl, tt, Tk, acceptable=acc_ok)} + V.append(vl), VT.append(vt), TL.append(tl), TT.append(tt) + val_lg, val_tg, test_lg, test_tg = _pad_logits(V), np.concatenate(VT), _pad_logits(TL), np.concatenate(TT) + T = fit_temperature(val_lg, val_tg) if cal.get("method", "temperature") == "temperature" else 1.0 + model.log_temperature.fill_(math.log(T)) + single = len(val_encs) == 1 + acc_ok = _acceptable(next(iter(test_encs.values())), len(test_tg)) if single else None + raw = calibration_report(test_lg, test_tg, 1.0, acceptable=acc_ok) + calibrated = calibration_report(test_lg, test_tg, T, acceptable=acc_ok) + # isotonic comparison (fit on val confidence, evaluate on test) + pv = softmax(val_lg, T) + iso = IsotonicConfidence().fit(pv.max(1), (pv.argmax(1) == val_tg).astype(float)) + pt = softmax(test_lg, T) + iso_ece = ece_fn(iso(pt.max(1)), (pt.argmax(1) == test_tg).astype(float)) + (run_dir / "reliability_raw.svg").write_text(reliability_svg(raw["reliability"], "Test - raw")) + (run_dir / "reliability_calibrated.svg").write_text( + reliability_svg(calibrated["reliability"], f"Test - temperature {T:.3f}")) + task_T = {k: v["temperature"] for k, v in per_task.items()} + torch.save({"model": model.state_dict(), "config": cfg, "temperature": T, "task_temperatures": task_T}, + ckpt_dir / "final.pt") + print(f"[calibration] T={T:.3f} | test acc {calibrated['accuracy']:.4f} | ECE {raw['ece']:.4f} -> " + f"{calibrated['ece']:.4f} | NLL {raw['nll']:.4f} -> {calibrated['nll']:.4f} | " + f"Brier {calibrated['brier']:.4f} | isotonic ECE {iso_ece:.4f}" + + (f" | acceptable acc {calibrated['acceptable_accuracy']:.4f}" if acc_ok is not None else "")) + if not single: + for k, v in per_task.items(): + c = v["test_calibrated"] + print(f" [{k}] T={v['temperature']:.3f} acc {c['accuracy']:.4f} ECE {v['test_raw']['ece']:.4f} -> " + f"{c['ece']:.4f} NLL {c['nll']:.4f}") + return {"temperature": T, "task_temperatures": task_T, "test_raw": raw, "test_calibrated": calibrated, + "test_isotonic_ece": iso_ece, "per_task": per_task, "final_checkpoint": str(ckpt_dir / "final.pt")} diff --git a/code/minijev/types.py b/code/minijev/types.py new file mode 100644 index 0000000000000000000000000000000000000000..d8e2dc9283d54a89af7205fa5fb4c281abf823fa --- /dev/null +++ b/code/minijev/types.py @@ -0,0 +1,63 @@ +"""Task-agnostic decision interfaces. + +MiniJEV always answers the same kind of request:: + + DecisionRequest(state=..., question="...", choices=["a", "b", ...]) -> Decision + +`state` is opaque to the core: each environment/task plugin knows how to turn +its states into tensors (see `minijev.tasks.Task`). Choices are plain strings, +so the number and the meaning of choices are *inputs*, not model constants. +""" +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any, Sequence + +State = Any # task-specific (SnakeState, str, dict, ...) + + +@dataclass +class DecisionRequest: + state: State + question: str + choices: Sequence[str] + + +@dataclass +class Decision: + choice: str + index: int + confidence: float # calibrated probability of `choice` + scores: dict[str, float] # calibrated probability per choice + logits: list[float] = field(default_factory=list) + embedding: list[float] | None = None # optional shared state representation + raw_scores: dict[str, float] | None = None # softmax(logits), before temperature calibration + temperature: float = 1.0 + + @property + def distribution(self) -> dict[str, float]: + return self.scores + + @property + def raw_confidence(self) -> float: + return self.raw_scores[self.choice] if self.raw_scores else self.confidence + + def to_dict(self) -> dict: + d = {"choice": self.choice, "confidence": round(self.confidence, 4), + "distribution": {k: round(v, 4) for k, v in self.scores.items()}} + if self.raw_scores is not None: + d["raw_distribution"] = {k: round(v, 4) for k, v in self.raw_scores.items()} + if self.embedding is not None: + d["embedding"] = self.embedding + return d + + +@dataclass +class BooleanDecision: + answer: bool + confidence: float # calibrated probability of `answer` + p_yes: float + raw_p_yes: float + + def __bool__(self) -> bool: + return self.answer diff --git a/code/pyproject.toml b/code/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..1cd3fa8b7d8ef36d819e1a03f9134f6da0bd4f80 --- /dev/null +++ b/code/pyproject.toml @@ -0,0 +1,35 @@ +[build-system] +requires = ["setuptools>=68"] +build-backend = "setuptools.build_meta" + +[project] +name = "minijev" +version = "0.1.0" +description = "MiniJEV: a tiny, calibrated, general-purpose decision model (state + question + choices -> scored choice)" +readme = "README.md" +requires-python = ">=3.10" +dependencies = [ + "numpy>=1.26", + "pyyaml>=6", + "psutil>=5.9", +] + +[project.optional-dependencies] +# Training / export. Inference-only deployments need just `runtime`. +train = ["torch>=2.3", "onnx>=1.16", "onnxscript>=0.1", "onnxruntime>=1.18", "tensorboard>=2.15"] +runtime = ["onnxruntime>=1.18"] +# Pretrained text encoders (v2 general decision model). +text = ["transformers>=4.40", "tokenizers>=0.19", "huggingface_hub>=0.23"] +dev = ["pytest>=8"] + +[project.scripts] +minijev = "minijev.cli:main" + +[tool.setuptools.packages.find] +include = ["minijev*", "environments*"] + +[tool.setuptools.package-data] +"environments.snake.demo" = ["static/*"] + +[tool.pytest.ini_options] +testpaths = ["tests"] diff --git a/config.json b/config.json new file mode 100644 index 0000000000000000000000000000000000000000..de80003f8af29b06145a366c488c57610d27bf06 --- /dev/null +++ b/config.json @@ -0,0 +1,89 @@ +{ + "format": "minijev-v2", + "config": { + "seed": 0, + "task": { + "name": "snake", + "choice_style": "semantic" + }, + "data": { + "dir": "runs/round2-dagger/data-it2" + }, + "env": { + "board_size": 10, + "reverse_action": "die", + "reward": { + "food": 1.0, + "death": -1.0, + "step": 0.0, + "win": 1.0 + } + }, + "model": { + "d_model": 96, + "n_heads": 4, + "n_layers": 3, + "n_decision_layers": 1, + "mlp_ratio": 2.0, + "dropout": 0.0, + "max_question_len": 32, + "max_choice_len": 16, + "state_encoders": { + "grid": { + "stem_channels": 32, + "patch_size": 1, + "max_grid": 34 + } + } + }, + "training": { + "batch_size": 256, + "epochs": 1, + "lr": 0.0005, + "min_lr_ratio": 0.05, + "weight_decay": 0.05, + "warmup_steps": 100, + "grad_clip": 1.0, + "choice_dropout": 0.1, + "eval_every": 1000, + "checkpoint_every": 1000, + "log_every": 100, + "eval_max_rows": 20000, + "hardware": { + "device": "auto", + "amp": "auto", + "num_workers": "auto", + "compile": "auto" + }, + "init_checkpoint": "runs/round2-dagger/it1/checkpoints/final.pt" + }, + "loss": { + "hard_weight": 1.0, + "label_smoothing": 0.0, + "soft_weight": 0.0, + "kd_weight": 1.0, + "kd_temperature": 2.0 + }, + "calibration": { + "method": "temperature" + }, + "eval": { + "games": 200, + "parallel": 64 + }, + "name": "snake-small-dagger8-dagger2", + "dagger": { + "keep_prob": 0.2, + "explore_eps": 0.02, + "epochs": 1, + "lr": 0.0005 + } + }, + "temperature": 1.4188514947891235, + "task_temperatures": {}, + "metrics": { + "avg_score": 88.56, + "win_rate": 0.735, + "games": 200 + } +} \ No newline at end of file diff --git a/model.safetensors b/model.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..52c948794d51e3c29c9e0ba253ebb7ae04d93251 --- /dev/null +++ b/model.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b1afa3fd90c8e17836f886f672fd6511b6e2137eb53df95cdd7e237875659dcb +size 1979080