Download engine.py from fmorgens/NextBoard: direct link, hf CLI and curl.
- Browser
- Download file 7.59 kB
-
https://huggingface.co/spaces/fmorgens/NextBoard/resolve/main/engine.py
- Command line
-
hf download hf://spaces/fmorgens/NextBoard/engine.py
-
curl -L -o engine.py https://huggingface.co/spaces/fmorgens/NextBoard/resolve/main/engine.py
7.59 kB
| """ | |
| 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 | |
| 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 | |