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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LM Tetris Arena — decoder-only LMs play Tetris zero-shot and earn Elo."""
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
# Keep the write token out of the environment before any model code runs:
|
| 5 |
+
# only the results store receives it (custom model code runs in this process).
|
| 6 |
+
_TOKEN = os.environ.pop("HF_TOKEN", None) or os.environ.pop("HUGGING_FACE_HUB_TOKEN", None)
|
| 7 |
+
os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1")
|
| 8 |
+
|
| 9 |
+
import html
|
| 10 |
+
import random
|
| 11 |
+
import time
|
| 12 |
+
|
| 13 |
+
import gradio as gr
|
| 14 |
+
import pandas as pd
|
| 15 |
+
import torch
|
| 16 |
+
|
| 17 |
+
from arena import MAX_PIECES, ResultsStore, choose, rank_games
|
| 18 |
+
from players import (BASELINES, MAX_PARAMS, ORACLE_ID, PROMPTS, RANDOM_ID, ModelRejected, OracleReaderPlayer,
|
| 19 |
+
RandomPlayer, fmt_params, load_player, precheck)
|
| 20 |
+
from render import CSS, arena_html, empty_html, results_html
|
| 21 |
+
from tetris import TetrisGame
|
| 22 |
+
|
| 23 |
+
# cpu-basic Spaces have 2 vCPUs; os.cpu_count() reports the host, which oversubscribes threads
|
| 24 |
+
torch.set_num_threads(int(os.environ.get("TORCH_THREADS", 2)))
|
| 25 |
+
|
| 26 |
+
RESULTS_REPO = os.environ.get("RESULTS_REPO", "DedeProGames/lm-tetris-arena-results")
|
| 27 |
+
MAX_MODELS = int(os.environ.get("MAX_MODELS", 4))
|
| 28 |
+
STORE = ResultsStore(RESULTS_REPO, _TOKEN)
|
| 29 |
+
|
| 30 |
+
SUGGESTED = [
|
| 31 |
+
"DedeProGames/Kiyo-65M",
|
| 32 |
+
"DedeProGames/Kiyo-230M-Preview",
|
| 33 |
+
"SupraLabs/SupraNeo-4M",
|
| 34 |
+
"BananaMind/BananaMind-2-Pro",
|
| 35 |
+
"BananaMind/BananaMind-2-Mini",
|
| 36 |
+
"DedeProGames/LowOnMind-5M",
|
| 37 |
+
"DedeProGames/DynamicMind-Mini",
|
| 38 |
+
"openai-community/gpt2",
|
| 39 |
+
"HuggingFaceTB/SmolLM2-135M",
|
| 40 |
+
"EleutherAI/pythia-70m",
|
| 41 |
+
"EleutherAI/pythia-160m",
|
| 42 |
+
"roneneldan/TinyStories-33M",
|
| 43 |
+
]
|
| 44 |
+
DEFAULT_MODELS = ["DedeProGames/Kiyo-65M", "SupraLabs/SupraNeo-4M", "BananaMind/BananaMind-2-Pro"]
|
| 45 |
+
PROTOCOL_CHOICES = [("Guided: the rules are in the prompt", "guided"), ("Blind: no rules, only pre-training knowledge", "blind")]
|
| 46 |
+
BASELINE_CHOICES = [(label, key) for key, label in BASELINES.items()]
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _status(text, kind="info"):
|
| 50 |
+
icon = {"info": "⏳", "ok": "✅", "err": "⛔", "warn": "⚠️"}[kind]
|
| 51 |
+
return f"{icon} {text}"
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def run_match(model_ids, baselines, protocol, ranked, seed, delay):
|
| 55 |
+
model_ids = [m.strip() for m in (model_ids or []) if m and m.strip()]
|
| 56 |
+
model_ids = list(dict.fromkeys(model_ids))
|
| 57 |
+
baselines = baselines or []
|
| 58 |
+
protocol = protocol or "guided"
|
| 59 |
+
if not model_ids:
|
| 60 |
+
yield _status("Pick at least one language model.", "err"), empty_html(), ""
|
| 61 |
+
return
|
| 62 |
+
if len(model_ids) > MAX_MODELS:
|
| 63 |
+
yield _status(f"At most {MAX_MODELS} language models per match on this CPU.", "err"), empty_html(), ""
|
| 64 |
+
return
|
| 65 |
+
if len(model_ids) + len(baselines) < 2:
|
| 66 |
+
yield _status("A match needs at least 2 players: add another model or a baseline.", "err"), empty_html(), ""
|
| 67 |
+
return
|
| 68 |
+
|
| 69 |
+
players = []
|
| 70 |
+
try:
|
| 71 |
+
metas = []
|
| 72 |
+
for m in model_ids:
|
| 73 |
+
yield _status(f"Checking `{m}`…"), empty_html("Checking models…"), ""
|
| 74 |
+
meta = precheck(m)
|
| 75 |
+
if any(x["id"] == meta["id"] for x in metas):
|
| 76 |
+
continue # same repo typed twice with different casing
|
| 77 |
+
metas.append(meta)
|
| 78 |
+
model_ids = [x["id"] for x in metas]
|
| 79 |
+
for i, (m, meta) in enumerate(zip(model_ids, metas), 1):
|
| 80 |
+
yield _status(f"Loading `{m}` on CPU ({i}/{len(model_ids)})… first load downloads the weights."), empty_html("Loading models…"), ""
|
| 81 |
+
players.append(load_player(m, meta))
|
| 82 |
+
except ModelRejected as e:
|
| 83 |
+
yield _status(str(e), "err"), empty_html("Match cancelled."), ""
|
| 84 |
+
return
|
| 85 |
+
if RANDOM_ID in baselines:
|
| 86 |
+
players.append(RandomPlayer())
|
| 87 |
+
if ORACLE_ID in baselines:
|
| 88 |
+
players.append(OracleReaderPlayer())
|
| 89 |
+
|
| 90 |
+
if ranked:
|
| 91 |
+
seed = random.SystemRandom().randrange(1, 10**9)
|
| 92 |
+
else:
|
| 93 |
+
seed = int(seed or 0)
|
| 94 |
+
games = [TetrisGame(seed) for _ in players]
|
| 95 |
+
mode = "ranked" if ranked else "unranked"
|
| 96 |
+
yield _status(f"Seed {seed} · {protocol} · {mode}. Scoring the first moves…"), arena_html(games, players), ""
|
| 97 |
+
|
| 98 |
+
last = time.time()
|
| 99 |
+
try:
|
| 100 |
+
while True:
|
| 101 |
+
active = [(g, p) for g, p in zip(games, players) if g.alive and g.pieces < MAX_PIECES]
|
| 102 |
+
if not active:
|
| 103 |
+
break
|
| 104 |
+
for g, p in active:
|
| 105 |
+
choose(g, p, protocol, seed)
|
| 106 |
+
elapsed = time.time() - last
|
| 107 |
+
if elapsed < delay:
|
| 108 |
+
time.sleep(delay - elapsed)
|
| 109 |
+
last = time.time()
|
| 110 |
+
n = max(g.pieces for g in games)
|
| 111 |
+
alive = sum(g.alive for g in games)
|
| 112 |
+
yield _status(f"Seed {seed} · {protocol} · {mode} · piece {n}/{MAX_PIECES} · {alive} still playing"), arena_html(games, players), ""
|
| 113 |
+
except ModelRejected as e:
|
| 114 |
+
yield _status(str(e), "err"), arena_html(games, players), ""
|
| 115 |
+
return
|
| 116 |
+
except Exception as e:
|
| 117 |
+
yield _status(f"A model crashed during play: {type(e).__name__}: {str(e)[:200]}", "err"), arena_html(games, players), ""
|
| 118 |
+
return
|
| 119 |
+
|
| 120 |
+
ranks = rank_games(games)
|
| 121 |
+
order = sorted(range(len(players)), key=lambda i: ranks[i])
|
| 122 |
+
elos = None
|
| 123 |
+
note = ""
|
| 124 |
+
if ranked:
|
| 125 |
+
match = STORE.record(protocol, seed, players, games)
|
| 126 |
+
elos = [(pp["elo_before"], pp["elo_after"]) for pp in match["players"]]
|
| 127 |
+
if STORE.persistent and not STORE.save_error:
|
| 128 |
+
note = f'Elo updated and saved to the public leaderboard (<a href="https://huggingface.co/datasets/{RESULTS_REPO}" target="_blank">{RESULTS_REPO}</a>).'
|
| 129 |
+
elif STORE.persistent:
|
| 130 |
+
note = f"⚠️ Elo updated in memory, but {html.escape(STORE.save_error)}."
|
| 131 |
+
else:
|
| 132 |
+
note = "⚠️ Elo updated in memory only: the Space has no <code>HF_TOKEN</code> secret, so results are not saved."
|
| 133 |
+
else:
|
| 134 |
+
note = "Unranked match: Elo not changed."
|
| 135 |
+
|
| 136 |
+
note += f" Ranking: score, then lines, then pieces survived. ✓ = still alive at the {MAX_PIECES}-piece cap."
|
| 137 |
+
results = results_html(order, ranks, players, games, elos, note)
|
| 138 |
+
yield _status(f"Match finished · seed {seed} · {protocol}.", "ok"), arena_html(games, players, ranks, elos), results
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def leaderboard_df(protocol):
|
| 142 |
+
rows = []
|
| 143 |
+
for i, e in enumerate(STORE.rows(protocol or "guided"), 1):
|
| 144 |
+
mid = e["model"]
|
| 145 |
+
name = BASELINES.get(mid) or f"[{mid}](https://huggingface.co/{mid})"
|
| 146 |
+
g = max(1, e["games"])
|
| 147 |
+
rows.append([
|
| 148 |
+
i, name, round(e["elo"]), e["games"], e["wins"],
|
| 149 |
+
round(e["total_pieces"] / g, 1), round(e["total_lines"] / g, 1), e["best_score"],
|
| 150 |
+
"–" if mid in BASELINES else fmt_params(e.get("params")),
|
| 151 |
+
])
|
| 152 |
+
cols = ["#", "Model", "Elo", "Games", "1st places", "Avg pieces", "Avg lines", "Best score", "Params"]
|
| 153 |
+
return pd.DataFrame(rows, columns=cols)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def refresh_leaderboard(protocol):
|
| 157 |
+
STORE.reload()
|
| 158 |
+
return leaderboard_df(protocol)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
INTRO = f"""
|
| 162 |
+
# 🧱 LM Tetris Arena
|
| 163 |
+
Small **decoder-only language models** (≤ {fmt_params(MAX_PARAMS)} parameters, custom architectures welcome) play Tetris
|
| 164 |
+
**zero-shot**: no fine-tuning, no game data, only what they learned from pre-training on text.
|
| 165 |
+
All players get the **same piece sequence** (same seed). Ranked matches update a public **Elo** leaderboard.
|
| 166 |
+
"""
|
| 167 |
+
|
| 168 |
+
HOW = f"""
|
| 169 |
+
### How a model plays
|
| 170 |
+
For every new piece the game lists all legal placements (rotation × column, hard drop), simulates each one and
|
| 171 |
+
describes the outcome in plain English. The model never sees the grid; it judges the descriptions:
|
| 172 |
+
|
| 173 |
+
```
|
| 174 |
+
{PROMPTS['guided'].format(desc='drops the piece into the lowest part of the board, clears one line, creates no new holes, keeps the stack low and leaves the surface flat')}
|
| 175 |
+
```
|
| 176 |
+
|
| 177 |
+
The model's value for a placement is **log P(" good move") − log P(" bad move")** after that prompt. The placement with the
|
| 178 |
+
highest value is played; exact ties are broken by a seeded coin that is identical for every player.
|
| 179 |
+
Because the value is a difference, a model's general bias towards "good" or "bad" cancels out.
|
| 180 |
+
|
| 181 |
+
### Protocols (separate leaderboards)
|
| 182 |
+
- **Guided**: the first line states the goal ("clear lines, avoid holes, keep the stack low"). Tests reading comprehension.
|
| 183 |
+
- **Blind**: `{PROMPTS['blind'].splitlines()[0]}` No rules; the model must already know what is good in Tetris.
|
| 184 |
+
|
| 185 |
+
### Rules of a match
|
| 186 |
+
- 2+ players, up to {MAX_MODELS} language models per match, plus optional baselines.
|
| 187 |
+
- Same 7-bag piece sequence for everyone. The game ends at top-out or after {MAX_PIECES} pieces.
|
| 188 |
+
- Placement = score (100/300/500/800 for 1/2/3/4 lines), then lines, then pieces survived.
|
| 189 |
+
- **Ranked** matches use a random seed and update Elo (K=32, multiplayer: every pair of players counts as a game, scaled by 1/(N−1)).
|
| 190 |
+
Unranked matches let you pick the seed and change nothing.
|
| 191 |
+
|
| 192 |
+
### Baselines
|
| 193 |
+
- **🎲 Random**: every placement ties, so it plays uniformly at random. This is the floor a model should beat.
|
| 194 |
+
- **📏 Oracle reader**: reads the same descriptions and ranks them with fixed common sense (holes > lines > height > surface > landing).
|
| 195 |
+
This is roughly the ceiling for a perfect reader of the text.
|
| 196 |
+
|
| 197 |
+
### Model requirements
|
| 198 |
+
Public, not gated, loads with `AutoModelForCausalLM` + `AutoTokenizer` (PyTorch or safetensors weights), ≤ {fmt_params(MAX_PARAMS)} parameters.
|
| 199 |
+
Models with custom code (`auto_map`) load with `trust_remote_code=True`. That code runs on this Space's CPU, so only
|
| 200 |
+
submit repos you trust. Prompts are in English (the language most pre-training corpora such as FineWeb-edu use).
|
| 201 |
+
|
| 202 |
+
Results and every match (seed, commit SHA of each model, scores) are published in
|
| 203 |
+
[`{RESULTS_REPO}`](https://huggingface.co/datasets/{RESULTS_REPO}).
|
| 204 |
+
"""
|
| 205 |
+
|
| 206 |
+
with gr.Blocks(title="LM Tetris Arena") as demo:
|
| 207 |
+
gr.Markdown(INTRO)
|
| 208 |
+
if not STORE.persistent:
|
| 209 |
+
gr.Markdown("⚠️ **Results are not being saved**: add an `HF_TOKEN` secret with write access to the results dataset.")
|
| 210 |
+
with gr.Tabs():
|
| 211 |
+
with gr.Tab("⚔️ Match"):
|
| 212 |
+
with gr.Row():
|
| 213 |
+
with gr.Column(scale=3):
|
| 214 |
+
models = gr.Dropdown(
|
| 215 |
+
choices=SUGGESTED, value=DEFAULT_MODELS, multiselect=True, allow_custom_value=True,
|
| 216 |
+
max_choices=MAX_MODELS, label=f"Language models (1–{MAX_MODELS})",
|
| 217 |
+
info="Pick from the list or type any Hub repo id (owner/name) and press Enter.",
|
| 218 |
+
)
|
| 219 |
+
baselines = gr.CheckboxGroup(BASELINE_CHOICES, value=[RANDOM_ID], label="Baselines (optional, also rated)")
|
| 220 |
+
with gr.Column(scale=2):
|
| 221 |
+
protocol = gr.Radio(PROTOCOL_CHOICES, value="guided", label="Protocol")
|
| 222 |
+
with gr.Row():
|
| 223 |
+
ranked = gr.Checkbox(value=True, label="Ranked (random seed, updates Elo)")
|
| 224 |
+
seed = gr.Number(value=42, precision=0, label="Seed (unranked only)")
|
| 225 |
+
delay = gr.Slider(0, 0.5, value=0.12, step=0.02, label="Seconds per piece (viewing speed)")
|
| 226 |
+
with gr.Row():
|
| 227 |
+
start = gr.Button("▶ Start match", variant="primary")
|
| 228 |
+
stop = gr.Button("■ Stop", variant="stop")
|
| 229 |
+
status = gr.Markdown(_status("Ready.", "ok"))
|
| 230 |
+
boards = gr.HTML(empty_html())
|
| 231 |
+
results = gr.HTML()
|
| 232 |
+
with gr.Tab("🏆 Leaderboard"):
|
| 233 |
+
lb_protocol = gr.Radio(PROTOCOL_CHOICES, value="guided", label="Protocol")
|
| 234 |
+
lb = gr.Dataframe(
|
| 235 |
+
value=leaderboard_df("guided"), interactive=False, wrap=True,
|
| 236 |
+
datatype=["number", "markdown", "number", "number", "number", "number", "number", "number", "str"],
|
| 237 |
+
)
|
| 238 |
+
lb_refresh = gr.Button("↻ Refresh")
|
| 239 |
+
with gr.Tab("📖 How it works"):
|
| 240 |
+
gr.Markdown(HOW)
|
| 241 |
+
|
| 242 |
+
match_event = start.click(
|
| 243 |
+
run_match, [models, baselines, protocol, ranked, seed, delay], [status, boards, results], concurrency_limit=1,
|
| 244 |
+
)
|
| 245 |
+
stop.click(lambda: _status("Match stopped. Nothing was recorded.", "warn"), None, status, cancels=[match_event])
|
| 246 |
+
match_event.then(leaderboard_df, lb_protocol, lb)
|
| 247 |
+
lb_protocol.change(leaderboard_df, lb_protocol, lb)
|
| 248 |
+
lb_refresh.click(refresh_leaderboard, lb_protocol, lb)
|
| 249 |
+
demo.load(leaderboard_df, lb_protocol, lb)
|
| 250 |
+
|
| 251 |
+
demo.queue(max_size=32)
|
| 252 |
+
|
| 253 |
+
if __name__ == "__main__":
|
| 254 |
+
demo.launch(css=CSS, theme=gr.themes.Soft(primary_hue="violet"), ssr_mode=False)
|