forked from lightvector/KataGo
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathevalsgf.cpp
More file actions
706 lines (625 loc) · 26.8 KB
/
Copy pathevalsgf.cpp
File metadata and controls
706 lines (625 loc) · 26.8 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
#include "../core/global.h"
#include "../core/config_parser.h"
#include "../core/timer.h"
#include "../dataio/sgf.h"
#include "../neuralnet/modelversion.h"
#include "../search/asyncbot.h"
#include "../search/searchnode.h"
#include "../program/setup.h"
#include "../program/playutils.h"
#include "../program/play.h"
#include "../command/commandline.h"
#include "../main.h"
using namespace std;
int MainCmds::evalsgf(const vector<string>& args) {
Board::initHash();
ScoreValue::initTables();
Rand seedRand;
ConfigParser cfg;
string modelFile;
string humanModelFile;
string sgfFile;
int moveNumStart;
int moveNumEnd;
string printBranch;
string extraMoves;
string avoidMoves;
string hintLoc;
int64_t maxVisits;
int numThreads;
float overrideKomi;
string overrideRules;
bool printOwnership;
bool printRootNNValues;
bool printPolicy;
bool printLogPolicy;
bool printDirichletShape;
bool printScoreNow;
bool printRootEndingBonus;
bool printLead;
bool printAvgShorttermError;
bool printSharpScore;
bool printGraph;
bool printJson;
int printMaxDepth;
bool rawNN;
string dumpNpzInputTo;
try {
KataGoCommandLine cmd("Run a search on a position from an sgf file, for debugging.");
cmd.addConfigFileArg("","gtp_example.cfg");
cmd.addModelFileArg();
cmd.addHumanModelFileArg();
TCLAP::UnlabeledValueArg<string> sgfFileArg("","Sgf file to analyze",true,string(),"FILE");
TCLAP::ValueArg<int> moveNumArg("m","move-num","Sgf move num to analyze",true,0,"MOVENUM");
TCLAP::ValueArg<int> moveNumEndArg("","move-num-end","End sgf move num range to analyze, inclusive",false,-1,"MOVENUM");
TCLAP::ValueArg<string> printBranchArg("","print-branch","Move branch in search tree to print",false,string(),"MOVE MOVE ...");
TCLAP::ValueArg<string> printArg("p","print","Alias for -print-branch",false,string(),"MOVE MOVE ...");
TCLAP::ValueArg<string> extraMovesArg("","extra-moves","Extra moves to force-play before doing search",false,string(),"MOVE MOVE ...");
TCLAP::ValueArg<string> extraArg("e","extra","Alias for -extra-moves",false,string(),"MOVE MOVE ...");
TCLAP::ValueArg<string> avoidMovesArg("","avoid-moves","Avoid moves in search",false,string(),"MOVE MOVE ...");
TCLAP::ValueArg<string> hintLocArg("","hint-loc","Hint loc",false,string(),"MOVE");
TCLAP::ValueArg<long> visitsArg("v","visits","Set the number of visits",false,-1,"VISITS");
TCLAP::ValueArg<int> threadsArg("t","threads","Set the number of threads",false,-1,"THREADS");
TCLAP::ValueArg<float> overrideKomiArg("","override-komi","Artificially set komi",false,std::numeric_limits<float>::quiet_NaN(),"KOMI");
TCLAP::ValueArg<string> overrideRulesArg("","override-rules","Artifically set rules",false,string(),"RULES");
TCLAP::SwitchArg printOwnershipArg("","print-ownership","Print ownership");
TCLAP::SwitchArg printRootNNValuesArg("","print-root-nn-values","Print root nn values");
TCLAP::SwitchArg printPolicyArg("","print-policy","Print policy");
TCLAP::SwitchArg printLogPolicyArg("","print-log-policy","Print log policy");
TCLAP::SwitchArg printDirichletShapeArg("","print-dirichlet-shape","Print dirichlet shape");
TCLAP::SwitchArg printScoreNowArg("","print-score-now","Print score now");
TCLAP::SwitchArg printRootEndingBonusArg("","print-root-ending-bonus","Print root ending bonus now");
TCLAP::SwitchArg printLeadArg("","print-lead","Compute and print lead");
TCLAP::SwitchArg printAvgShorttermErrorArg("","print-avg-shortterm-error","Compute and print avgShorttermError");
TCLAP::SwitchArg printSharpScoreArg("","print-sharp-score","Compute and print sharp weighted score");
TCLAP::SwitchArg printGraphArg("","print-graph","Print graph structure of the search");
TCLAP::SwitchArg printJsonArg("","print-json","Print analysis json of the search");
TCLAP::ValueArg<int> printMaxDepthArg("","print-max-depth","How deep to print",false,1,"DEPTH");
TCLAP::SwitchArg rawNNArg("","raw-nn","Perform single raw neural net eval");
TCLAP::ValueArg<string> dumpNpzInputToArg("","dump-npz-input-to","Dump the nn input tensor to npz file",false,string(),"NPZFILE");
cmd.add(sgfFileArg);
cmd.add(moveNumArg);
cmd.add(moveNumEndArg);
cmd.setShortUsageArgLimit();
cmd.addOverrideConfigArg();
cmd.add(printBranchArg);
cmd.add(printArg);
cmd.add(extraMovesArg);
cmd.add(extraArg);
cmd.add(avoidMovesArg);
cmd.add(hintLocArg);
cmd.add(visitsArg);
cmd.add(threadsArg);
cmd.add(overrideKomiArg);
cmd.add(overrideRulesArg);
cmd.add(printOwnershipArg);
cmd.add(printRootNNValuesArg);
cmd.add(printPolicyArg);
cmd.add(printLogPolicyArg);
cmd.add(printDirichletShapeArg);
cmd.add(printScoreNowArg);
cmd.add(printRootEndingBonusArg);
cmd.add(printLeadArg);
cmd.add(printAvgShorttermErrorArg);
cmd.add(printSharpScoreArg);
cmd.add(printGraphArg);
cmd.add(printJsonArg);
cmd.add(printMaxDepthArg);
cmd.add(rawNNArg);
cmd.add(dumpNpzInputToArg);
cmd.parseArgs(args);
modelFile = cmd.getModelFile();
humanModelFile = cmd.getHumanModelFile();
sgfFile = sgfFileArg.getValue();
moveNumStart = moveNumArg.getValue();
moveNumEnd = moveNumEndArg.getValue();
printBranch = printBranchArg.getValue();
string print = printArg.getValue();
extraMoves = extraMovesArg.getValue();
string extra = extraArg.getValue();
avoidMoves = avoidMovesArg.getValue();
hintLoc = hintLocArg.getValue();
maxVisits = (int64_t)visitsArg.getValue();
numThreads = threadsArg.getValue();
overrideKomi = overrideKomiArg.getValue();
overrideRules = overrideRulesArg.getValue();
printOwnership = printOwnershipArg.getValue();
printRootNNValues = printRootNNValuesArg.getValue();
printPolicy = printPolicyArg.getValue();
printLogPolicy = printLogPolicyArg.getValue();
printDirichletShape = printDirichletShapeArg.getValue();
printScoreNow = printScoreNowArg.getValue();
printRootEndingBonus = printRootEndingBonusArg.getValue();
printLead = printLeadArg.getValue();
printAvgShorttermError = printAvgShorttermErrorArg.getValue();
printSharpScore = printSharpScoreArg.getValue();
printGraph = printGraphArg.getValue();
printJson = printJsonArg.getValue();
printMaxDepth = printMaxDepthArg.getValue();
rawNN = rawNNArg.getValue();
dumpNpzInputTo = dumpNpzInputToArg.getValue();
if(printBranch.length() > 0 && print.length() > 0) {
cerr << "Error: -print-branch and -print both specified" << endl;
return 1;
}
if(printBranch.length() <= 0)
printBranch = print;
if(extraMoves.length() > 0 && extra.length() > 0) {
cerr << "Error: -extra-moves and -extra both specified" << endl;
return 1;
}
if(extraMoves.length() <= 0)
extraMoves = extra;
if(moveNumEnd < moveNumStart)
moveNumEnd = moveNumStart;
cmd.getConfig(cfg);
}
catch (TCLAP::ArgException &e) {
cerr << "Error: " << e.error() << " for argument " << e.argId() << endl;
return 1;
}
//Parse rules -------------------------------------------------------------------
Rules defaultRules = Rules::getTrompTaylorish();
Player perspective = Setup::parseReportAnalysisWinrates(cfg,P_BLACK);
//Parse sgf file and board ------------------------------------------------------------------
std::unique_ptr<CompactSgf> sgf = CompactSgf::loadFile(sgfFile);
Board board;
Player nextPla;
BoardHistory hist;
auto setUpBoardUsingRules = [&board,&nextPla,&hist,overrideKomi,&sgf,&extraMoves](const Rules& initialRules, int moveNum) {
sgf->setupInitialBoardAndHist(initialRules, board, nextPla, hist);
vector<Move>& moves = sgf->moves;
if(!isnan(overrideKomi)) {
if(overrideKomi > board.x_size * board.y_size + NNPos::KOMI_CLIP_RADIUS || overrideKomi < -board.x_size * board.y_size - NNPos::KOMI_CLIP_RADIUS)
throw StringError("Invalid komi, too much greater than the area of the board");
hist.setKomi(overrideKomi);
}
if(moveNum < 0)
throw StringError("Move num " + Global::intToString(moveNum) + " requested but must be non-negative");
if(moveNum > moves.size())
throw StringError("Move num " + Global::intToString(moveNum) + " requested but sgf has only " + Global::int64ToString(moves.size()));
sgf->playMovesTolerant(board,nextPla,hist,moveNum,false);
vector<Loc> extraMoveLocs = Location::parseSequence(extraMoves,board);
for(size_t i = 0; i<extraMoveLocs.size(); i++) {
Loc loc = extraMoveLocs[i];
if(!hist.isLegal(board,loc,nextPla)) {
cerr << board << endl;
cerr << "Extra illegal move for " << PlayerIO::colorToChar(nextPla) << ": " << Location::toString(loc,board) << endl;
throw StringError("Illegal extra move");
}
hist.makeBoardMoveAssumeLegal(board,loc,nextPla,NULL);
nextPla = getOpp(nextPla);
}
};
Rules initialRules = sgf->getRulesOrWarn(
defaultRules,
[](const string& msg) { cout << msg << endl; }
);
if(overrideRules != "") {
initialRules = Rules::parseRules(overrideRules);
}
// Set up once now for error catcihng
setUpBoardUsingRules(initialRules,moveNumStart);
//Parse move sequence arguments------------------------------------------
PrintTreeOptions options;
options = options.maxDepth(printMaxDepth);
if(printBranch.length() > 0)
options = options.onlyBranch(board,printBranch);
options = options.printAvgShorttermError(printAvgShorttermError);
//Load neural net and start bot------------------------------------------
const bool logToStdoutDefault = true;
Logger logger(&cfg, logToStdoutDefault);
logger.write("Engine starting...");
bool hasHumanModel = humanModelFile != "";
SearchParams params = Setup::loadSingleParams(cfg,Setup::SETUP_FOR_GTP,hasHumanModel);
if(maxVisits < -1 || maxVisits == 0)
throw StringError("maxVisits: invalid value");
else if(maxVisits == -1)
logger.write("No max visits specified on cmdline, using defaults in " + cfg.getFileName());
else {
params.maxVisits = maxVisits;
params.maxPlayouts = maxVisits; //Also set this so it doesn't cap us either
}
if(numThreads < -1 || numThreads == 0)
throw StringError("numThreads: invalid value");
else if(numThreads == -1)
logger.write("No num threads specified on cmdline, using defaults in " + cfg.getFileName());
else {
params.numThreads = numThreads;
}
string searchRandSeed;
if(cfg.contains("searchRandSeed"))
searchRandSeed = cfg.getString("searchRandSeed");
else
searchRandSeed = Global::uint64ToString(seedRand.nextUInt64());
NNEvaluator* nnEval = NULL;
NNEvaluator* humanEval = NULL;
{
Setup::initializeSession(cfg);
int expectedConcurrentEvals = params.numThreads;
int defaultMaxBatchSize = std::max(8,((params.numThreads+3)/4)*4);
bool defaultRequireExactNNLen = true;
bool disableFP16 = false;
string expectedSha256 = "";
nnEval = Setup::initializeNNEvaluator(
modelFile,modelFile,expectedSha256,cfg,logger,seedRand,expectedConcurrentEvals,
board.x_size,board.y_size,defaultMaxBatchSize,defaultRequireExactNNLen,disableFP16,
Setup::SETUP_FOR_GTP
);
if(humanModelFile != "") {
humanEval = Setup::initializeNNEvaluator(
humanModelFile,humanModelFile,expectedSha256,cfg,logger,seedRand,expectedConcurrentEvals,
board.x_size,board.y_size,defaultMaxBatchSize,defaultRequireExactNNLen,disableFP16,
Setup::SETUP_FOR_GTP
);
}
}
logger.write("Loaded neural net");
{
bool rulesWereSupported;
Rules supportedRules = nnEval->getSupportedRules(initialRules,rulesWereSupported);
if(!rulesWereSupported) {
cout << "Warning: Rules " << initialRules << " from sgf not supported by neural net, using " << supportedRules << " instead" << endl;
initialRules = supportedRules;
}
}
for(int moveNum = moveNumStart; moveNum <= moveNumEnd; moveNum++) {
setUpBoardUsingRules(initialRules,moveNum);
// {
// sgf->setupInitialBoardAndHist(initialRules, board, nextPla, hist);
// vector<Move>& moves = sgf->moves;
// for(size_t i = 0; i<moves.size(); i++) {
// bool preventEncore = false;
// bool suc = hist.makeBoardMoveTolerant(board,moves[i].loc,moves[i].pla,preventEncore);
// assert(suc);
// nextPla = getOpp(moves[i].pla);
// MiscNNInputParams nnInputParams;
// nnInputParams.nnPolicyTemperature = 1.2f;
// NNResultBuf buf;
// bool skipCache = true;
// bool includeOwnerMap = false;
// nnEval->evaluate(board,hist,nextPla,nnInputParams,buf,skipCache,includeOwnerMap);
// NNOutput* nnOutput = buf.result.get();
// vector<double> probs;
// for(int y = 0; y<board.y_size; y++) {
// for(int x = 0; x<board.x_size; x++) {
// int pos = NNPos::xyToPos(x,y,nnOutput->nnXLen);
// float prob = nnOutput->policyProbs[pos];
// probs.push_back(prob);
// }
// }
// std::sort(probs.begin(),probs.end());
// cout << probs[probs.size()-1] << " " << probs[probs.size()-2] << " " << probs[probs.size()-3] << endl;
// }
// continue;
// }
// {
// sgf->setupInitialBoardAndHist(initialRules, board, nextPla, hist);
// vector<Move>& moves = sgf->moves;
// for(size_t i = 0; i<moves.size(); i++) {
// bool preventEncore = false;
// bool suc = hist.makeBoardMoveTolerant(board,moves[i].loc,moves[i].pla,preventEncore);
// assert(suc);
// nextPla = getOpp(moves[i].pla);
// MiscNNInputParams nnInputParams;
// nnInputParams.drawEquivalentWinsForWhite = params.drawEquivalentWinsForWhite;
// NNResultBuf buf;
// bool skipCache = true;
// bool includeOwnerMap = false;
// nnEval->evaluate(board,hist,nextPla,nnInputParams,buf,skipCache,includeOwnerMap);
// NNOutput* nnOutput = buf.result.get();
// cout << nnOutput->whiteWinProb << " " << nnOutput->shorttermWinlossError << " "
// << nnOutput->whiteScoreMean << " " << nnOutput->shorttermScoreError << endl;
// }
// continue;
// }
//Check for unused config keys
cfg.warnUnusedKeys(cerr,&logger);
Setup::maybeWarnHumanSLParams(params,nnEval,NULL,cerr,&logger);
if(rawNN) {
NNResultBuf buf;
bool skipCache = true;
bool includeOwnerMap = true;
MiscNNInputParams nnInputParams;
nnInputParams.drawEquivalentWinsForWhite = params.drawEquivalentWinsForWhite;
nnEval->evaluate(board,hist,nextPla,nnInputParams,buf,skipCache,includeOwnerMap);
cout << "Rules: " << hist.rules << endl;
cout << "Encore phase " << hist.encorePhase << endl;
Board::printBoard(cout, board, Board::NULL_LOC, &(hist.moveHistory));
buf.result->debugPrint(cout,board);
if(humanEval != NULL) {
humanEval->evaluate(board,hist,nextPla,nnInputParams,buf,skipCache,includeOwnerMap);
buf.result->debugPrint(cout,board);
}
continue;
}
AsyncBot* bot = new AsyncBot(params, nnEval, humanEval, &logger, searchRandSeed);
bot->setPosition(nextPla,board,hist);
if(hintLoc != "") {
bot->setRootHintLoc(Location::ofString(hintLoc,board));
}
if(avoidMoves != "") {
vector<Loc> avoidMoveLocs = Location::parseSequence(avoidMoves,board);
vector<int> avoidMoveUntilByLoc(Board::MAX_ARR_SIZE,0);
for(Loc loc: avoidMoveLocs)
avoidMoveUntilByLoc[loc] = 1;
bot->setAvoidMoveUntilByLoc(avoidMoveUntilByLoc,avoidMoveUntilByLoc);
}
//Print initial state----------------------------------------------------------------
const Search* search = bot->getSearchStopAndWait();
ostringstream sout;
sout << "Rules: " << hist.rules << endl;
sout << "Encore phase " << hist.encorePhase << endl;
Board::printBoard(sout, board, Board::NULL_LOC, &(hist.moveHistory));
if(options.branch_.size() > 0) {
Board copy = board;
BoardHistory copyHist = hist;
Player pla = nextPla;
for(int i = 0; i<options.branch_.size(); i++) {
Loc loc = options.branch_[i];
if(!copyHist.isLegal(copy,loc,pla)) {
cerr << board << endl;
cerr << "Branch Illegal move for " << PlayerIO::colorToChar(pla) << ": " << Location::toString(loc,board) << endl;
return 1;
}
copyHist.makeBoardMoveAssumeLegal(copy,loc,pla,NULL);
pla = getOpp(pla);
}
Board::printBoard(sout, copy, Board::NULL_LOC, &(copyHist.moveHistory));
}
sout << "\n";
logger.write(sout.str());
sout.clear();
//Search!----------------------------------------------------------------
ClockTimer timer;
nnEval->clearStats();
if(humanEval != NULL)
humanEval->clearStats();
Loc loc = bot->genMoveSynchronous(bot->getSearch()->rootPla,TimeControls());
(void)loc;
//Postprocess------------------------------------------------------------
if(printOwnership) {
sout << "Ownership map (ROOT position):\n";
search->printRootOwnershipMap(sout,perspective);
}
if(printRootNNValues) {
const NNOutput* nnOutput = search->rootNode->getNNOutput();
if(nnOutput != NULL) {
cout << "White win: " << nnOutput->whiteWinProb << endl;
cout << "White loss: " << nnOutput->whiteLossProb << endl;
cout << "White noresult: " << nnOutput->whiteNoResultProb << endl;
cout << "White score mean " << nnOutput->whiteScoreMean << endl;
cout << "White score stdev " << sqrt(max(0.0,(double)nnOutput->whiteScoreMeanSq - nnOutput->whiteScoreMean*nnOutput->whiteScoreMean)) << endl;
cout << "Var time left " << nnOutput->varTimeLeft << endl;
cout << "Shortterm winloss error " << nnOutput->shorttermWinlossError << endl;
cout << "Shortterm score error " << nnOutput->shorttermScoreError << endl;
}
}
// {
// ReportedSearchValues values;
// bool suc = search->getRootValues(values);
// if(!suc)
// cout << "Unsuccessful getting root values" << endl;
// else
// cout << values << endl;
// }
// {
// ReportedSearchValues values;
// bool suc = search->getPrunedRootValues(values);
// if(!suc)
// cout << "Unsuccessful getting pruned root values" << endl;
// else
// cout << values << endl;
// }
if(printSharpScore) {
double ret = 0.0;
bool suc = search->getSharpScore(NULL,ret);
assert(suc);
(void)suc;
cout << "White sharp score " << ret << endl;
}
if(printPolicy) {
auto doPrintPolicy = [&](const float* policyProbs, int nnXLen, int nnYLen) {
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);
double prob = policyProbs[pos];
if(prob < 0)
cout << " - " << " ";
else
cout << Global::strprintf("%5.2f",prob*100) << " ";
}
cout << endl;
}
double prob = policyProbs[NNPos::locToPos(Board::PASS_LOC,board.x_size,nnXLen,nnYLen)];
cout << "Pass " << Global::strprintf("%5.2f",prob*100) << endl;
};
const NNOutput* nnOutput = search->rootNode->getNNOutput();
if(nnOutput != NULL) {
const float* policyProbs = nnOutput->getPolicyProbsMaybeNoised();
cout << "Root policy: " << endl;
doPrintPolicy(policyProbs, nnOutput->nnXLen, nnOutput->nnYLen);
}
const NNOutput* humanOutput = search->rootNode->getHumanOutput();
if(humanOutput != NULL) {
const float* policyProbs = humanOutput->getPolicyProbsMaybeNoised();
cout << "Root human policy: " << endl;
doPrintPolicy(policyProbs, humanOutput->nnXLen, humanOutput->nnYLen);
}
}
if(printLogPolicy) {
auto doPrintLogPolicy = [&](const float* policyProbs, int nnXLen, int nnYLen) {
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);
double prob = policyProbs[pos];
if(prob < 0)
cout << " _ " << " ";
else
cout << Global::strprintf("%+5.2f",log(prob)) << " ";
}
cout << endl;
}
double prob = policyProbs[NNPos::locToPos(Board::PASS_LOC,board.x_size,nnXLen,nnYLen)];
cout << "Pass " << Global::strprintf("%+5.2f",log(prob)) << endl;
};
const NNOutput* nnOutput = search->rootNode->getNNOutput();
if(nnOutput != NULL) {
const float* policyProbs = nnOutput->getPolicyProbsMaybeNoised();
cout << "Root policy: " << endl;
doPrintLogPolicy(policyProbs, nnOutput->nnXLen, nnOutput->nnYLen);
}
const NNOutput* humanOutput = search->rootNode->getHumanOutput();
if(humanOutput != NULL) {
const float* policyProbs = humanOutput->getPolicyProbsMaybeNoised();
cout << "Root human policy: " << endl;
doPrintLogPolicy(policyProbs, humanOutput->nnXLen, humanOutput->nnYLen);
}
}
if(printDirichletShape) {
const NNOutput* nnOutput = search->rootNode->getNNOutput();
if(nnOutput != NULL) {
const float* policyProbs = nnOutput->getPolicyProbsMaybeNoised();
double alphaDistr[NNPos::MAX_NN_POLICY_SIZE];
int policySize = nnOutput->nnXLen * nnOutput->nnYLen;
Search::computeDirichletAlphaDistribution(policySize, policyProbs, alphaDistr);
cout << "Dirichlet alphas with 10.83 total concentration: " << endl;
for(int y = 0; y<board.y_size; y++) {
for(int x = 0; x<board.x_size; x++) {
int pos = NNPos::xyToPos(x,y,nnOutput->nnXLen);
double alpha = alphaDistr[pos];
if(alpha < 0)
cout << " - " << " ";
else
cout << Global::strprintf("%5.4f",alpha * 10.83) << " ";
}
cout << endl;
}
double alpha = alphaDistr[NNPos::locToPos(Board::PASS_LOC,board.x_size,nnOutput->nnXLen,nnOutput->nnYLen)];
cout << "Pass " << Global::strprintf("%5.2f",alpha * 10.83) << endl;
}
}
if(printScoreNow) {
sout << "Score now (ROOT position):\n";
BoardHistory copyHist(hist);
Color area[Board::MAX_ARR_SIZE];
copyHist.endAndScoreGameNow(board,area);
for(int y = 0; y<board.y_size; y++) {
for(int x = 0; x<board.x_size; x++) {
Loc l = Location::getLoc(x,y,board.x_size);
sout << PlayerIO::colorToChar(area[l]);
}
sout << endl;
}
sout << endl;
sout << "Komi: " << copyHist.rules.komi << endl;
sout << "WBonus: " << copyHist.whiteBonusScore << endl;
sout << "Final: "; WriteSgf::printGameResult(sout, copyHist); sout << endl;
}
if(printRootEndingBonus) {
sout << "Ending bonus (ROOT position)\n";
search->printRootEndingScoreValueBonus(sout);
}
sout << "Time taken: " << timer.getSeconds() << "\n";
sout << "Root visits: " << search->getRootVisits() << "\n";
sout << "NN rows: " << nnEval->numRowsProcessed() << endl;
sout << "NN batches: " << nnEval->numBatchesProcessed() << endl;
sout << "NN avg batch size: " << nnEval->averageProcessedBatchSize() << endl;
std::vector<SearchNode*> nodes = bot->getSearchStopAndWait()->enumerateTreePostOrder();
sout << "True number of tree nodes: " << nodes.size() << endl;
sout << "PV: ";
search->printPV(sout, search->rootNode, 25);
sout << "\n";
sout << "Tree:\n";
search->printTree(sout, search->rootNode, options, perspective);
logger.write(sout.str());
if(printLead) {
BoardHistory hist2(hist);
double lead = PlayUtils::computeLead(
bot->getSearchStopAndWait(), NULL, board, hist2, nextPla,
20, OtherGameProperties()
);
cout << "LEAD: " << lead << endl;
}
if(printGraph) {
std::reverse(nodes.begin(),nodes.end());
std::map<SearchNode*,size_t> idxOfNode;
for(size_t nodeIdx = 0; nodeIdx<nodes.size(); nodeIdx++)
idxOfNode[nodes[nodeIdx]] = nodeIdx;
for(int nodeIdx = 0; nodeIdx<nodes.size(); nodeIdx++) {
SearchNode& node = *(nodes[nodeIdx]);
SearchNodeChildrenReference children = node.getChildren();
int childrenCapacity = children.getCapacity();
for(int i = 0; i<childrenCapacity; i++) {
SearchNode* child = children[i].getIfAllocated();
if(child == NULL)
break;
cout << nodeIdx << " -> " << idxOfNode[child] << "\n";
}
}
cout << endl;
}
if(printJson) {
int analysisPVLen = 7;
bool preventEncore = false;
bool includePolicy = printPolicy;
bool includeOwnership = printOwnership;
bool includeOwnershipStdev = false;
bool includeMovesOwnership = false;
bool includeMovesOwnershipStdev = false;
bool includePVVisits = true;
nlohmann::json ret;
bool includeNoResultValue = false;
bool suc = search->getAnalysisJson(
perspective,
analysisPVLen,
preventEncore,
includePolicy,
includeOwnership,
includeOwnershipStdev,
includeMovesOwnership,
includeMovesOwnershipStdev,
includePVVisits,
includeNoResultValue,
ret
);
if(suc) {
cout << ret << endl;
}
}
if(dumpNpzInputTo != "") {
bool inputsUseNHWC = false;
int nnXLen = nnEval->getNNXLen();
int nnYLen = nnEval->getNNYLen();
int modelVersion = nnEval->getModelVersion();
int numSpatialFeatures = NNModelVersion::getNumSpatialFeatures(modelVersion);
int numGlobalFeatures = NNModelVersion::getNumGlobalFeatures(modelVersion);
NumpyBuffer<float> binaryInputNCHW(std::vector<int64_t>({1,numSpatialFeatures,nnXLen,nnYLen}));
NumpyBuffer<float> globalInputNC(std::vector<int64_t>({1,numGlobalFeatures}));
MiscNNInputParams nnInputParams;
nnInputParams.symmetry = 0;
nnInputParams.policyOptimism = params.rootPolicyOptimism;
NNInputs::fillRowV7(board, hist, nextPla, nnInputParams, nnXLen, nnYLen, inputsUseNHWC, binaryInputNCHW.data, globalInputNC.data);
ZipFile zipFile(dumpNpzInputTo);
uint64_t numBytes;
numBytes = binaryInputNCHW.prepareHeaderWithNumRows(1);
zipFile.writeBuffer("binaryInputNCHW", binaryInputNCHW.dataIncludingHeader, numBytes);
numBytes = globalInputNC.prepareHeaderWithNumRows(1);
zipFile.writeBuffer("globalInputNC", globalInputNC.dataIncludingHeader, numBytes);
zipFile.close();
cout << "Wrote to " << dumpNpzInputTo << endl;
NNResultBuf buf;
bool skipCache = true;
bool includeOwnerMap = true;
nnEval->evaluate(board,hist,nextPla,nnInputParams,buf,skipCache,includeOwnerMap);
buf.result->debugPrint(cout,board);
}
delete bot;
}
delete nnEval;
if(humanEval != NULL)
delete humanEval;
NeuralNet::globalCleanup();
ScoreValue::freeTables();
return 0;
}