# SPDX-License-Identifier: AGPL-3.0-or-later """The Rook's bridge to Maia-3 (https://github.com/CSSLab/maia3, AGPL-3.0, University of Toronto CSSLab). Maia-3 predicts which move a human of a given rating plays in a position. Its own UCI wrapper reports the likeliest moves in order but not how likely each one is; this script asks the same model the same way and prints the whole distribution. It imports Maia-3's code, so it is under the same licence as Maia-3: AGPL-3.0. It is a separate process: The Rook's server talks to it over stdin/stdout in JSON lines and shares no code with it. python rook_maia.py [model] model: maia3-5m | maia3-23m | maia3-79m (default maia3-23m) In: {"id": 7, "fen": "", "history": ["", ...], "self": 1550, "oppo": 1550} history = the positions before this one, oldest first (up to 7 are used; none is fine). self / oppo = the rating of the side to move and of the other side, on the scale Maia-3 was trained on (Lichess). Out: {"id": 7, "moves": [["g8f6", 0.41], ["h7h6", 0.2], ...], "wdl": [win, draw, loss]} moves = every legal move with the probability that such a player plays it, likeliest first. wdl = how games between such players end from here, for the side to move. The first line printed is {"ready": true, "model": "..."}. """ import json import sys from collections import deque import chess import torch from maia3.dataset import get_legal_moves_mask, tokenize_board from maia3.uci import Maia3UCIEngine, parse_args from maia3.utils import seed_everything def answer(eng, cfg, req): board = chess.Board(req["fen"]) earlier = [chess.Board(f) for f in (req.get("history") or [])][-(cfg.history - 1):] eng.board = board eng.history = deque([tokenize_board(b) for b in earlier + [board]], maxlen=cfg.history) mask = get_legal_moves_mask(board, eng.all_moves_dict) if board.is_game_over() or not bool(mask.any()): return {"moves": [], "wdl": None} tokens = eng._tokens_from_history(eng.history).unsqueeze(0) self_elo = torch.tensor([int(req.get("self", 1500))], dtype=torch.long) oppo_elo = torch.tensor([int(req.get("oppo", 1500))], dtype=torch.long) with torch.no_grad(): logits_move, logits_value, _ = eng.model(tokens, self_elo, oppo_elo) logits = logits_move[0].float().masked_fill(~mask, float("-inf")) probs = torch.softmax(logits, dim=-1) loss, draw, win = torch.softmax(logits_value[0].float(), dim=-1).tolist() moves = [] for idx in torch.nonzero(mask).flatten().tolist(): move = eng._move_from_index(idx) if move is not None: moves.append([move.uci(), round(float(probs[idx]), 5)]) moves.sort(key=lambda m: -m[1]) return {"moves": moves, "wdl": [round(win, 4), round(draw, 4), round(loss, 4)]} def main(): model = sys.argv[1] if len(sys.argv) > 1 else "maia3-23m" # The weights are read from the local cache only: nothing is fetched while the app runs. cfg = parse_args(["--model", model, "--device", "cpu", "--no-use-amp", "--local-files-only"]) seed_everything(cfg.seed) torch.set_num_threads(4) eng = Maia3UCIEngine(cfg) eng.ensure_model_loaded() print(json.dumps({"ready": True, "model": model}), flush=True) for raw in sys.stdin: raw = raw.strip() if not raw: continue req = {} try: req = json.loads(raw) out = answer(eng, cfg, req) except Exception as exc: # a bad position must not stop the process out = {"error": str(exc)} out["id"] = req.get("id") print(json.dumps(out), flush=True) if __name__ == "__main__": main()