Spaces:
Running on Zero

File size: 7,591 Bytes
0b82dba
 
 
 
 
 
 
 
 
 
 
b28f310
0b82dba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b28f310
 
 
 
 
88cc578
 
 
0b82dba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88cc578
 
 
 
 
 
b28f310
88cc578
 
0b82dba
 
88cc578
0b82dba
88cc578
 
b28f310
 
 
0b82dba
 
 
 
 
 
 
 
 
b28f310
 
 
 
 
88cc578
0b82dba
88cc578
b28f310
0b82dba
 
 
 
 
 
 
 
 
 
88cc578
0b82dba
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
"""
NextBoard move generation for the Space: the same computation as api.py.

The model generates the whole next board. Chess rules are used only afterwards,
to decide whether that board is a legal move and so whether to sample again.
Nothing here scores, filters or picks moves.

chess_model.py, samplers.py, chess_boards.py and illegal_moves.py are unchanged
copies of the project files.
"""
import json
import time
from dataclasses import dataclass
from pathlib import Path

import torch
from safetensors.torch import load_file
from tokenizers import Tokenizer

import samplers
from chess_boards import board_from_history, get_validated_move, tokens_to_board
from chess_model import ChessBERT, TrainingConfig
from illegal_moves import classify_board

WEIGHTS_FILE = "model.safetensors"
CONFIG_FILE = "config.json"
TOKENIZER_FILE = "tokenizer.json"

# Model-shape keys of config.json -> TrainingConfig attribute (as in api.py).
SHAPE_KEYS = (("HIDDEN_SIZE", "hidden_size"), ("NUM_LAYERS", "num_layers"),
              ("NUM_HEADS", "num_heads"), ("FF_DIM", "ff_dim"))
# Only written for checkpoints that store them; older ones use the class defaults.
OPTIONAL_KEYS = (("CONTEXT_SIZE", "context_size"), ("BLOCK_LEN", "block_len"))

# Squares revealed per model call. The Space reveals one square per step (64 calls per board), so
# every square is decided after the ones before it. api.py and the benchmarks use
# samplers.TAIL16_PLAN ([20, 16, 10, 6] then 12 single squares, 16 calls). Switched 2026-12-02.
PLAN = [1] * 64

# Temperature of the first attempt. The page's "start temperature" slider can raise it.
START_TEMPERATURE, MIN_TEMPERATURE, MAX_TEMPERATURE = 0.1, 0.1, 1.5


@dataclass
class Bundle:
    model: ChessBERT
    tokenizer: Tokenizer
    config: TrainingConfig
    mask_id: int
    pad_id: int
    device: str
    denoiser: samplers.Denoiser


def make_config(shape: dict, tokenizer: Tokenizer) -> TrainingConfig:
    """TrainingConfig for a checkpoint, built the way api.py builds it."""
    config = TrainingConfig()
    config.VOCAB_SIZE = tokenizer.get_vocab_size()
    config.MASK_TOKEN_ID = tokenizer.token_to_id("[MASK]")
    for attr, key in SHAPE_KEYS + OPTIONAL_KEYS:
        if shape.get(key) is not None:
            setattr(config, attr, int(shape[key]))
    config.BLOCK_CAUSAL = bool(shape.get("block_causal", False))  # "every board" models
    return config


def make_bundle(model: ChessBERT, tokenizer: Tokenizer, config: TrainingConfig, device: str) -> Bundle:
    model = model.to(device)
    model.eval()
    mask_id = tokenizer.token_to_id("[MASK]")
    denoiser = samplers.Denoiser(model, mask_id, amp=torch.float16 if device == "cuda" else None)
    return Bundle(model, tokenizer, config, mask_id, tokenizer.token_to_id("[PAD]"), device, denoiser)


def load_bundle(folder, device: str = "cpu") -> Bundle:
    """Loads an exported checkpoint folder (model.safetensors, config.json, tokenizer.json)."""
    folder = Path(folder)
    tokenizer = Tokenizer.from_file(str(folder / TOKENIZER_FILE))
    shape = json.loads((folder / CONFIG_FILE).read_text(encoding="utf-8"))
    config = make_config(shape, tokenizer)
    model = ChessBERT(config)
    model.load_state_dict(load_file(str(folder / WEIGHTS_FILE), device="cpu"))
    return make_bundle(model, tokenizer, config, device)


# --- prompt building: api.py's build_prompt_string / build_input_tensor ---
def build_prompt_string(history_tokens, outcome_token=None):
    """<ply> <result> <64 board tokens> per board, then <ply> <result> of the board to generate."""
    if outcome_token:
        outcome_token = outcome_token.lower()  # the page sends <WHITE>, the tokenizer has <white>
    prompt_parts = []
    for i, board_tokens in enumerate(history_tokens):
        prompt_parts.append(f"<{i}>")
        prompt_parts.append(outcome_token)
        prompt_parts.extend(board_tokens)
    prompt_parts.append(f"<{len(history_tokens)}>")
    prompt_parts.append(outcome_token)
    return " ".join(prompt_parts)


def build_input_tensor(bundle: Bundle, history_tokens, outcome_token):
    """Model input: the last boards of the game, then 64 masked squares."""
    ids = bundle.tokenizer.encode(build_prompt_string(history_tokens, outcome_token)).ids + [bundle.mask_id] * 64
    ids = ids[-bundle.config.CONTEXT_SIZE:]
    ids = [bundle.pad_id] * (bundle.config.CONTEXT_SIZE - len(ids)) + ids
    return torch.tensor([ids], dtype=torch.long, device=bundle.device)


# --- the attempt loop: api.py's board_attempts, without the disk log ---
def attempt_temperature(attempt: int, max_attempts: int, start: float = START_TEMPERATURE) -> float:
    """Temperature of attempt `attempt` (0-based): `start` on the first try, rising to 1.0 over
    max_attempts retries. A start of 1.0 or more stays constant."""
    return start + (attempt / max(max_attempts, 1)) * max(0.0, 1.0 - start)


def board_attempts(bundle: Bundle, history_tokens, outcome_token, max_attempts, seed=None,
                   plan=None, first_attempt=0, time_budget=None, temperature=START_TEMPERATURE,
                   argmax=False):
    """Yields one dict per generated board until one is a legal move.

    The first try uses `temperature` (default 0.1, as in the evaluation), retries slowly
    rise to 1.0. `seed` exists for tests only; play uses a fresh random seed.
    argmax (tests only): every square takes its most likely token instead of a sampled one, so
    the result does not depend on random numbers and can be compared with the browser engine.
    plan: squares revealed per model call (default PLAN). first_attempt / time_budget let a long
    run of retries continue in another GPU call: it starts at attempt index `first_attempt`
    (same temperature schedule) and stops after the first board that ends past `time_budget` s.
    """
    tokenizer = bundle.tokenizer
    original_board = board_from_history(history_tokens)
    x = build_input_tensor(bundle, history_tokens, outcome_token)
    gen = torch.Generator(device=bundle.device)
    if seed is None:
        gen.seed()
    else:
        gen.manual_seed(seed)
    plan = PLAN if plan is None else plan
    started = time.perf_counter()
    for attempt in range(first_attempt, max_attempts):
        if attempt > first_attempt and time_budget is not None and time.perf_counter() - started > time_budget:
            break
        temp = 0.0 if argmax else attempt_temperature(attempt, max_attempts, temperature)
        trace = []
        out = samplers.confidence_sampler(bundle.denoiser, x, gen, temp=temp, t_mode="sync",
                                          plan=plan, trace=trace)
        steps = []
        for step, (t, board) in enumerate(trace):
            row = board[0].tolist()
            steps.append({"step": step, "t": round(t, 3),
                          "board_tokens": [tokenizer.id_to_token(i) for i in row],
                          "masks_remaining": row.count(bundle.mask_id)})
        final_tokens = [tokenizer.id_to_token(i) for i in out.board[0].tolist()]
        new_board = tokens_to_board(final_tokens)
        move = get_validated_move(original_board, new_board)
        problem = None if move else classify_board(original_board, final_tokens)
        yield {"type": "attempt", "attempt": attempt + 1, "temperature": round(temp, 3),
               "steps": steps, "final_tokens": final_tokens,
               "final_fen": new_board.fen() if new_board else None,
               "valid": move is not None, "move": move.uci() if move else None, "problem": problem}
        if move is not None:
            break