dpv007 commited on
Commit
ba7b4c0
·
verified ·
1 Parent(s): 0bdc0cd

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. neural_engine/src/main.rs +503 -903
neural_engine/src/main.rs CHANGED
@@ -1,903 +1,503 @@
1
- use std::io::{self, BufRead};
2
- use std::collections::HashMap;
3
- use std::fs;
4
- use std::path::Path;
5
- use std::sync::{Arc, atomic::{AtomicBool, Ordering}};
6
- use dashmap::DashMap;
7
- use shakmaty::{Chess, Position, CastlingMode};
8
- use shakmaty::zobrist::{Zobrist64, ZobristHash};
9
- use ort::session::Session;
10
- use ort::session::builder::GraphOptimizationLevel;
11
- use rand_distr::{Dirichlet, Distribution};
12
- use shakmaty_syzygy::{Tablebase, AmbiguousWdl};
13
-
14
- mod polyglot;
15
- use polyglot::PolyglotBook;
16
-
17
- #[derive(Clone)]
18
- struct RootKVCache {
19
- seq_len: usize,
20
- layers: Vec<(Vec<f32>, Vec<f32>)>,
21
- }
22
-
23
- struct MCTSNode {
24
- visit_count: u32,
25
- value_sum: f32,
26
- prior: f32,
27
- virtual_loss: u32,
28
- children: HashMap<String, u64>,
29
- }
30
-
31
- impl MCTSNode {
32
- fn new(prior: f32) -> Self {
33
- Self {
34
- visit_count: 0,
35
- value_sum: 0.0,
36
- prior,
37
- virtual_loss: 0,
38
- children: HashMap::new(),
39
- }
40
- }
41
- }
42
-
43
- fn load_vocab() -> (HashMap<String, i64>, HashMap<i64, String>) {
44
- let vocab_content = fs::read_to_string("vocab.json").expect("Unable to read vocab.json");
45
- let vocab: HashMap<String, i64> = serde_json::from_str(&vocab_content).expect("Invalid JSON in vocab.json");
46
- let inv_vocab: HashMap<i64, String> = vocab.iter().map(|(k, v)| (*v, k.clone())).collect();
47
- (vocab, inv_vocab)
48
- }
49
-
50
- fn add_dirichlet_noise(hash: u64, arena: &DashMap<u64, std::sync::Mutex<MCTSNode>>, alpha: f32, epsilon: f32) {
51
- let child_hashes: Vec<u64> = {
52
- if let Some(node_ref) = arena.get(&hash) {
53
- let node = node_ref.lock().unwrap();
54
- if node.children.is_empty() { return; }
55
- node.children.values().copied().collect()
56
- } else {
57
- return;
58
- }
59
- };
60
-
61
- let dirichlet = Dirichlet::new_with_size(alpha, child_hashes.len()).unwrap();
62
- let mut rng = rand::thread_rng();
63
- let noise = dirichlet.sample(&mut rng);
64
-
65
- for (i, child_hash) in child_hashes.into_iter().enumerate() {
66
- if let Some(child_entry) = arena.get(&child_hash) {
67
- let mut child = child_entry.lock().unwrap();
68
- child.prior = (1.0 - epsilon) * child.prior + epsilon * noise[i];
69
- }
70
- }
71
- }
72
-
73
- const PAWN_PST: [i32; 64] = [
74
- 0, 0, 0, 0, 0, 0, 0, 0,
75
- 50, 50, 50, 50, 50, 50, 50, 50,
76
- 10, 10, 20, 30, 30, 20, 10, 10,
77
- 5, 5, 10, 25, 25, 10, 5, 5,
78
- 0, 0, 0, 20, 20, 0, 0, 0,
79
- 5, -5,-10, 0, 0,-10, -5, 5,
80
- 5, 10, 10,-20,-20, 10, 10, 5,
81
- 0, 0, 0, 0, 0, 0, 0, 0
82
- ];
83
- const KNIGHT_PST: [i32; 64] = [
84
- -50,-40,-30,-30,-30,-30,-40,-50,
85
- -40,-20, 0, 0, 0, 0,-20,-40,
86
- -30, 0, 10, 15, 15, 10, 0,-30,
87
- -30, 5, 15, 20, 20, 15, 5,-30,
88
- -30, 0, 15, 20, 20, 15, 0,-30,
89
- -30, 5, 10, 15, 15, 10, 5,-30,
90
- -40,-20, 0, 5, 5, 0,-20,-40,
91
- -50,-40,-30,-30,-30,-30,-40,-50
92
- ];
93
- const BISHOP_PST: [i32; 64] = [
94
- -20,-10,-10,-10,-10,-10,-10,-20,
95
- -10, 0, 0, 0, 0, 0, 0,-10,
96
- -10, 0, 5, 10, 10, 5, 0,-10,
97
- -10, 5, 5, 10, 10, 5, 5,-10,
98
- -10, 0, 10, 10, 10, 10, 0,-10,
99
- -10, 10, 10, 10, 10, 10, 10,-10,
100
- -10, 5, 0, 0, 0, 0, 5,-10,
101
- -20,-10,-10,-10,-10,-10,-10,-20
102
- ];
103
- const ROOK_PST: [i32; 64] = [
104
- 0, 0, 0, 0, 0, 0, 0, 0,
105
- 5, 10, 10, 10, 10, 10, 10, 5,
106
- -5, 0, 0, 0, 0, 0, 0, -5,
107
- -5, 0, 0, 0, 0, 0, 0, -5,
108
- -5, 0, 0, 0, 0, 0, 0, -5,
109
- -5, 0, 0, 0, 0, 0, 0, -5,
110
- -5, 0, 0, 0, 0, 0, 0, -5,
111
- 0, 0, 0, 5, 5, 0, 0, 0
112
- ];
113
- const QUEEN_PST: [i32; 64] = [
114
- -20,-10,-10, -5, -5,-10,-10,-20,
115
- -10, 0, 0, 0, 0, 0, 0,-10,
116
- -10, 0, 5, 5, 5, 5, 0,-10,
117
- -5, 0, 5, 5, 5, 5, 0, -5,
118
- 0, 0, 5, 5, 5, 5, 0, -5,
119
- -10, 5, 5, 5, 5, 5, 0,-10,
120
- -10, 0, 5, 0, 0, 0, 0,-10,
121
- -20,-10,-10, -5, -5,-10,-10,-20
122
- ];
123
- const KING_MID_PST: [i32; 64] = [
124
- -30,-40,-40,-50,-50,-40,-40,-30,
125
- -30,-40,-40,-50,-50,-40,-40,-30,
126
- -30,-40,-40,-50,-50,-40,-40,-30,
127
- -30,-40,-40,-50,-50,-40,-40,-30,
128
- -20,-30,-30,-40,-40,-30,-30,-20,
129
- -10,-20,-20,-20,-20,-20,-20,-10,
130
- 20, 20, 0, 0, 0, 0, 20, 20,
131
- 20, 30, 10, 0, 0, 10, 30, 20
132
- ];
133
-
134
- fn get_piece_value(role: shakmaty::Role) -> i32 {
135
- match role {
136
- shakmaty::Role::Pawn => 100,
137
- shakmaty::Role::Knight => 320,
138
- shakmaty::Role::Bishop => 330,
139
- shakmaty::Role::Rook => 500,
140
- shakmaty::Role::Queen => 900,
141
- shakmaty::Role::King => 20000,
142
- }
143
- }
144
-
145
- fn evaluate_material(board: &Chess, color: shakmaty::Color) -> i32 {
146
- let b = board.board();
147
- let mut score = 0;
148
-
149
- for sq in b.occupied() {
150
- if b.color_at(sq) == Some(color) {
151
- let role = b.role_at(sq).unwrap();
152
- score += get_piece_value(role);
153
-
154
- let mut sq_idx = sq.file() as usize + (7 - sq.rank() as usize) * 8;
155
- if color == shakmaty::Color::Black {
156
- sq_idx = sq.file() as usize + (sq.rank() as usize) * 8;
157
- }
158
-
159
- match role {
160
- shakmaty::Role::Pawn => score += PAWN_PST[sq_idx],
161
- shakmaty::Role::Knight => score += KNIGHT_PST[sq_idx],
162
- shakmaty::Role::Bishop => score += BISHOP_PST[sq_idx],
163
- shakmaty::Role::Rook => score += ROOK_PST[sq_idx],
164
- shakmaty::Role::Queen => score += QUEEN_PST[sq_idx],
165
- shakmaty::Role::King => score += KING_MID_PST[sq_idx],
166
- }
167
- }
168
- }
169
-
170
- let mut king_safety_penalty = 0;
171
- if b.occupied().count() > 14 {
172
- if let Some(k) = b.king_of(color) {
173
- let k_file = k.file() as i8;
174
- let k_rank = k.rank() as i8;
175
- let mut pawn_shield = 0;
176
-
177
- let pawns = b.by_color(color) & b.by_role(shakmaty::Role::Pawn);
178
- for sq in pawns {
179
- let p_file = sq.file() as i8;
180
- let p_rank = sq.rank() as i8;
181
-
182
- if (p_file - k_file).abs() <= 1 {
183
- if (color == shakmaty::Color::White && p_rank > k_rank && p_rank - k_rank <= 2) ||
184
- (color == shakmaty::Color::Black && p_rank < k_rank && k_rank - p_rank <= 2) {
185
- pawn_shield += 1;
186
- }
187
- }
188
- }
189
-
190
- if pawn_shield == 0 {
191
- king_safety_penalty = 200; // 2 pawn equivalent
192
- } else if pawn_shield == 1 {
193
- king_safety_penalty = 100;
194
- }
195
- }
196
- }
197
-
198
- score - king_safety_penalty
199
- }
200
-
201
- fn material_difference(board: &Chess, color: shakmaty::Color) -> i32 {
202
- let other = match color {
203
- shakmaty::Color::White => shakmaty::Color::Black,
204
- shakmaty::Color::Black => shakmaty::Color::White,
205
- };
206
- evaluate_material(board, color) - evaluate_material(board, other)
207
- }
208
-
209
- fn score_move(m: &shakmaty::Move) -> i32 {
210
- if m.is_capture() {
211
- let victim = m.capture().map(|r| get_piece_value(r)).unwrap_or(0);
212
- let attacker = get_piece_value(m.role());
213
- 10000 + victim * 10 - attacker
214
- } else {
215
- 0
216
- }
217
- }
218
-
219
- fn quiescence_search(board: &Chess, mut alpha: i32, beta: i32, depth: u8) -> i32 {
220
- let in_check = board.is_check();
221
- let stand_pat = material_difference(board, board.turn());
222
-
223
- if depth >= 4 || board.is_game_over() { return stand_pat; }
224
-
225
- let mut best_score = if in_check { -99999 } else { stand_pat };
226
-
227
- if !in_check {
228
- if stand_pat >= beta { return stand_pat; }
229
- if alpha < stand_pat { alpha = stand_pat; }
230
- }
231
-
232
- let mut legals: Vec<_> = board.legal_moves().into_iter().collect();
233
- legals.sort_by_cached_key(|m| -score_move(m));
234
-
235
- for m in &legals {
236
- if m.is_capture() || in_check {
237
- let mut next_board = board.clone();
238
- next_board.play_unchecked(m);
239
- let score = -quiescence_search(&next_board, -beta, -alpha, depth + 1);
240
- if score > best_score {
241
- best_score = score;
242
- if score >= beta { break; }
243
- if score > alpha { alpha = score; }
244
- }
245
- }
246
- }
247
- best_score
248
- }
249
-
250
-
251
- fn evaluate_onnx(
252
- session: &mut Session,
253
- history: &[String],
254
- vocab: &HashMap<String, i64>,
255
- inv_vocab: &HashMap<i64, String>,
256
- root_cache: &Option<RootKVCache>,
257
- root_history_len: usize,
258
- ) -> (HashMap<String, f32>, f32) {
259
- let mut seq = Vec::new();
260
- let bos_id = vocab.get("<bos>").copied().unwrap_or(0);
261
-
262
- let is_root = root_cache.is_none();
263
-
264
- if is_root {
265
- seq.push(bos_id);
266
- let max_len = 120;
267
- let start_idx = if history.len() > max_len { history.len() - max_len } else { 0 };
268
- for tok in &history[start_idx..] {
269
- if tok == "<bos>" { continue; }
270
- if let Some(&id) = vocab.get(tok) { seq.push(id); }
271
- else { seq.push(vocab.get("<unk>").copied().unwrap_or(0)); }
272
- }
273
- } else {
274
- let new_moves = if history.len() > root_history_len { &history[root_history_len..] } else { &[] };
275
- for tok in new_moves {
276
- if tok == "<bos>" { continue; }
277
- if let Some(&id) = vocab.get(tok) { seq.push(id); }
278
- else { seq.push(vocab.get("<unk>").copied().unwrap_or(0)); }
279
- }
280
- if seq.is_empty() {
281
- seq.push(vocab.get("<unk>").copied().unwrap_or(0));
282
- }
283
- }
284
-
285
- let seq_len = seq.len();
286
- let input_value = ort::value::Tensor::from_array((vec![1, seq_len], seq)).unwrap();
287
-
288
- let mut empty_cache = RootKVCache { seq_len: 0, layers: vec![] };
289
- for _ in 0..6 { empty_cache.layers.push((vec![], vec![])); }
290
- let cache = if let Some(c) = root_cache { c } else { &empty_cache };
291
- let past_seq_len = cache.seq_len;
292
-
293
- let pk_0 = ort::value::Tensor::from_array((vec![1, 2, past_seq_len, 64], cache.layers[0].0.clone())).unwrap();
294
- let pv_0 = ort::value::Tensor::from_array((vec![1, 2, past_seq_len, 64], cache.layers[0].1.clone())).unwrap();
295
- let pk_1 = ort::value::Tensor::from_array((vec![1, 2, past_seq_len, 64], cache.layers[1].0.clone())).unwrap();
296
- let pv_1 = ort::value::Tensor::from_array((vec![1, 2, past_seq_len, 64], cache.layers[1].1.clone())).unwrap();
297
- let pk_2 = ort::value::Tensor::from_array((vec![1, 2, past_seq_len, 64], cache.layers[2].0.clone())).unwrap();
298
- let pv_2 = ort::value::Tensor::from_array((vec![1, 2, past_seq_len, 64], cache.layers[2].1.clone())).unwrap();
299
- let pk_3 = ort::value::Tensor::from_array((vec![1, 2, past_seq_len, 64], cache.layers[3].0.clone())).unwrap();
300
- let pv_3 = ort::value::Tensor::from_array((vec![1, 2, past_seq_len, 64], cache.layers[3].1.clone())).unwrap();
301
- let pk_4 = ort::value::Tensor::from_array((vec![1, 2, past_seq_len, 64], cache.layers[4].0.clone())).unwrap();
302
- let pv_4 = ort::value::Tensor::from_array((vec![1, 2, past_seq_len, 64], cache.layers[4].1.clone())).unwrap();
303
- let pk_5 = ort::value::Tensor::from_array((vec![1, 2, past_seq_len, 64], cache.layers[5].0.clone())).unwrap();
304
- let pv_5 = ort::value::Tensor::from_array((vec![1, 2, past_seq_len, 64], cache.layers[5].1.clone())).unwrap();
305
-
306
- let outputs = session.run(ort::inputs![
307
- "input_ids" => input_value,
308
- "past_k_0" => pk_0, "past_v_0" => pv_0,
309
- "past_k_1" => pk_1, "past_v_1" => pv_1,
310
- "past_k_2" => pk_2, "past_v_2" => pv_2,
311
- "past_k_3" => pk_3, "past_v_3" => pv_3,
312
- "past_k_4" => pk_4, "past_v_4" => pv_4,
313
- "past_k_5" => pk_5, "past_v_5" => pv_5
314
- ]).unwrap();
315
-
316
- let value_tensor = outputs["value"].try_extract_tensor::<f32>().unwrap();
317
- let val = value_tensor.1[0];
318
-
319
- let policy = HashMap::new();
320
-
321
- (policy, val)
322
- }
323
-
324
- fn compute_root_kv_cache(
325
- session: &mut Session,
326
- history: &[String],
327
- vocab: &HashMap<String, i64>,
328
- ) -> RootKVCache {
329
- let mut seq = Vec::new();
330
- let bos_id = vocab.get("<bos>").copied().unwrap_or(0);
331
- seq.push(bos_id);
332
- let max_len = 120;
333
- let start_idx = if history.len() > max_len { history.len() - max_len } else { 0 };
334
- for tok in &history[start_idx..] {
335
- if tok == "<bos>" { continue; }
336
- if let Some(&id) = vocab.get(tok) { seq.push(id); }
337
- else { seq.push(vocab.get("<unk>").copied().unwrap_or(0)); }
338
- }
339
-
340
- let seq_len = seq.len();
341
- let input_value = ort::value::Tensor::from_array((vec![1, seq_len], seq)).unwrap();
342
-
343
- let pk_0 = ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap();
344
- let pv_0 = ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap();
345
- let pk_1 = ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap();
346
- let pv_1 = ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap();
347
- let pk_2 = ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap();
348
- let pv_2 = ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap();
349
- let pk_3 = ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap();
350
- let pv_3 = ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap();
351
- let pk_4 = ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap();
352
- let pv_4 = ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap();
353
- let pk_5 = ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap();
354
- let pv_5 = ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap();
355
-
356
- let outputs = session.run(ort::inputs![
357
- "input_ids" => input_value,
358
- "past_k_0" => pk_0, "past_v_0" => pv_0,
359
- "past_k_1" => pk_1, "past_v_1" => pv_1,
360
- "past_k_2" => pk_2, "past_v_2" => pv_2,
361
- "past_k_3" => pk_3, "past_v_3" => pv_3,
362
- "past_k_4" => pk_4, "past_v_4" => pv_4,
363
- "past_k_5" => pk_5, "past_v_5" => pv_5
364
- ]).unwrap();
365
-
366
- let mut cache = RootKVCache { seq_len, layers: vec![] };
367
- for i in 0..6 {
368
- let pk = outputs[format!("present_k_{}", i).as_str()].try_extract_tensor::<f32>().unwrap().1.to_vec();
369
- let pv = outputs[format!("present_v_{}", i).as_str()].try_extract_tensor::<f32>().unwrap().1.to_vec();
370
- cache.layers.push((pk, pv));
371
- }
372
-
373
- cache
374
- }
375
-
376
-
377
- fn mcts_simulate(
378
- hash: u64,
379
- arena: &DashMap<u64, std::sync::Mutex<MCTSNode>>,
380
- board: Chess,
381
- history: &mut Vec<String>,
382
- history_hashes: &mut Vec<u64>,
383
- session: &mut Option<Session>,
384
- vocab: &HashMap<String, i64>,
385
- inv_vocab: &HashMap<i64, String>,
386
- nn_cache: &DashMap<u64, (HashMap<String, f32>, f32)>,
387
- tablebases: &Option<Tablebase<Chess>>,
388
- root_cache: &Option<RootKVCache>,
389
- root_history_len: usize
390
- ) -> f32 {
391
- if let Some(tb) = tablebases {
392
- if board.board().occupied().count() <= 6 {
393
- if let Ok(wdl) = tb.probe_wdl(&board) {
394
- match wdl {
395
- AmbiguousWdl::Win => return 0.99,
396
- AmbiguousWdl::Loss => return -0.99,
397
- AmbiguousWdl::Draw | AmbiguousWdl::BlessedLoss | AmbiguousWdl::CursedWin | AmbiguousWdl::MaybeLoss | AmbiguousWdl::MaybeWin => return 0.0,
398
- }
399
- }
400
- }
401
- }
402
-
403
- if board.is_game_over() {
404
- if board.is_checkmate() { return -1.0; }
405
- return 0.0;
406
- }
407
-
408
- if history_hashes.iter().filter(|&&h| h == hash).count() >= 3 {
409
- return 0.0; // 3-fold repetition
410
- }
411
-
412
- let is_empty = {
413
- let node_ref = arena.get(&hash);
414
- if let Some(n) = node_ref {
415
- n.lock().unwrap().children.is_empty()
416
- } else {
417
- true
418
- }
419
- };
420
-
421
- if is_empty {
422
- let legals: Vec<_> = board.legal_moves().into_iter().collect();
423
- for m in &legals {
424
- let uci = m.to_uci(CastlingMode::Standard).to_string();
425
- let mut next_board = board.clone();
426
- next_board.play_unchecked(m);
427
- if next_board.is_checkmate() {
428
- let next_hash = next_board.zobrist_hash::<Zobrist64>(shakmaty::EnPassantMode::Legal).0;
429
- arena.entry(next_hash).or_insert_with(|| std::sync::Mutex::new(MCTSNode::new(1.0)));
430
-
431
- if let Some(node_ref) = arena.get(&hash) {
432
- let mut node = node_ref.lock().unwrap();
433
- node.children.insert(uci, next_hash);
434
- node.visit_count += 1;
435
- node.value_sum += 1.0;
436
- }
437
- return -0.99;
438
- }
439
- }
440
-
441
- let cache_key = board.zobrist_hash::<Zobrist64>(shakmaty::EnPassantMode::Legal).0;
442
- let (policy, nn_val) = if let Some(cached) = nn_cache.get(&cache_key) {
443
- cached.value().clone()
444
- } else if let Some(sess) = session {
445
- let res = evaluate_onnx(sess, history, vocab, inv_vocab, root_cache, root_history_len);
446
- nn_cache.insert(cache_key, res.clone());
447
- res
448
- } else {
449
- (HashMap::new(), 0.0)
450
- };
451
-
452
- let mut value = if board.turn() == shakmaty::Color::Black { -nn_val } else { nn_val };
453
-
454
- let current_mat = material_difference(&board, board.turn());
455
- let qs_val = quiescence_search(&board, -99999, 99999, 0);
456
- let delta = qs_val - current_mat;
457
-
458
- if delta >= 300 {
459
- value = 0.95;
460
- } else if delta <= -300 {
461
- value = -0.95;
462
- }
463
-
464
- for m in legals {
465
- let uci_str = m.to_uci(CastlingMode::Standard).to_string();
466
- let p = *policy.get(&uci_str).unwrap_or(&0.05);
467
- let mut next_board = board.clone();
468
- next_board.play_unchecked(&m);
469
- let child_hash = next_board.zobrist_hash::<Zobrist64>(shakmaty::EnPassantMode::Legal).0;
470
-
471
- arena.entry(child_hash).or_insert_with(|| std::sync::Mutex::new(MCTSNode::new(p)));
472
- if let Some(node_ref) = arena.get(&hash) {
473
- node_ref.lock().unwrap().children.insert(uci_str, child_hash);
474
- }
475
- }
476
-
477
- if let Some(node_ref) = arena.get(&hash) {
478
- let mut node = node_ref.lock().unwrap();
479
- node.visit_count += 1;
480
- node.value_sum += value;
481
- }
482
- return -value * 0.99;
483
- }
484
-
485
- let mut best_score = f32::NEG_INFINITY;
486
- let mut best_action = String::new();
487
- let mut best_child_hash = 0;
488
-
489
- let (total_sqrt, children_info, parent_q) = {
490
- let node_ref = arena.get(&hash).unwrap();
491
- let node = node_ref.lock().unwrap();
492
- let sqrt = (node.visit_count as f32).sqrt();
493
- let pq = if node.visit_count > 0 { node.value_sum / (node.visit_count as f32) } else { 0.0 };
494
- let c_info: Vec<(String, u64)> = node.children.iter().map(|(a, &h)| (a.clone(), h)).collect();
495
- (sqrt, c_info, pq)
496
- };
497
-
498
- let c_puct = 1.5; // Lower PUCT to encourage deeper exploitation instead of wide exploration, since the model is fast
499
- for (action, child_hash) in children_info {
500
- if let Some(child_ref) = arena.get(&child_hash) {
501
- let child = child_ref.lock().unwrap();
502
- let effective_visits = child.visit_count + child.virtual_loss;
503
- let q = if effective_visits > 0 {
504
- (-child.value_sum - (child.virtual_loss as f32)) / (effective_visits as f32)
505
- } else { parent_q }; // FPU: Unvisited nodes inherit parent's perspective value
506
-
507
- let u = c_puct * child.prior * total_sqrt / (1.0 + effective_visits as f32);
508
- let score = q + u;
509
- if score > best_score {
510
- best_score = score;
511
- best_action = action.clone();
512
- best_child_hash = child_hash;
513
- }
514
- }
515
- }
516
-
517
- // Virtual Loss Application
518
- if let Some(child_ref) = arena.get(&best_child_hash) {
519
- child_ref.lock().unwrap().virtual_loss += 1;
520
- }
521
-
522
- let m = shakmaty::uci::Uci::from_ascii(best_action.as_bytes())
523
- .unwrap()
524
- .to_move(&board)
525
- .unwrap();
526
- let mut next_board = board.clone();
527
- next_board.play_unchecked(&m);
528
- history.push(best_action.clone());
529
- history_hashes.push(best_child_hash);
530
-
531
- let val = mcts_simulate(best_child_hash, arena, next_board, history, history_hashes, session, vocab, inv_vocab, nn_cache, tablebases, root_cache, root_history_len);
532
-
533
- history.pop();
534
- history_hashes.pop();
535
-
536
- if let Some(child_ref) = arena.get(&best_child_hash) {
537
- let mut child = child_ref.lock().unwrap();
538
- child.virtual_loss -= 1; // Remove virtual loss
539
- }
540
-
541
- if let Some(node_ref) = arena.get(&hash) {
542
- let mut node = node_ref.lock().unwrap();
543
- node.visit_count += 1;
544
- node.value_sum += val;
545
- }
546
-
547
- -val * 0.99
548
- }
549
-
550
- fn extract_pv(root_hash: u64, arena: &DashMap<u64, std::sync::Mutex<MCTSNode>>) -> Vec<String> {
551
- let mut pv = Vec::new();
552
- let mut current_hash = root_hash;
553
- let mut visited = std::collections::HashSet::new();
554
-
555
- while let Some(current_entry) = arena.get(&current_hash) {
556
- if !visited.insert(current_hash) { break; } // Break on cycles
557
-
558
- let current = current_entry.lock().unwrap();
559
- if current.children.is_empty() { break; }
560
- let mut best_child_hash = 0;
561
- let mut best_action = String::new();
562
- let mut best_visits = -1;
563
-
564
- for (action, &child_hash) in &current.children {
565
- if let Some(child_entry) = arena.get(&child_hash) {
566
- let child = child_entry.lock().unwrap();
567
- if (child.visit_count as i32) > best_visits {
568
- best_visits = child.visit_count as i32;
569
- best_action = action.clone();
570
- best_child_hash = child_hash;
571
- }
572
- }
573
- }
574
- if best_visits <= 0 { break; }
575
- pv.push(best_action);
576
- current_hash = best_child_hash;
577
- }
578
- pv
579
- }
580
-
581
- fn main() {
582
- let stdin = io::stdin();
583
- let mut board = Chess::default();
584
- let mut history_moves = vec!["<bos>".to_string()];
585
- let mut history_hashes = Vec::new();
586
-
587
- let _ = ort::init().with_name("neural_engine").commit();
588
-
589
- let num_threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4);
590
-
591
- let mut tb = Tablebase::<Chess>::new();
592
- let _ = tb.add_directory("syzygy");
593
- let tablebases = Arc::new(Some(tb));
594
-
595
- let polyglot_book = Arc::new(std::sync::Mutex::new(PolyglotBook::new("book.bin").ok()));
596
- let (vocab, inv_vocab) = load_vocab();
597
- let vocab = Arc::new(vocab);
598
- let inv_vocab = Arc::new(inv_vocab);
599
-
600
- let nn_cache = Arc::new(DashMap::new());
601
- let arena = Arc::new(DashMap::new());
602
- let mut global_root_hash = board.zobrist_hash::<Zobrist64>(shakmaty::EnPassantMode::Legal).0;
603
- arena.insert(global_root_hash, std::sync::Mutex::new(MCTSNode::new(1.0)));
604
-
605
- for line in stdin.lock().lines() {
606
- let line = line.expect("Failed to read line");
607
- let tokens: Vec<&str> = line.trim().split_whitespace().collect();
608
- if tokens.is_empty() { continue; }
609
-
610
- match tokens[0] {
611
- "uci" => {
612
- println!("id name Neurex");
613
- println!("id author Neural Engine Architect");
614
- println!("uciok");
615
- }
616
- "isready" => {
617
- println!("readyok");
618
- }
619
- "position" => {
620
- board = Chess::default();
621
- history_moves.clear();
622
- history_moves.push("<bos>".to_string());
623
- history_hashes.clear();
624
-
625
- let h = board.zobrist_hash::<Zobrist64>(shakmaty::EnPassantMode::Legal).0;
626
- history_hashes.push(h);
627
- global_root_hash = h;
628
-
629
- if tokens.contains(&"moves") {
630
- let moves_idx = tokens.iter().position(|&r| r == "moves").unwrap();
631
- for m_str in &tokens[moves_idx + 1..] {
632
- if let Ok(uci_move) = shakmaty::uci::Uci::from_ascii(m_str.as_bytes()) {
633
- if let Ok(m) = uci_move.to_move(&board) {
634
- board.play_unchecked(&m);
635
- history_moves.push(m_str.to_string());
636
- let h2 = board.zobrist_hash::<Zobrist64>(shakmaty::EnPassantMode::Legal).0;
637
- history_hashes.push(h2);
638
- global_root_hash = h2;
639
- }
640
- }
641
- }
642
- }
643
-
644
- if !arena.contains_key(&global_root_hash) {
645
- arena.insert(global_root_hash, std::sync::Mutex::new(MCTSNode::new(1.0)));
646
- }
647
- }
648
- "go" => {
649
- let mut movetime_ms = 5000;
650
- let mut wtime = 0;
651
- let mut btime = 0;
652
- let mut inc = 0;
653
-
654
- let mut i = 1;
655
- while i < tokens.len() {
656
- match tokens[i] {
657
- "wtime" => { wtime = tokens[i+1].parse().unwrap_or(0); i += 2; }
658
- "btime" => { btime = tokens[i+1].parse().unwrap_or(0); i += 2; }
659
- "winc" => { if board.turn() == shakmaty::Color::White { inc = tokens[i+1].parse().unwrap_or(0); } i += 2; }
660
- "binc" => { if board.turn() == shakmaty::Color::Black { inc = tokens[i+1].parse().unwrap_or(0); } i += 2; }
661
- "movetime" => { movetime_ms = tokens[i+1].parse().unwrap_or(5000); i += 2; }
662
- _ => { i += 1; }
663
- }
664
- }
665
-
666
- let mut time_left = 0;
667
- let mut opp_time = 0;
668
- if wtime > 0 || btime > 0 {
669
- if board.turn() == shakmaty::Color::White {
670
- time_left = wtime;
671
- opp_time = btime;
672
- } else {
673
- time_left = btime;
674
- opp_time = wtime;
675
- }
676
-
677
- let move_number = board.fullmoves().get();
678
- let estimated_moves_remaining = if move_number < 40 { 50 - move_number } else { 15 };
679
-
680
- let base_time = time_left / estimated_moves_remaining as u64;
681
- let inc_time = (inc as f64 * 0.75) as u64;
682
- movetime_ms = base_time + inc_time;
683
-
684
- // Time Advantage Scaling
685
- if time_left > 0 && opp_time > 0 {
686
- let ratio = time_left as f64 / opp_time as f64;
687
- if ratio > 2.0 {
688
- movetime_ms = (movetime_ms as f64 * 1.5) as u64;
689
- } else if ratio > 1.2 {
690
- movetime_ms = (movetime_ms as f64 * 1.25) as u64;
691
- } else if ratio < 0.8 {
692
- movetime_ms = (movetime_ms as f64 * 0.9) as u64;
693
- } else if ratio < 0.5 {
694
- movetime_ms = (movetime_ms as f64 * 0.75) as u64;
695
- }
696
- }
697
-
698
- let is_bullet = time_left < 120_000 && inc < 2000;
699
- if is_bullet {
700
- movetime_ms = (movetime_ms as f64 * 0.8) as u64;
701
- }
702
-
703
- if time_left < 3000 && inc < 1000 {
704
- movetime_ms = 100;
705
- }
706
-
707
- let max_allowable = if time_left > 1000 { time_left / 8 } else { time_left / 4 };
708
- movetime_ms = movetime_ms.min(max_allowable).max(10);
709
- }
710
-
711
- let buffer = (movetime_ms as f64 * 0.05) as u128;
712
- let mut safe_movetime = if movetime_ms as u128 > buffer { movetime_ms as u128 - buffer } else { movetime_ms as u128 };
713
- if safe_movetime < 10 { safe_movetime = 10; }
714
-
715
- if let Ok(book_opt) = polyglot_book.lock() {
716
- if let Some(book) = book_opt.as_ref() {
717
- if let Some(m_str) = book.lookup(global_root_hash) {
718
- println!("bestmove {}", m_str);
719
- continue;
720
- }
721
- }
722
- }
723
-
724
- add_dirichlet_noise(global_root_hash, &arena, 0.3, 0.25);
725
-
726
- let start_time = std::time::Instant::now();
727
- let keep_searching = Arc::new(AtomicBool::new(true));
728
- let mut handles = Vec::new();
729
-
730
- let root_history_len = history_moves.len();
731
- let mut root_cache = None;
732
- if let Some(mut sess) = if std::path::Path::new("model_int8.onnx").exists() {
733
- Some(Session::builder().unwrap()
734
- .with_optimization_level(GraphOptimizationLevel::Level3).unwrap()
735
- .with_intra_threads(1).unwrap()
736
- .commit_from_file("model_int8.onnx").unwrap())
737
- } else { None } {
738
- root_cache = Some(compute_root_kv_cache(&mut sess, &history_moves, &vocab));
739
- }
740
-
741
- for _ in 0..num_threads {
742
- let mut t_board = board.clone();
743
- let mut t_history = history_moves.clone();
744
- let mut t_history_hashes = history_hashes.clone();
745
- let t_arena = Arc::clone(&arena);
746
- let t_nn_cache = Arc::clone(&nn_cache);
747
- let t_vocab = Arc::clone(&vocab);
748
- let t_inv_vocab = Arc::clone(&inv_vocab);
749
- let t_tb = Arc::clone(&tablebases);
750
- let t_keep_searching = Arc::clone(&keep_searching);
751
- let t_root_cache = root_cache.clone();
752
-
753
- let handle = std::thread::spawn(move || {
754
- let mut t_session = if Path::new("model_int8.onnx").exists() {
755
- Some(Session::builder().unwrap()
756
- .with_optimization_level(GraphOptimizationLevel::Level3).unwrap()
757
- .with_intra_threads(1).unwrap()
758
- .commit_from_file("model_int8.onnx").unwrap())
759
- } else { None };
760
-
761
- while t_keep_searching.load(Ordering::Relaxed) {
762
- mcts_simulate(
763
- global_root_hash,
764
- &t_arena,
765
- t_board.clone(),
766
- &mut t_history,
767
- &mut t_history_hashes,
768
- &mut t_session,
769
- &t_vocab,
770
- &t_inv_vocab,
771
- &t_nn_cache,
772
- &t_tb,
773
- &t_root_cache,
774
- root_history_len
775
- );
776
- }
777
- });
778
- handles.push(handle);
779
- }
780
-
781
- // Dynamic Time Management Loop
782
- let mut last_best_move = String::new();
783
- let mut move_stability = 0;
784
- let mut last_print_time = std::time::Instant::now();
785
- loop {
786
- std::thread::sleep(std::time::Duration::from_millis(50));
787
- let elapsed = start_time.elapsed().as_millis();
788
-
789
- if elapsed >= safe_movetime {
790
- break;
791
- }
792
-
793
- if let Some(node_ref) = arena.get(&global_root_hash) {
794
- let node = node_ref.lock().unwrap();
795
- let mut best_visits = -1;
796
- let mut second_visits = -1;
797
- let mut best_action = String::new();
798
-
799
- for (action, &child_hash) in &node.children {
800
- if let Some(child_ref) = arena.get(&child_hash) {
801
- let visits = child_ref.lock().unwrap().visit_count as i32;
802
- if visits > best_visits {
803
- second_visits = best_visits;
804
- best_visits = visits;
805
- best_action = action.clone();
806
- } else if visits > second_visits {
807
- second_visits = visits;
808
- }
809
- }
810
- }
811
-
812
- if best_action == last_best_move {
813
- move_stability += 1;
814
- } else {
815
- move_stability = 0;
816
- last_best_move = best_action.clone();
817
- // Extend time by 50% if the best move changes, but respect max_allowable
818
- let extension = (movetime_ms as u128) / 2;
819
- safe_movetime = (safe_movetime + extension).min((movetime_ms * 2) as u128);
820
-
821
- // Safety clamp against total time
822
- if time_left > 0 {
823
- let absolute_max = if time_left > 1000 { time_left / 6 } else { time_left / 3 } as u128;
824
- safe_movetime = safe_movetime.min(absolute_max);
825
- }
826
- }
827
-
828
- // Early Stop if overwhelmingly better (stricter checks since nodes are cheap now)
829
- if best_visits > 0 && second_visits > 0 && best_visits > 3 * second_visits {
830
- if elapsed > safe_movetime / 4 && move_stability > 8 {
831
- break;
832
- }
833
- }
834
-
835
- // Stream UCI info periodically so GUIs and Lichess can read eval/nodes in real time!
836
- if last_print_time.elapsed().as_millis() > 500 {
837
- last_print_time = std::time::Instant::now();
838
- let root_visits = node.visit_count;
839
- let mut current_best_val = 0.0;
840
- if let Some(&child_hash) = node.children.get(&best_action) {
841
- if let Some(child_ref) = arena.get(&child_hash) {
842
- let child = child_ref.lock().unwrap();
843
- if child.visit_count > 0 {
844
- current_best_val = child.value_sum / child.visit_count as f32;
845
- }
846
- }
847
- }
848
- let score_cp = (current_best_val * 1000.0) as i32;
849
- // Wait! extract_pv ALSO needs to lock the root node!
850
- // Since we have `node` locked right now, we can't call extract_pv because it locks the root again!
851
- // We can just print the best action as a 1-move PV to avoid deadlock during the loop,
852
- // since GUI really just needs depth/nodes/score!
853
- let pv_str = best_action.clone();
854
-
855
- let nps = if elapsed > 1000 { (root_visits as u128 * 1000) / elapsed } else { 0 };
856
- let depth = (root_visits as f64).log2().max(1.0) as i32 + 5; // MCTS heuristic depth
857
- println!("info depth {} score cp {} nodes {} nps {} time {} pv {}", depth, score_cp, root_visits, nps, elapsed, pv_str);
858
- }
859
- }
860
- }
861
-
862
- keep_searching.store(false, Ordering::Relaxed);
863
- for h in handles { h.join().unwrap(); }
864
-
865
- let pv = extract_pv(global_root_hash, &arena);
866
- let best_move = if !pv.is_empty() {
867
- pv[0].clone()
868
- } else {
869
- let legals: Vec<_> = board.legal_moves().into_iter().collect();
870
- if legals.is_empty() { String::from("0000") } else { legals[0].to_uci(CastlingMode::Standard).to_string() }
871
- };
872
-
873
- let mut total_visits = 0;
874
- let mut best_val = 0.0;
875
- if let Some(root_ref) = arena.get(&global_root_hash) {
876
- let root = root_ref.lock().unwrap();
877
- total_visits = root.visit_count;
878
- if let Some(&child_hash) = root.children.get(&best_move) {
879
- if let Some(child_ref) = arena.get(&child_hash) {
880
- let child = child_ref.lock().unwrap();
881
- if child.visit_count > 0 {
882
- best_val = child.value_sum / child.visit_count as f32;
883
- }
884
- }
885
- }
886
- }
887
-
888
- let score_cp = (best_val * 1000.0) as i32;
889
- let nps = if start_time.elapsed().as_secs() > 0 {
890
- total_visits as u64 / start_time.elapsed().as_secs()
891
- } else { 0 };
892
-
893
- let mut pv_str = String::new();
894
- for m in pv { pv_str.push_str(&format!("{} ", m)); }
895
- println!("info depth {} score cp {} nodes {} nps {} time {} pv {}", 10, score_cp, total_visits, nps, start_time.elapsed().as_millis(), pv_str);
896
-
897
- println!("bestmove {}", best_move);
898
- }
899
- "quit" => break,
900
- _ => {}
901
- }
902
- }
903
- }
 
1
+ use std::collections::{HashMap, HashSet};
2
+ use std::io::{self, BufRead};
3
+ use std::sync::{Arc, Mutex};
4
+ use std::sync::atomic::{AtomicBool, Ordering};
5
+ use dashmap::DashMap;
6
+ use shakmaty::{Chess, Move, Position, Setup, CastlingMode};
7
+ use shakmaty::zobrist::{Zobrist64, ZobristHash};
8
+ use ort::session::builder::GraphOptimizationLevel;
9
+ use ort::session::Session;
10
+ use shakmaty_syzygy::{Tablebase, Wdl, AmbiguousWdl};
11
+ use std::path::Path;
12
+
13
+ struct PolyglotBook {
14
+ file: std::fs::File,
15
+ num_entries: u64,
16
+ }
17
+
18
+ impl PolyglotBook {
19
+ fn new(path: &str) -> Result<Self, io::Error> {
20
+ let file = std::fs::File::open(path)?;
21
+ let metadata = file.metadata()?;
22
+ let num_entries = metadata.len() / 16;
23
+ Ok(Self { file, num_entries })
24
+ }
25
+
26
+ fn lookup(&self, hash: u64) -> Option<String> {
27
+ use std::io::{Read, Seek, SeekFrom};
28
+ let mut low = 0;
29
+ let mut high = self.num_entries as i64 - 1;
30
+ let mut f = &self.file;
31
+
32
+ while low <= high {
33
+ let mid = low + (high - low) / 2;
34
+ f.seek(SeekFrom::Start(mid as u64 * 16)).ok()?;
35
+ let mut buf = [0u8; 8];
36
+ f.read_exact(&mut buf).ok()?;
37
+ let key = u64::from_be_bytes(buf);
38
+
39
+ if key == hash {
40
+ f.read_exact(&mut buf).ok()?;
41
+ let move_bits = u16::from_be_bytes([buf[0], buf[1]]);
42
+ return Some(Self::decode_move(move_bits));
43
+ } else if key < hash {
44
+ low = mid + 1;
45
+ } else {
46
+ high = mid - 1;
47
+ }
48
+ }
49
+ None
50
+ }
51
+
52
+ fn decode_move(move_bits: u16) -> String {
53
+ let to_file = (move_bits & 7) as u8;
54
+ let to_row = ((move_bits >> 3) & 7) as u8;
55
+ let from_file = ((move_bits >> 6) & 7) as u8;
56
+ let from_row = ((move_bits >> 9) & 7) as u8;
57
+ let prom = (move_bits >> 12) & 7;
58
+
59
+ let from_sq = format!("{}{}", (b'a' + from_file) as char, (b'1' + from_row) as char);
60
+ let to_sq = format!("{}{}", (b'a' + to_file) as char, (b'1' + to_row) as char);
61
+
62
+ let prom_char = match prom {
63
+ 1 => "n",
64
+ 2 => "b",
65
+ 3 => "r",
66
+ 4 => "q",
67
+ _ => "",
68
+ };
69
+
70
+ format!("{}{}{}", from_sq, to_sq, prom_char)
71
+ }
72
+ }
73
+
74
+ fn load_vocab() -> (HashMap<String, i64>, HashMap<i64, String>) {
75
+ let vocab_str = std::fs::read_to_string("vocab.json").expect("Failed to read vocab.json");
76
+ let vocab: HashMap<String, i64> = serde_json::from_str(&vocab_str).expect("Invalid vocab.json");
77
+ let mut inv_vocab = HashMap::new();
78
+ for (k, &v) in &vocab {
79
+ inv_vocab.insert(v, k.clone());
80
+ }
81
+ (vocab, inv_vocab)
82
+ }
83
+
84
+ fn get_piece_value(role: shakmaty::Role) -> i32 {
85
+ match role {
86
+ shakmaty::Role::Pawn => 100,
87
+ shakmaty::Role::Knight => 320,
88
+ shakmaty::Role::Bishop => 330,
89
+ shakmaty::Role::Rook => 500,
90
+ shakmaty::Role::Queen => 900,
91
+ shakmaty::Role::King => 20000,
92
+ }
93
+ }
94
+
95
+ #[derive(Clone)]
96
+ struct RootKVCache {
97
+ seq_len: usize,
98
+ layers: Vec<(Vec<f32>, Vec<f32>)>,
99
+ }
100
+
101
+ fn compute_root_kv_cache(
102
+ session: &mut Session,
103
+ history: &[String],
104
+ vocab: &HashMap<String, i64>,
105
+ ) -> RootKVCache {
106
+ let mut seq = Vec::new();
107
+ let bos_id = vocab.get("<bos>").copied().unwrap_or(0);
108
+ seq.push(bos_id);
109
+ let max_len = 120;
110
+ let start_idx = if history.len() > max_len { history.len() - max_len } else { 0 };
111
+ for tok in &history[start_idx..] {
112
+ if tok == "<bos>" { continue; }
113
+ if let Some(&id) = vocab.get(tok) { seq.push(id); }
114
+ else { seq.push(vocab.get("<unk>").copied().unwrap_or(0)); }
115
+ }
116
+
117
+ let seq_len = seq.len();
118
+ let input_value = ort::value::Tensor::from_array((vec![1, seq_len], seq)).unwrap();
119
+
120
+ let pk_0 = ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap();
121
+ let pv_0 = ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap();
122
+ let pk_1 = ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap();
123
+ let pv_1 = ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap();
124
+ let pk_2 = ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap();
125
+ let pv_2 = ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap();
126
+ let pk_3 = ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap();
127
+ let pv_3 = ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap();
128
+ let pk_4 = ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap();
129
+ let pv_4 = ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap();
130
+ let pk_5 = ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap();
131
+ let pv_5 = ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap();
132
+
133
+ let outputs = session.run(ort::inputs![
134
+ "input_ids" => input_value,
135
+ "past_k_0" => pk_0, "past_v_0" => pv_0,
136
+ "past_k_1" => pk_1, "past_v_1" => pv_1,
137
+ "past_k_2" => pk_2, "past_v_2" => pv_2,
138
+ "past_k_3" => pk_3, "past_v_3" => pv_3,
139
+ "past_k_4" => pk_4, "past_v_4" => pv_4,
140
+ "past_k_5" => pk_5, "past_v_5" => pv_5
141
+ ]).unwrap();
142
+
143
+ let mut cache = RootKVCache { seq_len, layers: vec![] };
144
+ for i in 0..6 {
145
+ let pk = outputs[format!("present_k_{}", i).as_str()].try_extract_tensor::<f32>().unwrap().1.to_vec();
146
+ let pv = outputs[format!("present_v_{}", i).as_str()].try_extract_tensor::<f32>().unwrap().1.to_vec();
147
+ cache.layers.push((pk, pv));
148
+ }
149
+
150
+ cache
151
+ }
152
+
153
+ fn evaluate_onnx_value(
154
+ session: &mut Session,
155
+ history: &[String],
156
+ vocab: &HashMap<String, i64>,
157
+ root_cache: &Option<RootKVCache>,
158
+ root_history_len: usize,
159
+ ) -> f32 {
160
+ let mut seq = Vec::new();
161
+ let is_root = root_cache.is_none();
162
+
163
+ if is_root {
164
+ let bos_id = vocab.get("<bos>").copied().unwrap_or(0);
165
+ seq.push(bos_id);
166
+ for tok in history {
167
+ if tok == "<bos>" { continue; }
168
+ if let Some(&id) = vocab.get(tok) { seq.push(id); }
169
+ else { seq.push(vocab.get("<unk>").copied().unwrap_or(0)); }
170
+ }
171
+ } else {
172
+ let new_moves = if history.len() > root_history_len { &history[root_history_len..] } else { &[] };
173
+ for tok in new_moves {
174
+ if tok == "<bos>" { continue; }
175
+ if let Some(&id) = vocab.get(tok) { seq.push(id); }
176
+ else { seq.push(vocab.get("<unk>").copied().unwrap_or(0)); }
177
+ }
178
+ if seq.is_empty() {
179
+ seq.push(vocab.get("<pad>").copied().unwrap_or(0));
180
+ }
181
+ }
182
+
183
+ let seq_len = seq.len();
184
+ let input_value = ort::value::Tensor::from_array((vec![1, seq_len], seq)).unwrap();
185
+
186
+ let past_seq_len = root_cache.as_ref().map(|c| c.seq_len).unwrap_or(0);
187
+
188
+ let pk_0 = if !is_root { let cache = root_cache.as_ref().unwrap(); ort::value::Tensor::from_array((vec![1, 2, past_seq_len, 64], cache.layers[0].0.clone())).unwrap() } else { ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap() };
189
+ let pv_0 = if !is_root { let cache = root_cache.as_ref().unwrap(); ort::value::Tensor::from_array((vec![1, 2, past_seq_len, 64], cache.layers[0].1.clone())).unwrap() } else { ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap() };
190
+ let pk_1 = if !is_root { let cache = root_cache.as_ref().unwrap(); ort::value::Tensor::from_array((vec![1, 2, past_seq_len, 64], cache.layers[1].0.clone())).unwrap() } else { ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap() };
191
+ let pv_1 = if !is_root { let cache = root_cache.as_ref().unwrap(); ort::value::Tensor::from_array((vec![1, 2, past_seq_len, 64], cache.layers[1].1.clone())).unwrap() } else { ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap() };
192
+ let pk_2 = if !is_root { let cache = root_cache.as_ref().unwrap(); ort::value::Tensor::from_array((vec![1, 2, past_seq_len, 64], cache.layers[2].0.clone())).unwrap() } else { ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap() };
193
+ let pv_2 = if !is_root { let cache = root_cache.as_ref().unwrap(); ort::value::Tensor::from_array((vec![1, 2, past_seq_len, 64], cache.layers[2].1.clone())).unwrap() } else { ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap() };
194
+ let pk_3 = if !is_root { let cache = root_cache.as_ref().unwrap(); ort::value::Tensor::from_array((vec![1, 2, past_seq_len, 64], cache.layers[3].0.clone())).unwrap() } else { ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap() };
195
+ let pv_3 = if !is_root { let cache = root_cache.as_ref().unwrap(); ort::value::Tensor::from_array((vec![1, 2, past_seq_len, 64], cache.layers[3].1.clone())).unwrap() } else { ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap() };
196
+ let pk_4 = if !is_root { let cache = root_cache.as_ref().unwrap(); ort::value::Tensor::from_array((vec![1, 2, past_seq_len, 64], cache.layers[4].0.clone())).unwrap() } else { ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap() };
197
+ let pv_4 = if !is_root { let cache = root_cache.as_ref().unwrap(); ort::value::Tensor::from_array((vec![1, 2, past_seq_len, 64], cache.layers[4].1.clone())).unwrap() } else { ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap() };
198
+ let pk_5 = if !is_root { let cache = root_cache.as_ref().unwrap(); ort::value::Tensor::from_array((vec![1, 2, past_seq_len, 64], cache.layers[5].0.clone())).unwrap() } else { ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap() };
199
+ let pv_5 = if !is_root { let cache = root_cache.as_ref().unwrap(); ort::value::Tensor::from_array((vec![1, 2, past_seq_len, 64], cache.layers[5].1.clone())).unwrap() } else { ort::value::Tensor::from_array(ndarray::Array4::<f32>::zeros((1, 2, 0, 64))).unwrap() };
200
+
201
+ let outputs = session.run(ort::inputs![
202
+ "input_ids" => input_value,
203
+ "past_k_0" => pk_0, "past_v_0" => pv_0,
204
+ "past_k_1" => pk_1, "past_v_1" => pv_1,
205
+ "past_k_2" => pk_2, "past_v_2" => pv_2,
206
+ "past_k_3" => pk_3, "past_v_3" => pv_3,
207
+ "past_k_4" => pk_4, "past_v_4" => pv_4,
208
+ "past_k_5" => pk_5, "past_v_5" => pv_5
209
+ ]).unwrap();
210
+ let value_tensor = outputs["value"].try_extract_tensor::<f32>().unwrap();
211
+ value_tensor.1[0]
212
+ }
213
+
214
+ #[derive(Clone, Copy, PartialEq)]
215
+ enum TTNodeType { Exact, LowerBound, UpperBound }
216
+
217
+ #[derive(Clone)]
218
+ struct TTEntry {
219
+ depth: u8,
220
+ score: f32,
221
+ node_type: TTNodeType,
222
+ best_move: Option<shakmaty::uci::Uci>,
223
+ }
224
+
225
+ fn alpha_beta(
226
+ board: &Chess,
227
+ depth: u8,
228
+ mut alpha: f32,
229
+ mut beta: f32,
230
+ history: &mut Vec<String>,
231
+ session: &mut Option<Session>,
232
+ vocab: &HashMap<String, i64>,
233
+ tt: &DashMap<u64, TTEntry>,
234
+ tablebases: &Option<Tablebase<Chess>>,
235
+ root_cache: &Option<RootKVCache>,
236
+ root_history_len: usize,
237
+ stop_flag: &AtomicBool,
238
+ ) -> f32 {
239
+ if stop_flag.load(Ordering::Relaxed) { return 0.0; }
240
+
241
+ if let Some(tb) = tablebases {
242
+ if board.board().occupied().count() <= 6 {
243
+ if let Ok(wdl) = tb.probe_wdl(board) {
244
+ match wdl {
245
+ AmbiguousWdl::Win => return 0.99,
246
+ AmbiguousWdl::Loss => return -0.99,
247
+ AmbiguousWdl::Draw | AmbiguousWdl::BlessedLoss | AmbiguousWdl::CursedWin | AmbiguousWdl::MaybeLoss | AmbiguousWdl::MaybeWin => return 0.0,
248
+ }
249
+ }
250
+ }
251
+ }
252
+
253
+ if board.is_game_over() {
254
+ if board.is_checkmate() { return -1.0; }
255
+ return 0.0;
256
+ }
257
+
258
+ let hash = board.zobrist_hash::<Zobrist64>(shakmaty::EnPassantMode::Legal).0;
259
+
260
+ let mut tt_move = None;
261
+ if let Some(entry) = tt.get(&hash) {
262
+ if entry.depth >= depth {
263
+ match entry.node_type {
264
+ TTNodeType::Exact => return entry.score,
265
+ TTNodeType::LowerBound => { if entry.score > alpha { alpha = entry.score; } },
266
+ TTNodeType::UpperBound => { if entry.score < beta { beta = entry.score; } },
267
+ }
268
+ if alpha >= beta { return entry.score; }
269
+ }
270
+ tt_move = entry.best_move.clone();
271
+ }
272
+
273
+ if depth == 0 {
274
+ let nn_val = if let Some(sess) = session {
275
+ evaluate_onnx_value(sess, history, vocab, root_cache, root_history_len)
276
+ } else {
277
+ 0.0
278
+ };
279
+ let val = if board.turn() == shakmaty::Color::Black { -nn_val } else { nn_val };
280
+ return val;
281
+ }
282
+
283
+ let mut legals: Vec<_> = board.legal_moves().into_iter().collect();
284
+ legals.sort_by_cached_key(|m| {
285
+ let uci = m.to_uci(CastlingMode::Standard);
286
+ if Some(uci.clone()) == tt_move { return -20000; }
287
+ if m.is_capture() {
288
+ let victim = m.capture().map(|r| get_piece_value(r)).unwrap_or(0);
289
+ let attacker = get_piece_value(m.role());
290
+ return -victim + attacker - 10000;
291
+ }
292
+ 0
293
+ });
294
+
295
+ let mut best_val = -2.0;
296
+ let mut best_move = None;
297
+ let old_alpha = alpha;
298
+
299
+ for m in &legals {
300
+ let uci = m.to_uci(CastlingMode::Standard);
301
+ let mut next_board = board.clone();
302
+ next_board.play_unchecked(m);
303
+ history.push(uci.to_string());
304
+
305
+ let score = -alpha_beta(&next_board, depth - 1, -beta, -alpha, history, session, vocab, tt, tablebases, root_cache, root_history_len, stop_flag);
306
+ history.pop();
307
+
308
+ if score > best_val {
309
+ best_val = score;
310
+ best_move = Some(uci.clone());
311
+ }
312
+ if score > alpha { alpha = score; }
313
+ if alpha >= beta { break; }
314
+ }
315
+
316
+ let node_type = if best_val <= old_alpha { TTNodeType::UpperBound }
317
+ else if best_val >= beta { TTNodeType::LowerBound }
318
+ else { TTNodeType::Exact };
319
+
320
+ tt.insert(hash, TTEntry {
321
+ depth,
322
+ score: best_val,
323
+ node_type,
324
+ best_move,
325
+ });
326
+
327
+ best_val
328
+ }
329
+
330
+ fn main() {
331
+ let stdin = io::stdin();
332
+ let mut board = Chess::default();
333
+ let mut history_moves = vec!["<bos>".to_string()];
334
+
335
+ let _ = ort::init().with_name("neural_engine").commit();
336
+
337
+ let num_threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4);
338
+
339
+ let mut tb = Tablebase::<Chess>::new();
340
+ let _ = tb.add_directory("syzygy");
341
+ let tablebases = Arc::new(Some(tb));
342
+
343
+ let polyglot_book = Arc::new(std::sync::Mutex::new(PolyglotBook::new("book.bin").ok()));
344
+ let (vocab, _) = load_vocab();
345
+ let vocab = Arc::new(vocab);
346
+
347
+ let tt = Arc::new(DashMap::new());
348
+ let mut global_root_hash = board.zobrist_hash::<Zobrist64>(shakmaty::EnPassantMode::Legal).0;
349
+
350
+ for line in stdin.lock().lines() {
351
+ let line = line.expect("Failed to read line");
352
+ let tokens: Vec<&str> = line.trim().split_whitespace().collect();
353
+ if tokens.is_empty() { continue; }
354
+
355
+ match tokens[0] {
356
+ "uci" => {
357
+ println!("id name Neurex Pure Value AB");
358
+ println!("id author Neural Engine Architect");
359
+ println!("uciok");
360
+ }
361
+ "isready" => {
362
+ println!("readyok");
363
+ }
364
+ "position" => {
365
+ board = Chess::default();
366
+ history_moves.clear();
367
+ history_moves.push("<bos>".to_string());
368
+ global_root_hash = board.zobrist_hash::<Zobrist64>(shakmaty::EnPassantMode::Legal).0;
369
+
370
+ if tokens.contains(&"moves") {
371
+ let moves_idx = tokens.iter().position(|&r| r == "moves").unwrap();
372
+ for m_str in &tokens[moves_idx + 1..] {
373
+ if let Ok(uci_move) = shakmaty::uci::Uci::from_ascii(m_str.as_bytes()) {
374
+ if let Ok(m) = uci_move.to_move(&board) {
375
+ board.play_unchecked(&m);
376
+ history_moves.push(m_str.to_string());
377
+ global_root_hash = board.zobrist_hash::<Zobrist64>(shakmaty::EnPassantMode::Legal).0;
378
+ }
379
+ }
380
+ }
381
+ }
382
+ }
383
+ "go" => {
384
+ let mut movetime_ms = 5000;
385
+ let mut wtime = 0;
386
+ let mut btime = 0;
387
+ let mut inc = 0;
388
+
389
+ let mut i = 1;
390
+ while i < tokens.len() {
391
+ match tokens[i] {
392
+ "wtime" => { wtime = tokens[i+1].parse().unwrap_or(0); i += 2; }
393
+ "btime" => { btime = tokens[i+1].parse().unwrap_or(0); i += 2; }
394
+ "winc" => { if board.turn() == shakmaty::Color::White { inc = tokens[i+1].parse().unwrap_or(0); } i += 2; }
395
+ "binc" => { if board.turn() == shakmaty::Color::Black { inc = tokens[i+1].parse().unwrap_or(0); } i += 2; }
396
+ "movetime" => { movetime_ms = tokens[i+1].parse().unwrap_or(5000); i += 2; }
397
+ _ => { i += 1; }
398
+ }
399
+ }
400
+
401
+ let mut time_left = 0;
402
+ if wtime > 0 || btime > 0 {
403
+ time_left = if board.turn() == shakmaty::Color::White { wtime } else { btime };
404
+ let estimated_moves_remaining = 30;
405
+ movetime_ms = time_left / estimated_moves_remaining + inc / 2;
406
+ let max_allowable = time_left / 4;
407
+ movetime_ms = movetime_ms.min(max_allowable).max(100);
408
+ }
409
+
410
+ if let Ok(book_opt) = polyglot_book.lock() {
411
+ if let Some(book) = book_opt.as_ref() {
412
+ if let Some(m_str) = book.lookup(global_root_hash) {
413
+ println!("bestmove {}", m_str);
414
+ continue;
415
+ }
416
+ }
417
+ }
418
+
419
+ tt.clear();
420
+ let stop_flag = Arc::new(AtomicBool::new(false));
421
+ let mut handles = Vec::new();
422
+
423
+ let root_history_len = history_moves.len();
424
+ let mut root_cache = None;
425
+ if let Some(mut sess) = if std::path::Path::new("model_int8.onnx").exists() {
426
+ Some(Session::builder().unwrap()
427
+ .with_optimization_level(GraphOptimizationLevel::Level3).unwrap()
428
+ .with_intra_threads(1).unwrap()
429
+ .commit_from_file("model_int8.onnx").unwrap())
430
+ } else { None } {
431
+ root_cache = Some(compute_root_kv_cache(&mut sess, &history_moves, &vocab));
432
+ }
433
+
434
+ for _thread_id in 0..num_threads {
435
+ let t_board = board.clone();
436
+ let mut t_history = history_moves.clone();
437
+ let t_vocab = Arc::clone(&vocab);
438
+ let t_tb = Arc::clone(&tablebases);
439
+ let t_stop_flag = Arc::clone(&stop_flag);
440
+ let t_root_cache = root_cache.clone();
441
+ let t_tt = Arc::clone(&tt);
442
+
443
+ let handle = std::thread::spawn(move || {
444
+ let mut t_session = if Path::new("model_int8.onnx").exists() {
445
+ Some(Session::builder().unwrap()
446
+ .with_optimization_level(GraphOptimizationLevel::Level3).unwrap()
447
+ .with_intra_threads(1).unwrap()
448
+ .commit_from_file("model_int8.onnx").unwrap())
449
+ } else { None };
450
+
451
+ let max_depth = 100;
452
+ for depth in 1..=max_depth {
453
+ if t_stop_flag.load(Ordering::Relaxed) { break; }
454
+
455
+ let alpha = -2.0;
456
+ let beta = 2.0;
457
+
458
+ alpha_beta(
459
+ &t_board,
460
+ depth,
461
+ alpha,
462
+ beta,
463
+ &mut t_history,
464
+ &mut t_session,
465
+ &t_vocab,
466
+ &t_tt,
467
+ &t_tb,
468
+ &t_root_cache,
469
+ root_history_len,
470
+ &t_stop_flag
471
+ );
472
+ }
473
+ });
474
+ handles.push(handle);
475
+ }
476
+
477
+ std::thread::sleep(std::time::Duration::from_millis(movetime_ms as u64));
478
+ stop_flag.store(true, Ordering::Relaxed);
479
+
480
+ for h in handles {
481
+ let _ = h.join();
482
+ }
483
+
484
+ let mut bestmove = String::from("0000");
485
+ if let Some(entry) = tt.get(&global_root_hash) {
486
+ if let Some(m) = &entry.best_move {
487
+ bestmove = m.to_string();
488
+ }
489
+ }
490
+
491
+ if bestmove == "0000" {
492
+ if let Some(m) = board.legal_moves().into_iter().next() {
493
+ bestmove = m.to_uci(CastlingMode::Standard).to_string();
494
+ }
495
+ }
496
+
497
+ println!("bestmove {}", bestmove);
498
+ }
499
+ "quit" => break,
500
+ _ => {}
501
+ }
502
+ }
503
+ }