"""Arkonium engine: PUCT Monte Carlo tree search guided by the Arkonium network (policy priors + value), with batched GPU evaluation, virtual loss and tree reuse between moves. Since Arkonium 1.6 the GPU search is pipelined: while the network evaluates one batch of leaves, the CPU already selects the next batch (virtual loss keeps the two batches apart). The search rules are unchanged; only the order of the work is different. engine09.py is the unchanged engine of Arkonium 0.9.""" import math import time import chess import numpy as np import torch from encoding import encode_board, move_index_chess from model import Arkonium, planes def load_model(path, device): """Load a training checkpoint (.pt) or released weights (.safetensors with config.json next to it).""" if path.endswith(".safetensors"): import json import os from safetensors.torch import load_file cfg = json.load(open(os.path.join(os.path.dirname(os.path.abspath(path)), "config.json")))["network"] weights = load_file(path, device=device) else: state = torch.load(path, map_location=device) cfg, weights = state["cfg"], state["model"] model = Arkonium(**cfg).to(device).to(memory_format=torch.channels_last) model.load_state_dict(weights) model.eval() return model class Node: __slots__ = ("moves", "prior", "n", "w", "children", "terminal", "value", "pending") def __init__(self): self.moves = None # list of chess.Move once expanded self.prior = None # np.float32 priors self.n = None # np.int32 visit counts per child self.w = None # np.float32 summed values per child (from this node's side to move) self.children = None # list of Node or None self.terminal = None # value for the side to move if the position is terminal self.value = 0.0 # network value of this node (side to move) self.pending = False # waiting for the network in the batch that is in flight def terminal_value(board): if not any(board.generate_legal_moves()): return -1.0 if board.is_check() else 0.0 # checkmate or stalemate if board.is_insufficient_material() or board.halfmove_clock >= 100: return 0.0 if board.is_repetition(2): return 0.0 return None class Engine: def __init__(self, model_path, device=None, batch=32, cpuct=1.8, fpu=0.3, softmax_temp=1.0, model=None, pipeline=True): device = device or ("cuda" if torch.cuda.is_available() else "cpu") self.device = device self.model = model if model is not None else load_model(model_path, device) self.batch = batch self.cpuct = cpuct self.fpu = fpu self.ptemp = softmax_temp self.root = None self.root_fen = None self.root_stack_len = None self.nodes = 0 self.graphs = {} self.pipeline = pipeline and device == "cuda" self._inflight = None if device == "cuda": self._capture() out_dim = self.graphs[self.batch][3][0].shape[1] self._host_lo = torch.empty(self.batch, out_dim, pin_memory=True) self._host_va = torch.empty(self.batch, pin_memory=True) self._event = torch.cuda.Event() self._evaluate([chess.Board()]) # ---- network ----------------------------------------------------------------------------- def _forward(self, bd, mt): with torch.no_grad(), torch.autocast(self.device, torch.bfloat16, enabled=self.device == "cuda"): logits, vlogit = self.model(planes(bd, mt).contiguous(memory_format=torch.channels_last)) return logits.float(), torch.tanh(vlogit.float() / 2) def _capture(self): """CUDA graphs for fixed batch sizes remove most of the per-call kernel launch overhead.""" self.graphs = {} for size in sorted({1, 8, self.batch}): bd = torch.zeros(size, 64, dtype=torch.uint8, device=self.device) mt = torch.zeros(size, 2, dtype=torch.uint8, device=self.device) stream = torch.cuda.Stream() stream.wait_stream(torch.cuda.current_stream()) with torch.cuda.stream(stream): for _ in range(3): self._forward(bd, mt) torch.cuda.current_stream().wait_stream(stream) g = torch.cuda.CUDAGraph() with torch.cuda.graph(g): out = self._forward(bd, mt) self.graphs[size] = (g, bd, mt, out) def _evaluate(self, boards): enc = [encode_board(b) for b in boards] n = len(enc) bd_np = np.array([e[0] for e in enc], np.uint8) mt_np = np.array([e[1] for e in enc], np.uint8) size = next((s for s in sorted(self.graphs) if s >= n), None) if self.graphs else None if size is None: logits, values = self._forward(torch.tensor(bd_np, device=self.device), torch.tensor(mt_np, device=self.device)) logits, values = logits.cpu().numpy(), values.cpu().numpy() else: g, bd, mt, (lo, va) = self.graphs[size] bd.zero_() mt.zero_() bd[:n].copy_(torch.from_numpy(bd_np)) mt[:n].copy_(torch.from_numpy(mt_np)) g.replay() logits, values = lo[:n].cpu().numpy(), va[:n].cpu().numpy() out = [] for b, lg, v in zip(boards, logits, values): moves = list(b.legal_moves) idx = [move_index_chess(m, b.turn) for m in moves] x = lg[idx] / self.ptemp x = np.exp(x - x.max()) out.append((moves, (x / x.sum()).astype(np.float32), float(v))) return out def _expand(self, node, moves, prior, value): node.moves = moves node.prior = prior node.n = np.zeros(len(moves), np.int32) node.w = np.zeros(len(moves), np.float32) node.children = [None] * len(moves) node.value = value # ---- search ------------------------------------------------------------------------------ def _select(self, node): total = node.n.sum() visited = node.n > 0 q_fpu = node.value - self.fpu * math.sqrt(float(node.prior[visited].sum())) q = np.where(visited, node.w / np.maximum(node.n, 1), q_fpu) u = self.cpuct * node.prior * math.sqrt(total + 1) / (1 + node.n) return int(np.argmax(q + u)) def _simulate_batch(self, board): leaves = [] # (path, board copy) waiting for the network pending = set() for _ in range(self.batch): node = self.root path = [] depth = 0 while True: if node.terminal is not None: break if node.moves is None: break if not node.moves: break i = self._select(node) path.append((node, i)) board.push(node.moves[i]) depth += 1 child = node.children[i] if child is None: child = Node() node.children[i] = child child.terminal = terminal_value(board) node = child # virtual loss along the path for parent, i in path: parent.n[i] += 1 parent.w[i] -= 1.0 if node.terminal is not None: self._backup(path, node.terminal, virtual=True) elif id(node) in pending: self._backup(path, None, virtual=True) # undo virtual loss only for _ in range(depth): board.pop() break else: pending.add(id(node)) leaves.append((path, node, board.copy(stack=8))) for _ in range(depth): board.pop() if leaves: results = self._evaluate([b for _, _, b in leaves]) for (path, node, _), (moves, prior, value) in zip(leaves, results): self._expand(node, moves, prior, value) self._backup(path, value, virtual=True) self.nodes += 1 # ---- pipelined search (GPU) ---------------------------------------------------------------- def _collect(self, board): """Select up to `batch` leaves. A leaf that is already waiting for the network (in this batch or in the batch in flight) ends the collection, as in the unpipelined search.""" leaves = [] for _ in range(self.batch): node = self.root path = [] depth = 0 while node.terminal is None and node.moves: i = self._select(node) path.append((node, i)) board.push(node.moves[i]) depth += 1 child = node.children[i] if child is None: child = Node() node.children[i] = child child.terminal = terminal_value(board) node = child for parent, i in path: parent.n[i] += 1 parent.w[i] -= 1.0 stop = False if node.terminal is not None: self._backup(path, node.terminal, virtual=True) elif node.pending or node.moves is not None: self._backup(path, None, virtual=True) # undo the virtual loss only stop = True else: node.pending = True leaves.append((path, node, board.copy(stack=8))) for _ in range(depth): board.pop() if stop: break return leaves def _launch(self, leaves): boards = [b for _, _, b in leaves] enc = [encode_board(b) for b in boards] n = len(enc) size = next(s for s in sorted(self.graphs) if s >= n) g, bd, mt, (lo, va) = self.graphs[size] bd.zero_() mt.zero_() bd[:n].copy_(torch.from_numpy(np.array([e[0] for e in enc], np.uint8))) mt[:n].copy_(torch.from_numpy(np.array([e[1] for e in enc], np.uint8))) g.replay() self._host_lo[:n].copy_(lo[:n], non_blocking=True) self._host_va[:n].copy_(va[:n], non_blocking=True) self._event.record() # move generation does not need the network: do it while the GPU works legal = [] for b in boards: moves = list(b.legal_moves) legal.append((moves, [move_index_chess(m, b.turn) for m in moves])) return leaves, n, legal def _finish(self, flight): leaves, n, legal = flight self._event.synchronize() logits = self._host_lo[:n].numpy() values = self._host_va[:n].numpy() for (path, node, _), (moves, idx), lg, v in zip(leaves, legal, logits, values): x = lg[idx] / self.ptemp x = np.exp(x - x.max()) node.pending = False self._expand(node, moves, (x / x.sum()).astype(np.float32), float(v)) self._backup(path, float(v), virtual=True) self.nodes += 1 def _step_pipelined(self, board): leaves = self._collect(board) if self._inflight is not None: self._finish(self._inflight) self._inflight = None if leaves: self._inflight = self._launch(leaves) def _drain(self): if self._inflight is not None: self._finish(self._inflight) self._inflight = None def _backup(self, path, value, virtual): # value is from the side to move at the leaf; flip sign each ply going up for parent, i in reversed(path): if virtual: parent.n[i] -= 1 parent.w[i] += 1.0 if value is None: continue value = -value parent.n[i] += 1 parent.w[i] += value def _set_root(self, board): # reuse the subtree if the new position follows the previous root by one or two plies if self.root is not None and self.root_fen is not None and self.root.moves is not None: stack = board.move_stack k = len(stack) - self.root_stack_len if 0 < k <= 2: probe = board.copy() played = [probe.pop() for _ in range(k)][::-1] if probe.fen() == self.root_fen: node = self.root for m in played: if node is None or node.moves is None or m not in node.moves: node = None break node = node.children[node.moves.index(m)] if node is not None and node.moves is not None: self.root = node self.root_fen = board.fen() self.root_stack_len = len(stack) return self.root = Node() moves, prior, value = self._evaluate([board])[0] self._expand(self.root, moves, prior, value) self.root_fen = board.fen() self.root_stack_len = len(board.move_stack) def search(self, board, seconds=None, nodes=None, info=None): """Return (best move, statistics). Stops after `seconds` or after `nodes` new root visits.""" start = time.time() moves = list(board.legal_moves) if len(moves) == 1: return moves[0], {"nodes": 0, "q": None} for m in moves: # mate in one is always played board.push(m) mate = board.is_checkmate() board.pop() if mate: return m, {"nodes": 0, "q": 1.0, "mate": True} self._set_root(board) self.nodes = 0 root = self.root work = board.copy() last_info = start start_visits = int(root.n.sum()) step = self._step_pipelined if self.pipeline else self._simulate_batch while True: step(work) el = time.time() - start if seconds is not None and el >= seconds: break # count visits, not network calls: lines that end in mate or draw never call the network if nodes is not None and int(root.n.sum()) - start_visits >= nodes: break if seconds is not None and el > 0.3 * seconds and root.n.sum() > 50: # stop early if the leader cannot be caught in the remaining time order = np.sort(root.n) rate = root.n.sum() / el if order[-1] - order[-2] > rate * (seconds - el): break if info and time.time() - last_info > 1.0: info(self._stats(root, start)) last_info = time.time() self._drain() best = int(np.argmax(root.n + root.w / np.maximum(root.n, 1) * 1e-3)) stats = self._stats(root, start) return root.moves[best], stats def _stats(self, root, start): best = int(np.argmax(root.n)) q = float(root.w[best] / max(root.n[best], 1)) pv = [root.moves[best].uci()] node = root.children[best] while node is not None and node.moves is not None and node.n.sum() > 0 and len(pv) < 12: j = int(np.argmax(node.n)) pv.append(node.moves[j].uci()) node = node.children[j] el = max(time.time() - start, 1e-6) return {"nodes": self.nodes, "visits": int(root.n.sum()), "q": q, "pv": pv, "nps": int(self.nodes / el), "seconds": round(el, 3)} def policy_move(self, board): """Raw network move without search.""" moves, prior, _ = self._evaluate([board])[0] return moves[int(np.argmax(prior))] def q_to_cp(q): q = max(min(q, 0.999), -0.999) p = (q + 1) / 2 return int(round(math.log(p / (1 - p)) / 0.00368208))