/
nninputs.cpp
2916 lines (2596 loc) · 109 KB
/
nninputs.cpp
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 "../neuralnet/nninputs.h"
using namespace std;
int NNPos::xyToPos(int x, int y, int nnXLen) {
return y * nnXLen + x;
}
int NNPos::locToPos(Loc loc, int boardXSize, int nnXLen, int nnYLen) {
if(loc == Board::PASS_LOC)
return nnXLen * nnYLen;
else if(loc == Board::NULL_LOC)
return nnXLen * (nnYLen + 1);
return Location::getY(loc,boardXSize) * nnXLen + Location::getX(loc,boardXSize);
}
Loc NNPos::posToLoc(int pos, int boardXSize, int boardYSize, int nnXLen, int nnYLen) {
if(pos == nnXLen * nnYLen)
return Board::PASS_LOC;
int x = pos % nnXLen;
int y = pos / nnXLen;
if(x < 0 || x >= boardXSize || y < 0 || y >= boardYSize)
return Board::NULL_LOC;
return Location::getLoc(x,y,boardXSize);
}
int NNPos::getPassPos(int nnXLen, int nnYLen) {
return nnXLen * nnYLen;
}
bool NNPos::isPassPos(int pos, int nnXLen, int nnYLen) {
return pos == nnXLen * nnYLen;
}
int NNPos::getPolicySize(int nnXLen, int nnYLen) {
return nnXLen * nnYLen + 1;
}
//-----------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
const Hash128 MiscNNInputParams::ZOBRIST_CONSERVATIVE_PASS =
Hash128(0x0c2b96f4b8ae2da9ULL, 0x5a14dee208fec0edULL);
const Hash128 MiscNNInputParams::ZOBRIST_FRIENDLY_PASS =
Hash128(0xe750505a66f7c5c2ULL, 0x7a83139bf632d6c4ULL);
const Hash128 MiscNNInputParams::ZOBRIST_PASSING_HACKS =
Hash128(0x9c89f4fd3ce5a92cULL, 0x268c9aff79c64d00ULL);
const Hash128 MiscNNInputParams::ZOBRIST_PLAYOUT_DOUBLINGS =
Hash128(0xa5e6114d380bfc1dULL, 0x4160557f1222f4adULL);
const Hash128 MiscNNInputParams::ZOBRIST_NN_POLICY_TEMP =
Hash128(0xebcbdfeec6f4334bULL, 0xb85e43ee243b5ad2ULL);
const Hash128 MiscNNInputParams::ZOBRIST_AVOID_MYTDAGGER_HACK =
Hash128(0x612d22ec402ce054ULL, 0x0db915c49de527aeULL);
const Hash128 MiscNNInputParams::ZOBRIST_POLICY_OPTIMISM =
Hash128(0x88415c85c2801955ULL, 0x39bdf76b2aaa5eb1ULL);
const Hash128 MiscNNInputParams::ZOBRIST_ZERO_HISTORY =
Hash128(0x78f02afdd1aa4910ULL, 0xda78d550486fe978ULL);
//-----------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
double ScoreValue::whiteWinsOfWinner(Player winner, double drawEquivalentWinsForWhite) {
if(winner == P_WHITE)
return 1.0;
else if(winner == P_BLACK)
return 0.0;
assert(winner == C_EMPTY);
return drawEquivalentWinsForWhite;
}
static const double twoOverPi = 0.63661977236758134308;
static const double piOverTwo = 1.57079632679489661923;
double ScoreValue::whiteScoreDrawAdjust(double finalWhiteMinusBlackScore, double drawEquivalentWinsForWhite, const BoardHistory& hist) {
return finalWhiteMinusBlackScore + hist.whiteKomiAdjustmentForDraws(drawEquivalentWinsForWhite);
}
double ScoreValue::whiteScoreValueOfScoreSmooth(
double finalWhiteMinusBlackScore,
double center,
double scale,
double drawEquivalentWinsForWhite,
double sqrtBoardArea,
const BoardHistory& hist)
{
double adjustedScore = finalWhiteMinusBlackScore + hist.whiteKomiAdjustmentForDraws(drawEquivalentWinsForWhite) - center;
return atan(adjustedScore / (scale * sqrtBoardArea)) * twoOverPi;
}
double ScoreValue::whiteScoreValueOfScoreSmoothNoDrawAdjust(double finalWhiteMinusBlackScore, double center, double scale, double sqrtBoardArea) {
double adjustedScore = finalWhiteMinusBlackScore - center;
return atan(adjustedScore / (scale * sqrtBoardArea)) * twoOverPi;
}
double ScoreValue::whiteDScoreValueDScoreSmoothNoDrawAdjust(double finalWhiteMinusBlackScore, double center, double scale, double sqrtBoardArea) {
double adjustedScore = finalWhiteMinusBlackScore - center;
double scaleFactor;
scaleFactor = scale * sqrtBoardArea;
return scaleFactor / (scaleFactor * scaleFactor + adjustedScore * adjustedScore) * twoOverPi;
}
static double inverse_atan(double x) {
if(x >= piOverTwo - 1e-6) return 1e6;
if(x <= -piOverTwo + 1e-6) return -1e6;
return tan(x);
}
double ScoreValue::approxWhiteScoreOfScoreValueSmooth(double scoreValue, double center, double scale, double sqrtBoardArea) {
assert(scoreValue >= -1 && scoreValue <= 1);
double scoreUnscaled = inverse_atan(scoreValue * piOverTwo);
return scoreUnscaled * (scale * sqrtBoardArea) + center;
}
double ScoreValue::whiteScoreMeanSqOfScoreGridded(double finalWhiteMinusBlackScore, double drawEquivalentWinsForWhite) {
assert((int)(finalWhiteMinusBlackScore * 2) == finalWhiteMinusBlackScore * 2);
bool finalScoreIsInteger = ((int)finalWhiteMinusBlackScore == finalWhiteMinusBlackScore);
if(!finalScoreIsInteger)
return finalWhiteMinusBlackScore * finalWhiteMinusBlackScore;
double lower = finalWhiteMinusBlackScore - 0.5;
double upper = finalWhiteMinusBlackScore + 0.5;
double lowerSq = lower * lower;
double upperSq = upper * upper;
return lowerSq + (upperSq - lowerSq) * drawEquivalentWinsForWhite;
}
static bool scoreValueTablesInitialized = false;
static double* expectedSVTable = NULL;
static const int svTableAssumedBSize = NNPos::MAX_BOARD_LEN;
static const int svTableMeanRadius = svTableAssumedBSize*svTableAssumedBSize + NNPos::EXTRA_SCORE_DISTR_RADIUS;
static const int svTableMeanLen = svTableMeanRadius*2;
static const int svTableStdevLen = svTableAssumedBSize*svTableAssumedBSize + NNPos::EXTRA_SCORE_DISTR_RADIUS;
void ScoreValue::freeTables() {
if(scoreValueTablesInitialized) {
delete[] expectedSVTable;
expectedSVTable = NULL;
scoreValueTablesInitialized = false;
}
}
void ScoreValue::initTables() {
assert(!scoreValueTablesInitialized);
expectedSVTable = new double[svTableMeanLen*svTableStdevLen];
//Precompute normal PDF
const int stepsPerUnit = 10; //Must be divisible by 2. This is both the number of segments that we divide points into, and that we divide stdevs into
const int boundStdevs = 5;
int minStdevSteps = -boundStdevs*stepsPerUnit;
int maxStdevSteps = boundStdevs*stepsPerUnit;
double* normalPDF = new double[(maxStdevSteps-minStdevSteps)+1];
for(int i = minStdevSteps; i <= maxStdevSteps; i++) {
double xInStdevs = (double)i / stepsPerUnit;
double w = exp(-0.5 * xInStdevs * xInStdevs);
normalPDF[i-minStdevSteps] = w;
}
//Precompute scorevalue at increments of 1/stepsPerUnit points
int minSVSteps = - (svTableMeanRadius*stepsPerUnit + stepsPerUnit/2 + boundStdevs * svTableStdevLen * stepsPerUnit);
int maxSVSteps = -minSVSteps;
double* svPrecomp = new double[(maxSVSteps-minSVSteps)+1];
for(int i = minSVSteps; i <= maxSVSteps; i++) {
double mean = (double)i / stepsPerUnit;
double sv = whiteScoreValueOfScoreSmoothNoDrawAdjust(mean, 0.0, 1.0, svTableAssumedBSize);
svPrecomp[i-minSVSteps] = sv;
}
//Perform numeric integration
for(int meanIdx = 0; meanIdx < svTableMeanLen; meanIdx++) {
int meanSteps = (meanIdx - svTableMeanRadius) * stepsPerUnit - stepsPerUnit/2;
for(int stdevIdx = 0; stdevIdx < svTableStdevLen; stdevIdx++) {
double wSum = 0.0;
double wsvSum = 0.0;
for(int i = minStdevSteps; i <= maxStdevSteps; i++) {
int xSteps = meanSteps + stdevIdx * i;
double w = normalPDF[i-minStdevSteps];
assert(xSteps >= minSVSteps && xSteps <= maxSVSteps);
double sv = svPrecomp[xSteps-minSVSteps];
wSum += w;
wsvSum += w*sv;
}
expectedSVTable[meanIdx*svTableStdevLen + stdevIdx] = wsvSum / wSum;
}
}
delete[] normalPDF;
delete[] svPrecomp;
scoreValueTablesInitialized = true;
}
double ScoreValue::expectedWhiteScoreValue(double whiteScoreMean, double whiteScoreStdev, double center, double scale, double sqrtBoardArea) {
assert(scoreValueTablesInitialized);
double scaleFactor = (double)svTableAssumedBSize / (scale * sqrtBoardArea);
double meanScaled = (whiteScoreMean - center) * scaleFactor;
double stdevScaled = whiteScoreStdev * scaleFactor;
double meanRounded = round(meanScaled);
double stdevFloored = floor(stdevScaled);
int meanIdx0 = (int)meanRounded + svTableMeanRadius;
int stdevIdx0 = (int)stdevFloored;
int meanIdx1 = meanIdx0+1;
int stdevIdx1 = stdevIdx0+1;
if(meanIdx0 < 0) { meanIdx0 = 0; meanIdx1 = 0; }
if(meanIdx1 >= svTableMeanLen) { meanIdx0 = svTableMeanLen-1; meanIdx1 = svTableMeanLen-1; }
assert(stdevIdx0 >= 0);
if(stdevIdx1 >= svTableStdevLen) { stdevIdx0 = svTableStdevLen-1; stdevIdx1 = svTableStdevLen-1; }
double lambdaMean = meanScaled - meanRounded + 0.5;
double lambdaStdev = stdevScaled - stdevFloored;
double a00 = expectedSVTable[meanIdx0*svTableStdevLen + stdevIdx0];
double a01 = expectedSVTable[meanIdx0*svTableStdevLen + stdevIdx1];
double a10 = expectedSVTable[meanIdx1*svTableStdevLen + stdevIdx0];
double a11 = expectedSVTable[meanIdx1*svTableStdevLen + stdevIdx1];
double b0 = a00 + lambdaStdev*(a01-a00);
double b1 = a10 + lambdaStdev*(a11-a10);
return b0 + lambdaMean*(b1-b0);
}
double ScoreValue::getScoreStdev(double scoreMean, double scoreMeanSq) {
double variance = scoreMeanSq - scoreMean * scoreMean;
if(variance <= 0.0)
return 0.0;
return sqrt(variance);
}
//-----------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
void NNInputs::fillScoring(
const Board& board,
const Color* area,
bool groupTax,
float* scoring
) {
if(!groupTax) {
std::fill(scoring, scoring + Board::MAX_ARR_SIZE, 0.0f);
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);
Color areaColor = area[loc];
if(areaColor == P_BLACK)
scoring[loc] = -1.0f;
else if(areaColor == P_WHITE)
scoring[loc] = 1.0f;
else {
assert(areaColor == C_EMPTY);
scoring[loc] = 0;
}
}
}
}
else {
bool visited[Board::MAX_ARR_SIZE];
Loc queue[Board::MAX_ARR_SIZE];
std::fill(visited, visited + Board::MAX_ARR_SIZE, false);
std::fill(scoring, scoring + Board::MAX_ARR_SIZE, 0.0f);
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(visited[loc])
continue;
Color areaColor = area[loc];
if(areaColor == P_BLACK || areaColor == P_WHITE) {
float fullValue = areaColor == P_WHITE ? 1.0f : -1.0f;
int queueHead = 0;
int queueTail = 1;
queue[0] = loc;
visited[loc] = true;
//First, count how many empty or opp locations there are
int territoryCount = 0;
while(queueHead < queueTail) {
Loc next = queue[queueHead];
queueHead++;
if(board.colors[next] != areaColor)
territoryCount++;
//Push adjacent locations on to queue
for(int i = 0; i<4; i++) {
Loc adj = next + board.adj_offsets[i];
if(area[adj] == areaColor && !visited[adj]) {
queue[queueTail] = adj;
queueTail++;
visited[adj] = true;
}
}
}
//Then, actually fill values
float territoryValue = territoryCount <= 2 ? 0.0f : fullValue * (territoryCount - 2.0f) / territoryCount;
for(int j = 0; j<queueTail; j++) {
Loc next = queue[j];
queueHead++;
if(board.colors[next] != areaColor)
scoring[next] = territoryValue;
else
scoring[next] = fullValue;
}
}
else {
assert(areaColor == C_EMPTY);
scoring[loc] = 0;
}
}
}
}
}
//-----------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
NNOutput::NNOutput()
:whiteOwnerMap(NULL),noisedPolicyProbs(NULL)
{}
NNOutput::NNOutput(const NNOutput& other) {
nnHash = other.nnHash;
whiteWinProb = other.whiteWinProb;
whiteLossProb = other.whiteLossProb;
whiteNoResultProb = other.whiteNoResultProb;
whiteScoreMean = other.whiteScoreMean;
whiteScoreMeanSq = other.whiteScoreMeanSq;
whiteLead = other.whiteLead;
varTimeLeft = other.varTimeLeft;
shorttermWinlossError = other.shorttermWinlossError;
shorttermScoreError = other.shorttermScoreError;
nnXLen = other.nnXLen;
nnYLen = other.nnYLen;
if(other.whiteOwnerMap != NULL) {
whiteOwnerMap = new float[nnXLen * nnYLen];
std::copy(other.whiteOwnerMap, other.whiteOwnerMap + nnXLen * nnYLen, whiteOwnerMap);
}
else
whiteOwnerMap = NULL;
if(other.noisedPolicyProbs != NULL) {
noisedPolicyProbs = new float[NNPos::MAX_NN_POLICY_SIZE];
std::copy(other.noisedPolicyProbs, other.noisedPolicyProbs + NNPos::MAX_NN_POLICY_SIZE, noisedPolicyProbs);
}
else
noisedPolicyProbs = NULL;
std::copy(other.policyProbs, other.policyProbs+NNPos::MAX_NN_POLICY_SIZE, policyProbs);
policyOptimismUsed = other.policyOptimismUsed;
}
NNOutput::NNOutput(const vector<shared_ptr<NNOutput>>& others) {
assert(others.size() < 1000000);
int len = (int)others.size();
float floatLen = (float)len;
assert(len > 0);
for(int i = 1; i<len; i++) {
assert(others[i]->nnHash == others[0]->nnHash);
}
nnHash = others[0]->nnHash;
whiteWinProb = 0.0f;
whiteLossProb = 0.0f;
whiteNoResultProb = 0.0f;
whiteScoreMean = 0.0f;
whiteScoreMeanSq = 0.0f;
whiteLead = 0.0f;
varTimeLeft = 0.0f;
shorttermWinlossError = 0.0f;
shorttermScoreError = 0.0f;
for(int i = 0; i<len; i++) {
const NNOutput& other = *(others[i]);
whiteWinProb += other.whiteWinProb;
whiteLossProb += other.whiteLossProb;
whiteNoResultProb += other.whiteNoResultProb;
whiteScoreMean += other.whiteScoreMean;
whiteScoreMeanSq += other.whiteScoreMeanSq;
whiteLead += other.whiteLead;
varTimeLeft += other.varTimeLeft;
shorttermWinlossError += other.shorttermWinlossError;
shorttermScoreError += other.shorttermScoreError;
}
whiteWinProb /= floatLen;
whiteLossProb /= floatLen;
whiteNoResultProb /= floatLen;
whiteScoreMean /= floatLen;
whiteScoreMeanSq /= floatLen;
whiteLead /= floatLen;
varTimeLeft /= floatLen;
shorttermWinlossError /= floatLen;
shorttermScoreError /= floatLen;
nnXLen = others[0]->nnXLen;
nnYLen = others[0]->nnYLen;
{
float whiteOwnerMapCount = 0.0f;
whiteOwnerMap = NULL;
for(int i = 0; i<len; i++) {
const NNOutput& other = *(others[i]);
if(other.whiteOwnerMap != NULL) {
if(whiteOwnerMap == NULL) {
whiteOwnerMap = new float[nnXLen * nnYLen];
std::fill(whiteOwnerMap, whiteOwnerMap + nnXLen * nnYLen, 0.0f);
}
whiteOwnerMapCount += 1.0f;
for(int pos = 0; pos<nnXLen*nnYLen; pos++)
whiteOwnerMap[pos] += other.whiteOwnerMap[pos];
}
}
if(whiteOwnerMap != NULL) {
assert(whiteOwnerMapCount > 0);
for(int pos = 0; pos<nnXLen*nnYLen; pos++)
whiteOwnerMap[pos] /= whiteOwnerMapCount;
}
}
noisedPolicyProbs = NULL;
//For technical correctness in case of impossibly rare hash collisions:
//Just give up if they don't all match in move legality
{
bool mismatch = false;
std::fill(policyProbs, policyProbs + NNPos::MAX_NN_POLICY_SIZE, 0.0f);
for(int i = 0; i<len; i++) {
const NNOutput& other = *(others[i]);
for(int pos = 0; pos<NNPos::MAX_NN_POLICY_SIZE; pos++) {
if(i > 0 && (policyProbs[pos] < 0) != (other.policyProbs[pos] < 0))
mismatch = true;
policyProbs[pos] += other.policyProbs[pos];
}
}
//In case of mismatch, just take the first one
//This should basically never happen, only on true hash collisions
if(mismatch) {
const NNOutput& other = *(others[0]);
std::copy(other.policyProbs, other.policyProbs + NNPos::MAX_NN_POLICY_SIZE, policyProbs);
}
else {
for(int pos = 0; pos<NNPos::MAX_NN_POLICY_SIZE; pos++)
policyProbs[pos] /= floatLen;
}
}
{
bool allOptimismsMatch = true;
for(int i = 1; i<len; i++) {
if(others[i]->policyOptimismUsed != others[0]->policyOptimismUsed) {
allOptimismsMatch = false;
break;
}
}
if(allOptimismsMatch) {
policyOptimismUsed = others[0]->policyOptimismUsed;
}
else {
policyOptimismUsed = 0.0;
for(int i = 0; i<len; i++) {
policyOptimismUsed += others[i]->policyOptimismUsed / (float)len;
}
}
}
}
NNOutput& NNOutput::operator=(const NNOutput& other) {
if(&other == this)
return *this;
nnHash = other.nnHash;
whiteWinProb = other.whiteWinProb;
whiteLossProb = other.whiteLossProb;
whiteNoResultProb = other.whiteNoResultProb;
whiteScoreMean = other.whiteScoreMean;
whiteScoreMeanSq = other.whiteScoreMeanSq;
whiteLead = other.whiteLead;
varTimeLeft = other.varTimeLeft;
shorttermWinlossError = other.shorttermWinlossError;
shorttermScoreError = other.shorttermScoreError;
nnXLen = other.nnXLen;
nnYLen = other.nnYLen;
if(whiteOwnerMap != NULL)
delete[] whiteOwnerMap;
if(other.whiteOwnerMap != NULL) {
whiteOwnerMap = new float[nnXLen * nnYLen];
std::copy(other.whiteOwnerMap, other.whiteOwnerMap + nnXLen * nnYLen, whiteOwnerMap);
}
else
whiteOwnerMap = NULL;
if(noisedPolicyProbs != NULL)
delete[] noisedPolicyProbs;
if(other.noisedPolicyProbs != NULL) {
noisedPolicyProbs = new float[NNPos::MAX_NN_POLICY_SIZE];
std::copy(other.noisedPolicyProbs, other.noisedPolicyProbs + NNPos::MAX_NN_POLICY_SIZE, noisedPolicyProbs);
}
else
noisedPolicyProbs = NULL;
std::copy(other.policyProbs, other.policyProbs+NNPos::MAX_NN_POLICY_SIZE, policyProbs);
policyOptimismUsed = other.policyOptimismUsed;
return *this;
}
NNOutput::~NNOutput() {
if(whiteOwnerMap != NULL) {
delete[] whiteOwnerMap;
whiteOwnerMap = NULL;
}
if(noisedPolicyProbs != NULL) {
delete[] noisedPolicyProbs;
noisedPolicyProbs = NULL;
}
}
void NNOutput::debugPrint(ostream& out, const Board& board) {
out << "Win " << Global::strprintf("%.2fc",whiteWinProb*100) << endl;
out << "Loss " << Global::strprintf("%.2fc",whiteLossProb*100) << endl;
out << "NoResult " << Global::strprintf("%.2fc",whiteNoResultProb*100) << endl;
out << "ScoreMean " << Global::strprintf("%.2f",whiteScoreMean) << endl;
out << "ScoreMeanSq " << Global::strprintf("%.1f",whiteScoreMeanSq) << endl;
out << "Lead " << Global::strprintf("%.2f",whiteLead) << endl;
out << "VarTimeLeft " << Global::strprintf("%.1f",varTimeLeft) << endl;
out << "STWinlossError " << Global::strprintf("%.2fc",shorttermWinlossError*100) << endl;
out << "STScoreError " << Global::strprintf("%.2f",shorttermScoreError) << endl;
out << "OptimismUsed " << Global::strprintf("%.2f",policyOptimismUsed) << endl;
out << "Policy" << endl;
out << "Pass" << Global::strprintf("%4d ", (int)round(policyProbs[NNPos::getPassPos(nnXLen,nnYLen)] * 1000)) << 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,nnXLen);
float prob = policyProbs[pos];
if(prob < 0)
out << " - ";
else
out << Global::strprintf("%4d ", (int)round(prob * 1000));
}
out << endl;
}
if(whiteOwnerMap != NULL) {
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);
float whiteOwn = whiteOwnerMap[pos];
out << Global::strprintf("%5d ", (int)round(whiteOwn * 1000));
}
out << endl;
}
out << endl;
}
}
//-------------------------------------------------------------------------------------------------------------
static void copyWithSymmetry(const float* src, float* dst, int nSize, int hSize, int wSize, int cSize, bool useNHWC, int symmetry, bool reverse) {
bool transpose = (symmetry & 0x4) != 0 && hSize == wSize;
bool flipX = (symmetry & 0x2) != 0;
bool flipY = (symmetry & 0x1) != 0;
if(transpose && !reverse)
std::swap(flipX,flipY);
if(useNHWC) {
int nStride = hSize * wSize * cSize;
int hStride = wSize * cSize;
int wStride = cSize;
int hBaseNew = 0; int hStrideNew = hStride;
int wBaseNew = 0; int wStrideNew = wStride;
if(flipY) { hBaseNew = (hSize-1) * hStrideNew; hStrideNew = -hStrideNew; }
if(flipX) { wBaseNew = (wSize-1) * wStrideNew; wStrideNew = -wStrideNew; }
if(transpose)
std::swap(hStrideNew,wStrideNew);
for(int n = 0; n<nSize; n++) {
for(int h = 0; h<hSize; h++) {
int nhOld = n * nStride + h*hStride;
int nhNew = n * nStride + hBaseNew + h*hStrideNew;
for(int w = 0; w<wSize; w++) {
int nhwOld = nhOld + w*wStride;
int nhwNew = nhNew + wBaseNew + w*wStrideNew;
for(int c = 0; c<cSize; c++) {
dst[nhwNew + c] = src[nhwOld + c];
}
}
}
}
}
else {
int ncSize = nSize * cSize;
int ncStride = hSize * wSize;
int hStride = wSize;
int wStride = 1;
int hBaseNew = 0; int hStrideNew = hStride;
int wBaseNew = 0; int wStrideNew = wStride;
if(flipY) { hBaseNew = (hSize-1) * hStrideNew; hStrideNew = -hStrideNew; }
if(flipX) { wBaseNew = (wSize-1) * wStrideNew; wStrideNew = -wStrideNew; }
if(transpose)
std::swap(hStrideNew,wStrideNew);
for(int nc = 0; nc<ncSize; nc++) {
for(int h = 0; h<hSize; h++) {
int nchOld = nc * ncStride + h*hStride;
int nchNew = nc * ncStride + hBaseNew + h*hStrideNew;
for(int w = 0; w<wSize; w++) {
int nchwOld = nchOld + w*wStride;
int nchwNew = nchNew + wBaseNew + w*wStrideNew;
dst[nchwNew] = src[nchwOld];
}
}
}
}
}
void SymmetryHelpers::copyInputsWithSymmetry(const float* src, float* dst, int nSize, int hSize, int wSize, int cSize, bool useNHWC, int symmetry) {
copyWithSymmetry(src, dst, nSize, hSize, wSize, cSize, useNHWC, symmetry, false);
}
void SymmetryHelpers::copyOutputsWithSymmetry(const float* src, float* dst, int nSize, int hSize, int wSize, int symmetry) {
copyWithSymmetry(src, dst, nSize, hSize, wSize, 1, false, symmetry, true);
}
int SymmetryHelpers::invert(int symmetry) {
if(symmetry == 5)
return 6;
if(symmetry == 6)
return 5;
return symmetry;
}
int SymmetryHelpers::compose(int firstSymmetry, int nextSymmetry) {
if(isTranspose(firstSymmetry))
nextSymmetry = (nextSymmetry & 0x4) | ((nextSymmetry & 0x2) >> 1) | ((nextSymmetry & 0x1) << 1);
return firstSymmetry ^ nextSymmetry;
}
int SymmetryHelpers::compose(int firstSymmetry, int nextSymmetry, int nextNextSymmetry) {
return compose(compose(firstSymmetry,nextSymmetry),nextNextSymmetry);
}
Loc SymmetryHelpers::getSymLoc(int x, int y, int xSize, int ySize, int symmetry) {
bool transpose = (symmetry & 0x4) != 0;
bool flipX = (symmetry & 0x2) != 0;
bool flipY = (symmetry & 0x1) != 0;
if(flipX) { x = xSize - x - 1; }
if(flipY) { y = ySize - y - 1; }
if(transpose)
std::swap(x,y);
return Location::getLoc(x,y,transpose ? ySize : xSize);
}
Loc SymmetryHelpers::getSymLoc(int x, int y, const Board& board, int symmetry) {
return getSymLoc(x,y,board.x_size,board.y_size,symmetry);
}
Loc SymmetryHelpers::getSymLoc(Loc loc, const Board& board, int symmetry) {
if(loc == Board::NULL_LOC || loc == Board::PASS_LOC)
return loc;
return getSymLoc(Location::getX(loc,board.x_size), Location::getY(loc,board.x_size), board, symmetry);
}
Loc SymmetryHelpers::getSymLoc(Loc loc, int xSize, int ySize, int symmetry) {
if(loc == Board::NULL_LOC || loc == Board::PASS_LOC)
return loc;
return getSymLoc(Location::getX(loc,xSize), Location::getY(loc,xSize), xSize, ySize, symmetry);
}
Board SymmetryHelpers::getSymBoard(const Board& board, int symmetry) {
bool transpose = (symmetry & 0x4) != 0;
bool flipX = (symmetry & 0x2) != 0;
bool flipY = (symmetry & 0x1) != 0;
Board symBoard(
transpose ? board.y_size : board.x_size,
transpose ? board.x_size : board.y_size
);
Loc symKoLoc = Board::NULL_LOC;
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);
int symX = flipX ? board.x_size - x - 1 : x;
int symY = flipY ? board.y_size - y - 1 : y;
if(transpose)
std::swap(symX,symY);
Loc symLoc = Location::getLoc(symX,symY,symBoard.x_size);
bool suc = symBoard.setStoneFailIfNoLibs(symLoc,board.colors[loc]);
assert(suc);
(void)suc;
if(loc == board.ko_loc)
symKoLoc = symLoc;
}
}
//Set only at the end because otherwise setStoneFailIfNoLibs clears it.
if(symKoLoc != Board::NULL_LOC)
symBoard.setSimpleKoLoc(symKoLoc);
return symBoard;
}
void SymmetryHelpers::markDuplicateMoveLocs(
const Board& board,
const BoardHistory& hist,
const std::vector<int>* onlySymmetries,
const std::vector<int>& avoidMoves,
bool* isSymDupLoc,
std::vector<int>& validSymmetries
) {
std::fill(isSymDupLoc, isSymDupLoc + Board::MAX_ARR_SIZE, false);
validSymmetries.clear();
validSymmetries.reserve(SymmetryHelpers::NUM_SYMMETRIES);
validSymmetries.push_back(0);
//The board should never be considered symmetric if any moves are banned by ko or superko
if(board.ko_loc != Board::NULL_LOC)
return;
for(int y = 0; y < board.y_size; y++) {
for(int x = 0; x < board.x_size; x++) {
if(hist.superKoBanned[Location::getLoc(x, y, board.x_size)])
return;
}
}
//If board has different sizes of x and y, we will not search symmetries involved with transpose.
int symmetrySearchUpperBound = board.x_size == board.y_size ? SymmetryHelpers::NUM_SYMMETRIES : SymmetryHelpers::NUM_SYMMETRIES_WITHOUT_TRANSPOSE;
for(int symmetry = 1; symmetry < symmetrySearchUpperBound; symmetry++) {
if(onlySymmetries != NULL && !contains(*onlySymmetries,symmetry))
continue;
bool isBoardSym = true;
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);
Loc symLoc = getSymLoc(x, y, board,symmetry);
bool isStoneSym = (board.colors[loc] == board.colors[symLoc]);
bool isKoRecapBlockedSym = hist.encorePhase > 0 ? hist.koRecapBlocked[loc] == hist.koRecapBlocked[symLoc] : true;
bool isSecondEncoreStartColorsSym = hist.encorePhase == 2 ? hist.secondEncoreStartColors[loc] == hist.secondEncoreStartColors[symLoc] : true;
if(!isStoneSym || !isKoRecapBlockedSym || !isSecondEncoreStartColorsSym) {
isBoardSym = false;
break;
}
}
if(!isBoardSym)
break;
}
if(isBoardSym)
validSymmetries.push_back(symmetry);
}
//The way we iterate is to achieve https://senseis.xmp.net/?PlayingTheFirstMoveInTheUpperRightCorner%2FDiscussion
//Reverse the iteration order for white, so that natural openings result in white on the left and black on the right
//as is common now in SGFs
if(hist.presumedNextMovePla == P_BLACK) {
for(int x = board.x_size-1; x >= 0; x--) {
for(int y = 0; y < board.y_size; y++) {
Loc loc = Location::getLoc(x, y, board.x_size);
if(avoidMoves.size() > 0 && avoidMoves[loc] > 0)
continue;
for(int symmetry: validSymmetries) {
if(symmetry == 0)
continue;
Loc symLoc = getSymLoc(x, y, board, symmetry);
if(!isSymDupLoc[loc] && loc != symLoc)
isSymDupLoc[symLoc] = true;
}
}
}
}
else {
for(int x = 0; x < board.x_size; x++) {
for(int y = board.y_size-1; y >= 0; y--) {
Loc loc = Location::getLoc(x, y, board.x_size);
if(avoidMoves.size() > 0 && avoidMoves[loc] > 0)
continue;
for(int symmetry: validSymmetries) {
if(symmetry == 0)
continue;
Loc symLoc = getSymLoc(x, y, board, symmetry);
if(!isSymDupLoc[loc] && loc != symLoc)
isSymDupLoc[symLoc] = true;
}
}
}
}
}
static double getSymmetryDifference(const Board& board, const Board& other, int symmetry, double maxDifferenceToReport) {
double thisDifference = 0.0;
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);
Loc symLoc = SymmetryHelpers::getSymLoc(x, y, board, symmetry);
// Difference!
if(board.colors[loc] != other.colors[symLoc]) {
// One of them was empty, the other was a stone
if(board.colors[loc] == C_EMPTY || other.colors[symLoc] == C_EMPTY)
thisDifference += 1.0;
// Differing stones - triple the penalty
else
thisDifference += 3.0;
if(thisDifference > maxDifferenceToReport)
return maxDifferenceToReport;
}
}
}
return thisDifference;
}
// For each symmetry, return a metric about the "amount" of difference that board would have with other
// if symmetry were applied to board.
void SymmetryHelpers::getSymmetryDifferences(
const Board& board, const Board& other, double maxDifferenceToReport, double symmetryDifferences[SymmetryHelpers::NUM_SYMMETRIES]
) {
for(int symmetry = 0; symmetry<SymmetryHelpers::NUM_SYMMETRIES; symmetry++)
symmetryDifferences[symmetry] = maxDifferenceToReport;
// Don't bother handling ultra-fancy transpose logic
if(board.x_size != other.x_size || board.y_size != other.y_size)
return;
int numSymmetries = SymmetryHelpers::NUM_SYMMETRIES;
if(board.x_size != board.y_size)
numSymmetries = SymmetryHelpers::NUM_SYMMETRIES_WITHOUT_TRANSPOSE;
for(int symmetry = 0; symmetry<numSymmetries; symmetry++) {
symmetryDifferences[symmetry] = getSymmetryDifference(board, other, symmetry, maxDifferenceToReport);
}
}
//-------------------------------------------------------------------------------------------------------------
Hash128 SGFMetadata::getHash(Player nextPlayer) const {
if(
inverseBRank < 0 ||
inverseBRank >= 128 ||
inverseWRank < 0 ||
inverseWRank >= 128 ||
source < 0 ||
source >= 128 ||
mainTimeSeconds < 0 ||
periodTimeSeconds < 0 ||
byoYomiPeriods < 0 ||
canadianMoves < 0
) {
Global::fatalError("Invalid SGFMetadata for hash");
}
uint32_t b =
(uint32_t)inverseBRank +
(uint32_t)bIsUnranked * 128u +
(uint32_t)bRankIsUnknown * 256u +
(uint32_t)bIsHuman * 512u;
uint32_t w =
(uint32_t)inverseWRank +
(uint32_t)wIsUnranked * 128u +
(uint32_t)wRankIsUnknown * 256u +
(uint32_t)wIsHuman * 512u;
uint32_t x0 = 0;
uint32_t x1 = 0;
uint32_t x2 = 0;
uint32_t x3 = 0;
if(nextPlayer == P_BLACK)
x0 += b + (w << 10);
else
x0 += w + (b << 10);
x0 += (uint32_t)gameIsUnrated << 20;
x0 += (uint32_t)gameRatednessIsUnknown << 21;
uint32_t whichTC = 0;
if(tcIsUnknown)
whichTC = 1;
else if(tcIsNone)
whichTC = 2;
else if(tcIsAbsolute)
whichTC = 3;
else if(tcIsSimple)
whichTC = 4;
else if(tcIsByoYomi)
whichTC = 5;
else if(tcIsCanadian)
whichTC = 6;
else if(tcIsFischer)
whichTC = 7;
x0 += (uint32_t)whichTC << 22;
// 7 bits left for source going up to 128
x0 += (uint32_t)source << 25;
assert(std::isfinite(mainTimeSeconds));
assert(std::isfinite(periodTimeSeconds));
double mainTimeSecondsCapped = std::min(std::max(mainTimeSeconds,0.0),3.0*86400);
// ~20 bits
x1 += (uint32_t)(mainTimeSecondsCapped * 4);
double periodTimeSecondsCapped = std::min(std::max(periodTimeSeconds,0.0),1.0*86400);
// ~22 bits
x2 += (uint32_t)(periodTimeSecondsCapped * 32);
int byoYomiPeriodsCapped = std::min(std::max(byoYomiPeriods,0),50);
x1 += (uint32_t)byoYomiPeriodsCapped << 24;
int canadianMovesCapped = std::min(std::max(canadianMoves,0),50);
x2 += (uint32_t)canadianMovesCapped << 24;
int daysDifference = gameDate.numDaysAfter(SimpleDate(1970,1,1));
x3 += (uint32_t)daysDifference;
uint64_t h0 = Hash::combine(x0,x1);
uint64_t h1 = Hash::combine(x2,x3);
h0 = Hash::nasam(h0);
h1 += h0;
h1 = Hash::nasam(h1);
h0 += h1;
return Hash128(h0,h1);
}
void SGFMetadata::fillMetadataRow(const SGFMetadata* sgfMeta, float* rowMetadata, Player nextPlayer, int boardArea) {
assert(sgfMeta != NULL);
for(int i = 0; i<SGFMetadata::METADATA_INPUT_NUM_CHANNELS; i++)
rowMetadata[i] = 0.0f;
bool plaIsHuman = (nextPlayer == P_WHITE) ? sgfMeta->wIsHuman : sgfMeta->bIsHuman;
bool oppIsHuman = (nextPlayer == P_WHITE) ? sgfMeta->bIsHuman : sgfMeta->wIsHuman;
rowMetadata[0] = plaIsHuman ? 1.0f : 0.0f;
rowMetadata[1] = oppIsHuman ? 1.0f : 0.0f;
bool plaIsUnranked = (nextPlayer == P_WHITE) ? sgfMeta->wIsUnranked : sgfMeta->bIsUnranked;
bool oppIsUnranked = (nextPlayer == P_WHITE) ? sgfMeta->bIsUnranked : sgfMeta->wIsUnranked;
rowMetadata[2] = plaIsUnranked ? 1.0f : 0.0f;
rowMetadata[3] = oppIsUnranked ? 1.0f : 0.0f;
bool plaRankIsUnknown = (nextPlayer == P_WHITE) ? sgfMeta->wRankIsUnknown : sgfMeta->bRankIsUnknown;
bool oppRankIsUnknown = (nextPlayer == P_WHITE) ? sgfMeta->bRankIsUnknown : sgfMeta->wRankIsUnknown;
rowMetadata[4] = plaRankIsUnknown ? 1.0f : 0.0f;
rowMetadata[5] = oppRankIsUnknown ? 1.0f : 0.0f;
static constexpr int RANK_START_IDX = 6;
int invPlaRank = (nextPlayer == P_WHITE) ? sgfMeta->inverseWRank : sgfMeta->inverseBRank;
int invOppRank = (nextPlayer == P_WHITE) ? sgfMeta->inverseBRank : sgfMeta->inverseWRank;
static constexpr int RANK_LEN_PER_PLA = 34;
if(!plaIsUnranked) {
for(int i = 0; i<std::min(invPlaRank,RANK_LEN_PER_PLA); i++)
rowMetadata[RANK_START_IDX + i] = 1.0f;
}
if(!oppIsUnranked) {
for(int i = 0; i<std::min(invOppRank,RANK_LEN_PER_PLA); i++)
rowMetadata[RANK_START_IDX + RANK_LEN_PER_PLA + i] = 1.0f;
}
static_assert(74 == RANK_START_IDX + 2 * RANK_LEN_PER_PLA, "");
rowMetadata[74] = sgfMeta->gameRatednessIsUnknown ? 0.5f : sgfMeta->gameIsUnrated ? 1.0f : 0.0f;
rowMetadata[75] = sgfMeta->tcIsUnknown ? 1.0f : 0.0f;
rowMetadata[76] = sgfMeta->tcIsNone ? 1.0f : 0.0f;
rowMetadata[77] = sgfMeta->tcIsAbsolute ? 1.0f : 0.0f;
rowMetadata[78] = sgfMeta->tcIsSimple ? 1.0f : 0.0f;
rowMetadata[79] = sgfMeta->tcIsByoYomi ? 1.0f : 0.0f;
rowMetadata[80] = sgfMeta->tcIsCanadian ? 1.0f : 0.0f;
rowMetadata[81] = sgfMeta->tcIsFischer ? 1.0f : 0.0f;
assert(rowMetadata[75] + rowMetadata[76] + rowMetadata[77] + rowMetadata[78] + rowMetadata[79] + rowMetadata[80] + rowMetadata[81] == 1.0f);
double mainTimeSecondsCapped = std::min(std::max(sgfMeta->mainTimeSeconds,0.0),3.0*86400);
double periodTimeSecondsCapped = std::min(std::max(sgfMeta->periodTimeSeconds,0.0),1.0*86400);
rowMetadata[82] = (float)(0.4 * (log(mainTimeSecondsCapped + 60.0) - 6.5));
rowMetadata[83] = (float)(0.3 * (log(periodTimeSecondsCapped + 1.0) - 3.0));
int byoYomiPeriodsCapped = std::min(std::max(sgfMeta->byoYomiPeriods,0),50);
int canadianMovesCapped = std::min(std::max(sgfMeta->canadianMoves,0),50);
rowMetadata[84] = (float)(0.5 * (log(byoYomiPeriodsCapped + 2.0) - 1.5));
rowMetadata[85] = (float)(0.25 * (log(canadianMovesCapped + 2.0) - 1.5));
rowMetadata[86] = (float)(0.5 * log(boardArea/361.0));
double daysDifference = sgfMeta->gameDate.numDaysAfter(SimpleDate(1970,1,1));
static constexpr int DATE_START_IDX = 87;
static constexpr int DATE_LEN = 32;
// 7 because we're curious if there's a day-of-the-week effect
// on gameplay...
double period = 7.0;
static const double factor = pow(80000, 1.0/(DATE_LEN-1));
static constexpr double twopi = 6.283185307179586476925;
for(int i = 0; i<DATE_LEN; i++) {
double numRevolutions = daysDifference / period;
rowMetadata[DATE_START_IDX + i*2 + 0] = (float)(cos(numRevolutions * twopi));
rowMetadata[DATE_START_IDX + i*2 + 1] = (float)(sin(numRevolutions * twopi));
period *= factor;
}
static_assert(151 == DATE_START_IDX + 2 * DATE_LEN, "");