dpv007 commited on
Commit
6292460
·
verified ·
1 Parent(s): 8e60e7a

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. 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
- # Global variables for UI monitoring
15
- current_game_pgn = ""
16
- current_eval = 0.0
17
- current_sf_eval = 0.0
18
- champion_wins = 0
19
- challenger_wins = 0
20
- draws = 0
21
- training_stats = {"loss": 0.0, "reward": 0.0, "epoch": 0}
22
- current_challenger_is_white = True
23
-
24
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
25
- print(f"Using device: {device}")
26
-
27
- # Reverse vocab for decoding
28
- INV_VOCAB = {v: k for k, v in VOCAB.items()}
29
-
30
- # Initialize Stockfish Oracle globally so threads can access it
31
- stockfish_path = os.path.join("stockfish", "stockfish-windows-x86-64-avx2.exe")
32
- if os.path.exists(stockfish_path):
33
- sf_engine = chess.engine.SimpleEngine.popen_uci(stockfish_path)
34
- sf_engine.configure({"Hash": 256, "Threads": 2})
35
- sf_limit = chess.engine.Limit(time=0.1)
36
- else:
37
- sf_engine = None
38
- sf_limit = None
39
-
40
- def evaluate_position(board):
41
- if sf_engine is None:
42
- return 0.0
43
- info = sf_engine.analyse(board, sf_limit)
44
- score = info["score"].white()
45
- if score.is_mate():
46
- return 10000 if score.mate() > 0 else -10000
47
- return score.score()
48
-
49
- def encode_history(history, max_length=120):
50
- seq = []
51
- for tok in history:
52
- seq.append(VOCAB.get(tok, VOCAB.get("<unk>", 0)))
53
- if len(seq) > max_length:
54
- seq = seq[-max_length:]
55
- else:
56
- seq = seq + [0] * (max_length - len(seq))
57
- return torch.tensor(seq, dtype=torch.long, device=device).unsqueeze(0)
58
-
59
- def sample_move(policy_logits, board, temperature=1.0):
60
- # Apply temperature
61
- logits = policy_logits / temperature
62
-
63
- # Mask illegal moves
64
- legal_moves = list(board.legal_moves)
65
- legal_ucis = [m.uci() for m in legal_moves]
66
-
67
- mask = torch.full_like(logits, float('-inf'))
68
- for idx, token in INV_VOCAB.items():
69
- if token in legal_ucis:
70
- mask[0, idx] = 0.0
71
-
72
- masked_logits = logits + mask
73
- probs = F.softmax(masked_logits, dim=-1)
74
-
75
- if torch.isnan(probs).any() or probs.sum() == 0:
76
- return random.choice(legal_moves).uci()
77
-
78
- m = torch.multinomial(probs[0], 1).item()
79
- action = INV_VOCAB.get(m)
80
-
81
- if action not in legal_ucis:
82
- return random.choice(legal_moves).uci()
83
- return action
84
-
85
- def play_game(champion, challenger):
86
- global current_game_pgn, current_eval, current_sf_eval, current_challenger_is_white
87
- board = chess.Board()
88
- history = ["<bos>"]
89
-
90
- states = []
91
- actions = []
92
- policies = []
93
- values = []
94
- advantages = []
95
- sf_values = []
96
-
97
- # Initialize Stockfish Eval
98
- eval_current_cp = evaluate_position(board)
99
- current_sf_eval = max(-1.0, min(1.0, eval_current_cp / 500.0))
100
-
101
- # Randomly assign sides
102
- challenger_is_white = random.choice([True, False])
103
- current_challenger_is_white = challenger_is_white
104
-
105
- while not board.is_game_over() and len(history) < 200:
106
- turn_white = board.turn
107
- active_model = challenger if (turn_white == challenger_is_white) else champion
108
-
109
- with torch.no_grad():
110
- x = encode_history(history)
111
- policy, value = active_model(x)
112
-
113
- # Use the last token's output
114
- p_logits = policy[0, -1, :]
115
- v = value[0, -1].item()
116
-
117
- action = sample_move(p_logits.unsqueeze(0), board)
118
-
119
- # Update UI BEFORE making the move, so that the board FEN, NN Eval, and SF Eval are 100% synchronized!
120
- current_game_pgn = board.fen()
121
- current_eval = v if turn_white else -v
122
- current_sf_eval = max(-1.0, min(1.0, eval_current_cp / 500.0))
123
- time.sleep(0.05) # Small delay to make UI watchable
124
-
125
- if active_model == challenger:
126
- states.append(x)
127
- # Find action index
128
- a_idx = VOCAB.get(action, 0)
129
- actions.append(a_idx)
130
- values.append(v)
131
- policies.append(p_logits)
132
-
133
- board.push_uci(action)
134
-
135
- # Stockfish Evaluation After
136
- eval_next_cp = evaluate_position(board)
137
-
138
- if turn_white:
139
- adv = eval_next_cp - eval_current_cp
140
- else:
141
- adv = eval_current_cp - eval_next_cp
142
-
143
- advantages.append(adv)
144
-
145
- # Record the scaled Stockfish evaluation for Value Head training
146
- # We want the NN value head to predict the Stockfish eval (scaled -1 to 1)
147
- sf_val = max(-1.0, min(1.0, eval_current_cp / 500.0))
148
- if not turn_white:
149
- sf_val = -sf_val # value head is always relative to active player
150
- sf_values.append(sf_val)
151
-
152
- eval_current_cp = eval_next_cp
153
- else:
154
- board.push_uci(action)
155
- eval_current_cp = evaluate_position(board)
156
-
157
- history.append(action)
158
-
159
- # Early Termination Optimization!
160
- # If the evaluation exceeds +/- 800 centipawns (8 pawns), the game is completely lost.
161
- # There is no point wasting Stockfish CPU time playing out a dead game.
162
- if abs(eval_current_cp) > 800:
163
- break
164
-
165
- outcome = board.outcome()
166
- if outcome is None:
167
- # Game hit the 200 move limit OR was terminated early due to massive advantage.
168
- # Adjudicate based on Stockfish evaluation!
169
- if eval_current_cp >= 500: # White is completely winning
170
- reward = 1.0 if challenger_is_white else -1.0
171
- elif eval_current_cp <= -500: # Black is completely winning
172
- reward = -1.0 if challenger_is_white else 1.0
173
- else:
174
- reward = 0.0 # Draw
175
- elif outcome.winner is None:
176
- reward = 0.0 # Genuine chess draw (stalemate, repetition, etc)
177
- else:
178
- reward = 1.0 if outcome.winner == challenger_is_white else -1.0
179
-
180
- return reward, states, actions, policies, advantages, sf_values
181
-
182
- def train_rl():
183
- global champion_wins, challenger_wins, draws, training_stats
184
-
185
- os.makedirs("rl_weights", exist_ok=True)
186
-
187
- champion = ChessTransformer(vocab_size=len(VOCAB), d_model=512, nhead=8, num_layers=6, max_length=120).to(device)
188
- challenger = ChessTransformer(vocab_size=len(VOCAB), d_model=512, nhead=8, num_layers=6, max_length=120).to(device)
189
-
190
- # Load base weights
191
- latest_rl_weights = "rl_weights/champion_latest.pth"
192
- fast_weights = "weights/chess_fast_best.pth"
193
-
194
- start_epoch = 0
195
-
196
- if os.path.exists(latest_rl_weights):
197
- print(f"Loading latest RL champion from {latest_rl_weights}")
198
- ckpt = torch.load(latest_rl_weights, map_location=device)
199
- if "epoch" in ckpt and isinstance(ckpt, dict):
200
- start_epoch = ckpt["epoch"]
201
- if "model_state_dict" in ckpt:
202
- ckpt = ckpt["model_state_dict"]
203
- champion.load_state_dict(ckpt)
204
- challenger.load_state_dict(ckpt)
205
- elif os.path.exists(fast_weights):
206
- print(f"Loading base Fast weights from {fast_weights}")
207
- ckpt = torch.load(fast_weights, map_location=device)
208
- if "epoch" in ckpt and isinstance(ckpt, dict):
209
- start_epoch = ckpt["epoch"]
210
- if "model_state_dict" in ckpt:
211
- ckpt = ckpt["model_state_dict"]
212
- champion.load_state_dict(ckpt)
213
- challenger.load_state_dict(ckpt)
214
- else:
215
- print("Base weights not found, starting from scratch!")
216
-
217
- champion.eval()
218
- challenger.train()
219
-
220
- optimizer = torch.optim.AdamW(challenger.parameters(), lr=1e-5)
221
-
222
- epochs = 1000
223
- games_per_epoch = 10
224
-
225
- for step in range(epochs):
226
- epoch = start_epoch + step
227
- epoch_loss = 0
228
- epoch_reward = 0
229
-
230
- for game in range(games_per_epoch):
231
- reward, states, actions, policies, advantages, sf_values = play_game(champion, challenger)
232
- epoch_reward += reward
233
-
234
- if reward > 0:
235
- challenger_wins += 1
236
- elif reward < 0:
237
- champion_wins += 1
238
- else:
239
- draws += 1
240
-
241
- if len(states) == 0:
242
- continue
243
-
244
- # Normalize Stockfish Advantages for stability
245
- import numpy as np
246
- adv_tensor = torch.tensor(advantages, dtype=torch.float32, device=device)
247
- if adv_tensor.std() > 0:
248
- adv_tensor = (adv_tensor - adv_tensor.mean()) / (adv_tensor.std() + 1e-8)
249
- else:
250
- adv_tensor = adv_tensor - adv_tensor.mean()
251
-
252
- # Compute loss (Stockfish Dense Policy Gradient)
253
- loss = 0
254
- for i in range(len(states)):
255
- s = states[i]
256
- a = actions[i]
257
- adv = adv_tensor[i]
258
- target_v = torch.tensor(sf_values[i], dtype=torch.float32, device=device)
259
-
260
- # Re-forward to get gradients
261
- p, v_pred = challenger(s)
262
- p_logits = p[0, -1, :]
263
- v_pred = v_pred[0, -1]
264
-
265
- # Policy gradient loss: -log(pi(a|s)) * Advantage
266
- log_prob = F.log_softmax(p_logits, dim=-1)[a]
267
- policy_loss = -log_prob * adv
268
-
269
- # Value MSE Loss: Train the Value Head to predict the Stockfish Eval!
270
- value_loss = F.mse_loss(v_pred, target_v)
271
-
272
- loss += policy_loss + 0.5 * value_loss
273
-
274
- loss = loss / len(states)
275
-
276
- optimizer.zero_grad()
277
- loss.backward()
278
- torch.nn.utils.clip_grad_norm_(challenger.parameters(), 1.0)
279
- optimizer.step()
280
-
281
- epoch_loss += loss.item()
282
-
283
- avg_loss = epoch_loss / games_per_epoch
284
- avg_reward = epoch_reward / games_per_epoch
285
-
286
- training_stats["loss"] = avg_loss
287
- training_stats["reward"] = avg_reward
288
- training_stats["epoch"] = epoch + 1
289
-
290
- print(f"Epoch {epoch+1} | Loss: {avg_loss:.4f} | Avg Reward: {avg_reward:.4f} | Challenger Wins: {challenger_wins}")
291
-
292
- # Always save the Challenger's progress so you have checkpoints!
293
- save_dict = {
294
- "epoch": epoch + 1,
295
- "model_state_dict": challenger.state_dict()
296
- }
297
- torch.save(save_dict, f"rl_weights/challenger_epoch_{epoch+1}.pth")
298
-
299
- if avg_reward > 0.1: # Challenger is consistently better
300
- print("Challenger promoted to Champion!")
301
- champion.load_state_dict(challenger.state_dict())
302
- torch.save(save_dict, "rl_weights/champion_latest.pth")
303
-
304
- def build_ui():
305
- # Get board state (FEN and Eval) for Javascript
306
- def get_state():
307
- try:
308
- import json
309
- b = chess.Board(current_game_pgn)
310
- white_name = "Challenger" if current_challenger_is_white else "Champion"
311
- black_name = "Champion" if current_challenger_is_white else "Challenger"
312
- return json.dumps({
313
- "fen": b.fen(),
314
- "eval": current_eval,
315
- "sf_eval": current_sf_eval,
316
- "white_name": white_name,
317
- "black_name": black_name
318
- })
319
- except:
320
- import json
321
- return json.dumps({"fen": chess.STARTING_FEN, "eval": 0.0, "sf_eval": 0.0, "white_name": "", "black_name": ""})
322
-
323
- def get_stats():
324
- return [
325
- ["Current Epoch", str(training_stats['epoch'])],
326
- ["Loss", f"{training_stats['loss']:.4f}"],
327
- ["Avg Reward", f"{training_stats['reward']:.4f}"],
328
- ["Current Eval", f"{current_eval:.2f}"],
329
- ["Challenger Wins", str(challenger_wins)],
330
- ["Champion Wins", str(champion_wins)],
331
- ["Draws", str(draws)]
332
- ]
333
-
334
- custom_css = """
335
- @import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;700&display=swap');
336
-
337
- body, .gradio-container {
338
- font-family: 'Outfit', sans-serif !important;
339
- background: linear-gradient(135deg, #0f2027, #203a43, #2c5364) !important;
340
- background-attachment: fixed !important;
341
- color: white !important;
342
- }
343
-
344
- /* Hide some default Gradio borders/backgrounds */
345
- .gradio-container {
346
- border: none !important;
347
- }
348
-
349
- .glass-panel {
350
- background: rgba(255, 255, 255, 0.1) !important;
351
- backdrop-filter: blur(10px) !important;
352
- border-radius: 12px !important;
353
- border: 1px solid rgba(255, 255, 255, 0.18) !important;
354
- padding: 20px !important;
355
- box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37) !important;
356
- }
357
-
358
- .eval-bar-container {
359
- width: 30px;
360
- height: 400px;
361
- background-color: #333;
362
- border-radius: 4px;
363
- border: 4px solid #fff;
364
- position: relative;
365
- overflow: hidden;
366
- display: flex;
367
- flex-direction: column-reverse;
368
- box-shadow: 0 15px 35px rgba(0,0,0,0.5);
369
- }
370
- .eval-bar-fill {
371
- width: 100%;
372
- height: 50%;
373
- background-color: #fff;
374
- transition: height 0.5s cubic-bezier(0.4, 0, 0.2, 1);
375
- }
376
- .eval-marker {
377
- position: absolute;
378
- top: 50%;
379
- left: 0;
380
- width: 100%;
381
- height: 2px;
382
- background-color: #ff5e7e;
383
- z-index: 10;
384
- }
385
- """
386
-
387
- with gr.Blocks(title="Neurex RL Dashboard", css=custom_css) as demo:
388
- 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>")
389
- gr.HTML("<p style='text-align: center; color: #ddd; font-size: 1.1rem;'>Watch the Challenger learn through AlphaZero-style self-play against the Champion.</p>")
390
-
391
- with gr.Row():
392
- with gr.Column(elem_classes=["glass-panel"]):
393
- # Static div for chessboardjs AND eval bar AND player names!
394
- board_html = """
395
- <div style="display: flex; flex-direction: column; align-items: center;">
396
- <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>
397
- <div style="display: flex; align-items: center; gap: 15px; justify-content: center;">
398
- <div class="eval-bar-container" title="Neural Network Evaluation">
399
- <div class="eval-bar-fill" id="evalBar"></div>
400
- <div class="eval-marker"></div>
401
- </div>
402
- <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>
403
- <div class="eval-bar-container" title="Stockfish Evaluation">
404
- <div class="eval-bar-fill" id="sfEvalBar" style="background-color: #00ff88;"></div>
405
- <div class="eval-marker"></div>
406
- </div>
407
- </div>
408
- <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>
409
- </div>
410
- """
411
- board_view = gr.HTML(board_html)
412
- # Hidden textbox to receive state updates from Python
413
- current_state_box = gr.Textbox(visible=False)
414
- with gr.Column(elem_classes=["glass-panel"]):
415
- stats_view = gr.Dataframe(headers=["Metric", "Value"], interactive=False)
416
-
417
- timer = gr.Timer(0.5)
418
- # Update State and stats every 0.5s
419
- timer.tick(get_state, inputs=[], outputs=[current_state_box])
420
- timer.tick(get_stats, inputs=[], outputs=[stats_view])
421
-
422
- # When State changes, trigger custom JS to animate the chessboard and eval bar!
423
- js_callback = """
424
- (state_str) => {
425
- try {
426
- let state = JSON.parse(state_str);
427
- if (window.my_board) window.my_board.position(state.fen);
428
-
429
- let evalBar = document.getElementById('evalBar');
430
- if (evalBar) {
431
- let heightPercent = ((state.eval + 1.0) / 2.0) * 100;
432
- heightPercent = Math.max(0, Math.min(100, heightPercent));
433
- evalBar.style.height = heightPercent + '%';
434
- }
435
-
436
- let sfEvalBar = document.getElementById('sfEvalBar');
437
- if (sfEvalBar) {
438
- let sfHeightPercent = ((state.sf_eval + 1.0) / 2.0) * 100;
439
- sfHeightPercent = Math.max(0, Math.min(100, sfHeightPercent));
440
- sfEvalBar.style.height = sfHeightPercent + '%';
441
- }
442
-
443
- let blackName = document.getElementById('blackName');
444
- if (blackName && state.black_name) {
445
- let dot = state.black_name === "Challenger" ? "🟢" : "🔴";
446
- let color = state.black_name === "Challenger" ? "#00ff88" : "#ff5e7e";
447
- blackName.innerText = dot + " " + state.black_name + " (Black)";
448
- blackName.style.color = color;
449
- }
450
-
451
- let whiteName = document.getElementById('whiteName');
452
- if (whiteName && state.white_name) {
453
- let dot = state.white_name === "Challenger" ? "🟢" : "🔴";
454
- let color = state.white_name === "Challenger" ? "#00ff88" : "#ff5e7e";
455
- whiteName.innerText = dot + " " + state.white_name + " (White)";
456
- whiteName.style.color = color;
457
- }
458
- } catch(e) {}
459
- return state_str;
460
- }
461
- """
462
- current_state_box.change(None, inputs=[current_state_box], js=js_callback)
463
-
464
- # Initialization JS to inject chessboardjs into Gradio
465
- init_js = """
466
- function() {
467
- var jq = document.createElement('script');
468
- jq.src = "https://code.jquery.com/jquery-3.5.1.min.js";
469
- document.head.appendChild(jq);
470
-
471
- var css = document.createElement('link');
472
- css.rel = "stylesheet";
473
- css.href = "https://unpkg.com/@chrisoakman/chessboardjs@1.0.0/dist/chessboard-1.0.0.min.css";
474
- document.head.appendChild(css);
475
-
476
- jq.onload = function() {
477
- var cb = document.createElement('script');
478
- cb.src = "https://unpkg.com/@chrisoakman/chessboardjs@1.0.0/dist/chessboard-1.0.0.min.js";
479
- document.head.appendChild(cb);
480
- cb.onload = function() {
481
- let checkExist = setInterval(function() {
482
- if (document.getElementById('board')) {
483
- window.my_board = Chessboard('board', {
484
- position: 'start',
485
- pieceTheme: 'https://chessboardjs.com/img/chesspieces/wikipedia/{piece}.png'
486
- });
487
- clearInterval(checkExist);
488
- }
489
- }, 100);
490
- };
491
- };
492
- }
493
- """
494
- demo.load(None, None, None, js=init_js)
495
-
496
- return demo
497
-
498
- if __name__ == "__main__":
499
- # Start training in a background thread
500
- t = threading.Thread(target=train_rl, daemon=True)
501
- t.start()
502
-
503
- # Launch Gradio UI in main thread
504
- demo = build_ui()
505
- demo.launch(server_name="0.0.0.0", prevent_thread_lock=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)