mac-alpha-zero 0.1.0__py3-none-macosx_14_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ """AlphaZero-style self-play training on Apple Silicon, built on MLX."""
2
+
3
+ __version__ = "0.0.1"
@@ -0,0 +1,135 @@
1
+ from collections.abc import Callable
2
+ from typing import NamedTuple
3
+
4
+ import mlx.core as mx
5
+ import numpy as np
6
+
7
+ from mac_alpha_zero import kernels
8
+ from mac_alpha_zero.games.base import BatchedGame, State
9
+ from mac_alpha_zero.gumbel import gumbel_search
10
+ from mac_alpha_zero.mcts import Evaluator, search
11
+
12
+ # Maps a batch of non-terminal states to actions (B,).
13
+ Agent = Callable[[State], mx.array]
14
+
15
+
16
+ class MatchResult(NamedTuple):
17
+ wins: int
18
+ draws: int
19
+ losses: int
20
+
21
+ @property
22
+ def score(self) -> float:
23
+ """Mean result in [0, 1]: a win counts 1 and a draw 0.5."""
24
+ return (self.wins + 0.5 * self.draws) / (self.wins + self.draws + self.losses)
25
+
26
+
27
+ def play_match(
28
+ game: BatchedGame, first: Agent, second: Agent, num_games: int, start: State | None = None
29
+ ) -> np.ndarray:
30
+ """Play `num_games` games in parallel. Returns +1 / 0 / -1 per game for `first`.
31
+
32
+ The games begin at `start` (`num_games` non-terminal states, `first` to move) or at
33
+ the starting position.
34
+ """
35
+ fresh = game.init(num_games)
36
+ state = fresh if start is None else start
37
+ results = np.zeros(num_games)
38
+ finished = np.zeros(num_games, dtype=bool)
39
+ ply = 0
40
+ while not finished.all():
41
+ mask = mx.array(finished)
42
+ # Agents cannot act on finished games, so those slots see a fresh board instead.
43
+ shown = {k: mx.where(_expand(mask, v.ndim), fresh[k], v) for k, v in state.items()}
44
+ actions = (first if ply % 2 == 0 else second)(shown)
45
+ stepped = game.step(state, actions)
46
+ state = {k: mx.where(_expand(mask, v.ndim), state[k], v) for k, v in stepped.items()}
47
+ done, value = game.terminal(state)
48
+ mx.eval(*state.values())
49
+ # `value` is for the player to move next, i.e. the opponent of whoever just moved.
50
+ mover_sign = 1.0 if ply % 2 == 0 else -1.0
51
+ just_finished = np.array(done) & ~finished
52
+ results[just_finished] = -mover_sign * np.array(value)[just_finished]
53
+ finished |= just_finished
54
+ ply += 1
55
+ return results
56
+
57
+
58
+ def evaluate(
59
+ game: BatchedGame, agent: Agent, opponent: Agent, num_games: int, start: State | None = None
60
+ ) -> MatchResult:
61
+ """`agent` against `opponent`, half the games with each side moving first.
62
+
63
+ `start` holds `num_games // 2` positions; each is played once with each side to move.
64
+ """
65
+ half = num_games // 2
66
+ results = np.concatenate(
67
+ [
68
+ play_match(game, agent, opponent, half, start),
69
+ -play_match(game, opponent, agent, half, start),
70
+ ]
71
+ )
72
+ return MatchResult(
73
+ wins=int((results > 0).sum()),
74
+ draws=int((results == 0).sum()),
75
+ losses=int((results < 0).sum()),
76
+ )
77
+
78
+
79
+ def random_agent(game: BatchedGame, seed: int = 0) -> Agent:
80
+ key = mx.random.key(seed)
81
+
82
+ def act(state: State) -> mx.array:
83
+ nonlocal key
84
+ key, subkey = mx.random.split(key)
85
+ logits = mx.where(game.legal_mask(state), 0.0, -mx.inf)
86
+ return mx.random.categorical(logits, key=subkey).astype(mx.int32)
87
+
88
+ return act
89
+
90
+
91
+ def random_openings(game: BatchedGame, count: int, plies: int, seed: int = 0) -> State:
92
+ """`count` positions after `plies` uniformly random moves each, to start matches from."""
93
+ agent = random_agent(game, seed)
94
+ state = game.init(count)
95
+ for _ in range(plies):
96
+ state = game.step(state, agent(state))
97
+ mx.eval(*state.values())
98
+ if mx.any(game.terminal(state)[0]).item():
99
+ raise ValueError("an opening ended the game; use fewer opening plies")
100
+ return state
101
+
102
+
103
+ def puct_agent(game: BatchedGame, evaluator: Evaluator, num_simulations: int) -> Agent:
104
+ """Plays the most visited action of a PUCT search."""
105
+
106
+ def act(state: State) -> mx.array:
107
+ result = search(game, state, evaluator, num_simulations, use_kernels=kernels.is_available())
108
+ return mx.argmax(result.visit_counts, axis=-1).astype(mx.int32)
109
+
110
+ return act
111
+
112
+
113
+ def gumbel_agent(
114
+ game: BatchedGame, evaluator: Evaluator, num_simulations: int, *, improved_nonroot: bool = False
115
+ ) -> Agent:
116
+ """Plays the Gumbel search action without noise, i.e. deterministically."""
117
+
118
+ def act(state: State) -> mx.array:
119
+ batch = next(iter(state.values())).shape[0]
120
+ result = gumbel_search(
121
+ game,
122
+ state,
123
+ evaluator,
124
+ num_simulations,
125
+ improved_nonroot=improved_nonroot,
126
+ gumbel=mx.zeros((batch, game.num_actions)),
127
+ use_kernels=kernels.is_available(),
128
+ )
129
+ return result.action
130
+
131
+ return act
132
+
133
+
134
+ def _expand(mask: mx.array, ndim: int) -> mx.array:
135
+ return mask.reshape(-1, *([1] * (ndim - 1)))
mac_alpha_zero/edax.py ADDED
@@ -0,0 +1,86 @@
1
+ """Play Othello against Edax (https://github.com/abulmo/edax-reversi).
2
+
3
+ Edax is a separate GPL-3.0 program and is not part of this package. Build it with
4
+ `scripts/build_edax.sh`; it is only ever run as a subprocess.
5
+ """
6
+
7
+ import re
8
+ import subprocess
9
+ import tempfile
10
+ from pathlib import Path
11
+
12
+ import mlx.core as mx
13
+ import numpy as np
14
+
15
+ from mac_alpha_zero.arena import Agent
16
+ from mac_alpha_zero.games.base import State
17
+ from mac_alpha_zero.games.othello import PASS, SIZE, Othello
18
+
19
+ DEFAULT_PATH = Path(__file__).resolve().parents[2] / "third_party" / "edax" / "edax"
20
+
21
+ # A result row of `edax -solve`: " 12| 3 -04 0:00.000 14 d3 C4 ...".
22
+ _RESULT_ROW = re.compile(r"^\s*(\d+)\|(.*)$")
23
+ _SQUARE = re.compile(r"\b([a-hA-H])([1-8])\b")
24
+
25
+
26
+ def to_obf(board: np.ndarray, player: int) -> str:
27
+ """One position in Edax's OBF format. `board` is (8, 8) with +1 black and -1 white."""
28
+ symbols = {1: "X", -1: "O", 0: "-"}
29
+ squares = "".join(symbols[int(v)] for v in board.reshape(-1))
30
+ return f"{squares} {symbols[player]};"
31
+
32
+
33
+ def parse_moves(output: str, count: int) -> list[int]:
34
+ """The move Edax chose for each of `count` positions, as squares `row * 8 + col`."""
35
+ moves: dict[int, int] = {}
36
+ for line in output.splitlines():
37
+ row = _RESULT_ROW.match(line)
38
+ if row is None:
39
+ continue
40
+ square = _SQUARE.search(row.group(2))
41
+ if square is None:
42
+ raise ValueError(f"no move in Edax output line: {line!r}")
43
+ column = ord(square.group(1).lower()) - ord("a")
44
+ moves[int(row.group(1))] = (int(square.group(2)) - 1) * SIZE + column
45
+ if sorted(moves) != list(range(1, count + 1)):
46
+ raise ValueError(f"expected {count} moves from Edax, got {len(moves)}:\n{output}")
47
+ return [moves[i] for i in range(1, count + 1)]
48
+
49
+
50
+ def edax_agent(level: int, path: Path | str = DEFAULT_PATH, threads: int = 1) -> Agent:
51
+ """Agent that plays Edax's move at search `level`, without its opening book.
52
+
53
+ Each call runs Edax once on all positions of the batch. Edax is deterministic, so
54
+ vary the starting positions to get different games.
55
+ """
56
+ path = Path(path)
57
+ if not path.exists():
58
+ raise FileNotFoundError(f"{path} not found; build Edax with scripts/build_edax.sh")
59
+ game = Othello()
60
+
61
+ def act(state: State) -> mx.array:
62
+ boards = np.array(game.boards(state))
63
+ players = np.array(state["player"])
64
+ legal = np.array(game.legal_mask(state))
65
+ actions = np.full(len(boards), PASS, dtype=np.int32)
66
+ # Edax is only asked where there is a real choice to make.
67
+ asked = np.flatnonzero(~legal[:, PASS])
68
+ if len(asked):
69
+ with tempfile.TemporaryDirectory() as directory:
70
+ problems = Path(directory) / "positions.obf"
71
+ problems.write_text(
72
+ "".join(to_obf(boards[i], int(players[i])) + "\n" for i in asked)
73
+ )
74
+ command = [str(path), "-solve", str(problems), "-l", str(level), "-n", str(threads)]
75
+ done = subprocess.run(
76
+ command, cwd=path.parent, capture_output=True, text=True, check=True
77
+ )
78
+ moves = parse_moves(done.stdout, len(asked))
79
+ for i, move in zip(asked, moves, strict=True):
80
+ if not legal[i, move]:
81
+ position = to_obf(boards[i], int(players[i]))
82
+ raise ValueError(f"Edax played illegal move {move} in {position}")
83
+ actions[i] = move
84
+ return mx.array(actions)
85
+
86
+ return act
@@ -0,0 +1,7 @@
1
+ """Batched game environments in MLX."""
2
+
3
+ from mac_alpha_zero.games.base import BatchedGame, State, Symmetries
4
+ from mac_alpha_zero.games.connect4 import Connect4
5
+ from mac_alpha_zero.games.othello import Othello
6
+
7
+ __all__ = ["BatchedGame", "Connect4", "Othello", "State", "Symmetries"]
@@ -0,0 +1,46 @@
1
+ from typing import Protocol
2
+
3
+ import mlx.core as mx
4
+ import numpy as np
5
+
6
+ # A batched state is a dict of arrays that all share a leading batch dimension.
7
+ State = dict[str, mx.array]
8
+
9
+ # (squares (S, H * W), actions (S, num_actions)) int arrays, one row per symmetry, the
10
+ # identity first. Under symmetry k, square j of the transformed observation is square
11
+ # `squares[k, j]` of the original (all planes alike), and action j of the transformed
12
+ # policy is action `actions[k, j]` of the original.
13
+ Symmetries = tuple[np.ndarray, np.ndarray]
14
+
15
+
16
+ class BatchedGame(Protocol):
17
+ """Batched version of `reference.Game`. Values are for the player to move.
18
+
19
+ `step` may be called with illegal actions or on finished games; callers discard
20
+ those results, so it must not raise.
21
+
22
+ A game may also define `symmetries()` (see `Symmetries`), the transformations that
23
+ leave its rules unchanged. Training then augments its samples with them.
24
+ """
25
+
26
+ num_actions: int
27
+ # (height, width, planes) of one observation.
28
+ observation_shape: tuple[int, int, int]
29
+
30
+ def init(self, batch_size: int) -> State:
31
+ """`batch_size` games at the starting position."""
32
+ ...
33
+
34
+ def observe(self, state: State) -> mx.array:
35
+ """(B, *observation_shape) float32 network input, from the player to move's view."""
36
+ ...
37
+
38
+ def legal_mask(self, state: State) -> mx.array:
39
+ """(B, num_actions) bool."""
40
+ ...
41
+
42
+ def step(self, state: State, actions: mx.array) -> State: ...
43
+
44
+ def terminal(self, state: State) -> tuple[mx.array, mx.array]:
45
+ """(done, value): (B,) bool and (B,) value for the player to move, 0 if not done."""
46
+ ...
@@ -0,0 +1,86 @@
1
+ import mlx.core as mx
2
+ import numpy as np
3
+
4
+ from mac_alpha_zero.games.base import State, Symmetries
5
+
6
+ ROWS = 6
7
+ COLS = 7
8
+
9
+
10
+ class Connect4:
11
+ """Batched Connect4 with the same conventions as `reference.Connect4`.
12
+
13
+ State keys: board (B, ROWS, COLS) int8 with row 0 at the bottom, +1 for the first
14
+ player and -1 for the second; player (B,) int8, the player to move; winner (B,) int8,
15
+ the player who just completed four in a row, or 0.
16
+ """
17
+
18
+ num_actions = COLS
19
+ observation_shape = (ROWS, COLS, 2)
20
+
21
+ def init(self, batch_size: int) -> State:
22
+ return {
23
+ "board": mx.zeros((batch_size, ROWS, COLS), dtype=mx.int8),
24
+ "player": mx.ones((batch_size,), dtype=mx.int8),
25
+ "winner": mx.zeros((batch_size,), dtype=mx.int8),
26
+ }
27
+
28
+ def observe(self, state: State) -> mx.array:
29
+ """Planes: the player to move's stones, then the opponent's."""
30
+ relative = state["board"] * state["player"][:, None, None]
31
+ return mx.stack([relative == 1, relative == -1], axis=-1).astype(mx.float32)
32
+
33
+ def legal_mask(self, state: State) -> mx.array:
34
+ """(B, COLS) bool. Empty for finished games."""
35
+ top_empty = state["board"][:, ROWS - 1, :] == 0
36
+ return top_empty & (state["winner"] == 0)[:, None]
37
+
38
+ def step(self, state: State, actions: mx.array) -> State:
39
+ """Play `actions` (B,) in every game. A full column leaves the board unchanged."""
40
+ board, player = state["board"], state["player"]
41
+ heights = (board != 0).sum(axis=1)
42
+ row = mx.take_along_axis(heights, actions[:, None], axis=1)
43
+ rows = mx.arange(ROWS)[None, :, None]
44
+ cols = mx.arange(COLS)[None, None, :]
45
+ placed = (rows == row[:, :, None]) & (cols == actions[:, None, None])
46
+ board = mx.where(placed, player[:, None, None], board)
47
+ # No four existed before this move, so any four of the mover's colour is new.
48
+ wins = _has_four(board == player[:, None, None])
49
+ winner = mx.where(wins, player, mx.zeros_like(player))
50
+ return {"board": board, "player": -player, "winner": winner}
51
+
52
+ def terminal(self, state: State) -> tuple[mx.array, mx.array]:
53
+ """(done, value) per game. Value is for the player to move and 0 if not done."""
54
+ won = state["winner"] != 0
55
+ full = mx.all(state["board"][:, ROWS - 1, :] != 0, axis=1)
56
+ value = mx.where(won, -1.0, 0.0)
57
+ return won | full, value
58
+
59
+ def symmetries(self) -> Symmetries:
60
+ """The identity and the left-right mirror."""
61
+ squares = np.arange(ROWS * COLS).reshape(ROWS, COLS)
62
+ squares = np.stack([squares.reshape(-1), squares[:, ::-1].reshape(-1)])
63
+ return squares, np.stack([np.arange(COLS), np.arange(COLS)[::-1]])
64
+
65
+ def from_reference(self, states) -> State:
66
+ """Stack `reference.Connect4State`s into a batched state."""
67
+ return {
68
+ "board": mx.array(np.stack([s.board for s in states]).astype(np.int8)),
69
+ "player": mx.array(np.array([s.player for s in states], dtype=np.int8)),
70
+ "winner": mx.array(np.array([s.winner for s in states], dtype=np.int8)),
71
+ }
72
+
73
+
74
+ def _has_four(stones: mx.array) -> mx.array:
75
+ """(B, ROWS, COLS) bool -> (B,) whether any four in a row exists."""
76
+ s = stones
77
+ horizontal = s[:, :, :-3] & s[:, :, 1:-2] & s[:, :, 2:-1] & s[:, :, 3:]
78
+ vertical = s[:, :-3, :] & s[:, 1:-2, :] & s[:, 2:-1, :] & s[:, 3:, :]
79
+ up_right = s[:, :-3, :-3] & s[:, 1:-2, 1:-2] & s[:, 2:-1, 2:-1] & s[:, 3:, 3:]
80
+ up_left = s[:, :-3, 3:] & s[:, 1:-2, 2:-1] & s[:, 2:-1, 1:-2] & s[:, 3:, :-3]
81
+ return (
82
+ mx.any(horizontal, axis=(1, 2))
83
+ | mx.any(vertical, axis=(1, 2))
84
+ | mx.any(up_right, axis=(1, 2))
85
+ | mx.any(up_left, axis=(1, 2))
86
+ )
@@ -0,0 +1,105 @@
1
+ """Exact win/draw/loss solver for Connect4 on Python-int bitboards.
2
+
3
+ Used to grade moves, not to play: it only answers who wins with perfect play, not how
4
+ fast. Fast enough for positions with roughly 16 or more stones on the board.
5
+
6
+ Bit `col * 7 + row` holds the cell at (row, col); the 7th bit of each column stays empty
7
+ so that shifts never wrap into the next column.
8
+ """
9
+
10
+ import numpy as np
11
+
12
+ ROWS = 6
13
+ COLS = 7
14
+ _HEIGHT = ROWS + 1
15
+ _COLUMN_ORDER = (3, 2, 4, 1, 5, 0, 6)
16
+ _BOTTOM = [1 << (col * _HEIGHT) for col in range(COLS)]
17
+ _TOP = [1 << (col * _HEIGHT + ROWS - 1) for col in range(COLS)]
18
+ _LOWER, _EXACT, _UPPER = 0, 1, 2
19
+
20
+
21
+ def move_values(board: np.ndarray, player: int) -> dict[int, int]:
22
+ """Game-theoretic value of every legal move for `player` to move: +1, 0 or -1.
23
+
24
+ `board` is (ROWS, COLS) with row 0 at the bottom, +1 / -1 stones, and no four in a
25
+ row yet.
26
+ """
27
+ current, mask = _to_bitboards(board, player)
28
+ table: dict[tuple[int, int], tuple[int, int]] = {}
29
+ values = {}
30
+ for col in range(COLS):
31
+ if mask & _TOP[col]:
32
+ continue
33
+ move = (mask + _BOTTOM[col]) & ~mask
34
+ if _has_four(current | move):
35
+ values[col] = 1
36
+ else:
37
+ values[col] = -_negamax(mask & ~current, mask | move, -1, 1, table)
38
+ return values
39
+
40
+
41
+ def _negamax(current: int, mask: int, alpha: int, beta: int, table: dict) -> int:
42
+ """Value for the player to move, who owns `current`. The opponent has no four."""
43
+ moves = []
44
+ for col in _COLUMN_ORDER:
45
+ if mask & _TOP[col]:
46
+ continue
47
+ move = (mask + _BOTTOM[col]) & ~mask
48
+ if _has_four(current | move):
49
+ return 1
50
+ moves.append(move)
51
+ if not moves:
52
+ return 0
53
+
54
+ key = (current, mask)
55
+ entry = table.get(key)
56
+ if entry is not None:
57
+ value, flag = entry
58
+ if flag == _EXACT:
59
+ return value
60
+ if flag == _LOWER:
61
+ alpha = max(alpha, value)
62
+ else:
63
+ beta = min(beta, value)
64
+ if alpha >= beta:
65
+ return value
66
+
67
+ original_alpha = alpha
68
+ best = -1
69
+ opponent = mask & ~current
70
+ for move in moves:
71
+ value = -_negamax(opponent, mask | move, -beta, -alpha, table)
72
+ if value > best:
73
+ best = value
74
+ alpha = max(alpha, value)
75
+ if alpha >= beta:
76
+ break
77
+
78
+ if best <= original_alpha:
79
+ flag = _UPPER
80
+ elif best >= beta:
81
+ flag = _LOWER
82
+ else:
83
+ flag = _EXACT
84
+ table[key] = (best, flag)
85
+ return best
86
+
87
+
88
+ def _has_four(stones: int) -> bool:
89
+ # Shifts: 1 vertical, 7 horizontal, 6 and 8 the two diagonals.
90
+ for shift in (1, _HEIGHT, _HEIGHT - 1, _HEIGHT + 1):
91
+ pairs = stones & (stones >> shift)
92
+ if pairs & (pairs >> (2 * shift)):
93
+ return True
94
+ return False
95
+
96
+
97
+ def _to_bitboards(board: np.ndarray, player: int) -> tuple[int, int]:
98
+ current = 0
99
+ mask = 0
100
+ for row, col in zip(*np.nonzero(board), strict=True):
101
+ bit = 1 << (int(col) * _HEIGHT + int(row))
102
+ mask |= bit
103
+ if board[row, col] == player:
104
+ current |= bit
105
+ return current, mask
@@ -0,0 +1,150 @@
1
+ import mlx.core as mx
2
+ import numpy as np
3
+
4
+ from mac_alpha_zero.games.base import State, Symmetries
5
+
6
+ SIZE = 8
7
+ PASS = SIZE * SIZE
8
+
9
+
10
+ def _u64(value: int) -> mx.array:
11
+ # Built through NumPy: MLX cannot make a uint64 array from a large Python int.
12
+ return mx.array(np.array(value, dtype=np.uint64))
13
+
14
+
15
+ _ZERO = _u64(0)
16
+ _ONE = _u64(1)
17
+ _SQUARES = mx.array(np.arange(PASS, dtype=np.uint64))
18
+ _ALL = 0xFFFFFFFFFFFFFFFF
19
+ _INNER_COLUMNS = 0x7E7E7E7E7E7E7E7E
20
+ # (shift towards higher bits?, distance, squares a line may pass through). Lines that
21
+ # change column may not pass through the edge columns, which stops them wrapping around.
22
+ _DIRECTIONS = [
23
+ (left, _u64(distance), _u64(passable))
24
+ for distance, passable in (
25
+ (1, _INNER_COLUMNS),
26
+ (7, _INNER_COLUMNS),
27
+ (9, _INNER_COLUMNS),
28
+ (8, _ALL),
29
+ )
30
+ for left in (True, False)
31
+ ]
32
+
33
+
34
+ class Othello:
35
+ """Batched Othello on bitboards, with the same rules as `reference.Othello`.
36
+
37
+ State keys: own and opp (B,) uint64, the discs of the player to move and of the
38
+ opponent, with bit `row * 8 + col` for each square; player (B,) int8, +1 if the first
39
+ player (black) is to move and -1 otherwise.
40
+ """
41
+
42
+ num_actions = PASS + 1
43
+ observation_shape = (SIZE, SIZE, 2)
44
+
45
+ def init(self, batch_size: int) -> State:
46
+ black = (1 << (3 * SIZE + 4)) | (1 << (4 * SIZE + 3))
47
+ white = (1 << (3 * SIZE + 3)) | (1 << (4 * SIZE + 4))
48
+ return {
49
+ "own": mx.broadcast_to(_u64(black), (batch_size,)),
50
+ "opp": mx.broadcast_to(_u64(white), (batch_size,)),
51
+ "player": mx.ones((batch_size,), dtype=mx.int8),
52
+ }
53
+
54
+ def observe(self, state: State) -> mx.array:
55
+ """Planes: the player to move's discs, then the opponent's."""
56
+ planes = mx.stack([_bits(state["own"]), _bits(state["opp"])], axis=-1)
57
+ return planes.reshape(-1, SIZE, SIZE, 2).astype(mx.float32)
58
+
59
+ def legal_mask(self, state: State) -> mx.array:
60
+ """(B, 65) bool. The pass is legal only if it is the only move. Empty when done."""
61
+ own, opp = state["own"], state["opp"]
62
+ placements = _placements(own, opp)
63
+ can_pass = (placements == _ZERO) & (_placements(opp, own) != _ZERO)
64
+ return mx.concatenate([_bits(placements), can_pass[:, None]], axis=1)
65
+
66
+ def step(self, state: State, actions: mx.array) -> State:
67
+ """Play `actions` (B,) in every game. An illegal action gives a meaningless state."""
68
+ own, opp = state["own"], state["opp"]
69
+ is_pass = actions >= PASS
70
+ square = mx.where(is_pass, 0, actions).astype(mx.uint64)
71
+ disc = mx.where(is_pass, _ZERO, mx.left_shift(_ONE, square))
72
+ flips = _flips(own, opp, disc)
73
+ return {
74
+ "own": opp & ~flips,
75
+ "opp": own | disc | flips,
76
+ "player": -state["player"],
77
+ }
78
+
79
+ def terminal(self, state: State) -> tuple[mx.array, mx.array]:
80
+ """(done, value) per game. Value is for the player to move and 0 if not done."""
81
+ own, opp = state["own"], state["opp"]
82
+ done = (_placements(own, opp) == _ZERO) & (_placements(opp, own) == _ZERO)
83
+ margin = _bits(own).sum(axis=1) - _bits(opp).sum(axis=1)
84
+ return done, mx.where(done, mx.sign(margin), 0).astype(mx.float32)
85
+
86
+ def boards(self, state: State) -> mx.array:
87
+ """(B, 8, 8) int8 boards as in `reference.OthelloState`: +1 black, -1 white."""
88
+ relative = _bits(state["own"]).astype(mx.int8) - _bits(state["opp"]).astype(mx.int8)
89
+ return relative.reshape(-1, SIZE, SIZE) * state["player"][:, None, None]
90
+
91
+ def symmetries(self) -> Symmetries:
92
+ """The 8 rotations and reflections of the board, as `reference.Othello` numbers
93
+ them. The pass (action 64) maps to itself."""
94
+ squares = np.arange(PASS).reshape(SIZE, SIZE)
95
+ rotations = [np.rot90(squares, k) for k in range(4)]
96
+ squares = np.stack([board.reshape(PASS) for board in rotations + [r.T for r in rotations]])
97
+ passes = np.full((len(squares), 1), PASS)
98
+ return squares, np.concatenate([squares, passes], axis=1)
99
+
100
+ def from_reference(self, states) -> State:
101
+ """Stack `reference.OthelloState`s into a batched state."""
102
+ weights = np.uint64(1) << np.arange(PASS, dtype=np.uint64)
103
+
104
+ def pack(discs: list[np.ndarray]) -> mx.array:
105
+ flat = np.stack(discs).reshape(len(discs), PASS)
106
+ return mx.array(np.where(flat, weights, np.uint64(0)).sum(axis=1, dtype=np.uint64))
107
+
108
+ return {
109
+ "own": pack([s.board == s.player for s in states]),
110
+ "opp": pack([s.board == -s.player for s in states]),
111
+ "player": mx.array(np.array([s.player for s in states], dtype=np.int8)),
112
+ }
113
+
114
+
115
+ def _shift(bits: mx.array, left: bool, distance: mx.array) -> mx.array:
116
+ return mx.left_shift(bits, distance) if left else mx.right_shift(bits, distance)
117
+
118
+
119
+ def _line(start: mx.array, opp: mx.array, left: bool, distance: mx.array, passable: mx.array):
120
+ """Unbroken run of opponent discs next to `start` in one direction (at most 6)."""
121
+ through = opp & passable
122
+ run = through & _shift(start, left, distance)
123
+ for _ in range(SIZE - 3):
124
+ run = run | (through & _shift(run, left, distance))
125
+ return run
126
+
127
+
128
+ def _placements(own: mx.array, opp: mx.array) -> mx.array:
129
+ """(B,) uint64: empty squares where the owner of `own` would flip at least one disc."""
130
+ empty = ~(own | opp)
131
+ result = mx.zeros_like(own)
132
+ for left, distance, passable in _DIRECTIONS:
133
+ run = _line(own, opp, left, distance, passable)
134
+ result = result | (_shift(run, left, distance) & empty)
135
+ return result
136
+
137
+
138
+ def _flips(own: mx.array, opp: mx.array, disc: mx.array) -> mx.array:
139
+ """(B,) uint64: opponent discs flipped when the owner of `own` places `disc`."""
140
+ result = mx.zeros_like(own)
141
+ for left, distance, passable in _DIRECTIONS:
142
+ run = _line(disc, opp, left, distance, passable)
143
+ closed = (_shift(run, left, distance) & own) != _ZERO
144
+ result = result | mx.where(closed, run, _ZERO)
145
+ return result
146
+
147
+
148
+ def _bits(bitboard: mx.array) -> mx.array:
149
+ """(B,) uint64 -> (B, 64) bool, one entry per square."""
150
+ return (mx.right_shift(bitboard[:, None], _SQUARES) & _ONE) != _ZERO