-
Notifications
You must be signed in to change notification settings - Fork 685
Expand file tree
/
Copy pathmisc.cpp
More file actions
2944 lines (2571 loc) · 111 KB
/
misc.cpp
File metadata and controls
2944 lines (2571 loc) · 111 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/fileutils.h"
#include "../core/fancymath.h"
#include "../core/makedir.h"
#include "../core/config_parser.h"
#include "../core/parallel.h"
#include "../core/timer.h"
#include "../core/test.h"
#include "../dataio/sgf.h"
#include "../dataio/poswriter.h"
#include "../dataio/files.h"
#include "../search/asyncbot.h"
#include "../program/setup.h"
#include "../program/playutils.h"
#include "../program/play.h"
#include "../command/commandline.h"
#include "../main.h"
#include <chrono>
#include <csignal>
using namespace std;
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 void writeLine(
const Search* search, const BoardHistory& baseHist,
const vector<double>& winLossHistory, const vector<double>& scoreHistory, const vector<double>& scoreStdevHistory
) {
const Board board = search->getRootBoard();
int nnXLen = search->nnXLen;
int nnYLen = search->nnYLen;
cout << board.x_size << " ";
cout << board.y_size << " ";
cout << nnXLen << " ";
cout << nnYLen << " ";
cout << baseHist.rules.komi << " ";
if(baseHist.isGameFinished) {
cout << PlayerIO::playerToString(baseHist.winner) << " ";
cout << baseHist.isResignation << " ";
cout << baseHist.finalWhiteMinusBlackScore << " ";
}
else {
cout << "-" << " ";
cout << "false" << " ";
cout << "0" << " ";
}
//Last move
Loc moveLoc = Board::NULL_LOC;
if(baseHist.moveHistory.size() > 0)
moveLoc = baseHist.moveHistory[baseHist.moveHistory.size()-1].loc;
cout << NNPos::locToPos(moveLoc,board.x_size,nnXLen,nnYLen) << " ";
cout << baseHist.moveHistory.size() << " ";
cout << board.numBlackCaptures << " ";
cout << board.numWhiteCaptures << " ";
for(int y = 0; y<board.y_size; y++) {
for(int x = 0; x<board.x_size; x++) {
Loc loc = Location::getLoc(x,y,board.x_size);
if(board.colors[loc] == C_BLACK)
cout << "x";
else if(board.colors[loc] == C_WHITE)
cout << "o";
else
cout << ".";
}
}
cout << " ";
vector<AnalysisData> buf;
if(!baseHist.isGameFinished) {
int minMovesToTryToGet = 0; //just get the default number
bool duplicateForSymmetries = true;
search->getAnalysisData(buf,minMovesToTryToGet,false,9,duplicateForSymmetries);
}
cout << buf.size() << " ";
for(int i = 0; i<buf.size(); i++) {
const AnalysisData& data = buf[i];
cout << NNPos::locToPos(data.move,board.x_size,nnXLen,nnYLen) << " ";
cout << data.numVisits << " ";
cout << data.winLossValue << " ";
cout << data.scoreMean << " ";
cout << data.scoreStdev << " ";
cout << data.policyPrior << " ";
}
vector<double> ownership = search->getAverageTreeOwnership();
for(int y = 0; y<board.y_size; y++) {
for(int x = 0; x<board.x_size; x++) {
int pos = NNPos::xyToPos(x,y,nnXLen);
cout << ownership[pos] << " ";
}
}
cout << winLossHistory.size() << " ";
for(int i = 0; i<winLossHistory.size(); i++)
cout << winLossHistory[i] << " ";
cout << scoreHistory.size() << " ";
assert(scoreStdevHistory.size() == scoreHistory.size());
for(int i = 0; i<scoreHistory.size(); i++)
cout << scoreHistory[i] << " " << scoreStdevHistory[i] << " ";
cout << endl;
}
static void initializeDemoGame(Board& board, BoardHistory& hist, Player& pla, Rand& rand, AsyncBot* bot) {
static const int numSizes = 9;
int sizes[numSizes] = {19,13,9,15,11,10,12,14,16};
int sizeFreqs[numSizes] = {240,18,12,6,2,1,1,1,1};
const int size = sizes[rand.nextUInt(sizeFreqs,numSizes)];
board = Board(size,size);
pla = P_BLACK;
hist.clear(board,pla,Rules::getTrompTaylorish(),0);
bot->setPosition(pla,board,hist);
if(size == 19) {
//Many games use a special opening
if(rand.nextBool(0.6)) {
auto g = [size](int x, int y) { return Location::getLoc(x,y,size); };
const Move nb = Move(Board::NULL_LOC, P_BLACK);
const Move nw = Move(Board::NULL_LOC, P_WHITE);
Player b = P_BLACK;
Player w = P_WHITE;
vector<vector<Move>> specialOpenings = {
//Sanrensei
{ Move(g(3,3), b), nw, Move(g(15,3), b), nw, Move(g(9,3), b) },
//Low Chinese
{ Move(g(3,3), b), nw, Move(g(16,3), b), nw, Move(g(10,2), b) },
//Low Chinese
{ Move(g(3,3), b), nw, Move(g(16,3), b), nw, Move(g(10,2), b) },
//High chinese
{ Move(g(3,3), b), nw, Move(g(16,3), b), nw, Move(g(10,3), b) },
//Low small chinese
{ Move(g(3,3), b), nw, Move(g(16,3), b), nw, Move(g(11,2), b) },
//Kobayashi
{ Move(g(3,3), b), Move(g(15,15), w), Move(g(16,3), b), nw, Move(g(16,13), b), Move(g(13,16), w), Move(g(15,9), b) },
//Kobayashi
{ Move(g(3,3), b), Move(g(15,15), w), Move(g(16,3), b), nw, Move(g(16,13), b), Move(g(13,16), w), Move(g(15,9), b) },
//Mini chinese
{ Move(g(3,3), b), Move(g(15,15), w), Move(g(15,2), b), nw, Move(g(16,13), b), Move(g(13,16), w), Move(g(16,8), b) },
//Mini chinese
{ Move(g(3,3), b), Move(g(15,15), w), Move(g(15,2), b), nw, Move(g(16,13), b), Move(g(13,16), w), Move(g(16,8), b) },
//Micro chinese
{ Move(g(3,3), b), Move(g(15,15), w), Move(g(15,2), b), nw, Move(g(16,13), b), Move(g(13,16), w), Move(g(16,7), b) },
//Micro chinese with variable other corner
{ Move(g(15,2), b), Move(g(15,15), w), nb, nw, Move(g(16,13), b), Move(g(13,16), w), Move(g(16,7), b) },
//Boring star points
{ Move(g(15,3), b), Move(g(15,15), w), nb, nw, Move(g(16,13), b), Move(g(13,16), w), Move(g(15,9), b) },
//High 3-4 counter approaches
{ Move(g(3,3), b), Move(g(15,16), w), Move(g(16,3), b), nw, Move(g(15,14), b), Move(g(14,3), w) },
//Double 3-3
{ Move(g(2,2), b), nw, Move(g(16,2), b) },
//Low enclosure
{ Move(g(2,3), b), nw, Move(g(4,2), b) },
//High enclosure
{ Move(g(2,3), b), nw, Move(g(4,3), b) },
//5-5 point
{ Move(g(4,4), b) },
//5-3 point
{ Move(g(2,4), b) },
//5-4 point
{ Move(g(3,4), b) },
//3-3 point
{ Move(g(2,2), b) },
//3-4 point far approach
{ Move(g(3,2), b), Move(g(2,5), w) },
//Tengen
{ Move(g(9,9), b) },
//2-2 point
{ Move(g(1,1), b) },
//Shusaku fuseki
{ Move(g(16,15), b), Move(g(3,16), w), Move(g(15,2), b), Move(g(14,16), w), nb, Move(g(16,4), w), Move(g(15,14), b) },
//Miyamoto fuseki
{ Move(g(16,13), b), Move(g(3,15), w), Move(g(13,2), b), nw, Move(g(9,16), b) },
//4-4 1-space low pincer - shared side
{ Move(g(15,15), b), Move(g(3,15), w), nb, nw, Move(g(5,16), b), Move(g(7,16), w) },
//4-4 2-space high pincer - shared side
{ Move(g(15,15), b), Move(g(3,15), w), nb, nw, Move(g(5,16), b), Move(g(8,15), w) },
//4-4 1-space low pincer - opponent side
{ Move(g(15,15), b), Move(g(3,15), w), nb, nw, Move(g(2,13), b), Move(g(2,11), w) },
//4-4 2-space high pincer - opponent side
{ Move(g(15,15), b), Move(g(3,15), w), nb, nw, Move(g(2,13), b), Move(g(3,10), w) },
//3-4 1-space low approach - shusaku kosumi and long extend
{ Move(g(15,15), b), Move(g(3,16), w), nb, nw, Move(g(2,14), b), Move(g(4,15), w), Move(g(2,10), b) },
//3-4 1-space low approach low pincer - opponent side
{ Move(g(15,15), b), Move(g(3,16), w), nb, nw, Move(g(2,14), b), Move(g(2,12), w) },
//3-4 2-space low approach high pincer - opponent side
{ Move(g(15,15), b), Move(g(3,16), w), nb, nw, Move(g(2,14), b), Move(g(3,11), w) },
//3-4 1-space high approach - opponent side
{ Move(g(15,15), b), Move(g(3,16), w), nb, nw, Move(g(3,14), b) },
//3-4 1-space high approach low pincer - opponent side
{ Move(g(15,15), b), Move(g(3,16), w), nb, nw, Move(g(3,14), b), Move(g(2,12), w) },
//3-4 2-space high approach high pincer - opponent side
{ Move(g(15,15), b), Move(g(3,16), w), nb, nw, Move(g(3,14), b), Move(g(3,11), w) },
//Orthodox
{ Move(g(3,3), b), nw, Move(g(15,2), b), nw, Move(g(16,4), b), Move(g(9,2), w) },
//Manchurian
{ Move(g(4,3), b), nw, Move(g(16,3), b), nw, Move(g(10,3), b) },
//Upper Manchurian
{ Move(g(4,4), b), nw, Move(g(16,4), b), nw, Move(g(10,4), b) },
//Great wall
{ Move(g(9,9), b), nw, Move(g(9,15), b), nw, Move(g(9,3), b), nw, Move(g(8,12), b), nw, Move(g(10,6), b) },
//Small wall
{ Move(g(9,8), b), nw, Move(g(8,11), b), nw, Move(g(10,5), b) },
//High approaches
{ Move(g(3,2), b), Move(g(3,4), w), Move(g(16,3), b), Move(g(14,3), w), Move(g(15,16), b), Move(g(15,14), w) },
//Black hole
{ Move(g(12,14), b), nw, Move(g(14,6), b), nw, Move(g(4,12), b), nw, Move(g(6,4), b) },
//Crosscut
{ Move(g(9,9), b), Move(g(9,10), w), Move(g(10,10), b), Move(g(10,9), w) },
//One-point jump center
{ Move(g(9,8), b), nw, Move(g(9,10), b) },
};
vector<Move> chosenOpening = specialOpenings[rand.nextUInt((int)specialOpenings.size())];
vector<vector<Move>> chosenOpenings;
for(int j = 0; j<8; j++) {
vector<Move> symmetric;
for(int k = 0; k<chosenOpening.size(); k++) {
Loc loc = chosenOpening[k].loc;
Player movePla = chosenOpening[k].pla;
if(loc == Board::NULL_LOC || loc == Board::PASS_LOC)
symmetric.push_back(Move(loc,movePla));
else {
int x = Location::getX(loc,size);
int y = Location::getY(loc,size);
if(j & 1) x = size-1-x;
if(j & 2) y = size-1-y;
if(j & 4) std::swap(x,y);
symmetric.push_back(Move(Location::getLoc(x,y,size),movePla));
}
}
chosenOpenings.push_back(symmetric);
}
for(int j = (int)chosenOpenings.size()-1; j>=1; j--) {
int r = rand.nextUInt(j+1);
vector<Move> tmp = chosenOpenings[j];
chosenOpenings[j] = chosenOpenings[r];
chosenOpenings[r] = tmp;
}
vector<Move> movesPlayed;
vector<Move> freeMovesPlayed;
vector<Move> specifiedMovesPlayed;
while(true) {
auto withinRadius1 = [size](Loc l0, Loc l1) {
if(l0 == Board::NULL_LOC || l1 == Board::NULL_LOC || l0 == Board::PASS_LOC || l1 == Board::PASS_LOC)
return false;
int x0 = Location::getX(l0,size);
int y0 = Location::getY(l0,size);
int x1 = Location::getX(l1,size);
int y1 = Location::getY(l1,size);
return std::abs(x0-x1) <= 1 && std::abs(y0-y1) <= 1;
};
auto symmetryIsGood = [&movesPlayed,&specifiedMovesPlayed,&freeMovesPlayed,&withinRadius1](const vector<Move>& moves) {
assert(movesPlayed.size() <= moves.size());
//Make sure the symmetry matches up to the desired point,
//and that free moves are not within radius 1 of any specified move
for(int j = 0; j<movesPlayed.size(); j++) {
if(moves[j].loc == Board::NULL_LOC) {
Loc actualLoc = movesPlayed[j].loc;
for(int k = 0; k<specifiedMovesPlayed.size(); k++) {
if(withinRadius1(specifiedMovesPlayed[k].loc,actualLoc))
return false;
}
}
else if(movesPlayed[j].loc != moves[j].loc)
return false;
}
//Make sure the next move will also not be within radius 1 of any free move.
if(movesPlayed.size() < moves.size()) {
Loc nextLoc = moves[movesPlayed.size()].loc;
for(int k = 0; k<freeMovesPlayed.size(); k++) {
if(withinRadius1(freeMovesPlayed[k].loc,nextLoc))
return false;
}
}
return true;
};
//Take the first good symmetry
vector<Move> goodSymmetry;
for(int i = 0; i<chosenOpenings.size(); i++) {
if(symmetryIsGood(chosenOpenings[i])) {
goodSymmetry = chosenOpenings[i];
break;
}
}
//If we have no further moves on that symmetry, we're done
if(movesPlayed.size() >= goodSymmetry.size())
break;
Move nextMove = goodSymmetry[movesPlayed.size()];
bool wasSpecified = true;
if(nextMove.loc == Board::NULL_LOC) {
wasSpecified = false;
Search* search = bot->getSearchStopAndWait();
NNResultBuf buf;
MiscNNInputParams nnInputParams;
nnInputParams.drawEquivalentWinsForWhite = search->searchParams.drawEquivalentWinsForWhite;
search->nnEvaluator->evaluate(board,hist,pla,nnInputParams,buf,false,false);
std::shared_ptr<NNOutput> nnOutput = std::move(buf.result);
double temperature = 0.8;
bool allowPass = false;
Loc banMove = Board::NULL_LOC;
Loc loc = PlayUtils::chooseRandomPolicyMove(nnOutput.get(), board, hist, pla, rand, temperature, allowPass, banMove);
nextMove.loc = loc;
}
//Make sure the next move is legal
if(!hist.isLegal(board,nextMove.loc,nextMove.pla))
break;
//Make the move!
hist.makeBoardMoveAssumeLegal(board,nextMove.loc,nextMove.pla,NULL);
pla = getOpp(pla);
hist.clear(board,pla,hist.rules,0);
bot->setPosition(pla,board,hist);
movesPlayed.push_back(nextMove);
if(wasSpecified)
specifiedMovesPlayed.push_back(nextMove);
else
freeMovesPlayed.push_back(nextMove);
bot->clearSearch();
writeLine(bot->getSearch(),hist,vector<double>(),vector<double>(),vector<double>());
std::this_thread::sleep_for(std::chrono::duration<double>(1.0));
} //Close while(true)
int numVisits = 20;
PlayUtils::adjustKomiToEven(bot->getSearchStopAndWait(),NULL,board,hist,pla,numVisits,OtherGameProperties(),rand);
double komi = hist.rules.komi + 0.3 * rand.nextGaussian();
komi = 0.5 * round(2.0 * komi);
hist.setKomi((float)komi);
bot->setPosition(pla,board,hist);
}
}
bot->clearSearch();
writeLine(bot->getSearch(),hist,vector<double>(),vector<double>(),vector<double>());
std::this_thread::sleep_for(std::chrono::duration<double>(2.0));
}
int MainCmds::demoplay(const vector<string>& args) {
Board::initHash();
ScoreValue::initTables();
Rand seedRand;
ConfigParser cfg;
string logFile;
string modelFile;
try {
KataGoCommandLine cmd("Self-play demo dumping status to stdout");
cmd.addConfigFileArg("","");
cmd.addModelFileArg();
cmd.addOverrideConfigArg();
TCLAP::ValueArg<string> logFileArg("","log-file","Log file to output to",false,string(),"FILE");
cmd.add(logFileArg);
cmd.parseArgs(args);
modelFile = cmd.getModelFile();
logFile = logFileArg.getValue();
cmd.getConfig(cfg);
}
catch (TCLAP::ArgException &e) {
cerr << "Error: " << e.error() << " for argument " << e.argId() << endl;
return 1;
}
Logger logger(&cfg);
logger.addFile(logFile);
logger.write("Engine starting...");
string searchRandSeed = Global::uint64ToString(seedRand.nextUInt64());
SearchParams params = Setup::loadSingleParams(cfg,Setup::SETUP_FOR_OTHER);
NNEvaluator* nnEval;
{
Setup::initializeSession(cfg);
const int expectedConcurrentEvals = params.numThreads;
const int defaultMaxBatchSize = -1;
const bool defaultRequireExactNNLen = false;
const bool disableFP16 = false;
const string expectedSha256 = "";
nnEval = Setup::initializeNNEvaluator(
modelFile,modelFile,expectedSha256,cfg,logger,seedRand,expectedConcurrentEvals,
NNPos::MAX_BOARD_LEN,NNPos::MAX_BOARD_LEN,defaultMaxBatchSize,defaultRequireExactNNLen,disableFP16,
Setup::SETUP_FOR_OTHER
);
}
logger.write("Loaded neural net");
const bool allowResignation = cfg.contains("allowResignation") ? cfg.getBool("allowResignation") : false;
const double resignThreshold = cfg.contains("allowResignation") ? cfg.getDouble("resignThreshold",-1.0,0.0) : -1.0; //Threshold on [-1,1], regardless of winLossUtilityFactor
const double resignScoreThreshold = cfg.contains("allowResignation") ? cfg.getDouble("resignScoreThreshold",-10000.0,0.0) : -10000.0;
const double searchFactorWhenWinning = cfg.contains("searchFactorWhenWinning") ? cfg.getDouble("searchFactorWhenWinning",0.01,1.0) : 1.0;
const double searchFactorWhenWinningThreshold = cfg.contains("searchFactorWhenWinningThreshold") ? cfg.getDouble("searchFactorWhenWinningThreshold",0.0,1.0) : 1.0;
//Check for unused config keys
cfg.warnUnusedKeys(cerr,&logger);
Setup::maybeWarnHumanSLParams(params,nnEval,NULL,cerr,&logger);
AsyncBot* bot = new AsyncBot(params, nnEval, &logger, searchRandSeed);
bot->setAlwaysIncludeOwnerMap(true);
Rand gameRand;
//Done loading!
//------------------------------------------------------------------------------------
logger.write("Loaded all config stuff, starting demo");
//Game loop
while(true) {
Player pla = P_BLACK;
Board baseBoard;
BoardHistory baseHist(baseBoard,pla,Rules::getTrompTaylorish(),0);
TimeControls tc;
initializeDemoGame(baseBoard, baseHist, pla, gameRand, bot);
bot->setPosition(pla,baseBoard,baseHist);
vector<double> recentWinLossValues;
vector<double> recentScores;
vector<double> recentScoreStdevs;
double callbackPeriod = 0.05;
std::function<void(const Search*)> callback = [&baseHist,&recentWinLossValues,&recentScores,&recentScoreStdevs](const Search* search) {
writeLine(search,baseHist,recentWinLossValues,recentScores,recentScoreStdevs);
};
//Move loop
int maxMovesPerGame = 1600;
for(int i = 0; i<maxMovesPerGame; i++) {
baseHist.endGameIfAllPassAlive(baseBoard);
if(baseHist.isGameFinished)
break;
callback(bot->getSearch());
double searchFactor =
//Speed up when either player is winning confidently, not just the winner only
std::min(
PlayUtils::getSearchFactor(searchFactorWhenWinningThreshold,searchFactorWhenWinning,params,recentWinLossValues,P_BLACK),
PlayUtils::getSearchFactor(searchFactorWhenWinningThreshold,searchFactorWhenWinning,params,recentWinLossValues,P_WHITE)
);
Loc moveLoc = bot->genMoveSynchronousAnalyze(pla,tc,searchFactor,callbackPeriod,callbackPeriod,callback);
bool isLegal = bot->isLegalStrict(moveLoc,pla);
if(moveLoc == Board::NULL_LOC || !isLegal) {
ostringstream sout;
sout << "genmove null location or illegal move!?!" << "\n";
sout << bot->getRootBoard() << "\n";
sout << "Pla: " << PlayerIO::playerToString(pla) << "\n";
sout << "MoveLoc: " << Location::toString(moveLoc,bot->getRootBoard()) << "\n";
logger.write(sout.str());
cerr << sout.str() << endl;
throw StringError("illegal move");
}
double winLossValue;
double expectedScore;
double expectedScoreStdev;
{
ReportedSearchValues values = bot->getSearch()->getRootValuesRequireSuccess();
winLossValue = values.winLossValue;
expectedScore = values.expectedScore;
expectedScoreStdev = values.expectedScoreStdev;
}
recentWinLossValues.push_back(winLossValue);
recentScores.push_back(expectedScore);
recentScoreStdevs.push_back(expectedScoreStdev);
bool resigned = false;
if(allowResignation) {
const BoardHistory hist = bot->getRootHist();
const Board initialBoard = hist.initialBoard;
//Play at least some moves no matter what
int minTurnForResignation = 1 + initialBoard.x_size * initialBoard.y_size / 6;
Player resignPlayerThisTurn = C_EMPTY;
if(winLossValue < resignThreshold && expectedScore < resignScoreThreshold)
resignPlayerThisTurn = P_WHITE;
else if(winLossValue > -resignThreshold && expectedScore > -resignScoreThreshold)
resignPlayerThisTurn = P_BLACK;
if(resignPlayerThisTurn == pla &&
bot->getRootHist().moveHistory.size() >= minTurnForResignation)
resigned = true;
}
if(resigned) {
baseHist.setWinnerByResignation(getOpp(pla));
break;
}
else {
//And make the move on our copy of the board
assert(baseHist.isLegal(baseBoard,moveLoc,pla));
baseHist.makeBoardMoveAssumeLegal(baseBoard,moveLoc,pla,NULL);
//If the game is over, skip making the move on the bot, to preserve
//the last known value of the search tree for display purposes
//Just immediately terminate the game loop
if(baseHist.isGameFinished)
break;
bool suc = bot->makeMove(moveLoc,pla);
assert(suc);
(void)suc; //Avoid warning when asserts are off
pla = getOpp(pla);
}
}
//End of game display line
writeLine(bot->getSearch(),baseHist,recentWinLossValues,recentScores,recentScoreStdevs);
//Wait a bit before diving into the next game
std::this_thread::sleep_for(std::chrono::seconds(10));
bot->clearSearch();
}
delete bot;
delete nnEval;
NeuralNet::globalCleanup();
ScoreValue::freeTables();
logger.write("All cleaned up, quitting");
return 0;
}
int MainCmds::printclockinfo(const vector<string>& args) {
(void)args;
#ifdef OS_IS_WINDOWS
cout << "Does nothing on windows, disabled" << endl;
#endif
#ifdef OS_IS_UNIX_OR_APPLE
cout << "Tick unit in seconds: " << std::chrono::steady_clock::period::num << " / " << std::chrono::steady_clock::period::den << endl;
cout << "Ticks since epoch: " << std::chrono::steady_clock::now().time_since_epoch().count() << endl;
#endif
return 0;
}
static void handleStartAnnotations(Sgf* rootSgf) {
std::function<bool(Sgf*)> hasStartNode = [&hasStartNode](Sgf* sgf) {
for(SgfNode* node : sgf->nodes) {
if(node->hasProperty("C")) {
std::string comment = node->getSingleProperty("C");
if(comment.find("%START%") != std::string::npos) {
return true;
}
}
}
for(Sgf* child : sgf->children) {
if(hasStartNode(child)) {
return true;
}
}
return false;
};
std::function<void(Sgf*)> markNodes = [&markNodes](Sgf* sgf) {
bool isInStartSubtree = false;
for(SgfNode* node : sgf->nodes) {
if(node->hasProperty("C")) {
std::string comment = node->getSingleProperty("C");
if(comment.find("%START%") != std::string::npos) {
isInStartSubtree = true;
break;
}
}
node->appendComment("%NOSAMPLE%");
node->appendComment("%NOHINT%");
}
if(!isInStartSubtree) {
for(Sgf* child : sgf->children)
markNodes(child);
}
};
if(hasStartNode(rootSgf)) {
markNodes(rootSgf);
}
}
int MainCmds::samplesgfs(const vector<string>& args) {
Board::initHash();
ScoreValue::initTables();
Rand seedRand;
vector<string> sgfFilesFromCmdline;
vector<string> sgfDirs;
vector<string> sgfsDirs;
string outDir;
vector<string> excludeHashesFiles;
double sampleProb;
double sampleWeight;
double forceSampleWeight;
double turnWeightLambda;
double minWeight;
int64_t maxDepth;
int64_t maxNodeCount;
int64_t maxBranchCount;
double minTurnNumberBoardAreaProp;
double maxTurnNumberBoardAreaProp;
bool flipIfPassOrWFirst;
double afterPassFactor;
bool allowGameOver;
bool hashComments;
double trainingWeight;
int verbosity;
string valueFluctuationModelFile;
double valueFluctuationTurnScale;
double valueFluctuationMaxWeight;
bool valueFluctuationMakeKomiFair;
double valueFluctuationWeightBySurprise;
double valueFluctuationWeightByCount;
double valueFluctuationWeightByUncertainty;
bool debugValueFluctuation;
int minMinRank;
int minMinRating;
string requiredPlayerName;
int maxHandicap;
double maxKomi;
int numThreads;
bool forTesting;
try {
KataGoCommandLine cmd("Search for suprising good moves in sgfs");
TCLAP::MultiArg<string> sgfArg("","sgf","Sgf file",false,"SGF");
TCLAP::MultiArg<string> sgfDirArg("","sgfdir","Directory of sgf files",false,"DIR");
TCLAP::MultiArg<string> sgfsDirArg("","sgfsdir","Directory of sgfs files",false,"DIR");
TCLAP::ValueArg<string> outDirArg("","outdir","Directory to write results",true,string(),"DIR");
TCLAP::MultiArg<string> excludeHashesArg("","exclude-hashes","Specify a list of hashes to filter out, one per line in a txt file",false,"FILEOF(HASH,HASH)");
TCLAP::ValueArg<double> sampleProbArg("","sample-prob","Probability to sample each position",true,0.0,"PROB");
TCLAP::ValueArg<double> sampleWeightArg("","sample-weight","",false,1.0,"Weight");
TCLAP::ValueArg<double> forceSampleWeightArg("","force-sample-weight","",false,5.0,"Weight");
TCLAP::ValueArg<double> turnWeightLambdaArg("","turn-weight-lambda","Adjust weight for writing down each position",true,0.0,"LAMBDA");
TCLAP::ValueArg<double> minWeightArg("","min-weight","",false,0.0,"Weight");
TCLAP::ValueArg<string> maxDepthArg("","max-depth","Max depth allowed for sgf",false,"100000000","INT");
TCLAP::ValueArg<string> maxNodeCountArg("","max-node-count","Max node count allowed for sgf",false,"100000000","INT");
TCLAP::ValueArg<string> maxBranchCountArg("","max-branch-count","Max branch count allowed for sgf",false,"100000000","INT");
TCLAP::ValueArg<double> minTurnNumberBoardAreaPropArg("","min-turn-number-board-area-prop","Only use turn number >= this board area",false,-1.0,"PROP");
TCLAP::ValueArg<double> maxTurnNumberBoardAreaPropArg("","max-turn-number-board-area-prop","Only use turn number <= this board area",false,10000.0,"PROP");
TCLAP::SwitchArg flipIfPassOrWFirstArg("","flip-if-pass","Try to heuristically find cases where an sgf passes to simulate white<->black");
TCLAP::ValueArg<double> afterPassFactorArg("","after-pass-factor","Scale down weight of positions following a pass",false, 1.0, "FACTOR");
TCLAP::SwitchArg allowGameOverArg("","allow-game-over","Allow sampling game over positions in sgf");
TCLAP::SwitchArg hashCommentsArg("","hash-comments","Hash comments in sgf");
TCLAP::ValueArg<double> trainingWeightArg("","training-weight","Scale the loss function weight from data from games that originate from this position",false,1.0,"WEIGHT");
TCLAP::ValueArg<int> verbosityArg("","verbosity","Print more stuff",false,0,"INT");
TCLAP::ValueArg<string> valueFluctuationModelFileArg("","value-fluctuation-model","Upweight positions prior to value fluctuations",false,string(),"MODELFILE");
TCLAP::ValueArg<double> valueFluctuationTurnScaleArg("","value-fluctuation-turn-scale","How much prior on average",false,1.0,"AVGTURNS");
TCLAP::ValueArg<double> valueFluctuationMaxWeightArg("","value-fluctuation-max-weight","",false,10.0,"MAXWEIGHT");
TCLAP::SwitchArg valueFluctuationMakeKomiFairArg("","value-fluctuation-make-komi-fair","");
TCLAP::ValueArg<double> valueFluctuationWeightBySurpriseArg("","value-fluctuation-weight-by-surprise","",false,0.0,"SCALE");
TCLAP::ValueArg<double> valueFluctuationWeightByCountArg("","value-fluctuation-weight-by-count","",false,1.0,"SCALE");
TCLAP::ValueArg<double> valueFluctuationWeightByUncertaintyArg("","value-fluctuation-weight-by-uncertainty","",false,0.0,"SCALE");
TCLAP::SwitchArg debugValueFluctuationArg("","debug-value-fluctuation","");
TCLAP::ValueArg<int> minMinRankArg("","min-min-rank","Require both players in a game to have rank at least this",false,Sgf::RANK_UNKNOWN,"INT");
TCLAP::ValueArg<int> minMinRatingArg("","min-min-rating","Require both players in a game to have rating at least this",false,-1000000000,"INT");
TCLAP::ValueArg<string> requiredPlayerNameArg("","required-player-name","Require player making the move to have this name",false,string(),"NAME");
TCLAP::ValueArg<int> maxHandicapArg("","max-handicap","Require no more than this big handicap in stones",false,100,"INT");
TCLAP::ValueArg<double> maxKomiArg("","max-komi","Require absolute value of game komi to be at most this",false,1000,"KOMI");
TCLAP::ValueArg<int> numThreadsArg("","num-threads","Number of threads to process",false,1,"INT");
TCLAP::SwitchArg forTestingArg("","for-testing","For testing");
cmd.add(sgfArg);
cmd.add(sgfDirArg);
cmd.add(sgfsDirArg);
cmd.add(outDirArg);
cmd.add(excludeHashesArg);
cmd.add(sampleProbArg);
cmd.add(sampleWeightArg);
cmd.add(forceSampleWeightArg);
cmd.add(turnWeightLambdaArg);
cmd.add(minWeightArg);
cmd.add(maxDepthArg);
cmd.add(maxNodeCountArg);
cmd.add(maxBranchCountArg);
cmd.add(minTurnNumberBoardAreaPropArg);
cmd.add(maxTurnNumberBoardAreaPropArg);
cmd.add(flipIfPassOrWFirstArg);
cmd.add(afterPassFactorArg);
cmd.add(allowGameOverArg);
cmd.add(hashCommentsArg);
cmd.add(trainingWeightArg);
cmd.add(verbosityArg);
cmd.add(valueFluctuationModelFileArg);
cmd.add(valueFluctuationTurnScaleArg);
cmd.add(valueFluctuationMaxWeightArg);
cmd.add(valueFluctuationMakeKomiFairArg);
cmd.add(valueFluctuationWeightBySurpriseArg);
cmd.add(valueFluctuationWeightByCountArg);
cmd.add(valueFluctuationWeightByUncertaintyArg);
cmd.add(debugValueFluctuationArg);
cmd.add(minMinRankArg);
cmd.add(minMinRatingArg);
cmd.add(requiredPlayerNameArg);
cmd.add(maxHandicapArg);
cmd.add(maxKomiArg);
cmd.add(numThreadsArg);
cmd.add(forTestingArg);
cmd.parseArgs(args);
sgfFilesFromCmdline = sgfArg.getValue();
sgfDirs = sgfDirArg.getValue();
sgfsDirs = sgfsDirArg.getValue();
outDir = outDirArg.getValue();
excludeHashesFiles = excludeHashesArg.getValue();
sampleProb = sampleProbArg.getValue();
sampleWeight = sampleWeightArg.getValue();
minWeight = minWeightArg.getValue();
forceSampleWeight = forceSampleWeightArg.getValue();
turnWeightLambda = turnWeightLambdaArg.getValue();
maxDepth = Global::stringToInt64(maxDepthArg.getValue());
maxNodeCount = Global::stringToInt64(maxNodeCountArg.getValue());
maxBranchCount = Global::stringToInt64(maxBranchCountArg.getValue());
minTurnNumberBoardAreaProp = minTurnNumberBoardAreaPropArg.getValue();
maxTurnNumberBoardAreaProp = maxTurnNumberBoardAreaPropArg.getValue();
flipIfPassOrWFirst = flipIfPassOrWFirstArg.getValue();
afterPassFactor = afterPassFactorArg.getValue();
allowGameOver = allowGameOverArg.getValue();
hashComments = hashCommentsArg.getValue();
trainingWeight = trainingWeightArg.getValue();
verbosity = verbosityArg.getValue();
valueFluctuationModelFile = valueFluctuationModelFileArg.getValue();
valueFluctuationTurnScale = valueFluctuationTurnScaleArg.getValue();
valueFluctuationMaxWeight = valueFluctuationMaxWeightArg.getValue();
valueFluctuationMakeKomiFair = valueFluctuationMakeKomiFairArg.getValue();
valueFluctuationWeightBySurprise = valueFluctuationWeightBySurpriseArg.getValue();
valueFluctuationWeightByCount = valueFluctuationWeightByCountArg.getValue();
valueFluctuationWeightByUncertainty = valueFluctuationWeightByUncertaintyArg.getValue();
debugValueFluctuation = debugValueFluctuationArg.getValue();
minMinRank = minMinRankArg.getValue();
minMinRating = minMinRatingArg.getValue();
requiredPlayerName = requiredPlayerNameArg.getValue();
maxHandicap = maxHandicapArg.getValue();
maxKomi = maxKomiArg.getValue();
numThreads = numThreadsArg.getValue();
forTesting = forTestingArg.getValue();
}
catch (TCLAP::ArgException &e) {
cerr << "Error: " << e.error() << " for argument " << e.argId() << endl;
return 1;
}
MakeDir::make(outDir);
const bool logToStdout = true;
const bool logToStderr = false;
const bool logTimeStamp = !forTesting;
Logger logger(nullptr, logToStdout, logToStderr, logTimeStamp);
logger.addFile(outDir + "/" + "log.log");
for(const string& arg: args)
logger.write(string("Command: ") + arg);
vector<string> sgfFiles;
FileHelpers::collectSgfsFromDirsOrFiles(sgfDirs,sgfFiles);
for(const string& s: sgfFilesFromCmdline)
sgfFiles.push_back(s);
logger.write("Found " + Global::int64ToString((int64_t)sgfFiles.size()) + " sgf files!");
vector<string> sgfsFiles;
FileHelpers::collectMultiSgfsFromDirsOrFiles(sgfsDirs,sgfsFiles);
logger.write("Found " + Global::int64ToString((int64_t)sgfsFiles.size()) + " sgfs files!");
if(forTesting) {
std::sort(sgfFiles.begin(),sgfFiles.end());
std::sort(sgfsFiles.begin(),sgfsFiles.end());
}
set<Hash128> excludeHashes = Sgf::readExcludes(excludeHashesFiles);
logger.write("Loaded " + Global::uint64ToString(excludeHashes.size()) + " excludes");
NNEvaluator* valueFluctuationNNEval = NULL;
if(valueFluctuationModelFile != "") {
if(valueFluctuationTurnScale <= 0.0 || valueFluctuationTurnScale > 100000000.0)
throw StringError("Invalid valueFluctuationTurnScale");
if(valueFluctuationMaxWeight <= 0.0 || valueFluctuationMaxWeight > 100000000.0)
throw StringError("Invalid valueFluctuationMaxWeight");
ConfigParser cfg;
if(forTesting)
cfg.overrideKey("nnRandSeed","forTesting");
Setup::initializeSession(cfg);
const int expectedConcurrentEvals = numThreads;
const int defaultMaxBatchSize = std::max(8,((numThreads+3)/4)*4);
const bool defaultRequireExactNNLen = false;
const bool disableFP16 = false;
const string expectedSha256 = "";
valueFluctuationNNEval = Setup::initializeNNEvaluator(
valueFluctuationModelFile,valueFluctuationModelFile,expectedSha256,cfg,logger,seedRand,expectedConcurrentEvals,
NNPos::MAX_BOARD_LEN,NNPos::MAX_BOARD_LEN,defaultMaxBatchSize,defaultRequireExactNNLen,disableFP16,
Setup::SETUP_FOR_ANALYSIS
);
logger.write("Loaded neural net");
}
// ---------------------------------------------------------------------------------------------------
auto isPlayerOkay = [&](const Sgf* sgf, Player pla) {
if(requiredPlayerName != "") {
if(sgf->getPlayerName(pla) != requiredPlayerName)
return false;
}
return true;
};
auto isSgfOkay = [&](const Sgf* sgf) {
if(maxHandicap < 100 && sgf->getHandicapValue() > maxHandicap)
return false;
if(sgf->depth() > maxDepth)
return false;
if(std::fabs(sgf->getKomiOrDefault(7.5f)) > maxKomi)
return false;
if(minMinRank != Sgf::RANK_UNKNOWN) {
if(sgf->getRank(P_BLACK) < minMinRank || sgf->getRank(P_WHITE) < minMinRank)
return false;
}
if(minMinRating > -10000000) {
if(sgf->getRating(P_BLACK) < minMinRating || sgf->getRating(P_WHITE) < minMinRating)
return false;
}
if(!isPlayerOkay(sgf,P_BLACK) && !isPlayerOkay(sgf,P_WHITE))
return false;
return true;
};
// ---------------------------------------------------------------------------------------------------
std::mutex mutex;
PosWriter posWriter("startposes.txt", outDir, 1, 0, 100000);
posWriter.start();
// ---------------------------------------------------------------------------------------------------
int64_t numKept = 0;
double weightKept = 0;
std::set<Hash128> uniqueHashes;
std::function<void(Sgf::PositionSample&, const BoardHistory&, const string&)> posHandler =
[sampleProb,sampleWeight,forceSampleWeight,&posWriter,turnWeightLambda,&numKept,&weightKept,&seedRand,minTurnNumberBoardAreaProp,maxTurnNumberBoardAreaProp,afterPassFactor,trainingWeight,minWeight](
Sgf::PositionSample& posSample, const BoardHistory& hist, const string& comments
) {
assert(posSample.getCurrentTurnNumber() == hist.getCurrentTurnNumber());
double minTurnNumber = minTurnNumberBoardAreaProp * (hist.initialBoard.x_size * hist.initialBoard.y_size);
double maxTurnNumber = maxTurnNumberBoardAreaProp * (hist.initialBoard.x_size * hist.initialBoard.y_size);
if(posSample.getCurrentTurnNumber() < minTurnNumber || posSample.getCurrentTurnNumber() > maxTurnNumber)
return;
if(comments.size() > 0 && comments.find("%NOSAMPLE%") != string::npos)
return;
if(seedRand.nextBool(sampleProb)) {
Sgf::PositionSample posSampleToWrite = posSample;
int64_t startTurn = posSampleToWrite.getCurrentTurnNumber();
posSampleToWrite.weight = sampleWeight * exp(-startTurn * turnWeightLambda) * posSampleToWrite.weight;
if(posSampleToWrite.moves.size() > 0 && posSampleToWrite.moves[posSampleToWrite.moves.size()-1].loc == Board::PASS_LOC)
posSampleToWrite.weight *= afterPassFactor;
if(comments.size() > 0 && comments.find("%SAMPLE%") != string::npos)
posSampleToWrite.weight = std::max(posSampleToWrite.weight,forceSampleWeight);
if(comments.size() > 0 && comments.find("%SAMPLELIGHT%") != string::npos)
posSampleToWrite.weight = std::max(posSampleToWrite.weight,0.5*forceSampleWeight);
if(posSampleToWrite.weight < minWeight)
return;
posSampleToWrite.trainingWeight = trainingWeight;
posWriter.writePos(posSampleToWrite);
numKept += 1;
weightKept += posSampleToWrite.weight;
}
};
std::map<string,int64_t> sgfCountUsedByPlayerName;
std::map<string,int64_t> sgfCountUsedByResult;
double totalWeightFromCount = 0.0;
double totalWeightFromSurprise = 0.0;
double totalWeightFromUncertainty = 0.0;
int64_t numExcluded = 0;
int64_t numSgfsFilteredTopLevel = 0;
auto trySgf = [&](Sgf* sgf) {
std::unique_lock<std::mutex> lock(mutex);
if(contains(excludeHashes,sgf->hash)) {
numExcluded += 1;
return;
}
int64_t depth = sgf->depth();
int64_t nodeCount = sgf->nodeCount();
int64_t branchCount = sgf->branchCount();
if(depth > maxDepth || nodeCount > maxNodeCount || branchCount > maxBranchCount) {
logger.write(
"Skipping due to violating limits depth " + Global::int64ToString(depth) +
" nodes " + Global::int64ToString(nodeCount) +
" branches " + Global::int64ToString(branchCount) +
" " + sgf->fileName
);
numSgfsFilteredTopLevel += 1;
return;
}
try {
if(!isSgfOkay(sgf)) {
if(verbosity >= 2)
logger.write("Filtering due to not okay: " + sgf->fileName);
numSgfsFilteredTopLevel += 1;
return;
}
}
catch(const StringError& e) {
logger.write("Filtering due to error checking okay: " + sgf->fileName + ": " + e.what());
numSgfsFilteredTopLevel += 1;
return;
}
handleStartAnnotations(sgf);
if(valueFluctuationNNEval == NULL) {
bool hashParent = false;
Rand iterRand;
sgf->iterAllUniquePositions(uniqueHashes, hashComments, hashParent, flipIfPassOrWFirst, allowGameOver, forTesting ? NULL : &iterRand, posHandler);
if(verbosity >= 2)
logger.write("Handled " + sgf->fileName + " kept weight " + Global::doubleToString(weightKept));
sgfCountUsedByPlayerName[sgf->getPlayerName(P_BLACK)] += 1;
sgfCountUsedByPlayerName[sgf->getPlayerName(P_WHITE)] += 1;
sgfCountUsedByResult[sgf->getRootPropertyWithDefault("RE","")] += 1;
}
else {
string fileName = sgf->fileName;
CompactSgf compactSgf(sgf);
Board board;
Player nextPla;
BoardHistory hist;
Rules rules = compactSgf.getRulesOrFailAllowUnspecified(Rules::getSimpleTerritory());
compactSgf.setupInitialBoardAndHist(rules, board, nextPla, hist);
if(valueFluctuationMakeKomiFair) {
Rand rand;
string searchRandSeed = Global::uint64ToString(rand.nextUInt64());
SearchParams params = SearchParams::basicDecentParams();
Search* search = new Search(params,valueFluctuationNNEval,&logger,searchRandSeed);
OtherGameProperties otherGameProps;
int64_t numVisits = 30;
lock.unlock();
PlayUtils::adjustKomiToEven(search, search, board, hist, nextPla, numVisits, otherGameProps, rand);
lock.lock();
}
const bool preventEncore = false;
const vector<Move>& sgfMoves = compactSgf.moves;
vector<Board> boards;
vector<BoardHistory> hists;
vector<Player> nextPlas;
vector<shared_ptr<NNOutput>> nnOutputs;
vector<double> winLossValues;
vector<Move> moves;
for(size_t m = 0; m<sgfMoves.size()+1; m++) {