jev-skills / code /play_bench.py
qmichalwarda's picture
play_bench: generic python decider hook
fda80b2 verified
Raw History Blame Contribute Delete
11.4 kB
"""Closed-loop game simulations driven by any `decide(state, questions) -> answers` callable (the System One call).
The method of a Snake race: the game code works out what each move would do and words it; the model
answers one yes/no question per move; the move with the highest P(yes) is played. Two framings, as in JevSpatial:
q the consequence is written INSIDE each question ("Moving up: the snake moves closer to the food. Should the snake
move up?"), minimal status state;
s the consequences are in the STATE ({"if the snake moves up": ...}), plain questions ("Is moving up a good move?").
Games (toy physics, fixed seeds, endless: a crash restarts the game): Snake 12x12, Dino, Breakout, Whac-A-Mole.
Reported per game and framing, over N decisions: apples (Snake), obstacles cleared (Dino), bricks (Breakout), moles
(Whac-A-Mole), the failures, and the median decision latency in ms. Wording and consequences come from
spatial_bench.py.
# any Python decider: module.path:factory, factory() returns an object with .decide(state, questions) or a function:
python play_bench.py --decider python --decider-target my_module:make_decider --decisions 300
# a /v1/systemone server (any server speaking the same protocol):
python play_bench.py --decider http --url http://127.0.0.1:8017 --decisions 300
# references: --decider oracle (always the best move), --decider random
"""
import argparse
import json
import random
import statistics
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT))
import spatial_bench as S # noqa: E402
GAMES = ("Snake", "Dino", "Breakout", "Whac-A-Mole")
# ------------------------------------------------------------------ environments
class Snake:
name, n = "Snake", 12
def __init__(self, seed):
self.rng = random.Random(seed)
self.m = {"apples": 0, "deaths": 0}
self.reset()
def reset(self):
c = (self.n // 2, self.n // 2)
self.walk = [(c[0], c[1] - 2), (c[0], c[1] - 1), c]
self.age = 0
self.spawn()
def spawn(self):
free = [(r, c) for r in range(self.n) for c in range(self.n) if (r, c) not in self.walk]
self.food = self.rng.choice(free)
def sit(self):
moves = S.snake_moves(self.walk, self.food, self.n)
status = {"game": "Snake", "board": f"{self.n}x{self.n}", "length": len(self.walk),
"apples eaten": len(self.walk) - 3, "turn": self.age}
return {"game": "Snake", "unit": "the snake", "status": status, "moves": moves}
def act(self, mid):
self.age += 1
dr, dc = S.DIRS[mid]
h = self.walk[-1]
new = (h[0] + dr, h[1] + dc)
if not (0 <= new[0] < self.n and 0 <= new[1] < self.n) or new in self.walk[1:] or self.age > 600:
self.m["deaths"] += 1
return self.reset()
self.walk.append(new)
if new == self.food:
self.m["apples"] += 1
self.spawn()
else:
self.walk.pop(0)
class Dino:
name, v, lo = "Dino", 8, 34
def __init__(self, seed):
self.rng = random.Random(seed)
self.m = {"obstacles_cleared": 0, "crashes": 0}
self.obs = [] # [distance of the front edge, kind]
self.busy = 0
self.score = 0
self.fill()
def fill(self):
last = self.obs[-1][0] if self.obs else 150
while len(self.obs) < 3:
last += self.rng.randint(150, 260)
self.obs.append([last, self.rng.choice(list(S.DINO_OBS))])
def phase(self):
if not self.obs or self.obs[0][0] >= 160:
return "clear", "clear"
d, kind = self.obs[0]
return ("now" if d < self.lo + self.v else "far"), kind
def advance(self):
for o in self.obs:
o[0] -= self.v
self.score += 1
def settle(self):
"""Obstacles that reached the dinosaur without an action hit it."""
while self.obs and self.obs[0][0] < self.lo:
self.m["crashes"] += 1
self.obs.pop(0)
self.fill()
def sit(self):
ph, kind = self.phase()
moves = S.dino_moves(kind, ph)
status = {"game": "Dino", "score": self.score, "speed": "medium"}
return {"game": "Dino", "unit": "the dinosaur", "status": status, "moves": moves}
def act(self, mid):
ph, kind = self.phase()
need = "run" if ph != "now" else ("duck" if S.DINO_OBS[kind] == "high" else "jump")
if ph == "now":
self.obs.pop(0)
self.m["obstacles_cleared" if mid == need else "crashes"] += 1
self.fill()
elif mid != need: # acted too early: busy for a few ticks, obstacles keep coming
for _ in range(6):
self.advance()
self.settle()
return
self.advance()
self.settle()
class Breakout:
name, W, w, step = "Breakout", 200, 40, 20
def __init__(self, seed):
self.rng = random.Random(seed)
self.m = {"bricks": 0, "balls_lost": 0}
self.p = 100
self.launch()
def launch(self):
self.t = self.rng.randint(5, 9)
reach = (self.t - 1) * self.step
self.x = min(self.W - 10, max(10, self.p + self.rng.randint(-reach, reach)))
def sit(self):
moves = S.breakout_moves(self.p, self.x, self.w, self.step, self.W)
status = {"game": "Breakout", "lives": 3, "bricks left": 40 - self.m["bricks"] % 40}
return {"game": "Breakout", "unit": "the paddle", "status": status, "moves": moves}
def act(self, mid):
d = {"left": -1, "stay": 0, "right": 1}[mid]
self.p = min(self.W - self.w // 2, max(self.w // 2, self.p + d * self.step))
self.t -= 1
if self.t == 0:
self.m["bricks" if abs(self.p - self.x) <= self.w // 2 else "balls_lost"] += 1
self.launch()
class Mole:
name = "Whac-A-Mole"
def __init__(self, seed):
self.rng = random.Random(seed)
self.m = {"moles": 0, "bombs_hit": 0, "empty_swings": 0}
self.kinds = {}
def sit(self):
while True:
s = S.mole_sit(self.rng)
if s:
break
self.kinds = {m["id"]: ("mole" if m["good"] else "bomb" if m["rank"] == 0 else "empty") for m in s["moves"]}
return s
def act(self, mid):
k = self.kinds[mid]
self.m["moles" if k == "mole" else "bombs_hit" if k == "bomb" else "empty_swings"] += 1
ENVS = {"Snake": Snake, "Dino": Dino, "Breakout": Breakout, "Whac-A-Mole": Mole}
# ------------------------------------------------------------------ deciders
def p_yes(a) -> float:
"""P(yes) from a System One noul answer ({"noul": p}, or a probabilities / probability variant)."""
if isinstance(a, (int, float)):
return float(a)
if isinstance(a, dict):
for k in ("noul", "probability", "p_yes", "yes"):
if k in a:
return float(a[k])
pr = a.get("probabilities")
if isinstance(pr, dict):
for k in ("true", "yes", "True"):
if k in pr:
return float(pr[k])
raise ValueError(f"no P(yes) in {a!r}")
def make_python(target):
"""`module.path:factory`: import the module, call factory(); use the result's .decide(state, questions), or the
result itself when it is a function."""
import importlib
import os
sys.path.insert(0, os.getcwd())
mod, _, name = target.partition(":")
if not name:
raise SystemExit("--decider-target must look like module.path:factory")
obj = getattr(importlib.import_module(mod), name)()
return obj.decide if hasattr(obj, "decide") else obj
def make_http(url="http://127.0.0.1:8017", key=None, model="jev-latest", timeout=30):
import urllib.request
def decide(state, questions):
req = urllib.request.Request(url.rstrip("/") + "/v1/systemone", method="POST",
data=json.dumps({"model": model, "state": state, "questions": questions}).encode(),
headers={"Content-Type": "application/json",
**({"Authorization": f"Bearer {key}"} if key else {})})
out = json.load(urllib.request.urlopen(req, timeout=timeout))
for wrap in ("answers", "results", "output"): # tolerate an envelope around the {question id: answer} map
if isinstance(out, dict) and wrap in out and isinstance(out[wrap], dict) and set(questions) <= set(out[wrap]):
return out[wrap]
return out
return decide
def make_random(seed=0):
rng = random.Random(seed)
return lambda state, questions: {k: {"type": "noul", "noul": rng.random()} for k in questions}
# ------------------------------------------------------------------ the loop
def play(game: str, framing: str, decide, decisions: int, seed: int = 0, oracle: bool = False) -> dict:
env = ENVS[game](seed)
rng = random.Random(f"{seed}:frame")
lat = []
t_all = time.perf_counter()
for i in range(decisions):
sit = env.sit()
item = (S.render_q if framing == "q" else S.render_s)(sit, rng, i)
keys = [m["id"] for m in sit["moves"]]
if oracle:
mid = max(sit["moves"], key=lambda m: m["rank"])["id"]
else:
t = time.perf_counter()
ans = decide(item["state"], {k: q for k, q in item["questions"].items() if k in keys})
lat.append((time.perf_counter() - t) * 1000)
mid = max(keys, key=lambda k: p_yes(ans[k]))
env.act(mid)
out = {"game": game, "framing": framing, "decisions": decisions, **env.m,
"median_decision_ms": round(statistics.median(lat), 2) if lat else None,
"wall_s": round(time.perf_counter() - t_all, 2)}
return out
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--decider", choices=["python", "http", "oracle", "random"], default="python")
ap.add_argument("--decider-target", default=None, help="module.path:factory for --decider python")
ap.add_argument("--url", default="http://127.0.0.1:8017")
ap.add_argument("--key", default=None)
ap.add_argument("--decisions", type=int, default=300, help="decisions per game and framing")
ap.add_argument("--games", default=",".join(GAMES))
ap.add_argument("--framings", default="q,s")
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--out", default=None)
a = ap.parse_args()
decide = {"python": lambda: make_python(a.decider_target), "http": lambda: make_http(a.url, a.key),
"random": make_random, "oracle": lambda: None}[a.decider]()
if decide is not None and a.decider != "random": # warm-up: compile / load outside the timed loop
play("Snake", "q", decide, 3, seed=999)
rows = []
for g in a.games.split(","):
for f in a.framings.split(","):
r = play(g, f, decide, a.decisions, a.seed, oracle=a.decider == "oracle")
rows.append(r)
print(json.dumps(r), flush=True)
if a.out:
json.dump(rows, open(a.out, "w"), indent=1)
if __name__ == "__main__":
main()