Upload folder using huggingface_hub
Browse files- rl_train.py +573 -505
rl_train.py
CHANGED
|
@@ -1,505 +1,573 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
import torch.nn as nn
|
| 3 |
-
import torch.nn.functional as F
|
| 4 |
-
from model import ChessTransformer
|
| 5 |
-
from data_loader import VOCAB
|
| 6 |
-
import os
|
| 7 |
-
import random
|
| 8 |
-
import chess
|
| 9 |
-
import chess.engine
|
| 10 |
-
import gradio as gr
|
| 11 |
-
import threading
|
| 12 |
-
import time
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
#
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
with
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from model import ChessTransformer
|
| 5 |
+
from data_loader import VOCAB
|
| 6 |
+
import os
|
| 7 |
+
import random
|
| 8 |
+
import chess
|
| 9 |
+
import chess.engine
|
| 10 |
+
import gradio as gr
|
| 11 |
+
import threading
|
| 12 |
+
import time
|
| 13 |
+
import collections
|
| 14 |
+
import numpy as np
|
| 15 |
+
|
| 16 |
+
# Global variables for UI monitoring
|
| 17 |
+
current_game_pgn = ""
|
| 18 |
+
current_eval = 0.0
|
| 19 |
+
current_sf_eval = 0.0
|
| 20 |
+
champion_wins = 0
|
| 21 |
+
challenger_wins = 0
|
| 22 |
+
draws = 0
|
| 23 |
+
training_stats = {"loss": 0.0, "reward": 0.0, "epoch": 0}
|
| 24 |
+
current_challenger_is_white = True
|
| 25 |
+
last_promoted_step = 0
|
| 26 |
+
|
| 27 |
+
# Thread-safe queues and locks
|
| 28 |
+
class ReplayBuffer:
|
| 29 |
+
def __init__(self, capacity=50000):
|
| 30 |
+
self.buffer = []
|
| 31 |
+
self.capacity = capacity
|
| 32 |
+
self.ptr = 0
|
| 33 |
+
self.lock = threading.Lock()
|
| 34 |
+
|
| 35 |
+
def append(self, item):
|
| 36 |
+
with self.lock:
|
| 37 |
+
if len(self.buffer) < self.capacity:
|
| 38 |
+
self.buffer.append(item)
|
| 39 |
+
else:
|
| 40 |
+
self.buffer[self.ptr] = item
|
| 41 |
+
self.ptr = (self.ptr + 1) % self.capacity
|
| 42 |
+
|
| 43 |
+
def __len__(self):
|
| 44 |
+
with self.lock:
|
| 45 |
+
return len(self.buffer)
|
| 46 |
+
|
| 47 |
+
def sample(self, batch_size):
|
| 48 |
+
with self.lock:
|
| 49 |
+
return random.sample(self.buffer, batch_size)
|
| 50 |
+
|
| 51 |
+
replay_buffer = ReplayBuffer(50000)
|
| 52 |
+
recent_outcomes = collections.deque(maxlen=100)
|
| 53 |
+
ui_lock = threading.Lock()
|
| 54 |
+
stats_lock = threading.Lock()
|
| 55 |
+
|
| 56 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 57 |
+
print(f"Using device: {device}")
|
| 58 |
+
|
| 59 |
+
INV_VOCAB = {v: k for k, v in VOCAB.items()}
|
| 60 |
+
|
| 61 |
+
# Global Models
|
| 62 |
+
champion = None
|
| 63 |
+
challenger = None
|
| 64 |
+
optimizer = None
|
| 65 |
+
|
| 66 |
+
def get_stockfish_engine():
|
| 67 |
+
stockfish_path = os.path.join("stockfish", "stockfish-windows-x86-64-avx2.exe")
|
| 68 |
+
if os.path.exists(stockfish_path):
|
| 69 |
+
sf_engine = chess.engine.SimpleEngine.popen_uci(stockfish_path)
|
| 70 |
+
sf_engine.configure({"Hash": 64, "Threads": 1})
|
| 71 |
+
return sf_engine
|
| 72 |
+
return None
|
| 73 |
+
|
| 74 |
+
def encode_history(history, max_length=120):
|
| 75 |
+
seq = []
|
| 76 |
+
for tok in history:
|
| 77 |
+
seq.append(VOCAB.get(tok, VOCAB.get("<unk>", 0)))
|
| 78 |
+
if len(seq) > max_length:
|
| 79 |
+
seq = seq[-max_length:]
|
| 80 |
+
else:
|
| 81 |
+
seq = seq + [0] * (max_length - len(seq))
|
| 82 |
+
return torch.tensor(seq, dtype=torch.long, device=device).unsqueeze(0)
|
| 83 |
+
|
| 84 |
+
def sample_move(policy_logits, board, temperature=1.0):
|
| 85 |
+
logits = policy_logits / temperature
|
| 86 |
+
legal_moves = list(board.legal_moves)
|
| 87 |
+
legal_ucis = [m.uci() for m in legal_moves]
|
| 88 |
+
|
| 89 |
+
mask = torch.full_like(logits, float('-inf'))
|
| 90 |
+
for idx, token in INV_VOCAB.items():
|
| 91 |
+
if token in legal_ucis:
|
| 92 |
+
mask[0, idx] = 0.0
|
| 93 |
+
|
| 94 |
+
masked_logits = logits + mask
|
| 95 |
+
probs = F.softmax(masked_logits, dim=-1)
|
| 96 |
+
|
| 97 |
+
if torch.isnan(probs).any() or probs.sum() == 0:
|
| 98 |
+
return random.choice(legal_moves).uci()
|
| 99 |
+
|
| 100 |
+
m = torch.multinomial(probs[0], 1).item()
|
| 101 |
+
action = INV_VOCAB.get(m)
|
| 102 |
+
|
| 103 |
+
if action not in legal_ucis:
|
| 104 |
+
return random.choice(legal_moves).uci()
|
| 105 |
+
return action
|
| 106 |
+
|
| 107 |
+
def actor_worker(worker_id):
|
| 108 |
+
"""Background thread playing BATCH_SIZE games concurrently."""
|
| 109 |
+
global current_game_pgn, current_eval, current_sf_eval, current_challenger_is_white
|
| 110 |
+
global champion_wins, challenger_wins, draws
|
| 111 |
+
|
| 112 |
+
BATCH_SIZE = 16
|
| 113 |
+
sf_engine = get_stockfish_engine()
|
| 114 |
+
sf_limit = chess.engine.Limit(time=0.05)
|
| 115 |
+
|
| 116 |
+
def evaluate_position(board):
|
| 117 |
+
if sf_engine is None: return 0.0
|
| 118 |
+
info = sf_engine.analyse(board, sf_limit)
|
| 119 |
+
score = info["score"].white()
|
| 120 |
+
if score.is_mate(): return 10000 if score.mate() > 0 else -10000
|
| 121 |
+
return score.score()
|
| 122 |
+
|
| 123 |
+
print(f"Actor {worker_id} started with Batch Size {BATCH_SIZE}.")
|
| 124 |
+
|
| 125 |
+
while True:
|
| 126 |
+
boards = [chess.Board() for _ in range(BATCH_SIZE)]
|
| 127 |
+
histories = [["<bos>"] for _ in range(BATCH_SIZE)]
|
| 128 |
+
active = [True for _ in range(BATCH_SIZE)]
|
| 129 |
+
|
| 130 |
+
evals_current = []
|
| 131 |
+
for b in boards:
|
| 132 |
+
evals_current.append(evaluate_position(b))
|
| 133 |
+
|
| 134 |
+
import random
|
| 135 |
+
challenger_is_white = [random.choice([True, False]) for _ in range(BATCH_SIZE)]
|
| 136 |
+
|
| 137 |
+
if worker_id == 0:
|
| 138 |
+
with ui_lock:
|
| 139 |
+
current_challenger_is_white = challenger_is_white[0]
|
| 140 |
+
|
| 141 |
+
game_data = [{"states": [], "actions": [], "advantages": [], "sf_values": []} for _ in range(BATCH_SIZE)]
|
| 142 |
+
|
| 143 |
+
turn_count = 0
|
| 144 |
+
while any(active) and turn_count < 200:
|
| 145 |
+
turn_count += 1
|
| 146 |
+
|
| 147 |
+
challenger_indices = []
|
| 148 |
+
champion_indices = []
|
| 149 |
+
|
| 150 |
+
for i in range(BATCH_SIZE):
|
| 151 |
+
if not active[i]:
|
| 152 |
+
continue
|
| 153 |
+
turn_white = boards[i].turn
|
| 154 |
+
if turn_white == challenger_is_white[i]:
|
| 155 |
+
challenger_indices.append(i)
|
| 156 |
+
else:
|
| 157 |
+
champion_indices.append(i)
|
| 158 |
+
|
| 159 |
+
p_chal, v_chal = None, None
|
| 160 |
+
p_champ, v_champ = None, None
|
| 161 |
+
|
| 162 |
+
with torch.no_grad():
|
| 163 |
+
with torch.autocast(device_type='cuda', dtype=torch.float16):
|
| 164 |
+
if len(challenger_indices) > 0:
|
| 165 |
+
x_chal = torch.cat([encode_history(histories[i]) for i in challenger_indices], dim=0)
|
| 166 |
+
p_chal, v_chal = challenger(x_chal)
|
| 167 |
+
if len(champion_indices) > 0:
|
| 168 |
+
x_champ = torch.cat([encode_history(histories[i]) for i in champion_indices], dim=0)
|
| 169 |
+
p_champ, v_champ = champion(x_champ)
|
| 170 |
+
|
| 171 |
+
# Process Challenger moves
|
| 172 |
+
for idx, i in enumerate(challenger_indices):
|
| 173 |
+
p_logits = p_chal[idx, -1, :]
|
| 174 |
+
v = v_chal[idx, -1].item()
|
| 175 |
+
action = sample_move(p_logits.unsqueeze(0), boards[i])
|
| 176 |
+
|
| 177 |
+
if worker_id == 0 and i == 0:
|
| 178 |
+
with ui_lock:
|
| 179 |
+
current_game_pgn = boards[0].fen()
|
| 180 |
+
turn_white_ui = boards[0].turn
|
| 181 |
+
current_eval = v if turn_white_ui else -v
|
| 182 |
+
current_sf_eval = max(-1.0, min(1.0, evals_current[0] / 500.0))
|
| 183 |
+
import time
|
| 184 |
+
time.sleep(0.05)
|
| 185 |
+
|
| 186 |
+
game_data[i]["states"].append(encode_history(histories[i]).cpu())
|
| 187 |
+
game_data[i]["actions"].append(VOCAB.get(action, 0))
|
| 188 |
+
|
| 189 |
+
boards[i].push_uci(action)
|
| 190 |
+
eval_next_cp = evaluate_position(boards[i])
|
| 191 |
+
|
| 192 |
+
turn_white_val = not boards[i].turn
|
| 193 |
+
adv = (eval_next_cp - evals_current[i]) if turn_white_val else (evals_current[i] - eval_next_cp)
|
| 194 |
+
game_data[i]["advantages"].append(adv)
|
| 195 |
+
|
| 196 |
+
sf_val = max(-1.0, min(1.0, evals_current[i] / 500.0))
|
| 197 |
+
if not turn_white_val: sf_val = -sf_val
|
| 198 |
+
game_data[i]["sf_values"].append(sf_val)
|
| 199 |
+
|
| 200 |
+
evals_current[i] = eval_next_cp
|
| 201 |
+
histories[i].append(action)
|
| 202 |
+
|
| 203 |
+
if abs(eval_next_cp) > 800 or boards[i].is_game_over():
|
| 204 |
+
active[i] = False
|
| 205 |
+
|
| 206 |
+
# Process Champion moves
|
| 207 |
+
for idx, i in enumerate(champion_indices):
|
| 208 |
+
p_logits = p_champ[idx, -1, :]
|
| 209 |
+
action = sample_move(p_logits.unsqueeze(0), boards[i])
|
| 210 |
+
|
| 211 |
+
boards[i].push_uci(action)
|
| 212 |
+
eval_next_cp = evaluate_position(boards[i])
|
| 213 |
+
evals_current[i] = eval_next_cp
|
| 214 |
+
histories[i].append(action)
|
| 215 |
+
|
| 216 |
+
if abs(eval_next_cp) > 800 or boards[i].is_game_over():
|
| 217 |
+
active[i] = False
|
| 218 |
+
|
| 219 |
+
# Calculate rewards and push to replay buffer
|
| 220 |
+
for i in range(BATCH_SIZE):
|
| 221 |
+
outcome = boards[i].outcome()
|
| 222 |
+
if outcome is None:
|
| 223 |
+
if evals_current[i] >= 500: reward = 1.0 if challenger_is_white[i] else -1.0
|
| 224 |
+
elif evals_current[i] <= -500: reward = -1.0 if challenger_is_white[i] else 1.0
|
| 225 |
+
else: reward = 0.0
|
| 226 |
+
elif outcome.winner is None:
|
| 227 |
+
reward = 0.0
|
| 228 |
+
else:
|
| 229 |
+
reward = 1.0 if outcome.winner == challenger_is_white[i] else -1.0
|
| 230 |
+
|
| 231 |
+
with stats_lock:
|
| 232 |
+
if reward > 0:
|
| 233 |
+
challenger_wins += 1
|
| 234 |
+
recent_outcomes.append(1)
|
| 235 |
+
elif reward < 0:
|
| 236 |
+
champion_wins += 1
|
| 237 |
+
recent_outcomes.append(-1)
|
| 238 |
+
else:
|
| 239 |
+
draws += 1
|
| 240 |
+
recent_outcomes.append(0)
|
| 241 |
+
|
| 242 |
+
states = game_data[i]["states"]
|
| 243 |
+
if len(states) > 0:
|
| 244 |
+
adv_tensor = torch.tensor(game_data[i]["advantages"], dtype=torch.float32)
|
| 245 |
+
if adv_tensor.std() > 0:
|
| 246 |
+
adv_tensor = (adv_tensor - adv_tensor.mean()) / (adv_tensor.std() + 1e-8)
|
| 247 |
+
else:
|
| 248 |
+
adv_tensor = adv_tensor - adv_tensor.mean()
|
| 249 |
+
|
| 250 |
+
for j in range(len(states)):
|
| 251 |
+
replay_buffer.append((states[j], game_data[i]["actions"][j], adv_tensor[j].item(), game_data[i]["sf_values"][j]))
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def learner_worker():
|
| 255 |
+
"""Background thread that continuously samples the Replay Buffer and updates the Neural Network."""
|
| 256 |
+
global training_stats
|
| 257 |
+
print("Learner started.")
|
| 258 |
+
|
| 259 |
+
batch_size = 128
|
| 260 |
+
scaler = torch.amp.GradScaler('cuda')
|
| 261 |
+
|
| 262 |
+
import time
|
| 263 |
+
while True:
|
| 264 |
+
if len(replay_buffer) < batch_size:
|
| 265 |
+
time.sleep(1)
|
| 266 |
+
continue
|
| 267 |
+
|
| 268 |
+
batch = replay_buffer.sample(batch_size)
|
| 269 |
+
|
| 270 |
+
# Move batch to GPU
|
| 271 |
+
s_batch = torch.cat([b[0] for b in batch]).to(device)
|
| 272 |
+
a_batch = torch.tensor([b[1] for b in batch], dtype=torch.long, device=device)
|
| 273 |
+
adv_batch = torch.tensor([b[2] for b in batch], dtype=torch.float32, device=device)
|
| 274 |
+
sf_val_batch = torch.tensor([b[3] for b in batch], dtype=torch.float32, device=device)
|
| 275 |
+
|
| 276 |
+
optimizer.zero_grad()
|
| 277 |
+
|
| 278 |
+
with torch.autocast(device_type='cuda', dtype=torch.float16):
|
| 279 |
+
p, v_pred = challenger(s_batch)
|
| 280 |
+
|
| 281 |
+
p_logits = p[:, -1, :]
|
| 282 |
+
v_pred = v_pred[:, -1].squeeze(-1)
|
| 283 |
+
|
| 284 |
+
log_prob = F.log_softmax(p_logits, dim=-1)
|
| 285 |
+
action_log_probs = log_prob[torch.arange(batch_size), a_batch]
|
| 286 |
+
|
| 287 |
+
policy_loss = -(action_log_probs * adv_batch).mean()
|
| 288 |
+
value_loss = F.mse_loss(v_pred, sf_val_batch)
|
| 289 |
+
|
| 290 |
+
loss = policy_loss + 0.5 * value_loss
|
| 291 |
+
|
| 292 |
+
scaler.scale(loss).backward()
|
| 293 |
+
scaler.unscale_(optimizer)
|
| 294 |
+
torch.nn.utils.clip_grad_norm_(challenger.parameters(), 1.0)
|
| 295 |
+
scaler.step(optimizer)
|
| 296 |
+
scaler.update()
|
| 297 |
+
|
| 298 |
+
with stats_lock:
|
| 299 |
+
training_stats["epoch"] += 1
|
| 300 |
+
training_stats["loss"] = loss.item()
|
| 301 |
+
|
| 302 |
+
if len(recent_outcomes) > 0:
|
| 303 |
+
win_rate = sum(1 for x in recent_outcomes if x == 1) / len(recent_outcomes)
|
| 304 |
+
training_stats["reward"] = win_rate
|
| 305 |
+
|
| 306 |
+
# If Challenger is consistently crushing the Champion, promote it!
|
| 307 |
+
if len(recent_outcomes) >= 50 and win_rate >= 0.55:
|
| 308 |
+
print(f"\\n>>> PROMOTING CHALLENGER! Win rate: {win_rate:.2f} <<<\\n")
|
| 309 |
+
global last_promoted_step
|
| 310 |
+
last_promoted_step = training_stats["epoch"]
|
| 311 |
+
champion.load_state_dict(challenger.state_dict())
|
| 312 |
+
recent_outcomes.clear()
|
| 313 |
+
|
| 314 |
+
torch.save({
|
| 315 |
+
"epoch": training_stats["epoch"],
|
| 316 |
+
"model_state_dict": challenger.state_dict()
|
| 317 |
+
}, "rl_weights/champion_latest.pth")
|
| 318 |
+
|
| 319 |
+
if training_stats["epoch"] % 100 == 0:
|
| 320 |
+
print(f"Step {training_stats['epoch']} | Loss: {loss.item():.4f} | Win Rate: {training_stats['reward']:.2f} | Buffer: {len(replay_buffer)}")
|
| 321 |
+
torch.save({
|
| 322 |
+
"epoch": training_stats["epoch"],
|
| 323 |
+
"model_state_dict": challenger.state_dict()
|
| 324 |
+
}, "rl_weights/challenger_latest.pth")
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def init_models():
|
| 328 |
+
global champion, challenger, optimizer
|
| 329 |
+
|
| 330 |
+
os.makedirs("rl_weights", exist_ok=True)
|
| 331 |
+
|
| 332 |
+
champion = ChessTransformer(vocab_size=len(VOCAB), d_model=512, nhead=8, num_layers=6, max_length=120).to(device)
|
| 333 |
+
challenger = ChessTransformer(vocab_size=len(VOCAB), d_model=512, nhead=8, num_layers=6, max_length=120).to(device)
|
| 334 |
+
|
| 335 |
+
latest_rl_weights = "rl_weights/champion_latest.pth"
|
| 336 |
+
fast_weights = "weights/chess_fast_best.pth"
|
| 337 |
+
|
| 338 |
+
start_epoch = 0
|
| 339 |
+
if os.path.exists(latest_rl_weights):
|
| 340 |
+
print(f"Loading latest RL champion from {latest_rl_weights}")
|
| 341 |
+
ckpt = torch.load(latest_rl_weights, map_location=device)
|
| 342 |
+
if "epoch" in ckpt and isinstance(ckpt, dict):
|
| 343 |
+
start_epoch = ckpt["epoch"]
|
| 344 |
+
training_stats["epoch"] = start_epoch
|
| 345 |
+
global last_promoted_step
|
| 346 |
+
last_promoted_step = start_epoch
|
| 347 |
+
if "model_state_dict" in ckpt:
|
| 348 |
+
ckpt = ckpt["model_state_dict"]
|
| 349 |
+
champion.load_state_dict(ckpt)
|
| 350 |
+
challenger.load_state_dict(ckpt)
|
| 351 |
+
elif os.path.exists(fast_weights):
|
| 352 |
+
print(f"Loading base Fast weights from {fast_weights}")
|
| 353 |
+
ckpt = torch.load(fast_weights, map_location=device)
|
| 354 |
+
if "epoch" in ckpt and isinstance(ckpt, dict):
|
| 355 |
+
start_epoch = ckpt["epoch"]
|
| 356 |
+
training_stats["epoch"] = start_epoch
|
| 357 |
+
if "model_state_dict" in ckpt:
|
| 358 |
+
ckpt = ckpt["model_state_dict"]
|
| 359 |
+
champion.load_state_dict(ckpt)
|
| 360 |
+
challenger.load_state_dict(ckpt)
|
| 361 |
+
|
| 362 |
+
champion.eval()
|
| 363 |
+
challenger.train()
|
| 364 |
+
|
| 365 |
+
optimizer = torch.optim.AdamW(challenger.parameters(), lr=1e-5)
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def build_ui():
|
| 369 |
+
def get_state():
|
| 370 |
+
try:
|
| 371 |
+
import json
|
| 372 |
+
with ui_lock:
|
| 373 |
+
b = chess.Board(current_game_pgn)
|
| 374 |
+
eval_val = current_eval
|
| 375 |
+
sf_eval_val = current_sf_eval
|
| 376 |
+
white_name = "Challenger" if current_challenger_is_white else "Champion"
|
| 377 |
+
black_name = "Champion" if current_challenger_is_white else "Challenger"
|
| 378 |
+
|
| 379 |
+
return json.dumps({
|
| 380 |
+
"fen": b.fen(),
|
| 381 |
+
"eval": eval_val,
|
| 382 |
+
"sf_eval": sf_eval_val,
|
| 383 |
+
"white_name": white_name,
|
| 384 |
+
"black_name": black_name
|
| 385 |
+
})
|
| 386 |
+
except:
|
| 387 |
+
import json
|
| 388 |
+
return json.dumps({"fen": chess.STARTING_FEN, "eval": 0.0, "sf_eval": 0.0, "white_name": "", "black_name": ""})
|
| 389 |
+
|
| 390 |
+
def get_stats():
|
| 391 |
+
with stats_lock:
|
| 392 |
+
return [
|
| 393 |
+
["Training Steps", str(training_stats['epoch'])],
|
| 394 |
+
["Last Promoted Step", str(last_promoted_step)],
|
| 395 |
+
["Loss", f"{training_stats['loss']:.4f}"],
|
| 396 |
+
["Recent Win Rate", f"{training_stats['reward']:.2f}"],
|
| 397 |
+
["Replay Buffer Size", str(len(replay_buffer))],
|
| 398 |
+
["Challenger Wins", str(challenger_wins)],
|
| 399 |
+
["Champion Wins", str(champion_wins)],
|
| 400 |
+
["Draws", str(draws)]
|
| 401 |
+
]
|
| 402 |
+
|
| 403 |
+
custom_css = """
|
| 404 |
+
@import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;700&display=swap');
|
| 405 |
+
|
| 406 |
+
body, .gradio-container {
|
| 407 |
+
font-family: 'Outfit', sans-serif !important;
|
| 408 |
+
background: linear-gradient(135deg, #0f2027, #203a43, #2c5364) !important;
|
| 409 |
+
background-attachment: fixed !important;
|
| 410 |
+
color: white !important;
|
| 411 |
+
}
|
| 412 |
+
|
| 413 |
+
.gradio-container { border: none !important; }
|
| 414 |
+
|
| 415 |
+
.glass-panel {
|
| 416 |
+
background: rgba(255, 255, 255, 0.1) !important;
|
| 417 |
+
backdrop-filter: blur(10px) !important;
|
| 418 |
+
border-radius: 12px !important;
|
| 419 |
+
border: 1px solid rgba(255, 255, 255, 0.18) !important;
|
| 420 |
+
padding: 20px !important;
|
| 421 |
+
box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37) !important;
|
| 422 |
+
}
|
| 423 |
+
|
| 424 |
+
.eval-bar-container {
|
| 425 |
+
width: 30px;
|
| 426 |
+
height: 400px;
|
| 427 |
+
background-color: #333;
|
| 428 |
+
border-radius: 4px;
|
| 429 |
+
border: 4px solid #fff;
|
| 430 |
+
position: relative;
|
| 431 |
+
overflow: hidden;
|
| 432 |
+
display: flex;
|
| 433 |
+
flex-direction: column-reverse;
|
| 434 |
+
box-shadow: 0 15px 35px rgba(0,0,0,0.5);
|
| 435 |
+
}
|
| 436 |
+
.eval-bar-fill {
|
| 437 |
+
width: 100%;
|
| 438 |
+
height: 50%;
|
| 439 |
+
background-color: #fff;
|
| 440 |
+
transition: height 0.5s cubic-bezier(0.4, 0, 0.2, 1);
|
| 441 |
+
}
|
| 442 |
+
.eval-marker {
|
| 443 |
+
position: absolute;
|
| 444 |
+
top: 50%;
|
| 445 |
+
left: 0;
|
| 446 |
+
width: 100%;
|
| 447 |
+
height: 2px;
|
| 448 |
+
background-color: #ff5e7e;
|
| 449 |
+
z-index: 10;
|
| 450 |
+
}
|
| 451 |
+
"""
|
| 452 |
+
|
| 453 |
+
with gr.Blocks(title="Neurex RL Dashboard", css=custom_css) as demo:
|
| 454 |
+
gr.HTML("<h1 style='text-align: center; color: white; font-weight: 700; font-size: 2.5rem; text-shadow: 2px 2px 10px rgba(0,0,0,0.5);'>🧠 Neurex RL Self-Play Dashboard</h1>")
|
| 455 |
+
gr.HTML("<p style='text-align: center; color: #ddd; font-size: 1.1rem;'><b>ASYNCHRONOUS ALPHA-ZERO MODE</b> | Real-time Actor-Learner Architecture</p>")
|
| 456 |
+
|
| 457 |
+
with gr.Row():
|
| 458 |
+
with gr.Column(elem_classes=["glass-panel"]):
|
| 459 |
+
board_html = """
|
| 460 |
+
<div style="display: flex; flex-direction: column; align-items: center;">
|
| 461 |
+
<div id="blackName" style="font-size: 1.3rem; font-weight: bold; margin-bottom: 12px; color: #ff5e7e; text-shadow: 1px 1px 5px rgba(0,0,0,0.5);">Black</div>
|
| 462 |
+
<div style="display: flex; align-items: center; gap: 15px; justify-content: center;">
|
| 463 |
+
<div class="eval-bar-container" title="Neural Network Evaluation">
|
| 464 |
+
<div class="eval-bar-fill" id="evalBar"></div>
|
| 465 |
+
<div class="eval-marker"></div>
|
| 466 |
+
</div>
|
| 467 |
+
<div id="board" style="width: 400px; box-shadow: 0 15px 35px rgba(0,0,0,0.5); border: 4px solid #fff; border-radius: 4px; overflow: hidden;"></div>
|
| 468 |
+
<div class="eval-bar-container" title="Stockfish Evaluation">
|
| 469 |
+
<div class="eval-bar-fill" id="sfEvalBar" style="background-color: #00ff88;"></div>
|
| 470 |
+
<div class="eval-marker"></div>
|
| 471 |
+
</div>
|
| 472 |
+
</div>
|
| 473 |
+
<div id="whiteName" style="font-size: 1.3rem; font-weight: bold; margin-top: 12px; color: #00ff88; text-shadow: 1px 1px 5px rgba(0,0,0,0.5);">White</div>
|
| 474 |
+
</div>
|
| 475 |
+
"""
|
| 476 |
+
board_view = gr.HTML(board_html)
|
| 477 |
+
current_state_box = gr.Textbox(visible=False)
|
| 478 |
+
with gr.Column(elem_classes=["glass-panel"]):
|
| 479 |
+
stats_view = gr.Dataframe(headers=["Metric", "Value"], interactive=False)
|
| 480 |
+
|
| 481 |
+
timer = gr.Timer(0.5)
|
| 482 |
+
timer.tick(get_state, inputs=[], outputs=[current_state_box])
|
| 483 |
+
timer.tick(get_stats, inputs=[], outputs=[stats_view])
|
| 484 |
+
|
| 485 |
+
js_callback = """
|
| 486 |
+
(state_str) => {
|
| 487 |
+
try {
|
| 488 |
+
let state = JSON.parse(state_str);
|
| 489 |
+
if (window.my_board) window.my_board.position(state.fen);
|
| 490 |
+
|
| 491 |
+
let evalBar = document.getElementById('evalBar');
|
| 492 |
+
if (evalBar) {
|
| 493 |
+
let heightPercent = ((state.eval + 1.0) / 2.0) * 100;
|
| 494 |
+
heightPercent = Math.max(0, Math.min(100, heightPercent));
|
| 495 |
+
evalBar.style.height = heightPercent + '%';
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
let sfEvalBar = document.getElementById('sfEvalBar');
|
| 499 |
+
if (sfEvalBar) {
|
| 500 |
+
let sfHeightPercent = ((state.sf_eval + 1.0) / 2.0) * 100;
|
| 501 |
+
sfHeightPercent = Math.max(0, Math.min(100, sfHeightPercent));
|
| 502 |
+
sfEvalBar.style.height = sfHeightPercent + '%';
|
| 503 |
+
}
|
| 504 |
+
|
| 505 |
+
let blackName = document.getElementById('blackName');
|
| 506 |
+
if (blackName && state.black_name) {
|
| 507 |
+
let dot = state.black_name === "Challenger" ? "🟢" : "🔴";
|
| 508 |
+
let color = state.black_name === "Challenger" ? "#00ff88" : "#ff5e7e";
|
| 509 |
+
blackName.innerText = dot + " " + state.black_name + " (Black)";
|
| 510 |
+
blackName.style.color = color;
|
| 511 |
+
}
|
| 512 |
+
|
| 513 |
+
let whiteName = document.getElementById('whiteName');
|
| 514 |
+
if (whiteName && state.white_name) {
|
| 515 |
+
let dot = state.white_name === "Challenger" ? "🟢" : "🔴";
|
| 516 |
+
let color = state.white_name === "Challenger" ? "#00ff88" : "#ff5e7e";
|
| 517 |
+
whiteName.innerText = dot + " " + state.white_name + " (White)";
|
| 518 |
+
whiteName.style.color = color;
|
| 519 |
+
}
|
| 520 |
+
} catch(e) {}
|
| 521 |
+
return state_str;
|
| 522 |
+
}
|
| 523 |
+
"""
|
| 524 |
+
current_state_box.change(None, inputs=[current_state_box], js=js_callback)
|
| 525 |
+
|
| 526 |
+
init_js = """
|
| 527 |
+
function() {
|
| 528 |
+
var jq = document.createElement('script');
|
| 529 |
+
jq.src = "https://code.jquery.com/jquery-3.5.1.min.js";
|
| 530 |
+
document.head.appendChild(jq);
|
| 531 |
+
|
| 532 |
+
var css = document.createElement('link');
|
| 533 |
+
css.rel = "stylesheet";
|
| 534 |
+
css.href = "https://unpkg.com/@chrisoakman/chessboardjs@1.0.0/dist/chessboard-1.0.0.min.css";
|
| 535 |
+
document.head.appendChild(css);
|
| 536 |
+
|
| 537 |
+
jq.onload = function() {
|
| 538 |
+
var cb = document.createElement('script');
|
| 539 |
+
cb.src = "https://unpkg.com/@chrisoakman/chessboardjs@1.0.0/dist/chessboard-1.0.0.min.js";
|
| 540 |
+
document.head.appendChild(cb);
|
| 541 |
+
cb.onload = function() {
|
| 542 |
+
let checkExist = setInterval(function() {
|
| 543 |
+
if (document.getElementById('board')) {
|
| 544 |
+
window.my_board = Chessboard('board', {
|
| 545 |
+
position: 'start',
|
| 546 |
+
pieceTheme: 'https://chessboardjs.com/img/chesspieces/wikipedia/{piece}.png'
|
| 547 |
+
});
|
| 548 |
+
clearInterval(checkExist);
|
| 549 |
+
}
|
| 550 |
+
}, 100);
|
| 551 |
+
};
|
| 552 |
+
};
|
| 553 |
+
}
|
| 554 |
+
"""
|
| 555 |
+
demo.load(None, None, None, js=init_js)
|
| 556 |
+
|
| 557 |
+
return demo
|
| 558 |
+
|
| 559 |
+
if __name__ == "__main__":
|
| 560 |
+
init_models()
|
| 561 |
+
|
| 562 |
+
# Spawn 3 Actor Threads to play games using 3 Stockfish instances
|
| 563 |
+
for i in range(4):
|
| 564 |
+
t = threading.Thread(target=actor_worker, args=(i,), daemon=True)
|
| 565 |
+
t.start()
|
| 566 |
+
|
| 567 |
+
# Spawn 1 Learner Thread to aggressively train the GPU
|
| 568 |
+
t_learner = threading.Thread(target=learner_worker, daemon=True)
|
| 569 |
+
t_learner.start()
|
| 570 |
+
|
| 571 |
+
# Launch Gradio UI in main thread
|
| 572 |
+
demo = build_ui()
|
| 573 |
+
demo.launch(server_name="0.0.0.0", prevent_thread_lock=False)
|