-
Notifications
You must be signed in to change notification settings - Fork 687
Expand file tree
/
Copy pathgenbook.cpp
More file actions
2585 lines (2275 loc) · 104 KB
/
genbook.cpp
File metadata and controls
2585 lines (2275 loc) · 104 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 "../core/global.h"
#include "../core/makedir.h"
#include "../core/config_parser.h"
#include "../core/fileutils.h"
#include "../core/timer.h"
#include "../core/threadsafequeue.h"
#include "../core/parallel.h"
#include "../dataio/poswriter.h"
#include "../dataio/sgf.h"
#include "../dataio/files.h"
#include "../book/book.h"
#include "../search/searchnode.h"
#include "../search/asyncbot.h"
#include "../program/setup.h"
#include "../program/playutils.h"
#include "../program/play.h"
#include "../command/commandline.h"
#include "../core/test.h"
#include "../main.h"
#include "../external/nlohmann_json/json.hpp"
#include <chrono>
#include <csignal>
//------------------------
#include "../core/using.h"
//------------------------
static std::atomic<bool> sigReceived(false);
static std::atomic<bool> shouldStop(false);
static void signalHandler(int signal)
{
if(signal == SIGINT || signal == SIGTERM) {
sigReceived.store(true);
shouldStop.store(true);
}
}
static double getMaxPolicy(float policyProbs[NNPos::MAX_NN_POLICY_SIZE]) {
double maxPolicy = 0.0;
for(int i = 0; i<NNPos::MAX_NN_POLICY_SIZE; i++)
if(policyProbs[i] > maxPolicy)
maxPolicy = policyProbs[i];
return maxPolicy;
}
static void optimizeSymmetriesInplace(std::vector<SymBookNode>& nodes, Rand* rand, Logger& logger) {
std::vector<std::unique_ptr<Board>> boards;
{
BoardHistory histBuf;
std::vector<Loc> moveHistoryBuf;
for(SymBookNode& node: nodes) {
if(node.getBoardHistoryReachingHere(histBuf,moveHistoryBuf)) {
boards.push_back(std::make_unique<Board>(histBuf.getRecentBoard(0)));
}
else {
logger.write("WARNING: Failed to get board history reaching node, probably there is some bug");
logger.write("BookHash of node optimizing symmetries: " + node.hash().toString());
throw StringError("Terminating");
}
}
}
assert(nodes.size() < 0x7FFFFFFFU);
std::vector<uint32_t> perm(nodes.size());
if(rand != nullptr)
rand->fillShuffledUIntRange(perm.size(), perm.data());
else {
for(size_t i = 0; i<perm.size(); i++)
perm[i] = (uint32_t)i;
}
double diffBuf[SymmetryHelpers::NUM_SYMMETRIES];
double similaritySumBuf[SymmetryHelpers::NUM_SYMMETRIES];
const double maxDifferenceToReport = 12;
// Iterate through all nodes in random order and for each one find its best symmetry
std::vector<int> bestSymmetries(nodes.size());
for(size_t i = 0; i<perm.size(); i++) {
const Board& nodeBoard = *(boards[perm[i]]);
std::fill(similaritySumBuf, similaritySumBuf+SymmetryHelpers::NUM_SYMMETRIES, 0.0);
// Iterate over all previously symmetrized nodes, up to at most 100, and accumulate similarity
for(size_t j = 0; j<i && j < 100; j++) {
const Board& otherBoard = *(boards[perm[j]]);
int otherBoardBestSymmetry = bestSymmetries[perm[j]];
SymmetryHelpers::getSymmetryDifferences(nodeBoard, otherBoard, maxDifferenceToReport, diffBuf);
for(int symmetry = 0; symmetry < SymmetryHelpers::NUM_SYMMETRIES; symmetry++) {
// diffBuff[symmetry] has the similarity between nodeBoard * symmetry and otherBoard.
// Which is the same as the similarity between nodeboard * compose(symmetry,otherBoardBestSymmetry) and otherBoard * otherBoardBestSymmetry.
// The latter is what we want, since that's what otherBoard will actually end up as after this whole function is done.
// For similarity, use quadratic harmonic
similaritySumBuf[SymmetryHelpers::compose(symmetry, otherBoardBestSymmetry)] += 1.0 / ((0.01 + diffBuf[symmetry]) * (0.01 + diffBuf[symmetry]));
}
}
double bestSimilarity = similaritySumBuf[0];
int bestSymmetry = 0;
for(int symmetry = 1; symmetry < SymmetryHelpers::NUM_SYMMETRIES; symmetry++) {
if(similaritySumBuf[symmetry] > bestSimilarity) {
bestSimilarity = similaritySumBuf[symmetry];
bestSymmetry = symmetry;
}
}
bestSymmetries[perm[i]] = bestSymmetry;
}
for(size_t i = 0; i<nodes.size(); i++) {
nodes[i] = nodes[i].applySymmetry(bestSymmetries[i]);
}
}
static void maybeParseHashBonusFile(
const std::string& hashBonusFile,
double bonusFileScale,
Logger& logger,
std::map<BookHash,double>& bonusByHash,
std::map<BookHash,double>& expandBonusByHash,
std::map<BookHash,double>& visitsRequiredByHash,
std::map<BookHash,int>& branchRequiredByHash
) {
if(hashBonusFile == "")
return;
std::vector<std::string> lines = FileUtils::readFileLines(hashBonusFile, '\n');
for(const std::string& line: lines) {
std::vector<std::string> pieces = Global::split(Global::trim(line));
if(pieces.size() > 2 && (
pieces[1] == "BONUS" ||
pieces[1] == "EXPAND" ||
pieces[1] == "VISITS" ||
pieces[1] == "BRANCH"
)
) {
double ret = Global::stringToDouble(pieces[2]);
BookHash hashRet = BookHash::ofString(pieces[0]);
if(pieces[1] == "BONUS") {
if(!std::isfinite(ret) || ret < -10000 || ret > 10000)
throw StringError("Invalid BONUS: " + Global::doubleToString(ret));
if(bonusByHash.find(hashRet) != bonusByHash.end())
bonusByHash[hashRet] = std::max(bonusByHash[hashRet], ret * bonusFileScale);
else
bonusByHash[hashRet] = ret * bonusFileScale;
bonusByHash[hashRet] = std::max(bonusByHash[hashRet], ret * bonusFileScale);
logger.write("Adding bonus " + Global::doubleToString(ret * bonusFileScale) + " to hash " + hashRet.toString());
}
else if(pieces[1] == "EXPAND") {
if(!std::isfinite(ret) || ret < 0 || ret > 10000)
throw StringError("Invalid EXPAND: " + Global::doubleToString(ret));
if(expandBonusByHash.find(hashRet) != expandBonusByHash.end())
expandBonusByHash[hashRet] = std::max(expandBonusByHash[hashRet], ret * bonusFileScale);
else
expandBonusByHash[hashRet] = ret * bonusFileScale;
logger.write("Adding expand bonus " + Global::doubleToString(ret * bonusFileScale) + " to hash " + hashRet.toString());
}
else if(pieces[1] == "VISITS") {
if(!std::isfinite(ret) || ret < 0)
throw StringError("Invalid VISITS: " + Global::doubleToString(ret));
if(visitsRequiredByHash.find(hashRet) != visitsRequiredByHash.end())
visitsRequiredByHash[hashRet] = std::max(visitsRequiredByHash[hashRet], ret * bonusFileScale);
else
visitsRequiredByHash[hashRet] = ret * bonusFileScale;
logger.write("Adding required visits " + Global::doubleToString(ret * bonusFileScale) + " to hash " + hashRet.toString());
}
else if(pieces[1] == "BRANCH") {
if(!std::isfinite(ret) || ret < 0 || ret > 200)
throw StringError("Invalid BRANCH: " + Global::doubleToString(ret));
if(branchRequiredByHash.find(hashRet) != branchRequiredByHash.end())
branchRequiredByHash[hashRet] = std::max(branchRequiredByHash[hashRet], (int)ret);
else
branchRequiredByHash[hashRet] = (int)ret;
logger.write("Adding required branching factor " + Global::intToString((int)ret) + " to hash " + hashRet.toString());
}
}
}
}
static void maybeParseBonusFile(
const std::string& bonusFile,
int boardSizeX,
int boardSizeY,
Rules rules,
int repBound,
double bonusFileScale,
Logger& logger,
std::map<BookHash,double>& bonusByHash,
std::map<BookHash,double>& expandBonusByHash,
std::map<BookHash,double>& visitsRequiredByHash,
std::map<BookHash,int>& branchRequiredByHash,
Board& bonusInitialBoard,
Player& bonusInitialPla
) {
if(bonusFile != "") {
std::unique_ptr<Sgf> sgf = Sgf::loadFile(bonusFile);
bool flipIfPassOrWFirst = false;
bool allowGameOver = false;
Rand seedRand("bonusByHash");
sgf->iterAllPositions(
flipIfPassOrWFirst, allowGameOver, &seedRand, [&](Sgf::PositionSample& unusedSample, const BoardHistory& sgfHist, const string& comments) {
(void)unusedSample;
if(comments.size() > 0 && (
comments.find("BONUS") != string::npos ||
comments.find("EXPAND") != string::npos ||
comments.find("VISITS") != string::npos ||
comments.find("BRANCH") != string::npos
)
) {
BoardHistory hist(sgfHist.initialBoard, sgfHist.initialPla, rules, sgfHist.initialEncorePhase);
Board board = hist.initialBoard;
for(size_t i = 0; i<sgfHist.moveHistory.size(); i++) {
bool suc = hist.makeBoardMoveTolerant(board, sgfHist.moveHistory[i].loc, sgfHist.moveHistory[i].pla);
if(!suc)
return;
}
auto parseCommand = [&comments,&board](const char* commandName, double& ret) {
if(comments.find(commandName) != string::npos) {
double bonus;
try {
vector<string> nextWords = Global::split(Global::trim(comments.substr(comments.find(commandName)+std::strlen(commandName))));
if(nextWords.size() <= 0)
throw StringError("Could not parse " + string(commandName) + " value");
bonus = Global::stringToDouble(nextWords[0]);
}
catch(const StringError& e) {
cerr << board << endl;
throw e;
}
ret = bonus;
return true;
}
return false;
};
double ret = 0.0;
BookHash hashRet;
int symmetryToAlignRet;
vector<int> symmetriesRet;
if(parseCommand("BONUS",ret)) {
if(!std::isfinite(ret) || ret < -10000 || ret > 10000)
throw StringError("Invalid BONUS: " + Global::doubleToString(ret));
for(int bookVersion = 1; bookVersion <= Book::LATEST_BOOK_VERSION; bookVersion++) {
BookHash::getHashAndSymmetry(hist, repBound, hashRet, symmetryToAlignRet, symmetriesRet, bookVersion);
if(bonusByHash.find(hashRet) != bonusByHash.end())
bonusByHash[hashRet] = std::max(bonusByHash[hashRet], ret * bonusFileScale);
else
bonusByHash[hashRet] = ret * bonusFileScale;
logger.write("Adding bonus " + Global::doubleToString(ret * bonusFileScale) + " to hash " + hashRet.toString());
}
}
if(parseCommand("EXPAND",ret)) {
if(!std::isfinite(ret) || ret < 0 || ret > 10000)
throw StringError("Invalid EXPAND: " + Global::doubleToString(ret));
for(int bookVersion = 1; bookVersion <= Book::LATEST_BOOK_VERSION; bookVersion++) {
BookHash::getHashAndSymmetry(hist, repBound, hashRet, symmetryToAlignRet, symmetriesRet, bookVersion);
if(expandBonusByHash.find(hashRet) != expandBonusByHash.end())
expandBonusByHash[hashRet] = std::max(expandBonusByHash[hashRet], ret * bonusFileScale);
else
expandBonusByHash[hashRet] = ret * bonusFileScale;
logger.write("Adding expand bonus " + Global::doubleToString(ret * bonusFileScale) + " to hash " + hashRet.toString());
}
}
if(parseCommand("VISITS",ret)) {
if(!std::isfinite(ret) || ret < 0)
throw StringError("Invalid VISITS: " + Global::doubleToString(ret));
for(int bookVersion = 1; bookVersion <= Book::LATEST_BOOK_VERSION; bookVersion++) {
BookHash::getHashAndSymmetry(hist, repBound, hashRet, symmetryToAlignRet, symmetriesRet, bookVersion);
if(visitsRequiredByHash.find(hashRet) != visitsRequiredByHash.end())
visitsRequiredByHash[hashRet] = std::max(visitsRequiredByHash[hashRet], ret * bonusFileScale);
else
visitsRequiredByHash[hashRet] = ret * bonusFileScale;
logger.write("Adding required visits " + Global::doubleToString(ret * bonusFileScale) + " to hash " + hashRet.toString());
}
}
if(parseCommand("BRANCH",ret)) {
if(!std::isfinite(ret) || ret < 0 || ret > 200)
throw StringError("Invalid BRANCH: " + Global::doubleToString(ret));
for(int bookVersion = 1; bookVersion <= Book::LATEST_BOOK_VERSION; bookVersion++) {
BookHash::getHashAndSymmetry(hist, repBound, hashRet, symmetryToAlignRet, symmetriesRet, bookVersion);
if(branchRequiredByHash.find(hashRet) != branchRequiredByHash.end())
branchRequiredByHash[hashRet] = std::max(branchRequiredByHash[hashRet], (int)ret);
else
branchRequiredByHash[hashRet] = (int)ret;
logger.write("Adding required branching factor " + Global::intToString((int)ret) + " to hash " + hashRet.toString());
}
}
}
}
);
XYSize xySize = sgf->getXYSize();
if(boardSizeX != xySize.x || boardSizeY != xySize.y)
throw StringError("Board size in config does not match the board size of the bonus file");
vector<Move> placements;
sgf->getPlacements(placements,boardSizeX,boardSizeY);
bool suc = bonusInitialBoard.setStonesFailIfNoLibs(placements);
if(!suc)
throw StringError("Invalid placements in sgf");
bonusInitialPla = sgf->getFirstPlayerColor();
}
}
int MainCmds::genbook(const vector<string>& args) {
Board::initHash();
ScoreValue::initTables();
ConfigParser cfg;
string modelFile;
string humanModelFile;
string htmlDir;
string bookFile;
string traceBookFile;
string traceSgfFile;
string logFile;
std::vector<string> bonusFiles;
std::vector<string> hashBonusFiles;
int numIterations;
int saveEveryIterations;
double traceBookMinVisits;
bool allowChangingBookParams;
bool htmlDevMode;
double htmlMinVisits;
int numBookThreads;
try {
KataGoCommandLine cmd("Generate opening book");
cmd.addConfigFileArg("","",true);
cmd.addModelFileArg();
cmd.addHumanModelFileArg();
cmd.addOverrideConfigArg();
TCLAP::ValueArg<string> htmlDirArg("","html-dir","HTML directory to export to, at the end of -num-iters",false,string(),"DIR");
TCLAP::ValueArg<string> bookFileArg("","book-file","Book file to write to or continue expanding",true,string(),"FILE");
TCLAP::ValueArg<string> traceBookFileArg("","trace-book-file","Other book file we should copy all the lines from",false,string(),"FILE");
TCLAP::ValueArg<string> traceSgfFileArg("","trace-sgf-file","Other sgf file we should copy all the lines from",false,string(),"FILE");
TCLAP::ValueArg<string> logFileArg("","log-file","Log file to write to",true,string(),"DIR");
TCLAP::MultiArg<string> bonusFileArg("","bonus-file","SGF of bonuses marked",false,"DIR");
TCLAP::MultiArg<string> hashBonusFileArg("","hash-bonus-file","File of bookhashes and bonuses, one hash per line",false,"DIR");
TCLAP::ValueArg<int> numIterationsArg("","num-iters","Number of iterations to expand book",true,0,"N");
TCLAP::ValueArg<int> saveEveryIterationsArg("","save-every","Number of iterations per save to book file",true,0,"N");
TCLAP::ValueArg<double> traceBookMinVisitsArg("","trace-book-min-visits","Require >= this many visits for copying from traceBookFile",false,0.0,"N");
TCLAP::SwitchArg allowChangingBookParamsArg("","allow-changing-book-params","Allow changing book params");
TCLAP::SwitchArg htmlDevModeArg("","html-dev-mode","Denser debug output for html");
TCLAP::ValueArg<double> htmlMinVisitsArg("","html-min-visits","Require >= this many visits to export a position to html",false,0.0,"N");
TCLAP::ValueArg<int> numBookThreadsArg("","num-book-threads","Use this many threads to parallelize book operations",false,1,"N");
cmd.add(htmlDirArg);
cmd.add(bookFileArg);
cmd.add(traceBookFileArg);
cmd.add(traceSgfFileArg);
cmd.add(logFileArg);
cmd.add(bonusFileArg);
cmd.add(hashBonusFileArg);
cmd.add(numIterationsArg);
cmd.add(saveEveryIterationsArg);
cmd.add(traceBookMinVisitsArg);
cmd.add(allowChangingBookParamsArg);
cmd.add(htmlDevModeArg);
cmd.add(htmlMinVisitsArg);
cmd.add(numBookThreadsArg);
cmd.parseArgs(args);
cmd.getConfig(cfg);
modelFile = cmd.getModelFile();
humanModelFile = cmd.getHumanModelFile();
htmlDir = htmlDirArg.getValue();
bookFile = bookFileArg.getValue();
traceBookFile = traceBookFileArg.getValue();
traceSgfFile = traceSgfFileArg.getValue();
logFile = logFileArg.getValue();
bonusFiles = bonusFileArg.getValue();
hashBonusFiles = hashBonusFileArg.getValue();
numIterations = numIterationsArg.getValue();
saveEveryIterations = saveEveryIterationsArg.getValue();
traceBookMinVisits = traceBookMinVisitsArg.getValue();
allowChangingBookParams = allowChangingBookParamsArg.getValue();
htmlDevMode = htmlDevModeArg.getValue();
htmlMinVisits = htmlMinVisitsArg.getValue();
numBookThreads = numBookThreadsArg.getValue();
}
catch (TCLAP::ArgException &e) {
cerr << "Error: " << e.error() << " for argument " << e.argId() << endl;
return 1;
}
Rand rand;
const bool logToStdoutDefault = true;
Logger logger(&cfg, logToStdoutDefault);
logger.addFile(logFile);
const bool loadKomiFromCfg = true;
Rules rules = Setup::loadSingleRules(cfg,loadKomiFromCfg);
const bool hasHumanModel = humanModelFile != "";
const SearchParams params = Setup::loadSingleParams(cfg,Setup::SETUP_FOR_GTP,hasHumanModel);
const int boardSizeX = cfg.getInt("boardSizeX",2,Board::MAX_LEN);
const int boardSizeY = cfg.getInt("boardSizeY",2,Board::MAX_LEN);
const int repBound = cfg.getInt("repBound",3,1000);
const double bonusFileScale = cfg.contains("bonusFileScale") ? cfg.getDouble("bonusFileScale",0.0,1000000.0) : 1.0;
const double randomizeParamsStdev = cfg.contains("randomizeParamsStdev") ? cfg.getDouble("randomizeParamsStdev",0.0,2.0) : 0.0;
const bool logSearchInfo = cfg.getBool("logSearchInfo");
const string rulesLabel = cfg.getString("rulesLabel");
const string rulesLink = cfg.getString("rulesLink");
const int64_t minTreeVisitsToRecord =
cfg.contains("minTreeVisitsToRecord") ? cfg.getInt64("minTreeVisitsToRecord", (int64_t)1, (int64_t)1 << 50) : params.maxVisits;
const int maxDepthToRecord =
cfg.contains("maxDepthToRecord") ? cfg.getInt("maxDepthToRecord", 1, 100) : 1;
const int64_t maxVisitsForLeaves =
cfg.contains("maxVisitsForLeaves") ? cfg.getInt64("maxVisitsForLeaves", (int64_t)1, (int64_t)1 << 50) : (params.maxVisits+1) / 2;
BookParams cfgParams = BookParams::loadFromCfg(cfg, params.maxVisits, maxVisitsForLeaves);
const int numGameThreads = cfg.getInt("numGameThreads",1,1000);
const int numToExpandPerIteration = cfg.getInt("numToExpandPerIteration",1,10000000);
std::map<BookHash,double> bonusByHash;
std::map<BookHash,double> expandBonusByHash;
std::map<BookHash,double> visitsRequiredByHash;
std::map<BookHash,int> branchRequiredByHash;
Board bonusInitialBoard;
Player bonusInitialPla;
bonusInitialBoard = Board(boardSizeX,boardSizeY);
bonusInitialPla = P_BLACK;
for(const std::string& bonusFile: bonusFiles) {
maybeParseBonusFile(
bonusFile,
boardSizeX,
boardSizeY,
rules,
repBound,
bonusFileScale,
logger,
bonusByHash,
expandBonusByHash,
visitsRequiredByHash,
branchRequiredByHash,
bonusInitialBoard,
bonusInitialPla
);
}
for(const std::string& hashBonusFile: hashBonusFiles) {
maybeParseHashBonusFile(
hashBonusFile,
bonusFileScale,
logger,
bonusByHash,
expandBonusByHash,
visitsRequiredByHash,
branchRequiredByHash
);
}
const double wideRootNoiseBookExplore = cfg.contains("wideRootNoiseBookExplore") ? cfg.getDouble("wideRootNoiseBookExplore",0.0,5.0) : params.wideRootNoise;
const double cpuctExplorationLogBookExplore = cfg.contains("cpuctExplorationLogBookExplore") ? cfg.getDouble("cpuctExplorationLogBookExplore",0.0,10.0) : params.cpuctExplorationLog;
NNEvaluator* nnEval;
NNEvaluator* humanEval = NULL;
{
Setup::initializeSession(cfg);
const int expectedConcurrentEvals = numGameThreads * params.numThreads;
const int defaultMaxBatchSize = std::max(8,((numGameThreads * params.numThreads+3)/4)*4);
const bool defaultRequireExactNNLen = true;
const bool disableFP16 = false;
const string expectedSha256 = "";
nnEval = Setup::initializeNNEvaluator(
modelFile,modelFile,expectedSha256,cfg,logger,rand,expectedConcurrentEvals,
boardSizeX,boardSizeY,defaultMaxBatchSize,defaultRequireExactNNLen,disableFP16,
Setup::SETUP_FOR_ANALYSIS
);
logger.write("Loaded neural net");
if(humanModelFile != "") {
humanEval = Setup::initializeNNEvaluator(
humanModelFile,humanModelFile,expectedSha256,cfg,logger,rand,expectedConcurrentEvals,
boardSizeX,boardSizeY,defaultMaxBatchSize,defaultRequireExactNNLen,disableFP16,
Setup::SETUP_FOR_ANALYSIS
);
logger.write("Loaded human SL net with nnXLen " + Global::intToString(humanEval->getNNXLen()) + " nnYLen " + Global::intToString(humanEval->getNNYLen()));
}
}
NNEvaluator* policyEvaluator = nnEval;
if(humanEval != NULL)
policyEvaluator = humanEval;
vector<Search*> searches;
for(int i = 0; i<numGameThreads; i++) {
string searchRandSeed = Global::uint64ToString(rand.nextUInt64());
searches.push_back(new Search(params, nnEval, &logger, searchRandSeed));
}
// Check for unused config keys
cfg.warnUnusedKeys(cerr,&logger);
Setup::maybeWarnHumanSLParams(params,nnEval,NULL,cerr,&logger);
Setup::maybeWarnHumanSLParams(params,humanEval,NULL,cerr,&logger);
if(htmlDir != "")
MakeDir::make(htmlDir);
Book* book;
bool bookFileExists;
{
std::ifstream infile;
bookFileExists = FileUtils::tryOpen(infile,bookFile);
}
if(bookFileExists) {
book = Book::loadFromFile(bookFile,numBookThreads);
if(
boardSizeX != book->getInitialHist().getRecentBoard(0).x_size ||
boardSizeY != book->getInitialHist().getRecentBoard(0).y_size ||
repBound != book->repBound ||
rules != book->getInitialHist().rules
) {
throw StringError("Book parameters do not match");
}
if(bonusFiles.size() > 0) {
if(!bonusInitialBoard.isEqualForTesting(book->getInitialHist().getRecentBoard(0), false, false))
throw StringError(
"Book initial board and initial board in bonus sgf file do not match\n" +
Board::toStringSimple(book->getInitialHist().getRecentBoard(0)) + "\n" +
Board::toStringSimple(bonusInitialBoard)
);
if(bonusInitialPla != book->initialPla)
throw StringError(
"Book initial player and initial player in bonus sgf file do not match\n" +
PlayerIO::playerToString(book->initialPla) + " book \n" +
PlayerIO::playerToString(bonusInitialPla) + " bonus"
);
}
if(!allowChangingBookParams) {
BookParams existingBookParams = book->getParams();
if(
cfgParams.errorFactor != existingBookParams.errorFactor ||
cfgParams.costPerMove != existingBookParams.costPerMove ||
cfgParams.costPerUCBWinLossLoss != existingBookParams.costPerUCBWinLossLoss ||
cfgParams.costPerUCBWinLossLossPow3 != existingBookParams.costPerUCBWinLossLossPow3 ||
cfgParams.costPerUCBWinLossLossPow7 != existingBookParams.costPerUCBWinLossLossPow7 ||
cfgParams.costPerUCBScoreLoss != existingBookParams.costPerUCBScoreLoss ||
cfgParams.costPerLogPolicy != existingBookParams.costPerLogPolicy ||
cfgParams.costPerMovesExpanded != existingBookParams.costPerMovesExpanded ||
cfgParams.costPerSquaredMovesExpanded != existingBookParams.costPerSquaredMovesExpanded ||
cfgParams.costWhenPassFavored != existingBookParams.costWhenPassFavored ||
cfgParams.bonusPerWinLossError != existingBookParams.bonusPerWinLossError ||
cfgParams.bonusPerScoreError != existingBookParams.bonusPerScoreError ||
cfgParams.bonusPerSharpScoreDiscrepancy != existingBookParams.bonusPerSharpScoreDiscrepancy ||
cfgParams.bonusPerExcessUnexpandedPolicy != existingBookParams.bonusPerExcessUnexpandedPolicy ||
cfgParams.bonusPerUnexpandedBestWinLoss != existingBookParams.bonusPerUnexpandedBestWinLoss ||
cfgParams.bonusForWLPV1 != existingBookParams.bonusForWLPV1 ||
cfgParams.bonusForWLPV2 != existingBookParams.bonusForWLPV2 ||
cfgParams.bonusForWLPVFinalProp != existingBookParams.bonusForWLPVFinalProp ||
cfgParams.bonusForBiggestWLCost != existingBookParams.bonusForBiggestWLCost ||
cfgParams.bonusBehindInVisitsScale != existingBookParams.bonusBehindInVisitsScale ||
cfgParams.scoreLossCap != existingBookParams.scoreLossCap ||
cfgParams.earlyBookCostReductionFactor != existingBookParams.earlyBookCostReductionFactor ||
cfgParams.earlyBookCostReductionLambda != existingBookParams.earlyBookCostReductionLambda ||
cfgParams.utilityPerScore != existingBookParams.utilityPerScore ||
cfgParams.policyBoostSoftUtilityScale != existingBookParams.policyBoostSoftUtilityScale ||
cfgParams.utilityPerPolicyForSorting != existingBookParams.utilityPerPolicyForSorting ||
cfgParams.adjustedVisitsWLScale != existingBookParams.adjustedVisitsWLScale ||
cfgParams.maxVisitsForReExpansion != existingBookParams.maxVisitsForReExpansion ||
cfgParams.visitsScale != existingBookParams.visitsScale ||
cfgParams.visitsScaleLeaves != existingBookParams.visitsScaleLeaves ||
cfgParams.sharpScoreOutlierCap != existingBookParams.sharpScoreOutlierCap
) {
throw StringError("Book parameters do not match");
}
}
else {
book->setParams(cfgParams);
}
logger.write("Loaded preexisting book with " + Global::uint64ToString(book->size()) + " nodes from " + bookFile);
logger.write("Book version = " + Global::intToString(book->bookVersion));
}
else {
{
ostringstream bout;
Board::printBoard(bout, bonusInitialBoard, Board::NULL_LOC, NULL);
logger.write("Initializing new book with starting position:\n" + bout.str());
}
book = new Book(
Book::LATEST_BOOK_VERSION,
bonusInitialBoard,
rules,
bonusInitialPla,
repBound,
cfgParams
);
logger.write("Creating new book at " + bookFile);
book->saveToFile(bookFile);
ofstream out;
FileUtils::open(out,bookFile + ".cfg");
out << cfg.getContents() << endl;
out.close();
}
if(traceBookFile.size() > 0 && traceSgfFile.size() > 0)
throw StringError("Cannot trace book and sgf at the same time");
MutexPool mutexPool(1 << 17);
Book* traceBook = NULL;
if(traceBookFile.size() > 0) {
if(numIterations > 0)
throw StringError("Cannot specify iterations and trace book at the same time");
traceBook = Book::loadFromFile(traceBookFile);
traceBook->recomputeEverythingMultiThreaded(mutexPool, numBookThreads);
logger.write("Loaded trace book with " + Global::uint64ToString(traceBook->size()) + " nodes from " + traceBookFile);
logger.write("traceBookMinVisits = " + Global::doubleToString(traceBookMinVisits));
}
book->setBonusByHash(bonusByHash);
book->setExpandBonusByHash(expandBonusByHash);
book->setVisitsRequiredByHash(visitsRequiredByHash);
book->setBranchRequiredByHash(branchRequiredByHash);
book->recomputeEverythingMultiThreaded(mutexPool, numBookThreads);
if(!std::atomic_is_lock_free(&shouldStop))
throw StringError("shouldStop is not lock free, signal-quitting mechanism for terminating matches will NOT work!");
std::signal(SIGINT, signalHandler);
std::signal(SIGTERM, signalHandler);
const PrintTreeOptions options;
const Player perspective = P_WHITE;
// ClockTimer timer;
std::mutex bookMutex;
// Avoid all moves that are currently in the book on this node,
// unless allowReExpansion is true and this node qualifies for the visit threshold for allowReExpansion and
// to re-search already searched moves freshly.
// Mark avoidMoveUntilByLoc to be passed to search so that we only search new stuff.
auto findNewMovesAlreadyLocked = [&](
const BoardHistory& hist,
ConstSymBookNode constNode,
bool allowReExpansion,
std::vector<int>& avoidMoveUntilByLoc,
bool& isReExpansion
) {
avoidMoveUntilByLoc = std::vector<int>(Board::MAX_ARR_SIZE,0);
isReExpansion = allowReExpansion && constNode.canReExpand() && constNode.recursiveValues().visits <= book->getParams().maxVisitsForReExpansion;
Player pla = hist.presumedNextMovePla;
Board board = hist.getRecentBoard(0);
bool hasAtLeastOneLegalNewMove = false;
for(Loc moveLoc = 0; moveLoc < Board::MAX_ARR_SIZE; moveLoc++) {
if(hist.isLegal(board,moveLoc,pla)) {
if(!isReExpansion && constNode.isMoveInBook(moveLoc))
avoidMoveUntilByLoc[moveLoc] = 1;
else
hasAtLeastOneLegalNewMove = true;
}
}
return hasAtLeastOneLegalNewMove;
};
auto setParamsAndAvoidMoves = [&](Search* search, SearchParams thisParams, const std::vector<int>& avoidMoveUntilByLoc) {
thisParams.enableMorePassingHacks = false;
search->setParams(thisParams);
search->setAvoidMoveUntilByLoc(avoidMoveUntilByLoc, avoidMoveUntilByLoc);
search->setAvoidMoveUntilRescaleRoot(true);
};
auto setNodeThisValuesNoMoves = [&](SymBookNode node) {
std::lock_guard<std::mutex> lock(bookMutex);
BookValues& nodeValues = node.thisValuesNotInBook();
if(node.pla() == P_WHITE) {
nodeValues.winLossValue = -1e20;
nodeValues.scoreMean = -1e20;
nodeValues.sharpScoreMeanRaw = -1e20;
nodeValues.sharpScoreMeanClamped = -1e20;
}
else {
nodeValues.winLossValue = 1e20;
nodeValues.scoreMean = 1e20;
nodeValues.sharpScoreMeanRaw = 1e20;
nodeValues.sharpScoreMeanClamped = 1e20;
}
nodeValues.winLossError = 0.0;
nodeValues.scoreError = 0.0;
nodeValues.scoreStdev = 0.0;
nodeValues.maxPolicy = 0.0;
nodeValues.weight = 0.0;
nodeValues.visits = 0.0;
node.canExpand() = false;
};
auto setNodeThisValuesTerminal = [&](SymBookNode node, const BoardHistory& hist) {
assert(hist.isGameFinished);
std::lock_guard<std::mutex> lock(bookMutex);
BookValues& nodeValues = node.thisValuesNotInBook();
if(hist.isNoResult) {
nodeValues.winLossValue = 0.0;
nodeValues.scoreMean = 0.0;
nodeValues.sharpScoreMeanRaw = 0.0;
nodeValues.sharpScoreMeanClamped = 0.0;
}
else {
if(hist.winner == P_WHITE) {
assert(hist.finalWhiteMinusBlackScore > 0.0);
nodeValues.winLossValue = 1.0;
}
else if(hist.winner == P_BLACK) {
assert(hist.finalWhiteMinusBlackScore < 0.0);
nodeValues.winLossValue = -1.0;
}
else {
assert(hist.finalWhiteMinusBlackScore == 0.0);
nodeValues.winLossValue = 0.0;
}
nodeValues.scoreMean = hist.finalWhiteMinusBlackScore;
nodeValues.sharpScoreMeanRaw = hist.finalWhiteMinusBlackScore;
nodeValues.sharpScoreMeanClamped = hist.finalWhiteMinusBlackScore;
}
nodeValues.winLossError = 0.0;
nodeValues.scoreError = 0.0;
nodeValues.scoreStdev = 0.0;
nodeValues.maxPolicy = 1.0;
double visits = maxVisitsForLeaves;
nodeValues.weight = visits;
nodeValues.visits = visits;
node.canExpand() = false;
};
auto setNodeThisValuesFromFinishedSearch = [&](
SymBookNode node,
Search* search,
const SearchNode* searchNode,
const Board& board,
const BoardHistory& hist,
const std::vector<int>& avoidMoveUntilByLoc
) {
// Get root values
ReportedSearchValues remainingSearchValues;
bool getSuc = search->getPrunedNodeValues(searchNode,remainingSearchValues);
// Something is bad if this is false, since we should be searching with positive visits
// or otherwise this searchNode must be a terminal node with visits from a deeper search.
assert(getSuc);
(void)getSuc;
double sharpScore = 0.0;
// cout << "Calling sharpscore " << timer.getSeconds() << endl;
getSuc = search->getSharpScore(searchNode,sharpScore);
// cout << "Done sharpscore " << timer.getSeconds() << endl;
assert(getSuc);
(void)getSuc;
// cout << "Calling shallowAvg " << timer.getSeconds() << endl;
std::pair<double,double> errors = search->getShallowAverageShorttermWLAndScoreError(searchNode);
// cout << "Done shallowAvg " << timer.getSeconds() << endl;
// Use full symmetry for the policy for nodes we record for the book
bool includeOwnerMap = false;
// cout << "Calling full nn " << timer.getSeconds() << endl;
std::shared_ptr<NNOutput> fullSymNNOutput = PlayUtils::getFullSymmetryNNOutput(board, hist, node.pla(), includeOwnerMap, ¶ms.humanSLProfile, policyEvaluator);
float policyProbs[NNPos::MAX_NN_POLICY_SIZE];
std::copy(fullSymNNOutput->policyProbs, fullSymNNOutput->policyProbs+NNPos::MAX_NN_POLICY_SIZE, policyProbs);
// cout << "Done full nn " << timer.getSeconds() << endl;
// Zero out all the policies for moves we already have, we want the max *remaining* policy
if(avoidMoveUntilByLoc.size() > 0) {
assert(avoidMoveUntilByLoc.size() == Board::MAX_ARR_SIZE);
for(Loc loc = 0; loc<Board::MAX_ARR_SIZE; loc++) {
if(avoidMoveUntilByLoc[loc] > 0) {
int pos = search->getPos(loc);
assert(pos >= 0 && pos < NNPos::MAX_NN_POLICY_SIZE);
policyProbs[pos] = -1;
}
}
}
double maxPolicy = getMaxPolicy(policyProbs);
assert(maxPolicy >= 0.0);
// LOCK BOOK AND UPDATE -------------------------------------------------------
std::lock_guard<std::mutex> lock(bookMutex);
// Record those values to the book
BookValues& nodeValues = node.thisValuesNotInBook();
nodeValues.winLossValue = remainingSearchValues.winLossValue;
nodeValues.scoreMean = remainingSearchValues.expectedScore;
nodeValues.sharpScoreMeanRaw = sharpScore;
nodeValues.sharpScoreMeanClamped = sharpScore;
nodeValues.winLossError = errors.first;
nodeValues.scoreError = errors.second;
nodeValues.scoreStdev = remainingSearchValues.expectedScoreStdev;
nodeValues.maxPolicy = maxPolicy;
nodeValues.weight = remainingSearchValues.weight;
nodeValues.visits = (double)remainingSearchValues.visits;
};
// Perform a short search and update thisValuesNotInBook for a node
auto searchAndUpdateNodeThisValues = [&](Search* search, SymBookNode node) {
ConstSymBookNode constNode(node);
BoardHistory hist;
std::vector<int> symmetries;
{
std::lock_guard<std::mutex> lock(bookMutex);
std::vector<Loc> moveHistory;
bool suc = node.getBoardHistoryReachingHere(hist,moveHistory);
if(!suc) {
logger.write("WARNING: Failed to get board history reaching node when trying to export to trace book, probably there is some bug");
logger.write("or else some hash collision or something else is wrong.");
logger.write("BookHash of node unable to expand: " + node.hash().toString());
throw StringError("Terminating since there's not a good way to put the book back into a good state with this node unupdated");
}
symmetries = constNode.getSymmetries();
}
Player pla = hist.presumedNextMovePla;
Board board = hist.getRecentBoard(0);
search->setPosition(pla,board,hist);
search->setRootSymmetryPruningOnly(symmetries);
// Directly set the values for a terminal position
if(hist.isGameFinished) {
setNodeThisValuesTerminal(node,hist);
return;
}
std::vector<int> avoidMoveUntilByLoc;
bool foundNewMoves;
{
const bool allowReExpansion = false;
bool isReExpansion;
std::lock_guard<std::mutex> lock(bookMutex);
foundNewMoves = findNewMovesAlreadyLocked(hist,constNode,allowReExpansion,avoidMoveUntilByLoc,isReExpansion);
}
if(!foundNewMoves) {
setNodeThisValuesNoMoves(node);
}
else {
{
SearchParams thisParams = params;
thisParams.maxVisits = std::min(params.maxVisits, maxVisitsForLeaves);
setParamsAndAvoidMoves(search,thisParams,avoidMoveUntilByLoc);
// cout << "Search and update" << timer.getSeconds() << endl;
search->runWholeSearch(search->rootPla);
// cout << "Search and update done" << timer.getSeconds() << endl;
}
if(logSearchInfo) {
std::lock_guard<std::mutex> lock(bookMutex);
logger.write("Quick search on remaining moves");
ostringstream out;
search->printTree(out, search->rootNode, options, perspective);
logger.write(out.str());
}
// Stick all the new values into the book node
setNodeThisValuesFromFinishedSearch(node, search, search->getRootNode(), search->getRootBoard(), search->getRootHist(), avoidMoveUntilByLoc);
}
};
auto addVariationToBookWithoutUpdate = [&](int gameThreadIdx, const BoardHistory& targetHist, std::set<BookHash>& nodesHashesToUpdate) {
std::unique_lock<std::mutex> lock(bookMutex);
Search* search = searches[gameThreadIdx];
SymBookNode node = book->getRoot();
BoardHistory hist = book->getInitialHist();
Player pla = hist.presumedNextMovePla;
Board board = hist.getRecentBoard(0);
search->setPosition(pla,board,hist);
// Run some basic error checking
if(
targetHist.initialBoard.pos_hash != board.pos_hash ||
targetHist.initialBoard.ko_loc != board.ko_loc ||
targetHist.initialPla != pla ||
targetHist.initialEncorePhase != hist.initialEncorePhase
) {
throw StringError("Target board history to add to book doesn't start from the same position");
}
assert(hist.moveHistory.size() == 0);
for(auto& move: targetHist.moveHistory) {
// Make sure we don't walk off the edge under this ruleset.
if(hist.isGameFinished || hist.isPastNormalPhaseEnd) {
logger.write("Skipping trace variation at this book hash " + node.hash().toString() + " since game over");
node.canExpand() = false;
break;
}
Loc moveLoc = move.loc;
Player movePla = move.pla;
if(movePla != pla)
throw StringError("Target board history to add player got out of sync");
if(movePla != node.pla())
throw StringError("Target board history to add player got out of sync with node");
if(movePla != hist.presumedNextMovePla)
throw StringError("Target board history to add player got out of sync with hist");
// Illegal move, possibly due to rules mismatch between the books. In that case, we just stop where we are.
if(!hist.isLegal(board,moveLoc,movePla)) {
logger.write("Skipping trace variation at this book hash " + node.hash().toString() + " since illegal");
break;
}
if(!node.isMoveInBook(moveLoc)) {
// If this node in this book or under this ruleset is nonexpandable, then although we can
// follow existing moves, we can't add any moves.
if(!node.canExpand()) {
logger.write("Skipping trace variation at this book hash " + node.hash().toString() + " since nonexpandable");
break;
}
// UNLOCK for performing expensive symmetry computations
lock.unlock();
// To avoid oddities in positions where the rules mismatch, expand every move with a noticeably higher raw policy
// Average all 8 symmetries
const bool includeOwnerMap = false;
std::shared_ptr<NNOutput> result = PlayUtils::getFullSymmetryNNOutput(board, hist, pla, includeOwnerMap, ¶ms.humanSLProfile, policyEvaluator);
const float* policyProbs = result->policyProbs;
float moveLocPolicy = policyProbs[search->getPos(moveLoc)];
assert(moveLocPolicy >= 0);
vector<std::pair<Loc,float>> extraMoveLocsToExpand;
for(int pos = 0; pos<NNPos::MAX_NN_POLICY_SIZE; pos++) {
Loc loc = NNPos::posToLoc(pos, board.x_size, board.y_size, result->nnXLen, result->nnYLen);
if(loc == Board::NULL_LOC || loc == moveLoc)
continue;
if(policyProbs[pos] > 0.0 && policyProbs[pos] > 1.5 * moveLocPolicy + 0.05f)
extraMoveLocsToExpand.push_back(std::make_pair(loc,policyProbs[pos]));
}
std::sort(
extraMoveLocsToExpand.begin(),
extraMoveLocsToExpand.end(),
[](std::pair<Loc,float>& p0, std::pair<Loc,float>& p1) {
return p0.second > p1.second;
}
);
// LOCK for going back to modifying the book and other shared state
lock.lock();
// We're adding moves to this node, so it needs update
nodesHashesToUpdate.insert(node.hash());
{
// Possibly another thread added it, so we need to check again.
if(!node.isMoveInBook(moveLoc)) {
Board boardCopy = board;
BoardHistory histCopy = hist;
bool childIsTransposing;
SymBookNode child = node.playAndAddMove(boardCopy,histCopy,moveLoc,moveLocPolicy,childIsTransposing);
if(!child.isNull() && !childIsTransposing)
nodesHashesToUpdate.insert(child.hash());
}
}
for(std::pair<Loc,float>& extraMoveLocToExpand: extraMoveLocsToExpand) {
// Possibly we added it via symmetry, or maybe even another thread, so we need to check again.
if(!node.isMoveInBook(extraMoveLocToExpand.first)) {
Board boardCopy = board;
BoardHistory histCopy = hist;
bool childIsTransposing;
SymBookNode child = node.playAndAddMove(boardCopy,histCopy,extraMoveLocToExpand.first,extraMoveLocToExpand.second,childIsTransposing);
if(!child.isNull() && !childIsTransposing)
nodesHashesToUpdate.insert(child.hash());
}
}
}
assert(node.isMoveInBook(moveLoc));
node = node.playMove(board,hist,moveLoc);
assert(!node.isNull());
pla = getOpp(pla);
}
};
// Returns true if any child was added directly to this node (doesn't count recursive stuff).
std::function<bool(
Search*, const SearchNode*, SymBookNode,
const Board&, const BoardHistory&, int,
std::set<BookHash>&, std::set<BookHash>&,
std::set<const SearchNode*>&
)> expandFromSearchResultRecursively;
expandFromSearchResultRecursively = [&](
Search* search, const SearchNode* searchNode, SymBookNode node,
const Board& board, const BoardHistory& hist, int maxDepth,
std::set<BookHash>& nodesHashesToSearch, std::set<BookHash>& nodesHashesToUpdate,
std::set<const SearchNode*>& searchNodesRecursedOn
) {
// cout << "Entering expandFromSearchResultRecursively " << timer.getSeconds() << endl;
if(maxDepth <= 0)
return false;
// Quit out immediately when handling transpositions in graph search
if(searchNodesRecursedOn.find(searchNode) != searchNodesRecursedOn.end())