-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch.cpp
More file actions
2380 lines (2086 loc) · 95.7 KB
/
Copy pathsearch.cpp
File metadata and controls
2380 lines (2086 loc) · 95.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "search.h"
#include "types.h"
#include "movegen.h"
#include "tt.h"
#include "evaluate.h"
#include "tbprobe.h"
#include <iostream>
// Constants for evaluation and search bounds
// Decisive tablebase scores must remain below the mate band so that UCI mate
// conversion, TT score normalization, and mate-distance pruning cannot confuse
// a DTZ result with a forced checkmate.
const int VALUE_TB = 28000;
#include <chrono>
#include <algorithm>
#include <array>
#include <cmath>
#include <cstring>
#include <thread>
#include <vector>
// Constants for evaluation and search bounds
const int MATE_SCORE = 30000;
const int MATE_THRESHOLD = 29000;
// Nodes visited counter
thread_local uint64_t nodes_visited = 0;
thread_local int active_thread_id = 0;
// Maximum ply reached in search (for seldepth reporting)
thread_local int max_ply_reached = 0;
thread_local Move root_excluded_moves[256];
thread_local int root_excluded_count = 0;
thread_local Move root_search_best_move;
thread_local TranspositionTable* thread_tt = &tt;
thread_local bool root_accounting_enabled = false;
thread_local int currmove_report_depth = -1;
thread_local Move reported_currmoves[256];
thread_local int reported_currmove_count = 0;
inline TranspositionTable& search_tt() {
return *thread_tt;
}
struct RootNodeStat {
Move move;
};
RootNodeStat root_node_stats[256];
std::atomic<uint64_t> root_node_counts[MAX_THREADS][256]{};
int root_node_stat_count = 0;
Move root_allowed_moves[256];
int root_allowed_count = 0;
bool root_moves_restricted = false;
inline void record_root_nodes(Move move, uint64_t nodes) {
if (!root_accounting_enabled) return;
for (int i = 0; i < root_node_stat_count; ++i) {
if (root_node_stats[i].move == move) {
root_node_counts[active_thread_id][i].fetch_add(
nodes, std::memory_order_relaxed);
return;
}
}
}
inline uint64_t root_nodes_for_move(Move move) {
for (int i = 0; i < root_node_stat_count; ++i) {
if (root_node_stats[i].move == move)
return root_node_counts[0][i].load(std::memory_order_relaxed);
}
return 0;
}
inline uint64_t root_nodes_total() {
uint64_t total = 0;
for (int move_index = 0; move_index < root_node_stat_count; ++move_index)
for (int thread = 0; thread < Search::num_threads; ++thread)
total += root_node_counts[thread][move_index].load(
std::memory_order_relaxed);
return total;
}
inline double root_node_fraction_multiplier(uint64_t best_nodes,
uint64_t total_nodes) {
if (total_nodes == 0 || best_nodes > total_nodes) return 1.0;
const double fraction = static_cast<double>(best_nodes)
/ static_cast<double>(total_nodes);
if (fraction >= 0.60) return 0.85;
if (fraction <= 0.20) return 1.15;
return 1.0;
}
#ifdef COCO_TESTING
thread_local int nmp_test_attempts = 0;
thread_local int nmp_test_cutoffs = 0;
thread_local int probcut_test_attempts = 0;
thread_local int probcut_test_cutoffs = 0;
thread_local uint64_t probcut_test_nodes = 0;
thread_local int probcut_test_last_score = -INFINITY_SCORE;
#endif
// Time utility in milliseconds
inline uint64_t get_time_ms() {
auto now = std::chrono::steady_clock::now();
return std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
}
// Check time and trigger abort if hard boundary is exceeded
inline void check_time() {
if ((nodes_visited & Search::time_check_mask) != 0)
return;
// Publish progress only at an existing periodic stop check. This keeps
// multi-thread node limits accurate without an atomic increment per node.
Search::thread_stats[active_thread_id].nodes.store(nodes_visited, std::memory_order_relaxed);
Search::thread_stats[active_thread_id].seldepth.store(max_ply_reached, std::memory_order_relaxed);
if (Search::node_limit != 0) {
uint64_t total_nodes = 0;
for (int t = 0; t < Search::num_threads; ++t)
total_nodes += Search::thread_stats[t].nodes.load(std::memory_order_relaxed);
if (total_nodes >= Search::node_limit) {
Search::b_abort.store(true, std::memory_order_relaxed);
return;
}
}
if (!Search::pondering.load(std::memory_order_relaxed) && Search::hard_limit != 0) {
uint64_t elapsed = get_time_ms() - Search::start_time.load(std::memory_order_relaxed);
if (elapsed >= Search::hard_limit) {
Search::b_abort.store(true, std::memory_order_relaxed);
}
}
}
// Move string converter helper
std::string move_to_str(Move m) {
if (m.is_none()) return "0000";
std::string s = square_to_str(m.from()) + square_to_str(m.to());
if (m.is_promotion()) {
int pt = m.promotion_piece_type();
if (pt == KNIGHT) s += "n";
else if (pt == BISHOP) s += "b";
else if (pt == ROOK) s += "r";
else if (pt == QUEEN) s += "q";
}
return s;
}
const int MAX_PLY = 128;
thread_local Move killer_moves[MAX_PLY][2];
thread_local Move explicit_pv[MAX_PLY][MAX_PLY];
thread_local int explicit_pv_length[MAX_PLY];
thread_local Color root_color = WHITE;
thread_local int16_t history_table[2][2][2][7][64]; // [color][threat_from][threat_to][piece_type][to_square] - size 7 to prevent out-of-bounds on NO_PIECE_TYPE
int lmr_table[64][64];
using Search::NodeType;
int get_pv(Board& board, Move* pv_array, int max_pv_depth);
int get_pv_impl(Board& board, Move* pv_array, int max_pv_depth,
bool include_bound_moves);
inline void reset_explicit_pv(int ply) {
if (ply >= 0 && ply < MAX_PLY)
explicit_pv_length[ply] = ply;
}
inline void update_explicit_pv(int ply, Move move) {
if (ply < 0 || ply >= MAX_PLY || move.is_none()) return;
explicit_pv[ply][ply] = move;
int end = ply + 1;
if (ply + 1 < MAX_PLY)
end = std::clamp(explicit_pv_length[ply + 1], ply + 1, MAX_PLY);
for (int index = ply + 1; index < end; ++index)
explicit_pv[ply][index] = explicit_pv[ply + 1][index];
explicit_pv_length[ply] = end;
}
int copy_explicit_pv(Move* output, int max_depth) {
if (!output || max_depth <= 0) return 0;
const int length = std::clamp(explicit_pv_length[0], 0,
std::min(max_depth, MAX_PLY));
for (int index = 0; index < length; ++index)
output[index] = explicit_pv[0][index];
return length;
}
int complete_explicit_pv_from_tt(Board& board, Move* pv, int length,
int max_depth, bool include_bound_moves) {
int replayed = 0;
for (; replayed < length; ++replayed) {
if (!board.make_move(pv[replayed], true)) {
length = replayed;
break;
}
}
if (length < max_depth) {
Move tail[MAX_PLY];
const int tail_length = get_pv_impl(
board, tail, max_depth - length, include_bound_moves);
for (int index = 0; index < tail_length; ++index)
pv[length + index] = tail[index];
length += tail_length;
}
for (int index = replayed - 1; index >= 0; --index)
board.unmake_move(pv[index]);
return length;
}
struct SearchStack {
int piece = -1;
int to_sq = -1;
int static_eval = INFINITY_SCORE;
Move current_move;
#ifdef COCO_CORRHIST_PROFILE
int16_t corr_profile_value[3]{};
#endif
};
thread_local SearchStack search_stack[MAX_PLY + 4];
thread_local int16_t cont_history[2][7][64][7][64];
thread_local int16_t capture_history[12][64][6];
#ifdef COCO_CORRHIST_PROFILE
// Compile-time-only shadow profiler for Phase 3.1. It never changes an
// evaluation or a search decision. The three tables isolate table-size and
// cross-search-lifetime effects while replaying the rejected calibration.
struct CorrHistProfileStats {
uint64_t lookups = 0;
uint64_t occupied_hits = 0;
uint64_t exact_key_hits = 0;
uint64_t collisions = 0;
uint64_t cross_search_hits = 0;
uint64_t updates = 0;
uint64_t informative_predictions = 0;
uint64_t sign_matches = 0;
uint64_t absolute_error_before = 0;
uint64_t absolute_error_after = 0;
uint64_t saturations = 0;
};
struct CorrHistProfileEntry {
int16_t value = 0;
uint16_t key = 0;
uint32_t last_search = 0;
bool occupied = false;
};
template <size_t Size>
struct CorrHistProfileTable {
static_assert((Size & (Size - 1)) == 0);
CorrHistProfileEntry entries[2][Size]{};
CorrHistProfileStats stats{};
void begin_search(bool clear_entries) {
stats = CorrHistProfileStats{};
if (clear_entries)
std::memset(entries, 0, sizeof(entries));
}
int16_t lookup(Color side, uint16_t key, uint32_t search_generation) {
CorrHistProfileEntry& entry = entries[side][key & (Size - 1)];
++stats.lookups;
if (!entry.occupied)
return 0;
++stats.occupied_hits;
if (entry.key == key)
++stats.exact_key_hits;
else
++stats.collisions;
if (entry.last_search != 0 && entry.last_search < search_generation)
++stats.cross_search_hits;
return entry.value;
}
void update(Color side, uint16_t key, uint32_t search_generation,
int16_t prediction, int raw_eval, int result, int depth) {
const int error = result - raw_eval;
const int correction = prediction * 29 / 256;
++stats.updates;
stats.absolute_error_before += std::abs(error);
stats.absolute_error_after += std::abs(error - correction);
if (prediction != 0 && error != 0) {
++stats.informative_predictions;
if ((prediction > 0) == (error > 0))
++stats.sign_matches;
}
const int bonus = std::clamp(error * depth / 8, -256, 256);
CorrHistProfileEntry& entry = entries[side][key & (Size - 1)];
int value = entry.value;
value += bonus - value * std::abs(bonus) / 1024;
entry.value = static_cast<int16_t>(std::clamp(value, -1024, 1024));
entry.key = key;
entry.last_search = search_generation;
entry.occupied = true;
if (std::abs(entry.value) >= 1000)
++stats.saturations;
}
};
// The UCI layer creates fresh OS search threads for every `go`. Keeping the
// persistent shadow outside thread-local storage is therefore essential to
// measure actual between-move lifetime. Only worker 0 touches these objects.
CorrHistProfileTable<16384> corr_profile_old_reset;
CorrHistProfileTable<4096> corr_profile_small_reset;
CorrHistProfileTable<4096> corr_profile_small_persistent;
uint32_t corr_profile_search_generation = 0;
inline void corrhist_profile_begin_search() {
++corr_profile_search_generation;
corr_profile_old_reset.begin_search(true);
corr_profile_small_reset.begin_search(true);
corr_profile_small_persistent.begin_search(false);
}
inline void corrhist_profile_lookup(const Board& board, SearchStack& stack) {
if (active_thread_id != 0)
return;
const Color side = board.get_side_to_move();
const uint16_t key = board.get_pawn_key();
stack.corr_profile_value[0] = corr_profile_old_reset.lookup(
side, key, corr_profile_search_generation);
stack.corr_profile_value[1] = corr_profile_small_reset.lookup(
side, key, corr_profile_search_generation);
stack.corr_profile_value[2] = corr_profile_small_persistent.lookup(
side, key, corr_profile_search_generation);
}
inline void corrhist_profile_update(const Board& board, const SearchStack& stack,
int raw_eval, int result, int depth,
bool in_check, Move best_move,
uint8_t bound, Move excluded_move) {
if (active_thread_id != 0 || in_check || !excluded_move.is_none()
|| best_move.is_none()
|| best_move.is_capture() || best_move.is_promotion()
|| std::abs(result) >= MATE_THRESHOLD)
return;
if ((bound == HASH_BETA && result <= raw_eval)
|| (bound == HASH_ALPHA && result >= raw_eval))
return;
const Color side = board.get_side_to_move();
const uint16_t key = board.get_pawn_key();
corr_profile_old_reset.update(side, key, corr_profile_search_generation,
stack.corr_profile_value[0], raw_eval,
result, depth);
corr_profile_small_reset.update(side, key, corr_profile_search_generation,
stack.corr_profile_value[1], raw_eval,
result, depth);
corr_profile_small_persistent.update(
side, key, corr_profile_search_generation,
stack.corr_profile_value[2], raw_eval, result, depth);
}
template <size_t Size>
void print_corrhist_profile_table(const char* name,
const CorrHistProfileTable<Size>& table) {
const CorrHistProfileStats& stats = table.stats;
std::cout << "info string corrhist_profile " << name
<< " lookups=" << stats.lookups
<< " occupied=" << stats.occupied_hits
<< " exact=" << stats.exact_key_hits
<< " collisions=" << stats.collisions
<< " cross_search=" << stats.cross_search_hits
<< " updates=" << stats.updates
<< " informative=" << stats.informative_predictions
<< " sign_matches=" << stats.sign_matches
<< " abs_before=" << stats.absolute_error_before
<< " abs_after=" << stats.absolute_error_after
<< " saturations=" << stats.saturations << "\n";
}
inline void corrhist_profile_print() {
print_corrhist_profile_table("old_reset_16384", corr_profile_old_reset);
print_corrhist_profile_table("small_reset_4096", corr_profile_small_reset);
print_corrhist_profile_table("small_persistent_4096",
corr_profile_small_persistent);
}
#endif
inline bool root_move_is_excluded(Move move) {
for (int i = 0; i < root_excluded_count; ++i) {
if (root_excluded_moves[i] == move) return true;
}
return false;
}
inline bool root_move_is_allowed(Move move) {
if (!root_moves_restricted) return true;
for (int i = 0; i < root_allowed_count; ++i)
if (root_allowed_moves[i] == move) return true;
return false;
}
inline bool mate_within_limit(int score) {
if (Search::mate_limit <= 0 || std::abs(score) <= MATE_THRESHOLD) return false;
const int plies = MATE_SCORE - std::abs(score);
return plies <= Search::mate_limit * 2;
}
struct WdlPermille { int win; int draw; int loss; };
inline WdlPermille score_to_wdl(int score) {
if (score > MATE_THRESHOLD) return {1000, 0, 0};
if (score < -MATE_THRESHOLD) return {0, 0, 1000};
const double bounded = std::clamp(static_cast<double>(score), -2000.0, 2000.0);
const auto logistic = [](double value) { return 1.0 / (1.0 + std::exp(-value)); };
int win = static_cast<int>(std::lround(1000.0 * logistic((bounded - 100.0) / 180.0)));
int loss = static_cast<int>(std::lround(1000.0 * logistic((-bounded - 100.0) / 180.0)));
if (win + loss > 1000) {
const double scale = 1000.0 / static_cast<double>(win + loss);
win = static_cast<int>(std::lround(win * scale));
loss = 1000 - win;
}
return {win, 1000 - win - loss, loss};
}
inline void print_uci_score(int score) {
if (score > MATE_THRESHOLD) {
const int plies = MATE_SCORE - score;
std::cout << "score mate " << ((plies + 1) / 2);
} else if (score < -MATE_THRESHOLD) {
const int plies = score + MATE_SCORE;
std::cout << "score mate -" << ((plies + 1) / 2);
} else {
std::cout << "score cp " << score;
}
if (Search::UCI_ShowWDL) {
const WdlPermille wdl = score_to_wdl(score);
std::cout << " wdl " << wdl.win << " " << wdl.draw << " " << wdl.loss;
}
}
inline uint64_t aggregate_tbhits() {
uint64_t total = 0;
for (int thread = 0; thread < Search::num_threads; ++thread)
total += Search::thread_stats[thread].tbhits.load(std::memory_order_relaxed);
return total;
}
inline void widen_aspiration_window(int score, int& alpha, int& beta,
int& delta, bool fail_low,
bool record = true) {
if (fail_low) {
beta = (alpha + beta) / 2;
alpha = std::max(score - delta, -INFINITY_SCORE);
if (record)
Search::thread_stats[active_thread_id].aspiration_fail_lows
.fetch_add(1, std::memory_order_relaxed);
} else {
beta = std::min(score + delta, INFINITY_SCORE);
if (record)
Search::thread_stats[active_thread_id].aspiration_fail_highs
.fetch_add(1, std::memory_order_relaxed);
}
delta += delta / 2;
}
inline void update_history(int16_t& entry, int bonus) {
int val = entry;
val += bonus - val * std::abs(bonus) / 32768;
entry = static_cast<int16_t>(std::clamp(val, -30000, 30000));
}
inline int draw_score(const Board& board) {
return board.get_side_to_move() == root_color ? -Search::Contempt : Search::Contempt;
}
// Map Fathom move representation to Coco's Move class
Move fathom_to_coco_move(const Board& board, unsigned fathom_res) {
int from = TB_GET_FROM(fathom_res);
int to = TB_GET_TO(fathom_res);
int promotes = TB_GET_PROMOTES(fathom_res);
bool ep = TB_GET_EP(fathom_res);
bool is_cap = (board.get_piece_at(to) != NO_PIECE) || ep;
int flags = FLAG_QUIET;
if (ep) {
flags = FLAG_EP;
} else if (promotes != TB_PROMOTES_NONE) {
int pt = KNIGHT;
if (promotes == TB_PROMOTES_QUEEN) pt = QUEEN;
else if (promotes == TB_PROMOTES_ROOK) pt = ROOK;
else if (promotes == TB_PROMOTES_BISHOP) pt = BISHOP;
flags = (pt - 1) + 8;
if (is_cap) {
flags += 4;
}
} else if (is_cap) {
flags = FLAG_CAPTURE;
} else {
Piece p = board.get_piece_at(from);
if ((p == W_PAWN || p == B_PAWN) && std::abs(from - to) == 16) {
flags = FLAG_DOUBLE_PAWN;
}
}
return Move(from, to, flags);
}
// Convert Coco board to Fathom bitboards and call tb_probe_wdl
unsigned probe_wdl(const Board& board) {
U64 white = board.get_occupancy(WHITE);
U64 black = board.get_occupancy(BLACK);
U64 kings = board.get_pieces(WHITE, KING) | board.get_pieces(BLACK, KING);
U64 queens = board.get_pieces(WHITE, QUEEN) | board.get_pieces(BLACK, QUEEN);
U64 rooks = board.get_pieces(WHITE, ROOK) | board.get_pieces(BLACK, ROOK);
U64 bishops = board.get_pieces(WHITE, BISHOP) | board.get_pieces(BLACK, BISHOP);
U64 knights = board.get_pieces(WHITE, KNIGHT) | board.get_pieces(BLACK, KNIGHT);
U64 pawns = board.get_pieces(WHITE, PAWN) | board.get_pieces(BLACK, PAWN);
unsigned ep = board.get_en_passant_square();
if (ep == SQ_NONE) ep = 0;
bool turn = (board.get_side_to_move() == WHITE);
unsigned castling = board.get_castling_rights();
unsigned rule50 = Search::Syzygy50MoveRule ? board.get_halfmove_clock() : 0;
return tb_probe_wdl(white, black, kings, queens, rooks, bishops, knights, pawns, rule50, castling, ep, turn);
}
// Helper to retrieve the combined quiet history score for a move
inline int get_quiet_history_score(const Board& board, Move move, int ply, U64 threats) {
Color side = board.get_side_to_move();
Piece piece_raw = board.get_piece_at(move.from());
PieceType piece = (PieceType)(piece_raw % 6);
int to = move.to();
bool tf = threats & (1ULL << move.from());
bool tt = threats & (1ULL << move.to());
int score = 0;
if (piece < 7) {
score += history_table[side][tf][tt][piece][to];
if (ply >= 1 && ply - 1 < MAX_PLY) {
const SearchStack& ni1 = search_stack[ply - 1];
if (ni1.piece >= 0 && ni1.piece < 7) {
score += cont_history[0][ni1.piece][ni1.to_sq][piece][to];
}
}
if (ply >= 2 && ply - 2 < MAX_PLY) {
const SearchStack& ni2 = search_stack[ply - 2];
if (ni2.piece >= 0 && ni2.piece < 7) {
score += cont_history[1][ni2.piece][ni2.to_sq][piece][to];
}
}
}
return score;
}
// Move Ordering helper function using stack memory
void order_moves(const Board& board, const MoveList& move_list, Move tt_move, int ply, int* scores, U64 threats = 0) {
const int mvv_lva_values[6] = { 100, 320, 330, 500, 900, 20000 };
Color side = board.get_side_to_move();
for (int i = 0; i < move_list.count; i++) {
Move move = move_list.moves[i];
if (move == tt_move) {
scores[i] = 10000000;
} else if (move.is_capture()) {
int victim = PAWN;
if (!move.is_en_passant()) {
victim = board.get_piece_at(move.to()) % 6;
}
int assailant = board.get_piece_at(move.from()) % 6;
int promotion_gain = 0;
if (move.is_promotion()) {
promotion_gain = mvv_lva_values[move.promotion_piece_type()]
- mvv_lva_values[PAWN];
}
int capture_value = (mvv_lva_values[victim] + promotion_gain) * 10 - assailant;
int moved_piece = board.get_piece_at(move.from());
int cap_hist = 0;
if (moved_piece < 12 && victim < 6) {
cap_hist = capture_history[moved_piece][move.to()][victim];
}
if (mvv_lva_values[victim] >= mvv_lva_values[assailant]) {
scores[i] = 1000000 + capture_value + cap_hist;
} else {
scores[i] = 10000 + capture_value + cap_hist;
}
} else if (move.is_promotion()) {
int promo = move.promotion_piece_type();
scores[i] = 950000 + mvv_lva_values[promo];
} else {
// Quiet move
if (ply < MAX_PLY && move == killer_moves[ply][0]) {
scores[i] = 900000;
} else if (ply < MAX_PLY && move == killer_moves[ply][1]) {
scores[i] = 800000;
} else {
scores[i] = get_quiet_history_score(board, move, ply, threats);
}
}
}
}
// Stateful ordering boundary. The baseline picker deliberately reproduces
// the former incremental selection-sort order exactly; later stage changes
// can therefore be measured without also changing the caller's control flow.
class MovePicker {
public:
MovePicker(const Board& board, MoveList& moves, Move tt_move, int ply, U64 threats = 0)
: moves_(moves) {
order_moves(board, moves_, tt_move, ply, scores_, threats);
}
bool next(Move& move) {
if (index_ >= moves_.count)
return false;
int best = index_;
for (int i = index_ + 1; i < moves_.count; ++i) {
if (scores_[i] > scores_[best])
best = i;
}
if (best != index_) {
std::swap(moves_.moves[index_], moves_.moves[best]);
std::swap(scores_[index_], scores_[best]);
}
move = moves_.moves[index_++];
return true;
}
private:
MoveList& moves_;
int scores_[256]{};
int index_ = 0;
};
// Forward declarations of search functions
int quiescence(Board& board, int alpha, int beta, int ply);
// Extract Principal Variation (PV) from the Transposition Table
int get_pv_impl(Board& board, Move* pv_array, int max_pv_depth,
bool include_bound_moves) {
int pv_length = 0;
U64 key = board.get_hash_key();
int score;
uint8_t depth;
uint8_t flag;
Move best_move;
while (pv_length < max_pv_depth) {
const bool found_entry = include_bound_moves
? search_tt().probe_entry(key, score, depth, flag, best_move, 0)
: search_tt().probe(key, score, best_move, 0,
-INFINITY_SCORE, INFINITY_SCORE, 0);
if (!found_entry || best_move.is_none()) {
break;
}
// Validate best move legally against the board state
MoveList list;
generate_pseudo_legal_moves(board, list);
bool found = false;
for (int i = 0; i < list.count; i++) {
if (list.moves[i] == best_move) {
found = true;
break;
}
}
if (!found) break;
pv_array[pv_length++] = best_move;
if (!board.make_move(best_move)) {
pv_length--;
break;
}
// A PV ends when the game ends. TT entries can otherwise form a
// legal repetition cycle and make GUIs/fastchess report a bogus
// continuation after the draw has already been reached.
if (board.get_halfmove_clock() >= 100 || board.is_repetition()) {
break;
}
key = board.get_hash_key();
}
// Restore the board back to the original root state
for (int i = pv_length - 1; i >= 0; i--) {
board.unmake_move(pv_array[i]);
}
return pv_length;
}
int get_pv(Board& board, Move* pv_array, int max_pv_depth) {
return get_pv_impl(board, pv_array, max_pv_depth, false);
}
// Alpha-Beta Search Core with Null Move Pruning (NMP)
int alpha_beta(Board& board, int alpha, int beta, int depth, int ply, NodeType node_type, bool in_null_move_search, int parent_eval_1, int parent_eval_2, Move excluded_move, int double_ext) {
const bool is_pv = node_type == NodeType::PV;
reset_explicit_pv(ply);
// Cooperative search abortion check
check_time();
if (Search::b_abort.load(std::memory_order_relaxed)) return 0;
// Draw detection (Fifty-move rule and repetition check)
if (ply > 0 && (board.get_halfmove_clock() >= 100 || board.is_repetition())) {
return draw_score(board);
}
if (depth <= 0) {
return quiescence(board, alpha, beta, ply);
}
nodes_visited++;
if (ply > max_ply_reached) {
max_ply_reached = ply;
}
// Syzygy WDL Probing at non-root nodes
int num_pieces = count_bits(board.get_occupancy(BOTH));
if (TB_LARGEST > 0
&& num_pieces <= (int)TB_LARGEST
&& ply > 0
&& board.get_castling_rights() == 0
&& (!Search::Syzygy50MoveRule || board.get_halfmove_clock() == 0)
&& excluded_move.is_none()
&& (num_pieces < (int)TB_LARGEST || !Search::SyzygyProbeLimit || depth >= Search::SyzygyProbeDepth))
{
unsigned wdl = probe_wdl(board);
if (wdl != TB_RESULT_FAILED) {
Search::thread_stats[active_thread_id].tbhits.fetch_add(1, std::memory_order_relaxed);
int tb_score = 0;
if (wdl == TB_WIN) {
tb_score = VALUE_TB - ply;
} else if (wdl == TB_CURSED_WIN) {
tb_score = 1;
} else if (wdl == TB_DRAW) {
tb_score = 0;
} else if (wdl == TB_BLESSED_LOSS) {
tb_score = -1;
} else if (wdl == TB_LOSS) {
tb_score = -VALUE_TB + ply;
}
uint8_t flag = HASH_EXACT;
if (tb_score >= beta) {
flag = HASH_BETA;
} else if (tb_score <= alpha) {
flag = HASH_ALPHA;
}
if (excluded_move.is_none()) {
search_tt().store(board.get_hash_key(), Move(), tb_score, depth, flag, ply);
}
return tb_score;
}
}
Color us = board.get_side_to_move();
Move quiet_moves_searched[64];
int quiet_count = 0;
Move capture_moves_searched[64];
int capture_count = 0;
int king_sq = get_lsb(board.get_pieces(us, KING));
bool in_check = board.is_square_attacked(king_sq, us ^ 1);
// NMP and the later forward-pruning stages share one static evaluation.
const int raw_static_eval = Evaluation::evaluate(board);
int static_eval = raw_static_eval;
if (ply < MAX_PLY + 4) search_stack[ply].static_eval = static_eval;
#ifdef COCO_CORRHIST_PROFILE
if (ply < MAX_PLY + 4)
corrhist_profile_lookup(board, search_stack[ply]);
#endif
// Compute improving before any evaluation-based pruning. Checks inherit
// the last usable evaluations rather than treating a missing value as an
// improvement signal.
bool improving = false;
if (!in_check && parent_eval_2 != INFINITY_SCORE) {
improving = static_eval > parent_eval_2;
}
int next_parent_eval_1 = in_check ? parent_eval_1 : static_eval;
int next_parent_eval_2 = in_check ? parent_eval_2 : parent_eval_1;
// Null Move Pruning (NMP)
if (Search::mate_limit == 0 && depth >= 3 && !is_pv && !in_check && !in_null_move_search
&& excluded_move.is_none() && static_eval >= beta
&& std::abs(beta) < MATE_SCORE - MAX_PLY) {
const int minor_count = count_bits(board.get_pieces(us, KNIGHT)
| board.get_pieces(us, BISHOP));
const bool has_heavy = board.get_pieces(us, ROOK) || board.get_pieces(us, QUEEN);
// Pawn-only and lone-minor endings are the classic zugzwang danger
// zone. Requiring a heavy piece or two minors is deliberately more
// conservative than the old any-non-pawn test.
if (has_heavy || minor_count >= 2) {
const int eval_bonus = std::clamp((static_eval - beta) / 200, 0, 3);
int R = Search::NMP_Base + (depth / Search::NMP_Divisor) + eval_bonus;
R = std::clamp(R, 2, depth - 1);
if (ply < MAX_PLY) {
search_stack[ply].piece = -1;
search_stack[ply].to_sq = -1;
search_stack[ply].current_move = Move();
}
if (board.make_null_move()) {
#ifdef COCO_TESTING
if (ply == 0) ++nmp_test_attempts;
#endif
int null_score = -alpha_beta(board, -beta, -beta + 1, depth - 1 - R, ply + 1, NodeType::NON_PV, true, parent_eval_1, parent_eval_2, excluded_move, double_ext);
board.unmake_null_move();
if (null_score >= beta) {
#ifdef COCO_TESTING
if (ply == 0) ++nmp_test_cutoffs;
#endif
return beta;
}
}
}
}
// Probe the Transposition Table
int tt_score = 0;
uint8_t tt_depth = 0;
uint8_t tt_flag = 0;
Move tt_move;
bool tt_hit = search_tt().probe_entry(board.get_hash_key(), tt_score, tt_depth, tt_flag, tt_move, ply);
const bool restricted_root = ply == 0
&& (root_excluded_count > 0 || root_moves_restricted);
if (tt_hit && tt_move != excluded_move && !restricted_root) {
if (tt_depth >= depth) {
if (tt_flag == HASH_EXACT) {
if (ply == 0) root_search_best_move = tt_move;
return tt_score;
}
if (tt_flag == HASH_ALPHA && tt_score <= alpha) {
if (ply == 0) root_search_best_move = tt_move;
return tt_score;
}
if (tt_flag == HASH_BETA && tt_score >= beta) {
if (ply == 0) root_search_best_move = tt_move;
return tt_score;
}
}
}
if (tt_move == excluded_move
|| (ply == 0 && (!root_move_is_allowed(tt_move) || root_move_is_excluded(tt_move)))) {
tt_move = Move();
}
// Internal Iterative Reductions (IIR)
if (Search::mate_limit == 0 && is_pv && depth >= 3 && tt_move.is_none()) {
depth--;
}
// Reverse Futility Pruning (RFP) keeps its accepted post-IIR depth
// semantics while the strict-order alternative is evaluated separately.
if (Search::mate_limit == 0 && depth <= 3 && !is_pv && !in_check && excluded_move.is_none()
&& std::abs(beta) < MATE_SCORE - MAX_PLY) {
int margin = Search::RFP_Margin * depth - (improving ? 35 : 0);
if (static_eval - margin >= beta) {
return static_eval;
}
}
// Razoring follows RFP with the post-IIR depth, preserving the calibrated
// T4 selectivity boundary established by the accepted baseline.
if (Search::mate_limit == 0 && depth == 1 && !is_pv && !in_check && excluded_move.is_none()
&& alpha > -INFINITY_SCORE + 1000) {
constexpr int razor_margin = 300;
if (static_eval + razor_margin <= alpha) {
int q_score = quiescence(board, alpha, beta, ply);
if (q_score <= alpha) {
return q_score;
}
}
}
// Capture-only ProbCut. A clearly winning tactical capture is verified
// first by qsearch and then by a reduced null-window search. Keeping this
// independent of capture-history thresholds gives the next candidate a
// clean baseline, while the SEE gate avoids spending work on losing
// exchanges. PV, check, excluded-move, and decisive-score nodes are kept
// out of this speculative cutoff path.
if (Search::mate_limit == 0 && depth >= 5 && !is_pv && !in_check
&& excluded_move.is_none() && std::abs(beta) < MATE_SCORE - MAX_PLY) {
constexpr int PROBCUT_MARGIN = 200;
constexpr int PROBCUT_REDUCTION = 4;
const int probcut_beta = std::min(beta + PROBCUT_MARGIN,
MATE_SCORE - MAX_PLY - 1);
const int see_threshold = std::max(0, probcut_beta - static_eval);
MoveList probcut_moves;
generate_capture_moves(board, probcut_moves);
MovePicker probcut_picker(board, probcut_moves, tt_move, ply);
LegalityMasks probcut_masks = board.get_legality_masks();
Move probcut_move;
while (probcut_picker.next(probcut_move)) {
if (probcut_move == excluded_move || board.see(probcut_move) < see_threshold
|| !board.is_move_legal(probcut_move, probcut_masks)) {
continue;
}
#ifdef COCO_TESTING
if (ply == 0) ++probcut_test_attempts;
const uint64_t probcut_nodes_before = nodes_visited;
#endif
if (ply < MAX_PLY) {
search_stack[ply].piece = -1;
search_stack[ply].to_sq = -1;
search_stack[ply].current_move = probcut_move;
}
board.make_move(probcut_move, true);
search_tt().prefetch(board.get_hash_key());
int probcut_score = -quiescence(board, -probcut_beta,
-probcut_beta + 1, ply + 1);
if (probcut_score >= probcut_beta) {
probcut_score = -alpha_beta(
board, -probcut_beta, -probcut_beta + 1,
depth - PROBCUT_REDUCTION, ply + 1, NodeType::NON_PV,
in_null_move_search, next_parent_eval_1, next_parent_eval_2,
Move(), double_ext);
}
board.unmake_move(probcut_move);
#ifdef COCO_TESTING
if (ply == 0) {
probcut_test_nodes += nodes_visited - probcut_nodes_before;
probcut_test_last_score = probcut_score;
}
#endif
if (Search::b_abort.load(std::memory_order_relaxed)) return 0;
if (probcut_score >= probcut_beta) {
#ifdef COCO_TESTING
if (ply == 0) ++probcut_test_cutoffs;
#endif
search_tt().store(board.get_hash_key(), probcut_move,
probcut_score, depth - PROBCUT_REDUCTION + 1,
HASH_BETA, ply);
return probcut_score;
}
}
}
// Internal Iterative Deepening (IID)
if (tt_move.is_none() && depth >= 4 && !in_check && is_pv) {
int iid_depth = depth - 2;
alpha_beta(board, alpha, beta, iid_depth, ply, node_type, in_null_move_search, parent_eval_1, parent_eval_2, excluded_move, double_ext);
// Time-abort check: immediately return 0 and skip probing the TT to prevent move pollution
if (Search::b_abort.load(std::memory_order_relaxed)) return 0;
int dummy_score;
search_tt().probe(board.get_hash_key(), dummy_score, tt_move, 0, -INFINITY_SCORE, INFINITY_SCORE, ply);
}
int alpha_orig = alpha;
LegalityMasks masks = board.get_legality_masks();
MoveList move_list;
if (in_check)
generate_evasion_moves(board, move_list);
else
generate_pseudo_legal_moves(board, move_list);
MovePicker move_picker(board, move_list, tt_move, ply, masks.threats);
int legal_moves_count = 0;
int best_score = -INFINITY_SCORE;
Move best_move_in_node;
int moves_searched = 0;
Move move;
while (move_picker.next(move)) {
if (move == excluded_move) {
continue;
}
if (ply == 0 && (!root_move_is_allowed(move) || root_move_is_excluded(move))) {
continue;
}
// Late Move Pruning (LMP)
if (Search::mate_limit == 0 && !move.is_capture() && !move.is_promotion()) {
if (depth <= 3 && !is_pv && !in_check) {
bool from_threatened = masks.threats & (1ULL << move.from());
if (!from_threatened) { // Only prune non-escaping moves
int move_threshold = 4 + (depth * depth);
if (moves_searched >= move_threshold) {