update breakthrough_mcvs.py
Browse files- breakthrough_mcvs.py +1149 -1149
breakthrough_mcvs.py
CHANGED
|
@@ -1,1149 +1,1149 @@
|
|
| 1 |
-
import numpy as np
|
| 2 |
-
import torch
|
| 3 |
-
import torch.nn as nn
|
| 4 |
-
import torch.optim as optim
|
| 5 |
-
import torch.nn.functional as F
|
| 6 |
-
from torch.utils.data import DataLoader, TensorDataset
|
| 7 |
-
from typing import List, Dict, Tuple
|
| 8 |
-
import random
|
| 9 |
-
import time
|
| 10 |
-
import os
|
| 11 |
-
import bisect
|
| 12 |
-
|
| 13 |
-
# ============================================================================
|
| 14 |
-
# HILBERT CURVE UTILITIES
|
| 15 |
-
# ============================================================================
|
| 16 |
-
|
| 17 |
-
def xy2d(n: int, x: int, y: int) -> int:
|
| 18 |
-
"""Convert (x,y) to Hilbert curve distance."""
|
| 19 |
-
d = 0
|
| 20 |
-
s = n // 2
|
| 21 |
-
while s > 0:
|
| 22 |
-
rx = 1 if (x & s) > 0 else 0
|
| 23 |
-
ry = 1 if (y & s) > 0 else 0
|
| 24 |
-
d += s * s * ((3 * rx) ^ ry)
|
| 25 |
-
if ry == 0:
|
| 26 |
-
if rx == 1:
|
| 27 |
-
x = n - 1 - x
|
| 28 |
-
y = n - 1 - y
|
| 29 |
-
x, y = y, x
|
| 30 |
-
s //= 2
|
| 31 |
-
return d
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
def matrix_to_hilbert_index(W: np.ndarray) -> int:
|
| 35 |
-
if W.size == 0:
|
| 36 |
-
return 0
|
| 37 |
-
W_flat = W.flatten()
|
| 38 |
-
max_idx = np.argmax(W_flat)
|
| 39 |
-
x = max_idx % 64
|
| 40 |
-
y = max_idx // 64
|
| 41 |
-
return xy2d(64, x, y)
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
def move_to_index(fr: int, fc: int, tr: int, tc: int) -> int:
|
| 45 |
-
"""Convert move tuple (fr,fc,tr,tc) to policy index in [0,4095]."""
|
| 46 |
-
from_sq = fr * 8 + fc
|
| 47 |
-
to_sq = tr * 8 + tc
|
| 48 |
-
return from_sq * 64 + to_sq
|
| 49 |
-
|
| 50 |
-
# ============================================================================
|
| 51 |
-
# ABC MODEL DYNAMIC
|
| 52 |
-
# ============================================================================
|
| 53 |
-
|
| 54 |
-
class ABCModelDynamic:
|
| 55 |
-
"""ABC Model with displacement-based B matrices."""
|
| 56 |
-
|
| 57 |
-
def __init__(self, n: int = 2, t: float = 1.0, T: float = 1.41):
|
| 58 |
-
self.n = n
|
| 59 |
-
self.t = t
|
| 60 |
-
self.T = T
|
| 61 |
-
self.c0 = np.array([0.0, 0.0, 1.0])
|
| 62 |
-
self.B_blocks = []
|
| 63 |
-
self.piece_positions = []
|
| 64 |
-
self.a_product = np.eye(3)
|
| 65 |
-
self.delta = {}
|
| 66 |
-
self.kappa = {}
|
| 67 |
-
self.stage = 0
|
| 68 |
-
self.MB_current = self.c0.copy()
|
| 69 |
-
self.MB_previous = self.c0.copy()
|
| 70 |
-
self.history = []
|
| 71 |
-
|
| 72 |
-
def create_B_displacement(self, dx: float, dy: float) -> np.ndarray:
|
| 73 |
-
return np.array([
|
| 74 |
-
[1.0, 0.0, dx],
|
| 75 |
-
[0.0, 1.0, dy],
|
| 76 |
-
[0.0, 0.0, 1.0]
|
| 77 |
-
])
|
| 78 |
-
|
| 79 |
-
def add_piece(self, position: tuple, delta_values: tuple, kappa_vector: np.ndarray = None):
|
| 80 |
-
x, y = position
|
| 81 |
-
current_MB = self.MB_current.copy()
|
| 82 |
-
dx = x - current_MB[0]
|
| 83 |
-
dy = y - current_MB[1]
|
| 84 |
-
B_i = self.create_B_displacement(dx, dy)
|
| 85 |
-
idx = len(self.B_blocks)
|
| 86 |
-
self.B_blocks.append(B_i)
|
| 87 |
-
self.piece_positions.append((x, y))
|
| 88 |
-
self.a_product = self.a_product @ B_i
|
| 89 |
-
self.MB_previous = self.MB_current.copy()
|
| 90 |
-
self.MB_current = self.a_product @ self.c0
|
| 91 |
-
self.delta[idx] = delta_values
|
| 92 |
-
if kappa_vector is None:
|
| 93 |
-
kappa_vector = np.array(delta_values)
|
| 94 |
-
self.kappa[idx] = kappa_vector
|
| 95 |
-
self.stage += 1
|
| 96 |
-
self.history.append({
|
| 97 |
-
'stage': self.stage,
|
| 98 |
-
'SB_position': (x, y),
|
| 99 |
-
'displacement': (dx, dy),
|
| 100 |
-
'B_i': B_i.copy(),
|
| 101 |
-
'a_t': self.a_product.copy(),
|
| 102 |
-
'MB_prev': self.MB_previous.copy(),
|
| 103 |
-
'MB_curr': self.MB_current.copy(),
|
| 104 |
-
'delta': delta_values,
|
| 105 |
-
'kappa': kappa_vector.copy()
|
| 106 |
-
})
|
| 107 |
-
|
| 108 |
-
# ============================================================================
|
| 109 |
-
# WEIGHTED MATRIX ABC
|
| 110 |
-
# ============================================================================
|
| 111 |
-
|
| 112 |
-
class WeightedMatrixABC:
|
| 113 |
-
"""Compute weighted adjacency matrix from ABCModelDynamic."""
|
| 114 |
-
|
| 115 |
-
def __init__(self, abc_model: ABCModelDynamic, sigma: float = 1.0):
|
| 116 |
-
self.abc = abc_model
|
| 117 |
-
self.n = abc_model.n
|
| 118 |
-
self.t = abc_model.t
|
| 119 |
-
self.T = abc_model.T
|
| 120 |
-
self.sigma = sigma
|
| 121 |
-
self.positions = None
|
| 122 |
-
self.D = None
|
| 123 |
-
self.A = None
|
| 124 |
-
self.S = None
|
| 125 |
-
self.F = None
|
| 126 |
-
self.W = None
|
| 127 |
-
|
| 128 |
-
def compute_piece_positions(self) -> np.ndarray:
|
| 129 |
-
positions = []
|
| 130 |
-
for pos in self.abc.piece_positions:
|
| 131 |
-
x, y = pos
|
| 132 |
-
positions.append(np.array([x, y, 1.0]))
|
| 133 |
-
self.positions = np.array(positions)
|
| 134 |
-
return self.positions
|
| 135 |
-
|
| 136 |
-
def compute_distance_matrix(self) -> np.ndarray:
|
| 137 |
-
if self.positions is None:
|
| 138 |
-
self.compute_piece_positions()
|
| 139 |
-
num = len(self.positions)
|
| 140 |
-
D = np.zeros((num, num))
|
| 141 |
-
for i in range(num):
|
| 142 |
-
for j in range(num):
|
| 143 |
-
pos_i = self.positions[i][:2]
|
| 144 |
-
pos_j = self.positions[j][:2]
|
| 145 |
-
D[i, j] = np.linalg.norm(pos_i - pos_j)
|
| 146 |
-
self.D = D
|
| 147 |
-
return D
|
| 148 |
-
|
| 149 |
-
def compute_adjacency_matrix(self) -> np.ndarray:
|
| 150 |
-
if self.D is None:
|
| 151 |
-
self.compute_distance_matrix()
|
| 152 |
-
num = len(self.positions)
|
| 153 |
-
A = np.zeros((num, num))
|
| 154 |
-
isolated = set()
|
| 155 |
-
for i in range(num):
|
| 156 |
-
has_neighbor = False
|
| 157 |
-
for j in range(num):
|
| 158 |
-
if i != j and self.t <= self.D[i, j] <= self.T:
|
| 159 |
-
has_neighbor = True
|
| 160 |
-
break
|
| 161 |
-
if not has_neighbor:
|
| 162 |
-
isolated.add(i)
|
| 163 |
-
for i in range(num):
|
| 164 |
-
for j in range(num):
|
| 165 |
-
if i != j and self.t <= self.D[i, j] <= self.T:
|
| 166 |
-
A[i, j] = 1.0
|
| 167 |
-
elif i == j and i in isolated:
|
| 168 |
-
A[i, j] = 1.0
|
| 169 |
-
self.A = A
|
| 170 |
-
return A
|
| 171 |
-
|
| 172 |
-
def compute_spatial_matrix(self) -> np.ndarray:
|
| 173 |
-
if self.D is None:
|
| 174 |
-
self.compute_distance_matrix()
|
| 175 |
-
num = len(self.positions)
|
| 176 |
-
S = np.zeros((num, num))
|
| 177 |
-
for i in range(num):
|
| 178 |
-
for j in range(num):
|
| 179 |
-
S[i, j] = np.exp(-self.D[i, j] ** 2 / (2 * self.sigma ** 2))
|
| 180 |
-
self.S = S
|
| 181 |
-
return S
|
| 182 |
-
|
| 183 |
-
def compute_feature_matrix(self) -> np.ndarray:
|
| 184 |
-
num = len(self.positions)
|
| 185 |
-
F = np.zeros((num, num))
|
| 186 |
-
kappas = []
|
| 187 |
-
for i in range(num):
|
| 188 |
-
if i in self.abc.kappa:
|
| 189 |
-
kappas.append(self.abc.kappa[i])
|
| 190 |
-
elif i in self.abc.delta:
|
| 191 |
-
kappas.append(np.array(self.abc.delta[i]))
|
| 192 |
-
else:
|
| 193 |
-
kappas.append(np.array([1.0, 1.0, 1.0]))
|
| 194 |
-
for i in range(num):
|
| 195 |
-
for j in range(num):
|
| 196 |
-
kappa_i = kappas[i]
|
| 197 |
-
kappa_j = kappas[j]
|
| 198 |
-
dot_product = np.dot(kappa_i, kappa_j)
|
| 199 |
-
norm_i = np.linalg.norm(kappa_i)
|
| 200 |
-
norm_j = np.linalg.norm(kappa_j)
|
| 201 |
-
if norm_i > 0 and norm_j > 0:
|
| 202 |
-
F[i, j] = dot_product / (norm_i * norm_j)
|
| 203 |
-
else:
|
| 204 |
-
F[i, j] = 0.0
|
| 205 |
-
self.F = F
|
| 206 |
-
return F
|
| 207 |
-
|
| 208 |
-
def compute_weighted_matrix(self) -> np.ndarray:
|
| 209 |
-
if self.A is None:
|
| 210 |
-
self.compute_adjacency_matrix()
|
| 211 |
-
if self.S is None:
|
| 212 |
-
self.compute_spatial_matrix()
|
| 213 |
-
if self.F is None:
|
| 214 |
-
self.compute_feature_matrix()
|
| 215 |
-
W = self.A * self.S * self.F
|
| 216 |
-
self.W = W
|
| 217 |
-
return W
|
| 218 |
-
|
| 219 |
-
# ============================================================================
|
| 220 |
-
# BREAKTHROUGH GAME LOGIC
|
| 221 |
-
# ============================================================================
|
| 222 |
-
|
| 223 |
-
class Breakthrough:
|
| 224 |
-
ROWS, COLS = 8, 8
|
| 225 |
-
EMPTY, PLAYER1, PLAYER2 = 0, 1, 2
|
| 226 |
-
|
| 227 |
-
def __init__(self):
|
| 228 |
-
self.board = np.zeros((self.ROWS, self.COLS), dtype=np.int32)
|
| 229 |
-
self.board[0:2, :] = self.PLAYER1
|
| 230 |
-
self.board[6:8, :] = self.PLAYER2
|
| 231 |
-
self.move_count = 0
|
| 232 |
-
self._move_stack: List[Tuple] = [] # (fr, fc, tr, tc, captured)
|
| 233 |
-
self._cached_matrix = None
|
| 234 |
-
|
| 235 |
-
def copy(self):
|
| 236 |
-
new_game = Breakthrough.__new__(Breakthrough)
|
| 237 |
-
new_game.board = self.board.copy()
|
| 238 |
-
new_game.move_count = self.move_count
|
| 239 |
-
new_game._move_stack = list(self._move_stack)
|
| 240 |
-
new_game._cached_matrix = (
|
| 241 |
-
self._cached_matrix.copy() if self._cached_matrix is not None else None
|
| 242 |
-
)
|
| 243 |
-
return new_game
|
| 244 |
-
|
| 245 |
-
def get_legal_moves(self) -> List[Tuple[int, int, int, int]]:
|
| 246 |
-
moves = []
|
| 247 |
-
player = self.PLAYER1 if self.move_count % 2 == 0 else self.PLAYER2
|
| 248 |
-
direction = 1 if player == self.PLAYER1 else -1
|
| 249 |
-
opponent = 3 - player
|
| 250 |
-
for r in range(self.ROWS):
|
| 251 |
-
for c in range(self.COLS):
|
| 252 |
-
if self.board[r, c] == player:
|
| 253 |
-
nr = r + direction
|
| 254 |
-
if 0 <= nr < self.ROWS:
|
| 255 |
-
if self.board[nr, c] == self.EMPTY:
|
| 256 |
-
moves.append((r, c, nr, c))
|
| 257 |
-
for dc in [-1, 1]:
|
| 258 |
-
nc = c + dc
|
| 259 |
-
if 0 <= nc < self.COLS and self.board[nr, nc] == opponent:
|
| 260 |
-
moves.append((r, c, nr, nc))
|
| 261 |
-
return moves
|
| 262 |
-
|
| 263 |
-
def apply_move(self, move: Tuple[int, int, int, int]) -> None:
|
| 264 |
-
fr, fc, tr, tc = move
|
| 265 |
-
captured = int(self.board[tr, tc])
|
| 266 |
-
self._move_stack.append((fr, fc, tr, tc, captured))
|
| 267 |
-
self.board[tr, tc] = self.board[fr, fc]
|
| 268 |
-
self.board[fr, fc] = self.EMPTY
|
| 269 |
-
self.move_count += 1
|
| 270 |
-
self._cached_matrix = None
|
| 271 |
-
|
| 272 |
-
def undo_move(self) -> None:
|
| 273 |
-
if not self._move_stack:
|
| 274 |
-
return
|
| 275 |
-
fr, fc, tr, tc, captured = self._move_stack.pop()
|
| 276 |
-
self.board[fr, fc] = self.board[tr, tc]
|
| 277 |
-
self.board[tr, tc] = captured
|
| 278 |
-
self.move_count -= 1
|
| 279 |
-
self._cached_matrix = None
|
| 280 |
-
|
| 281 |
-
def check_winner(self) -> int:
|
| 282 |
-
"""Return PLAYER1 (1) if row 7 reached, PLAYER2 (2) if row 0 reached, else EMPTY (0)."""
|
| 283 |
-
if np.any(self.board[7, :] == self.PLAYER1):
|
| 284 |
-
return self.PLAYER1
|
| 285 |
-
if np.any(self.board[0, :] == self.PLAYER2):
|
| 286 |
-
return self.PLAYER2
|
| 287 |
-
return self.EMPTY
|
| 288 |
-
|
| 289 |
-
def is_terminal(self) -> bool:
|
| 290 |
-
return self.check_winner() != self.EMPTY or len(self.get_legal_moves()) == 0
|
| 291 |
-
|
| 292 |
-
def get_weighted_adjacency_matrix(self) -> np.ndarray:
|
| 293 |
-
if self._cached_matrix is not None:
|
| 294 |
-
return self._cached_matrix
|
| 295 |
-
|
| 296 |
-
occupied = []
|
| 297 |
-
for r in range(8):
|
| 298 |
-
for c in range(8):
|
| 299 |
-
piece = self.board[r, c]
|
| 300 |
-
if piece != self.EMPTY:
|
| 301 |
-
x = c - 3.5
|
| 302 |
-
y = 3.5 - r
|
| 303 |
-
delta_2 = 1.0 if piece == self.PLAYER1 else 1.1
|
| 304 |
-
kappa = np.array([1.0, delta_2, 1.0])
|
| 305 |
-
hilbert_d = xy2d(8, c, r)
|
| 306 |
-
occupied.append((hilbert_d, (x, y), kappa))
|
| 307 |
-
|
| 308 |
-
occupied.sort(key=lambda t: t[0])
|
| 309 |
-
|
| 310 |
-
abc = ABCModelDynamic(n=2, t=1.0, T=1.41)
|
| 311 |
-
for _, pos, kappa_vec in occupied:
|
| 312 |
-
abc.add_piece(pos, delta_values=(1.0, float(kappa_vec[1]), 1.0), kappa_vector=kappa_vec)
|
| 313 |
-
|
| 314 |
-
builder = WeightedMatrixABC(abc, sigma=1.0)
|
| 315 |
-
W_small = builder.compute_weighted_matrix()
|
| 316 |
-
|
| 317 |
-
n = len(occupied)
|
| 318 |
-
W = np.zeros((64, 64), dtype=np.float32)
|
| 319 |
-
if n > 0:
|
| 320 |
-
W[:n, :n] = W_small
|
| 321 |
-
|
| 322 |
-
self._cached_matrix = W
|
| 323 |
-
return W
|
| 324 |
-
|
| 325 |
-
# ============================================================================
|
| 326 |
-
# NEURAL NETWORKS
|
| 327 |
-
# ============================================================================
|
| 328 |
-
|
| 329 |
-
class PolicyNetworkCNN(nn.Module):
|
| 330 |
-
def __init__(self):
|
| 331 |
-
super().__init__()
|
| 332 |
-
self.conv = nn.Sequential(
|
| 333 |
-
nn.Conv2d(1, 64, kernel_size=5, padding=2, stride=2),
|
| 334 |
-
nn.ReLU(),
|
| 335 |
-
nn.Conv2d(64, 128, kernel_size=5, padding=2, stride=2),
|
| 336 |
-
nn.ReLU(),
|
| 337 |
-
nn.Conv2d(128, 128, kernel_size=3, padding=1, stride=2),
|
| 338 |
-
nn.ReLU(),
|
| 339 |
-
)
|
| 340 |
-
self.fc = nn.Linear(128 * 8 * 8, 4096)
|
| 341 |
-
|
| 342 |
-
def forward(self, x):
|
| 343 |
-
x = self.conv(x)
|
| 344 |
-
x = x.view(x.size(0), -1)
|
| 345 |
-
return self.fc(x)
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
class ValueNetworkCNN(nn.Module):
|
| 349 |
-
def __init__(self):
|
| 350 |
-
super().__init__()
|
| 351 |
-
self.conv = nn.Sequential(
|
| 352 |
-
nn.Conv2d(1, 64, kernel_size=5, padding=2, stride=2),
|
| 353 |
-
nn.ReLU(),
|
| 354 |
-
nn.Conv2d(64, 128, kernel_size=5, padding=2, stride=2),
|
| 355 |
-
nn.ReLU(),
|
| 356 |
-
nn.Conv2d(128, 128, kernel_size=3, padding=1, stride=2),
|
| 357 |
-
nn.ReLU(),
|
| 358 |
-
)
|
| 359 |
-
self.fc = nn.Sequential(
|
| 360 |
-
nn.Linear(128 * 8 * 8, 512),
|
| 361 |
-
nn.ReLU(),
|
| 362 |
-
nn.Linear(512, 1),
|
| 363 |
-
nn.Tanh()
|
| 364 |
-
)
|
| 365 |
-
|
| 366 |
-
def forward(self, x):
|
| 367 |
-
x = self.conv(x)
|
| 368 |
-
x = x.view(x.size(0), -1)
|
| 369 |
-
return self.fc(x)
|
| 370 |
-
|
| 371 |
-
# ============================================================================
|
| 372 |
-
# ZONE DATABASE
|
| 373 |
-
# ============================================================================
|
| 374 |
-
|
| 375 |
-
class HilbertOrderedZoneDatabase:
|
| 376 |
-
def __init__(self, filepath: str = "breakthrough_zone_db.npz", max_size: int = 10000):
|
| 377 |
-
self.filepath = filepath
|
| 378 |
-
self.max_size = max_size
|
| 379 |
-
self.winning_matrices = []
|
| 380 |
-
self.winning_indices = []
|
| 381 |
-
self.losing_matrices = []
|
| 382 |
-
self.losing_indices = []
|
| 383 |
-
self.draw_matrices = []
|
| 384 |
-
self.draw_indices = []
|
| 385 |
-
self.load()
|
| 386 |
-
|
| 387 |
-
def add_winning_matrix(self, W: np.ndarray):
|
| 388 |
-
if W.shape != (64, 64):
|
| 389 |
-
return
|
| 390 |
-
hilbert_idx = matrix_to_hilbert_index(W)
|
| 391 |
-
pos = bisect.bisect_left(self.winning_indices, hilbert_idx)
|
| 392 |
-
self.winning_indices.insert(pos, hilbert_idx)
|
| 393 |
-
self.winning_matrices.insert(pos, W.copy())
|
| 394 |
-
|
| 395 |
-
def add_losing_matrix(self, W: np.ndarray):
|
| 396 |
-
if W.shape != (64, 64):
|
| 397 |
-
return
|
| 398 |
-
hilbert_idx = matrix_to_hilbert_index(W)
|
| 399 |
-
pos = bisect.bisect_left(self.losing_indices, hilbert_idx)
|
| 400 |
-
self.losing_indices.insert(pos, hilbert_idx)
|
| 401 |
-
self.losing_matrices.insert(pos, W.copy())
|
| 402 |
-
|
| 403 |
-
def add_draw_matrix(self, W: np.ndarray):
|
| 404 |
-
if W.shape != (64, 64):
|
| 405 |
-
return
|
| 406 |
-
hilbert_idx = matrix_to_hilbert_index(W)
|
| 407 |
-
pos = bisect.bisect_left(self.draw_indices, hilbert_idx)
|
| 408 |
-
self.draw_indices.insert(pos, hilbert_idx)
|
| 409 |
-
self.draw_matrices.insert(pos, W.copy())
|
| 410 |
-
|
| 411 |
-
def add_game_record(self, trajectory: List[Breakthrough], result: int, sample_rate: float = 0.3):
|
| 412 |
-
sampled_states = []
|
| 413 |
-
for i, state in enumerate(trajectory):
|
| 414 |
-
if i == 0 or i == len(trajectory) - 1:
|
| 415 |
-
sampled_states.append(state)
|
| 416 |
-
elif random.random() < sample_rate:
|
| 417 |
-
sampled_states.append(state)
|
| 418 |
-
for state in sampled_states:
|
| 419 |
-
W = state.get_weighted_adjacency_matrix()
|
| 420 |
-
if result == 1:
|
| 421 |
-
self.add_winning_matrix(W)
|
| 422 |
-
elif result == -1:
|
| 423 |
-
self.add_losing_matrix(W)
|
| 424 |
-
else:
|
| 425 |
-
self.add_draw_matrix(W)
|
| 426 |
-
|
| 427 |
-
def save(self):
|
| 428 |
-
threshold = int(self.max_size * 0.8)
|
| 429 |
-
if (len(self.winning_matrices) > threshold or
|
| 430 |
-
len(self.losing_matrices) > threshold or
|
| 431 |
-
len(self.draw_matrices) > threshold):
|
| 432 |
-
print("Pruning database before save...")
|
| 433 |
-
self.prune_database(target_size=int(self.max_size * 0.7))
|
| 434 |
-
try:
|
| 435 |
-
np.savez_compressed(
|
| 436 |
-
self.filepath,
|
| 437 |
-
winning=np.array(self.winning_matrices, dtype=object),
|
| 438 |
-
winning_indices=np.array(self.winning_indices),
|
| 439 |
-
losing=np.array(self.losing_matrices, dtype=object),
|
| 440 |
-
losing_indices=np.array(self.losing_indices),
|
| 441 |
-
draw=np.array(self.draw_matrices, dtype=object),
|
| 442 |
-
draw_indices=np.array(self.draw_indices),
|
| 443 |
-
)
|
| 444 |
-
print(f"Zone DB saved: W={len(self.winning_matrices)}, L={len(self.losing_matrices)}, D={len(self.draw_matrices)}")
|
| 445 |
-
except MemoryError:
|
| 446 |
-
print("MemoryError during save! Pruning more aggressively...")
|
| 447 |
-
self.prune_database(target_size=1000)
|
| 448 |
-
np.savez_compressed(
|
| 449 |
-
self.filepath,
|
| 450 |
-
winning=np.array(self.winning_matrices, dtype=object),
|
| 451 |
-
winning_indices=np.array(self.winning_indices),
|
| 452 |
-
losing=np.array(self.losing_matrices, dtype=object),
|
| 453 |
-
losing_indices=np.array(self.losing_indices),
|
| 454 |
-
draw=np.array(self.draw_matrices, dtype=object),
|
| 455 |
-
draw_indices=np.array(self.draw_indices),
|
| 456 |
-
)
|
| 457 |
-
|
| 458 |
-
def load(self):
|
| 459 |
-
if os.path.exists(self.filepath):
|
| 460 |
-
try:
|
| 461 |
-
data = np.load(self.filepath, allow_pickle=True)
|
| 462 |
-
if 'winning' in data and 'winning_indices' in data:
|
| 463 |
-
self.winning_matrices = list(data['winning'])
|
| 464 |
-
self.winning_indices = list(data['winning_indices'])
|
| 465 |
-
self.losing_matrices = list(data['losing'])
|
| 466 |
-
self.losing_indices = list(data['losing_indices'])
|
| 467 |
-
self.draw_matrices = list(data['draw'])
|
| 468 |
-
self.draw_indices = list(data['draw_indices'])
|
| 469 |
-
elif 'winning_matrices' in data and 'winning_indices' in data:
|
| 470 |
-
self.winning_matrices = list(data['winning_matrices'])
|
| 471 |
-
self.winning_indices = list(data['winning_indices'])
|
| 472 |
-
self.losing_matrices = list(data['losing_matrices'])
|
| 473 |
-
self.losing_indices = list(data['losing_indices'])
|
| 474 |
-
self.draw_matrices = list(data['draw_matrices'])
|
| 475 |
-
self.draw_indices = list(data['draw_indices'])
|
| 476 |
-
else:
|
| 477 |
-
try:
|
| 478 |
-
self.winning_matrices = list(data.get('winning', data.get('winning_matrices', [])))
|
| 479 |
-
self.winning_indices = list(data.get('winning_indices', []))
|
| 480 |
-
self.losing_matrices = list(data.get('losing', data.get('losing_matrices', [])))
|
| 481 |
-
self.losing_indices = list(data.get('losing_indices', []))
|
| 482 |
-
self.draw_matrices = list(data.get('draw', data.get('draw_matrices', [])))
|
| 483 |
-
self.draw_indices = list(data.get('draw_indices', []))
|
| 484 |
-
except Exception:
|
| 485 |
-
self.winning_matrices = []
|
| 486 |
-
self.winning_indices = []
|
| 487 |
-
self.losing_matrices = []
|
| 488 |
-
self.losing_indices = []
|
| 489 |
-
self.draw_matrices = []
|
| 490 |
-
self.draw_indices = []
|
| 491 |
-
print(f"Loaded zone DB: W={len(self.winning_matrices)}, L={len(self.losing_matrices)}, D={len(self.draw_matrices)}")
|
| 492 |
-
except Exception as e:
|
| 493 |
-
print(f"Failed to load zone database: {e}")
|
| 494 |
-
|
| 495 |
-
def prune_database(self, target_size: int = 5000):
|
| 496 |
-
def prune_zone(matrices, indices, target):
|
| 497 |
-
if len(matrices) <= target:
|
| 498 |
-
return matrices, indices
|
| 499 |
-
step = max(1, len(matrices) // target)
|
| 500 |
-
keep_idx = list(range(0, len(matrices), step))[:target]
|
| 501 |
-
return [matrices[i] for i in keep_idx], [indices[i] for i in keep_idx]
|
| 502 |
-
|
| 503 |
-
old_sizes = (len(self.winning_matrices), len(self.losing_matrices), len(self.draw_matrices))
|
| 504 |
-
self.winning_matrices, self.winning_indices = prune_zone(
|
| 505 |
-
self.winning_matrices, self.winning_indices, target_size)
|
| 506 |
-
self.losing_matrices, self.losing_indices = prune_zone(
|
| 507 |
-
self.losing_matrices, self.losing_indices, target_size)
|
| 508 |
-
self.draw_matrices, self.draw_indices = prune_zone(
|
| 509 |
-
self.draw_matrices, self.draw_indices, target_size)
|
| 510 |
-
new_sizes = (len(self.winning_matrices), len(self.losing_matrices), len(self.draw_matrices))
|
| 511 |
-
print(f"Pruned: W {old_sizes[0]}->{new_sizes[0]}, L {old_sizes[1]}->{new_sizes[1]}, D {old_sizes[2]}->{new_sizes[2]}")
|
| 512 |
-
|
| 513 |
-
def compute_zone_score(self, W: np.ndarray, k: int = 5, beta: float = 0.5) -> float:
|
| 514 |
-
if W.shape != (64, 64):
|
| 515 |
-
return 0.0
|
| 516 |
-
|
| 517 |
-
def knn_similarity(matrices, k_val):
|
| 518 |
-
if len(matrices) == 0:
|
| 519 |
-
return 0.0
|
| 520 |
-
k_actual = min(k_val, len(matrices))
|
| 521 |
-
distances = [np.sum(np.abs(W - mat)) / (64.0 * 64.0) for mat in matrices[:k_actual]]
|
| 522 |
-
return np.mean([1.0 - d for d in distances])
|
| 523 |
-
|
| 524 |
-
zone_win = knn_similarity(self.winning_matrices, k)
|
| 525 |
-
zone_loss = knn_similarity(self.losing_matrices, k)
|
| 526 |
-
zone_draw = knn_similarity(self.draw_matrices, k)
|
| 527 |
-
Z = zone_win - zone_loss + beta * zone_draw
|
| 528 |
-
return float(np.clip(Z, -1.0, 1.0))
|
| 529 |
-
|
| 530 |
-
# ============================================================================
|
| 531 |
-
# TRAINING FUNCTION
|
| 532 |
-
# ============================================================================
|
| 533 |
-
|
| 534 |
-
def train_networks(policy_net, value_net, W_states, policies, values,
|
| 535 |
-
epochs=5, batch_size=32, device='cpu', lr=0.001):
|
| 536 |
-
policy_net.train()
|
| 537 |
-
value_net.train()
|
| 538 |
-
opt_p = optim.Adam(policy_net.parameters(), lr=lr)
|
| 539 |
-
opt_v = optim.Adam(value_net.parameters(), lr=lr)
|
| 540 |
-
|
| 541 |
-
W_tensor = torch.tensor(np.array(W_states)[:, np.newaxis, :, :], dtype=torch.float32)
|
| 542 |
-
pi_tensor = torch.tensor(np.array(policies), dtype=torch.float32)
|
| 543 |
-
v_tensor = torch.tensor(np.array(values), dtype=torch.float32).unsqueeze(1)
|
| 544 |
-
|
| 545 |
-
dataset = TensorDataset(W_tensor, pi_tensor, v_tensor)
|
| 546 |
-
loader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
|
| 547 |
-
|
| 548 |
-
for epoch in range(epochs):
|
| 549 |
-
total_loss = 0.0
|
| 550 |
-
for batch_W, batch_pi, batch_v in loader:
|
| 551 |
-
batch_W = batch_W.to(device)
|
| 552 |
-
batch_pi = batch_pi.to(device)
|
| 553 |
-
batch_v = batch_v.to(device)
|
| 554 |
-
|
| 555 |
-
logits = policy_net(batch_W)
|
| 556 |
-
policy_loss = F.kl_div(F.log_softmax(logits, dim=1), batch_pi, reduction='batchmean')
|
| 557 |
-
pred_v = value_net(batch_W)
|
| 558 |
-
value_loss = F.mse_loss(pred_v, batch_v)
|
| 559 |
-
|
| 560 |
-
loss = policy_loss + value_loss
|
| 561 |
-
total_loss += loss.item()
|
| 562 |
-
|
| 563 |
-
opt_p.zero_grad()
|
| 564 |
-
opt_v.zero_grad()
|
| 565 |
-
loss.backward()
|
| 566 |
-
torch.nn.utils.clip_grad_norm_(policy_net.parameters(), max_norm=1.0)
|
| 567 |
-
torch.nn.utils.clip_grad_norm_(value_net.parameters(), max_norm=1.0)
|
| 568 |
-
opt_p.step()
|
| 569 |
-
opt_v.step()
|
| 570 |
-
|
| 571 |
-
print(f"Epoch {epoch+1}/{epochs} - Loss: {total_loss/len(loader):.4f}")
|
| 572 |
-
|
| 573 |
-
# ============================================================================
|
| 574 |
-
# MCVS SEARCHER
|
| 575 |
-
# ============================================================================
|
| 576 |
-
|
| 577 |
-
class MCVSSearcher:
|
| 578 |
-
def __init__(self, policy_net, value_net, zone_db, device='cpu',
|
| 579 |
-
cpuct=1.41, lambda_zone=0.0, k_zone=5, use_nets=True,
|
| 580 |
-
dirichlet_alpha: float = 0.3, dirichlet_noise_fraction: float = 0.25):
|
| 581 |
-
self.policy_net = policy_net.to(device) if policy_net and use_nets else None
|
| 582 |
-
self.value_net = value_net.to(device) if value_net and use_nets else None
|
| 583 |
-
self.zone_db = zone_db
|
| 584 |
-
self.device = device
|
| 585 |
-
self.cpuct = cpuct
|
| 586 |
-
self.lambda_zone = lambda_zone
|
| 587 |
-
self.k_zone = k_zone
|
| 588 |
-
self.use_nets = use_nets
|
| 589 |
-
self.dirichlet_alpha = float(dirichlet_alpha)
|
| 590 |
-
self.dirichlet_noise_fraction = float(dirichlet_noise_fraction)
|
| 591 |
-
|
| 592 |
-
def _rollout(self, game: Breakthrough) -> float:
|
| 593 |
-
"""Random rollout using apply/undo for efficiency; leaves game at leaf state."""
|
| 594 |
-
depth = 0
|
| 595 |
-
max_depth = 60
|
| 596 |
-
moves_played = []
|
| 597 |
-
while not game.is_terminal() and depth < max_depth:
|
| 598 |
-
moves = game.get_legal_moves()
|
| 599 |
-
if not moves:
|
| 600 |
-
break
|
| 601 |
-
m = random.choice(moves)
|
| 602 |
-
game.apply_move(m)
|
| 603 |
-
moves_played.append(m)
|
| 604 |
-
depth += 1
|
| 605 |
-
|
| 606 |
-
winner = game.check_winner()
|
| 607 |
-
for _ in range(len(moves_played)):
|
| 608 |
-
game.undo_move()
|
| 609 |
-
|
| 610 |
-
if winner == Breakthrough.PLAYER1:
|
| 611 |
-
return 1.0
|
| 612 |
-
elif winner == Breakthrough.PLAYER2:
|
| 613 |
-
return -1.0
|
| 614 |
-
return 0.0
|
| 615 |
-
|
| 616 |
-
class Node:
|
| 617 |
-
def __init__(self, prior: float = 0.0, zone: float = 0.0):
|
| 618 |
-
self.prior = prior
|
| 619 |
-
self.zone = zone
|
| 620 |
-
self.visit_count = 0
|
| 621 |
-
self.value_sum = 0.0
|
| 622 |
-
self.children: Dict[Tuple[int, int, int, int], 'MCVSSearcher.Node'] = {}
|
| 623 |
-
|
| 624 |
-
def search_with_time_budget(self, game: Breakthrough, time_budget: float
|
| 625 |
-
) -> Tuple[Dict[Tuple[int, int, int, int], int], int]:
|
| 626 |
-
root = self.Node()
|
| 627 |
-
start_time = time.time()
|
| 628 |
-
simulations = 0
|
| 629 |
-
|
| 630 |
-
if not game.get_legal_moves():
|
| 631 |
-
return {}, 0
|
| 632 |
-
|
| 633 |
-
while time.time() - start_time < time_budget:
|
| 634 |
-
current_game = game # shared reference — apply/undo restores state
|
| 635 |
-
node = root
|
| 636 |
-
path = []
|
| 637 |
-
moves_made = []
|
| 638 |
-
|
| 639 |
-
# ---- Selection ----
|
| 640 |
-
while node.children:
|
| 641 |
-
path.append(node)
|
| 642 |
-
total_n = sum(c.visit_count for c in node.children.values()) + 1
|
| 643 |
-
best_score = -float('inf')
|
| 644 |
-
best_move = None
|
| 645 |
-
best_child = None
|
| 646 |
-
for move, child in node.children.items():
|
| 647 |
-
q = child.value_sum / child.visit_count if child.visit_count > 0 else 0.0
|
| 648 |
-
p_lambda = max(child.prior + self.lambda_zone * child.zone, 0.001)
|
| 649 |
-
u = self.cpuct * p_lambda * np.sqrt(total_n) / (1 + child.visit_count)
|
| 650 |
-
score = q + u
|
| 651 |
-
if score > best_score:
|
| 652 |
-
best_score = score
|
| 653 |
-
best_move = move
|
| 654 |
-
best_child = child
|
| 655 |
-
current_game.apply_move(best_move)
|
| 656 |
-
moves_made.append(best_move)
|
| 657 |
-
node = best_child
|
| 658 |
-
|
| 659 |
-
path.append(node)
|
| 660 |
-
|
| 661 |
-
# ---- Expansion & Evaluation ----
|
| 662 |
-
if current_game.is_terminal():
|
| 663 |
-
w = current_game.check_winner()
|
| 664 |
-
value = 1.0 if w == Breakthrough.PLAYER1 else (-1.0 if w == Breakthrough.PLAYER2 else 0.0)
|
| 665 |
-
legal_moves = []
|
| 666 |
-
else:
|
| 667 |
-
legal_moves = current_game.get_legal_moves()
|
| 668 |
-
|
| 669 |
-
if self.use_nets and self.policy_net is not None and self.value_net is not None:
|
| 670 |
-
W = current_game.get_weighted_adjacency_matrix()
|
| 671 |
-
W_tensor = torch.from_numpy(W)[None, None, :, :].float().to(self.device)
|
| 672 |
-
with torch.no_grad():
|
| 673 |
-
logits = self.policy_net(W_tensor)[0]
|
| 674 |
-
value = self.value_net(W_tensor)[0, 0].item()
|
| 675 |
-
|
| 676 |
-
probs = F.softmax(logits, dim=0).cpu().numpy()
|
| 677 |
-
prior_dict = {}
|
| 678 |
-
prior_sum = 0.0
|
| 679 |
-
for m in legal_moves:
|
| 680 |
-
idx = move_to_index(*m)
|
| 681 |
-
p = float(probs[idx]) if idx < probs.size else 0.0
|
| 682 |
-
prior_dict[m] = p
|
| 683 |
-
prior_sum += p
|
| 684 |
-
if prior_sum > 0.0:
|
| 685 |
-
for m in prior_dict:
|
| 686 |
-
prior_dict[m] /= prior_sum
|
| 687 |
-
else:
|
| 688 |
-
p = 1.0 / len(legal_moves)
|
| 689 |
-
prior_dict = {m: p for m in legal_moves}
|
| 690 |
-
else:
|
| 691 |
-
value = self._rollout(current_game)
|
| 692 |
-
prior_dict = {m: 1.0 / len(legal_moves) for m in legal_moves} if legal_moves else {}
|
| 693 |
-
|
| 694 |
-
# Dirichlet noise at root when using nets
|
| 695 |
-
noise = None
|
| 696 |
-
if len(path) == 1 and self.use_nets and legal_moves:
|
| 697 |
-
noise = np.random.dirichlet([self.dirichlet_alpha] * len(legal_moves))
|
| 698 |
-
for i, m in enumerate(legal_moves):
|
| 699 |
-
prior_dict[m] = ((1 - self.dirichlet_noise_fraction) * prior_dict[m]
|
| 700 |
-
+ self.dirichlet_noise_fraction * noise[i])
|
| 701 |
-
prior_sum = sum(prior_dict.values())
|
| 702 |
-
if prior_sum > 0:
|
| 703 |
-
for m in prior_dict:
|
| 704 |
-
prior_dict[m] /= prior_sum
|
| 705 |
-
|
| 706 |
-
zone_db_empty = (
|
| 707 |
-
self.zone_db is None or
|
| 708 |
-
(len(getattr(self.zone_db, 'winning_matrices', [])) == 0 and
|
| 709 |
-
len(getattr(self.zone_db, 'losing_matrices', [])) == 0 and
|
| 710 |
-
len(getattr(self.zone_db, 'draw_matrices', [])) == 0)
|
| 711 |
-
)
|
| 712 |
-
need_zone = (self.lambda_zone != 0.0) and (not zone_db_empty)
|
| 713 |
-
|
| 714 |
-
for i, m in enumerate(legal_moves):
|
| 715 |
-
if need_zone:
|
| 716 |
-
current_game.apply_move(m)
|
| 717 |
-
child_W = current_game.get_weighted_adjacency_matrix()
|
| 718 |
-
child_Z = self.zone_db.compute_zone_score(child_W, k=self.k_zone)
|
| 719 |
-
current_game.undo_move()
|
| 720 |
-
else:
|
| 721 |
-
child_Z = 0.0
|
| 722 |
-
|
| 723 |
-
if len(path) == 1 and self.use_nets and legal_moves and noise is not None:
|
| 724 |
-
z_noise = (noise[i] * 2.0) - 1.0
|
| 725 |
-
child_Z = ((1 - self.dirichlet_noise_fraction) * child_Z
|
| 726 |
-
+ self.dirichlet_noise_fraction * z_noise)
|
| 727 |
-
|
| 728 |
-
node.children[m] = self.Node(prior=prior_dict.get(m, 0.0), zone=child_Z)
|
| 729 |
-
|
| 730 |
-
# ---- Backpropagation ----
|
| 731 |
-
v = value
|
| 732 |
-
for n in reversed(path):
|
| 733 |
-
n.visit_count += 1
|
| 734 |
-
n.value_sum += v
|
| 735 |
-
v = -v
|
| 736 |
-
|
| 737 |
-
# Restore game to root state
|
| 738 |
-
for _ in range(len(moves_made)):
|
| 739 |
-
current_game.undo_move()
|
| 740 |
-
|
| 741 |
-
simulations += 1
|
| 742 |
-
|
| 743 |
-
visits = {move: child.visit_count for move, child in root.children.items()}
|
| 744 |
-
if not visits:
|
| 745 |
-
legal = game.get_legal_moves()
|
| 746 |
-
visits = {random.choice(legal): 1} if legal else {}
|
| 747 |
-
return visits, simulations
|
| 748 |
-
|
| 749 |
-
# ============================================================================
|
| 750 |
-
# UCT SEARCHER (baseline)
|
| 751 |
-
# ============================================================================
|
| 752 |
-
|
| 753 |
-
class UCTSearcher:
|
| 754 |
-
def __init__(self, cpuct: float = np.sqrt(2.0)):
|
| 755 |
-
self.cpuct = cpuct
|
| 756 |
-
|
| 757 |
-
class Node:
|
| 758 |
-
def __init__(self):
|
| 759 |
-
self.visit_count = 0
|
| 760 |
-
self.value_sum = 0.0
|
| 761 |
-
self.children: Dict[Tuple[int, int, int, int], 'UCTSearcher.Node'] = {}
|
| 762 |
-
|
| 763 |
-
def _rollout(self, game: Breakthrough) -> float:
|
| 764 |
-
depth = 0
|
| 765 |
-
max_depth = 60
|
| 766 |
-
moves_played = []
|
| 767 |
-
while not game.is_terminal() and depth < max_depth:
|
| 768 |
-
moves = game.get_legal_moves()
|
| 769 |
-
if not moves:
|
| 770 |
-
break
|
| 771 |
-
m = random.choice(moves)
|
| 772 |
-
game.apply_move(m)
|
| 773 |
-
moves_played.append(m)
|
| 774 |
-
depth += 1
|
| 775 |
-
|
| 776 |
-
if depth >= max_depth:
|
| 777 |
-
for _ in range(len(moves_played)):
|
| 778 |
-
game.undo_move()
|
| 779 |
-
return 0.0
|
| 780 |
-
|
| 781 |
-
winner = game.check_winner()
|
| 782 |
-
for _ in range(len(moves_played)):
|
| 783 |
-
game.undo_move()
|
| 784 |
-
|
| 785 |
-
if winner == Breakthrough.PLAYER1:
|
| 786 |
-
return 1.0
|
| 787 |
-
elif winner == Breakthrough.PLAYER2:
|
| 788 |
-
return -1.0
|
| 789 |
-
return 0.0
|
| 790 |
-
|
| 791 |
-
def search_with_time_budget(self, game: Breakthrough, time_budget: float
|
| 792 |
-
) -> Tuple[Dict[Tuple[int, int, int, int], int], int]:
|
| 793 |
-
root = self.Node()
|
| 794 |
-
start_time = time.time()
|
| 795 |
-
simulations = 0
|
| 796 |
-
|
| 797 |
-
while time.time() - start_time < time_budget:
|
| 798 |
-
current_game = game
|
| 799 |
-
node = root
|
| 800 |
-
path = [node]
|
| 801 |
-
moves_made = []
|
| 802 |
-
|
| 803 |
-
while True:
|
| 804 |
-
legal_moves = current_game.get_legal_moves()
|
| 805 |
-
|
| 806 |
-
if current_game.is_terminal():
|
| 807 |
-
w = current_game.check_winner()
|
| 808 |
-
value = 1.0 if w == Breakthrough.PLAYER1 else (-1.0 if w == Breakthrough.PLAYER2 else 0.0)
|
| 809 |
-
break
|
| 810 |
-
|
| 811 |
-
if not legal_moves:
|
| 812 |
-
value = 0.0
|
| 813 |
-
break
|
| 814 |
-
|
| 815 |
-
unvisited = [m for m in legal_moves if m not in node.children]
|
| 816 |
-
if unvisited:
|
| 817 |
-
move = random.choice(unvisited)
|
| 818 |
-
child = self.Node()
|
| 819 |
-
node.children[move] = child
|
| 820 |
-
current_game.apply_move(move)
|
| 821 |
-
moves_made.append(move)
|
| 822 |
-
path.append(child)
|
| 823 |
-
value = self._rollout(current_game)
|
| 824 |
-
break
|
| 825 |
-
|
| 826 |
-
best_score = -float('inf')
|
| 827 |
-
best_move = None
|
| 828 |
-
best_child = None
|
| 829 |
-
total_visits = node.visit_count
|
| 830 |
-
|
| 831 |
-
for move in legal_moves:
|
| 832 |
-
child = node.children[move]
|
| 833 |
-
Q = child.value_sum / (child.visit_count + 1e-8)
|
| 834 |
-
U = self.cpuct * np.sqrt(np.log(total_visits + 1) / (child.visit_count + 1e-8))
|
| 835 |
-
score = Q + U
|
| 836 |
-
if score > best_score:
|
| 837 |
-
best_score = score
|
| 838 |
-
best_move = move
|
| 839 |
-
best_child = child
|
| 840 |
-
|
| 841 |
-
current_game.apply_move(best_move)
|
| 842 |
-
moves_made.append(best_move)
|
| 843 |
-
node = best_child
|
| 844 |
-
path.append(node)
|
| 845 |
-
|
| 846 |
-
for n in reversed(path):
|
| 847 |
-
n.visit_count += 1
|
| 848 |
-
n.value_sum += value
|
| 849 |
-
value = -value
|
| 850 |
-
|
| 851 |
-
for _ in range(len(moves_made)):
|
| 852 |
-
current_game.undo_move()
|
| 853 |
-
|
| 854 |
-
simulations += 1
|
| 855 |
-
|
| 856 |
-
visits = {move: child.visit_count for move, child in root.children.items()}
|
| 857 |
-
if not visits:
|
| 858 |
-
legal = game.get_legal_moves()
|
| 859 |
-
return {random.choice(legal): 1} if legal else {}, simulations
|
| 860 |
-
return visits, simulations
|
| 861 |
-
|
| 862 |
-
# ============================================================================
|
| 863 |
-
# SELF-PLAY DATA GENERATION
|
| 864 |
-
# ============================================================================
|
| 865 |
-
|
| 866 |
-
def generate_self_play_data(policy_net, value_net, zone_db, max_time_seconds=60.0,
|
| 867 |
-
lambda_zone=0.5, device='cpu'):
|
| 868 |
-
"""Generate self-play games using MCVS with zone guidance."""
|
| 869 |
-
searcher = MCVSSearcher(policy_net, value_net, zone_db, device=device,
|
| 870 |
-
cpuct=1.41, lambda_zone=lambda_zone, k_zone=5)
|
| 871 |
-
|
| 872 |
-
W_states = []
|
| 873 |
-
policies = []
|
| 874 |
-
values = []
|
| 875 |
-
trajectories = []
|
| 876 |
-
|
| 877 |
-
start_time = time.time()
|
| 878 |
-
game_idx = 0
|
| 879 |
-
|
| 880 |
-
while time.time() - start_time < max_time_seconds:
|
| 881 |
-
game_start_time = time.time()
|
| 882 |
-
game = Breakthrough()
|
| 883 |
-
trajectory = [game.copy()]
|
| 884 |
-
W_state_list = []
|
| 885 |
-
policy_list = []
|
| 886 |
-
|
| 887 |
-
while not game.is_terminal():
|
| 888 |
-
time_per_move = 0.3
|
| 889 |
-
W_t = game.get_weighted_adjacency_matrix()
|
| 890 |
-
visits, _ = searcher.search_with_time_budget(game, time_per_move)
|
| 891 |
-
|
| 892 |
-
if not visits:
|
| 893 |
-
break
|
| 894 |
-
|
| 895 |
-
moves = list(visits.keys())
|
| 896 |
-
visit_counts = np.array([visits[m] for m in moves], dtype=float)
|
| 897 |
-
total_visits = visit_counts.sum()
|
| 898 |
-
if total_visits <= 0:
|
| 899 |
-
break
|
| 900 |
-
probs = visit_counts / total_visits
|
| 901 |
-
|
| 902 |
-
temperature = 1.0 if game.move_count < 8 else 0.25
|
| 903 |
-
if temperature != 1.0:
|
| 904 |
-
probs = probs ** (1.0 / temperature)
|
| 905 |
-
prob_sum = probs.sum()
|
| 906 |
-
if prob_sum <= 0:
|
| 907 |
-
probs = np.ones(len(moves)) / len(moves)
|
| 908 |
-
else:
|
| 909 |
-
probs = probs / prob_sum
|
| 910 |
-
|
| 911 |
-
policy_target = np.zeros(4096)
|
| 912 |
-
for move, count in visits.items():
|
| 913 |
-
idx = move_to_index(*move)
|
| 914 |
-
if 0 <= idx < 4096:
|
| 915 |
-
policy_target[idx] = count / total_visits
|
| 916 |
-
|
| 917 |
-
W_state_list.append(W_t)
|
| 918 |
-
policy_list.append(policy_target)
|
| 919 |
-
|
| 920 |
-
if len(moves) > 1:
|
| 921 |
-
chosen_idx = np.random.choice(len(moves), p=probs)
|
| 922 |
-
chosen_move = moves[chosen_idx]
|
| 923 |
-
else:
|
| 924 |
-
chosen_move = moves[0]
|
| 925 |
-
|
| 926 |
-
game.apply_move(chosen_move)
|
| 927 |
-
trajectory.append(game.copy())
|
| 928 |
-
|
| 929 |
-
winner = game.check_winner()
|
| 930 |
-
result = (1 if winner == Breakthrough.PLAYER1
|
| 931 |
-
else -1 if winner == Breakthrough.PLAYER2
|
| 932 |
-
else 0)
|
| 933 |
-
|
| 934 |
-
for i in range(len(W_state_list)):
|
| 935 |
-
player_to_move = 1 if i % 2 == 0 else -1
|
| 936 |
-
value = result if result == 0 else (result if result == player_to_move else -result)
|
| 937 |
-
W_states.append(W_state_list[i])
|
| 938 |
-
policies.append(policy_list[i])
|
| 939 |
-
values.append(value)
|
| 940 |
-
|
| 941 |
-
zone_db.add_game_record(trajectory, result)
|
| 942 |
-
trajectories.append(trajectory)
|
| 943 |
-
|
| 944 |
-
game_idx += 1
|
| 945 |
-
game_duration = time.time() - game_start_time
|
| 946 |
-
total_elapsed = time.time() - start_time
|
| 947 |
-
print(f"Game {game_idx}: Winner={winner}, Moves={game.move_count}, "
|
| 948 |
-
f"Duration={game_duration:.1f}s, Total={total_elapsed:.1f}s")
|
| 949 |
-
|
| 950 |
-
elapsed = time.time() - start_time
|
| 951 |
-
print(f"\nSelf-play finished: {game_idx} games in {elapsed:.1f}s, "
|
| 952 |
-
f"{len(W_states)} training examples collected")
|
| 953 |
-
|
| 954 |
-
return W_states, policies, values, trajectories
|
| 955 |
-
|
| 956 |
-
# ============================================================================
|
| 957 |
-
# DIAGNOSTIC TEST FOR MOVE DIVERSITY
|
| 958 |
-
# ============================================================================
|
| 959 |
-
|
| 960 |
-
def test_move_diversity(policy_net, value_net, zone_db, num_trials=30,
|
| 961 |
-
time_budget=2.0, device='cpu'):
|
| 962 |
-
searcher = MCVSSearcher(policy_net, value_net, zone_db, device=device)
|
| 963 |
-
game = Breakthrough()
|
| 964 |
-
|
| 965 |
-
move_counts = {}
|
| 966 |
-
for _ in range(num_trials):
|
| 967 |
-
visits, _ = searcher.search_with_time_budget(game, time_budget)
|
| 968 |
-
if visits:
|
| 969 |
-
best_move = max(visits, key=visits.get)
|
| 970 |
-
move_counts[best_move] = move_counts.get(best_move, 0) + 1
|
| 971 |
-
|
| 972 |
-
print("\nMove diversity test (starting position):")
|
| 973 |
-
total = sum(move_counts.values())
|
| 974 |
-
for m, cnt in sorted(move_counts.items(), key=lambda x: -x[1]):
|
| 975 |
-
print(f"{m}: {cnt:2d}x ({cnt/total:.1%})")
|
| 976 |
-
print(f"Unique moves chosen: {len(move_counts)} out of {len(game.get_legal_moves())} legal\n")
|
| 977 |
-
|
| 978 |
-
# ============================================================================
|
| 979 |
-
# GUIDED MCVS vs UCT-MCTS TOURNAMENT
|
| 980 |
-
# ============================================================================
|
| 981 |
-
|
| 982 |
-
def play_match_mcvs_vs_uct(policy_net, value_net, zone_db, num_games: int = 200,
|
| 983 |
-
time_per_move: float = 0.3, device: str = 'cpu'):
|
| 984 |
-
"""
|
| 985 |
-
Tournament between guided MCVS and UCT.
|
| 986 |
-
Odd games: MCVS as PLAYER1; even games: UCT as PLAYER1.
|
| 987 |
-
"""
|
| 988 |
-
mcvs_searcher = MCVSSearcher(policy_net, value_net, zone_db,
|
| 989 |
-
device=device, cpuct=1.41,
|
| 990 |
-
lambda_zone=1.0, k_zone=5)
|
| 991 |
-
uct_searcher = UCTSearcher(cpuct=np.sqrt(2.0))
|
| 992 |
-
|
| 993 |
-
mcvs_wins = 0
|
| 994 |
-
uct_wins = 0
|
| 995 |
-
draws = 0
|
| 996 |
-
|
| 997 |
-
for g in range(1, num_games + 1):
|
| 998 |
-
game = Breakthrough()
|
| 999 |
-
mcvs_as_player1 = (g % 2 == 1)
|
| 1000 |
-
|
| 1001 |
-
while not game.is_terminal():
|
| 1002 |
-
moves = game.get_legal_moves()
|
| 1003 |
-
if not moves:
|
| 1004 |
-
break
|
| 1005 |
-
|
| 1006 |
-
is_player1_turn = (game.move_count % 2 == 0)
|
| 1007 |
-
use_mcvs = mcvs_as_player1 if is_player1_turn else not mcvs_as_player1
|
| 1008 |
-
|
| 1009 |
-
if use_mcvs:
|
| 1010 |
-
visits, _ = mcvs_searcher.search_with_time_budget(game, time_per_move)
|
| 1011 |
-
else:
|
| 1012 |
-
visits, _ = uct_searcher.search_with_time_budget(game, time_per_move)
|
| 1013 |
-
|
| 1014 |
-
if not visits:
|
| 1015 |
-
break
|
| 1016 |
-
|
| 1017 |
-
moves_list = list(visits.keys())
|
| 1018 |
-
counts = np.array([visits[m] for m in moves_list], dtype=float)
|
| 1019 |
-
chosen_move = moves_list[int(np.argmax(counts))]
|
| 1020 |
-
game.apply_move(chosen_move)
|
| 1021 |
-
|
| 1022 |
-
winner = game.check_winner()
|
| 1023 |
-
if winner == Breakthrough.PLAYER1:
|
| 1024 |
-
if mcvs_as_player1:
|
| 1025 |
-
mcvs_wins += 1
|
| 1026 |
-
else:
|
| 1027 |
-
uct_wins += 1
|
| 1028 |
-
elif winner == Breakthrough.PLAYER2:
|
| 1029 |
-
if mcvs_as_player1:
|
| 1030 |
-
uct_wins += 1
|
| 1031 |
-
else:
|
| 1032 |
-
mcvs_wins += 1
|
| 1033 |
-
else:
|
| 1034 |
-
draws += 1
|
| 1035 |
-
|
| 1036 |
-
print(f"Game {g}/{num_games} finished. Winner={winner} (MCVS as P1: {mcvs_as_player1})")
|
| 1037 |
-
|
| 1038 |
-
print("\n=== MCVS vs UCT Tournament Results ===")
|
| 1039 |
-
print(f"Total games : {num_games}")
|
| 1040 |
-
print(f"MCVS wins : {mcvs_wins}")
|
| 1041 |
-
print(f"UCT wins : {uct_wins}")
|
| 1042 |
-
print(f"Draws : {draws}")
|
| 1043 |
-
if num_games > 0:
|
| 1044 |
-
print(f"Win rates : MCVS={mcvs_wins/num_games*100:.1f}%, "
|
| 1045 |
-
f"UCT={uct_wins/num_games*100:.1f}%, Draw={draws/num_games*100:.1f}%\n")
|
| 1046 |
-
|
| 1047 |
-
def main():
|
| 1048 |
-
print("=" * 80)
|
| 1049 |
-
print("BREAKTHROUGH MCVS - INCREMENTAL TRAINING")
|
| 1050 |
-
print("=" * 80)
|
| 1051 |
-
|
| 1052 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 1053 |
-
print(f"Device: {device}")
|
| 1054 |
-
|
| 1055 |
-
policy_net = PolicyNetworkCNN().to(device)
|
| 1056 |
-
value_net = ValueNetworkCNN().to(device)
|
| 1057 |
-
|
| 1058 |
-
zone_db = HilbertOrderedZoneDatabase("breakthrough_zone_db.npz", max_size=10000)
|
| 1059 |
-
|
| 1060 |
-
checkpoint_path = "breakthrough_checkpoint.pt"
|
| 1061 |
-
iteration = 0
|
| 1062 |
-
|
| 1063 |
-
if os.path.exists(checkpoint_path):
|
| 1064 |
-
print(f"Loading checkpoint from {checkpoint_path}...")
|
| 1065 |
-
checkpoint = torch.load(checkpoint_path, map_location=device)
|
| 1066 |
-
policy_net.load_state_dict(checkpoint['policy'])
|
| 1067 |
-
value_net.load_state_dict(checkpoint['value'])
|
| 1068 |
-
iteration = checkpoint.get('iteration', 0)
|
| 1069 |
-
print(f"Resumed from iteration {iteration}")
|
| 1070 |
-
|
| 1071 |
-
all_W_states: List = []
|
| 1072 |
-
all_policies: List = []
|
| 1073 |
-
all_values: List = []
|
| 1074 |
-
|
| 1075 |
-
while True:
|
| 1076 |
-
print("=" * 80)
|
| 1077 |
-
print(f"ITERATION {iteration}")
|
| 1078 |
-
print("=" * 80)
|
| 1079 |
-
|
| 1080 |
-
print("Generating self-play data (30 minutes)...")
|
| 1081 |
-
lambda_zone = 0.0 if iteration == 0 else 1.0
|
| 1082 |
-
|
| 1083 |
-
W_states, policies, values, trajectories = generate_self_play_data(
|
| 1084 |
-
policy_net, value_net, zone_db,
|
| 1085 |
-
max_time_seconds=1800.0,
|
| 1086 |
-
lambda_zone=lambda_zone,
|
| 1087 |
-
device=device
|
| 1088 |
-
)
|
| 1089 |
-
|
| 1090 |
-
print(f"Collected {len(W_states)} training examples from {len(trajectories)} games")
|
| 1091 |
-
|
| 1092 |
-
all_W_states.extend(W_states)
|
| 1093 |
-
all_policies.extend(policies)
|
| 1094 |
-
all_values.extend(values)
|
| 1095 |
-
|
| 1096 |
-
max_training_examples = 50000
|
| 1097 |
-
if len(all_W_states) > max_training_examples:
|
| 1098 |
-
print(f"Trimming training data to most recent {max_training_examples} examples...")
|
| 1099 |
-
all_W_states = all_W_states[-max_training_examples:]
|
| 1100 |
-
all_policies = all_policies[-max_training_examples:]
|
| 1101 |
-
all_values = all_values[-max_training_examples:]
|
| 1102 |
-
|
| 1103 |
-
print(f"Total accumulated training examples: {len(all_W_states)}")
|
| 1104 |
-
|
| 1105 |
-
print("Training networks...")
|
| 1106 |
-
train_networks(
|
| 1107 |
-
policy_net, value_net,
|
| 1108 |
-
all_W_states, all_policies, all_values,
|
| 1109 |
-
epochs=10,
|
| 1110 |
-
device=device,
|
| 1111 |
-
lr=0.001
|
| 1112 |
-
)
|
| 1113 |
-
|
| 1114 |
-
print("Saving checkpoint...")
|
| 1115 |
-
torch.save({
|
| 1116 |
-
'policy': policy_net.state_dict(),
|
| 1117 |
-
'value': value_net.state_dict(),
|
| 1118 |
-
'iteration': iteration,
|
| 1119 |
-
'num_training_examples': len(all_W_states)
|
| 1120 |
-
}, checkpoint_path)
|
| 1121 |
-
print(f"Checkpoint saved: {checkpoint_path}")
|
| 1122 |
-
|
| 1123 |
-
zone_db.save()
|
| 1124 |
-
print(f"Zone DB saved: W={len(zone_db.winning_matrices)}, "
|
| 1125 |
-
f"L={len(zone_db.losing_matrices)}, D={len(zone_db.draw_matrices)}")
|
| 1126 |
-
|
| 1127 |
-
iteration += 1
|
| 1128 |
-
|
| 1129 |
-
print("\n" + "=" * 80)
|
| 1130 |
-
print(f"Iteration {iteration} complete!")
|
| 1131 |
-
print(f"Files updated: {checkpoint_path}, {zone_db.filepath}")
|
| 1132 |
-
print("=" * 80 + "\n")
|
| 1133 |
-
|
| 1134 |
-
if iteration % 5 == 0:
|
| 1135 |
-
print("\nRunning tournament evaluation...")
|
| 1136 |
-
play_match_mcvs_vs_uct(
|
| 1137 |
-
policy_net, value_net, zone_db,
|
| 1138 |
-
num_games=20,
|
| 1139 |
-
time_per_move=0.5,
|
| 1140 |
-
device=device
|
| 1141 |
-
)
|
| 1142 |
-
|
| 1143 |
-
|
| 1144 |
-
# ============================================================================
|
| 1145 |
-
# MAIN
|
| 1146 |
-
# ============================================================================
|
| 1147 |
-
|
| 1148 |
-
if __name__ == "__main__":
|
| 1149 |
-
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.optim as optim
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from torch.utils.data import DataLoader, TensorDataset
|
| 7 |
+
from typing import List, Dict, Tuple
|
| 8 |
+
import random
|
| 9 |
+
import time
|
| 10 |
+
import os
|
| 11 |
+
import bisect
|
| 12 |
+
|
| 13 |
+
# ============================================================================
|
| 14 |
+
# HILBERT CURVE UTILITIES
|
| 15 |
+
# ============================================================================
|
| 16 |
+
|
| 17 |
+
def xy2d(n: int, x: int, y: int) -> int:
|
| 18 |
+
"""Convert (x,y) to Hilbert curve distance."""
|
| 19 |
+
d = 0
|
| 20 |
+
s = n // 2
|
| 21 |
+
while s > 0:
|
| 22 |
+
rx = 1 if (x & s) > 0 else 0
|
| 23 |
+
ry = 1 if (y & s) > 0 else 0
|
| 24 |
+
d += s * s * ((3 * rx) ^ ry)
|
| 25 |
+
if ry == 0:
|
| 26 |
+
if rx == 1:
|
| 27 |
+
x = n - 1 - x
|
| 28 |
+
y = n - 1 - y
|
| 29 |
+
x, y = y, x
|
| 30 |
+
s //= 2
|
| 31 |
+
return d
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def matrix_to_hilbert_index(W: np.ndarray) -> int:
|
| 35 |
+
if W.size == 0:
|
| 36 |
+
return 0
|
| 37 |
+
W_flat = W.flatten()
|
| 38 |
+
max_idx = np.argmax(W_flat)
|
| 39 |
+
x = max_idx % 64
|
| 40 |
+
y = max_idx // 64
|
| 41 |
+
return xy2d(64, x, y)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def move_to_index(fr: int, fc: int, tr: int, tc: int) -> int:
|
| 45 |
+
"""Convert move tuple (fr,fc,tr,tc) to policy index in [0,4095]."""
|
| 46 |
+
from_sq = fr * 8 + fc
|
| 47 |
+
to_sq = tr * 8 + tc
|
| 48 |
+
return from_sq * 64 + to_sq
|
| 49 |
+
|
| 50 |
+
# ============================================================================
|
| 51 |
+
# ABC MODEL DYNAMIC
|
| 52 |
+
# ============================================================================
|
| 53 |
+
|
| 54 |
+
class ABCModelDynamic:
|
| 55 |
+
"""ABC Model with displacement-based B matrices."""
|
| 56 |
+
|
| 57 |
+
def __init__(self, n: int = 2, t: float = 1.0, T: float = 1.41):
|
| 58 |
+
self.n = n
|
| 59 |
+
self.t = t
|
| 60 |
+
self.T = T
|
| 61 |
+
self.c0 = np.array([0.0, 0.0, 1.0])
|
| 62 |
+
self.B_blocks = []
|
| 63 |
+
self.piece_positions = []
|
| 64 |
+
self.a_product = np.eye(3)
|
| 65 |
+
self.delta = {}
|
| 66 |
+
self.kappa = {}
|
| 67 |
+
self.stage = 0
|
| 68 |
+
self.MB_current = self.c0.copy()
|
| 69 |
+
self.MB_previous = self.c0.copy()
|
| 70 |
+
self.history = []
|
| 71 |
+
|
| 72 |
+
def create_B_displacement(self, dx: float, dy: float) -> np.ndarray:
|
| 73 |
+
return np.array([
|
| 74 |
+
[1.0, 0.0, dx],
|
| 75 |
+
[0.0, 1.0, dy],
|
| 76 |
+
[0.0, 0.0, 1.0]
|
| 77 |
+
])
|
| 78 |
+
|
| 79 |
+
def add_piece(self, position: tuple, delta_values: tuple, kappa_vector: np.ndarray = None):
|
| 80 |
+
x, y = position
|
| 81 |
+
current_MB = self.MB_current.copy()
|
| 82 |
+
dx = x - current_MB[0]
|
| 83 |
+
dy = y - current_MB[1]
|
| 84 |
+
B_i = self.create_B_displacement(dx, dy)
|
| 85 |
+
idx = len(self.B_blocks)
|
| 86 |
+
self.B_blocks.append(B_i)
|
| 87 |
+
self.piece_positions.append((x, y))
|
| 88 |
+
self.a_product = self.a_product @ B_i
|
| 89 |
+
self.MB_previous = self.MB_current.copy()
|
| 90 |
+
self.MB_current = self.a_product @ self.c0
|
| 91 |
+
self.delta[idx] = delta_values
|
| 92 |
+
if kappa_vector is None:
|
| 93 |
+
kappa_vector = np.array(delta_values)
|
| 94 |
+
self.kappa[idx] = kappa_vector
|
| 95 |
+
self.stage += 1
|
| 96 |
+
self.history.append({
|
| 97 |
+
'stage': self.stage,
|
| 98 |
+
'SB_position': (x, y),
|
| 99 |
+
'displacement': (dx, dy),
|
| 100 |
+
'B_i': B_i.copy(),
|
| 101 |
+
'a_t': self.a_product.copy(),
|
| 102 |
+
'MB_prev': self.MB_previous.copy(),
|
| 103 |
+
'MB_curr': self.MB_current.copy(),
|
| 104 |
+
'delta': delta_values,
|
| 105 |
+
'kappa': kappa_vector.copy()
|
| 106 |
+
})
|
| 107 |
+
|
| 108 |
+
# ============================================================================
|
| 109 |
+
# WEIGHTED MATRIX ABC
|
| 110 |
+
# ============================================================================
|
| 111 |
+
|
| 112 |
+
class WeightedMatrixABC:
|
| 113 |
+
"""Compute weighted adjacency matrix from ABCModelDynamic."""
|
| 114 |
+
|
| 115 |
+
def __init__(self, abc_model: ABCModelDynamic, sigma: float = 1.0):
|
| 116 |
+
self.abc = abc_model
|
| 117 |
+
self.n = abc_model.n
|
| 118 |
+
self.t = abc_model.t
|
| 119 |
+
self.T = abc_model.T
|
| 120 |
+
self.sigma = sigma
|
| 121 |
+
self.positions = None
|
| 122 |
+
self.D = None
|
| 123 |
+
self.A = None
|
| 124 |
+
self.S = None
|
| 125 |
+
self.F = None
|
| 126 |
+
self.W = None
|
| 127 |
+
|
| 128 |
+
def compute_piece_positions(self) -> np.ndarray:
|
| 129 |
+
positions = []
|
| 130 |
+
for pos in self.abc.piece_positions:
|
| 131 |
+
x, y = pos
|
| 132 |
+
positions.append(np.array([x, y, 1.0]))
|
| 133 |
+
self.positions = np.array(positions)
|
| 134 |
+
return self.positions
|
| 135 |
+
|
| 136 |
+
def compute_distance_matrix(self) -> np.ndarray:
|
| 137 |
+
if self.positions is None:
|
| 138 |
+
self.compute_piece_positions()
|
| 139 |
+
num = len(self.positions)
|
| 140 |
+
D = np.zeros((num, num))
|
| 141 |
+
for i in range(num):
|
| 142 |
+
for j in range(num):
|
| 143 |
+
pos_i = self.positions[i][:2]
|
| 144 |
+
pos_j = self.positions[j][:2]
|
| 145 |
+
D[i, j] = np.linalg.norm(pos_i - pos_j)
|
| 146 |
+
self.D = D
|
| 147 |
+
return D
|
| 148 |
+
|
| 149 |
+
def compute_adjacency_matrix(self) -> np.ndarray:
|
| 150 |
+
if self.D is None:
|
| 151 |
+
self.compute_distance_matrix()
|
| 152 |
+
num = len(self.positions)
|
| 153 |
+
A = np.zeros((num, num))
|
| 154 |
+
isolated = set()
|
| 155 |
+
for i in range(num):
|
| 156 |
+
has_neighbor = False
|
| 157 |
+
for j in range(num):
|
| 158 |
+
if i != j and self.t <= self.D[i, j] <= self.T:
|
| 159 |
+
has_neighbor = True
|
| 160 |
+
break
|
| 161 |
+
if not has_neighbor:
|
| 162 |
+
isolated.add(i)
|
| 163 |
+
for i in range(num):
|
| 164 |
+
for j in range(num):
|
| 165 |
+
if i != j and self.t <= self.D[i, j] <= self.T:
|
| 166 |
+
A[i, j] = 1.0
|
| 167 |
+
elif i == j and i in isolated:
|
| 168 |
+
A[i, j] = 1.0
|
| 169 |
+
self.A = A
|
| 170 |
+
return A
|
| 171 |
+
|
| 172 |
+
def compute_spatial_matrix(self) -> np.ndarray:
|
| 173 |
+
if self.D is None:
|
| 174 |
+
self.compute_distance_matrix()
|
| 175 |
+
num = len(self.positions)
|
| 176 |
+
S = np.zeros((num, num))
|
| 177 |
+
for i in range(num):
|
| 178 |
+
for j in range(num):
|
| 179 |
+
S[i, j] = np.exp(-self.D[i, j] ** 2 / (2 * self.sigma ** 2))
|
| 180 |
+
self.S = S
|
| 181 |
+
return S
|
| 182 |
+
|
| 183 |
+
def compute_feature_matrix(self) -> np.ndarray:
|
| 184 |
+
num = len(self.positions)
|
| 185 |
+
F = np.zeros((num, num))
|
| 186 |
+
kappas = []
|
| 187 |
+
for i in range(num):
|
| 188 |
+
if i in self.abc.kappa:
|
| 189 |
+
kappas.append(self.abc.kappa[i])
|
| 190 |
+
elif i in self.abc.delta:
|
| 191 |
+
kappas.append(np.array(self.abc.delta[i]))
|
| 192 |
+
else:
|
| 193 |
+
kappas.append(np.array([1.0, 1.0, 1.0]))
|
| 194 |
+
for i in range(num):
|
| 195 |
+
for j in range(num):
|
| 196 |
+
kappa_i = kappas[i]
|
| 197 |
+
kappa_j = kappas[j]
|
| 198 |
+
dot_product = np.dot(kappa_i, kappa_j)
|
| 199 |
+
norm_i = np.linalg.norm(kappa_i)
|
| 200 |
+
norm_j = np.linalg.norm(kappa_j)
|
| 201 |
+
if norm_i > 0 and norm_j > 0:
|
| 202 |
+
F[i, j] = dot_product / (norm_i * norm_j)
|
| 203 |
+
else:
|
| 204 |
+
F[i, j] = 0.0
|
| 205 |
+
self.F = F
|
| 206 |
+
return F
|
| 207 |
+
|
| 208 |
+
def compute_weighted_matrix(self) -> np.ndarray:
|
| 209 |
+
if self.A is None:
|
| 210 |
+
self.compute_adjacency_matrix()
|
| 211 |
+
if self.S is None:
|
| 212 |
+
self.compute_spatial_matrix()
|
| 213 |
+
if self.F is None:
|
| 214 |
+
self.compute_feature_matrix()
|
| 215 |
+
W = self.A * self.S * self.F
|
| 216 |
+
self.W = W
|
| 217 |
+
return W
|
| 218 |
+
|
| 219 |
+
# ============================================================================
|
| 220 |
+
# BREAKTHROUGH GAME LOGIC
|
| 221 |
+
# ============================================================================
|
| 222 |
+
|
| 223 |
+
class Breakthrough:
|
| 224 |
+
ROWS, COLS = 8, 8
|
| 225 |
+
EMPTY, PLAYER1, PLAYER2 = 0, 1, 2
|
| 226 |
+
|
| 227 |
+
def __init__(self):
|
| 228 |
+
self.board = np.zeros((self.ROWS, self.COLS), dtype=np.int32)
|
| 229 |
+
self.board[0:2, :] = self.PLAYER1
|
| 230 |
+
self.board[6:8, :] = self.PLAYER2
|
| 231 |
+
self.move_count = 0
|
| 232 |
+
self._move_stack: List[Tuple] = [] # (fr, fc, tr, tc, captured)
|
| 233 |
+
self._cached_matrix = None
|
| 234 |
+
|
| 235 |
+
def copy(self):
|
| 236 |
+
new_game = Breakthrough.__new__(Breakthrough)
|
| 237 |
+
new_game.board = self.board.copy()
|
| 238 |
+
new_game.move_count = self.move_count
|
| 239 |
+
new_game._move_stack = list(self._move_stack)
|
| 240 |
+
new_game._cached_matrix = (
|
| 241 |
+
self._cached_matrix.copy() if self._cached_matrix is not None else None
|
| 242 |
+
)
|
| 243 |
+
return new_game
|
| 244 |
+
|
| 245 |
+
def get_legal_moves(self) -> List[Tuple[int, int, int, int]]:
|
| 246 |
+
moves = []
|
| 247 |
+
player = self.PLAYER1 if self.move_count % 2 == 0 else self.PLAYER2
|
| 248 |
+
direction = 1 if player == self.PLAYER1 else -1
|
| 249 |
+
opponent = 3 - player
|
| 250 |
+
for r in range(self.ROWS):
|
| 251 |
+
for c in range(self.COLS):
|
| 252 |
+
if self.board[r, c] == player:
|
| 253 |
+
nr = r + direction
|
| 254 |
+
if 0 <= nr < self.ROWS:
|
| 255 |
+
if self.board[nr, c] == self.EMPTY:
|
| 256 |
+
moves.append((r, c, nr, c))
|
| 257 |
+
for dc in [-1, 1]:
|
| 258 |
+
nc = c + dc
|
| 259 |
+
if 0 <= nc < self.COLS and self.board[nr, nc] == opponent:
|
| 260 |
+
moves.append((r, c, nr, nc))
|
| 261 |
+
return moves
|
| 262 |
+
|
| 263 |
+
def apply_move(self, move: Tuple[int, int, int, int]) -> None:
|
| 264 |
+
fr, fc, tr, tc = move
|
| 265 |
+
captured = int(self.board[tr, tc])
|
| 266 |
+
self._move_stack.append((fr, fc, tr, tc, captured))
|
| 267 |
+
self.board[tr, tc] = self.board[fr, fc]
|
| 268 |
+
self.board[fr, fc] = self.EMPTY
|
| 269 |
+
self.move_count += 1
|
| 270 |
+
self._cached_matrix = None
|
| 271 |
+
|
| 272 |
+
def undo_move(self) -> None:
|
| 273 |
+
if not self._move_stack:
|
| 274 |
+
return
|
| 275 |
+
fr, fc, tr, tc, captured = self._move_stack.pop()
|
| 276 |
+
self.board[fr, fc] = self.board[tr, tc]
|
| 277 |
+
self.board[tr, tc] = captured
|
| 278 |
+
self.move_count -= 1
|
| 279 |
+
self._cached_matrix = None
|
| 280 |
+
|
| 281 |
+
def check_winner(self) -> int:
|
| 282 |
+
"""Return PLAYER1 (1) if row 7 reached, PLAYER2 (2) if row 0 reached, else EMPTY (0)."""
|
| 283 |
+
if np.any(self.board[7, :] == self.PLAYER1):
|
| 284 |
+
return self.PLAYER1
|
| 285 |
+
if np.any(self.board[0, :] == self.PLAYER2):
|
| 286 |
+
return self.PLAYER2
|
| 287 |
+
return self.EMPTY
|
| 288 |
+
|
| 289 |
+
def is_terminal(self) -> bool:
|
| 290 |
+
return self.check_winner() != self.EMPTY or len(self.get_legal_moves()) == 0
|
| 291 |
+
|
| 292 |
+
def get_weighted_adjacency_matrix(self) -> np.ndarray:
|
| 293 |
+
if self._cached_matrix is not None:
|
| 294 |
+
return self._cached_matrix
|
| 295 |
+
|
| 296 |
+
occupied = []
|
| 297 |
+
for r in range(8):
|
| 298 |
+
for c in range(8):
|
| 299 |
+
piece = self.board[r, c]
|
| 300 |
+
if piece != self.EMPTY:
|
| 301 |
+
x = c - 3.5
|
| 302 |
+
y = 3.5 - r
|
| 303 |
+
delta_2 = 1.0 if piece == self.PLAYER1 else 1.1
|
| 304 |
+
kappa = np.array([1.0, delta_2, 1.0])
|
| 305 |
+
hilbert_d = xy2d(8, c, r)
|
| 306 |
+
occupied.append((hilbert_d, (x, y), kappa))
|
| 307 |
+
|
| 308 |
+
occupied.sort(key=lambda t: t[0])
|
| 309 |
+
|
| 310 |
+
abc = ABCModelDynamic(n=2, t=1.0, T=1.41)
|
| 311 |
+
for _, pos, kappa_vec in occupied:
|
| 312 |
+
abc.add_piece(pos, delta_values=(1.0, float(kappa_vec[1]), 1.0), kappa_vector=kappa_vec)
|
| 313 |
+
|
| 314 |
+
builder = WeightedMatrixABC(abc, sigma=1.0)
|
| 315 |
+
W_small = builder.compute_weighted_matrix()
|
| 316 |
+
|
| 317 |
+
n = len(occupied)
|
| 318 |
+
W = np.zeros((64, 64), dtype=np.float32)
|
| 319 |
+
if n > 0:
|
| 320 |
+
W[:n, :n] = W_small
|
| 321 |
+
|
| 322 |
+
self._cached_matrix = W
|
| 323 |
+
return W
|
| 324 |
+
|
| 325 |
+
# ============================================================================
|
| 326 |
+
# NEURAL NETWORKS
|
| 327 |
+
# ============================================================================
|
| 328 |
+
|
| 329 |
+
class PolicyNetworkCNN(nn.Module):
|
| 330 |
+
def __init__(self):
|
| 331 |
+
super().__init__()
|
| 332 |
+
self.conv = nn.Sequential(
|
| 333 |
+
nn.Conv2d(1, 64, kernel_size=5, padding=2, stride=2),
|
| 334 |
+
nn.ReLU(),
|
| 335 |
+
nn.Conv2d(64, 128, kernel_size=5, padding=2, stride=2),
|
| 336 |
+
nn.ReLU(),
|
| 337 |
+
nn.Conv2d(128, 128, kernel_size=3, padding=1, stride=2),
|
| 338 |
+
nn.ReLU(),
|
| 339 |
+
)
|
| 340 |
+
self.fc = nn.Linear(128 * 8 * 8, 4096)
|
| 341 |
+
|
| 342 |
+
def forward(self, x):
|
| 343 |
+
x = self.conv(x)
|
| 344 |
+
x = x.view(x.size(0), -1)
|
| 345 |
+
return self.fc(x)
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
class ValueNetworkCNN(nn.Module):
|
| 349 |
+
def __init__(self):
|
| 350 |
+
super().__init__()
|
| 351 |
+
self.conv = nn.Sequential(
|
| 352 |
+
nn.Conv2d(1, 64, kernel_size=5, padding=2, stride=2),
|
| 353 |
+
nn.ReLU(),
|
| 354 |
+
nn.Conv2d(64, 128, kernel_size=5, padding=2, stride=2),
|
| 355 |
+
nn.ReLU(),
|
| 356 |
+
nn.Conv2d(128, 128, kernel_size=3, padding=1, stride=2),
|
| 357 |
+
nn.ReLU(),
|
| 358 |
+
)
|
| 359 |
+
self.fc = nn.Sequential(
|
| 360 |
+
nn.Linear(128 * 8 * 8, 512),
|
| 361 |
+
nn.ReLU(),
|
| 362 |
+
nn.Linear(512, 1),
|
| 363 |
+
nn.Tanh()
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
def forward(self, x):
|
| 367 |
+
x = self.conv(x)
|
| 368 |
+
x = x.view(x.size(0), -1)
|
| 369 |
+
return self.fc(x)
|
| 370 |
+
|
| 371 |
+
# ============================================================================
|
| 372 |
+
# ZONE DATABASE
|
| 373 |
+
# ============================================================================
|
| 374 |
+
|
| 375 |
+
class HilbertOrderedZoneDatabase:
|
| 376 |
+
def __init__(self, filepath: str = "breakthrough_zone_db.npz", max_size: int = 10000):
|
| 377 |
+
self.filepath = filepath
|
| 378 |
+
self.max_size = max_size
|
| 379 |
+
self.winning_matrices = []
|
| 380 |
+
self.winning_indices = []
|
| 381 |
+
self.losing_matrices = []
|
| 382 |
+
self.losing_indices = []
|
| 383 |
+
self.draw_matrices = []
|
| 384 |
+
self.draw_indices = []
|
| 385 |
+
self.load()
|
| 386 |
+
|
| 387 |
+
def add_winning_matrix(self, W: np.ndarray):
|
| 388 |
+
if W.shape != (64, 64):
|
| 389 |
+
return
|
| 390 |
+
hilbert_idx = matrix_to_hilbert_index(W)
|
| 391 |
+
pos = bisect.bisect_left(self.winning_indices, hilbert_idx)
|
| 392 |
+
self.winning_indices.insert(pos, hilbert_idx)
|
| 393 |
+
self.winning_matrices.insert(pos, W.copy())
|
| 394 |
+
|
| 395 |
+
def add_losing_matrix(self, W: np.ndarray):
|
| 396 |
+
if W.shape != (64, 64):
|
| 397 |
+
return
|
| 398 |
+
hilbert_idx = matrix_to_hilbert_index(W)
|
| 399 |
+
pos = bisect.bisect_left(self.losing_indices, hilbert_idx)
|
| 400 |
+
self.losing_indices.insert(pos, hilbert_idx)
|
| 401 |
+
self.losing_matrices.insert(pos, W.copy())
|
| 402 |
+
|
| 403 |
+
def add_draw_matrix(self, W: np.ndarray):
|
| 404 |
+
if W.shape != (64, 64):
|
| 405 |
+
return
|
| 406 |
+
hilbert_idx = matrix_to_hilbert_index(W)
|
| 407 |
+
pos = bisect.bisect_left(self.draw_indices, hilbert_idx)
|
| 408 |
+
self.draw_indices.insert(pos, hilbert_idx)
|
| 409 |
+
self.draw_matrices.insert(pos, W.copy())
|
| 410 |
+
|
| 411 |
+
def add_game_record(self, trajectory: List[Breakthrough], result: int, sample_rate: float = 0.3):
|
| 412 |
+
sampled_states = []
|
| 413 |
+
for i, state in enumerate(trajectory):
|
| 414 |
+
if i == 0 or i == len(trajectory) - 1:
|
| 415 |
+
sampled_states.append(state)
|
| 416 |
+
elif random.random() < sample_rate:
|
| 417 |
+
sampled_states.append(state)
|
| 418 |
+
for state in sampled_states:
|
| 419 |
+
W = state.get_weighted_adjacency_matrix()
|
| 420 |
+
if result == 1:
|
| 421 |
+
self.add_winning_matrix(W)
|
| 422 |
+
elif result == -1:
|
| 423 |
+
self.add_losing_matrix(W)
|
| 424 |
+
else:
|
| 425 |
+
self.add_draw_matrix(W)
|
| 426 |
+
|
| 427 |
+
def save(self):
|
| 428 |
+
threshold = int(self.max_size * 0.8)
|
| 429 |
+
if (len(self.winning_matrices) > threshold or
|
| 430 |
+
len(self.losing_matrices) > threshold or
|
| 431 |
+
len(self.draw_matrices) > threshold):
|
| 432 |
+
print("Pruning database before save...")
|
| 433 |
+
self.prune_database(target_size=int(self.max_size * 0.7))
|
| 434 |
+
try:
|
| 435 |
+
np.savez_compressed(
|
| 436 |
+
self.filepath,
|
| 437 |
+
winning=np.array(self.winning_matrices, dtype=object),
|
| 438 |
+
winning_indices=np.array(self.winning_indices),
|
| 439 |
+
losing=np.array(self.losing_matrices, dtype=object),
|
| 440 |
+
losing_indices=np.array(self.losing_indices),
|
| 441 |
+
draw=np.array(self.draw_matrices, dtype=object),
|
| 442 |
+
draw_indices=np.array(self.draw_indices),
|
| 443 |
+
)
|
| 444 |
+
print(f"Zone DB saved: W={len(self.winning_matrices)}, L={len(self.losing_matrices)}, D={len(self.draw_matrices)}")
|
| 445 |
+
except MemoryError:
|
| 446 |
+
print("MemoryError during save! Pruning more aggressively...")
|
| 447 |
+
self.prune_database(target_size=1000)
|
| 448 |
+
np.savez_compressed(
|
| 449 |
+
self.filepath,
|
| 450 |
+
winning=np.array(self.winning_matrices, dtype=object),
|
| 451 |
+
winning_indices=np.array(self.winning_indices),
|
| 452 |
+
losing=np.array(self.losing_matrices, dtype=object),
|
| 453 |
+
losing_indices=np.array(self.losing_indices),
|
| 454 |
+
draw=np.array(self.draw_matrices, dtype=object),
|
| 455 |
+
draw_indices=np.array(self.draw_indices),
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
def load(self):
|
| 459 |
+
if os.path.exists(self.filepath):
|
| 460 |
+
try:
|
| 461 |
+
data = np.load(self.filepath, allow_pickle=True)
|
| 462 |
+
if 'winning' in data and 'winning_indices' in data:
|
| 463 |
+
self.winning_matrices = list(data['winning'])
|
| 464 |
+
self.winning_indices = list(data['winning_indices'])
|
| 465 |
+
self.losing_matrices = list(data['losing'])
|
| 466 |
+
self.losing_indices = list(data['losing_indices'])
|
| 467 |
+
self.draw_matrices = list(data['draw'])
|
| 468 |
+
self.draw_indices = list(data['draw_indices'])
|
| 469 |
+
elif 'winning_matrices' in data and 'winning_indices' in data:
|
| 470 |
+
self.winning_matrices = list(data['winning_matrices'])
|
| 471 |
+
self.winning_indices = list(data['winning_indices'])
|
| 472 |
+
self.losing_matrices = list(data['losing_matrices'])
|
| 473 |
+
self.losing_indices = list(data['losing_indices'])
|
| 474 |
+
self.draw_matrices = list(data['draw_matrices'])
|
| 475 |
+
self.draw_indices = list(data['draw_indices'])
|
| 476 |
+
else:
|
| 477 |
+
try:
|
| 478 |
+
self.winning_matrices = list(data.get('winning', data.get('winning_matrices', [])))
|
| 479 |
+
self.winning_indices = list(data.get('winning_indices', []))
|
| 480 |
+
self.losing_matrices = list(data.get('losing', data.get('losing_matrices', [])))
|
| 481 |
+
self.losing_indices = list(data.get('losing_indices', []))
|
| 482 |
+
self.draw_matrices = list(data.get('draw', data.get('draw_matrices', [])))
|
| 483 |
+
self.draw_indices = list(data.get('draw_indices', []))
|
| 484 |
+
except Exception:
|
| 485 |
+
self.winning_matrices = []
|
| 486 |
+
self.winning_indices = []
|
| 487 |
+
self.losing_matrices = []
|
| 488 |
+
self.losing_indices = []
|
| 489 |
+
self.draw_matrices = []
|
| 490 |
+
self.draw_indices = []
|
| 491 |
+
print(f"Loaded zone DB: W={len(self.winning_matrices)}, L={len(self.losing_matrices)}, D={len(self.draw_matrices)}")
|
| 492 |
+
except Exception as e:
|
| 493 |
+
print(f"Failed to load zone database: {e}")
|
| 494 |
+
|
| 495 |
+
def prune_database(self, target_size: int = 5000):
|
| 496 |
+
def prune_zone(matrices, indices, target):
|
| 497 |
+
if len(matrices) <= target:
|
| 498 |
+
return matrices, indices
|
| 499 |
+
step = max(1, len(matrices) // target)
|
| 500 |
+
keep_idx = list(range(0, len(matrices), step))[:target]
|
| 501 |
+
return [matrices[i] for i in keep_idx], [indices[i] for i in keep_idx]
|
| 502 |
+
|
| 503 |
+
old_sizes = (len(self.winning_matrices), len(self.losing_matrices), len(self.draw_matrices))
|
| 504 |
+
self.winning_matrices, self.winning_indices = prune_zone(
|
| 505 |
+
self.winning_matrices, self.winning_indices, target_size)
|
| 506 |
+
self.losing_matrices, self.losing_indices = prune_zone(
|
| 507 |
+
self.losing_matrices, self.losing_indices, target_size)
|
| 508 |
+
self.draw_matrices, self.draw_indices = prune_zone(
|
| 509 |
+
self.draw_matrices, self.draw_indices, target_size)
|
| 510 |
+
new_sizes = (len(self.winning_matrices), len(self.losing_matrices), len(self.draw_matrices))
|
| 511 |
+
print(f"Pruned: W {old_sizes[0]}->{new_sizes[0]}, L {old_sizes[1]}->{new_sizes[1]}, D {old_sizes[2]}->{new_sizes[2]}")
|
| 512 |
+
|
| 513 |
+
def compute_zone_score(self, W: np.ndarray, k: int = 5, beta: float = 0.5) -> float:
|
| 514 |
+
if W.shape != (64, 64):
|
| 515 |
+
return 0.0
|
| 516 |
+
|
| 517 |
+
def knn_similarity(matrices, k_val):
|
| 518 |
+
if len(matrices) == 0:
|
| 519 |
+
return 0.0
|
| 520 |
+
k_actual = min(k_val, len(matrices))
|
| 521 |
+
distances = [np.sum(np.abs(W - mat)) / (64.0 * 64.0) for mat in matrices[:k_actual]]
|
| 522 |
+
return np.mean([1.0 - d for d in distances])
|
| 523 |
+
|
| 524 |
+
zone_win = knn_similarity(self.winning_matrices, k)
|
| 525 |
+
zone_loss = knn_similarity(self.losing_matrices, k)
|
| 526 |
+
zone_draw = knn_similarity(self.draw_matrices, k)
|
| 527 |
+
Z = zone_win - zone_loss + beta * zone_draw
|
| 528 |
+
return float(np.clip(Z, -1.0, 1.0))
|
| 529 |
+
|
| 530 |
+
# ============================================================================
|
| 531 |
+
# TRAINING FUNCTION
|
| 532 |
+
# ============================================================================
|
| 533 |
+
|
| 534 |
+
def train_networks(policy_net, value_net, W_states, policies, values,
|
| 535 |
+
epochs=5, batch_size=32, device='cpu', lr=0.001):
|
| 536 |
+
policy_net.train()
|
| 537 |
+
value_net.train()
|
| 538 |
+
opt_p = optim.Adam(policy_net.parameters(), lr=lr)
|
| 539 |
+
opt_v = optim.Adam(value_net.parameters(), lr=lr)
|
| 540 |
+
|
| 541 |
+
W_tensor = torch.tensor(np.array(W_states)[:, np.newaxis, :, :], dtype=torch.float32)
|
| 542 |
+
pi_tensor = torch.tensor(np.array(policies), dtype=torch.float32)
|
| 543 |
+
v_tensor = torch.tensor(np.array(values), dtype=torch.float32).unsqueeze(1)
|
| 544 |
+
|
| 545 |
+
dataset = TensorDataset(W_tensor, pi_tensor, v_tensor)
|
| 546 |
+
loader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
|
| 547 |
+
|
| 548 |
+
for epoch in range(epochs):
|
| 549 |
+
total_loss = 0.0
|
| 550 |
+
for batch_W, batch_pi, batch_v in loader:
|
| 551 |
+
batch_W = batch_W.to(device)
|
| 552 |
+
batch_pi = batch_pi.to(device)
|
| 553 |
+
batch_v = batch_v.to(device)
|
| 554 |
+
|
| 555 |
+
logits = policy_net(batch_W)
|
| 556 |
+
policy_loss = F.kl_div(F.log_softmax(logits, dim=1), batch_pi, reduction='batchmean')
|
| 557 |
+
pred_v = value_net(batch_W)
|
| 558 |
+
value_loss = F.mse_loss(pred_v, batch_v)
|
| 559 |
+
|
| 560 |
+
loss = policy_loss + value_loss
|
| 561 |
+
total_loss += loss.item()
|
| 562 |
+
|
| 563 |
+
opt_p.zero_grad()
|
| 564 |
+
opt_v.zero_grad()
|
| 565 |
+
loss.backward()
|
| 566 |
+
torch.nn.utils.clip_grad_norm_(policy_net.parameters(), max_norm=1.0)
|
| 567 |
+
torch.nn.utils.clip_grad_norm_(value_net.parameters(), max_norm=1.0)
|
| 568 |
+
opt_p.step()
|
| 569 |
+
opt_v.step()
|
| 570 |
+
|
| 571 |
+
print(f"Epoch {epoch+1}/{epochs} - Loss: {total_loss/len(loader):.4f}")
|
| 572 |
+
|
| 573 |
+
# ============================================================================
|
| 574 |
+
# MCVS SEARCHER
|
| 575 |
+
# ============================================================================
|
| 576 |
+
|
| 577 |
+
class MCVSSearcher:
|
| 578 |
+
def __init__(self, policy_net, value_net, zone_db, device='cpu',
|
| 579 |
+
cpuct=1.41, lambda_zone=0.0, k_zone=5, use_nets=True,
|
| 580 |
+
dirichlet_alpha: float = 0.3, dirichlet_noise_fraction: float = 0.25):
|
| 581 |
+
self.policy_net = policy_net.to(device) if policy_net and use_nets else None
|
| 582 |
+
self.value_net = value_net.to(device) if value_net and use_nets else None
|
| 583 |
+
self.zone_db = zone_db
|
| 584 |
+
self.device = device
|
| 585 |
+
self.cpuct = cpuct
|
| 586 |
+
self.lambda_zone = lambda_zone
|
| 587 |
+
self.k_zone = k_zone
|
| 588 |
+
self.use_nets = use_nets
|
| 589 |
+
self.dirichlet_alpha = float(dirichlet_alpha)
|
| 590 |
+
self.dirichlet_noise_fraction = float(dirichlet_noise_fraction)
|
| 591 |
+
|
| 592 |
+
def _rollout(self, game: Breakthrough) -> float:
|
| 593 |
+
"""Random rollout using apply/undo for efficiency; leaves game at leaf state."""
|
| 594 |
+
depth = 0
|
| 595 |
+
max_depth = 60
|
| 596 |
+
moves_played = []
|
| 597 |
+
while not game.is_terminal() and depth < max_depth:
|
| 598 |
+
moves = game.get_legal_moves()
|
| 599 |
+
if not moves:
|
| 600 |
+
break
|
| 601 |
+
m = random.choice(moves)
|
| 602 |
+
game.apply_move(m)
|
| 603 |
+
moves_played.append(m)
|
| 604 |
+
depth += 1
|
| 605 |
+
|
| 606 |
+
winner = game.check_winner()
|
| 607 |
+
for _ in range(len(moves_played)):
|
| 608 |
+
game.undo_move()
|
| 609 |
+
|
| 610 |
+
if winner == Breakthrough.PLAYER1:
|
| 611 |
+
return 1.0
|
| 612 |
+
elif winner == Breakthrough.PLAYER2:
|
| 613 |
+
return -1.0
|
| 614 |
+
return 0.0
|
| 615 |
+
|
| 616 |
+
class Node:
|
| 617 |
+
def __init__(self, prior: float = 0.0, zone: float = 0.0):
|
| 618 |
+
self.prior = prior
|
| 619 |
+
self.zone = zone
|
| 620 |
+
self.visit_count = 0
|
| 621 |
+
self.value_sum = 0.0
|
| 622 |
+
self.children: Dict[Tuple[int, int, int, int], 'MCVSSearcher.Node'] = {}
|
| 623 |
+
|
| 624 |
+
def search_with_time_budget(self, game: Breakthrough, time_budget: float
|
| 625 |
+
) -> Tuple[Dict[Tuple[int, int, int, int], int], int]:
|
| 626 |
+
root = self.Node()
|
| 627 |
+
start_time = time.time()
|
| 628 |
+
simulations = 0
|
| 629 |
+
|
| 630 |
+
if not game.get_legal_moves():
|
| 631 |
+
return {}, 0
|
| 632 |
+
|
| 633 |
+
while time.time() - start_time < time_budget:
|
| 634 |
+
current_game = game # shared reference — apply/undo restores state
|
| 635 |
+
node = root
|
| 636 |
+
path = []
|
| 637 |
+
moves_made = []
|
| 638 |
+
|
| 639 |
+
# ---- Selection ----
|
| 640 |
+
while node.children:
|
| 641 |
+
path.append(node)
|
| 642 |
+
total_n = sum(c.visit_count for c in node.children.values()) + 1
|
| 643 |
+
best_score = -float('inf')
|
| 644 |
+
best_move = None
|
| 645 |
+
best_child = None
|
| 646 |
+
for move, child in node.children.items():
|
| 647 |
+
q = child.value_sum / child.visit_count if child.visit_count > 0 else 0.0
|
| 648 |
+
p_lambda = max(child.prior + self.lambda_zone * child.zone, 0.001)
|
| 649 |
+
u = self.cpuct * p_lambda * np.sqrt(total_n) / (1 + child.visit_count)
|
| 650 |
+
score = q + u
|
| 651 |
+
if score > best_score:
|
| 652 |
+
best_score = score
|
| 653 |
+
best_move = move
|
| 654 |
+
best_child = child
|
| 655 |
+
current_game.apply_move(best_move)
|
| 656 |
+
moves_made.append(best_move)
|
| 657 |
+
node = best_child
|
| 658 |
+
|
| 659 |
+
path.append(node)
|
| 660 |
+
|
| 661 |
+
# ---- Expansion & Evaluation ----
|
| 662 |
+
if current_game.is_terminal():
|
| 663 |
+
w = current_game.check_winner()
|
| 664 |
+
value = 1.0 if w == Breakthrough.PLAYER1 else (-1.0 if w == Breakthrough.PLAYER2 else 0.0)
|
| 665 |
+
legal_moves = []
|
| 666 |
+
else:
|
| 667 |
+
legal_moves = current_game.get_legal_moves()
|
| 668 |
+
|
| 669 |
+
if self.use_nets and self.policy_net is not None and self.value_net is not None:
|
| 670 |
+
W = current_game.get_weighted_adjacency_matrix()
|
| 671 |
+
W_tensor = torch.from_numpy(W)[None, None, :, :].float().to(self.device)
|
| 672 |
+
with torch.no_grad():
|
| 673 |
+
logits = self.policy_net(W_tensor)[0]
|
| 674 |
+
value = self.value_net(W_tensor)[0, 0].item()
|
| 675 |
+
|
| 676 |
+
probs = F.softmax(logits, dim=0).cpu().numpy()
|
| 677 |
+
prior_dict = {}
|
| 678 |
+
prior_sum = 0.0
|
| 679 |
+
for m in legal_moves:
|
| 680 |
+
idx = move_to_index(*m)
|
| 681 |
+
p = float(probs[idx]) if idx < probs.size else 0.0
|
| 682 |
+
prior_dict[m] = p
|
| 683 |
+
prior_sum += p
|
| 684 |
+
if prior_sum > 0.0:
|
| 685 |
+
for m in prior_dict:
|
| 686 |
+
prior_dict[m] /= prior_sum
|
| 687 |
+
else:
|
| 688 |
+
p = 1.0 / len(legal_moves)
|
| 689 |
+
prior_dict = {m: p for m in legal_moves}
|
| 690 |
+
else:
|
| 691 |
+
value = self._rollout(current_game)
|
| 692 |
+
prior_dict = {m: 1.0 / len(legal_moves) for m in legal_moves} if legal_moves else {}
|
| 693 |
+
|
| 694 |
+
# Dirichlet noise at root when using nets
|
| 695 |
+
noise = None
|
| 696 |
+
if len(path) == 1 and self.use_nets and legal_moves:
|
| 697 |
+
noise = np.random.dirichlet([self.dirichlet_alpha] * len(legal_moves))
|
| 698 |
+
for i, m in enumerate(legal_moves):
|
| 699 |
+
prior_dict[m] = ((1 - self.dirichlet_noise_fraction) * prior_dict[m]
|
| 700 |
+
+ self.dirichlet_noise_fraction * noise[i])
|
| 701 |
+
prior_sum = sum(prior_dict.values())
|
| 702 |
+
if prior_sum > 0:
|
| 703 |
+
for m in prior_dict:
|
| 704 |
+
prior_dict[m] /= prior_sum
|
| 705 |
+
|
| 706 |
+
zone_db_empty = (
|
| 707 |
+
self.zone_db is None or
|
| 708 |
+
(len(getattr(self.zone_db, 'winning_matrices', [])) == 0 and
|
| 709 |
+
len(getattr(self.zone_db, 'losing_matrices', [])) == 0 and
|
| 710 |
+
len(getattr(self.zone_db, 'draw_matrices', [])) == 0)
|
| 711 |
+
)
|
| 712 |
+
need_zone = (self.lambda_zone != 0.0) and (not zone_db_empty)
|
| 713 |
+
|
| 714 |
+
for i, m in enumerate(legal_moves):
|
| 715 |
+
if need_zone:
|
| 716 |
+
current_game.apply_move(m)
|
| 717 |
+
child_W = current_game.get_weighted_adjacency_matrix()
|
| 718 |
+
child_Z = self.zone_db.compute_zone_score(child_W, k=self.k_zone)
|
| 719 |
+
current_game.undo_move()
|
| 720 |
+
else:
|
| 721 |
+
child_Z = 0.0
|
| 722 |
+
|
| 723 |
+
if len(path) == 1 and self.use_nets and legal_moves and noise is not None:
|
| 724 |
+
z_noise = (noise[i] * 2.0) - 1.0
|
| 725 |
+
child_Z = ((1 - self.dirichlet_noise_fraction) * child_Z
|
| 726 |
+
+ self.dirichlet_noise_fraction * z_noise)
|
| 727 |
+
|
| 728 |
+
node.children[m] = self.Node(prior=prior_dict.get(m, 0.0), zone=child_Z)
|
| 729 |
+
|
| 730 |
+
# ---- Backpropagation ----
|
| 731 |
+
v = value
|
| 732 |
+
for n in reversed(path):
|
| 733 |
+
n.visit_count += 1
|
| 734 |
+
n.value_sum += v
|
| 735 |
+
v = -v
|
| 736 |
+
|
| 737 |
+
# Restore game to root state
|
| 738 |
+
for _ in range(len(moves_made)):
|
| 739 |
+
current_game.undo_move()
|
| 740 |
+
|
| 741 |
+
simulations += 1
|
| 742 |
+
|
| 743 |
+
visits = {move: child.visit_count for move, child in root.children.items()}
|
| 744 |
+
if not visits:
|
| 745 |
+
legal = game.get_legal_moves()
|
| 746 |
+
visits = {random.choice(legal): 1} if legal else {}
|
| 747 |
+
return visits, simulations
|
| 748 |
+
|
| 749 |
+
# ============================================================================
|
| 750 |
+
# UCT SEARCHER (baseline)
|
| 751 |
+
# ============================================================================
|
| 752 |
+
|
| 753 |
+
class UCTSearcher:
|
| 754 |
+
def __init__(self, cpuct: float = np.sqrt(2.0)):
|
| 755 |
+
self.cpuct = cpuct
|
| 756 |
+
|
| 757 |
+
class Node:
|
| 758 |
+
def __init__(self):
|
| 759 |
+
self.visit_count = 0
|
| 760 |
+
self.value_sum = 0.0
|
| 761 |
+
self.children: Dict[Tuple[int, int, int, int], 'UCTSearcher.Node'] = {}
|
| 762 |
+
|
| 763 |
+
def _rollout(self, game: Breakthrough) -> float:
|
| 764 |
+
depth = 0
|
| 765 |
+
max_depth = 60
|
| 766 |
+
moves_played = []
|
| 767 |
+
while not game.is_terminal() and depth < max_depth:
|
| 768 |
+
moves = game.get_legal_moves()
|
| 769 |
+
if not moves:
|
| 770 |
+
break
|
| 771 |
+
m = random.choice(moves)
|
| 772 |
+
game.apply_move(m)
|
| 773 |
+
moves_played.append(m)
|
| 774 |
+
depth += 1
|
| 775 |
+
|
| 776 |
+
if depth >= max_depth:
|
| 777 |
+
for _ in range(len(moves_played)):
|
| 778 |
+
game.undo_move()
|
| 779 |
+
return 0.0
|
| 780 |
+
|
| 781 |
+
winner = game.check_winner()
|
| 782 |
+
for _ in range(len(moves_played)):
|
| 783 |
+
game.undo_move()
|
| 784 |
+
|
| 785 |
+
if winner == Breakthrough.PLAYER1:
|
| 786 |
+
return 1.0
|
| 787 |
+
elif winner == Breakthrough.PLAYER2:
|
| 788 |
+
return -1.0
|
| 789 |
+
return 0.0
|
| 790 |
+
|
| 791 |
+
def search_with_time_budget(self, game: Breakthrough, time_budget: float
|
| 792 |
+
) -> Tuple[Dict[Tuple[int, int, int, int], int], int]:
|
| 793 |
+
root = self.Node()
|
| 794 |
+
start_time = time.time()
|
| 795 |
+
simulations = 0
|
| 796 |
+
|
| 797 |
+
while time.time() - start_time < time_budget:
|
| 798 |
+
current_game = game
|
| 799 |
+
node = root
|
| 800 |
+
path = [node]
|
| 801 |
+
moves_made = []
|
| 802 |
+
|
| 803 |
+
while True:
|
| 804 |
+
legal_moves = current_game.get_legal_moves()
|
| 805 |
+
|
| 806 |
+
if current_game.is_terminal():
|
| 807 |
+
w = current_game.check_winner()
|
| 808 |
+
value = 1.0 if w == Breakthrough.PLAYER1 else (-1.0 if w == Breakthrough.PLAYER2 else 0.0)
|
| 809 |
+
break
|
| 810 |
+
|
| 811 |
+
if not legal_moves:
|
| 812 |
+
value = 0.0
|
| 813 |
+
break
|
| 814 |
+
|
| 815 |
+
unvisited = [m for m in legal_moves if m not in node.children]
|
| 816 |
+
if unvisited:
|
| 817 |
+
move = random.choice(unvisited)
|
| 818 |
+
child = self.Node()
|
| 819 |
+
node.children[move] = child
|
| 820 |
+
current_game.apply_move(move)
|
| 821 |
+
moves_made.append(move)
|
| 822 |
+
path.append(child)
|
| 823 |
+
value = self._rollout(current_game)
|
| 824 |
+
break
|
| 825 |
+
|
| 826 |
+
best_score = -float('inf')
|
| 827 |
+
best_move = None
|
| 828 |
+
best_child = None
|
| 829 |
+
total_visits = node.visit_count
|
| 830 |
+
|
| 831 |
+
for move in legal_moves:
|
| 832 |
+
child = node.children[move]
|
| 833 |
+
Q = child.value_sum / (child.visit_count + 1e-8)
|
| 834 |
+
U = self.cpuct * np.sqrt(np.log(total_visits + 1) / (child.visit_count + 1e-8))
|
| 835 |
+
score = Q + U
|
| 836 |
+
if score > best_score:
|
| 837 |
+
best_score = score
|
| 838 |
+
best_move = move
|
| 839 |
+
best_child = child
|
| 840 |
+
|
| 841 |
+
current_game.apply_move(best_move)
|
| 842 |
+
moves_made.append(best_move)
|
| 843 |
+
node = best_child
|
| 844 |
+
path.append(node)
|
| 845 |
+
|
| 846 |
+
for n in reversed(path):
|
| 847 |
+
n.visit_count += 1
|
| 848 |
+
n.value_sum += value
|
| 849 |
+
value = -value
|
| 850 |
+
|
| 851 |
+
for _ in range(len(moves_made)):
|
| 852 |
+
current_game.undo_move()
|
| 853 |
+
|
| 854 |
+
simulations += 1
|
| 855 |
+
|
| 856 |
+
visits = {move: child.visit_count for move, child in root.children.items()}
|
| 857 |
+
if not visits:
|
| 858 |
+
legal = game.get_legal_moves()
|
| 859 |
+
return {random.choice(legal): 1} if legal else {}, simulations
|
| 860 |
+
return visits, simulations
|
| 861 |
+
|
| 862 |
+
# ============================================================================
|
| 863 |
+
# SELF-PLAY DATA GENERATION
|
| 864 |
+
# ============================================================================
|
| 865 |
+
|
| 866 |
+
def generate_self_play_data(policy_net, value_net, zone_db, max_time_seconds=60.0,
|
| 867 |
+
lambda_zone=0.5, device='cpu'):
|
| 868 |
+
"""Generate self-play games using MCVS with zone guidance."""
|
| 869 |
+
searcher = MCVSSearcher(policy_net, value_net, zone_db, device=device,
|
| 870 |
+
cpuct=1.41, lambda_zone=lambda_zone, k_zone=5)
|
| 871 |
+
|
| 872 |
+
W_states = []
|
| 873 |
+
policies = []
|
| 874 |
+
values = []
|
| 875 |
+
trajectories = []
|
| 876 |
+
|
| 877 |
+
start_time = time.time()
|
| 878 |
+
game_idx = 0
|
| 879 |
+
|
| 880 |
+
while time.time() - start_time < max_time_seconds:
|
| 881 |
+
game_start_time = time.time()
|
| 882 |
+
game = Breakthrough()
|
| 883 |
+
trajectory = [game.copy()]
|
| 884 |
+
W_state_list = []
|
| 885 |
+
policy_list = []
|
| 886 |
+
|
| 887 |
+
while not game.is_terminal():
|
| 888 |
+
time_per_move = 0.3
|
| 889 |
+
W_t = game.get_weighted_adjacency_matrix()
|
| 890 |
+
visits, _ = searcher.search_with_time_budget(game, time_per_move)
|
| 891 |
+
|
| 892 |
+
if not visits:
|
| 893 |
+
break
|
| 894 |
+
|
| 895 |
+
moves = list(visits.keys())
|
| 896 |
+
visit_counts = np.array([visits[m] for m in moves], dtype=float)
|
| 897 |
+
total_visits = visit_counts.sum()
|
| 898 |
+
if total_visits <= 0:
|
| 899 |
+
break
|
| 900 |
+
probs = visit_counts / total_visits
|
| 901 |
+
|
| 902 |
+
temperature = 1.0 if game.move_count < 8 else 0.25
|
| 903 |
+
if temperature != 1.0:
|
| 904 |
+
probs = probs ** (1.0 / temperature)
|
| 905 |
+
prob_sum = probs.sum()
|
| 906 |
+
if prob_sum <= 0:
|
| 907 |
+
probs = np.ones(len(moves)) / len(moves)
|
| 908 |
+
else:
|
| 909 |
+
probs = probs / prob_sum
|
| 910 |
+
|
| 911 |
+
policy_target = np.zeros(4096)
|
| 912 |
+
for move, count in visits.items():
|
| 913 |
+
idx = move_to_index(*move)
|
| 914 |
+
if 0 <= idx < 4096:
|
| 915 |
+
policy_target[idx] = count / total_visits
|
| 916 |
+
|
| 917 |
+
W_state_list.append(W_t)
|
| 918 |
+
policy_list.append(policy_target)
|
| 919 |
+
|
| 920 |
+
if len(moves) > 1:
|
| 921 |
+
chosen_idx = np.random.choice(len(moves), p=probs)
|
| 922 |
+
chosen_move = moves[chosen_idx]
|
| 923 |
+
else:
|
| 924 |
+
chosen_move = moves[0]
|
| 925 |
+
|
| 926 |
+
game.apply_move(chosen_move)
|
| 927 |
+
trajectory.append(game.copy())
|
| 928 |
+
|
| 929 |
+
winner = game.check_winner()
|
| 930 |
+
result = (1 if winner == Breakthrough.PLAYER1
|
| 931 |
+
else -1 if winner == Breakthrough.PLAYER2
|
| 932 |
+
else 0)
|
| 933 |
+
|
| 934 |
+
for i in range(len(W_state_list)):
|
| 935 |
+
player_to_move = 1 if i % 2 == 0 else -1
|
| 936 |
+
value = result if result == 0 else (result if result == player_to_move else -result)
|
| 937 |
+
W_states.append(W_state_list[i])
|
| 938 |
+
policies.append(policy_list[i])
|
| 939 |
+
values.append(value)
|
| 940 |
+
|
| 941 |
+
zone_db.add_game_record(trajectory, result)
|
| 942 |
+
trajectories.append(trajectory)
|
| 943 |
+
|
| 944 |
+
game_idx += 1
|
| 945 |
+
game_duration = time.time() - game_start_time
|
| 946 |
+
total_elapsed = time.time() - start_time
|
| 947 |
+
print(f"Game {game_idx}: Winner={winner}, Moves={game.move_count}, "
|
| 948 |
+
f"Duration={game_duration:.1f}s, Total={total_elapsed:.1f}s")
|
| 949 |
+
|
| 950 |
+
elapsed = time.time() - start_time
|
| 951 |
+
print(f"\nSelf-play finished: {game_idx} games in {elapsed:.1f}s, "
|
| 952 |
+
f"{len(W_states)} training examples collected")
|
| 953 |
+
|
| 954 |
+
return W_states, policies, values, trajectories
|
| 955 |
+
|
| 956 |
+
# ============================================================================
|
| 957 |
+
# DIAGNOSTIC TEST FOR MOVE DIVERSITY
|
| 958 |
+
# ============================================================================
|
| 959 |
+
|
| 960 |
+
def test_move_diversity(policy_net, value_net, zone_db, num_trials=30,
|
| 961 |
+
time_budget=2.0, device='cpu'):
|
| 962 |
+
searcher = MCVSSearcher(policy_net, value_net, zone_db, device=device)
|
| 963 |
+
game = Breakthrough()
|
| 964 |
+
|
| 965 |
+
move_counts = {}
|
| 966 |
+
for _ in range(num_trials):
|
| 967 |
+
visits, _ = searcher.search_with_time_budget(game, time_budget)
|
| 968 |
+
if visits:
|
| 969 |
+
best_move = max(visits, key=visits.get)
|
| 970 |
+
move_counts[best_move] = move_counts.get(best_move, 0) + 1
|
| 971 |
+
|
| 972 |
+
print("\nMove diversity test (starting position):")
|
| 973 |
+
total = sum(move_counts.values())
|
| 974 |
+
for m, cnt in sorted(move_counts.items(), key=lambda x: -x[1]):
|
| 975 |
+
print(f"{m}: {cnt:2d}x ({cnt/total:.1%})")
|
| 976 |
+
print(f"Unique moves chosen: {len(move_counts)} out of {len(game.get_legal_moves())} legal\n")
|
| 977 |
+
|
| 978 |
+
# ============================================================================
|
| 979 |
+
# GUIDED MCVS vs UCT-MCTS TOURNAMENT
|
| 980 |
+
# ============================================================================
|
| 981 |
+
|
| 982 |
+
def play_match_mcvs_vs_uct(policy_net, value_net, zone_db, num_games: int = 200,
|
| 983 |
+
time_per_move: float = 0.3, device: str = 'cpu'):
|
| 984 |
+
"""
|
| 985 |
+
Tournament between guided MCVS and UCT.
|
| 986 |
+
Odd games: MCVS as PLAYER1; even games: UCT as PLAYER1.
|
| 987 |
+
"""
|
| 988 |
+
mcvs_searcher = MCVSSearcher(policy_net, value_net, zone_db,
|
| 989 |
+
device=device, cpuct=1.41,
|
| 990 |
+
lambda_zone=1.0, k_zone=5)
|
| 991 |
+
uct_searcher = UCTSearcher(cpuct=np.sqrt(2.0))
|
| 992 |
+
|
| 993 |
+
mcvs_wins = 0
|
| 994 |
+
uct_wins = 0
|
| 995 |
+
draws = 0
|
| 996 |
+
|
| 997 |
+
for g in range(1, num_games + 1):
|
| 998 |
+
game = Breakthrough()
|
| 999 |
+
mcvs_as_player1 = (g % 2 == 1)
|
| 1000 |
+
|
| 1001 |
+
while not game.is_terminal():
|
| 1002 |
+
moves = game.get_legal_moves()
|
| 1003 |
+
if not moves:
|
| 1004 |
+
break
|
| 1005 |
+
|
| 1006 |
+
is_player1_turn = (game.move_count % 2 == 0)
|
| 1007 |
+
use_mcvs = mcvs_as_player1 if is_player1_turn else not mcvs_as_player1
|
| 1008 |
+
|
| 1009 |
+
if use_mcvs:
|
| 1010 |
+
visits, _ = mcvs_searcher.search_with_time_budget(game, time_per_move)
|
| 1011 |
+
else:
|
| 1012 |
+
visits, _ = uct_searcher.search_with_time_budget(game, time_per_move)
|
| 1013 |
+
|
| 1014 |
+
if not visits:
|
| 1015 |
+
break
|
| 1016 |
+
|
| 1017 |
+
moves_list = list(visits.keys())
|
| 1018 |
+
counts = np.array([visits[m] for m in moves_list], dtype=float)
|
| 1019 |
+
chosen_move = moves_list[int(np.argmax(counts))]
|
| 1020 |
+
game.apply_move(chosen_move)
|
| 1021 |
+
|
| 1022 |
+
winner = game.check_winner()
|
| 1023 |
+
if winner == Breakthrough.PLAYER1:
|
| 1024 |
+
if mcvs_as_player1:
|
| 1025 |
+
mcvs_wins += 1
|
| 1026 |
+
else:
|
| 1027 |
+
uct_wins += 1
|
| 1028 |
+
elif winner == Breakthrough.PLAYER2:
|
| 1029 |
+
if mcvs_as_player1:
|
| 1030 |
+
uct_wins += 1
|
| 1031 |
+
else:
|
| 1032 |
+
mcvs_wins += 1
|
| 1033 |
+
else:
|
| 1034 |
+
draws += 1
|
| 1035 |
+
|
| 1036 |
+
print(f"Game {g}/{num_games} finished. Winner={winner} (MCVS as P1: {mcvs_as_player1})")
|
| 1037 |
+
|
| 1038 |
+
print("\n=== MCVS vs UCT Tournament Results ===")
|
| 1039 |
+
print(f"Total games : {num_games}")
|
| 1040 |
+
print(f"MCVS wins : {mcvs_wins}")
|
| 1041 |
+
print(f"UCT wins : {uct_wins}")
|
| 1042 |
+
print(f"Draws : {draws}")
|
| 1043 |
+
if num_games > 0:
|
| 1044 |
+
print(f"Win rates : MCVS={mcvs_wins/num_games*100:.1f}%, "
|
| 1045 |
+
f"UCT={uct_wins/num_games*100:.1f}%, Draw={draws/num_games*100:.1f}%\n")
|
| 1046 |
+
|
| 1047 |
+
def main():
|
| 1048 |
+
print("=" * 80)
|
| 1049 |
+
print("BREAKTHROUGH MCVS - INCREMENTAL TRAINING")
|
| 1050 |
+
print("=" * 80)
|
| 1051 |
+
|
| 1052 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 1053 |
+
print(f"Device: {device}")
|
| 1054 |
+
|
| 1055 |
+
policy_net = PolicyNetworkCNN().to(device)
|
| 1056 |
+
value_net = ValueNetworkCNN().to(device)
|
| 1057 |
+
|
| 1058 |
+
zone_db = HilbertOrderedZoneDatabase("breakthrough_zone_db.npz", max_size=10000)
|
| 1059 |
+
|
| 1060 |
+
checkpoint_path = "breakthrough_checkpoint.pt"
|
| 1061 |
+
iteration = 0
|
| 1062 |
+
|
| 1063 |
+
if os.path.exists(checkpoint_path):
|
| 1064 |
+
print(f"Loading checkpoint from {checkpoint_path}...")
|
| 1065 |
+
checkpoint = torch.load(checkpoint_path, map_location=device)
|
| 1066 |
+
policy_net.load_state_dict(checkpoint['policy'])
|
| 1067 |
+
value_net.load_state_dict(checkpoint['value'])
|
| 1068 |
+
iteration = checkpoint.get('iteration', 0)
|
| 1069 |
+
print(f"Resumed from iteration {iteration}")
|
| 1070 |
+
|
| 1071 |
+
all_W_states: List = []
|
| 1072 |
+
all_policies: List = []
|
| 1073 |
+
all_values: List = []
|
| 1074 |
+
|
| 1075 |
+
while True:
|
| 1076 |
+
print("=" * 80)
|
| 1077 |
+
print(f"ITERATION {iteration}")
|
| 1078 |
+
print("=" * 80)
|
| 1079 |
+
|
| 1080 |
+
print("Generating self-play data (30 minutes)...")
|
| 1081 |
+
lambda_zone = 0.0 if iteration == 0 else 1.0
|
| 1082 |
+
|
| 1083 |
+
W_states, policies, values, trajectories = generate_self_play_data(
|
| 1084 |
+
policy_net, value_net, zone_db,
|
| 1085 |
+
max_time_seconds=1800.0,
|
| 1086 |
+
lambda_zone=lambda_zone,
|
| 1087 |
+
device=device
|
| 1088 |
+
)
|
| 1089 |
+
|
| 1090 |
+
print(f"Collected {len(W_states)} training examples from {len(trajectories)} games")
|
| 1091 |
+
|
| 1092 |
+
all_W_states.extend(W_states)
|
| 1093 |
+
all_policies.extend(policies)
|
| 1094 |
+
all_values.extend(values)
|
| 1095 |
+
|
| 1096 |
+
max_training_examples = 50000
|
| 1097 |
+
if len(all_W_states) > max_training_examples:
|
| 1098 |
+
print(f"Trimming training data to most recent {max_training_examples} examples...")
|
| 1099 |
+
all_W_states = all_W_states[-max_training_examples:]
|
| 1100 |
+
all_policies = all_policies[-max_training_examples:]
|
| 1101 |
+
all_values = all_values[-max_training_examples:]
|
| 1102 |
+
|
| 1103 |
+
print(f"Total accumulated training examples: {len(all_W_states)}")
|
| 1104 |
+
|
| 1105 |
+
print("Training networks...")
|
| 1106 |
+
train_networks(
|
| 1107 |
+
policy_net, value_net,
|
| 1108 |
+
all_W_states, all_policies, all_values,
|
| 1109 |
+
epochs=10,
|
| 1110 |
+
device=device,
|
| 1111 |
+
lr=0.001
|
| 1112 |
+
)
|
| 1113 |
+
|
| 1114 |
+
print("Saving checkpoint...")
|
| 1115 |
+
torch.save({
|
| 1116 |
+
'policy': policy_net.state_dict(),
|
| 1117 |
+
'value': value_net.state_dict(),
|
| 1118 |
+
'iteration': iteration,
|
| 1119 |
+
'num_training_examples': len(all_W_states)
|
| 1120 |
+
}, checkpoint_path)
|
| 1121 |
+
print(f"Checkpoint saved: {checkpoint_path}")
|
| 1122 |
+
|
| 1123 |
+
zone_db.save()
|
| 1124 |
+
print(f"Zone DB saved: W={len(zone_db.winning_matrices)}, "
|
| 1125 |
+
f"L={len(zone_db.losing_matrices)}, D={len(zone_db.draw_matrices)}")
|
| 1126 |
+
|
| 1127 |
+
iteration += 1
|
| 1128 |
+
|
| 1129 |
+
print("\n" + "=" * 80)
|
| 1130 |
+
print(f"Iteration {iteration} complete!")
|
| 1131 |
+
print(f"Files updated: {checkpoint_path}, {zone_db.filepath}")
|
| 1132 |
+
print("=" * 80 + "\n")
|
| 1133 |
+
|
| 1134 |
+
if iteration % 5 == 0:
|
| 1135 |
+
print("\nRunning tournament evaluation...")
|
| 1136 |
+
play_match_mcvs_vs_uct(
|
| 1137 |
+
policy_net, value_net, zone_db,
|
| 1138 |
+
num_games=20,
|
| 1139 |
+
time_per_move=0.5,
|
| 1140 |
+
device=device
|
| 1141 |
+
)
|
| 1142 |
+
|
| 1143 |
+
|
| 1144 |
+
# ============================================================================
|
| 1145 |
+
# MAIN
|
| 1146 |
+
# ============================================================================
|
| 1147 |
+
|
| 1148 |
+
if __name__ == "__main__":
|
| 1149 |
+
pass
|