forked from tensorflow/minigo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkata_net.py
1848 lines (1582 loc) · 90 KB
/
kata_net.py
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
import logging
import math
import traceback
import tensorflow as tf
import numpy as np
from kata_board import Board
#Feature extraction functions-------------------------------------------------------------------
class Model:
# Sizes of the various array targets in the data, used also to size some of the output head dimensions
# for auxiliary outputs
NUM_POLICY_TARGETS = 2
NUM_GLOBAL_TARGETS = 64
NUM_VALUE_SPATIAL_TARGETS = 5
EXTRA_SCORE_DISTR_RADIUS = 60
@staticmethod
def get_version(config):
if "version" in config:
return config["version"]
return 5 #by default, since this was the version before we put it in the config
@staticmethod
def get_num_bin_input_features(config):
version = Model.get_version(config)
if version == 4:
return 22
elif version == 5:
return 22
elif version == 6:
return 13
elif version <= 10:
return 22
else:
assert(False)
@staticmethod
def get_num_global_input_features(config):
version = Model.get_version(config)
if version == 4:
return 14
elif version == 5:
return 14
elif version == 6:
return 12
elif version == 7:
return 16
elif version <= 10:
return 19
else:
assert(False)
def __init__(self,save_file,config,pos_len,placeholders,is_training=False):
self.save_file = save_file
self.config = config
self.pos_len = pos_len
self.num_bin_input_features = Model.get_num_bin_input_features(config)
self.num_global_input_features = Model.get_num_global_input_features(config)
self.bin_input_shape = [self.pos_len*self.pos_len,self.num_bin_input_features]
self.binp_input_shape = [self.num_bin_input_features,(self.pos_len*self.pos_len+7)//8]
self.global_input_shape = [self.num_global_input_features]
self.post_input_shape = [self.pos_len,self.pos_len,self.num_bin_input_features]
self.policy_output_shape_nopass = [self.pos_len*self.pos_len,2]
self.policy_output_shape = [self.pos_len*self.pos_len+1,2] #+1 for pass move
self.policy_target_shape = [self.pos_len*self.pos_len+1] #+1 for pass move
self.policy_target_weight_shape = []
self.value_target_shape = [3]
self.td_value_target_shape = [3,3]
self.td_score_target_shape = [3]
self.miscvalues_target_shape = [10] #0:scoremean, #1 scorestdev, #2 lead, #3 variance time #4-#9 td value targets
self.scoremean_target_shape = [] #0
self.scorestdev_target_shape = [] #1
self.lead_target_shape = [] #2
self.variance_time_target_shape = [] #3
self.moremiscvalues_target_shape = [8] #0:shortterm value stdev, #1 shortterm score stdev, #2,3,4 td value, #5,#6-#7 td score
self.scorebelief_target_shape = [self.pos_len*self.pos_len*2+Model.EXTRA_SCORE_DISTR_RADIUS*2]
self.ownership_target_shape = [self.pos_len,self.pos_len]
self.scoring_target_shape = [self.pos_len,self.pos_len]
self.futurepos_target_shape = [self.pos_len,self.pos_len,2]
self.seki_output_shape = [self.pos_len,self.pos_len,4]
self.seki_target_shape = [self.pos_len,self.pos_len]
self.target_weight_shape = []
self.lead_target_weight_shape = []
self.ownership_target_weight_shape = []
self.scoring_target_weight_shape = []
self.futurepos_target_weight_shape = []
self.pass_pos = self.pos_len * self.pos_len
self.reg_variables = []
self.reg_variables_tiny = []
self.prescale_variables = []
self.lr_adjusted_variables = {}
self.is_training = is_training
self.is_training_tensor = tf.constant(is_training,dtype=tf.bool)
self.num_blocks = len(config["block_kind"])
self.use_fixup = config["use_fixup"]
#Accumulates outputs for printing stats about their activations
self.outputs_by_layer = []
self.other_internal_outputs = []
#Accumulates info about batch norm laywers
self.batch_norms = {}
self.support_japanese_rules = True #by default
if "support_japanese_rules" in config and config["support_japanese_rules"] == False:
self.support_japanese_rules = False
self.use_scoremean_as_lead = False #by default
if "use_scoremean_as_lead" in config and config["use_scoremean_as_lead"] == True:
self.use_scoremean_as_lead = True
self.build_model(config,placeholders)
#self.inference_input = None
#self.inference_output = None
self.fetches = [tf.nn.softmax(self.policy_output[:,:,0]),tf.nn.softmax(self.value_output)]
#session_config = tf.compat.v1.ConfigProto(allow_soft_placement=True)
#session_config.gpu_options.per_process_gpu_memory_fraction = 0.3
self.rules = {
"koRule": "KO_POSITIONAL",
"scoringRule": "SCORING_AREA",
"taxRule": "TAX_NONE",
"multiStoneSuicideLegal": True,
"hasButton": False,
"encorePhase": 0,
"passWouldEndPhase": False,
"whiteKomi": 7.5
}
self.sess = tf.compat.v1.Session()
self.initialize_weights(save_file)
def initialize_weights(self, save_file):
"""Initialize the weights from the given save_file.
Assumes that the graph has been constructed, and the
save_file contains weights that match the graph. Used
to set the weights to a different version of the player
without redifining the entire graph."""
if self.save_file is not None:
tf.train.Saver().restore(self.sess, save_file)
else:
self.sess.run(tf.global_variables_initializer())
def assert_batched_shape(self,name,tensor,shape):
if (len(tensor.shape) != len(shape)+1 or
[int(tensor.shape[i+1].value) for i in range(len(shape))] != [int(x) for x in shape]):
raise Exception("%s should have shape %s after a batch dimension but instead it had shape %s" % (
name, str(shape), str([str(x.value) for x in tensor.shape])))
def assert_shape(self,name,tensor,shape):
if (len(tensor.shape) != len(shape) or
[int(x.value) for x in tensor.shape] != [int(x) for x in shape]):
raise Exception("%s should have shape %s but instead it had shape %s" % (
name, str(shape), str([str(x.value) for x in tensor.shape])))
def xy_to_tensor_pos(self,x,y):
return y * self.pos_len + x
def loc_to_tensor_pos(self,loc,board):
assert(loc != Board.PASS_LOC)
return board.loc_y(loc) * self.pos_len + board.loc_x(loc)
def tensor_pos_to_loc(self,pos,board):
if pos == self.pass_pos:
return None
pos_len = self.pos_len
bsize = board.size
assert(self.pos_len >= bsize)
x = pos % pos_len
y = pos // pos_len
if x < 0 or x >= bsize or y < 0 or y >= bsize:
return board.loc(-10,-10) #Return an illegal move since this is offboard
return board.loc(x,y)
def sym_tensor_pos(self,pos,symmetry):
if pos == self.pass_pos:
return pos
pos_len = self.pos_len
x = pos % pos_len
y = pos // pos_len
if symmetry >= 4:
symmetry -= 4
tmp = x
x = y
y = tmp
if symmetry >= 2:
symmetry -= 2
x = pos_len-x-1
if symmetry >= 1:
symmetry -= 1
y = pos_len-y-1
return y * pos_len + x
#Calls f on each location that is part of an inescapable atari, or a group that can be put into inescapable atari
def iterLadders(self, board, f):
chainHeadsSolved = {}
copy = board.copy()
bsize = board.size
assert(self.pos_len >= bsize)
for y in range(bsize):
for x in range(bsize):
pos = self.xy_to_tensor_pos(x,y)
loc = board.loc(x,y)
stone = board.board[loc]
if stone == Board.BLACK or stone == Board.WHITE:
libs = board.num_liberties(loc)
if libs == 1 or libs == 2:
head = board.group_head[loc]
if head in chainHeadsSolved:
laddered = chainHeadsSolved[head]
if laddered:
f(loc,pos,[])
else:
#Perform search on copy so as not to mess up tracking of solved heads
if libs == 1:
workingMoves = []
laddered = copy.searchIsLadderCaptured(loc,True)
else:
workingMoves = copy.searchIsLadderCapturedAttackerFirst2Libs(loc)
laddered = len(workingMoves) > 0
chainHeadsSolved[head] = laddered
if laddered:
f(loc,pos,workingMoves)
#Returns the new idx, which could be the same as idx if this isn't a good training row
def fill_row_features(self, board, pla, opp, boards, moves, move_idx, rules, bin_input_data, global_input_data, idx):
#Currently only support v4 or v5 or v7-10 MODEL features (inputs version v3 and v4 and v6)
assert(self.version == 4 or self.version == 5 or self.version == 7 or self.version == 8 or self.version == 9 or self.version == 10)
bsize = board.size
assert(self.pos_len >= bsize)
assert(len(boards) > 0)
assert(board.zobrist == boards[move_idx].zobrist)
for y in range(bsize):
for x in range(bsize):
pos = self.xy_to_tensor_pos(x,y)
bin_input_data[idx,pos,0] = 1.0
loc = board.loc(x,y)
stone = board.board[loc]
if stone == pla:
bin_input_data[idx,pos,1] = 1.0
elif stone == opp:
bin_input_data[idx,pos,2] = 1.0
if stone == pla or stone == opp:
libs = board.num_liberties(loc)
if libs == 1:
bin_input_data[idx,pos,3] = 1.0
elif libs == 2:
bin_input_data[idx,pos,4] = 1.0
elif libs == 3:
bin_input_data[idx,pos,5] = 1.0
#Python code does NOT handle superko
if board.simple_ko_point is not None:
pos = self.loc_to_tensor_pos(board.simple_ko_point,board)
bin_input_data[idx,pos,6] = 1.0
#Python code does NOT handle ko-prohibited encore spots or anything relating to the encore
#so features 7 and 8 leave that blank
if move_idx >= 1 and moves[move_idx-1][0] == opp:
prev1_loc = moves[move_idx-1][1]
if prev1_loc is not None and prev1_loc != Board.PASS_LOC:
pos = self.loc_to_tensor_pos(prev1_loc,board)
bin_input_data[idx,pos,9] = 1.0
elif prev1_loc == Board.PASS_LOC:
global_input_data[idx,0] = 1.0
if move_idx >= 2 and moves[move_idx-2][0] == pla:
prev2_loc = moves[move_idx-2][1]
if prev2_loc is not None and prev2_loc != Board.PASS_LOC:
pos = self.loc_to_tensor_pos(prev2_loc,board)
bin_input_data[idx,pos,10] = 1.0
elif prev2_loc == Board.PASS_LOC:
global_input_data[idx,1] = 1.0
if move_idx >= 3 and moves[move_idx-3][0] == opp:
prev3_loc = moves[move_idx-3][1]
if prev3_loc is not None and prev3_loc != Board.PASS_LOC:
pos = self.loc_to_tensor_pos(prev3_loc,board)
bin_input_data[idx,pos,11] = 1.0
elif prev3_loc == Board.PASS_LOC:
global_input_data[idx,2] = 1.0
if move_idx >= 4 and moves[move_idx-4][0] == pla:
prev4_loc = moves[move_idx-4][1]
if prev4_loc is not None and prev4_loc != Board.PASS_LOC:
pos = self.loc_to_tensor_pos(prev4_loc,board)
bin_input_data[idx,pos,12] = 1.0
elif prev4_loc == Board.PASS_LOC:
global_input_data[idx,3] = 1.0
if move_idx >= 5 and moves[move_idx-5][0] == opp:
prev5_loc = moves[move_idx-5][1]
if prev5_loc is not None and prev5_loc != Board.PASS_LOC:
pos = self.loc_to_tensor_pos(prev5_loc,board)
bin_input_data[idx,pos,13] = 1.0
elif prev5_loc == Board.PASS_LOC:
global_input_data[idx,4] = 1.0
def addLadderFeature(loc,pos,workingMoves):
assert(board.board[loc] == Board.BLACK or board.board[loc] == Board.WHITE)
bin_input_data[idx,pos,14] = 1.0
if board.board[loc] == opp and board.num_liberties(loc) > 1:
for workingMove in workingMoves:
workingPos = self.loc_to_tensor_pos(workingMove,board)
bin_input_data[idx,workingPos,17] = 1.0
self.iterLadders(board, addLadderFeature)
if move_idx > 0:
prevBoard = boards[move_idx-1]
else:
prevBoard = board
def addPrevLadderFeature(loc,pos,workingMoves):
assert(prevBoard.board[loc] == Board.BLACK or prevBoard.board[loc] == Board.WHITE)
bin_input_data[idx,pos,15] = 1.0
self.iterLadders(prevBoard, addPrevLadderFeature)
if move_idx > 1:
prevPrevBoard = boards[move_idx-2]
else:
prevPrevBoard = prevBoard
def addPrevPrevLadderFeature(loc,pos,workingMoves):
assert(prevPrevBoard.board[loc] == Board.BLACK or prevPrevBoard.board[loc] == Board.WHITE)
bin_input_data[idx,pos,16] = 1.0
self.iterLadders(prevPrevBoard, addPrevPrevLadderFeature)
#Features 18,19 - area
area = [0 for i in range(board.arrsize)]
if self.version <= 6:
if rules["scoringRule"] == "SCORING_AREA":
nonPassAliveStones = False
safeBigTerritories = True
unsafeBigTerritories = False
if self.version != 5:
nonPassAliveStones = True
unsafeBigTerritories = True
board.calculateArea(area,nonPassAliveStones,safeBigTerritories,unsafeBigTerritories,rules["multiStoneSuicideLegal"])
elif rules["scoringRule"] == "SCORING_TERRITORY":
nonPassAliveStones = False
safeBigTerritories = True
unsafeBigTerritories = False
board.calculateArea(area,nonPassAliveStones,safeBigTerritories,unsafeBigTerritories,rules["multiStoneSuicideLegal"])
else:
assert(False)
else:
if rules["scoringRule"] == "SCORING_AREA" and rules["taxRule"] == "TAX_NONE":
safeBigTerritories = True
nonPassAliveStones = True
unsafeBigTerritories = True
board.calculateArea(area,nonPassAliveStones,safeBigTerritories,unsafeBigTerritories,rules["multiStoneSuicideLegal"])
else:
hasAreaFeature = False
keepTerritories = False
keepStones = False
if rules["scoringRule"] == "SCORING_AREA" and (rules["taxRule"] == "TAX_SEKI" or rules["taxRule"] == "TAX_ALL"):
hasAreaFeature = True
keepTerritories = False
keepStones = True
elif rules["scoringRule"] == "SCORING_TERRITORY" and rules["taxRule"] == "TAX_NONE":
if rules["encorePhase"] >= 2:
hasAreaFeature = True
keepTerritories = True
keepStones = False
elif rules["scoringRule"] == "SCORING_TERRITORY" and (rules["taxRule"] == "TAX_SEKI" or rules["taxRule"] == "TAX_ALL"):
if rules["encorePhase"] >= 2:
hasAreaFeature = True
keepTerritories = False
keepStones = False
else:
assert(False)
if hasAreaFeature:
board.calculateNonDameTouchingArea(
area,
keepTerritories,
keepStones,
rules["multiStoneSuicideLegal"]
)
for y in range(bsize):
for x in range(bsize):
loc = board.loc(x,y)
pos = self.xy_to_tensor_pos(x,y)
if area[loc] == pla:
bin_input_data[idx,pos,18] = 1.0
elif area[loc] == opp:
bin_input_data[idx,pos,19] = 1.0
#Features 20,21 - second encore phase starting stones, we just set them to the current stones in pythong
#since we don't really have a jp rules impl
if rules["encorePhase"] >= 2:
for y in range(bsize):
for x in range(bsize):
pos = self.xy_to_tensor_pos(x,y)
loc = board.loc(x,y)
stone = board.board[loc]
if stone == pla:
bin_input_data[idx,pos,20] = 1.0
elif stone == opp:
bin_input_data[idx,pos,21] = 1.0
#Not quite right, japanese rules aren't really implemented in the python
bArea = board.size * board.size
whiteKomi = rules["whiteKomi"]
if rules["scoringRule"] == "SCORING_TERRITORY":
selfKomi = (whiteKomi+1 if pla == Board.WHITE else -whiteKomi)
else:
selfKomi = (whiteKomi if pla == Board.WHITE else -whiteKomi)
if selfKomi > bArea+1:
selfKomi = bArea+1
if selfKomi < -bArea-1:
selfKomi = -bArea-1
if self.version >= 7:
global_input_data[idx,5] = selfKomi/20.0
else:
global_input_data[idx,5] = selfKomi/15.0
if rules["koRule"] == "KO_SIMPLE":
pass
elif rules["koRule"] == "KO_POSITIONAL" or rules["koRule"] == "KO_SPIGHT":
global_input_data[idx,6] = 1.0
global_input_data[idx,7] = 0.5
elif rules["koRule"] == "KO_SITUATIONAL":
global_input_data[idx,6] = 1.0
global_input_data[idx,7] = -0.5
else:
assert(False)
if rules["multiStoneSuicideLegal"]:
global_input_data[idx,8] = 1.0
if rules["scoringRule"] == "SCORING_AREA":
pass
elif rules["scoringRule"] == "SCORING_TERRITORY":
global_input_data[idx,9] = 1.0
else:
assert(False)
if self.version >= 7:
if rules["taxRule"] == "TAX_NONE":
pass
elif rules["taxRule"] == "TAX_SEKI":
global_input_data[idx,10] = 1.0
elif rules["taxRule"] == "TAX_ALL":
global_input_data[idx,10] = 1.0
global_input_data[idx,11] = 1.0
else:
assert(False)
if self.version >= 7:
if rules["encorePhase"] > 0:
global_input_data[idx,12] = 1.0
if rules["encorePhase"] > 1:
global_input_data[idx,13] = 1.0
passWouldEndPhase = rules["passWouldEndPhase"]
global_input_data[idx,14] = (1.0 if passWouldEndPhase else 0.0)
else:
if rules["encorePhase"] > 0:
global_input_data[idx,10] = 1.0
if rules["encorePhase"] > 1:
global_input_data[idx,11] = 1.0
passWouldEndPhase = rules["passWouldEndPhase"]
global_input_data[idx,12] = (1.0 if passWouldEndPhase else 0.0)
if self.version >= 8 and "asymPowersOfTwo" in rules:
global_input_data[idx,15] = 1.0
global_input_data[idx,16] = rules["asymPowersOfTwo"]
if self.version >= 8:
if "hasButton" in rules and rules["hasButton"] and Board.PASS_LOC not in [move[1] for move in moves]:
global_input_data[idx,17] = 1.0
if rules["scoringRule"] == "SCORING_AREA" or rules["encorePhase"] > 1:
boardAreaIsEven = (board.size % 2 == 0)
drawableKomisAreEven = boardAreaIsEven
if drawableKomisAreEven:
komiFloor = math.floor(selfKomi / 2.0) * 2.0
else:
komiFloor = math.floor((selfKomi-1.0) / 2.0) * 2.0 + 1.0
delta = selfKomi - komiFloor
assert(delta >= -0.0001)
assert(delta <= 2.0001)
if delta < 0.0:
delta = 0.0
if delta > 2.0:
delta = 2.0
if delta < 0.5:
wave = delta
elif delta < 1.5:
wave = 1.0-delta
else:
wave = delta-2.0
if self.version >= 8:
global_input_data[idx,18] = wave
elif self.version >= 7:
global_input_data[idx,15] = wave
else:
global_input_data[idx,13] = wave
return idx+1
# Build model -------------------------------------------------------------
def ensure_variable_exists(self,name):
for v in tf.compat.v1.trainable_variables():
if v.name == name:
return name
raise Exception("Could not find variable " + name)
def add_lr_factor(self,name,factor):
if not self.is_training:
return
self.ensure_variable_exists(name)
if name in self.lr_adjusted_variables:
self.lr_adjusted_variables[name] = factor * self.lr_adjusted_variables[name]
else:
self.lr_adjusted_variables[name] = factor
def batchnorm_and_mask(self,name,tensor,mask,mask_sum,use_gamma_in_fixup=False):
if self.use_fixup:
self.batch_norms[name] = (tensor.shape[-1].value,1e-20,True,use_gamma_in_fixup,self.use_fixup)
if use_gamma_in_fixup:
gamma = self.weight_variable_init_constant(name+"/gamma", [tensor.shape[3].value], 1.0)
beta = self.weight_variable_init_constant(name+"/beta", [tensor.shape[3].value], 0.0, reg="tiny")
return (tensor * gamma + beta) * mask
else:
beta = self.weight_variable_init_constant(name+"/beta", [tensor.shape[3].value], 0.0, reg="tiny")
return (tensor + beta) * mask
epsilon = 0.001
has_bias = True
has_scale = False
self.batch_norms[name] = (tensor.shape[-1].value,epsilon,has_bias,has_scale,self.use_fixup)
num_channels = tensor.shape[3].value
collections = [tf.compat.v1.GraphKeys.GLOBAL_VARIABLES,tf.compat.v1.GraphKeys.MODEL_VARIABLES,tf.compat.v1.GraphKeys.MOVING_AVERAGE_VARIABLES]
#Define variables to keep track of the mean and variance
moving_mean = tf.compat.v1.get_variable(initializer=tf.zeros([num_channels]),name=(name+"/moving_mean"),trainable=False,collections=collections)
moving_var = tf.compat.v1.get_variable(initializer=tf.ones([num_channels]),name=(name+"/moving_variance"),trainable=False,collections=collections)
beta = self.weight_variable_init_constant(name+"/beta", [tensor.shape[3].value], 0.0, reg=False)
#This is the mean, computed only over exactly the areas of the mask, weighting each spot equally,
#even across different elements in the batch that might have different board sizes.
mean = tf.reduce_sum(tensor * mask,axis=[0,1,2]) / mask_sum
zmtensor = tensor-mean
#Similarly, the variance computed exactly only over those spots
var = tf.reduce_sum(tf.square(zmtensor * mask),axis=[0,1,2]) / mask_sum
with tf.compat.v1.variable_scope(name):
mean_op = tf.keras.backend.moving_average_update(moving_mean,mean,0.998)
var_op = tf.keras.backend.moving_average_update(moving_var,var,0.998)
tf.compat.v1.add_to_collection(tf.compat.v1.GraphKeys.UPDATE_OPS, mean_op)
tf.compat.v1.add_to_collection(tf.compat.v1.GraphKeys.UPDATE_OPS, var_op)
def training_f():
return (mean,var)
def inference_f():
return (moving_mean,moving_var)
use_mean,use_var = tf.cond(self.is_training_tensor,training_f,inference_f)
return tf.nn.batch_normalization(tensor,use_mean,use_var,beta,None,epsilon) * mask
# def batchnorm(self,name,tensor):
# epsilon = 0.001
# has_bias = True
# has_scale = False
# self.batch_norms[name] = (tensor.shape[-1].value,epsilon,has_bias,has_scale)
# return tf.layers.batch_normalization(
# tensor,
# axis=-1, #Because channels are our last axis, -1 refers to that via wacky python indexing
# momentum=0.99,
# epsilon=epsilon,
# center=has_bias,
# scale=has_scale,
# training=self.is_training_tensor,
# name=name,
# )
def init_stdev(self,num_inputs,num_outputs):
#xavier
#return math.sqrt(2.0 / (num_inputs + num_outputs))
#herangzhen
return math.sqrt(2.0 / (num_inputs))
def init_weights(self, shape, num_inputs, num_outputs):
stdev = self.init_stdev(num_inputs,num_outputs) / 1.0
return tf.random.truncated_normal(shape=shape, stddev=stdev)
def weight_variable_init_constant(self, name, shape, constant, reg=True):
init = tf.zeros(shape)
if constant != 0.0:
init = init + constant
variable = tf.compat.v1.get_variable(initializer=init,name=name)
if reg is True:
self.reg_variables.append(variable)
elif reg == "tiny":
self.reg_variables_tiny.append(variable)
return variable
def weight_variable(self, name, shape, num_inputs, num_outputs, scale_initial_weights=1.0, extra_initial_weight=None, reg=True):
initial = self.init_weights(shape, num_inputs, num_outputs)
if extra_initial_weight is not None:
initial = initial + extra_initial_weight
initial = initial * scale_initial_weights
variable = tf.compat.v1.get_variable(initializer=initial,name=name)
if reg is True:
self.reg_variables.append(variable)
elif reg == "tiny":
self.reg_variables_tiny.append(variable)
return variable
def conv2d(self, x, w):
return tf.nn.conv2d(x, w, strides=[1,1,1,1], padding='SAME')
def dilated_conv2d(self, x, w, dilation):
return tf.nn.atrous_conv2d(x, w, rate = dilation, padding='SAME')
def apply_symmetry(self,tensor,symmetries,inverse):
ud = symmetries[0]
lr = symmetries[1]
transp = symmetries[2]
if not inverse:
tensor = tf.cond(
ud,
lambda: tf.reverse(tensor,[1]),
lambda: tensor
)
tensor = tf.cond(
lr,
lambda: tf.reverse(tensor,[2]),
lambda: tensor
)
tensor = tf.cond(
transp,
lambda: tf.transpose(tensor, [0,2,1,3]),
lambda: tensor)
if inverse:
tensor = tf.cond(
ud,
lambda: tf.reverse(tensor,[1]),
lambda: tensor
)
tensor = tf.cond(
lr,
lambda: tf.reverse(tensor,[2]),
lambda: tensor
)
return tensor
#Define useful components --------------------------------------------------------------------------
def relu(self, name, layer):
assert(len(layer.shape) == 4)
#num_channels = layer.shape[3].value
#alphas = self.weight_variable_init_constant(name+"/relu",[1,1,1,num_channels],constant=0.0)
return tf.nn.relu(layer)
def relu_spatial1d(self, name, layer):
assert(len(layer.shape) == 3)
#num_channels = layer.shape[1].value
#alphas = self.weight_variable_init_constant(name+"/relu",[1,num_channels],constant=0.0)
return tf.nn.relu(layer)
def relu_non_spatial(self, name, layer):
assert(len(layer.shape) == 2)
#num_channels = layer.shape[1].value
#alphas = self.weight_variable_init_constant(name+"/relu",[1,num_channels],constant=0.0)
return tf.nn.relu(layer)
def merge_residual(self,name,trunk,residual):
trunk = trunk + residual
self.outputs_by_layer.append((name,trunk))
return trunk
def conv_weight_variable(self, name, diam1, diam2, in_channels, out_channels, scale_initial_weights=1.0, reg=True):
radius1 = diam1 // 2
radius2 = diam2 // 2
weights = self.weight_variable(name,[diam1,diam2,in_channels,out_channels],in_channels*diam1*diam2,out_channels,scale_initial_weights,reg=reg)
return weights
#Convolutional layer with batch norm and nonlinear activation
def conv_block(
self, name, in_layer, mask, mask_sum, diam, in_channels, out_channels,
scale_initial_weights=1.0
):
weights = self.conv_weight_variable(name+"/w", diam, diam, in_channels, out_channels, scale_initial_weights)
convolved = self.conv2d(in_layer, weights)
self.outputs_by_layer.append((name+"/prenorm",convolved))
out_layer = self.relu(name+"/relu",self.batchnorm_and_mask(name+"/norm",convolved,mask,mask_sum))
self.outputs_by_layer.append((name,out_layer))
return out_layer
#Convolution only, no batch norm or nonlinearity
def conv_only_block(
self, name, in_layer, diam, in_channels, out_channels,
scale_initial_weights=1.0, reg=True
):
weights = self.conv_weight_variable(name+"/w", diam, diam, in_channels, out_channels, scale_initial_weights, reg=reg)
out_layer = self.conv2d(in_layer, weights)
self.outputs_by_layer.append((name,out_layer))
return out_layer
#Convolutional residual block with internal batch norm and nonlinear activation
def res_conv_block(
self, name, in_layer, mask, mask_sum, diam, main_channels, mid_channels,
scale_initial_weights=1.0
):
trans1_layer = self.relu(name+"/relu1",(self.batchnorm_and_mask(name+"/norm1",in_layer,mask,mask_sum)))
self.outputs_by_layer.append((name+"/trans1",trans1_layer))
fixup_scale = 1.0 / math.sqrt(self.num_blocks) if self.use_fixup else 1.0
weights1 = self.conv_weight_variable(name+"/w1", diam, diam, main_channels, mid_channels, scale_initial_weights * fixup_scale)
conv1_layer = self.conv2d(trans1_layer, weights1)
self.outputs_by_layer.append((name+"/conv1",conv1_layer))
trans2_layer = self.relu(name+"/relu2",(self.batchnorm_and_mask(name+"/norm2",conv1_layer,mask,mask_sum,use_gamma_in_fixup=True)))
self.outputs_by_layer.append((name+"/trans2",trans2_layer))
fixup_scale_last_layer = 0.0 if self.use_fixup else 1.0
weights2 = self.conv_weight_variable(name+"/w2", diam, diam, mid_channels, main_channels, scale_initial_weights*fixup_scale_last_layer)
conv2_layer = self.conv2d(trans2_layer, weights2)
self.outputs_by_layer.append((name+"/conv2",conv2_layer))
return conv2_layer
#Convolutional residual block with internal batch norm and nonlinear activation
def global_res_conv_block(
self, name, in_layer, mask, mask_sum, mask_sum_hw, mask_sum_hw_sqrt,
diam, main_channels, mid_channels, global_mid_channels,
scale_initial_weights=1.0
):
trans1_layer = self.relu(name+"/relu1",(self.batchnorm_and_mask(name+"/norm1",in_layer,mask,mask_sum)))
self.outputs_by_layer.append((name+"/trans1",trans1_layer))
fixup_scale2 = 1.0 / math.sqrt(self.num_blocks) if self.use_fixup else 1.0
fixup_scale4 = 1.0 / (self.num_blocks ** (1.0 / 4.0)) if self.use_fixup else 1.0
weights1a = self.conv_weight_variable(name+"/w1a", diam, diam, main_channels, mid_channels, scale_initial_weights * fixup_scale2)
weights1b = self.conv_weight_variable(name+"/w1b", diam, diam, main_channels, global_mid_channels, scale_initial_weights * fixup_scale4)
conv1a_layer = self.conv2d(trans1_layer, weights1a)
conv1b_layer = self.conv2d(trans1_layer, weights1b)
self.outputs_by_layer.append((name+"/conv1a",conv1a_layer))
self.outputs_by_layer.append((name+"/conv1b",conv1b_layer))
trans1b_layer = self.relu(name+"/trans1b",(self.batchnorm_and_mask(name+"/norm1b",conv1b_layer,mask,mask_sum)))
trans1b_pooled = self.global_pool(trans1b_layer, mask_sum_hw, mask_sum_hw_sqrt)
remix_weights = self.weight_variable(name+"/w1r",[global_mid_channels*3,mid_channels],global_mid_channels*3,mid_channels, scale_initial_weights * fixup_scale4 * 0.5)
conv1_layer = conv1a_layer + tf.tensordot(trans1b_pooled,remix_weights,axes=[[3],[0]])
trans2_layer = self.relu(name+"/relu2",(self.batchnorm_and_mask(name+"/norm2",conv1_layer,mask,mask_sum,use_gamma_in_fixup=True)))
self.outputs_by_layer.append((name+"/trans2",trans2_layer))
fixup_scale_last_layer = 0.0 if self.use_fixup else 1.0
weights2 = self.conv_weight_variable(name+"/w2", diam, diam, mid_channels, main_channels, scale_initial_weights * fixup_scale_last_layer)
conv2_layer = self.conv2d(trans2_layer, weights2)
self.outputs_by_layer.append((name+"/conv2",conv2_layer))
return conv2_layer
#Convolutional residual block with internal batch norm and nonlinear activation
def dilated_res_conv_block(self, name, in_layer, mask, mask_sum, diam, main_channels, mid_channels, dilated_mid_channels, dilation, scale_initial_weights=1.0):
trans1_layer = self.relu(name+"/relu1",(self.batchnorm_and_mask(name+"/norm1",in_layer,mask,mask_sum)))
self.outputs_by_layer.append((name+"/trans1",trans1_layer))
fixup_scale = 1.0 / math.sqrt(self.num_blocks) if self.use_fixup else 1.0
weights1a = self.conv_weight_variable(name+"/w1a", diam, diam, main_channels, mid_channels, scale_initial_weights*fixup_scale)
weights1b = self.conv_weight_variable(name+"/w1b", diam, diam, main_channels, dilated_mid_channels, scale_initial_weights*fixup_scale)
conv1a_layer = self.conv2d(trans1_layer, weights1a)
conv1b_layer = self.dilated_conv2d(trans1_layer, weights1b, dilation=dilation)
self.outputs_by_layer.append((name+"/conv1a",conv1a_layer))
self.outputs_by_layer.append((name+"/conv1b",conv1b_layer))
conv1_layer = tf.concat([conv1a_layer,conv1b_layer],axis=3)
trans2_layer = self.relu(name+"/relu2",(self.batchnorm_and_mask(name+"/norm2",conv1_layer,mask,mask_sum,use_gamma_in_fixup=True)))
self.outputs_by_layer.append((name+"/trans2",trans2_layer))
fixup_scale_last_layer = 0.0 if self.use_fixup else 1.0
weights2 = self.conv_weight_variable(name+"/w2", diam, diam, mid_channels+dilated_mid_channels, main_channels, scale_initial_weights * fixup_scale_last_layer)
conv2_layer = self.conv2d(trans2_layer, weights2)
self.outputs_by_layer.append((name+"/conv2",conv2_layer))
return conv2_layer
def global_pool(self, in_layer, mask_sum_hw, mask_sum_hw_sqrt):
div = tf.reshape(mask_sum_hw,[-1,1,1,1])
div_sqrt = tf.reshape(mask_sum_hw_sqrt,[-1,1,1,1])
layer_raw_mean = tf.reduce_sum(in_layer,axis=[1,2],keepdims=True) / div
layer_raw_max = tf.reduce_max(in_layer,axis=[1,2],keepdims=True)
# 1, (x-14)/10, and (x-14)^2/100 - 0.1 are three orthogonal functions over [9,19], the range of reasonable board sizes.
# We have the 14 in there since it's the midpoint of that range. The /10 is just sort of arbitrary normalization to keep things on the same scale.
center_bsize = 14.0
layer_0 = layer_raw_mean
layer_1 = layer_raw_mean * ((div_sqrt - center_bsize) / 10.0)
layer_2 = layer_raw_max
layer_pooled = tf.concat([layer_0,layer_1,layer_2],axis=3)
return layer_pooled
def value_head_pool(self, in_layer, mask_sum_hw, mask_sum_hw_sqrt):
div = tf.reshape(mask_sum_hw,[-1,1])
div_sqrt = tf.reshape(mask_sum_hw_sqrt,[-1,1])
layer_raw_mean = tf.reduce_sum(in_layer,axis=[1,2],keepdims=False) / div
# 1, (x-14)/10, and (x-14)^2/100 - 0.1 are three orthogonal functions over [9,19], the range of reasonable board sizes.
# We have the 14 in there since it's the midpoint of that range. The /10 and /100 are just sort of arbitrary normalization to keep things on the same scale
center_bsize = 14.0
layer_0 = layer_raw_mean
layer_1 = layer_raw_mean * ((div_sqrt - center_bsize) / 10.0)
layer_2 = layer_raw_mean * (tf.square(div_sqrt - center_bsize) / 100.0 - 0.1)
layer_pooled = tf.concat([layer_0,layer_1,layer_2],axis=1)
return layer_pooled
#Begin Neural net------------------------------------------------------------------------------------
#Indexing:
#batch, bsize, bsize, channel
def build_model(self,config,placeholders):
pos_len = self.pos_len
#Model version-------------------------------------------------------------------------------
#This is written out in the model file when it gets built for export
#self.version = 0 #V1 features, with old head architecture using crelus (no longer supported)
#self.version = 1 #V1 features, with new head architecture, no crelus
#self.version = 2 #V2 features, no internal architecture change.
#self.version = 3 #V3 features, selfplay-planned features with lots of aux targets
#self.version = 4 #V3 features, but supporting belief stdev and dynamic scorevalue
#self.version = 5 #V4 features, slightly different pass-alive stones feature
#self.version = 6 #V5 features, most higher-level go features removed
#self.version = 7 #V6 features, more rules support
#self.version = 8 #V7 features, asym, lead, variance time
#self.version = 9 #V7 features, shortterm value error prediction, inference actually uses variance time, unsupported now
#self.version = 10 #V7 features, shortterm value error prediction done properly
self.version = Model.get_version(config)
# These are the only supported versions for training
# Version 9 is disabled because it's a total mess to support its partly broken versions of the value error predictions.
if self.version == 9:
raise ValueError("This is a version 9 model, which is a version that has some slightly buggy mathematical formulation of a training target and is no longer supported. Use an older version of KataGo python code to train it, such as git revision e20d7c29.")
assert(self.version == 8 or self.version == 10)
#Input layer---------------------------------------------------------------------------------
bin_inputs = (placeholders["bin_inputs"] if "bin_inputs" in placeholders else
tf.compat.v1.placeholder(tf.float32, [None] + self.bin_input_shape, name="bin_inputs"))
global_inputs = (placeholders["global_inputs"] if "global_inputs" in placeholders else
tf.compat.v1.placeholder(tf.float32, [None] + self.global_input_shape, name="global_inputs"))
symmetries = (placeholders["symmetries"] if "symmetries" in placeholders else
tf.compat.v1.placeholder(tf.bool, [3], name="symmetries"))
include_history = (placeholders["include_history"] if "include_history" in placeholders else
tf.compat.v1.placeholder(tf.float32, [None] + [5], name="include_history"))
self.assert_batched_shape("bin_inputs",bin_inputs,self.bin_input_shape)
self.assert_batched_shape("global_inputs",global_inputs,self.global_input_shape)
self.assert_shape("symmetries",symmetries,[3])
self.assert_batched_shape("include_history",include_history,[5])
self.bin_inputs = bin_inputs
self.global_inputs = global_inputs
self.symmetries = symmetries
self.include_history = include_history
cur_layer = tf.reshape(bin_inputs, [-1] + self.post_input_shape)
input_num_channels = self.post_input_shape[2]
mask_before_symmetry = cur_layer[:,:,:,0:1]
#Input symmetries - we apply symmetries during training by transforming the input and reverse-transforming the output
cur_layer = self.apply_symmetry(cur_layer,symmetries,inverse=False)
#Apply history transform to turn off various features randomly.
#We do this by building a matrix for each batch element, mapping input channels to possibly-turned off channels.
#This matrix is a sum of hist_matrix_base which always turns off all the channels, and h0, h1, h2,... which perform
#the modifications to hist_matrix_base to make it turn on channels based on whether we have move0, move1,...
if self.version >= 8:
hist_matrix_base = np.diag(np.array([
1.0, #0
1.0, #1
1.0, #2
1.0, #3
1.0, #4
1.0, #5
1.0, #6
1.0, #7
1.0, #8
0.0, #9
0.0, #10
0.0, #11
0.0, #12
0.0, #13
1.0, #14
0.0, #15
0.0, #16
1.0, #17
1.0, #18
1.0, #19
1.0, #20
1.0, #21
],dtype=np.float32))
#Because we have ladder features that express past states rather than past diffs, the most natural encoding when
#we have no history is that they were always the same, rather than that they were all zero. So rather than zeroing
#them we have no history, we add entries in the matrix to copy them over.
#By default, without history, the ladder features 15 and 16 just copy over from 14.
hist_matrix_base[14,15] = 1.0
hist_matrix_base[14,16] = 1.0
#When have the prev move, we enable feature 9 and 15
h0 = np.zeros([self.num_bin_input_features,self.num_bin_input_features],dtype=np.float32)
h0[9,9] = 1.0 #Enable 9 -> 9
h0[14,15] = -1.0 #Stop copying 14 -> 15
h0[14,16] = -1.0 #Stop copying 14 -> 16
h0[15,15] = 1.0 #Enable 15 -> 15
h0[15,16] = 1.0 #Start copying 15 -> 16
#When have the prevprev move, we enable feature 10 and 16
h1 = np.zeros([self.num_bin_input_features,self.num_bin_input_features],dtype=np.float32)
h1[10,10] = 1.0 #Enable 10 -> 10
h1[15,16] = -1.0 #Stop copying 15 -> 16
h1[16,16] = 1.0 #Enable 16 -> 16
#Further history moves
h2 = np.zeros([self.num_bin_input_features,self.num_bin_input_features],dtype=np.float32)
h2[11,11] = 1.0
h3 = np.zeros([self.num_bin_input_features,self.num_bin_input_features],dtype=np.float32)
h3[12,12] = 1.0
h4 = np.zeros([self.num_bin_input_features,self.num_bin_input_features],dtype=np.float32)
h4[13,13] = 1.0
hist_matrix_base = tf.reshape(tf.constant(hist_matrix_base),[1,self.num_bin_input_features,self.num_bin_input_features])
hist_matrix_builder = tf.constant(np.array([h0,h1,h2,h3,h4]))
assert(hist_matrix_base.dtype == tf.float32)
assert(hist_matrix_builder.dtype == tf.float32)
assert(len(hist_matrix_builder.shape) == 3)
assert(hist_matrix_builder.shape[0].value == 5)
assert(hist_matrix_builder.shape[1].value == self.num_bin_input_features)
assert(hist_matrix_builder.shape[2].value == self.num_bin_input_features)
hist_filter_matrix = hist_matrix_base + tf.tensordot(include_history, hist_matrix_builder, axes=[[1],[0]]) #[batch,move] * [move,inc,outc] = [batch,inc,outc]
cur_layer = tf.reshape(cur_layer,[-1,self.pos_len*self.pos_len,self.num_bin_input_features]) #[batch,xy,inc]
cur_layer = tf.matmul(cur_layer,hist_filter_matrix) #[batch,xy,inc] * [batch,inc,outc] = [batch,xy,outc]
cur_layer = tf.reshape(cur_layer,[-1,self.pos_len,self.pos_len,self.num_bin_input_features])
assert(include_history.shape[1].value == 5)
transformed_global_inputs = global_inputs * tf.pad(include_history, [(0,0),(0,self.num_global_input_features - include_history.shape[1].value)], constant_values=1.0)
self.transformed_bin_inputs = cur_layer
self.transformed_global_inputs = transformed_global_inputs
#Channel counts---------------------------------------------------------------------------------------
trunk_num_channels = config["trunk_num_channels"]
mid_num_channels = config["mid_num_channels"]
regular_num_channels = config["regular_num_channels"]
dilated_num_channels = config["dilated_num_channels"]
gpool_num_channels = config["gpool_num_channels"]
assert(regular_num_channels + dilated_num_channels == mid_num_channels)
self.trunk_num_channels = trunk_num_channels
self.mid_num_channels = mid_num_channels
self.regular_num_channels = regular_num_channels
self.dilated_num_channels = dilated_num_channels
self.gpool_num_channels = gpool_num_channels
mask = cur_layer[:,:,:,0:1]
mask_sum = tf.reduce_sum(mask) # Global sum
mask_sum_hw = tf.reduce_sum(mask,axis=[1,2,3]) # Sum per batch element
mask_sum_hw_sqrt = tf.sqrt(mask_sum_hw)
#Initial convolutional layer-------------------------------------------------------------------------------------