OpenPawn bot service, licensed under the GNU AGPL, version 3 (see /licenses/agpl-3.0.txt). It runs Maia-3 from https://github.com/CSSLab/maia3 with the weights from https://huggingface.co/UofTCSSLab/Maia3-5M. Every file of the service follows. ==> services/maia/Dockerfile <== # The bot inference service. The model is not in the image: it's mounted # read-only at /models (see docs/deploy.md, Human-like bots). FROM python:3.13-slim WORKDIR /srv COPY build-requirements.txt requirements.txt ./ # Every package is checked against its pinned hash. chess comes as source, so # it builds with the pinned setuptools, which is removed again afterwards. RUN pip install --no-cache-dir --require-hashes -r build-requirements.txt \ && pip install --no-cache-dir --require-hashes --no-build-isolation -r requirements.txt \ && pip uninstall --yes setuptools COPY LICENSE encode.py server.py ./ ENV PYTHONDONTWRITEBYTECODE=1 \ PYTHONUNBUFFERED=1 \ OMP_NUM_THREADS=1 USER nobody EXPOSE 8080 CMD ["python", "server.py"] ==> services/maia/build-requirements.txt <== # chess is published as source only. It is built with this setuptools, pinned # by hash like the rest, rather than whatever is newest on the day. setuptools==84.2.1 \ --hash=sha256:3ff8b3b5492a0aa66960f4419365a86b84e013070d4313e4d4a6894f5d64d6bc \ --hash=sha256:ca140b45d5325a9478f880e351484f62fef15f336462e449ca0c03c873d589c2 ==> services/maia/contract.json <== { "comment": "One request and the shape of its answer, shared by the app's tests and the service's tests.", "app": { "fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", "moves": ["e2e4", "e7e5", "g1f3"], "band": 1100 }, "service": { "fen": "rnbqkbnr/pppp1ppp/8/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2", "history": [ "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1", "rnbqkbnr/pppp1ppp/8/4p3/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2" ], "legal": [ "a7a5", "a7a6", "b7b5", "b7b6", "b8a6", "b8c6", "c7c5", "c7c6", "d7d5", "d7d6", "d8e7", "d8f6", "d8g5", "d8h4", "e8e7", "f7f5", "f7f6", "f8a3", "f8b4", "f8c5", "f8d6", "f8e7", "g7g5", "g7g6", "g8e7", "g8f6", "g8h6", "h7h5", "h7h6" ], "band": 1100, "opponent": 1100 }, "answer": { "keys": ["band", "ms", "policy", "value"], "policyKeys": ["p", "uci"], "valueKeys": ["draw", "loss", "win"] } } ==> services/maia/encode.py <== # SPDX-License-Identifier: AGPL-3.0-or-later """ How Maia-3 sees a position, rewritten with numpy from the reference code in CSSLab/maia3 (maia3/dataset.py and maia3/utils.py at commit 1e13597), so the service needs neither torch nor the upstream package at run time. The model always looks at the board from the side to move: black's positions are mirrored, and so are its moves. It takes the last eight positions, each tokenised from its own side to move, oldest first, padded at the front with the oldest one when the game is shorter than that. """ import chess import numpy as np HISTORY = 8 PLANES = 12 PIECE_PLANE = { chess.PAWN: 0, chess.KNIGHT: 1, chess.BISHOP: 2, chess.ROOK: 3, chess.QUEEN: 4, chess.KING: 5, } def _all_moves(): moves = [] for rank in range(8): for file in range(8): start = chess.square_name(chess.square(file, rank)) for target_rank in range(8): for target_file in range(8): moves.append(start + chess.square_name(chess.square(target_file, target_rank))) # After mirroring, every promotion goes from the 7th rank to the 8th. for file_from in "abcdefgh": for file_to in "abcdefgh": for piece in "qrbn": moves.append(f"{file_from}7{file_to}8{piece}") return moves MOVES = _all_moves() MOVE_INDEX = {uci: i for i, uci in enumerate(MOVES)} assert len(MOVES) == 4352 def mirror_move(uci): def flip(square): return square[0] + str(9 - int(square[1])) return flip(uci[0:2]) + flip(uci[2:4]) + uci[4:] def tokenize(board): """(64, 12) one-hot planes, from the point of view of the side to move.""" planes = np.zeros((64, PLANES), dtype=np.float32) seen = board.mirror() if board.turn == chess.BLACK else board for square, piece in seen.piece_map().items(): planes[square, PIECE_PLANE[piece.piece_type] + (6 if piece.color == chess.BLACK else 0)] = 1 return planes def tokens(boards): """(64, 96) input for the newest of `boards`, given oldest first.""" recent = [tokenize(board) for board in boards[-HISTORY:]] pad = [recent[0]] * (HISTORY - len(recent)) return np.concatenate(pad + recent, axis=1) def model_index(board, move): """Where a legal move sits in the model's output.""" uci = move.uci() return MOVE_INDEX[uci if board.turn == chess.WHITE else mirror_move(uci)] ==> services/maia/export.py <== # SPDX-License-Identifier: AGPL-3.0-or-later """ Downloads a Maia-3 checkpoint from Hugging Face and exports it to ONNX for the bot service, then checks that the ONNX file and our numpy encoding give the same answers as the reference PyTorch code. pip install -r services/maia/requirements-export.txt python services/maia/export.py --model 5m --out deploy/maia/models Writes /maia3.onnx and /maia3.json, the manifest the service reads and reports on /healthz. Needs torch, so run it on a workstation, not in the service's container. --random-init skips the download and exports the same architecture with untrained weights: only for timing and tests, and the service refuses to load it unless told it's a test. """ import argparse import hashlib import json import sys import time from pathlib import Path import chess import numpy as np import torch sys.path.insert(0, str(Path(__file__).resolve().parent)) from encode import tokens as our_tokens # noqa: E402 from maia3.dataset import get_historical_tokens, tokenize_board # noqa: E402 from maia3.model_registry import apply_model_config, resolve_model_spec # noqa: E402 from maia3.models import MAIA3Model # noqa: E402 # The upstream code this export was checked against. Keep it in step with # requirements-export.txt. UPSTREAM = "https://github.com/CSSLab/maia3/tree/1e13597c42d4858b7cfd7cfdae01e297263364b2" # Hugging Face revisions we have exported and checked. Pass --revision to # move to a newer one, then update this table. REVISIONS = { "maia3-5m": "b6559de2398d7140b985f28fd2c19fb5e47ddabe", } class Config: def __init__(self, spec): apply_model_config(self, spec) class Exportable(torch.nn.Module): """Just the policy and value heads, with ratings as floats.""" def __init__(self, model): super().__init__() self.model = model def forward(self, tokens, elo_self, elo_oppo): policy, value, _ = self.model(tokens, elo_self, elo_oppo) return policy, value class PlainRMSNorm(torch.nn.Module): """RMSNorm written out, since the ONNX exporter has no rms_norm at opset 17.""" def __init__(self, norm): super().__init__() self.weight = norm.weight self.eps = norm.eps def forward(self, x): eps = self.eps if self.eps is not None else torch.finfo(x.dtype).eps scaled = x * torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + eps) return scaled * self.weight if self.weight is not None else scaled def exportable(model): """A copy of the model the exporter can read, with the same weights and answers.""" import copy model = copy.deepcopy(model) for module in list(model.modules()): for name, child in list(module.named_children()): if isinstance(child, torch.nn.RMSNorm): setattr(module, name, PlainRMSNorm(child)) return Exportable(model) def load(spec, revision, random_init): cfg = Config(spec) model = MAIA3Model(cfg) if random_init: torch.manual_seed(0) for parameter in model.parameters(): if parameter.dim() > 1: torch.nn.init.xavier_normal_(parameter) return model.eval(), None, None from huggingface_hub import HfApi, hf_hub_download info = HfApi().model_info(spec.repo_id, revision=revision) path = hf_hub_download(spec.repo_id, spec.checkpoint_filename, revision=info.sha) checkpoint = torch.load(path, map_location="cpu", weights_only=True) state = checkpoint.get("model_state_dict", checkpoint) state = {key.replace("smolgen", "gab"): value for key, value in state.items()} missing, unexpected = model.load_state_dict(state, strict=False) if missing or unexpected: raise SystemExit(f"Checkpoint does not fit the model: {missing[:3]} {unexpected[:3]}") return model.eval(), info.sha, hashlib.sha256(Path(path).read_bytes()).hexdigest() def sample_positions(count=48, seed=1): """Positions from random games, each with the boards before it, oldest first.""" rng = np.random.default_rng(seed) out = [] while len(out) < count: board = chess.Board() boards = [board.copy()] for _ in range(int(rng.integers(0, 90))): moves = list(board.legal_moves) if not moves: break board.push(moves[int(rng.integers(len(moves)))]) boards.append(board.copy()) if not board.is_game_over(): out.append(boards[-8:]) return out def upstream_tokens(boards, cfg): from collections import deque history = deque((tokenize_board(board) for board in boards), maxlen=cfg.history) return get_historical_tokens(history, cfg, base=0.0, inc=0.0, clk_left_before=0.0, clk_ponder=0.0) def check(model, cfg, onnx_path): import onnxruntime session = onnxruntime.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"]) worst_tokens = 0.0 worst_policy = 0.0 timings = [] for i, boards in enumerate(sample_positions()): ours = our_tokens(boards) theirs = upstream_tokens(boards, cfg).numpy()[:, : ours.shape[1]] worst_tokens = max(worst_tokens, float(np.abs(ours - theirs).max())) elo = np.array([600 + 100 * (i % 21)], dtype=np.float32) with torch.no_grad(): expected, _, _ = model(torch.from_numpy(ours)[None], torch.from_numpy(elo), torch.from_numpy(elo)) started = time.perf_counter() got, _ = session.run(["policy", "value"], {"tokens": ours[None], "elo_self": elo, "elo_oppo": elo}) timings.append((time.perf_counter() - started) * 1000) worst_policy = max(worst_policy, float(np.abs(got - expected.numpy()).max())) return worst_tokens, worst_policy, float(np.median(timings)) def main(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--model", default="5m", help="5m, 23m or 79m") parser.add_argument("--revision", help="Hugging Face revision; defaults to the one we checked") parser.add_argument("--out", default="deploy/maia/models", type=Path) parser.add_argument("--random-init", action="store_true", help="untrained weights, for tests only") args = parser.parse_args() spec = resolve_model_spec(args.model) revision = args.revision or REVISIONS.get(spec.name, "main") model, sha, checkpoint_sha = load(spec, revision, args.random_init) cfg = model.cfg args.out.mkdir(parents=True, exist_ok=True) onnx_path = args.out / "maia3.onnx" example = ( torch.zeros(1, 64, 12 * cfg.history), torch.full((1,), 1500.0), torch.full((1,), 1500.0), ) torch.onnx.export( exportable(model).eval(), example, str(onnx_path), input_names=["tokens", "elo_self", "elo_oppo"], output_names=["policy", "value"], dynamic_axes={name: {0: "batch"} for name in ["tokens", "elo_self", "elo_oppo", "policy", "value"]}, opset_version=17, dynamo=False, ) worst_tokens, worst_policy, median_ms = check(model, cfg, onnx_path) if worst_tokens > 0 or worst_policy > 2e-3: raise SystemExit(f"Export does not match PyTorch: tokens {worst_tokens}, policy {worst_policy}") manifest = { "model": spec.name, "repo": spec.repo_id, "revision": sha, "source": "random" if args.random_init else "huggingface", "checkpoint_sha256": checkpoint_sha, "sha256": hashlib.sha256(onnx_path.read_bytes()).hexdigest(), "upstream": UPSTREAM, "checked": {"policy_max_diff": worst_policy, "median_ms": round(median_ms, 2)}, } (args.out / "maia3.json").write_text(json.dumps(manifest, indent=2) + "\n") size = onnx_path.stat().st_size / 1e6 print(f"{spec.display_name}: {onnx_path} ({size:.1f} MB), matches PyTorch within {worst_policy:.1e}") print(f"Median inference {median_ms:.1f} ms on this machine") if __name__ == "__main__": main() ==> services/maia/requirements-export.txt <== -r requirements.in huggingface-hub>=0.23 onnx torch maia3 @ git+https://github.com/CSSLab/maia3@1e13597c42d4858b7cfd7cfdae01e297263364b2 ==> services/maia/requirements.in <== # What the service imports, by version. requirements.txt pins these and # everything they pull in, by hash; after changing a line here, run # uv pip compile requirements.in --python-version 3.13 --generate-hashes --no-header -o requirements.txt chess==1.11.2 numpy==2.5.3 onnxruntime==1.29.0 ==> services/maia/requirements.txt <== # Every package the service runs on, with the hash of each file PyPI has for # it. Made from requirements.in; see there to change it. chess==1.11.2 \ --hash=sha256:a8b43e5678fdb3000695bdaa573117ad683761e5ca38e591c4826eba6d25bb39 # via -r requirements.in flatbuffers==25.12.19 \ --hash=sha256:7634f50c427838bb021c2d66a3d1168e9d199b0607e6329399f04846d42e20b4 # via onnxruntime numpy==2.5.3 \ --hash=sha256:012e66aca395d795496446e52aeeb5866312a5d4d3f27da270e5a0b43f70dc5c \ --hash=sha256:09d5a423c71ad5feb5625844ad58050e35df43871004b52ac9c0ad44a56775be \ --hash=sha256:09ffa5d903faeaa5c4dd05009cf81c8bab9f2cb37c548b8d39b65b4cfa7c97f7 \ --hash=sha256:0a59a421a32580a009e8a1751345bf829631b990dc1794b80514ab722b435def \ --hash=sha256:116f96cadd935c6122e9228d676fe7ede19e741f5c8bb1c3cddbe0c51ccebea2 \ --hash=sha256:1302b90c0e52281681b2975adfe8a860cb7b12216a27b4b0b4207c44bf7bccf0 \ --hash=sha256:15aa985ac73a8db02db7663381aa109510449d3819d37206caed27b33a65a8a6 \ --hash=sha256:1aad64d99730d013cfc6debafed22783b4fc5a7f4b8bc744d2d8cf7dcc880551 \ --hash=sha256:1c80eabb4035ecf4ca9cd49cde8a9fdd69a729e63e6474887d1523ade7aa277f \ --hash=sha256:1f3ed25271581281f2fccb1adcedfcde4c07362eec69189b50baf6f90e3ae159 \ --hash=sha256:1fb6f8fb9ff0b3a69f52c66ce397b0246583e9f28616231b0e32ca49259a5fa6 \ --hash=sha256:214045a5bf00113a146ab9ee9730c44501af6723cdf1f6830932f7b5ef2e7af0 \ --hash=sha256:26e15e4aecd8617dfbaecb37d223e365d7b39411fba20454be2670a96aa74cb5 \ --hash=sha256:2c25dfa72943e4336ddb6b0ee4277b47a0c85bede0807530ec68103bf58e2c10 \ --hash=sha256:2d8240cb4c16fd831074aa2b2cf9fc54664d826341d61c372245b96a74a49a9a \ --hash=sha256:350ba9783ce969cf9f7ce6e6a9a58e1a6e2a19ca025b7ee448c4db727706212a \ --hash=sha256:4c8a6d2ebce6305fd82fbefca827775437147052a976ee7c94b36a0c1b52ac6c \ --hash=sha256:4f8929ee6c96bfbd7b4ed2032e0c03af86fe1826740ab61ddabf9072d06e57ff \ --hash=sha256:536f963710a4e63934d80ac0dc4f478804a83e9a84b6828018f25d09953ada33 \ --hash=sha256:54a115e5a73b8fc44f0cebef486365a1894b5c9760685d4558b72b7c3eb846e0 \ --hash=sha256:595d020938c84e320bcf40ad71089e108eac0d377cd018e14a8c094f39e98d85 \ --hash=sha256:66a78fe4556c60aceda5916f9eacd638b18e9e681016ec302dcb4682d6d4d034 \ --hash=sha256:6b05c171afb3aa07adbd20abc00aea86fe375beb0fdb9ef780ec5b7f63bab1c0 \ --hash=sha256:6cef4bb1706dfec49243c05d921eefb4e190d41e2528b30d8035ea1f36b4c24a \ --hash=sha256:6f24021b9f22bc6301c37b196974a92c1c18dccedb6fef3dd252e95f2d6adbe4 \ --hash=sha256:71b39d9f935b6ec0f8753e3e2afb51e3efba6f2e05b68b32a40754d24bcd4a3c \ --hash=sha256:71cad2b2a7451ab79d8f5e71b453485b6775963d5cf794179144a7463fe6e8ec \ --hash=sha256:76c2c1e6bfa5c84adc6434dfbf013aa92096a7985221762c8f11fedfd20fff58 \ --hash=sha256:8617bbfae4486cf99c9f899966699428d19da931d06ca94ad3da986c76e15997 \ --hash=sha256:86bff898a431c0fb71f7610b75726e75a54d47b37edc9d537f48de63bb3c0b90 \ --hash=sha256:8e4dd766076855b5ff7ea52fa5f07ce26286726e0f8bff446b7739d02e6ea204 \ --hash=sha256:92f30e89b8ee0ecf363033576c422b2f58fed6a80bed0aa48dff6d14c654663e \ --hash=sha256:93e1f5447e2b1e479d7bd74701e84746b86450cff1fc368b132d195e2b8f8211 \ --hash=sha256:9a37475425b431b4d060f23b4f52cd2f3aef6bc7c654bd760adf0040eec9d435 \ --hash=sha256:9deb49575e5b0b94ed72c8a64ec4d033381adc27e9060ae842971f697ba96104 \ --hash=sha256:a5fa86b80fd24bcd1aff83ad23be44ea323de3f787be8f8b15d4a65621e25321 \ --hash=sha256:a6391fafaba97500887132cd582abc6e19452b1ac775a47caa7b24490e152058 \ --hash=sha256:a72f874bc9e10e4b8f80426fb49716d5141f64442a0c8418065093ec8017fbb0 \ --hash=sha256:ac7bb1c52d445bd4f8f7f97fefe6abc3a084dc4d63df50d79b17fa2b78e89297 \ --hash=sha256:adc1ada2662f8a5f960b8a10d9986897e7499ef07e06d4cfe7197f8cce923c07 \ --hash=sha256:b00eefbcf0f292945c4b4dec2ae845389ef5bcdcd596e6e4328051db5b5ba694 \ --hash=sha256:b0521d0f4aebb6e06189451025fa17a913287b13c03d5fe05c017333b654ea5b \ --hash=sha256:b5d93cf48f687479941d12b69c873ad2cc76bbd487f0091c2200636497f34034 \ --hash=sha256:b7e18c623bb5c95acb3b3328861272816ba199fb531921c5d6d0b675f1fde9e3 \ --hash=sha256:bd4cb9ad3c7889b9b3fe0a9a9fb5d2ed26f9879bff2608d9f01aed147a20d231 \ --hash=sha256:be5a8381859b6da607c84f4f7d6847725f1cf1853ef8a2c9e115b7d58bef47dc \ --hash=sha256:befa1ae5bd6030b3f512b43ff3fa5290bbed6b84411a44244b14adf835f5b89d \ --hash=sha256:bf63afbe037eb5d2fe87fbcc7778e61da53ebaf21d938a4515aa73b62532a5d4 \ --hash=sha256:c00abe94c1a69d75d827dcf1c025b25c8a45d230b3bcd77a9020883a1b047653 \ --hash=sha256:c2381f82999704f818e2c987a865050e285ec3621262c66d40f5a96c8f899f8e \ --hash=sha256:c76d5dde9f445058f83d0c02af00557a4db91de9a9a57c0df87d1535001d654b \ --hash=sha256:cb189f09db39283b26bfd061ec16189e14f71c6755207f72a0f7540867afe5b9 \ --hash=sha256:ccb32e0525d29e8b0572eb84c9a57af0e7a4e615726927506f55063c62414034 \ --hash=sha256:ccbc4665079665c3cf3bab4db9f6b095370cd6437d66be549b6c2a1fd19e1958 \ --hash=sha256:d1c89973648c85069c5046ad460f7b8a00218b29a2e42359ac8cc63e9ab94832 \ --hash=sha256:df2d5874ff183595a4ba404edd04f6bd9b5505c1d7708573f6a6c17489a67563 \ --hash=sha256:e01c918ac3d48e18a927cf7b14a26a3e29ff2bdf2eacb976da0aecd6a43ed034 \ --hash=sha256:e6ab667ba76450084eb64013762c438ea76d9d29cc676dcd6c2e9892ba37f841 \ --hash=sha256:e931e4f499e0dc7ef29d269a8e5b35dd722e5d14be07df6240166ea7c6532fae \ --hash=sha256:f54660b0eb6b0b9f36e7fe1cdfdff472028dd0d14acd9b9b65098efbad059469 \ --hash=sha256:f59a878c33d6b88122d80d239bb3b845d58708750b0cb06a09aebb9b18ec696c \ --hash=sha256:f7fabeb6cea87d65f3b926de33d03fb016cfdc29314c90974383b5582ae72891 \ --hash=sha256:f9579f383d1bf9df80081e72760e84960a7fd4f88cf0c9e535a8597c9bb646f5 \ --hash=sha256:f9a2353b37a1a9e78fd82b27ad7e2a32a2d036604d18f02b05e3136c62ca3b09 \ --hash=sha256:fc36dc566135b5eceec4cf89758fcb719266a019ef07dae1754ae7c9f617ef3e \ --hash=sha256:ffdc76bfcae6b255dff75202c5e7feaf95b40246bc0a17944facc1fecf9f79ab # via # -r requirements.in # onnxruntime onnxruntime==1.29.0 \ --hash=sha256:07c5907474dec4a2792fd7626b753dc66707808385a6d9eecf993db0066a9d0f \ --hash=sha256:0d4f427afac434b0070fe992b540ddf20a7aff2265f760f314d91331935b6b98 \ --hash=sha256:11264bb58f7b7cf6af835ab10d36838d73680580820fd6f51d90124a1ca8f449 \ --hash=sha256:16925ef8497e2c07e4b5ae15b504079b3ab3f65e22c58efd10dde0f3caea969a \ --hash=sha256:1ea91cef3b971506e51ae9c37c16d027774ec64994a524ec1bdfb027d68a9832 \ --hash=sha256:2945e1f82f81f27e88decea88c7861f45baea23818950d467bf3909aa303119e \ --hash=sha256:2b80d8c7ec2cc7438e4da3760b88c24568cba72c9ace96d668800a6c79419acb \ --hash=sha256:3a3814c041251d6a77fdf513fb282056538ee826d2f1178a0df3c549d3fff6ba \ --hash=sha256:4a3129ae56e70d2618ff773920166916310370a7e3cacb60b9e0e8910092725f \ --hash=sha256:4acf2b4948b7ede87221ca6332344b8facdc8059d6ac751a7d367d04532b02dd \ --hash=sha256:4b940b0d777590c7e20bf298f5c16af1ea6ad1b400a1c822a6be192f64f4d954 \ --hash=sha256:4eae472cf7dc3107dec1bb53cd6d142d1964616d08aae48654cd4254b2363c4b \ --hash=sha256:533f8370ce124304e5cb08ab961836cf755631e3dd77adc5f3bbdab70c2b7d99 \ --hash=sha256:6c0c37b92f67ed68dd36221ce0403e1d9bd4f7efce724439978a2597848530e5 \ --hash=sha256:85f8e8406c52658735fe5c7fbfd3ebaa1ed340768324f6252e4274e374580a23 \ --hash=sha256:939e5d65f332e6d399774b2bd0d3559fd8fa629c1e77833db29d968d2384f23d \ --hash=sha256:be0f8ed688cfb1d4d5765a137193b7bfab0c8ea214eed99260b380bb525a3a7f \ --hash=sha256:c1ad3f437153fe77f9d01a08fbaac0beb030e09b8a80ace1603bcf69b6c95481 \ --hash=sha256:d2fb19e848f7c33ed8d3182b52504aaa11c5e8da438bbb47296f85b133cbcf6b \ --hash=sha256:d67673c5367727860922c5262d724472f1b5539fb7ccf4c81a638f9b71719803 \ --hash=sha256:dc61a79cb39afd66ab3f01fd2c23591a7f01de89c1668e1fb6315067fc279164 \ --hash=sha256:e2128f31f449e922c62dbe5d8b6b7b079f0bcaf2d56a102fa203cb6e5bb5ab19 \ --hash=sha256:e417ef8628dcce310d2d53023e750ea298ec14d4341ae6dc3a572bfd9bc7fa97 \ --hash=sha256:e74b278af1d949876f5d91d1268fd6c680e79f2bac194967394eaba9fdf69e7e # via -r requirements.in packaging==26.3 \ --hash=sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79 \ --hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c # via onnxruntime protobuf==7.36.2 \ --hash=sha256:497d0463ff3316681da6c0b9e8d06cb465d61abce00b613ab42226175644d1bb \ --hash=sha256:89f23aa53c24553a2416fd4fd1ec06f74fa42b14b546d8883128813f775bbfd2 \ --hash=sha256:912c1221170e16c08d1f086762f563dd61ff83c18b5fa6652952dfaded66f728 \ --hash=sha256:a300819d441e078a5608c0d3c709796bb548136058fda017ae51d425b44fd353 \ --hash=sha256:bdb3a345d48db958e6ce1f18e508beb0cc981d64f24088427549c866cd039f1e \ --hash=sha256:cbc70b17ee27e28894c7fee8bb04be1abead49e936bc70eb60052531eee2079e \ --hash=sha256:e11e1f0180583a2af89db6a2ecd9e8dc40aa6d2988ca175bfd0e6d12ea72d74e \ --hash=sha256:f4fee11ec330d238b34a05c9b675f693c20415d1c5bd7d5320cc2f8a798eb9cf # via onnxruntime ==> services/maia/server.py <== # SPDX-License-Identifier: AGPL-3.0-or-later """ The bot inference service: Maia-3 behind a small HTTP API, for the OpenPawn app only. It answers one question, how likely a player of a given rating is to play each legal move, and leaves the choice to the app. POST /v1/policy {"fen", "history", "band", "opponent", "legal"} GET /healthz what is loaded, and whether it is ready It runs as its own program in its own container, so the model and this code stay a separate work from the app, which only talks to it over HTTP. Settings come from the environment: MAIA_MODEL the ONNX file (default /models/maia3.onnx) MAIA_BIND address to listen on (default 127.0.0.1) MAIA_PORT port (default 8080) MAIA_CLIENTS comma separated addresses or networks allowed to ask (default 127.0.0.1/32) MAIA_THREADS threads for one inference (default 1) MAIA_RATE requests per second per client, and twice that as a burst (default 40) """ import ipaddress import json import os import sys import threading import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path import chess import numpy as np from encode import model_index, tokens LOWEST_BAND = 600 HIGHEST_BAND = 2600 BAND_STEP = 100 MAX_BODY = 8 * 1024 MAX_HISTORY = 7 MAX_FEN = 100 # Inference is a few milliseconds; more than this many at once means # something is wrong upstream, and queueing would only make every bot late. MAX_IN_FLIGHT = 4 class BadRequest(Exception): pass def parse_board(fen): if not isinstance(fen, str) or not fen or len(fen) > MAX_FEN: raise BadRequest("fen") try: board = chess.Board(fen) except ValueError: raise BadRequest("fen") from None # Kings in place, the side not to move not in check, and so on. if not board.is_valid(): raise BadRequest("fen") return board def parse_band(value, name): if ( not isinstance(value, int) or isinstance(value, bool) or value < LOWEST_BAND or value > HIGHEST_BAND or value % BAND_STEP ): raise BadRequest(name) return value def parse_request(body): """The checked request: the boards oldest first, both bands and the legal moves.""" if not isinstance(body, dict): raise BadRequest("body") board = parse_board(body.get("fen")) history = body.get("history", []) if not isinstance(history, list) or len(history) > MAX_HISTORY: raise BadRequest("history") boards = [parse_board(fen) for fen in history] + [board] band = parse_band(body.get("band"), "band") opponent = parse_band(body.get("opponent", band), "opponent") # The caller sends the moves it thinks are legal. If we disagree about the # position, better to say so than to answer about a different one. legal = body.get("legal") if not isinstance(legal, list) or not all(isinstance(m, str) for m in legal): raise BadRequest("legal") moves = list(board.legal_moves) if not moves or sorted(legal) != sorted(m.uci() for m in moves): raise BadRequest("legal") return boards, band, opponent, moves def softmax(values): shifted = np.exp(values - values.max()) return shifted / shifted.sum() class Model: def __init__(self, path): import onnxruntime self.path = Path(path) options = onnxruntime.SessionOptions() options.intra_op_num_threads = int(os.environ.get("MAIA_THREADS", "1")) options.inter_op_num_threads = 1 self.session = onnxruntime.InferenceSession( str(self.path), options, providers=["CPUExecutionProvider"] ) manifest = self.path.with_suffix(".json") self.about = json.loads(manifest.read_text()) if manifest.exists() else {} def logits(self, planes, band, opponent): policy, value = self.session.run( ["policy", "value"], { "tokens": planes[None, :, :], "elo_self": np.array([band], dtype=np.float32), "elo_oppo": np.array([opponent], dtype=np.float32), }, ) return policy[0], value[0] def policy(model, boards, band, opponent, moves): board = boards[-1] move_logits, value_logits = model.logits(tokens(boards), band, opponent) chosen = np.array([move_logits[model_index(board, move)] for move in moves], dtype=np.float64) probabilities = softmax(chosen) order = np.argsort(-probabilities, kind="stable") # The value head says [loss, draw, win] for the side to move. loss, draw, win = softmax(value_logits.astype(np.float64)) return { "policy": [ {"uci": moves[i].uci(), "p": round(float(probabilities[i]), 6)} for i in order ], "value": {"win": round(float(win), 4), "draw": round(float(draw), 4), "loss": round(float(loss), 4)}, } class Bucket: """A token bucket per client address.""" def __init__(self, rate, burst): self.rate = rate self.burst = burst self.tokens = {} self.lock = threading.Lock() def take(self, key): now = time.monotonic() with self.lock: level, then = self.tokens.get(key, (self.burst, now)) level = min(self.burst, level + (now - then) * self.rate) if level < 1: self.tokens[key] = (level, now) return False self.tokens[key] = (level - 1, now) if len(self.tokens) > 1024: self.tokens = {key: self.tokens[key]} return True def parse_clients(value): return [ipaddress.ip_network(part.strip(), strict=False) for part in value.split(",") if part.strip()] class Service: def __init__(self, model, clients, rate): self.model = model self.clients = clients self.bucket = Bucket(rate, rate * 2) self.in_flight = threading.BoundedSemaphore(MAX_IN_FLIGHT) def allowed(self, address): try: ip = ipaddress.ip_address(address) except ValueError: return False return any(ip in network for network in self.clients) def health(self): about = self.model.about return { "ready": True, "model": about.get("model") or self.model.path.stem, "revision": about.get("revision"), "source": about.get("source", "unknown"), "sha256": about.get("sha256"), "bands": [LOWEST_BAND, HIGHEST_BAND], } def handler_for(service): class Handler(BaseHTTPRequestHandler): # A request that takes longer than this to arrive is dropped. timeout = 5 server_version = "maia" sys_version = "" def send(self, status, payload): data = json.dumps(payload, separators=(",", ":")).encode() self.send_response(status) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))) self.send_header("Cache-Control", "no-store") self.end_headers() self.wfile.write(data) def gate(self): if not service.allowed(self.client_address[0]): self.send(403, {"error": "forbidden"}) return False return True def do_GET(self): if not self.gate(): return if self.path != "/healthz": self.send(404, {"error": "not found"}) return self.send(200, service.health()) def do_POST(self): if not self.gate(): return if self.path != "/v1/policy": self.send(404, {"error": "not found"}) return if self.headers.get_content_type() != "application/json": self.send(415, {"error": "json only"}) return try: length = int(self.headers.get("Content-Length", "")) except ValueError: self.send(411, {"error": "length required"}) return if length <= 0 or length > MAX_BODY: self.send(413, {"error": "too large"}) return if not service.bucket.take(self.client_address[0]): self.send(429, {"error": "busy"}) return body = self.rfile.read(length) try: boards, band, opponent, moves = parse_request(json.loads(body)) except (BadRequest, ValueError) as problem: field = problem.args[0] if isinstance(problem, BadRequest) else "body" self.send(400, {"error": "invalid", "field": field}) return if not service.in_flight.acquire(timeout=0.05): self.send(503, {"error": "busy"}) return try: started = time.perf_counter() answer = policy(service.model, boards, band, opponent, moves) answer["ms"] = round((time.perf_counter() - started) * 1000, 2) answer["band"] = band finally: service.in_flight.release() self.send(200, answer) def log_message(self, format, *args): # Positions are not personal, but there is no reason to keep them either. pass return Handler def main(): path = os.environ.get("MAIA_MODEL", "/models/maia3.onnx") # Without weights the site still works, with engine bots. Wait for them # quietly rather than restarting over and over. if not Path(path).is_file(): print(f"No model at {path} yet. See docs/deploy.md, Human-like bots.", file=sys.stderr, flush=True) while not Path(path).is_file(): time.sleep(60) model = Model(path) if model.about.get("source") == "random" and os.environ.get("MAIA_ALLOW_RANDOM") != "1": print("Refusing a model with random weights outside a test.", file=sys.stderr) sys.exit(1) clients = parse_clients(os.environ.get("MAIA_CLIENTS", "127.0.0.1/32")) rate = float(os.environ.get("MAIA_RATE", "40")) service = Service(model, clients, rate) bind = os.environ.get("MAIA_BIND", "127.0.0.1") port = int(os.environ.get("MAIA_PORT", "8080")) server = ThreadingHTTPServer((bind, port), handler_for(service)) server.daemon_threads = True print(f"Maia-3 ({service.health()['model']}) listening on {bind}:{port}", file=sys.stderr, flush=True) server.serve_forever() if __name__ == "__main__": main() ==> services/maia/test_server.py <== # SPDX-License-Identifier: AGPL-3.0-or-later """ Tests for the service without a real model: a stand-in gives the logits. cd services/maia && python -m unittest -v """ import json import threading import unittest import urllib.error import urllib.request from pathlib import Path from http.server import ThreadingHTTPServer import chess import numpy as np import server from encode import MOVES, model_index, tokens START = chess.STARTING_FEN START_LEGAL = [move.uci() for move in chess.Board().legal_moves] class StubModel: """Likes moves in the order of the model's vocabulary, so the answer is predictable.""" def __init__(self): self.about = {"model": "stub", "source": "random"} self.path = None self.seen = [] def logits(self, planes, band, opponent): self.seen.append((planes.shape, band, opponent)) return -np.arange(len(MOVES), dtype=np.float32) / 100, np.array([0.0, 1.0, 2.0], dtype=np.float32) def request(**overrides): body = {"fen": START, "band": 1500, "legal": START_LEGAL} body.update(overrides) return body class ParseTest(unittest.TestCase): def test_accepts_a_plain_request(self): boards, band, opponent, moves = server.parse_request(request()) self.assertEqual(len(boards), 1) self.assertEqual((band, opponent), (1500, 1500)) self.assertEqual(len(moves), 20) def test_rejects_bad_fields(self): cases = { "fen": [request(fen="not a fen"), request(fen=""), request(fen=None), request(fen="x" * 200)], "band": [request(band=550), request(band=2700), request(band=1550), request(band="1500"), request(band=True)], "opponent": [request(opponent=3000)], "legal": [request(legal=START_LEGAL[:-1]), request(legal=START_LEGAL + ["e2e5"]), request(legal="e2e4")], "history": [request(history=[START] * 8), request(history="x"), request(history=["bad"])], } for field, bodies in cases.items(): for body in bodies: with self.assertRaises(server.BadRequest) as caught: server.parse_request(body) self.assertEqual(caught.exception.args[0], "fen" if field == "history" and body["history"] == ["bad"] else field) def test_rejects_impossible_positions(self): no_king = "8/8/8/8/8/8/8/8 w - - 0 1" with self.assertRaises(server.BadRequest): server.parse_request(request(fen=no_king, legal=[])) def test_rejects_a_finished_game(self): mate = "rnb1kbnr/pppp1ppp/8/4p3/6Pq/5P2/PPPPP2P/RNBQKBNR w KQkq - 1 3" with self.assertRaises(server.BadRequest): server.parse_request(request(fen=mate, legal=[])) class EncodeTest(unittest.TestCase): def test_black_sees_the_board_from_its_side(self): board = chess.Board() board.push_uci("e2e4") planes = tokens([board]) # Black's own pawns sit on the second rank of its view, as white's do for white. white_view = tokens([chess.Board()]) self.assertEqual(planes.shape, (64, 96)) self.assertEqual(planes[chess.E2, 84], 1) # e7 pawn mirrored, newest slot, own pawn plane self.assertEqual(white_view[chess.E2, 84], 1) def test_moves_are_mirrored_for_black(self): board = chess.Board() board.push_uci("e2e4") self.assertEqual(model_index(board, chess.Move.from_uci("e7e5")), MOVES.index("e2e4")) def test_promotions_have_their_own_slot(self): board = chess.Board("8/4P3/8/8/8/8/k7/4K3 w - - 0 1") self.assertEqual(MOVES[model_index(board, chess.Move.from_uci("e7e8n"))], "e7e8n") def test_short_games_are_padded_with_the_first_position(self): board = chess.Board() planes = tokens([board]) for slot in range(8): np.testing.assert_array_equal(planes[:, slot * 12 : slot * 12 + 12], planes[:, 84:96]) class PolicyTest(unittest.TestCase): def test_every_legal_move_once_and_sums_to_one(self): model = StubModel() boards, band, opponent, moves = server.parse_request(request(opponent=1200)) answer = server.policy(model, boards, band, opponent, moves) self.assertEqual(sorted(item["uci"] for item in answer["policy"]), sorted(START_LEGAL)) self.assertAlmostEqual(sum(item["p"] for item in answer["policy"]), 1, places=4) probabilities = [item["p"] for item in answer["policy"]] self.assertEqual(probabilities, sorted(probabilities, reverse=True)) self.assertEqual(model.seen[0], ((64, 96), 1500, 1200)) self.assertGreater(answer["value"]["win"], answer["value"]["loss"]) class ContractTest(unittest.TestCase): """The request the app sends, from contract.json, and the answer it expects.""" def test_the_apps_request_gets_the_promised_answer(self): with open(Path(__file__).with_name("contract.json")) as file: contract = json.load(file) boards, band, opponent, moves = server.parse_request(contract["service"]) answer = server.policy(StubModel(), boards, band, opponent, moves) answer.update(band=band, ms=0) self.assertEqual(sorted(answer), contract["answer"]["keys"]) self.assertEqual(sorted(answer["policy"][0]), contract["answer"]["policyKeys"]) self.assertEqual(sorted(answer["value"]), contract["answer"]["valueKeys"]) self.assertEqual(len(boards), 4) class BucketTest(unittest.TestCase): def test_runs_dry_and_keeps_clients_apart(self): bucket = server.Bucket(rate=0.001, burst=2) self.assertTrue(bucket.take("a")) self.assertTrue(bucket.take("a")) self.assertFalse(bucket.take("a")) self.assertTrue(bucket.take("b")) class HttpTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.model = StubModel() service = server.Service(cls.model, server.parse_clients("127.0.0.1/32"), rate=1000) cls.httpd = ThreadingHTTPServer(("127.0.0.1", 0), server.handler_for(service)) cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" threading.Thread(target=cls.httpd.serve_forever, daemon=True).start() @classmethod def tearDownClass(cls): cls.httpd.shutdown() def post(self, body, content_type="application/json"): data = body if isinstance(body, bytes) else json.dumps(body).encode() req = urllib.request.Request(f"{self.base}/v1/policy", data=data, headers={"Content-Type": content_type}) try: with urllib.request.urlopen(req) as response: return response.status, json.load(response) except urllib.error.HTTPError as failed: return failed.code, json.load(failed) def test_answers_with_the_policy(self): status, answer = self.post(request()) self.assertEqual(status, 200) self.assertEqual(answer["band"], 1500) self.assertEqual(len(answer["policy"]), 20) self.assertIn("ms", answer) def test_says_which_field_is_wrong(self): self.assertEqual(self.post(request(band=42)), (400, {"error": "invalid", "field": "band"})) self.assertEqual(self.post(b"{not json"), (400, {"error": "invalid", "field": "body"})) def test_json_only_and_small_only(self): self.assertEqual(self.post(request(), "text/plain")[0], 415) self.assertEqual(self.post(b"x" * 10_000)[0], 413) def test_health(self): with urllib.request.urlopen(f"{self.base}/healthz") as response: health = json.load(response) self.assertTrue(health["ready"]) self.assertEqual(health["bands"], [600, 2600]) def test_strangers_are_turned_away(self): service = server.Service(self.model, server.parse_clients("10.0.0.0/8"), rate=10) self.assertFalse(service.allowed("127.0.0.1")) self.assertTrue(service.allowed("10.1.2.3")) self.assertFalse(service.allowed("not an address")) if __name__ == "__main__": unittest.main()