MiniJEV v2 model export
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- README.md +70 -0
- code/environments/__init__.py +0 -0
- code/environments/__pycache__/__init__.cpython-314.pyc +0 -0
- code/environments/snake/__init__.py +0 -0
- code/environments/snake/__pycache__/__init__.cpython-314.pyc +0 -0
- code/environments/snake/__pycache__/agents.cpython-314.pyc +0 -0
- code/environments/snake/__pycache__/encoder.cpython-314.pyc +0 -0
- code/environments/snake/__pycache__/env.cpython-314.pyc +0 -0
- code/environments/snake/__pycache__/task.cpython-314.pyc +0 -0
- code/environments/snake/agents.py +264 -0
- code/environments/snake/dagger.py +80 -0
- code/environments/snake/dataset.py +196 -0
- code/environments/snake/demo/__init__.py +0 -0
- code/environments/snake/demo/server.py +184 -0
- code/environments/snake/demo/static/index.html +128 -0
- code/environments/snake/encoder.py +13 -0
- code/environments/snake/env.py +222 -0
- code/environments/snake/evaluate.py +101 -0
- code/environments/snake/rl.py +158 -0
- code/environments/snake/task.py +124 -0
- code/minijev/__init__.py +14 -0
- code/minijev/__pycache__/__init__.cpython-314.pyc +0 -0
- code/minijev/__pycache__/device.cpython-314.pyc +0 -0
- code/minijev/__pycache__/hub.cpython-314.pyc +0 -0
- code/minijev/__pycache__/keys.cpython-314.pyc +0 -0
- code/minijev/__pycache__/runs.cpython-314.pyc +0 -0
- code/minijev/__pycache__/tasks.cpython-314.pyc +0 -0
- code/minijev/__pycache__/text_task_utils.cpython-314.pyc +0 -0
- code/minijev/__pycache__/tokenizer.cpython-314.pyc +0 -0
- code/minijev/__pycache__/tokenizers.cpython-314.pyc +0 -0
- code/minijev/__pycache__/types.cpython-314.pyc +0 -0
- code/minijev/benchmark/__init__.py +0 -0
- code/minijev/benchmark/perf.py +131 -0
- code/minijev/calibration/__init__.py +0 -0
- code/minijev/calibration/__pycache__/__init__.cpython-314.pyc +0 -0
- code/minijev/calibration/__pycache__/metrics.cpython-314.pyc +0 -0
- code/minijev/calibration/metrics.py +155 -0
- code/minijev/choices/__init__.py +3 -0
- code/minijev/choices/__pycache__/__init__.cpython-314.pyc +0 -0
- code/minijev/choices/__pycache__/encoder.cpython-314.pyc +0 -0
- code/minijev/choices/encoder.py +66 -0
- code/minijev/cli.py +416 -0
- code/minijev/config.py +62 -0
- code/minijev/core/__init__.py +3 -0
- code/minijev/core/__pycache__/__init__.cpython-314.pyc +0 -0
- code/minijev/core/__pycache__/core.cpython-314.pyc +0 -0
- code/minijev/core/__pycache__/layers.cpython-314.pyc +0 -0
- code/minijev/core/core.py +88 -0
- code/minijev/core/layers.py +76 -0
- code/minijev/datasets/__init__.py +0 -0
README.md
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
tags:
|
| 6 |
+
- decision-model
|
| 7 |
+
- reinforcement-learning
|
| 8 |
+
- snake
|
| 9 |
+
- minijev
|
| 10 |
+
library_name: minijev
|
| 11 |
+
---
|
| 12 |
+
|
| 13 |
+
# MiniJEV · Snake
|
| 14 |
+
|
| 15 |
+
A **tiny decision model** (≈0.5M parameters, 2 MB) that plays Snake on a 10×10 board.
|
| 16 |
+
It is not a language model and generates no text. At each step it scores the
|
| 17 |
+
available choices (`move up`, `move down`, `move left`, `move right`) and returns a
|
| 18 |
+
**calibrated probability** for each one.
|
| 19 |
+
|
| 20 |
+
It is the first benchmark of **MiniJEV**. The same core (state + question +
|
| 21 |
+
dynamic list of choices → choice + calibrated confidence) is used for text decisions
|
| 22 |
+
in [`markuz89/minijev-general`](https://huggingface.co/markuz89/minijev-general).
|
| 23 |
+
|
| 24 |
+
## Results (200 games, 10×10, max score 97)
|
| 25 |
+
|
| 26 |
+
| metric | value |
|
| 27 |
+
|---|---|
|
| 28 |
+
| average score | **88.6** |
|
| 29 |
+
| median score | 97 (board filled) |
|
| 30 |
+
| games won (board filled) | **73.5 %** |
|
| 31 |
+
| deaths | 19 % |
|
| 32 |
+
| stopped for starvation | 7.5 % |
|
| 33 |
+
| fatal moves | 0.02 % of decisions |
|
| 34 |
+
|
| 35 |
+
For comparison, the search-based oracle the model was first distilled from scores
|
| 36 |
+
95 on average and wins 38 % of games. The model wins more often but has a lower
|
| 37 |
+
average score.
|
| 38 |
+
|
| 39 |
+
Training pipeline:
|
| 40 |
+
1. Supervised distillation from the oracle.
|
| 41 |
+
2. DAgger.
|
| 42 |
+
3. PPO (two rounds, γ = 0.995, on an RTX 4090).
|
| 43 |
+
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).
|
| 44 |
+
|
| 45 |
+
## Usage
|
| 46 |
+
|
| 47 |
+
```bash
|
| 48 |
+
git clone https://huggingface.co/markuz89/minijev-snake && cd minijev-snake/code
|
| 49 |
+
pip install -e ".[train]" # needs torch; ONNX export is available for torch-free inference
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
```python
|
| 53 |
+
from minijev.inference.runtime import MiniJEV
|
| 54 |
+
|
| 55 |
+
dec = MiniJEV.load("..") # the cloned repo folder (or the repo id)
|
| 56 |
+
state = dec.task.example_states(1)[0] # {"body": [...], "food": (x, y), "direction": ...}
|
| 57 |
+
d = dec.decide(state) # question and choices default to the Snake task
|
| 58 |
+
print(d.choice, d.confidence, d.scores) # e.g. "move left" 0.999 {...}
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
## Files
|
| 62 |
+
|
| 63 |
+
- `model.safetensors`: weights (no pickle)
|
| 64 |
+
- `config.json`: architecture, task config, calibration temperature, metrics
|
| 65 |
+
- `code/`: the `minijev` package and the Snake environment needed to run it
|
| 66 |
+
|
| 67 |
+
## Limits
|
| 68 |
+
|
| 69 |
+
The model was trained only on 10×10 boards. Inputs are the grid channels of the
|
| 70 |
+
MiniJEV Snake environment, and it is not a general game-playing agent.
|
code/environments/__init__.py
ADDED
|
File without changes
|
code/environments/__pycache__/__init__.cpython-314.pyc
ADDED
|
Binary file (175 Bytes). View file
|
|
|
code/environments/snake/__init__.py
ADDED
|
File without changes
|
code/environments/snake/__pycache__/__init__.cpython-314.pyc
ADDED
|
Binary file (181 Bytes). View file
|
|
|
code/environments/snake/__pycache__/agents.cpython-314.pyc
ADDED
|
Binary file (17.8 kB). View file
|
|
|
code/environments/snake/__pycache__/encoder.cpython-314.pyc
ADDED
|
Binary file (1.33 kB). View file
|
|
|
code/environments/snake/__pycache__/env.cpython-314.pyc
ADDED
|
Binary file (18.3 kB). View file
|
|
|
code/environments/snake/__pycache__/task.cpython-314.pyc
ADDED
|
Binary file (10.9 kB). View file
|
|
|
code/environments/snake/agents.py
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Scripted Snake agents: the oracle used for supervision and the baselines.
|
| 2 |
+
|
| 3 |
+
All agents implement `act(state: SnakeState) -> str`.
|
| 4 |
+
|
| 5 |
+
Path search is *time-aware*: a body cell at index i (head=0) of a snake of
|
| 6 |
+
length L becomes free after L - i moves, so a path may pass where the tail
|
| 7 |
+
currently is if it arrives late enough. This makes BFS paths exact as long as
|
| 8 |
+
no food is eaten along the way (food is only ever the final cell).
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
from collections import deque
|
| 13 |
+
from functools import lru_cache
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
|
| 17 |
+
from .env import ACTIONS, DELTAS, SnakeState
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@lru_cache(maxsize=16)
|
| 21 |
+
def _neighbors(h: int, w: int) -> tuple[tuple[tuple[int, str], ...], ...]:
|
| 22 |
+
out = []
|
| 23 |
+
for cell in range(h * w):
|
| 24 |
+
r, c = divmod(cell, w)
|
| 25 |
+
nb = []
|
| 26 |
+
for a in ACTIONS:
|
| 27 |
+
dr, dc = DELTAS[a]
|
| 28 |
+
nr, nc = r + dr, c + dc
|
| 29 |
+
if 0 <= nr < h and 0 <= nc < w:
|
| 30 |
+
nb.append((nr * w + nc, a))
|
| 31 |
+
out.append(tuple(nb))
|
| 32 |
+
return tuple(out)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _flat(state: SnakeState) -> tuple[list[int], int]:
|
| 36 |
+
w = state.width
|
| 37 |
+
body = [r * w + c for r, c in state.body]
|
| 38 |
+
food = state.food[0] * w + state.food[1] if state.food is not None else -1
|
| 39 |
+
return body, food
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _free_times(body: list[int], area: int) -> list[int]:
|
| 43 |
+
ft = [0] * area
|
| 44 |
+
L = len(body)
|
| 45 |
+
for i, cell in enumerate(body):
|
| 46 |
+
ft[cell] = L - i
|
| 47 |
+
return ft
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _bfs(nbrs, area: int, start: int, ft: list[int], goal: int = -1):
|
| 51 |
+
dist = [-1] * area
|
| 52 |
+
parent = [-1] * area
|
| 53 |
+
dist[start] = 0
|
| 54 |
+
q = deque([start])
|
| 55 |
+
while q:
|
| 56 |
+
u = q.popleft()
|
| 57 |
+
du = dist[u] + 1
|
| 58 |
+
for v, _ in nbrs[u]:
|
| 59 |
+
if dist[v] < 0 and du >= ft[v]:
|
| 60 |
+
dist[v] = du
|
| 61 |
+
parent[v] = u
|
| 62 |
+
if v == goal:
|
| 63 |
+
return dist, parent
|
| 64 |
+
q.append(v)
|
| 65 |
+
return dist, parent
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _reachable_count(nbrs, area: int, start: int, ft: list[int]) -> int:
|
| 69 |
+
dist, _ = _bfs(nbrs, area, start, ft)
|
| 70 |
+
return sum(1 for d in dist if d > 0)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _tail_reachable(nbrs, area: int, body: list[int]) -> tuple[bool, int]:
|
| 74 |
+
if len(body) < 2:
|
| 75 |
+
return True, 0
|
| 76 |
+
ft = _free_times(body, area)
|
| 77 |
+
tail = body[-1]
|
| 78 |
+
dist, _ = _bfs(nbrs, area, body[0], ft, goal=tail)
|
| 79 |
+
return dist[tail] > 0, dist[tail]
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def safe_moves(state: SnakeState) -> list[str]:
|
| 83 |
+
"""Moves that do not die on the very next step."""
|
| 84 |
+
body, _ = _flat(state)
|
| 85 |
+
nbrs = _neighbors(state.height, state.width)
|
| 86 |
+
ft = _free_times(body, state.height * state.width)
|
| 87 |
+
return [a for v, a in nbrs[body[0]] if ft[v] <= 1]
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class Agent:
|
| 91 |
+
name = "agent"
|
| 92 |
+
|
| 93 |
+
def act(self, state: SnakeState) -> str: # pragma: no cover - interface
|
| 94 |
+
raise NotImplementedError
|
| 95 |
+
|
| 96 |
+
def reset(self, seed: int | None = None) -> None:
|
| 97 |
+
pass
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class RandomAgent(Agent):
|
| 101 |
+
name = "random"
|
| 102 |
+
|
| 103 |
+
def __init__(self, seed: int = 0):
|
| 104 |
+
self.rng = np.random.default_rng(seed)
|
| 105 |
+
|
| 106 |
+
def reset(self, seed=None):
|
| 107 |
+
if seed is not None:
|
| 108 |
+
self.rng = np.random.default_rng(seed)
|
| 109 |
+
|
| 110 |
+
def act(self, state):
|
| 111 |
+
return ACTIONS[int(self.rng.integers(4))]
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class GreedyFoodAgent(Agent):
|
| 115 |
+
"""Minimise Manhattan distance to food; avoid *immediately* fatal moves when possible."""
|
| 116 |
+
name = "greedy"
|
| 117 |
+
|
| 118 |
+
def act(self, state):
|
| 119 |
+
safe = safe_moves(state) or list(ACTIONS)
|
| 120 |
+
hr, hc = state.body[0]
|
| 121 |
+
fr, fc = state.food if state.food else (hr, hc)
|
| 122 |
+
return min(safe, key=lambda a: abs(hr + DELTAS[a][0] - fr) + abs(hc + DELTAS[a][1] - fc))
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class BFSAgent(Agent):
|
| 126 |
+
"""Shortest (time-aware) path to food, no look-ahead; else the safe move with most space."""
|
| 127 |
+
name = "bfs"
|
| 128 |
+
|
| 129 |
+
def act(self, state):
|
| 130 |
+
h, w = state.height, state.width
|
| 131 |
+
area = h * w
|
| 132 |
+
nbrs = _neighbors(h, w)
|
| 133 |
+
body, food = _flat(state)
|
| 134 |
+
ft = _free_times(body, area)
|
| 135 |
+
if food >= 0:
|
| 136 |
+
path = _path_to(nbrs, area, body[0], ft, food)
|
| 137 |
+
if path:
|
| 138 |
+
return _direction(w, body[0], path[0])
|
| 139 |
+
return _max_space_move(nbrs, area, body) or ACTIONS[0]
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class SurvivalAgent(Agent):
|
| 143 |
+
"""Flood-fill heuristic: maximise reachable space, break ties by distance to food."""
|
| 144 |
+
name = "survival"
|
| 145 |
+
|
| 146 |
+
def act(self, state):
|
| 147 |
+
h, w = state.height, state.width
|
| 148 |
+
area = h * w
|
| 149 |
+
nbrs = _neighbors(h, w)
|
| 150 |
+
body, food = _flat(state)
|
| 151 |
+
ft = _free_times(body, area)
|
| 152 |
+
best, best_key = None, None
|
| 153 |
+
fr, fc = divmod(food, w) if food >= 0 else divmod(body[0], w)
|
| 154 |
+
for v, a in nbrs[body[0]]:
|
| 155 |
+
if ft[v] > 1:
|
| 156 |
+
continue
|
| 157 |
+
nb = [v] + (body if v == food else body[:-1])
|
| 158 |
+
space = _reachable_count(nbrs, area, v, _free_times(nb, area))
|
| 159 |
+
r, c = divmod(v, w)
|
| 160 |
+
key = (min(space, len(nb) + 1), -(abs(r - fr) + abs(c - fc)))
|
| 161 |
+
if best_key is None or key > best_key:
|
| 162 |
+
best, best_key = a, key
|
| 163 |
+
return best or ACTIONS[0]
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class OracleAgent(Agent):
|
| 167 |
+
"""Strong teacher: eat only if the snake can still reach its tail afterwards,
|
| 168 |
+
otherwise chase the tail along the longest safe route, otherwise maximise space.
|
| 169 |
+
|
| 170 |
+
`analyze` also returns the *set* of equally good moves. Ties are broken by a fixed
|
| 171 |
+
priority (UP > DOWN > LEFT > RIGHT) instead of BFS queue order, so the hard label
|
| 172 |
+
is a learnable function of the state (and this rule also scored best: 95.0 vs
|
| 173 |
+
91.5-92.1 for "close the larger/smaller axis gap first", 60 games 10x10).
|
| 174 |
+
"""
|
| 175 |
+
name = "oracle"
|
| 176 |
+
|
| 177 |
+
def act(self, state):
|
| 178 |
+
return self.analyze(state)[0]
|
| 179 |
+
|
| 180 |
+
def analyze(self, state) -> tuple[str, list[str], str]:
|
| 181 |
+
"""-> (move, optimal_moves, mode) with mode in {eat, tail, space, dead}."""
|
| 182 |
+
h, w = state.height, state.width
|
| 183 |
+
area = h * w
|
| 184 |
+
nbrs = _neighbors(h, w)
|
| 185 |
+
body, food = _flat(state)
|
| 186 |
+
L = len(body)
|
| 187 |
+
ft = _free_times(body, area)
|
| 188 |
+
head = body[0]
|
| 189 |
+
safe = [(v, a) for v, a in nbrs[head] if ft[v] <= 1]
|
| 190 |
+
if not safe:
|
| 191 |
+
return ACTIONS[0], list(ACTIONS), "dead"
|
| 192 |
+
if food >= 0:
|
| 193 |
+
dist, _ = _bfs(nbrs, area, head, ft, goal=food)
|
| 194 |
+
d = dist[food]
|
| 195 |
+
if d > 0:
|
| 196 |
+
good = []
|
| 197 |
+
for v, a in safe:
|
| 198 |
+
if v == food:
|
| 199 |
+
virtual = [v] + body
|
| 200 |
+
else:
|
| 201 |
+
nb = [v] + body[:-1]
|
| 202 |
+
path = _path_to(nbrs, area, v, _free_times(nb, area), food)
|
| 203 |
+
if len(path) != d - 1:
|
| 204 |
+
continue
|
| 205 |
+
virtual = (path[::-1] + nb)[: L + 1]
|
| 206 |
+
if len(virtual) >= area or _tail_reachable(nbrs, area, virtual)[0]:
|
| 207 |
+
good.append(a)
|
| 208 |
+
if good:
|
| 209 |
+
return good[0], good, "eat"
|
| 210 |
+
# tail chasing: keep an escape route, prefer the move farthest from the tail
|
| 211 |
+
cands = []
|
| 212 |
+
for v, a in safe:
|
| 213 |
+
nb = [v] + (body if v == food else body[:-1])
|
| 214 |
+
ok, dt = _tail_reachable(nbrs, area, nb)
|
| 215 |
+
if ok:
|
| 216 |
+
cands.append((dt, a))
|
| 217 |
+
if cands:
|
| 218 |
+
best = max(dt for dt, _ in cands)
|
| 219 |
+
good = [a for dt, a in cands if dt == best]
|
| 220 |
+
return good[0], good, "tail"
|
| 221 |
+
spaces = []
|
| 222 |
+
for v, a in safe:
|
| 223 |
+
nb = [v] + (body if v == food else body[:-1])
|
| 224 |
+
spaces.append((_reachable_count(nbrs, area, v, _free_times(nb, area)), a))
|
| 225 |
+
best = max(sp for sp, _ in spaces)
|
| 226 |
+
good = [a for sp, a in spaces if sp == best]
|
| 227 |
+
return good[0], good, "space"
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def _path_to(nbrs, area, start, ft, goal) -> list[int]:
|
| 231 |
+
dist, parent = _bfs(nbrs, area, start, ft, goal)
|
| 232 |
+
if dist[goal] <= 0:
|
| 233 |
+
return []
|
| 234 |
+
path = [goal]
|
| 235 |
+
while parent[path[-1]] != start:
|
| 236 |
+
path.append(parent[path[-1]])
|
| 237 |
+
return path[::-1]
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def _direction(w: int, a: int, b: int) -> str:
|
| 241 |
+
ar, ac = divmod(a, w)
|
| 242 |
+
br, bc = divmod(b, w)
|
| 243 |
+
return {(-1, 0): "UP", (1, 0): "DOWN", (0, -1): "LEFT", (0, 1): "RIGHT"}[(br - ar, bc - ac)]
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def _max_space_move(nbrs, area, body) -> str | None:
|
| 247 |
+
ft = _free_times(body, area)
|
| 248 |
+
best, best_space = None, -1
|
| 249 |
+
for v, a in nbrs[body[0]]:
|
| 250 |
+
if ft[v] > 1:
|
| 251 |
+
continue
|
| 252 |
+
nb = [v] + body[:-1]
|
| 253 |
+
space = _reachable_count(nbrs, area, v, _free_times(nb, area))
|
| 254 |
+
if space > best_space:
|
| 255 |
+
best, best_space = a, space
|
| 256 |
+
return best
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
AGENTS = {c.name: c for c in (RandomAgent, GreedyFoodAgent, BFSAgent, SurvivalAgent, OracleAgent)}
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def make_agent(name: str, seed: int = 0) -> Agent:
|
| 263 |
+
cls = AGENTS[name]
|
| 264 |
+
return cls(seed) if cls is RandomAgent else cls()
|
code/environments/snake/dagger.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""DAgger for Snake (Ross et al., 2011).
|
| 2 |
+
|
| 3 |
+
Behaviour cloning only sees states the oracle visits; once the student makes a
|
| 4 |
+
mistake it lands in states it never trained on and errors compound. DAgger lets
|
| 5 |
+
the student play, labels *its* states with the oracle, aggregates them with the
|
| 6 |
+
original data and fine-tunes. Cheap (no reward engineering, the oracle is
|
| 7 |
+
free) and directly targets the student's own failure modes.
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import copy
|
| 12 |
+
import json
|
| 13 |
+
import shutil
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
from minijev.datasets.decision_data import DecisionData
|
| 17 |
+
from minijev.inference.runtime import TorchDecider
|
| 18 |
+
from minijev.training.supervised import train
|
| 19 |
+
|
| 20 |
+
from .dataset import QUESTION, collect_with_policy
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def run_dagger(cfg: dict, checkpoint: str, iterations: int = 2, samples: int = 100_000,
|
| 24 |
+
run_dir: str | None = None) -> list[dict]:
|
| 25 |
+
import torch
|
| 26 |
+
|
| 27 |
+
# model/training settings come from the checkpoint (DAgger fine-tunes *that* model);
|
| 28 |
+
# the dagger config only contributes its `dagger`, `env` and `eval` sections
|
| 29 |
+
ck_cfg = torch.load(checkpoint, map_location="cpu", weights_only=False)["config"]
|
| 30 |
+
cfg = {**copy.deepcopy(ck_cfg), **{k: cfg[k] for k in ("dagger", "env", "eval") if k in cfg}}
|
| 31 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 32 |
+
root = Path(run_dir or f"runs/{ck_cfg.get('name', 'snake')}-dagger")
|
| 33 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 34 |
+
base_dir = Path(cfg["data"]["dir"])
|
| 35 |
+
agg = DecisionData.load(base_dir / "train.npz")
|
| 36 |
+
dcfg = cfg.get("dagger", {})
|
| 37 |
+
board_sizes = cfg["data"].get("generate", {}).get("board_sizes", [cfg.get("env", {}).get("board_size", 10)])
|
| 38 |
+
history = json.loads((root / "dagger.json").read_text()) if (root / "dagger.json").exists() else []
|
| 39 |
+
for rec in history: # resume: finished iterations are kept, their data is rebuilt below
|
| 40 |
+
checkpoint = rec["checkpoint"]
|
| 41 |
+
if history:
|
| 42 |
+
agg = DecisionData.load(root / f"data-it{history[-1]['iteration']}" / "train.npz")
|
| 43 |
+
print(f"[dagger] resuming after iteration {history[-1]['iteration']}")
|
| 44 |
+
for it in range(len(history) + 1, iterations + 1):
|
| 45 |
+
dec = TorchDecider(checkpoint, threads=4, device=device)
|
| 46 |
+
# probs are aligned with ACTIONS order whatever the labels ("UP" or "move up")
|
| 47 |
+
policy = lambda states: dec.probs(states, QUESTION, list(dec.task.default_choices)) # noqa: E731
|
| 48 |
+
print(f"[dagger] iteration {it}: collecting {samples:,} student states ...")
|
| 49 |
+
new = collect_with_policy(policy, samples, seed=1000 + it, board_sizes=board_sizes,
|
| 50 |
+
keep_prob=dcfg.get("keep_prob", 0.2), explore_eps=dcfg.get("explore_eps", 0.02),
|
| 51 |
+
env_cfg={k: v for k, v in cfg.get("env", {}).items() if k != "board_size"},
|
| 52 |
+
game_id_base=10**9 * it, parallel=256)
|
| 53 |
+
agg = DecisionData.concat([agg, new])
|
| 54 |
+
data_dir = root / f"data-it{it}"
|
| 55 |
+
data_dir.mkdir(exist_ok=True)
|
| 56 |
+
agg.save(data_dir / "train.npz")
|
| 57 |
+
for split in ("val", "test"): # evaluation splits stay the original, untouched ones
|
| 58 |
+
shutil.copy(base_dir / f"{split}.npz", data_dir / f"{split}.npz")
|
| 59 |
+
c = copy.deepcopy(cfg)
|
| 60 |
+
c["name"] = f"{cfg.get('name', 'snake')}-dagger{it}"
|
| 61 |
+
c["data"] = {"dir": str(data_dir)}
|
| 62 |
+
c["training"]["init_checkpoint"] = checkpoint
|
| 63 |
+
c["training"]["epochs"] = dcfg.get("epochs", 1)
|
| 64 |
+
c["training"]["lr"] = dcfg.get("lr", cfg["training"].get("lr", 1e-3) * 0.5)
|
| 65 |
+
c["training"]["warmup_steps"] = 100
|
| 66 |
+
it_dir = root / f"it{it}"
|
| 67 |
+
summary = train(c, run_dir=it_dir, resume=(it_dir / "checkpoints" / "last.pt").exists())
|
| 68 |
+
checkpoint = summary["final_checkpoint"]
|
| 69 |
+
from .evaluate import model_policy, play_games
|
| 70 |
+
games = play_games(model_policy(TorchDecider(checkpoint, threads=4, device=device)),
|
| 71 |
+
cfg.get("eval", {}).get("games", 200), cfg.get("env", {}), parallel=200)
|
| 72 |
+
(root / f"it{it}" / "games.json").write_text(json.dumps(games, indent=2))
|
| 73 |
+
rec = {"iteration": it, "rows": len(agg), "new_rows": len(new), "checkpoint": checkpoint,
|
| 74 |
+
"test_acc": summary["test_calibrated"]["accuracy"], "test_ece": summary["test_calibrated"]["ece"],
|
| 75 |
+
"avg_score": games["avg_score"], "fatal_move_rate": games["fatal_move_rate"]}
|
| 76 |
+
print(f"[dagger] it {it}: avg score {games['avg_score']:.1f} | test acc {rec['test_acc']:.4f} "
|
| 77 |
+
f"| fatal-move {games['fatal_move_rate']:.4%}")
|
| 78 |
+
history.append(rec)
|
| 79 |
+
(root / "dagger.json").write_text(json.dumps(history, indent=2))
|
| 80 |
+
return history
|
code/environments/snake/dataset.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Oracle-labelled Snake datasets.
|
| 2 |
+
|
| 3 |
+
Games are played by a behaviour policy (oracle + a little exploration), every
|
| 4 |
+
visited state is labelled with the oracle's move, and a random subset of states
|
| 5 |
+
(`keep_prob`) is kept so a dataset of N rows spans many independent games.
|
| 6 |
+
Rows carry their game id (`group`) for leakage-free splits and an exact state
|
| 7 |
+
hash to drop train/test duplicates (e.g. near-identical opening positions).
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import json
|
| 12 |
+
import multiprocessing as mp
|
| 13 |
+
import os
|
| 14 |
+
import sys
|
| 15 |
+
from concurrent.futures import ProcessPoolExecutor
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
from minijev.datasets.decision_data import DecisionData, split_by_group
|
| 21 |
+
|
| 22 |
+
from .agents import make_agent, safe_moves
|
| 23 |
+
from .env import ACTIONS, SnakeConfig, SnakeEnv, SnakeState
|
| 24 |
+
from .task import SnakeTask
|
| 25 |
+
|
| 26 |
+
QUESTION = SnakeTask.default_question
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def state_hash(s: SnakeState) -> int:
|
| 30 |
+
return hash((s.height, s.width, tuple(s.body), s.food))
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def play_and_label(n_samples: int, seed: int, board_sizes=(10,), keep_prob: float = 0.1,
|
| 34 |
+
explore_eps: float = 0.05, env_cfg: dict | None = None,
|
| 35 |
+
behaviour=None, labeler: str = "oracle", game_id_base: int = 0):
|
| 36 |
+
"""Collect `n_samples` labelled states. `behaviour(state, rng) -> action` (default: the
|
| 37 |
+
labeler itself with epsilon-random safe moves). Returns (states, labels, groups)."""
|
| 38 |
+
rng = np.random.default_rng(seed)
|
| 39 |
+
oracle = make_agent(labeler)
|
| 40 |
+
states, labels, groups, optimal = [], [], [], []
|
| 41 |
+
game = 0
|
| 42 |
+
while len(states) < n_samples:
|
| 43 |
+
size = int(board_sizes[game % len(board_sizes)])
|
| 44 |
+
cfg = SnakeConfig.from_dict({**(env_cfg or {}), "height": size, "width": size})
|
| 45 |
+
gid = game_id_base + game
|
| 46 |
+
env = SnakeEnv(cfg, seed=int(rng.integers(2**31)))
|
| 47 |
+
while not env.done and len(states) < n_samples:
|
| 48 |
+
s = env.state()
|
| 49 |
+
label, good, _ = oracle.analyze(s)
|
| 50 |
+
if rng.random() < keep_prob:
|
| 51 |
+
states.append(s)
|
| 52 |
+
labels.append(label)
|
| 53 |
+
groups.append(gid)
|
| 54 |
+
optimal.append(good)
|
| 55 |
+
if behaviour is not None:
|
| 56 |
+
action = behaviour(s, rng)
|
| 57 |
+
elif rng.random() < explore_eps:
|
| 58 |
+
safe = safe_moves(s)
|
| 59 |
+
action = safe[int(rng.integers(len(safe)))] if safe else label
|
| 60 |
+
else:
|
| 61 |
+
action = label
|
| 62 |
+
env.step(action)
|
| 63 |
+
game += 1
|
| 64 |
+
return states, labels, groups, optimal
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _worker(args):
|
| 68 |
+
n, seed, sizes, keep, eps, env_cfg, gbase = args
|
| 69 |
+
return play_and_label(n, seed, sizes, keep, eps, env_cfg, game_id_base=gbase)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def to_decision_data(states, labels, groups, optimal=None, meta: dict | None = None) -> DecisionData:
|
| 73 |
+
"""`soft` = uniform distribution over the oracle's equally-optimal moves: used for the
|
| 74 |
+
"optimal-move accuracy" metric and available as a soft-label training target."""
|
| 75 |
+
task = SnakeTask()
|
| 76 |
+
lab = {a: i for i, a in enumerate(ACTIONS)}
|
| 77 |
+
n = len(states)
|
| 78 |
+
soft = None
|
| 79 |
+
if optimal is not None:
|
| 80 |
+
soft = np.zeros((n, 4), np.float32)
|
| 81 |
+
for i, good in enumerate(optimal):
|
| 82 |
+
soft[i, [lab[a] for a in good]] = 1.0 / len(good)
|
| 83 |
+
return DecisionData(
|
| 84 |
+
task="snake",
|
| 85 |
+
state=task.states_to_arrays(states),
|
| 86 |
+
questions=[QUESTION],
|
| 87 |
+
question_idx=np.zeros(n, np.int32),
|
| 88 |
+
choices=list(ACTIONS),
|
| 89 |
+
choice_idx=np.tile(np.arange(4, dtype=np.int32), (n, 1)),
|
| 90 |
+
target=np.array([lab[a] for a in labels], np.int64),
|
| 91 |
+
group=np.array(groups, np.int64),
|
| 92 |
+
hash=np.array([state_hash(s) for s in states], np.int64),
|
| 93 |
+
soft=soft,
|
| 94 |
+
meta=meta or {},
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def generate(n_samples: int, seed: int = 0, board_sizes=(10,), keep_prob: float = 0.1,
|
| 99 |
+
explore_eps: float = 0.05, env_cfg: dict | None = None, workers: int | None = None) -> DecisionData:
|
| 100 |
+
workers = workers or max(1, (os.cpu_count() or 2) - 1)
|
| 101 |
+
workers = min(workers, max(1, n_samples // 2000))
|
| 102 |
+
per = [n_samples // workers + (1 if i < n_samples % workers else 0) for i in range(workers)]
|
| 103 |
+
jobs = [(per[i], seed * 1000 + i, tuple(board_sizes), keep_prob, explore_eps, env_cfg, i * 10_000_000)
|
| 104 |
+
for i in range(workers)]
|
| 105 |
+
if workers == 1:
|
| 106 |
+
results = [_worker(jobs[0])]
|
| 107 |
+
else:
|
| 108 |
+
ctx = mp.get_context("fork") if sys.platform == "linux" else None
|
| 109 |
+
with ProcessPoolExecutor(workers, mp_context=ctx) as ex:
|
| 110 |
+
results = list(ex.map(_worker, jobs))
|
| 111 |
+
states = [s for r in results for s in r[0]]
|
| 112 |
+
labels = [a for r in results for a in r[1]]
|
| 113 |
+
groups = [g for r in results for g in r[2]]
|
| 114 |
+
optimal = [o for r in results for o in r[3]]
|
| 115 |
+
meta = {"generator": "oracle", "board_sizes": list(board_sizes), "keep_prob": keep_prob,
|
| 116 |
+
"explore_eps": explore_eps, "seed": seed, "env": env_cfg or {}}
|
| 117 |
+
return to_decision_data(states, labels, groups, optimal, meta)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def generate_splits(out_dir: str | Path, n_samples: int, seed: int = 0, fractions=(0.9, 0.05, 0.05),
|
| 121 |
+
preview: int = 50, **kw) -> dict:
|
| 122 |
+
data = generate(n_samples, seed=seed, **kw)
|
| 123 |
+
splits = split_by_group(data, fractions, seed=seed)
|
| 124 |
+
out = Path(out_dir)
|
| 125 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 126 |
+
summary = {}
|
| 127 |
+
for name, d in splits.items():
|
| 128 |
+
d.save(out / f"{name}.npz")
|
| 129 |
+
summary[name] = {"rows": len(d), "games": int(len(np.unique(d.group))),
|
| 130 |
+
"dropped_duplicates": d.meta.get("dropped_duplicates", 0),
|
| 131 |
+
"label_distribution": {a: int((d.target == i).sum()) for i, a in enumerate(ACTIONS)}}
|
| 132 |
+
(out / "meta.json").write_text(json.dumps({"task": "snake", **data.meta, "splits": summary}, indent=2))
|
| 133 |
+
if preview:
|
| 134 |
+
export_jsonl(splits["train"], out / "preview.jsonl", limit=preview)
|
| 135 |
+
return summary
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def export_jsonl(data: DecisionData, path: str | Path, limit: int | None = None) -> None:
|
| 139 |
+
"""Human-readable export in the canonical {state, question, choices, target} format."""
|
| 140 |
+
from minijev.tasks import ragged_take
|
| 141 |
+
|
| 142 |
+
n = len(data) if limit is None else min(limit, len(data))
|
| 143 |
+
with open(path, "w") as f:
|
| 144 |
+
for i in range(n):
|
| 145 |
+
w = int(data.state["width"][i])
|
| 146 |
+
cells, _ = ragged_take(data.state["body"], data.state["body_offsets"], np.array([i]))
|
| 147 |
+
food = int(data.state["food"][i])
|
| 148 |
+
state = {"height": int(data.state["height"][i]), "width": w,
|
| 149 |
+
"body": [list(divmod(int(c), w)) for c in cells],
|
| 150 |
+
"food": list(divmod(food, w)) if food >= 0 else None,
|
| 151 |
+
"direction": ACTIONS[int(data.state["direction"][i])]}
|
| 152 |
+
choices = data.row_choices(i)
|
| 153 |
+
f.write(json.dumps({"state": state, "question": data.questions[data.question_idx[i]],
|
| 154 |
+
"choices": choices, "target": choices[data.target[i]]}) + "\n")
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def collect_with_policy(policy_probs, n_samples: int, seed: int = 0, board_sizes=(10,), keep_prob: float = 0.2,
|
| 158 |
+
explore_eps: float = 0.0, env_cfg: dict | None = None, parallel: int = 64,
|
| 159 |
+
game_id_base: int = 0) -> DecisionData:
|
| 160 |
+
"""DAgger collection: the *student* drives (`policy_probs(states) -> (B, 4) probs`),
|
| 161 |
+
the oracle labels every kept state. Games run `parallel` at a time for batched inference."""
|
| 162 |
+
rng = np.random.default_rng(seed)
|
| 163 |
+
oracle = make_agent("oracle")
|
| 164 |
+
states, labels, groups, optimal = [], [], [], []
|
| 165 |
+
next_game = 0
|
| 166 |
+
|
| 167 |
+
def spawn():
|
| 168 |
+
nonlocal next_game
|
| 169 |
+
size = int(board_sizes[next_game % len(board_sizes)])
|
| 170 |
+
cfg = SnakeConfig.from_dict({**(env_cfg or {}), "height": size, "width": size})
|
| 171 |
+
env = SnakeEnv(cfg, seed=int(rng.integers(2**31)))
|
| 172 |
+
env.gid = game_id_base + next_game
|
| 173 |
+
next_game += 1
|
| 174 |
+
return env
|
| 175 |
+
|
| 176 |
+
envs = [spawn() for _ in range(parallel)]
|
| 177 |
+
while len(states) < n_samples:
|
| 178 |
+
cur = [e.state() for e in envs]
|
| 179 |
+
probs = policy_probs(cur)
|
| 180 |
+
for i, (env, s) in enumerate(zip(envs, cur)):
|
| 181 |
+
if rng.random() < keep_prob and len(states) < n_samples:
|
| 182 |
+
label, good, _ = oracle.analyze(s)
|
| 183 |
+
states.append(s)
|
| 184 |
+
labels.append(label)
|
| 185 |
+
groups.append(env.gid)
|
| 186 |
+
optimal.append(good)
|
| 187 |
+
if rng.random() < explore_eps:
|
| 188 |
+
safe = safe_moves(s) or list(ACTIONS)
|
| 189 |
+
action = safe[int(rng.integers(len(safe)))]
|
| 190 |
+
else:
|
| 191 |
+
action = ACTIONS[int(probs[i].argmax())]
|
| 192 |
+
env.step(action)
|
| 193 |
+
if env.done:
|
| 194 |
+
envs[i] = spawn()
|
| 195 |
+
return to_decision_data(states, labels, groups, optimal,
|
| 196 |
+
{"generator": "dagger", "keep_prob": keep_prob, "seed": seed})
|
code/environments/snake/demo/__init__.py
ADDED
|
File without changes
|
code/environments/snake/demo/server.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Snake demo: a background thread plays the game, the browser renders snapshots.
|
| 2 |
+
|
| 3 |
+
Stdlib only (http.server). The simulation runs independently of rendering, so
|
| 4 |
+
"max" speed is limited by the agent, not by the browser.
|
| 5 |
+
|
| 6 |
+
minijev snake demo --model runs/.../final.onnx
|
| 7 |
+
minijev snake play # you play with the arrow keys
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import json
|
| 12 |
+
import threading
|
| 13 |
+
import time
|
| 14 |
+
import webbrowser
|
| 15 |
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
from ..agents import AGENTS, make_agent
|
| 19 |
+
from ..env import ACTIONS, OPPOSITE, SnakeConfig, SnakeEnv
|
| 20 |
+
|
| 21 |
+
STATIC = Path(__file__).parent / "static"
|
| 22 |
+
SPEEDS = {"realtime": 8.0, "fast": 60.0, "max": None}
|
| 23 |
+
QUESTION = "Choose the next move"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class Session:
|
| 27 |
+
def __init__(self, model: str | None, board_size: int, agent: str):
|
| 28 |
+
self.lock = threading.Lock()
|
| 29 |
+
self.decider = None
|
| 30 |
+
if model:
|
| 31 |
+
from minijev.inference.runtime import MiniJEV
|
| 32 |
+
self.decider = MiniJEV.load(model, threads=1)
|
| 33 |
+
self.model_path = model
|
| 34 |
+
self.board_size = board_size
|
| 35 |
+
self.agent_name = agent if (agent != "minijev" or self.decider) else "oracle"
|
| 36 |
+
self.agent = None if self.agent_name in ("minijev", "human") else make_agent(self.agent_name)
|
| 37 |
+
self.speed = "realtime"
|
| 38 |
+
self.seed = 1
|
| 39 |
+
self.env = SnakeEnv(SnakeConfig.from_dict({"board_size": board_size}), seed=self.seed)
|
| 40 |
+
self.human_dir = self.env.direction
|
| 41 |
+
self.last = {"choice": None, "scores": {}, "confidence": None, "latency_ms": None}
|
| 42 |
+
self.lat_avg = None
|
| 43 |
+
self.games: list[int] = []
|
| 44 |
+
self.best = 0
|
| 45 |
+
self.last_end = None
|
| 46 |
+
self.steps_total = 0
|
| 47 |
+
self.rate_t, self.rate_n, self.sim_rate = time.perf_counter(), 0, 0.0
|
| 48 |
+
self.pause_until = 0.0
|
| 49 |
+
self.running = True
|
| 50 |
+
|
| 51 |
+
# ------------------------------------------------------------- control
|
| 52 |
+
def control(self, msg: dict) -> None:
|
| 53 |
+
with self.lock:
|
| 54 |
+
if msg.get("speed") in SPEEDS:
|
| 55 |
+
self.speed = msg["speed"]
|
| 56 |
+
if "agent" in msg:
|
| 57 |
+
a = msg["agent"]
|
| 58 |
+
if a == "minijev" and not self.decider:
|
| 59 |
+
pass
|
| 60 |
+
elif a in AGENTS or a in ("minijev", "human"):
|
| 61 |
+
self.agent_name = a
|
| 62 |
+
self.agent = None if a in ("minijev", "human") else make_agent(a)
|
| 63 |
+
self._reset(clear_stats=True)
|
| 64 |
+
if msg.get("key") in ACTIONS:
|
| 65 |
+
k = msg["key"]
|
| 66 |
+
if not (len(self.env.body) > 1 and k == OPPOSITE[self.env.direction]):
|
| 67 |
+
self.human_dir = k
|
| 68 |
+
if msg.get("reset"):
|
| 69 |
+
self._reset()
|
| 70 |
+
if "board_size" in msg:
|
| 71 |
+
self.board_size = int(msg["board_size"])
|
| 72 |
+
self._reset(clear_stats=True)
|
| 73 |
+
|
| 74 |
+
def _reset(self, clear_stats: bool = False):
|
| 75 |
+
self.seed += 1
|
| 76 |
+
self.env = SnakeEnv(SnakeConfig.from_dict({"board_size": self.board_size}), seed=self.seed)
|
| 77 |
+
self.human_dir = self.env.direction
|
| 78 |
+
if clear_stats:
|
| 79 |
+
self.games, self.best = [], 0
|
| 80 |
+
|
| 81 |
+
# ----------------------------------------------------------------- loop
|
| 82 |
+
def decide(self):
|
| 83 |
+
s = self.env.state()
|
| 84 |
+
t = time.perf_counter()
|
| 85 |
+
if self.agent_name == "minijev":
|
| 86 |
+
task = self.decider.task
|
| 87 |
+
d = self.decider.decide(s, QUESTION, list(task.default_choices))
|
| 88 |
+
choice, conf = task.action_of(d.choice), d.confidence
|
| 89 |
+
scores = {task.action_of(k): v for k, v in d.scores.items()}
|
| 90 |
+
elif self.agent_name == "human":
|
| 91 |
+
choice, scores, conf = self.human_dir, {a: float(a == self.human_dir) for a in ACTIONS}, None
|
| 92 |
+
else:
|
| 93 |
+
choice = self.agent.act(s)
|
| 94 |
+
scores, conf = {a: float(a == choice) for a in ACTIONS}, None
|
| 95 |
+
lat = (time.perf_counter() - t) * 1000
|
| 96 |
+
self.lat_avg = lat if self.lat_avg is None else 0.9 * self.lat_avg + 0.1 * lat
|
| 97 |
+
self.last = {"choice": choice, "scores": scores, "confidence": conf, "latency_ms": lat}
|
| 98 |
+
return choice
|
| 99 |
+
|
| 100 |
+
def run(self):
|
| 101 |
+
while self.running:
|
| 102 |
+
now = time.perf_counter()
|
| 103 |
+
if now < self.pause_until:
|
| 104 |
+
time.sleep(0.02)
|
| 105 |
+
continue
|
| 106 |
+
with self.lock:
|
| 107 |
+
choice = self.decide()
|
| 108 |
+
self.env.step(choice)
|
| 109 |
+
self.steps_total += 1
|
| 110 |
+
self.rate_n += 1
|
| 111 |
+
if self.env.done:
|
| 112 |
+
self.games.append(self.env.score)
|
| 113 |
+
self.best = max(self.best, self.env.score)
|
| 114 |
+
self.last_end = {"score": self.env.score, "reason": self.env.end_reason, "steps": self.env.steps}
|
| 115 |
+
self._reset()
|
| 116 |
+
if self.speed != "max":
|
| 117 |
+
self.pause_until = time.perf_counter() + 0.8
|
| 118 |
+
if now - self.rate_t > 0.5:
|
| 119 |
+
self.sim_rate = self.rate_n / (now - self.rate_t)
|
| 120 |
+
self.rate_t, self.rate_n = now, 0
|
| 121 |
+
speed = SPEEDS[self.speed] if self.agent_name != "human" else min(SPEEDS[self.speed] or 12, 12)
|
| 122 |
+
if speed:
|
| 123 |
+
time.sleep(max(0.0, 1.0 / speed - (time.perf_counter() - now)))
|
| 124 |
+
else:
|
| 125 |
+
time.sleep(0) # yield to the HTTP threads
|
| 126 |
+
|
| 127 |
+
def snapshot(self) -> dict:
|
| 128 |
+
with self.lock:
|
| 129 |
+
s = self.env.state()
|
| 130 |
+
g = self.games
|
| 131 |
+
return {"height": s.height, "width": s.width, "body": s.body, "food": s.food, "direction": s.direction,
|
| 132 |
+
"score": self.env.score, "step": self.env.steps, "agent": self.agent_name, "speed": self.speed,
|
| 133 |
+
"decision": self.last, "latency_avg_ms": self.lat_avg, "sim_steps_per_sec": self.sim_rate,
|
| 134 |
+
"games_played": len(g), "avg_score": sum(g) / len(g) if g else None, "best_score": self.best,
|
| 135 |
+
"last_game": self.last_end, "has_model": self.decider is not None,
|
| 136 |
+
"model": Path(self.model_path).name if self.model_path else None,
|
| 137 |
+
"agents": ["minijev"] * bool(self.decider) + list(AGENTS) + ["human"]}
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def serve(model: str | None = None, board_size: int = 10, port: int = 8765, agent: str = "minijev",
|
| 141 |
+
open_browser: bool = True):
|
| 142 |
+
session = Session(model, board_size, agent)
|
| 143 |
+
threading.Thread(target=session.run, daemon=True).start()
|
| 144 |
+
|
| 145 |
+
class Handler(BaseHTTPRequestHandler):
|
| 146 |
+
def log_message(self, *a):
|
| 147 |
+
pass
|
| 148 |
+
|
| 149 |
+
def _send(self, body: bytes, ctype: str, code: int = 200):
|
| 150 |
+
self.send_response(code)
|
| 151 |
+
self.send_header("Content-Type", ctype)
|
| 152 |
+
self.send_header("Cache-Control", "no-store")
|
| 153 |
+
self.send_header("Content-Length", str(len(body)))
|
| 154 |
+
self.end_headers()
|
| 155 |
+
self.wfile.write(body)
|
| 156 |
+
|
| 157 |
+
def do_GET(self):
|
| 158 |
+
if self.path.startswith("/api/state"):
|
| 159 |
+
self._send(json.dumps(session.snapshot()).encode(), "application/json")
|
| 160 |
+
elif self.path in ("/", "/index.html"):
|
| 161 |
+
self._send((STATIC / "index.html").read_bytes(), "text/html; charset=utf-8")
|
| 162 |
+
else:
|
| 163 |
+
self._send(b"not found", "text/plain", 404)
|
| 164 |
+
|
| 165 |
+
def do_POST(self):
|
| 166 |
+
if self.path.startswith("/api/control"):
|
| 167 |
+
n = int(self.headers.get("Content-Length", 0))
|
| 168 |
+
session.control(json.loads(self.rfile.read(n) or b"{}"))
|
| 169 |
+
self._send(b"{}", "application/json")
|
| 170 |
+
else:
|
| 171 |
+
self._send(b"not found", "text/plain", 404)
|
| 172 |
+
|
| 173 |
+
httpd = ThreadingHTTPServer(("127.0.0.1", port), Handler)
|
| 174 |
+
url = f"http://127.0.0.1:{port}/"
|
| 175 |
+
print(f"MiniJEV Snake demo on {url} (agent={session.agent_name}, model={model}) Ctrl-C to stop")
|
| 176 |
+
if open_browser:
|
| 177 |
+
threading.Timer(0.5, lambda: webbrowser.open(url)).start()
|
| 178 |
+
try:
|
| 179 |
+
httpd.serve_forever()
|
| 180 |
+
except KeyboardInterrupt:
|
| 181 |
+
pass
|
| 182 |
+
finally:
|
| 183 |
+
session.running = False
|
| 184 |
+
httpd.server_close()
|
code/environments/snake/demo/static/index.html
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!doctype html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 6 |
+
<title>MiniJEV Snake</title>
|
| 7 |
+
<style>
|
| 8 |
+
:root { --bg:#0f1115; --panel:#171a21; --line:#262b36; --text:#e6e8ee; --muted:#8b93a7;
|
| 9 |
+
--snake:#4ade80; --head:#22c55e; --food:#f43f5e; --accent:#60a5fa; --cell:#12151b; }
|
| 10 |
+
* { box-sizing: border-box; }
|
| 11 |
+
body { margin:0; background:var(--bg); color:var(--text); font:14px/1.4 system-ui, sans-serif; }
|
| 12 |
+
main { display:flex; gap:20px; padding:20px; flex-wrap:wrap; justify-content:center; }
|
| 13 |
+
canvas { background:var(--cell); border:1px solid var(--line); border-radius:8px; max-width:100%; }
|
| 14 |
+
.panel { background:var(--panel); border:1px solid var(--line); border-radius:8px; padding:16px; width:320px; }
|
| 15 |
+
h1 { font-size:16px; margin:0 0 12px; letter-spacing:.02em; }
|
| 16 |
+
h1 span { color:var(--muted); font-weight:400; }
|
| 17 |
+
.stats { display:grid; grid-template-columns: 1fr 1fr; gap:8px 16px; margin-bottom:16px; }
|
| 18 |
+
.stat .k { color:var(--muted); font-size:12px; }
|
| 19 |
+
.stat .v { font-size:18px; font-variant-numeric: tabular-nums; }
|
| 20 |
+
.bar { display:grid; grid-template-columns: 56px 1fr 52px; align-items:center; gap:8px; margin:6px 0; }
|
| 21 |
+
.bar .track { height:14px; background:var(--cell); border-radius:4px; overflow:hidden; }
|
| 22 |
+
.bar .fill { height:100%; background:var(--accent); width:0; transition: width .08s linear; }
|
| 23 |
+
.bar.chosen .fill { background:var(--snake); }
|
| 24 |
+
.bar .pct { text-align:right; font-variant-numeric: tabular-nums; }
|
| 25 |
+
.row { display:flex; gap:6px; margin:10px 0; flex-wrap:wrap; }
|
| 26 |
+
button, select { background:var(--cell); color:var(--text); border:1px solid var(--line); border-radius:6px;
|
| 27 |
+
padding:6px 10px; cursor:pointer; font:inherit; }
|
| 28 |
+
button.on { border-color:var(--accent); color:var(--accent); }
|
| 29 |
+
.muted { color:var(--muted); font-size:12px; }
|
| 30 |
+
</style>
|
| 31 |
+
</head>
|
| 32 |
+
<body>
|
| 33 |
+
<main>
|
| 34 |
+
<canvas id="board" width="560" height="560"></canvas>
|
| 35 |
+
<div class="panel">
|
| 36 |
+
<h1>MiniJEV <span>· Snake decision demo</span></h1>
|
| 37 |
+
<div class="stats">
|
| 38 |
+
<div class="stat"><div class="k">Score</div><div class="v" id="score">0</div></div>
|
| 39 |
+
<div class="stat"><div class="k">Step</div><div class="v" id="step">0</div></div>
|
| 40 |
+
<div class="stat"><div class="k">Decision latency</div><div class="v" id="lat">–</div></div>
|
| 41 |
+
<div class="stat"><div class="k">Sim steps/s · FPS</div><div class="v" id="fps">–</div></div>
|
| 42 |
+
<div class="stat"><div class="k">Games · avg</div><div class="v" id="games">0</div></div>
|
| 43 |
+
<div class="stat"><div class="k">Best</div><div class="v" id="best">0</div></div>
|
| 44 |
+
</div>
|
| 45 |
+
<div class="muted">Question: “Choose the next move” — choice: <b id="choice">–</b>,
|
| 46 |
+
confidence <b id="conf">–</b></div>
|
| 47 |
+
<div id="bars"></div>
|
| 48 |
+
<div class="row" id="speeds">
|
| 49 |
+
<button data-speed="realtime">Realtime</button>
|
| 50 |
+
<button data-speed="fast">Fast</button>
|
| 51 |
+
<button data-speed="max">Maximum</button>
|
| 52 |
+
</div>
|
| 53 |
+
<div class="row">
|
| 54 |
+
<select id="agent"></select>
|
| 55 |
+
<select id="size"><option>10</option><option>15</option><option>20</option></select>
|
| 56 |
+
<button id="reset">New game</button>
|
| 57 |
+
</div>
|
| 58 |
+
<div class="muted" id="info"></div>
|
| 59 |
+
<div class="muted" id="last"></div>
|
| 60 |
+
</div>
|
| 61 |
+
</main>
|
| 62 |
+
<script>
|
| 63 |
+
const ACTIONS = ["UP", "DOWN", "LEFT", "RIGHT"];
|
| 64 |
+
const $ = id => document.getElementById(id);
|
| 65 |
+
const cv = $("board"), ctx = cv.getContext("2d");
|
| 66 |
+
const css = n => getComputedStyle(document.documentElement).getPropertyValue(n).trim();
|
| 67 |
+
$("bars").innerHTML = ACTIONS.map(a =>
|
| 68 |
+
`<div class="bar" id="bar-${a}"><span>${a}</span><div class="track"><div class="fill"></div></div><span class="pct">–</span></div>`).join("");
|
| 69 |
+
const post = body => fetch("/api/control", {method: "POST", body: JSON.stringify(body)});
|
| 70 |
+
document.querySelectorAll("#speeds button").forEach(b => b.onclick = () => post({speed: b.dataset.speed}));
|
| 71 |
+
$("reset").onclick = () => post({reset: true});
|
| 72 |
+
$("agent").onchange = e => post({agent: e.target.value});
|
| 73 |
+
$("size").onchange = e => post({board_size: +e.target.value});
|
| 74 |
+
const KEYS = {ArrowUp: "UP", ArrowDown: "DOWN", ArrowLeft: "LEFT", ArrowRight: "RIGHT", w: "UP", s: "DOWN", a: "LEFT", d: "RIGHT"};
|
| 75 |
+
addEventListener("keydown", e => { if (KEYS[e.key]) { post({key: KEYS[e.key]}); e.preventDefault(); } });
|
| 76 |
+
|
| 77 |
+
let frames = 0, fps = 0, fpsT = performance.now(), agentsFilled = false;
|
| 78 |
+
function draw(s) {
|
| 79 |
+
const n = Math.max(s.height, s.width), cell = Math.floor(Math.min(cv.width, cv.height) / n);
|
| 80 |
+
ctx.fillStyle = css("--cell"); ctx.fillRect(0, 0, cv.width, cv.height);
|
| 81 |
+
ctx.strokeStyle = "#1b1f28";
|
| 82 |
+
for (let i = 0; i <= n; i++) {
|
| 83 |
+
ctx.beginPath(); ctx.moveTo(i * cell, 0); ctx.lineTo(i * cell, n * cell); ctx.stroke();
|
| 84 |
+
ctx.beginPath(); ctx.moveTo(0, i * cell); ctx.lineTo(n * cell, i * cell); ctx.stroke();
|
| 85 |
+
}
|
| 86 |
+
if (s.food) { ctx.fillStyle = css("--food"); ctx.beginPath();
|
| 87 |
+
ctx.arc(s.food[1] * cell + cell / 2, s.food[0] * cell + cell / 2, cell * 0.36, 0, 7); ctx.fill(); }
|
| 88 |
+
s.body.forEach(([r, c], i) => {
|
| 89 |
+
const t = i / Math.max(1, s.body.length - 1);
|
| 90 |
+
ctx.fillStyle = i === 0 ? css("--head") : `rgba(74,222,128,${1 - 0.55 * t})`;
|
| 91 |
+
const p = i === 0 ? 1 : 2;
|
| 92 |
+
ctx.fillRect(c * cell + p, r * cell + p, cell - 2 * p, cell - 2 * p);
|
| 93 |
+
});
|
| 94 |
+
}
|
| 95 |
+
function update(s) {
|
| 96 |
+
draw(s);
|
| 97 |
+
$("score").textContent = s.score; $("step").textContent = s.step;
|
| 98 |
+
$("lat").textContent = s.decision.latency_ms != null ? s.decision.latency_ms.toFixed(2) + " ms" : "–";
|
| 99 |
+
$("fps").textContent = `${Math.round(s.sim_steps_per_sec)} · ${fps}`;
|
| 100 |
+
$("games").textContent = s.games_played + (s.avg_score != null ? " · " + s.avg_score.toFixed(1) : "");
|
| 101 |
+
$("best").textContent = s.best_score;
|
| 102 |
+
$("choice").textContent = s.decision.choice || "–";
|
| 103 |
+
$("conf").textContent = s.decision.confidence != null ? (100 * s.decision.confidence).toFixed(1) + "%" : "n/a (scripted)";
|
| 104 |
+
ACTIONS.forEach(a => {
|
| 105 |
+
const p = s.decision.scores[a] ?? 0, el = $("bar-" + a);
|
| 106 |
+
el.querySelector(".fill").style.width = (100 * p) + "%";
|
| 107 |
+
el.querySelector(".pct").textContent = (100 * p).toFixed(p < 0.1 ? 1 : 0) + "%";
|
| 108 |
+
el.classList.toggle("chosen", a === s.decision.choice);
|
| 109 |
+
});
|
| 110 |
+
document.querySelectorAll("#speeds button").forEach(b => b.classList.toggle("on", b.dataset.speed === s.speed));
|
| 111 |
+
if (!agentsFilled) {
|
| 112 |
+
$("agent").innerHTML = s.agents.map(a => `<option ${a === s.agent ? "selected" : ""}>${a}</option>`).join("");
|
| 113 |
+
$("size").value = String(s.height); agentsFilled = true;
|
| 114 |
+
}
|
| 115 |
+
$("info").textContent = `agent: ${s.agent}` + (s.model ? ` · model: ${s.model}` : "") +
|
| 116 |
+
(s.agent === "human" ? " · use arrow keys / WASD" : "");
|
| 117 |
+
if (s.last_game) $("last").textContent = `last game: ${s.last_game.score} food, ${s.last_game.steps} steps, ended by ${s.last_game.reason}`;
|
| 118 |
+
}
|
| 119 |
+
async function loop() {
|
| 120 |
+
try { update(await (await fetch("/api/state")).json()); } catch (e) {}
|
| 121 |
+
frames++; const now = performance.now();
|
| 122 |
+
if (now - fpsT > 1000) { fps = Math.round(frames * 1000 / (now - fpsT)); frames = 0; fpsT = now; }
|
| 123 |
+
requestAnimationFrame(loop);
|
| 124 |
+
}
|
| 125 |
+
loop();
|
| 126 |
+
</script>
|
| 127 |
+
</body>
|
| 128 |
+
</html>
|
code/environments/snake/encoder.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""SnakeStateEncoder: the Snake board (8 channels, see task.py) -> core tokens.
|
| 2 |
+
|
| 3 |
+
A thin, Snake-specific configuration of the generic GridStateEncoder: the Snake
|
| 4 |
+
featurisation lives in `task.encode_grid`, the learnable part is generic.
|
| 5 |
+
"""
|
| 6 |
+
from minijev.encoders.grid import GridStateEncoder
|
| 7 |
+
|
| 8 |
+
from .task import N_CHANNELS
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class SnakeStateEncoder(GridStateEncoder):
|
| 12 |
+
def __init__(self, d: int, in_channels: int = N_CHANNELS, **kw):
|
| 13 |
+
super().__init__(d, in_channels=in_channels, **kw)
|
code/environments/snake/env.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Headless, deterministic Snake.
|
| 2 |
+
|
| 3 |
+
Cells are flattened indices `r * width + c`. The body is stored head-first in a
|
| 4 |
+
deque plus a bytearray occupancy grid, so a step is O(1) and thousands of games
|
| 5 |
+
run without any rendering.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
from collections import deque
|
| 10 |
+
from dataclasses import dataclass, field
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
|
| 14 |
+
ACTIONS = ("UP", "DOWN", "LEFT", "RIGHT")
|
| 15 |
+
DELTAS = {"UP": (-1, 0), "DOWN": (1, 0), "LEFT": (0, -1), "RIGHT": (0, 1)}
|
| 16 |
+
OPPOSITE = {"UP": "DOWN", "DOWN": "UP", "LEFT": "RIGHT", "RIGHT": "LEFT"}
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@dataclass
|
| 20 |
+
class RewardConfig:
|
| 21 |
+
food: float = 1.0
|
| 22 |
+
death: float = -1.0
|
| 23 |
+
step: float = 0.0 # small survival bonus; keep tiny, starvation limit prevents stalling exploits
|
| 24 |
+
win: float = 1.0
|
| 25 |
+
|
| 26 |
+
@classmethod
|
| 27 |
+
def from_dict(cls, d: dict | None) -> "RewardConfig":
|
| 28 |
+
return cls(**(d or {}))
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclass
|
| 32 |
+
class SnakeConfig:
|
| 33 |
+
height: int = 10
|
| 34 |
+
width: int = 10
|
| 35 |
+
initial_length: int = 3
|
| 36 |
+
# "die": reversing into the neck is a collision (every choice has a distinct outcome)
|
| 37 |
+
# "ignore": reversal keeps the current heading (classic arcade behaviour)
|
| 38 |
+
reverse_action: str = "die"
|
| 39 |
+
starvation_steps: int | None = None # None -> 2 * area
|
| 40 |
+
max_steps: int | None = None
|
| 41 |
+
reward: RewardConfig = field(default_factory=RewardConfig)
|
| 42 |
+
|
| 43 |
+
@classmethod
|
| 44 |
+
def from_dict(cls, d: dict | None) -> "SnakeConfig":
|
| 45 |
+
d = dict(d or {})
|
| 46 |
+
board = d.pop("board_size", None)
|
| 47 |
+
if board is not None:
|
| 48 |
+
d["height"] = d["width"] = int(board)
|
| 49 |
+
d["reward"] = RewardConfig.from_dict(d.get("reward"))
|
| 50 |
+
return cls(**d)
|
| 51 |
+
|
| 52 |
+
@property
|
| 53 |
+
def starvation_limit(self) -> int:
|
| 54 |
+
return self.starvation_steps or 2 * self.height * self.width
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@dataclass
|
| 58 |
+
class SnakeState:
|
| 59 |
+
"""Immutable-ish snapshot, the `state` MiniJEV receives for Snake."""
|
| 60 |
+
height: int
|
| 61 |
+
width: int
|
| 62 |
+
body: list[tuple[int, int]] # head first
|
| 63 |
+
food: tuple[int, int] | None
|
| 64 |
+
direction: str
|
| 65 |
+
steps_since_food: int = 0
|
| 66 |
+
|
| 67 |
+
def to_dict(self) -> dict:
|
| 68 |
+
return {"height": self.height, "width": self.width, "body": [list(p) for p in self.body],
|
| 69 |
+
"food": list(self.food) if self.food else None, "direction": self.direction,
|
| 70 |
+
"steps_since_food": self.steps_since_food}
|
| 71 |
+
|
| 72 |
+
@classmethod
|
| 73 |
+
def from_dict(cls, d: dict) -> "SnakeState":
|
| 74 |
+
return cls(d["height"], d["width"], [tuple(p) for p in d["body"]],
|
| 75 |
+
tuple(d["food"]) if d.get("food") else None, d["direction"], d.get("steps_since_food", 0))
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class SnakeEnv:
|
| 79 |
+
def __init__(self, config: SnakeConfig | None = None, seed: int | None = None):
|
| 80 |
+
self.cfg = config or SnakeConfig()
|
| 81 |
+
self.h, self.w = self.cfg.height, self.cfg.width
|
| 82 |
+
self.area = self.h * self.w
|
| 83 |
+
self.rng = np.random.default_rng(seed)
|
| 84 |
+
self.body: deque[int] = deque()
|
| 85 |
+
self.occ = bytearray(self.area)
|
| 86 |
+
self.reset()
|
| 87 |
+
|
| 88 |
+
# ------------------------------------------------------------------ core
|
| 89 |
+
def seed(self, seed: int) -> None:
|
| 90 |
+
self.rng = np.random.default_rng(seed)
|
| 91 |
+
|
| 92 |
+
def reset(self, seed: int | None = None) -> SnakeState:
|
| 93 |
+
if seed is not None:
|
| 94 |
+
self.seed(seed)
|
| 95 |
+
self.body.clear()
|
| 96 |
+
self.occ = bytearray(self.area)
|
| 97 |
+
self.direction = ACTIONS[int(self.rng.integers(4))]
|
| 98 |
+
dr, dc = DELTAS[self.direction]
|
| 99 |
+
L = min(self.cfg.initial_length, min(self.h, self.w) // 2)
|
| 100 |
+
# place head so the body (trailing behind it) fits on the board
|
| 101 |
+
r = int(self.rng.integers(L, self.h - L)) if self.h > 2 * L else self.h // 2
|
| 102 |
+
c = int(self.rng.integers(L, self.w - L)) if self.w > 2 * L else self.w // 2
|
| 103 |
+
for i in range(L):
|
| 104 |
+
cell = (r - dr * i) * self.w + (c - dc * i)
|
| 105 |
+
self.body.append(cell)
|
| 106 |
+
self.occ[cell] = 1
|
| 107 |
+
self.score = 0
|
| 108 |
+
self.steps = 0
|
| 109 |
+
self.steps_since_food = 0
|
| 110 |
+
self.done = False
|
| 111 |
+
self.end_reason: str | None = None
|
| 112 |
+
self._place_food()
|
| 113 |
+
return self.state()
|
| 114 |
+
|
| 115 |
+
def _place_food(self) -> None:
|
| 116 |
+
free = self.area - len(self.body)
|
| 117 |
+
if free <= 0:
|
| 118 |
+
self.food = -1
|
| 119 |
+
return
|
| 120 |
+
# k-th free cell, found by scanning; cheap versus rejection sampling on full boards
|
| 121 |
+
k = int(self.rng.integers(free))
|
| 122 |
+
if free > self.area // 4:
|
| 123 |
+
while True:
|
| 124 |
+
cell = int(self.rng.integers(self.area))
|
| 125 |
+
if not self.occ[cell]:
|
| 126 |
+
self.food = cell
|
| 127 |
+
return
|
| 128 |
+
for cell in range(self.area):
|
| 129 |
+
if not self.occ[cell]:
|
| 130 |
+
if k == 0:
|
| 131 |
+
self.food = cell
|
| 132 |
+
return
|
| 133 |
+
k -= 1
|
| 134 |
+
|
| 135 |
+
def step(self, action: str | int) -> tuple[float, bool]:
|
| 136 |
+
"""Returns (reward, done). Call `state()` for the observation."""
|
| 137 |
+
if self.done:
|
| 138 |
+
raise RuntimeError("step() on finished game; call reset()")
|
| 139 |
+
if not isinstance(action, str):
|
| 140 |
+
action = ACTIONS[int(action)]
|
| 141 |
+
if self.cfg.reverse_action == "ignore" and len(self.body) > 1 and action == OPPOSITE[self.direction]:
|
| 142 |
+
action = self.direction
|
| 143 |
+
rw = self.cfg.reward
|
| 144 |
+
dr, dc = DELTAS[action]
|
| 145 |
+
head = self.body[0]
|
| 146 |
+
r, c = divmod(head, self.w)
|
| 147 |
+
nr, nc = r + dr, c + dc
|
| 148 |
+
self.direction = action
|
| 149 |
+
self.steps += 1
|
| 150 |
+
self.steps_since_food += 1
|
| 151 |
+
if not (0 <= nr < self.h and 0 <= nc < self.w):
|
| 152 |
+
return self._finish("wall", rw.death)
|
| 153 |
+
cell = nr * self.w + nc
|
| 154 |
+
eating = cell == self.food
|
| 155 |
+
tail = self.body[-1]
|
| 156 |
+
if self.occ[cell] and not (cell == tail and not eating):
|
| 157 |
+
return self._finish("body", rw.death)
|
| 158 |
+
if not eating:
|
| 159 |
+
self.body.pop()
|
| 160 |
+
self.occ[tail] = 0
|
| 161 |
+
self.body.appendleft(cell)
|
| 162 |
+
self.occ[cell] = 1
|
| 163 |
+
reward = rw.step
|
| 164 |
+
if eating:
|
| 165 |
+
self.score += 1
|
| 166 |
+
self.steps_since_food = 0
|
| 167 |
+
reward += rw.food
|
| 168 |
+
if len(self.body) == self.area:
|
| 169 |
+
return self._finish("win", reward + rw.win)
|
| 170 |
+
self._place_food()
|
| 171 |
+
if self.steps_since_food >= self.cfg.starvation_limit:
|
| 172 |
+
return self._finish("starvation", rw.death)
|
| 173 |
+
if self.cfg.max_steps and self.steps >= self.cfg.max_steps:
|
| 174 |
+
self.done, self.end_reason = True, "max_steps"
|
| 175 |
+
return reward, True
|
| 176 |
+
return reward, False
|
| 177 |
+
|
| 178 |
+
def _finish(self, reason: str, reward: float) -> tuple[float, bool]:
|
| 179 |
+
self.done, self.end_reason = True, reason
|
| 180 |
+
return reward, True
|
| 181 |
+
|
| 182 |
+
# --------------------------------------------------------------- views
|
| 183 |
+
def state(self) -> SnakeState:
|
| 184 |
+
w = self.w
|
| 185 |
+
return SnakeState(self.h, self.w, [divmod(b, w) for b in self.body],
|
| 186 |
+
divmod(self.food, w) if self.food >= 0 else None,
|
| 187 |
+
self.direction, self.steps_since_food)
|
| 188 |
+
|
| 189 |
+
def render_ascii(self) -> str:
|
| 190 |
+
grid = [["." for _ in range(self.w)] for _ in range(self.h)]
|
| 191 |
+
for i, b in enumerate(self.body):
|
| 192 |
+
r, c = divmod(b, self.w)
|
| 193 |
+
grid[r][c] = "H" if i == 0 else "o"
|
| 194 |
+
if self.food >= 0:
|
| 195 |
+
r, c = divmod(self.food, self.w)
|
| 196 |
+
grid[r][c] = "*"
|
| 197 |
+
return "\n".join("".join(row) for row in grid)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class VectorSnakeEnv:
|
| 201 |
+
"""N independent games stepped together (auto-reset); used for batched
|
| 202 |
+
inference in RL/evaluation. Deterministic given `seed`."""
|
| 203 |
+
|
| 204 |
+
def __init__(self, n: int, config: SnakeConfig | None = None, seed: int = 0):
|
| 205 |
+
self.envs = [SnakeEnv(config, seed=seed + i) for i in range(n)]
|
| 206 |
+
self.next_seed = seed + n
|
| 207 |
+
self.n = n
|
| 208 |
+
|
| 209 |
+
def states(self) -> list[SnakeState]:
|
| 210 |
+
return [e.state() for e in self.envs]
|
| 211 |
+
|
| 212 |
+
def step(self, actions) -> tuple[np.ndarray, np.ndarray, list[dict]]:
|
| 213 |
+
rewards = np.zeros(self.n, dtype=np.float32)
|
| 214 |
+
dones = np.zeros(self.n, dtype=bool)
|
| 215 |
+
infos: list[dict] = [{} for _ in range(self.n)]
|
| 216 |
+
for i, (env, a) in enumerate(zip(self.envs, actions)):
|
| 217 |
+
rewards[i], dones[i] = env.step(a)
|
| 218 |
+
if dones[i]:
|
| 219 |
+
infos[i] = {"score": env.score, "steps": env.steps, "end_reason": env.end_reason}
|
| 220 |
+
env.reset(seed=self.next_seed)
|
| 221 |
+
self.next_seed += 1
|
| 222 |
+
return rewards, dones, infos
|
code/environments/snake/evaluate.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Play full Snake games with any policy and report game-level metrics."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import time
|
| 5 |
+
from typing import Callable, Sequence
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
from .agents import Agent, make_agent, safe_moves
|
| 10 |
+
from .env import ACTIONS, SnakeConfig, SnakeEnv, SnakeState
|
| 11 |
+
|
| 12 |
+
BatchPolicy = Callable[[Sequence[SnakeState]], Sequence[str]]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def agent_policy(agent: Agent) -> BatchPolicy:
|
| 16 |
+
return lambda states: [agent.act(s) for s in states]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def model_policy(decider, question: str = "Choose the next move", choices=None) -> BatchPolicy:
|
| 20 |
+
"""Greedy MiniJEV policy; choices default to the model's own labels (legacy "UP" or "move up")."""
|
| 21 |
+
task = decider.task
|
| 22 |
+
choices = list(choices) if choices is not None else list(task.default_choices)
|
| 23 |
+
actions = [task.action_of(c) for c in choices]
|
| 24 |
+
|
| 25 |
+
def policy(states):
|
| 26 |
+
probs = decider.probs(states, question, choices)
|
| 27 |
+
return [actions[i] for i in probs.argmax(1)]
|
| 28 |
+
return policy
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def play_games(policy: BatchPolicy, n_games: int = 100, env_cfg: dict | None = None, seed: int = 12345,
|
| 32 |
+
parallel: int = 64, max_decisions: int | None = None) -> dict:
|
| 33 |
+
"""Run `n_games` complete games (`parallel` at a time, batched decisions).
|
| 34 |
+
|
| 35 |
+
Game seeds are fixed (seed + i), so all agents are compared on identical games.
|
| 36 |
+
"""
|
| 37 |
+
cfg = SnakeConfig.from_dict(env_cfg)
|
| 38 |
+
results = []
|
| 39 |
+
next_game = 0
|
| 40 |
+
active: list[SnakeEnv] = []
|
| 41 |
+
fatal = decisions = 0
|
| 42 |
+
t0 = time.perf_counter()
|
| 43 |
+
policy_time = 0.0
|
| 44 |
+
|
| 45 |
+
def spawn():
|
| 46 |
+
nonlocal next_game
|
| 47 |
+
env = SnakeEnv(cfg, seed=seed + next_game)
|
| 48 |
+
next_game += 1
|
| 49 |
+
return env
|
| 50 |
+
|
| 51 |
+
while next_game < min(parallel, n_games):
|
| 52 |
+
active.append(spawn())
|
| 53 |
+
while active:
|
| 54 |
+
states = [e.state() for e in active]
|
| 55 |
+
tp = time.perf_counter()
|
| 56 |
+
actions = policy(states)
|
| 57 |
+
policy_time += time.perf_counter() - tp
|
| 58 |
+
still = []
|
| 59 |
+
for env, s, a in zip(active, states, actions):
|
| 60 |
+
decisions += 1
|
| 61 |
+
if a not in safe_moves(s):
|
| 62 |
+
fatal += 1
|
| 63 |
+
env.step(a)
|
| 64 |
+
if env.done:
|
| 65 |
+
results.append({"score": env.score, "steps": env.steps, "end": env.end_reason})
|
| 66 |
+
if next_game < n_games:
|
| 67 |
+
still.append(spawn())
|
| 68 |
+
else:
|
| 69 |
+
still.append(env)
|
| 70 |
+
active = still
|
| 71 |
+
if max_decisions and decisions >= max_decisions:
|
| 72 |
+
break
|
| 73 |
+
wall = time.perf_counter() - t0
|
| 74 |
+
scores = np.array([r["score"] for r in results]) if results else np.zeros(1)
|
| 75 |
+
steps = np.array([r["steps"] for r in results]) if results else np.zeros(1)
|
| 76 |
+
ends: dict[str, int] = {}
|
| 77 |
+
for r in results:
|
| 78 |
+
ends[r["end"]] = ends.get(r["end"], 0) + 1
|
| 79 |
+
n = max(1, len(results))
|
| 80 |
+
return {
|
| 81 |
+
"games": len(results),
|
| 82 |
+
"board": f"{cfg.height}x{cfg.width}",
|
| 83 |
+
"avg_score": float(scores.mean()), "median_score": float(np.median(scores)),
|
| 84 |
+
"max_score": int(scores.max()), "min_score": int(scores.min()),
|
| 85 |
+
"avg_survival_steps": float(steps.mean()), "food_collected": int(scores.sum()),
|
| 86 |
+
"max_possible_score": cfg.height * cfg.width - cfg.initial_length,
|
| 87 |
+
"win_rate": ends.get("win", 0) / n,
|
| 88 |
+
"death_rate": (ends.get("wall", 0) + ends.get("body", 0)) / n, # collisions
|
| 89 |
+
"starvation_rate": ends.get("starvation", 0) / n,
|
| 90 |
+
"end_reasons": ends,
|
| 91 |
+
"decisions": decisions,
|
| 92 |
+
"fatal_move_rate": fatal / max(1, decisions), # chose a move that dies immediately
|
| 93 |
+
"policy_seconds": round(policy_time, 3),
|
| 94 |
+
"wall_seconds": round(wall, 3),
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def baseline_suite(n_games: int = 100, env_cfg: dict | None = None, seed: int = 12345,
|
| 99 |
+
agents: Sequence[str] = ("random", "greedy", "bfs", "survival", "oracle")) -> dict:
|
| 100 |
+
return {name: play_games(agent_policy(make_agent(name, seed)), n_games, env_cfg, seed, parallel=1)
|
| 101 |
+
for name in agents}
|
code/environments/snake/rl.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PPO fine-tuning of a supervised MiniJEV Snake policy (Phase 2).
|
| 2 |
+
|
| 3 |
+
Rollouts: `n_envs` games stepped together, batched inference, sampled actions.
|
| 4 |
+
Reward comes from `env.reward` in the config (food +, death -, tiny/zero per
|
| 5 |
+
step). The value head is warmed up first (it was never trained by behaviour
|
| 6 |
+
cloning), and a KL penalty to the frozen supervised policy keeps early updates
|
| 7 |
+
from destroying what imitation learned. Resumable from `rl_last.pt`.
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import copy
|
| 12 |
+
import json
|
| 13 |
+
import time
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
import torch
|
| 18 |
+
|
| 19 |
+
from minijev.calibration.metrics import calibration_report, fit_temperature
|
| 20 |
+
from minijev.datasets.batching import BatchEncoder
|
| 21 |
+
from minijev.datasets.decision_data import DecisionData
|
| 22 |
+
from minijev.inference.runtime import TorchDecider
|
| 23 |
+
from minijev.runs import RunLogger, environment_info
|
| 24 |
+
from minijev.tokenizer import encode_batch
|
| 25 |
+
from minijev.training.ppo import gae, ppo_update
|
| 26 |
+
from minijev.training.supervised import make_model, predict_logits
|
| 27 |
+
|
| 28 |
+
from .env import SnakeConfig, VectorSnakeEnv
|
| 29 |
+
from .evaluate import model_policy, play_games
|
| 30 |
+
from .task import SnakeTask
|
| 31 |
+
|
| 32 |
+
QUESTION = SnakeTask.default_question
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def train_ppo(cfg: dict, checkpoint: str, run_dir: str | None = None, resume: bool = False) -> dict:
|
| 36 |
+
rl = cfg.get("rl", {})
|
| 37 |
+
seed = int(cfg.get("seed", 0))
|
| 38 |
+
torch.manual_seed(seed)
|
| 39 |
+
torch.set_num_threads(int(rl.get("threads", 8)))
|
| 40 |
+
ck = torch.load(checkpoint, map_location="cpu", weights_only=False)
|
| 41 |
+
base_cfg = ck["config"]
|
| 42 |
+
task = SnakeTask(base_cfg.get("task", {})) # the checkpoint decides the choice labels
|
| 43 |
+
model = make_model(base_cfg, task)
|
| 44 |
+
model.load_state_dict(ck["model"])
|
| 45 |
+
model.log_temperature.zero_()
|
| 46 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 47 |
+
model.to(device)
|
| 48 |
+
ref = copy.deepcopy(model).eval()
|
| 49 |
+
for p in ref.parameters():
|
| 50 |
+
p.requires_grad_(False)
|
| 51 |
+
|
| 52 |
+
run_dir = Path(run_dir or f"runs/{cfg.get('name', 'snake')}-ppo")
|
| 53 |
+
log = RunLogger(run_dir, {**cfg, "init_checkpoint": checkpoint}, resume=resume)
|
| 54 |
+
opt = torch.optim.AdamW(model.parameters(), lr=rl.get("lr", 1e-4), weight_decay=0.0)
|
| 55 |
+
env_cfg = SnakeConfig.from_dict(cfg.get("env", {}))
|
| 56 |
+
n_envs, T = int(rl.get("n_envs", 64)), int(rl.get("rollout", 128))
|
| 57 |
+
total_updates = int(rl.get("total_env_steps", 1_000_000)) // (n_envs * T)
|
| 58 |
+
start, best = 0, -1.0
|
| 59 |
+
last_ck = run_dir / "checkpoints" / "rl_last.pt"
|
| 60 |
+
if resume and last_ck.exists():
|
| 61 |
+
st = torch.load(last_ck, weights_only=False)
|
| 62 |
+
model.load_state_dict(st["model"])
|
| 63 |
+
opt.load_state_dict(st["optimizer"])
|
| 64 |
+
start, best = st["update"], st["best"]
|
| 65 |
+
print(f"[rl] resumed at update {start}")
|
| 66 |
+
envs = VectorSnakeEnv(n_envs, env_cfg, seed=seed * 7919 + start * n_envs)
|
| 67 |
+
mcfg = base_cfg["model"]
|
| 68 |
+
q = torch.as_tensor(encode_batch([QUESTION], mcfg.get("max_question_len", 32)), device=device).repeat(n_envs, 1)
|
| 69 |
+
c = torch.as_tensor(encode_batch(list(task.default_choices), mcfg.get("max_choice_len", 16)),
|
| 70 |
+
device=device)[None].repeat(n_envs, 1, 1)
|
| 71 |
+
gamma, lam = rl.get("gamma", 0.99), rl.get("gae_lambda", 0.95)
|
| 72 |
+
warm = int(rl.get("value_warmup_updates", 5))
|
| 73 |
+
eval_every = int(rl.get("eval_every", 10))
|
| 74 |
+
log.write_json("env.json", {"env": environment_info(), "updates": total_updates, "n_envs": n_envs, "rollout": T})
|
| 75 |
+
ep_scores: list[int] = []
|
| 76 |
+
t0 = time.time()
|
| 77 |
+
print(f"[rl] PPO: {total_updates} updates x {n_envs * T} steps, reward={cfg.get('env', {}).get('reward')}")
|
| 78 |
+
for upd in range(start, total_updates):
|
| 79 |
+
obs, acts, logps, vals, rews, dns = [], [], [], [], [], []
|
| 80 |
+
model.eval()
|
| 81 |
+
for _ in range(T):
|
| 82 |
+
x = torch.as_tensor(task.encode_states(envs.states())["state_grid"], device=device)
|
| 83 |
+
with torch.no_grad():
|
| 84 |
+
out = model({"state_grid": x}, q, c)
|
| 85 |
+
dist = torch.distributions.Categorical(logits=out["logits"])
|
| 86 |
+
a = dist.sample()
|
| 87 |
+
r, d, infos = envs.step(a.cpu().tolist())
|
| 88 |
+
ep_scores += [i["score"] for i in infos if i]
|
| 89 |
+
obs.append(x)
|
| 90 |
+
acts.append(a)
|
| 91 |
+
logps.append(dist.log_prob(a))
|
| 92 |
+
vals.append(out["value"].cpu())
|
| 93 |
+
rews.append(r)
|
| 94 |
+
dns.append(d.astype(np.float32))
|
| 95 |
+
with torch.no_grad():
|
| 96 |
+
x = torch.as_tensor(task.encode_states(envs.states())["state_grid"], device=device)
|
| 97 |
+
last_v = model({"state_grid": x}, q, c)["value"].cpu().numpy()
|
| 98 |
+
V = torch.stack(vals).numpy()
|
| 99 |
+
adv, ret = gae(np.stack(rews), V, np.stack(dns), last_v, gamma, lam)
|
| 100 |
+
adv_t = torch.as_tensor(adv.reshape(-1), device=device)
|
| 101 |
+
data = {"state": {"state_grid": torch.cat(obs)}, "question_ids": q.repeat(T, 1),
|
| 102 |
+
"choice_ids": c.repeat(T, 1, 1), "actions": torch.cat(acts), "old_logp": torch.cat(logps),
|
| 103 |
+
"adv": (adv_t - adv_t.mean()) / (adv_t.std() + 1e-8), "ret": torch.as_tensor(ret.reshape(-1), device=device)}
|
| 104 |
+
stats = ppo_update(model, opt, data, rl, ref_model=ref, policy_coef=0.0 if upd < warm else 1.0)
|
| 105 |
+
recent = ep_scores[-200:]
|
| 106 |
+
log.log(upd + 1, env_steps=(upd + 1) * n_envs * T, train_avg_score=float(np.mean(recent)) if recent else 0.0,
|
| 107 |
+
episodes=len(ep_scores), **{k: round(v, 5) for k, v in stats.items()})
|
| 108 |
+
print(f" update {upd + 1}/{total_updates} | sampled-policy avg score {np.mean(recent) if recent else 0:.1f} "
|
| 109 |
+
f"| entropy {stats['entropy']:.3f} kl_ref {stats['kl_ref']:.4f} vf {stats['vf']:.4f} "
|
| 110 |
+
f"| {time.time() - t0:.0f}s", flush=True)
|
| 111 |
+
if (upd + 1) % eval_every == 0 or upd + 1 == total_updates:
|
| 112 |
+
dec = TorchDecider(model=model, cfg=base_cfg, device=str(device))
|
| 113 |
+
g = play_games(model_policy(dec), int(rl.get("eval_games", 100)), cfg.get("env", {}), seed=777)
|
| 114 |
+
log.log(upd + 1, eval_avg_score=g["avg_score"], eval_fatal=g["fatal_move_rate"])
|
| 115 |
+
print(f" [eval] greedy avg score {g['avg_score']:.2f} median {g['median_score']} "
|
| 116 |
+
f"fatal-move {g['fatal_move_rate']:.4%}", flush=True)
|
| 117 |
+
if g["avg_score"] > best:
|
| 118 |
+
best = g["avg_score"]
|
| 119 |
+
model.to(device) # TorchDecider may have moved it
|
| 120 |
+
torch.save({"model": model.state_dict(), "config": base_cfg, "update": upd + 1, "eval": g},
|
| 121 |
+
run_dir / "checkpoints" / "rl_best.pt")
|
| 122 |
+
torch.save({"model": model.state_dict(), "optimizer": opt.state_dict(), "update": upd + 1,
|
| 123 |
+
"best": best}, last_ck)
|
| 124 |
+
return finalize_rl(cfg, base_cfg, run_dir, log)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def finalize_rl(cfg, base_cfg, run_dir: Path, log) -> dict:
|
| 128 |
+
"""Re-calibrate the best RL policy on the validation split and evaluate it."""
|
| 129 |
+
task = SnakeTask(base_cfg.get("task", {}))
|
| 130 |
+
best = torch.load(run_dir / "checkpoints" / "rl_best.pt", weights_only=False)
|
| 131 |
+
model = make_model(base_cfg, task)
|
| 132 |
+
model.load_state_dict(best["model"])
|
| 133 |
+
data_dir = Path(base_cfg["data"]["dir"])
|
| 134 |
+
mc = base_cfg["model"]
|
| 135 |
+
kw = dict(max_question_len=mc.get("max_question_len", 32), max_choice_len=mc.get("max_choice_len", 16))
|
| 136 |
+
val = BatchEncoder(DecisionData.load(data_dir / "val.npz"), task, **kw)
|
| 137 |
+
test = BatchEncoder(DecisionData.load(data_dir / "test.npz"), task, **kw)
|
| 138 |
+
vl, vt = predict_logits(model, val, "cpu")
|
| 139 |
+
tl, tt = predict_logits(model, test, "cpu")
|
| 140 |
+
T = fit_temperature(vl, vt)
|
| 141 |
+
model.log_temperature.fill_(float(np.log(T)))
|
| 142 |
+
acc_ok = test.data.soft > 0 if test.data.soft is not None else None
|
| 143 |
+
rep = calibration_report(tl, tt, T, acceptable=acc_ok)
|
| 144 |
+
torch.save({"model": model.state_dict(), "config": base_cfg, "temperature": T}, run_dir / "checkpoints" / "final.pt")
|
| 145 |
+
games = play_games(model_policy(TorchDecider(run_dir / "checkpoints" / "final.pt", threads=4)),
|
| 146 |
+
cfg.get("eval", {}).get("games", 200), cfg.get("env", {}))
|
| 147 |
+
(run_dir / "games.json").write_text(json.dumps(games, indent=2))
|
| 148 |
+
summary = {"params": model.num_parameters(), "temperature": T, "test_calibrated": rep,
|
| 149 |
+
"test_raw": calibration_report(tl, tt, 1.0, acceptable=acc_ok), "games": games,
|
| 150 |
+
"final_checkpoint": str(run_dir / "checkpoints" / "final.pt")}
|
| 151 |
+
log.write_json("summary.json", summary)
|
| 152 |
+
log.close()
|
| 153 |
+
print(f"[rl] final: avg score {games['avg_score']:.2f} | oracle-agreement {rep['accuracy']:.4f} "
|
| 154 |
+
f"| ECE vs oracle {rep['ece']:.4f} (T={T:.3f})")
|
| 155 |
+
return summary
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
__all__ = ["train_ppo"]
|
code/environments/snake/task.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Snake as a MiniJEV task: SnakeState -> multi-channel board image.
|
| 2 |
+
|
| 3 |
+
Channels (board padded by a 1-cell wall border; smaller boards in a batch are
|
| 4 |
+
padded with more wall, which is semantically exact):
|
| 5 |
+
|
| 6 |
+
0 wall 1 head 2 body (excl. head) 3 tail 4 food
|
| 7 |
+
5 time-until-free: (L - i) / area for body segment i (head=0)
|
| 8 |
+
6 row offset from the head (r - r_head) / max(H, W)
|
| 9 |
+
7 col offset from the head (c - c_head) / max(H, W)
|
| 10 |
+
|
| 11 |
+
Channel 5 lets the model reason about which cells will open up as the snake
|
| 12 |
+
moves - the same information the oracle's time-aware search uses. Channels 6-7
|
| 13 |
+
make every cell egocentric ("the food is 3 up, 2 left"), which removes the
|
| 14 |
+
long learning plateau of discovering relative geometry from absolute positions.
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
from typing import Sequence
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
from minijev.tasks import Task, ragged_pack, ragged_take
|
| 23 |
+
|
| 24 |
+
from .env import ACTIONS, SnakeState
|
| 25 |
+
|
| 26 |
+
N_CHANNELS = 8
|
| 27 |
+
DIRS = {a: i for i, a in enumerate(ACTIONS)}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
SEMANTIC_CHOICES = {"UP": "move up", "DOWN": "move down", "LEFT": "move left", "RIGHT": "move right"}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class SnakeTask(Task):
|
| 34 |
+
"""task.choice_style: "semantic" -> choices "move up/down/left/right" (v2 models);
|
| 35 |
+
"legacy" (default, what pre-v2 checkpoints were trained with) -> "UP/DOWN/LEFT/RIGHT"."""
|
| 36 |
+
|
| 37 |
+
name = "snake"
|
| 38 |
+
state_encoder = "grid"
|
| 39 |
+
default_question = "Choose the next move"
|
| 40 |
+
|
| 41 |
+
@property
|
| 42 |
+
def choice_alias(self) -> dict[str, str]:
|
| 43 |
+
return SEMANTIC_CHOICES if self.cfg.get("choice_style", "legacy") == "semantic" else {}
|
| 44 |
+
|
| 45 |
+
@property
|
| 46 |
+
def default_choices(self) -> tuple[str, ...]:
|
| 47 |
+
return tuple(self.model_label(a) for a in ACTIONS)
|
| 48 |
+
|
| 49 |
+
def encoder_class(self):
|
| 50 |
+
from .encoder import SnakeStateEncoder
|
| 51 |
+
return SnakeStateEncoder
|
| 52 |
+
|
| 53 |
+
def encoder_config(self) -> dict:
|
| 54 |
+
return {"in_channels": N_CHANNELS}
|
| 55 |
+
|
| 56 |
+
def states_to_arrays(self, states: Sequence[SnakeState]) -> dict[str, np.ndarray]:
|
| 57 |
+
bodies = [[r * s.width + c for r, c in s.body] for s in states]
|
| 58 |
+
flat, offsets = ragged_pack(bodies, np.int16)
|
| 59 |
+
return {
|
| 60 |
+
"body": flat,
|
| 61 |
+
"body_offsets": offsets,
|
| 62 |
+
"food": np.array([s.food[0] * s.width + s.food[1] if s.food else -1 for s in states], np.int16),
|
| 63 |
+
"height": np.array([s.height for s in states], np.uint8),
|
| 64 |
+
"width": np.array([s.width for s in states], np.uint8),
|
| 65 |
+
"direction": np.array([DIRS[s.direction] for s in states], np.uint8),
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
def example_states(self, n=4, seed=0):
|
| 69 |
+
from .agents import OracleAgent
|
| 70 |
+
from .env import SnakeConfig, SnakeEnv
|
| 71 |
+
|
| 72 |
+
states, oracle = [], OracleAgent()
|
| 73 |
+
env = SnakeEnv(SnakeConfig.from_dict({"board_size": self.cfg.get("board_size", 10)}), seed=seed)
|
| 74 |
+
while len(states) < n:
|
| 75 |
+
states.append(env.state())
|
| 76 |
+
for _ in range(7): # spread samples along the game
|
| 77 |
+
env.step(oracle.act(env.state()))
|
| 78 |
+
if env.done:
|
| 79 |
+
env.reset()
|
| 80 |
+
return states
|
| 81 |
+
|
| 82 |
+
def encode_arrays(self, arrays, idx):
|
| 83 |
+
return {"state_grid": encode_grid(arrays, np.asarray(idx))}
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def encode_grid(arrays: dict[str, np.ndarray], idx: np.ndarray) -> np.ndarray:
|
| 87 |
+
B = len(idx)
|
| 88 |
+
hs = arrays["height"][idx].astype(np.int64)
|
| 89 |
+
ws = arrays["width"][idx].astype(np.int64)
|
| 90 |
+
H, W = int(hs.max()) + 2, int(ws.max()) + 2
|
| 91 |
+
x = np.zeros((B, N_CHANNELS, H, W), dtype=np.float32)
|
| 92 |
+
x[:, 0] = 1.0
|
| 93 |
+
for h, w in set(zip(hs.tolist(), ws.tolist())):
|
| 94 |
+
sel = np.nonzero((hs == h) & (ws == w))[0]
|
| 95 |
+
x[sel, 0, 1:h + 1, 1:w + 1] = 0.0
|
| 96 |
+
|
| 97 |
+
cells, lengths = ragged_take(arrays["body"], arrays["body_offsets"], idx)
|
| 98 |
+
cells = cells.astype(np.int64)
|
| 99 |
+
sample = np.repeat(np.arange(B), lengths)
|
| 100 |
+
pos = np.arange(len(cells)) - np.repeat(np.cumsum(lengths) - lengths, lengths) # index from head
|
| 101 |
+
Ls = np.repeat(lengths, lengths)
|
| 102 |
+
w_s = ws[sample]
|
| 103 |
+
r, c = cells // w_s + 1, cells % w_s + 1
|
| 104 |
+
head = pos == 0
|
| 105 |
+
x[sample[head], 1, r[head], c[head]] = 1.0
|
| 106 |
+
x[sample[~head], 2, r[~head], c[~head]] = 1.0
|
| 107 |
+
tail = pos == Ls - 1
|
| 108 |
+
x[sample[tail], 3, r[tail], c[tail]] = 1.0
|
| 109 |
+
x[sample, 5, r, c] = (Ls - pos) / (hs[sample] * w_s)
|
| 110 |
+
|
| 111 |
+
hr, hc = np.zeros(B, np.int64), np.zeros(B, np.int64)
|
| 112 |
+
hr[sample[head]], hc[sample[head]] = r[head], c[head]
|
| 113 |
+
scale = np.maximum(hs, ws).astype(np.float32)[:, None, None]
|
| 114 |
+
x[:, 6] = (np.arange(H)[None, :, None] - hr[:, None, None]) / scale
|
| 115 |
+
x[:, 7] = (np.arange(W)[None, None, :] - hc[:, None, None]) / scale
|
| 116 |
+
|
| 117 |
+
food = arrays["food"][idx].astype(np.int64)
|
| 118 |
+
has = np.nonzero(food >= 0)[0]
|
| 119 |
+
x[has, 4, food[has] // ws[has] + 1, food[has] % ws[has] + 1] = 1.0
|
| 120 |
+
return x
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def make_task(cfg: dict) -> SnakeTask:
|
| 124 |
+
return SnakeTask(cfg)
|
code/minijev/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""MiniJEV: a tiny, general decision model (state + question + choices -> calibrated choice)."""
|
| 2 |
+
from minijev.types import BooleanDecision, Decision, DecisionRequest
|
| 3 |
+
|
| 4 |
+
__version__ = "0.1.0"
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def __getattr__(name): # lazy: `import minijev` must not pull in torch/onnxruntime
|
| 8 |
+
if name == "MiniJEV":
|
| 9 |
+
from minijev.inference.runtime import MiniJEV
|
| 10 |
+
return MiniJEV
|
| 11 |
+
raise AttributeError(name)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
__all__ = ["MiniJEV", "BooleanDecision", "Decision", "DecisionRequest", "__version__"]
|
code/minijev/__pycache__/__init__.cpython-314.pyc
ADDED
|
Binary file (708 Bytes). View file
|
|
|
code/minijev/__pycache__/device.cpython-314.pyc
ADDED
|
Binary file (5.89 kB). View file
|
|
|
code/minijev/__pycache__/hub.cpython-314.pyc
ADDED
|
Binary file (7.41 kB). View file
|
|
|
code/minijev/__pycache__/keys.cpython-314.pyc
ADDED
|
Binary file (404 Bytes). View file
|
|
|
code/minijev/__pycache__/runs.cpython-314.pyc
ADDED
|
Binary file (8.65 kB). View file
|
|
|
code/minijev/__pycache__/tasks.cpython-314.pyc
ADDED
|
Binary file (8.1 kB). View file
|
|
|
code/minijev/__pycache__/text_task_utils.cpython-314.pyc
ADDED
|
Binary file (1.39 kB). View file
|
|
|
code/minijev/__pycache__/tokenizer.cpython-314.pyc
ADDED
|
Binary file (3.39 kB). View file
|
|
|
code/minijev/__pycache__/tokenizers.cpython-314.pyc
ADDED
|
Binary file (6.83 kB). View file
|
|
|
code/minijev/__pycache__/types.cpython-314.pyc
ADDED
|
Binary file (4.2 kB). View file
|
|
|
code/minijev/benchmark/__init__.py
ADDED
|
File without changes
|
code/minijev/benchmark/perf.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Inference performance: latency percentiles, max throughput, paced-rate CPU/RAM cost.
|
| 2 |
+
|
| 3 |
+
Latency is end-to-end `decide()` (state encoding + tokenisation + model), the
|
| 4 |
+
number an embedding application actually pays. Max throughput is measured
|
| 5 |
+
unthrottled; the paced tests (1..1000 decisions/s) show what a given decision
|
| 6 |
+
rate costs in CPU, which is what matters when MiniJEV lives inside other software.
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import os
|
| 11 |
+
import time
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
import psutil
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _pct(xs: list[float]) -> dict:
|
| 19 |
+
a = np.array(xs) * 1000
|
| 20 |
+
return {"p50_ms": round(float(np.percentile(a, 50)), 4), "p95_ms": round(float(np.percentile(a, 95)), 4),
|
| 21 |
+
"p99_ms": round(float(np.percentile(a, 99)), 4), "mean_ms": round(float(a.mean()), 4)}
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def latency(decider, states, question, choices, n: int = 2000, warmup: int = 100) -> dict:
|
| 25 |
+
for i in range(warmup):
|
| 26 |
+
decider.decide(states[i % len(states)], question, choices)
|
| 27 |
+
xs = []
|
| 28 |
+
for i in range(n):
|
| 29 |
+
t = time.perf_counter()
|
| 30 |
+
decider.decide(states[i % len(states)], question, choices)
|
| 31 |
+
xs.append(time.perf_counter() - t)
|
| 32 |
+
# model-only latency (pre-encoded input), to separate pre-processing cost
|
| 33 |
+
enc = [decider.encode([s]) for s in states[:64]]
|
| 34 |
+
ys = []
|
| 35 |
+
for i in range(n):
|
| 36 |
+
t = time.perf_counter()
|
| 37 |
+
decider.probs(None, question, choices, encoded=enc[i % len(enc)])
|
| 38 |
+
ys.append(time.perf_counter() - t)
|
| 39 |
+
return {"end_to_end": _pct(xs), "model_only": _pct(ys),
|
| 40 |
+
"max_decisions_per_sec_batch1": round(1.0 / float(np.mean(xs)), 1)}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def batched_throughput(decider, states, question, choices, batch: int = 64, seconds: float = 3.0) -> dict:
|
| 44 |
+
enc = decider.encode(states[:batch])
|
| 45 |
+
decider.probs(None, question, choices, encoded=enc)
|
| 46 |
+
n, t0 = 0, time.perf_counter()
|
| 47 |
+
while time.perf_counter() - t0 < seconds:
|
| 48 |
+
decider.probs(None, question, choices, encoded=enc)
|
| 49 |
+
n += len(enc)
|
| 50 |
+
return {"batch": len(enc), "decisions_per_sec": round(n / (time.perf_counter() - t0), 1)}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def paced(decider, states, question, choices, rate: float, seconds: float = 3.0) -> dict:
|
| 54 |
+
"""Issue decisions at a fixed rate; measure achieved rate, latency and process CPU."""
|
| 55 |
+
proc = psutil.Process(os.getpid())
|
| 56 |
+
period = 1.0 / rate
|
| 57 |
+
n_target = max(3, int(rate * seconds))
|
| 58 |
+
lat = []
|
| 59 |
+
proc.cpu_percent(None)
|
| 60 |
+
cpu_t0 = proc.cpu_times()
|
| 61 |
+
t0 = time.perf_counter()
|
| 62 |
+
next_t = t0
|
| 63 |
+
for i in range(n_target):
|
| 64 |
+
now = time.perf_counter()
|
| 65 |
+
if next_t > now:
|
| 66 |
+
time.sleep(next_t - now)
|
| 67 |
+
t = time.perf_counter()
|
| 68 |
+
decider.decide(states[i % len(states)], question, choices)
|
| 69 |
+
lat.append(time.perf_counter() - t)
|
| 70 |
+
next_t += period
|
| 71 |
+
wall = max(time.perf_counter() - t0, n_target * period) # a paced run lasts n_target periods
|
| 72 |
+
cpu_t1 = proc.cpu_times()
|
| 73 |
+
cpu_s = (cpu_t1.user - cpu_t0.user) + (cpu_t1.system - cpu_t0.system)
|
| 74 |
+
achieved = n_target / wall
|
| 75 |
+
return {"target_per_sec": rate, "achieved_per_sec": round(achieved, 1),
|
| 76 |
+
"sustained": achieved >= 0.95 * rate, **_pct(lat),
|
| 77 |
+
"cpu_percent_of_one_core": round(100 * cpu_s / wall, 1),
|
| 78 |
+
"rss_mb": round(proc.memory_info().rss / 2**20, 1)}
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def benchmark_decider(path: str | Path, task=None, threads: int = 1, rates=(1, 10, 100, 500, 1000),
|
| 82 |
+
n_latency: int = 2000, quick: bool = False) -> dict:
|
| 83 |
+
from minijev.inference.runtime import MiniJEV
|
| 84 |
+
|
| 85 |
+
proc = psutil.Process(os.getpid())
|
| 86 |
+
rss0 = proc.memory_info().rss
|
| 87 |
+
dec = MiniJEV.load(path, threads=threads)
|
| 88 |
+
rss1 = proc.memory_info().rss
|
| 89 |
+
task = task or dec.task
|
| 90 |
+
states = task.example_states(256, seed=3)
|
| 91 |
+
q, ch = task.default_question, list(task.default_choices)
|
| 92 |
+
res = {"model": str(path), "file_size_mb": round(Path(path).stat().st_size / 2**20, 3), "threads": threads,
|
| 93 |
+
"model_load_rss_mb": round((rss1 - rss0) / 2**20, 1)}
|
| 94 |
+
if hasattr(dec, "model"):
|
| 95 |
+
res["params"] = dec.model.num_parameters()
|
| 96 |
+
elif hasattr(dec, "meta"):
|
| 97 |
+
res["params"] = dec.meta.get("params")
|
| 98 |
+
res["latency"] = latency(dec, states, q, ch, n=200 if quick else n_latency)
|
| 99 |
+
res["batched"] = batched_throughput(dec, states, q, ch, seconds=1.0 if quick else 3.0)
|
| 100 |
+
max_rate = res["latency"]["max_decisions_per_sec_batch1"]
|
| 101 |
+
res["paced"] = []
|
| 102 |
+
for r in rates:
|
| 103 |
+
secs = 2.0 if quick else (5.0 if r <= 10 else 3.0)
|
| 104 |
+
if r > 1.5 * max_rate:
|
| 105 |
+
res["paced"].append({"target_per_sec": r, "achieved_per_sec": None, "sustained": False,
|
| 106 |
+
"note": f"above measured max ({max_rate}/s)"})
|
| 107 |
+
continue
|
| 108 |
+
if r == 1 and quick:
|
| 109 |
+
secs = 3.0
|
| 110 |
+
res["paced"].append(paced(dec, states, q, ch, r, secs))
|
| 111 |
+
res["process_rss_mb"] = round(proc.memory_info().rss / 2**20, 1)
|
| 112 |
+
return res
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def format_perf(res: dict) -> str:
|
| 116 |
+
L = res["latency"]
|
| 117 |
+
lines = [f"{res['model']} ({res['file_size_mb']} MB, params={res.get('params')}, threads={res['threads']})",
|
| 118 |
+
f" latency end-to-end p50 {L['end_to_end']['p50_ms']:.3f} ms p95 {L['end_to_end']['p95_ms']:.3f} ms "
|
| 119 |
+
f"p99 {L['end_to_end']['p99_ms']:.3f} ms",
|
| 120 |
+
f" latency model-only p50 {L['model_only']['p50_ms']:.3f} ms p95 {L['model_only']['p95_ms']:.3f} ms "
|
| 121 |
+
f"p99 {L['model_only']['p99_ms']:.3f} ms",
|
| 122 |
+
f" max decisions/s: batch=1 {L['max_decisions_per_sec_batch1']:,.0f} "
|
| 123 |
+
f"batch={res['batched']['batch']} {res['batched']['decisions_per_sec']:,.0f}",
|
| 124 |
+
" paced: target achieved p50ms p99ms cpu%(1 core) rss MB"]
|
| 125 |
+
for p in res["paced"]:
|
| 126 |
+
if p.get("achieved_per_sec") is None:
|
| 127 |
+
lines.append(f" {p['target_per_sec']:>6} -- {p['note']}")
|
| 128 |
+
else:
|
| 129 |
+
lines.append(f" {p['target_per_sec']:>6} {p['achieved_per_sec']:>8} {p['p50_ms']:>6.3f} "
|
| 130 |
+
f"{p['p99_ms']:>6.3f} {p['cpu_percent_of_one_core']:>12} {p['rss_mb']:>6}")
|
| 131 |
+
return "\n".join(lines)
|
code/minijev/calibration/__init__.py
ADDED
|
File without changes
|
code/minijev/calibration/__pycache__/__init__.cpython-314.pyc
ADDED
|
Binary file (182 Bytes). View file
|
|
|
code/minijev/calibration/__pycache__/metrics.cpython-314.pyc
ADDED
|
Binary file (14.1 kB). View file
|
|
|
code/minijev/calibration/metrics.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Calibration metrics and post-hoc calibrators (numpy only).
|
| 2 |
+
|
| 3 |
+
All functions take logits of shape (n, N) where absent choices hold a very
|
| 4 |
+
negative value (they get probability 0), and integer targets.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def softmax(logits: np.ndarray, temperature: float = 1.0) -> np.ndarray:
|
| 12 |
+
z = logits / temperature
|
| 13 |
+
z = z - z.max(1, keepdims=True)
|
| 14 |
+
e = np.exp(z)
|
| 15 |
+
return e / e.sum(1, keepdims=True)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def nll(probs: np.ndarray, targets: np.ndarray) -> float:
|
| 19 |
+
p = probs[np.arange(len(targets)), targets]
|
| 20 |
+
return float(-np.log(np.clip(p, 1e-12, 1.0)).mean())
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def brier(probs: np.ndarray, targets: np.ndarray) -> float:
|
| 24 |
+
"""Multi-class Brier score: mean over rows of sum_k (p_k - y_k)^2 (0 = perfect, 2 = worst)."""
|
| 25 |
+
y = np.zeros_like(probs)
|
| 26 |
+
y[np.arange(len(targets)), targets] = 1.0
|
| 27 |
+
return float(((probs - y) ** 2).sum(1).mean())
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def reliability_bins(confidence: np.ndarray, correct: np.ndarray, n_bins: int = 15) -> list[dict]:
|
| 31 |
+
edges = np.linspace(0.0, 1.0, n_bins + 1)
|
| 32 |
+
ids = np.clip(np.digitize(confidence, edges[1:-1], right=True), 0, n_bins - 1)
|
| 33 |
+
bins = []
|
| 34 |
+
for b in range(n_bins):
|
| 35 |
+
m = ids == b
|
| 36 |
+
n = int(m.sum())
|
| 37 |
+
bins.append({"lo": float(edges[b]), "hi": float(edges[b + 1]), "count": n,
|
| 38 |
+
"confidence": float(confidence[m].mean()) if n else None,
|
| 39 |
+
"accuracy": float(correct[m].mean()) if n else None})
|
| 40 |
+
return bins
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def ece(confidence: np.ndarray, correct: np.ndarray, n_bins: int = 15) -> float:
|
| 44 |
+
"""Expected Calibration Error (top-label, equal-width bins)."""
|
| 45 |
+
total = len(confidence)
|
| 46 |
+
return float(sum(b["count"] / total * abs(b["accuracy"] - b["confidence"])
|
| 47 |
+
for b in reliability_bins(confidence, correct, n_bins) if b["count"]))
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def calibration_report(logits: np.ndarray, targets: np.ndarray, temperature: float = 1.0,
|
| 51 |
+
n_bins: int = 15, acceptable: np.ndarray | None = None) -> dict:
|
| 52 |
+
"""`acceptable` (n, N) bool: choices that are also correct (e.g. equally optimal moves)."""
|
| 53 |
+
probs = softmax(logits, temperature)
|
| 54 |
+
pred = probs.argmax(1)
|
| 55 |
+
conf = probs.max(1)
|
| 56 |
+
correct = (pred == targets).astype(np.float64)
|
| 57 |
+
extra = {}
|
| 58 |
+
if acceptable is not None:
|
| 59 |
+
ok = acceptable[np.arange(len(pred)), pred].astype(np.float64)
|
| 60 |
+
extra = {"acceptable_accuracy": float(ok.mean()),
|
| 61 |
+
"acceptable_ece": ece(conf, ok, n_bins),
|
| 62 |
+
"mean_acceptable_choices": float(acceptable.sum(1).mean())}
|
| 63 |
+
return {**extra,
|
| 64 |
+
"n": int(len(targets)),
|
| 65 |
+
"accuracy": float(correct.mean()),
|
| 66 |
+
"nll": nll(probs, targets),
|
| 67 |
+
"brier": brier(probs, targets),
|
| 68 |
+
"ece": ece(conf, correct, n_bins),
|
| 69 |
+
"mean_confidence": float(conf.mean()),
|
| 70 |
+
"temperature": float(temperature),
|
| 71 |
+
"reliability": reliability_bins(conf, correct, n_bins),
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
# ------------------------------------------------------------------- calibrators
|
| 76 |
+
def fit_temperature(logits: np.ndarray, targets: np.ndarray, lo: float = -3.0, hi: float = 3.0,
|
| 77 |
+
iters: int = 60) -> float:
|
| 78 |
+
"""Temperature scaling: argmin_T NLL(softmax(logits / T)) by golden-section search on log T.
|
| 79 |
+
|
| 80 |
+
One scalar -> cannot overfit a validation set, preserves the argmax (accuracy
|
| 81 |
+
unchanged) and works for any number of choices; the natural fit for MiniJEV.
|
| 82 |
+
"""
|
| 83 |
+
f = lambda lt: nll(softmax(logits, float(np.exp(lt))), targets) # noqa: E731
|
| 84 |
+
g = (np.sqrt(5) - 1) / 2
|
| 85 |
+
a, b = lo, hi
|
| 86 |
+
c, d = b - g * (b - a), a + g * (b - a)
|
| 87 |
+
fc, fd = f(c), f(d)
|
| 88 |
+
for _ in range(iters):
|
| 89 |
+
if fc < fd:
|
| 90 |
+
b, d, fd = d, c, fc
|
| 91 |
+
c = b - g * (b - a)
|
| 92 |
+
fc = f(c)
|
| 93 |
+
else:
|
| 94 |
+
a, c, fc = c, d, fd
|
| 95 |
+
d = a + g * (b - a)
|
| 96 |
+
fd = f(d)
|
| 97 |
+
return float(np.exp((a + b) / 2))
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class IsotonicConfidence:
|
| 101 |
+
"""Top-label isotonic regression (pool-adjacent-violators) on confidence.
|
| 102 |
+
|
| 103 |
+
Maps raw confidence -> calibrated confidence. More flexible than temperature
|
| 104 |
+
scaling but needs more validation data and only recalibrates the top choice;
|
| 105 |
+
reported as a comparison, temperature scaling stays the default.
|
| 106 |
+
"""
|
| 107 |
+
|
| 108 |
+
def fit(self, confidence: np.ndarray, correct: np.ndarray) -> "IsotonicConfidence":
|
| 109 |
+
order = np.argsort(confidence)
|
| 110 |
+
x, y = confidence[order], correct[order].astype(np.float64)
|
| 111 |
+
vals, wts, xs = [], [], []
|
| 112 |
+
for xi, yi in zip(x, y):
|
| 113 |
+
vals.append(yi)
|
| 114 |
+
wts.append(1.0)
|
| 115 |
+
xs.append(xi)
|
| 116 |
+
while len(vals) > 1 and vals[-2] > vals[-1]:
|
| 117 |
+
w = wts[-2] + wts[-1]
|
| 118 |
+
v = (vals[-2] * wts[-2] + vals[-1] * wts[-1]) / w
|
| 119 |
+
vals[-2:], wts[-2:], xs[-2:] = [v], [w], [xs[-1]]
|
| 120 |
+
self.x, self.y = np.array(xs), np.array(vals)
|
| 121 |
+
return self
|
| 122 |
+
|
| 123 |
+
def __call__(self, confidence: np.ndarray) -> np.ndarray:
|
| 124 |
+
return np.interp(confidence, self.x, self.y)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def reliability_svg(bins: list[dict], title: str = "Reliability diagram", size: int = 360) -> str:
|
| 128 |
+
"""Dependency-free SVG reliability diagram (accuracy vs confidence per bin)."""
|
| 129 |
+
pad = 40
|
| 130 |
+
inner = size - 2 * pad
|
| 131 |
+
X = lambda v: pad + v * inner # noqa: E731
|
| 132 |
+
Y = lambda v: size - pad - v * inner # noqa: E731
|
| 133 |
+
total = sum(b["count"] for b in bins) or 1
|
| 134 |
+
parts = [f'<svg xmlns="http://www.w3.org/2000/svg" width="{size}" height="{size}" '
|
| 135 |
+
f'font-family="sans-serif" font-size="11">',
|
| 136 |
+
f'<rect width="{size}" height="{size}" fill="white"/>',
|
| 137 |
+
f'<text x="{size / 2}" y="18" text-anchor="middle" font-size="13">{title}</text>',
|
| 138 |
+
f'<line x1="{X(0)}" y1="{Y(0)}" x2="{X(1)}" y2="{Y(1)}" stroke="#999" stroke-dasharray="4"/>']
|
| 139 |
+
for b in bins:
|
| 140 |
+
if not b["count"]:
|
| 141 |
+
continue
|
| 142 |
+
w = (b["hi"] - b["lo"]) * inner
|
| 143 |
+
parts.append(f'<rect x="{X(b["lo"]) + 1}" y="{Y(b["accuracy"])}" width="{w - 2}" '
|
| 144 |
+
f'height="{b["accuracy"] * inner}" fill="#3b82f6" fill-opacity="0.75"/>')
|
| 145 |
+
parts.append(f'<rect x="{X(b["lo"]) + 1}" y="{Y(0) + 4}" width="{w - 2}" '
|
| 146 |
+
f'height="{max(1.0, 20 * b["count"] / total)}" fill="#94a3b8"/>')
|
| 147 |
+
parts.append(f'<circle cx="{X(b["confidence"])}" cy="{Y(b["confidence"])}" r="2" fill="#ef4444"/>')
|
| 148 |
+
for v in (0, 0.25, 0.5, 0.75, 1):
|
| 149 |
+
parts.append(f'<text x="{X(v)}" y="{size - pad + 38}" text-anchor="middle">{v:g}</text>')
|
| 150 |
+
parts.append(f'<text x="{pad - 6}" y="{Y(v) + 4}" text-anchor="end">{v:g}</text>')
|
| 151 |
+
parts.append(f'<rect x="{pad}" y="{pad}" width="{inner}" height="{inner}" fill="none" stroke="#333"/>')
|
| 152 |
+
parts.append(f'<text x="{size / 2}" y="{size - 4}" text-anchor="middle">confidence '
|
| 153 |
+
f'(blue = accuracy, grey = share of samples)</text>')
|
| 154 |
+
parts.append("</svg>")
|
| 155 |
+
return "\n".join(parts)
|
code/minijev/choices/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .encoder import ChoiceEncoder, EmbeddingCache
|
| 2 |
+
|
| 3 |
+
__all__ = ["ChoiceEncoder", "EmbeddingCache"]
|
code/minijev/choices/__pycache__/__init__.cpython-314.pyc
ADDED
|
Binary file (289 Bytes). View file
|
|
|
code/minijev/choices/__pycache__/encoder.cpython-314.pyc
ADDED
|
Binary file (5.81 kB). View file
|
|
|
code/minijev/choices/encoder.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ChoiceEncoder: choice label -> semantic embedding in the core space.
|
| 2 |
+
|
| 3 |
+
Choices are *inputs*: "yes", "no", "database", "move up" are encoded from their
|
| 4 |
+
text, so the same weights serve 2, 4 or 10 options and unseen labels. With a
|
| 5 |
+
pretrained text encoder the choice embedding comes from the same backbone as the
|
| 6 |
+
question (shared weights), so "sì" and "yes" start close together.
|
| 7 |
+
|
| 8 |
+
`EmbeddingCache` memoises backbone outputs per string. With a frozen backbone a
|
| 9 |
+
question or a choice label is encoded once, ever: Snake's 4 moves and a fixed
|
| 10 |
+
question cost nothing at inference, only the core runs.
|
| 11 |
+
"""
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
from collections import OrderedDict
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from torch import nn
|
| 18 |
+
|
| 19 |
+
from minijev.encoders.text import Projection, TextPooler
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class ChoiceEncoder(nn.Module):
|
| 23 |
+
def __init__(self, d: int, embed: nn.Embedding | None = None, max_len: int = 16, d_text: int | None = None):
|
| 24 |
+
super().__init__()
|
| 25 |
+
self.byte = embed is not None
|
| 26 |
+
if self.byte:
|
| 27 |
+
self.pooler = TextPooler(embed, d, max_len)
|
| 28 |
+
else:
|
| 29 |
+
self.proj = Projection(d_text, d, hidden=2 * d)
|
| 30 |
+
|
| 31 |
+
def forward(self, ids=None, pooled=None):
|
| 32 |
+
"""byte: ids (..., L) -> (..., d); pretrained: backbone pooled (..., d_text) -> (..., d)."""
|
| 33 |
+
return self.pooler(ids) if self.byte else self.proj(pooled)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class EmbeddingCache:
|
| 37 |
+
"""LRU cache: text -> backbone output (tokens, mask, pooled) as CPU tensors."""
|
| 38 |
+
|
| 39 |
+
def __init__(self, max_items: int = 4096):
|
| 40 |
+
self.max_items = max_items
|
| 41 |
+
self.data: OrderedDict[str, tuple] = OrderedDict()
|
| 42 |
+
self.hits = self.misses = 0
|
| 43 |
+
|
| 44 |
+
def get_many(self, texts, compute):
|
| 45 |
+
"""compute(list[str]) -> (tok (n, L, dt), mask (n, L), pooled (n, dt)) for the missing texts."""
|
| 46 |
+
missing = [t for t in dict.fromkeys(texts) if t not in self.data]
|
| 47 |
+
self.hits += len(texts) - len(missing)
|
| 48 |
+
self.misses += len(missing)
|
| 49 |
+
if missing:
|
| 50 |
+
tok, mask, pooled = compute(missing)
|
| 51 |
+
for i, t in enumerate(missing):
|
| 52 |
+
n = int(mask[i].sum())
|
| 53 |
+
self.data[t] = (tok[i, :n].detach().cpu(), pooled[i].detach().cpu())
|
| 54 |
+
if len(self.data) > self.max_items:
|
| 55 |
+
self.data.popitem(last=False)
|
| 56 |
+
for t in texts:
|
| 57 |
+
self.data.move_to_end(t)
|
| 58 |
+
rows = [self.data[t] for t in texts]
|
| 59 |
+
L = max(1, max(r[0].shape[0] for r in rows))
|
| 60 |
+
dt = rows[0][1].shape[-1]
|
| 61 |
+
tok = torch.zeros(len(rows), L, dt)
|
| 62 |
+
mask = torch.zeros(len(rows), L, dtype=torch.bool)
|
| 63 |
+
for i, (t, _) in enumerate(rows):
|
| 64 |
+
tok[i, : t.shape[0]] = t
|
| 65 |
+
mask[i, : t.shape[0]] = True
|
| 66 |
+
return tok, mask, torch.stack([r[1] for r in rows])
|
code/minijev/cli.py
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""`minijev` command line.
|
| 2 |
+
|
| 3 |
+
minijev hardware
|
| 4 |
+
minijev train --config configs/snake-small.yaml [--resume RUN_DIR] [--set key=value ...]
|
| 5 |
+
minijev evaluate --checkpoint RUN/checkpoints/final.pt [--games 200]
|
| 6 |
+
minijev benchmark --checkpoint RUN/checkpoints/final.pt [--onnx]
|
| 7 |
+
minijev export --checkpoint RUN/checkpoints/final.pt --format onnx
|
| 8 |
+
minijev estimate --config configs/vast/vast-small.yaml --gpu-hourly-cost 0.20
|
| 9 |
+
minijev compare RUN_DIR [RUN_DIR ...]
|
| 10 |
+
minijev runs annotate RUN_DIR --actual-cost 0.42
|
| 11 |
+
minijev export-hf --checkpoint X.pt --out hf/name (checkpoint may then be a folder or a hub repo id)
|
| 12 |
+
minijev relabel --checkpoint X.pt --out Y.pt --map UP="move up" ... [--set task.choice_style=semantic]
|
| 13 |
+
minijev ask --checkpoint X.pt --state hotdog --question "Is this food?" --choices yes no
|
| 14 |
+
minijev bench-jsonl --checkpoint X.pt --data data/general_qa/benchmark.jsonl
|
| 15 |
+
minijev snake generate|baselines|demo|play|dagger|rl ...
|
| 16 |
+
minijev sentiment prepare ...
|
| 17 |
+
"""
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
import json
|
| 22 |
+
import sys
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _cfg(args):
|
| 27 |
+
from minijev.config import load_config
|
| 28 |
+
return load_config(args.config, getattr(args, "set", None) or [])
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# ------------------------------------------------------------------ generic
|
| 32 |
+
def cmd_hardware(args):
|
| 33 |
+
import torch
|
| 34 |
+
|
| 35 |
+
from minijev.device import resolve_runtime
|
| 36 |
+
prof = resolve_runtime({"batch_size": args.batch_size}, args.params)
|
| 37 |
+
print(json.dumps({"torch": torch.__version__, **prof.to_dict()}, indent=2))
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def cmd_train(args):
|
| 41 |
+
from minijev.training.supervised import train
|
| 42 |
+
cfg = _cfg(args)
|
| 43 |
+
run_dir = args.resume or args.run_dir
|
| 44 |
+
s = train(cfg, run_dir=run_dir, resume=bool(args.resume), max_steps=args.max_steps, max_minutes=args.max_minutes)
|
| 45 |
+
print(json.dumps({k: v for k, v in s.items() if not k.startswith("test_")}, indent=2, default=str))
|
| 46 |
+
if cfg["task"]["name"] == "snake" and s.get("final_checkpoint") and not args.no_games:
|
| 47 |
+
_snake_eval(s["final_checkpoint"], cfg, Path(s["run_dir"]))
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _snake_eval(ckpt, cfg, run_dir: Path, games: int | None = None):
|
| 51 |
+
from environments.snake.evaluate import model_policy, play_games
|
| 52 |
+
from minijev.inference.runtime import MiniJEV
|
| 53 |
+
dec = MiniJEV.load(ckpt, threads=4)
|
| 54 |
+
env = cfg.get("env", {})
|
| 55 |
+
n = games or cfg.get("eval", {}).get("games", 200)
|
| 56 |
+
res = play_games(model_policy(dec), n, env, parallel=cfg.get("eval", {}).get("parallel", 64))
|
| 57 |
+
print(f"[games] {res['games']} games on {res['board']}: avg {res['avg_score']:.1f} median {res['median_score']:.0f} "
|
| 58 |
+
f"max {res['max_score']} / {res['max_possible_score']} | win {res['win_rate']:.2%} "
|
| 59 |
+
f"collision {res['death_rate']:.2%} starvation {res['starvation_rate']:.2%} | "
|
| 60 |
+
f"fatal-move rate {res['fatal_move_rate']:.4%}")
|
| 61 |
+
(run_dir / "games.json").write_text(json.dumps(res, indent=2))
|
| 62 |
+
return res
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def cmd_evaluate(args):
|
| 66 |
+
import numpy as np
|
| 67 |
+
|
| 68 |
+
from minijev.calibration.metrics import calibration_report
|
| 69 |
+
from minijev.datasets.batching import BatchEncoder
|
| 70 |
+
from minijev.datasets.decision_data import DecisionData
|
| 71 |
+
from minijev.inference.runtime import MiniJEV
|
| 72 |
+
dec = MiniJEV.load(args.checkpoint, threads=args.threads)
|
| 73 |
+
import torch
|
| 74 |
+
cfg = torch.load(args.checkpoint, weights_only=False)["config"] if args.checkpoint.endswith(".pt") else None
|
| 75 |
+
data_dir = Path(args.data or (cfg["data"]["dir"] if cfg else ""))
|
| 76 |
+
out = {"checkpoint": args.checkpoint}
|
| 77 |
+
split = data_dir / f"{args.split}.npz"
|
| 78 |
+
if split.exists():
|
| 79 |
+
data = DecisionData.load(split)
|
| 80 |
+
enc = BatchEncoder(data, dec.task, dec.max_question_len, dec.max_choice_len)
|
| 81 |
+
logits = []
|
| 82 |
+
for i in range(0, len(data), 1024):
|
| 83 |
+
b = enc(np.arange(i, min(len(data), i + 1024)))
|
| 84 |
+
logits.append(dec._run(next(v for k, v in b.items() if k.startswith("state_")),
|
| 85 |
+
b["question_ids"], b["choice_ids"])[1])
|
| 86 |
+
acceptable = data.soft > 0 if data.soft is not None else None
|
| 87 |
+
rep = calibration_report(np.concatenate(logits), data.target, acceptable=acceptable) # T already applied
|
| 88 |
+
out["calibration"] = {k: v for k, v in rep.items() if k != "reliability"}
|
| 89 |
+
out["reliability"] = rep["reliability"]
|
| 90 |
+
print(f"[{args.split}] n={rep['n']} acc {rep['accuracy']:.4f} ECE {rep['ece']:.4f} "
|
| 91 |
+
f"NLL {rep['nll']:.4f} Brier {rep['brier']:.4f}"
|
| 92 |
+
+ (f" acceptable-acc {rep['acceptable_accuracy']:.4f}" if acceptable is not None else ""))
|
| 93 |
+
if dec.task.name == "snake" and args.games:
|
| 94 |
+
from environments.snake.evaluate import model_policy, play_games
|
| 95 |
+
env = (cfg or {}).get("env", {})
|
| 96 |
+
if args.board_size:
|
| 97 |
+
env = {**env, "board_size": args.board_size}
|
| 98 |
+
res = play_games(model_policy(dec), args.games, env)
|
| 99 |
+
out["games"] = res
|
| 100 |
+
print(f"[games] avg {res['avg_score']:.2f} median {res['median_score']} max {res['max_score']} "
|
| 101 |
+
f"win {res['win_rate']:.2%} collisions {res['death_rate']:.2%} fatal-move {res['fatal_move_rate']:.4%}")
|
| 102 |
+
if args.out:
|
| 103 |
+
Path(args.out).write_text(json.dumps(out, indent=2))
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def cmd_benchmark(args):
|
| 107 |
+
from minijev.benchmark.perf import benchmark_decider, format_perf
|
| 108 |
+
paths = [args.checkpoint]
|
| 109 |
+
if args.onnx:
|
| 110 |
+
p = Path(args.checkpoint)
|
| 111 |
+
for cand in (p.with_suffix(".onnx"), p.with_name(p.stem + ".int8.onnx")):
|
| 112 |
+
if cand.exists():
|
| 113 |
+
paths.append(str(cand))
|
| 114 |
+
results = []
|
| 115 |
+
for path in paths:
|
| 116 |
+
r = benchmark_decider(path, threads=args.threads, quick=args.quick)
|
| 117 |
+
print(format_perf(r))
|
| 118 |
+
results.append(r)
|
| 119 |
+
if args.out:
|
| 120 |
+
Path(args.out).write_text(json.dumps(results, indent=2))
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def cmd_export(args):
|
| 124 |
+
from minijev.export.onnx_export import export_onnx
|
| 125 |
+
if args.format != "onnx":
|
| 126 |
+
sys.exit("only --format onnx is supported")
|
| 127 |
+
r = export_onnx(args.checkpoint, args.out, quantize=not args.no_quantize)
|
| 128 |
+
print(json.dumps({k: v for k, v in r.items() if k != "meta"}, indent=2))
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def cmd_estimate(args):
|
| 132 |
+
from minijev.estimate import estimate
|
| 133 |
+
estimate(_cfg(args), args.gpu_hourly_cost, throughput=args.throughput, bench_seconds=args.bench_seconds,
|
| 134 |
+
gpu_name=args.gpu_name, budget=args.budget)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def cmd_relabel(args):
|
| 138 |
+
from minijev.config import _parse_value
|
| 139 |
+
from minijev.training.relabel import relabel_checkpoint
|
| 140 |
+
mapping = dict(m.split("=", 1) for m in args.map)
|
| 141 |
+
updates = {k: _parse_value(v) for k, v in (kv.split("=", 1) for kv in (args.set or []))}
|
| 142 |
+
print(json.dumps(relabel_checkpoint(args.checkpoint, args.out, mapping, updates, steps=args.steps), indent=2))
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def cmd_export_hf(args):
|
| 146 |
+
from minijev.hub import save_pretrained
|
| 147 |
+
print(save_pretrained(args.checkpoint, args.out))
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def cmd_ask(args):
|
| 151 |
+
from minijev.inference.runtime import MiniJEV
|
| 152 |
+
dec = MiniJEV.load(args.checkpoint, threads=args.threads, **({"task": args.task} if args.task else {}))
|
| 153 |
+
d = dec.decide(args.state, args.question, args.choices)
|
| 154 |
+
print(json.dumps(d.to_dict(), ensure_ascii=False, indent=2))
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def cmd_bench_jsonl(args):
|
| 158 |
+
"""Accuracy + calibration of a model on a JSONL decision file, row by row."""
|
| 159 |
+
import numpy as np
|
| 160 |
+
|
| 161 |
+
from minijev.calibration.metrics import calibration_report
|
| 162 |
+
from minijev.datasets.jsonl import read_jsonl
|
| 163 |
+
from minijev.inference.runtime import MiniJEV
|
| 164 |
+
dec = MiniJEV.load(args.checkpoint, threads=args.threads, **({"task": args.task} if args.task else {}))
|
| 165 |
+
rows = read_jsonl(args.data)
|
| 166 |
+
ok, logits, targets, out = 0, [], [], []
|
| 167 |
+
for r in rows:
|
| 168 |
+
d = dec.decide(r.get("state") or "", r["question"], r["choices"])
|
| 169 |
+
tgt = r["target"] if isinstance(r["target"], str) else r["choices"][r["target"]]
|
| 170 |
+
hit = d.choice == tgt
|
| 171 |
+
ok += hit
|
| 172 |
+
n = max(len(x["choices"]) for x in rows)
|
| 173 |
+
logits.append(np.pad(np.array(d.logits), (0, n - len(d.logits)), constant_values=-1e9))
|
| 174 |
+
targets.append(r["choices"].index(tgt))
|
| 175 |
+
out.append({**r, "pred": d.choice, "confidence": round(d.confidence, 4), "correct": bool(hit)})
|
| 176 |
+
if args.verbose:
|
| 177 |
+
print(f"{'OK ' if hit else 'XX '} {d.confidence:.2f} {r.get('state') or '-':>10} | {r['question']} "
|
| 178 |
+
f"-> {d.choice} (gold {tgt})")
|
| 179 |
+
rep = calibration_report(np.stack(logits), np.array(targets)) # logits are already calibrated
|
| 180 |
+
print(f"[{args.data}] {ok}/{len(rows)} = {ok / len(rows):.3f} | ECE {rep['ece']:.4f} NLL {rep['nll']:.4f} "
|
| 181 |
+
f"Brier {rep['brier']:.4f}")
|
| 182 |
+
if args.out:
|
| 183 |
+
Path(args.out).write_text(json.dumps({"accuracy": ok / len(rows), "ece": rep["ece"], "nll": rep["nll"],
|
| 184 |
+
"brier": rep["brier"], "rows": out}, indent=2, ensure_ascii=False))
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def cmd_compare(args):
|
| 188 |
+
from minijev.report import compare_runs
|
| 189 |
+
print(compare_runs(args.runs, out=args.out))
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def cmd_runs_annotate(args):
|
| 193 |
+
p = Path(args.run) / "summary.json"
|
| 194 |
+
s = json.loads(p.read_text())
|
| 195 |
+
s.setdefault("cost", {})
|
| 196 |
+
if args.actual_cost is not None:
|
| 197 |
+
s["cost"]["actual_cost"] = args.actual_cost
|
| 198 |
+
if args.gpu:
|
| 199 |
+
s["cost"]["gpu"] = args.gpu
|
| 200 |
+
if args.note:
|
| 201 |
+
s["note"] = args.note
|
| 202 |
+
p.write_text(json.dumps(s, indent=2))
|
| 203 |
+
print(json.dumps(s.get("cost"), indent=2))
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
# -------------------------------------------------------------------- snake
|
| 207 |
+
def cmd_snake_generate(args):
|
| 208 |
+
from environments.snake.dataset import generate_splits
|
| 209 |
+
sizes = [int(x) for x in str(args.board_size).split(",")]
|
| 210 |
+
out = args.out or f"data/snake{'-'.join(map(str, sizes))}-{_short(args.samples)}"
|
| 211 |
+
s = generate_splits(out, args.samples, seed=args.seed, board_sizes=sizes, keep_prob=args.keep_prob,
|
| 212 |
+
explore_eps=args.explore_eps, workers=args.workers)
|
| 213 |
+
if args.jsonl:
|
| 214 |
+
from environments.snake.dataset import export_jsonl
|
| 215 |
+
from minijev.datasets.decision_data import DecisionData
|
| 216 |
+
for split in ("train", "val", "test"):
|
| 217 |
+
export_jsonl(DecisionData.load(Path(out) / f"{split}.npz"), Path(out) / f"{split}.jsonl")
|
| 218 |
+
print(json.dumps(s, indent=2))
|
| 219 |
+
print(f"-> {out}")
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def _short(n: int) -> str:
|
| 223 |
+
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))
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def cmd_snake_baselines(args):
|
| 227 |
+
from environments.snake.evaluate import baseline_suite
|
| 228 |
+
res = baseline_suite(args.games, {"board_size": args.board_size}, seed=args.seed)
|
| 229 |
+
print(f"{'agent':10} {'avg':>7} {'median':>7} {'max':>5} {'win':>6} {'collide':>8} {'starve':>7} {'fatal%':>8}")
|
| 230 |
+
for name, r in res.items():
|
| 231 |
+
print(f"{name:10} {r['avg_score']:7.1f} {r['median_score']:7.0f} {r['max_score']:5d} {r['win_rate']:6.1%} "
|
| 232 |
+
f"{r['death_rate']:8.1%} {r['starvation_rate']:7.1%} {r['fatal_move_rate']:8.3%}")
|
| 233 |
+
if args.out:
|
| 234 |
+
Path(args.out).write_text(json.dumps(res, indent=2))
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def cmd_snake_demo(args, human=False):
|
| 238 |
+
from environments.snake.demo.server import serve
|
| 239 |
+
serve(model=args.model, board_size=args.board_size, port=args.port, agent="human" if human else args.agent,
|
| 240 |
+
open_browser=not args.no_browser)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def cmd_snake_dagger(args):
|
| 244 |
+
from environments.snake.dagger import run_dagger
|
| 245 |
+
run_dagger(_cfg(args), args.checkpoint, iterations=args.iterations, samples=args.samples, run_dir=args.run_dir)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def cmd_snake_rl(args):
|
| 249 |
+
from environments.snake.rl import train_ppo
|
| 250 |
+
train_ppo(_cfg(args), args.checkpoint, run_dir=args.run_dir, resume=args.resume)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def cmd_sentiment_prepare(args):
|
| 254 |
+
from environments.sentiment.dataset import prepare
|
| 255 |
+
print(json.dumps(prepare(args.out, source=args.source), indent=2))
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
# --------------------------------------------------------------------- main
|
| 259 |
+
def build_parser() -> argparse.ArgumentParser:
|
| 260 |
+
p = argparse.ArgumentParser(prog="minijev", description="MiniJEV: tiny calibrated decision model")
|
| 261 |
+
sub = p.add_subparsers(dest="cmd", required=True)
|
| 262 |
+
|
| 263 |
+
s = sub.add_parser("hardware", help="show detected device and runtime profile")
|
| 264 |
+
s.add_argument("--batch-size", type=int, default=256)
|
| 265 |
+
s.add_argument("--params", type=int, default=1_000_000)
|
| 266 |
+
s.set_defaults(fn=cmd_hardware)
|
| 267 |
+
|
| 268 |
+
s = sub.add_parser("train", help="supervised / distillation training")
|
| 269 |
+
s.add_argument("--config", required=True)
|
| 270 |
+
s.add_argument("--set", nargs="*", help="override config values, e.g. training.lr=5e-4")
|
| 271 |
+
s.add_argument("--run-dir")
|
| 272 |
+
s.add_argument("--resume", help="run directory to resume from (uses checkpoints/last.pt)")
|
| 273 |
+
s.add_argument("--max-steps", type=int)
|
| 274 |
+
s.add_argument("--max-minutes", type=float, help="stop cleanly (checkpoint saved) after this wall time")
|
| 275 |
+
s.add_argument("--no-games", action="store_true", help="skip game evaluation after training")
|
| 276 |
+
s.set_defaults(fn=cmd_train)
|
| 277 |
+
|
| 278 |
+
s = sub.add_parser("evaluate", help="calibration on a split + (snake) full games")
|
| 279 |
+
s.add_argument("--checkpoint", required=True)
|
| 280 |
+
s.add_argument("--data", help="dataset dir (default: from checkpoint config)")
|
| 281 |
+
s.add_argument("--split", default="test")
|
| 282 |
+
s.add_argument("--games", type=int, default=200)
|
| 283 |
+
s.add_argument("--board-size", type=int)
|
| 284 |
+
s.add_argument("--threads", type=int, default=4)
|
| 285 |
+
s.add_argument("--out")
|
| 286 |
+
s.set_defaults(fn=cmd_evaluate)
|
| 287 |
+
|
| 288 |
+
s = sub.add_parser("benchmark", help="latency / throughput / CPU / RAM")
|
| 289 |
+
s.add_argument("--checkpoint", required=True, help=".pt or .onnx")
|
| 290 |
+
s.add_argument("--onnx", action="store_true", help="also benchmark sibling .onnx and .int8.onnx files")
|
| 291 |
+
s.add_argument("--threads", type=int, default=1)
|
| 292 |
+
s.add_argument("--quick", action="store_true")
|
| 293 |
+
s.add_argument("--out")
|
| 294 |
+
s.set_defaults(fn=cmd_benchmark)
|
| 295 |
+
|
| 296 |
+
s = sub.add_parser("export", help="export to ONNX (+ INT8) and verify parity")
|
| 297 |
+
s.add_argument("--checkpoint", required=True)
|
| 298 |
+
s.add_argument("--format", default="onnx")
|
| 299 |
+
s.add_argument("--out")
|
| 300 |
+
s.add_argument("--no-quantize", action="store_true")
|
| 301 |
+
s.set_defaults(fn=cmd_export)
|
| 302 |
+
|
| 303 |
+
s = sub.add_parser("estimate", help="estimate training time and cost (measures real throughput)")
|
| 304 |
+
s.add_argument("--config", required=True)
|
| 305 |
+
s.add_argument("--set", nargs="*")
|
| 306 |
+
s.add_argument("--gpu-hourly-cost", type=float, default=0.0)
|
| 307 |
+
s.add_argument("--gpu-name")
|
| 308 |
+
s.add_argument("--throughput", type=float, help="samples/s; skip the measurement")
|
| 309 |
+
s.add_argument("--bench-seconds", type=float, default=60)
|
| 310 |
+
s.add_argument("--budget", type=float, help="warn if the estimate exceeds this amount")
|
| 311 |
+
s.set_defaults(fn=cmd_estimate)
|
| 312 |
+
|
| 313 |
+
s = sub.add_parser("compare", help="results table across runs")
|
| 314 |
+
s.add_argument("runs", nargs="+")
|
| 315 |
+
s.add_argument("--out", help="write markdown table here")
|
| 316 |
+
s.set_defaults(fn=cmd_compare)
|
| 317 |
+
|
| 318 |
+
runs = sub.add_parser("runs", help="run bookkeeping").add_subparsers(dest="runs_cmd", required=True)
|
| 319 |
+
s = runs.add_parser("annotate")
|
| 320 |
+
s.add_argument("run")
|
| 321 |
+
s.add_argument("--actual-cost", type=float)
|
| 322 |
+
s.add_argument("--gpu")
|
| 323 |
+
s.add_argument("--note")
|
| 324 |
+
s.set_defaults(fn=cmd_runs_annotate)
|
| 325 |
+
|
| 326 |
+
snake = sub.add_parser("snake", help="Snake environment tools").add_subparsers(dest="snake_cmd", required=True)
|
| 327 |
+
s = snake.add_parser("generate", help="generate an oracle-labelled dataset")
|
| 328 |
+
s.add_argument("--samples", type=int, default=100_000)
|
| 329 |
+
s.add_argument("--board-size", default="10", help="e.g. 10 or 10,20")
|
| 330 |
+
s.add_argument("--out")
|
| 331 |
+
s.add_argument("--seed", type=int, default=0)
|
| 332 |
+
s.add_argument("--keep-prob", type=float, default=0.1)
|
| 333 |
+
s.add_argument("--explore-eps", type=float, default=0.05)
|
| 334 |
+
s.add_argument("--workers", type=int)
|
| 335 |
+
s.add_argument("--jsonl", action="store_true", help="also write full JSONL exports")
|
| 336 |
+
s.set_defaults(fn=cmd_snake_generate)
|
| 337 |
+
|
| 338 |
+
s = snake.add_parser("baselines", help="play the scripted baselines")
|
| 339 |
+
s.add_argument("--games", type=int, default=100)
|
| 340 |
+
s.add_argument("--board-size", type=int, default=10)
|
| 341 |
+
s.add_argument("--seed", type=int, default=12345)
|
| 342 |
+
s.add_argument("--out")
|
| 343 |
+
s.set_defaults(fn=cmd_snake_baselines)
|
| 344 |
+
|
| 345 |
+
for name, human in (("demo", False), ("play", True)):
|
| 346 |
+
s = snake.add_parser(name, help="web UI: watch MiniJEV/baselines" if not human else "web UI: play yourself")
|
| 347 |
+
s.add_argument("--model", help=".onnx or .pt")
|
| 348 |
+
s.add_argument("--agent", default="minijev", help="minijev | oracle | bfs | survival | greedy | random | human")
|
| 349 |
+
s.add_argument("--board-size", type=int, default=10)
|
| 350 |
+
s.add_argument("--port", type=int, default=8765)
|
| 351 |
+
s.add_argument("--no-browser", action="store_true")
|
| 352 |
+
s.set_defaults(fn=lambda a, h=human: cmd_snake_demo(a, h))
|
| 353 |
+
|
| 354 |
+
s = snake.add_parser("dagger", help="DAgger: label the model's own states with the oracle, retrain")
|
| 355 |
+
s.add_argument("--config", required=True)
|
| 356 |
+
s.add_argument("--set", nargs="*")
|
| 357 |
+
s.add_argument("--checkpoint", required=True)
|
| 358 |
+
s.add_argument("--iterations", type=int, default=2)
|
| 359 |
+
s.add_argument("--samples", type=int, default=100_000)
|
| 360 |
+
s.add_argument("--run-dir")
|
| 361 |
+
s.set_defaults(fn=cmd_snake_dagger)
|
| 362 |
+
|
| 363 |
+
s = snake.add_parser("rl", help="PPO fine-tuning from a supervised checkpoint")
|
| 364 |
+
s.add_argument("--config", required=True)
|
| 365 |
+
s.add_argument("--set", nargs="*")
|
| 366 |
+
s.add_argument("--checkpoint", required=True)
|
| 367 |
+
s.add_argument("--run-dir")
|
| 368 |
+
s.add_argument("--resume", action="store_true")
|
| 369 |
+
s.set_defaults(fn=cmd_snake_rl)
|
| 370 |
+
|
| 371 |
+
s = sub.add_parser("relabel", help="rename choice labels of a trained model (fits the ChoiceEncoder only)")
|
| 372 |
+
s.add_argument("--checkpoint", required=True)
|
| 373 |
+
s.add_argument("--out", required=True)
|
| 374 |
+
s.add_argument("--map", nargs="+", required=True, help='OLD="new label" ...')
|
| 375 |
+
s.add_argument("--set", nargs="*", help="config updates stored in the new checkpoint")
|
| 376 |
+
s.add_argument("--steps", type=int, default=3000)
|
| 377 |
+
s.set_defaults(fn=cmd_relabel)
|
| 378 |
+
|
| 379 |
+
s = sub.add_parser("export-hf", help="write a pickle-free folder (safetensors + JSON) for Hugging Face")
|
| 380 |
+
s.add_argument("--checkpoint", required=True)
|
| 381 |
+
s.add_argument("--out", required=True)
|
| 382 |
+
s.set_defaults(fn=cmd_export_hf)
|
| 383 |
+
|
| 384 |
+
s = sub.add_parser("ask", help="one decision from the command line")
|
| 385 |
+
s.add_argument("--checkpoint", required=True)
|
| 386 |
+
s.add_argument("--state", default="")
|
| 387 |
+
s.add_argument("--question", required=True)
|
| 388 |
+
s.add_argument("--choices", nargs="+", required=True)
|
| 389 |
+
s.add_argument("--task")
|
| 390 |
+
s.add_argument("--threads", type=int, default=1)
|
| 391 |
+
s.set_defaults(fn=cmd_ask)
|
| 392 |
+
|
| 393 |
+
s = sub.add_parser("bench-jsonl", help="accuracy/calibration on a JSONL decision file")
|
| 394 |
+
s.add_argument("--checkpoint", required=True)
|
| 395 |
+
s.add_argument("--data", required=True)
|
| 396 |
+
s.add_argument("--task")
|
| 397 |
+
s.add_argument("--threads", type=int, default=4)
|
| 398 |
+
s.add_argument("--out")
|
| 399 |
+
s.add_argument("-v", "--verbose", action="store_true")
|
| 400 |
+
s.set_defaults(fn=cmd_bench_jsonl)
|
| 401 |
+
|
| 402 |
+
sent = sub.add_parser("sentiment", help="sentiment task tools").add_subparsers(dest="sent_cmd", required=True)
|
| 403 |
+
s = sent.add_parser("prepare", help="download / build the sentiment dataset")
|
| 404 |
+
s.add_argument("--out", default="data/sentiment")
|
| 405 |
+
s.add_argument("--source", default="tweet_eval")
|
| 406 |
+
s.set_defaults(fn=cmd_sentiment_prepare)
|
| 407 |
+
return p
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def main(argv=None):
|
| 411 |
+
args = build_parser().parse_args(argv)
|
| 412 |
+
args.fn(args)
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
if __name__ == "__main__":
|
| 416 |
+
main()
|
code/minijev/config.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""YAML configs with `extends:` inheritance and dotted CLI overrides."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import copy
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import yaml
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def deep_merge(base: dict, override: dict) -> dict:
|
| 12 |
+
out = copy.deepcopy(base)
|
| 13 |
+
for k, v in override.items():
|
| 14 |
+
if isinstance(v, dict) and isinstance(out.get(k), dict):
|
| 15 |
+
out[k] = deep_merge(out[k], v)
|
| 16 |
+
else:
|
| 17 |
+
out[k] = copy.deepcopy(v)
|
| 18 |
+
return out
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _load(path: Path) -> dict:
|
| 22 |
+
cfg = yaml.safe_load(path.read_text()) or {}
|
| 23 |
+
parent = cfg.pop("extends", None)
|
| 24 |
+
return deep_merge(_load(path.parent / parent), cfg) if parent else cfg
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def load_config(path: str | Path, overrides: list[str] | None = None) -> dict:
|
| 28 |
+
path = Path(path)
|
| 29 |
+
raw = yaml.safe_load(path.read_text()) or {}
|
| 30 |
+
cfg = _load(path)
|
| 31 |
+
cfg["name"] = raw.get("name", path.stem)
|
| 32 |
+
for ov in overrides or []:
|
| 33 |
+
key, _, val = ov.partition("=")
|
| 34 |
+
set_dotted(cfg, key.strip(), _parse_value(val))
|
| 35 |
+
return cfg
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _parse_value(val: str) -> Any:
|
| 39 |
+
v = yaml.safe_load(val)
|
| 40 |
+
if isinstance(v, str): # YAML 1.1 reads "3e-4" as a string
|
| 41 |
+
try:
|
| 42 |
+
return float(v)
|
| 43 |
+
except ValueError:
|
| 44 |
+
pass
|
| 45 |
+
return v
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def set_dotted(cfg: dict, key: str, value: Any) -> None:
|
| 49 |
+
node = cfg
|
| 50 |
+
parts = key.split(".")
|
| 51 |
+
for p in parts[:-1]:
|
| 52 |
+
node = node.setdefault(p, {})
|
| 53 |
+
node[parts[-1]] = value
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def get_dotted(cfg: dict, key: str, default: Any = None) -> Any:
|
| 57 |
+
node = cfg
|
| 58 |
+
for p in key.split("."):
|
| 59 |
+
if not isinstance(node, dict) or p not in node:
|
| 60 |
+
return default
|
| 61 |
+
node = node[p]
|
| 62 |
+
return node
|
code/minijev/core/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .core import NEG, SCORERS, MiniJEVCore
|
| 2 |
+
|
| 3 |
+
__all__ = ["MiniJEVCore", "NEG", "SCORERS"]
|
code/minijev/core/__pycache__/__init__.cpython-314.pyc
ADDED
|
Binary file (292 Bytes). View file
|
|
|
code/minijev/core/__pycache__/core.cpython-314.pyc
ADDED
|
Binary file (8.33 kB). View file
|
|
|
code/minijev/core/__pycache__/layers.cpython-314.pyc
ADDED
|
Binary file (6.84 kB). View file
|
|
|
code/minijev/core/core.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""MiniJEV Core: the domain-agnostic decision network.
|
| 2 |
+
|
| 3 |
+
It only sees vectors in a shared latent space of width `d`:
|
| 4 |
+
|
| 5 |
+
state_tokens (B, S, d) + state_mask (B, S) from any StateEncoder (grid, text, numeric, ...)
|
| 6 |
+
question_tokens (B, Q, d) + question_mask (B, Q) from the question encoder
|
| 7 |
+
choice_emb (B, N, d) + choice_mask (B, N) from the ChoiceEncoder (N is dynamic)
|
| 8 |
+
|
| 9 |
+
and returns one logit per choice (+ value, scalar score and the CLS embedding).
|
| 10 |
+
It knows nothing about Snake, text, bytes or tokenizers.
|
| 11 |
+
|
| 12 |
+
[CLS] + question tokens + state tokens ──► Transformer ──► context H
|
| 13 |
+
│
|
| 14 |
+
scorer "cross": choices cross-attend H, then self-attend each other ─► Linear ─► logit_i
|
| 15 |
+
scorer "bi": logit_i = MLP([h, c_i, h*c_i]) (light cross scorer on pooled h = CLS)
|
| 16 |
+
scorer "fixed_head": Linear(CLS) -> max_choices logits (ablation: ignores choice meaning)
|
| 17 |
+
|
| 18 |
+
"cross" and "bi" are permutation-equivariant over choices (no positional information).
|
| 19 |
+
"""
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
from torch import nn
|
| 24 |
+
|
| 25 |
+
from .layers import DecisionBlock, EncoderBlock
|
| 26 |
+
|
| 27 |
+
NEG = -1e9
|
| 28 |
+
SCORERS = ("cross", "bi", "fixed_head")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class MiniJEVCore(nn.Module):
|
| 32 |
+
def __init__(self, d: int, n_layers: int, n_heads: int = 4, mlp_ratio: float = 4.0, dropout: float = 0.0,
|
| 33 |
+
n_decision_layers: int = 1, scorer: str = "cross", max_choices: int = 16):
|
| 34 |
+
super().__init__()
|
| 35 |
+
if scorer not in SCORERS:
|
| 36 |
+
raise ValueError(f"scorer must be one of {SCORERS}, got {scorer!r}")
|
| 37 |
+
self.d, self.scorer = d, scorer
|
| 38 |
+
self.cls = nn.Parameter(torch.zeros(1, 1, d))
|
| 39 |
+
self.type_emb = nn.Parameter(torch.zeros(3, d)) # cls / question / state
|
| 40 |
+
nn.init.normal_(self.type_emb, std=0.02)
|
| 41 |
+
self.blocks = nn.ModuleList(EncoderBlock(d, n_heads, mlp_ratio, dropout) for _ in range(n_layers))
|
| 42 |
+
self.ln_ctx = nn.LayerNorm(d)
|
| 43 |
+
if scorer == "cross":
|
| 44 |
+
self.decision = nn.ModuleList(DecisionBlock(d, n_heads, mlp_ratio, dropout)
|
| 45 |
+
for _ in range(n_decision_layers))
|
| 46 |
+
self.choice_head = nn.Sequential(nn.LayerNorm(d), nn.Linear(d, 1))
|
| 47 |
+
elif scorer == "bi":
|
| 48 |
+
self.ln_h, self.ln_c = nn.LayerNorm(d), nn.LayerNorm(d)
|
| 49 |
+
self.choice_head = nn.Sequential(nn.Linear(3 * d, d), nn.GELU(), nn.Linear(d, 1))
|
| 50 |
+
else:
|
| 51 |
+
self.choice_head = nn.Sequential(nn.LayerNorm(d), nn.Linear(d, max_choices))
|
| 52 |
+
self.value_head = nn.Sequential(nn.LayerNorm(d), nn.Linear(d, d), nn.GELU(), nn.Linear(d, 1))
|
| 53 |
+
# continuous 0..1 score for `model.score(state, question)` (trained with BCE when rows carry `score`)
|
| 54 |
+
self.scalar_head = nn.Sequential(nn.LayerNorm(d), nn.Linear(d, 1))
|
| 55 |
+
|
| 56 |
+
def encode_context(self, state_tokens, state_mask, question_tokens, question_mask):
|
| 57 |
+
B = question_tokens.shape[0]
|
| 58 |
+
parts = [self.cls.expand(B, -1, -1) + self.type_emb[0], question_tokens + self.type_emb[1]]
|
| 59 |
+
masks = [torch.ones(B, 1, dtype=torch.bool, device=question_tokens.device), question_mask]
|
| 60 |
+
if state_tokens is not None:
|
| 61 |
+
parts.append(state_tokens + self.type_emb[2])
|
| 62 |
+
masks.append(state_mask)
|
| 63 |
+
x, mask = torch.cat(parts, 1), torch.cat(masks, 1)
|
| 64 |
+
for blk in self.blocks:
|
| 65 |
+
x = blk(x, key_mask=mask)
|
| 66 |
+
return self.ln_ctx(x), mask
|
| 67 |
+
|
| 68 |
+
def score_choices(self, ctx, ctx_mask, choice_emb, choice_mask):
|
| 69 |
+
if self.scorer == "cross":
|
| 70 |
+
c = choice_emb
|
| 71 |
+
for blk in self.decision:
|
| 72 |
+
c = blk(c, ctx, ctx_mask, choice_mask)
|
| 73 |
+
logits = self.choice_head(c).squeeze(-1)
|
| 74 |
+
elif self.scorer == "bi":
|
| 75 |
+
h = self.ln_h(ctx[:, :1]).expand(-1, choice_emb.shape[1], -1)
|
| 76 |
+
c = self.ln_c(choice_emb)
|
| 77 |
+
logits = self.choice_head(torch.cat([h, c, h * c], -1)).squeeze(-1)
|
| 78 |
+
else:
|
| 79 |
+
logits = self.choice_head(ctx[:, 0])[:, : choice_emb.shape[1]]
|
| 80 |
+
return logits.float().masked_fill(~choice_mask, NEG)
|
| 81 |
+
|
| 82 |
+
def forward(self, state_tokens, state_mask, question_tokens, question_mask, choice_emb, choice_mask):
|
| 83 |
+
ctx, ctx_mask = self.encode_context(state_tokens, state_mask, question_tokens, question_mask)
|
| 84 |
+
cls = ctx[:, 0]
|
| 85 |
+
return {"logits": self.score_choices(ctx, ctx_mask, choice_emb, choice_mask),
|
| 86 |
+
"value": self.value_head(cls).squeeze(-1).float(),
|
| 87 |
+
"score": self.scalar_head(cls).squeeze(-1).float(), # logit; sigmoid -> 0..1
|
| 88 |
+
"embedding": cls, "choice_mask": choice_mask}
|
code/minijev/core/layers.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from torch import nn
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Attention(nn.Module):
|
| 9 |
+
"""Multi-head (self or cross) attention on top of SDPA; `key_mask` is bool (B, S), True = valid."""
|
| 10 |
+
|
| 11 |
+
def __init__(self, d: int, heads: int, dropout: float = 0.0):
|
| 12 |
+
super().__init__()
|
| 13 |
+
assert d % heads == 0, "d_model must be divisible by n_heads"
|
| 14 |
+
self.h, self.dh = heads, d // heads
|
| 15 |
+
self.q = nn.Linear(d, d)
|
| 16 |
+
self.kv = nn.Linear(d, 2 * d)
|
| 17 |
+
self.o = nn.Linear(d, d)
|
| 18 |
+
self.dropout = dropout
|
| 19 |
+
|
| 20 |
+
def forward(self, x, ctx=None, key_mask=None):
|
| 21 |
+
ctx = x if ctx is None else ctx
|
| 22 |
+
B, T, D = x.shape
|
| 23 |
+
S = ctx.shape[1]
|
| 24 |
+
q = self.q(x).view(B, T, self.h, self.dh).transpose(1, 2)
|
| 25 |
+
kv = self.kv(ctx).view(B, S, 2, self.h, self.dh).permute(2, 0, 3, 1, 4)
|
| 26 |
+
mask = key_mask[:, None, None, :] if key_mask is not None else None
|
| 27 |
+
out = F.scaled_dot_product_attention(q, kv[0], kv[1], attn_mask=mask,
|
| 28 |
+
dropout_p=self.dropout if self.training else 0.0)
|
| 29 |
+
return self.o(out.transpose(1, 2).reshape(B, T, D))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class MLP(nn.Module):
|
| 33 |
+
def __init__(self, d: int, ratio: float = 4.0, dropout: float = 0.0):
|
| 34 |
+
super().__init__()
|
| 35 |
+
hidden = int(d * ratio)
|
| 36 |
+
self.net = nn.Sequential(nn.Linear(d, hidden), nn.GELU(), nn.Linear(hidden, d), nn.Dropout(dropout))
|
| 37 |
+
|
| 38 |
+
def forward(self, x):
|
| 39 |
+
return self.net(x)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class EncoderBlock(nn.Module):
|
| 43 |
+
"""Pre-LN transformer block."""
|
| 44 |
+
|
| 45 |
+
def __init__(self, d, heads, mlp_ratio=4.0, dropout=0.0):
|
| 46 |
+
super().__init__()
|
| 47 |
+
self.ln1, self.ln2 = nn.LayerNorm(d), nn.LayerNorm(d)
|
| 48 |
+
self.attn = Attention(d, heads, dropout)
|
| 49 |
+
self.mlp = MLP(d, mlp_ratio, dropout)
|
| 50 |
+
|
| 51 |
+
def forward(self, x, key_mask=None):
|
| 52 |
+
h = self.ln1(x)
|
| 53 |
+
x = x + self.attn(h, key_mask=key_mask)
|
| 54 |
+
return x + self.mlp(self.ln2(x))
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class DecisionBlock(nn.Module):
|
| 58 |
+
"""Choices read the context (cross-attn), then compare with each other (self-attn).
|
| 59 |
+
|
| 60 |
+
No positional information over choices -> the block is permutation-equivariant:
|
| 61 |
+
reordering the choices reorders the scores, nothing else.
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
def __init__(self, d, heads, mlp_ratio=4.0, dropout=0.0):
|
| 65 |
+
super().__init__()
|
| 66 |
+
self.ln_q, self.ln_ctx = nn.LayerNorm(d), nn.LayerNorm(d)
|
| 67 |
+
self.cross = Attention(d, heads, dropout)
|
| 68 |
+
self.ln_s = nn.LayerNorm(d)
|
| 69 |
+
self.self_attn = Attention(d, heads, dropout)
|
| 70 |
+
self.ln_m = nn.LayerNorm(d)
|
| 71 |
+
self.mlp = MLP(d, mlp_ratio, dropout)
|
| 72 |
+
|
| 73 |
+
def forward(self, c, ctx, ctx_mask, choice_mask):
|
| 74 |
+
c = c + self.cross(self.ln_q(c), self.ln_ctx(ctx), key_mask=ctx_mask)
|
| 75 |
+
c = c + self.self_attn(self.ln_s(c), key_mask=choice_mask)
|
| 76 |
+
return c + self.mlp(self.ln_m(c))
|
code/minijev/datasets/__init__.py
ADDED
|
File without changes
|