Skip to content

Commit 82526b0

Browse files
luccabbclaude
andcommitted
[3/9] Open Syzygy tablebase once at initialization
Performance optimization for endgame evaluation: - Open Syzygy tablebase once in `__init__` instead of on every `eval_board` call - Add `close()` method for proper resource cleanup - Use pre-opened tablebase handle for all probes This eliminates the overhead of repeatedly opening/closing the tablebase file during search, which was especially costly in endgame positions where many evaluations may hit the tablebase. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
1 parent bb2ac9f commit 82526b0

1 file changed

Lines changed: 23 additions & 8 deletions

File tree

moonfish/engines/alpha_beta.py

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,21 @@ class AlphaBeta:
3636
def __init__(self, config: Config):
3737
self.config = config
3838

39+
# Open Syzygy tablebase once at initialization (not on every eval)
40+
self.tablebase = None
41+
if config.syzygy_path:
42+
try:
43+
self.tablebase = chess.syzygy.open_tablebase(config.syzygy_path)
44+
except Exception:
45+
# Tablebase path invalid or not accessible
46+
self.tablebase = None
47+
48+
def close(self):
49+
"""Close the tablebase if open. Call when done with the engine."""
50+
if self.tablebase is not None:
51+
self.tablebase.close()
52+
self.tablebase = None
53+
3954
def random_move(self, board: Board) -> Move:
4055
move = choice([move for move in board.legal_moves])
4156
return move
@@ -53,14 +68,14 @@ def eval_board(self, board: Board) -> float:
5368
"""
5469
pieces = sum(count_pieces(board))
5570

56-
if pieces <= self.config.syzygy_pieces and self.config.syzygy_path:
57-
with chess.syzygy.open_tablebase(self.config.syzygy_path) as tablebase:
58-
try:
59-
eval = tablebase.probe_dtz(board)
60-
return eval
61-
except (chess.syzygy.MissingTableError, KeyError):
62-
# syzygy tablebase position not found, continue with evaluation
63-
pass
71+
# Use pre-opened tablebase for endgame positions
72+
if pieces <= self.config.syzygy_pieces and self.tablebase is not None:
73+
try:
74+
dtz = self.tablebase.probe_dtz(board)
75+
return dtz
76+
except (chess.syzygy.MissingTableError, KeyError):
77+
# Position not in tablebase, fall through to normal evaluation
78+
pass
6479

6580
return board_evaluation(board)
6681

0 commit comments

Comments
 (0)