Geoo/THX-01-bucket / doom /bench_doom.py
Geoo's picture
download
raw
7.38 kB
"""Headless Doom benchmark + GIF recorder for THX-01.
python doom/bench_doom.py --model doofz/THX-01 --episodes 10 --out results/doom.json
python doom/bench_doom.py --model doofz/THX-01 --gif release/assets/doom.gif --gif-seconds 20
"""
import argparse, json, os, random, sys, time
from collections import Counter, deque
import numpy as np
from PIL import Image, ImageDraw, ImageFont
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import doom_live as D
FONT = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
FONT_B = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
FONT_M = "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf"
def font(p, s):
try:
return ImageFont.truetype(p, s)
except OSError:
return ImageFont.load_default()
F = {"t": font(FONT_B, 22), "s": font(FONT, 13), "h": font(FONT_B, 13), "m": font(FONT_M, 12), "b": font(FONT_B, 15)}
ORDER = ["ATTACK", "TURN_LEFT", "TURN_RIGHT", "MOVE_FORWARD", "MOVE_LEFT", "MOVE_RIGHT", "MOVE_BACKWARD"]
def compose(screen, ev):
W, H = 1040, 480
img = Image.new("RGB", (W, H), (14, 14, 13))
img.paste(Image.fromarray(screen), (0, 0))
d = ImageDraw.Draw(img)
x = 656
d.text((x, 12), "THX-01 plays Doom", font=F["t"], fill=(244, 243, 238))
d.text((x, 42), "no vision · no text generation · 1 forward pass", font=F["s"], fill=(150, 148, 140))
d.text((x, 74), "CHOICE · next action", font=F["h"], fill=(120, 170, 240))
y = 98
for k in ORDER:
if k not in ev["probs"]:
continue
p = ev["probs"][k]; on = k == ev["action"]
d.text((x, y), k, font=F["m"], fill=(244, 243, 238) if on else (150, 148, 140))
d.rounded_rectangle((x + 118, y + 3, x + 318, y + 13), 5, fill=(43, 43, 41))
d.rounded_rectangle((x + 118, y + 3, x + 118 + max(4, int(200 * p)), y + 13), 5,
fill=(57, 135, 229) if on else (110, 108, 102))
d.text((x + 326, y), f"{100 * p:3.0f}%", font=F["m"], fill=(200, 198, 190))
y += 22
y += 8
d.text((x, y), "NOUL · enemy in crosshair?", font=F["h"], fill=(120, 170, 240)); y += 24
t = ev["threat"]
d.rounded_rectangle((x, y + 2, x + 318, y + 16), 7, fill=(43, 43, 41))
d.rounded_rectangle((x, y + 2, x + max(6, int(318 * t)), y + 16), 7, fill=(230, 103, 103))
d.text((x + 326, y + 1), f"{100 * t:3.0f}%", font=F["m"], fill=(200, 198, 190)); y += 30
why = "noul ≥ 0.5 → fire" if ev["action"] == "ATTACK" and ev["threat"] >= 0.5 else "top choice"
d.text((x, y), f"KEY PRESSED: {ev['action']} ({why})", font=F["b"], fill=(120, 200, 150)); y += 26
d.text((x, y), f"{ev['latency_ms']:.1f} ms / decision · health {ev['hp']:.0f} · kills {ev['kills']:.0f}",
font=F["b"], fill=(244, 243, 238)); y += 30
d.text((x, y), "STATE · what the model reads", font=F["h"], fill=(120, 170, 240)); y += 22
for line in ev["state"].split("\n"):
while line:
d.text((x, y), line[:52], font=F["m"], fill=(200, 198, 190)); y += 16; line = line[52:]
if y > H - 30:
break
d.text((x, H - 22), "RTX 4090 · 0 output tokens · no Doom data in training", font=F["s"], fill=(120, 118, 110))
return img
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--model", default="doofz/THX-01")
ap.add_argument("--scenarios", default="defend_the_center,defend_the_line,basic,deadly_corridor")
ap.add_argument("--episodes", type=int, default=10)
ap.add_argument("--out", default="")
ap.add_argument("--gif", default="")
ap.add_argument("--gif-scenario", default="defend_the_center")
ap.add_argument("--gif-seconds", type=float, default=14)
ap.add_argument("--skill", type=int, default=2)
a = ap.parse_args()
import vizdoom as vzd
agent = D.load_agent(a.model)
if a.gif:
frames = []
g = D.Game(agent, a.gif_scenario, a.skill, 4, realtime=False)
limit = int(a.gif_seconds * 35)
def grab(screen, ev):
if len(frames) < limit:
frames.append((screen, ev))
g.on_frame = grab
g.start()
while len(frames) < limit:
time.sleep(0.2)
g.on_frame = None
pal = [compose(sc, ev).resize((780, 360), Image.LANCZOS).convert("P", palette=Image.ADAPTIVE, colors=96)
for sc, ev in frames[::3]]
pal[0].save(a.gif, save_all=True, append_images=pal[1:], duration=int(3000 / 35), loop=0, optimize=True)
print("gif", a.gif, len(pal), "frames", os.path.getsize(a.gif) // 1024, "KB")
os._exit(0)
res = {}
for scen in a.scenarios.split(","):
for policy in ("thx01", "random"):
g = D.Game(agent, scen, a.skill, 4, realtime=False)
game = g._make_game(vzd)
buttons = [b.name for b in game.get_available_buttons()]
crit = {k: v for k, v in D.ACTIONS.items() if k in buttons}
if scen in D.IDLE and D.IDLE[scen][0] in crit:
crit[D.IDLE[scen][0]] += D.IDLE[scen][1]
q = {"action": {"type": "choice", "instructions": D.INSTRUCTION, "criteria": crit},
"threat": {"type": "noul", "instructions": D.THREAT}}
rng = random.Random(0)
eps, lats, acts = [], [], Counter()
for e in range(a.episodes):
game.set_seed(1000 + e); game.new_episode()
hist, last, steps = deque(maxlen=4), None, 0
while not game.is_episode_finished():
st = game.get_state()
me = next((o for o in st.objects if o.name == "DoomPlayer"), None)
pos = (round(me.position_x), round(me.position_y)) if me else None
stuck = bool(pos and pos == last and hist and hist[-1].startswith("MOVE")); last = pos
if policy == "thx01":
text, _, _ = D.describe(game, st, list(hist), stuck, vzd)
t0 = time.perf_counter()
act = D.policy(agent.predict(text, q)["answers"], crit)
lats.append((time.perf_counter() - t0) * 1000)
else:
act = rng.choice(list(crit))
hist.append(act); acts[act] += 1; steps += 1
vec = [0] * len(buttons); vec[buttons.index(act)] = 1
game.make_action(vec, 4)
eps.append({"kills": game.get_game_variable(vzd.GameVariable.KILLCOUNT),
"reward": game.get_total_reward(), "steps": steps})
game.close()
r = {"kills_mean": float(np.mean([x["kills"] for x in eps])), "kills_std": float(np.std([x["kills"] for x in eps])), "reward_mean": float(np.mean([x["reward"] for x in eps])),
"steps_mean": float(np.mean([x["steps"] for x in eps])), "episodes": len(eps), "actions": dict(acts)}
if lats:
r["latency_p50_ms"] = float(np.percentile(lats, 50))
res.setdefault(scen, {})[policy] = r
print(scen, policy, flush=True) or print(scen, policy, {k: (round(v, 2) if isinstance(v, float) else v) for k, v in r.items() if k != "actions"}, flush=True)
if a.out:
json.dump(res, open(a.out, "w"), indent=1)
os._exit(0)
if __name__ == "__main__":
main()

Xet Storage Details

Size:
7.38 kB
·
Xet hash:
77aee6c3f40aa6eed6c7aa9b4fcf23f782be31864aca9bc4defdd6e8c6d0685f

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.