-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy pathtfprocess.py
1676 lines (1485 loc) · 73.7 KB
/
tfprocess.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
#!/usr/bin/env python3
#
# This file is part of Leela Zero.
# Copyright (C) 2017-2018 Gian-Carlo Pascutto
#
# Leela Zero is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Leela Zero is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Leela Zero. If not, see <http://www.gnu.org/licenses/>.
import numpy as np
import os
import random
import tensorflow as tf
import time
import bisect
import lc0_az_policy_map
import attention_policy_map as apm
import proto.net_pb2 as pb
from functools import reduce
import operator
from net import Net
def square_relu(x):
return tf.nn.relu(x)**2
class Gating(tf.keras.layers.Layer):
def __init__(self, name=None, additive=True, init_value=None, **kwargs):
self.additive = additive
if init_value is None:
init_value = 0 if self.additive else 1
self.init_value = init_value
super().__init__(name=name, **kwargs)
def build(self, input_shape):
self.gate = self.add_weight(name='gate',
shape=input_shape[1:],
constraint=tf.keras.constraints.NonNeg()
if not self.additive else None,
initializer=tf.constant_initializer(
self.init_value),
trainable=True)
def call(self, inputs):
return tf.add(inputs, self.gate) if self.additive else tf.multiply(
inputs, self.gate)
def ma_gating(inputs, name):
out = Gating(name=name + '/mult_gate', additive=False)(inputs)
out = Gating(name=name + '/add_gate', additive=True)(out)
return out
class ApplySqueezeExcitation(tf.keras.layers.Layer):
def __init__(self, **kwargs):
super(ApplySqueezeExcitation, self).__init__(**kwargs)
def build(self, input_dimens):
self.reshape_size = input_dimens[1][1]
def call(self, inputs):
x = inputs[0]
excited = inputs[1]
gammas, betas = tf.split(tf.reshape(excited,
[-1, self.reshape_size, 1, 1]),
2,
axis=1)
return tf.nn.sigmoid(gammas) * x + betas
class ApplyPolicyMap(tf.keras.layers.Layer):
def __init__(self, **kwargs):
super(ApplyPolicyMap, self).__init__(**kwargs)
self.fc1 = tf.constant(lc0_az_policy_map.make_map())
def call(self, inputs):
h_conv_pol_flat = tf.reshape(inputs, [-1, 80 * 8 * 8])
return tf.matmul(h_conv_pol_flat,
tf.cast(self.fc1, h_conv_pol_flat.dtype))
class ApplyAttentionPolicyMap(tf.keras.layers.Layer):
def __init__(self, **kwargs):
super(ApplyAttentionPolicyMap, self).__init__(**kwargs)
self.fc1 = tf.constant(apm.make_map())
def call(self, logits, pp_logits):
logits = tf.concat([
tf.reshape(logits, [-1, 64 * 64]),
tf.reshape(pp_logits, [-1, 8 * 24])
],
axis=1)
return tf.matmul(logits, tf.cast(self.fc1, logits.dtype))
class Metric:
def __init__(self, short_name, long_name, suffix='', **kwargs):
self.short_name = short_name
self.long_name = long_name
self.suffix = suffix
self.value = 0.0
self.count = 0
def assign(self, value):
self.value = value
self.count = 1
def accumulate(self, value):
if self.count > 0:
self.value = self.value + value
self.count = self.count + 1
else:
self.assign(value)
def merge(self, other):
assert self.short_name == other.short_name
self.value = self.value + other.value
self.count = self.count + other.count
def get(self):
if self.count == 0:
return self.value
return self.value / self.count
def reset(self):
self.value = 0.0
self.count = 0
class TFProcess:
def __init__(self, cfg):
self.cfg = cfg
self.net = Net()
self.root_dir = os.path.join(self.cfg['training']['path'],
self.cfg['name'])
# Network structure
self.RESIDUAL_FILTERS = self.cfg['model'].get('filters', 0)
self.RESIDUAL_BLOCKS = self.cfg['model'].get('residual_blocks', 0)
self.SE_ratio = self.cfg['model'].get('se_ratio', 0)
self.encoder_layers = self.cfg['model'].get('encoder_layers', 0)
self.encoder_heads = self.cfg['model'].get('encoder_heads', 2)
assert (self.RESIDUAL_BLOCKS > 0) != (self.encoder_layers > 0), \
"Nets with both encoder layers and residual blocks are not supported"
if self.encoder_layers > 0:
self.RESIDUAL_FILTERS = self.cfg['model']['embedding_size']
self.embedding_size = self.RESIDUAL_FILTERS
self.policy_channels = self.cfg['model'].get('policy_channels', 32)
self.pol_embedding_size = self.cfg['model'].get(
'pol_embedding_size', self.RESIDUAL_FILTERS)
self.val_embedding_size = self.cfg['model'].get(
'value_embedding_size', 32)
self.mov_embedding_size = self.cfg['model'].get(
'moves_left_embedding_size', 8)
#policy head
self.pol_encoder_layers = (0 if self.encoder_layers > 0 else 1)
#logic is to explictly warn users who set both in yaml
if self.cfg['model'].get('pol_encoder_layers') is not None:
self.pol_encoder_layers = self.cfg['model'].get(
'pol_encoder_layers')
assert not ((self.pol_encoder_layers > 0) and (self.encoder_layers > 0)), \
"Nets with both body encoder layers and policy encoder layers are not supported"
self.pol_encoder_heads = self.cfg['model'].get('pol_encoder_heads', 2)
self.pol_encoder_d_model = self.cfg['model'].get(
'pol_encoder_d_model', self.RESIDUAL_FILTERS)
self.pol_encoder_dff = self.cfg['model'].get(
'pol_encoder_dff', (self.RESIDUAL_FILTERS * 1.5) // 1)
self.policy_d_model = self.cfg['model'].get('policy_d_model',
self.RESIDUAL_FILTERS)
#encoder body
self.input_gate = self.cfg['model'].get('input_gate')
self.encoder_d_model = self.cfg['model'].get('encoder_d_model')
self.encoder_dff = self.cfg['model'].get(
'encoder_dff', (self.RESIDUAL_FILTERS * 1.5) // 1)
self.policy_d_model = self.cfg['model'].get('policy_d_model',
self.RESIDUAL_FILTERS)
self.arc_encoding = self.cfg['model'].get('arc_encoding', True)
self.square_relu_ffn = self.cfg['model'].get('square_relu_ffn', False)
self.use_smolgen = self.cfg['model'].get('use_smolgen', False)
self.smolgen_hidden_channels = self.cfg['model'].get(
'smolgen_hidden_channels', 16)
self.smolgen_hidden_sz = self.cfg['model'].get('smolgen_hidden_sz',
128)
self.smolgen_gen_sz = self.cfg['model'].get('smolgen_gen_sz', 128)
self.smolgen_activation = self.cfg['model'].get(
'smolgen_activation', 'swish')
self.dropout_rate = self.cfg['model'].get('dropout_rate', 0.0)
precision = self.cfg['training'].get('precision', 'single')
loss_scale = self.cfg['training'].get('loss_scale', 128)
self.virtual_batch_size = self.cfg['model'].get(
'virtual_batch_size', None)
if precision == 'single':
self.model_dtype = tf.float32
elif precision == 'half':
self.model_dtype = tf.float16
else:
raise ValueError("Unknown precision: {}".format(precision))
# Scale the loss to prevent gradient underflow
self.loss_scale = 1 if self.model_dtype == tf.float32 else loss_scale
policy_head = self.cfg['model'].get('policy', 'convolution')
value_head = self.cfg['model'].get('value', 'wdl')
moves_left_head = self.cfg['model'].get('moves_left', 'v1')
input_mode = self.cfg['model'].get('input_type', 'classic')
default_activation = self.cfg['model'].get('default_activation',
'relu')
self.POLICY_HEAD = None
self.VALUE_HEAD = None
self.MOVES_LEFT_HEAD = None
self.INPUT_MODE = None
self.DEFAULT_ACTIVATION = None
if policy_head == "classical":
self.POLICY_HEAD = pb.NetworkFormat.POLICY_CLASSICAL
elif policy_head == "convolution":
self.POLICY_HEAD = pb.NetworkFormat.POLICY_CONVOLUTION
elif policy_head == "attention":
self.POLICY_HEAD = pb.NetworkFormat.POLICY_ATTENTION
if self.pol_encoder_layers > 0:
self.net.set_pol_headcount(self.pol_encoder_heads)
else:
raise ValueError(
"Unknown policy head format: {}".format(policy_head))
self.net.set_policyformat(self.POLICY_HEAD)
if value_head == "classical":
self.VALUE_HEAD = pb.NetworkFormat.VALUE_CLASSICAL
self.wdl = False
elif value_head == "wdl":
self.VALUE_HEAD = pb.NetworkFormat.VALUE_WDL
self.wdl = True
else:
raise ValueError(
"Unknown value head format: {}".format(value_head))
self.net.set_valueformat(self.VALUE_HEAD)
if moves_left_head == "none":
self.MOVES_LEFT_HEAD = pb.NetworkFormat.MOVES_LEFT_NONE
self.moves_left = False
elif moves_left_head == "v1":
self.MOVES_LEFT_HEAD = pb.NetworkFormat.MOVES_LEFT_V1
self.moves_left = True
else:
raise ValueError(
"Unknown moves left head format: {}".format(moves_left_head))
self.net.set_movesleftformat(self.MOVES_LEFT_HEAD)
if input_mode == "classic":
self.INPUT_MODE = pb.NetworkFormat.INPUT_CLASSICAL_112_PLANE
elif input_mode == "frc_castling":
self.INPUT_MODE = pb.NetworkFormat.INPUT_112_WITH_CASTLING_PLANE
elif input_mode == "canonical":
self.INPUT_MODE = pb.NetworkFormat.INPUT_112_WITH_CANONICALIZATION
elif input_mode == "canonical_100":
self.INPUT_MODE = pb.NetworkFormat.INPUT_112_WITH_CANONICALIZATION_HECTOPLIES
elif input_mode == "canonical_armageddon":
self.INPUT_MODE = pb.NetworkFormat.INPUT_112_WITH_CANONICALIZATION_HECTOPLIES_ARMAGEDDON
elif input_mode == "canonical_v2":
self.INPUT_MODE = pb.NetworkFormat.INPUT_112_WITH_CANONICALIZATION_V2
elif input_mode == "canonical_v2_armageddon":
self.INPUT_MODE = pb.NetworkFormat.INPUT_112_WITH_CANONICALIZATION_V2_ARMAGEDDON
else:
raise ValueError(
"Unknown input mode format: {}".format(input_mode))
self.net.set_input(self.INPUT_MODE)
if default_activation == "relu":
self.net.set_defaultactivation(
pb.NetworkFormat.DEFAULT_ACTIVATION_RELU)
self.DEFAULT_ACTIVATION = 'relu'
elif default_activation == "mish":
self.net.set_defaultactivation(
pb.NetworkFormat.DEFAULT_ACTIVATION_MISH)
try:
self.DEFAULT_ACTIVATION = tf.keras.activations.mish
except AttributeError:
import tensorflow_addons as tfa
self.DEFAULT_ACTIVATION = tfa.activations.mish
else:
raise ValueError("Unknown default activation type: {}".format(
default_activation))
if self.encoder_layers > 0:
self.net.set_headcount(self.encoder_heads)
self.net.set_networkformat(
pb.NetworkFormat.NETWORK_ATTENTIONBODY_WITH_HEADFORMAT)
self.net.set_smolgen_activation(
self.net.activation(self.smolgen_activation))
self.net.set_ffn_activation(
self.net.activation(
'sqrrelu' if self.square_relu_ffn else 'default'))
self.swa_enabled = self.cfg['training'].get('swa', False)
# Limit momentum of SWA exponential average to 1 - 1/(swa_max_n + 1)
self.swa_max_n = self.cfg['training'].get('swa_max_n', 0)
self.renorm_enabled = self.cfg['training'].get('renorm', False)
self.renorm_max_r = self.cfg['training'].get('renorm_max_r', 1)
self.renorm_max_d = self.cfg['training'].get('renorm_max_d', 0)
self.renorm_momentum = self.cfg['training'].get(
'renorm_momentum', 0.99)
if self.cfg['gpu'] == 'all':
gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
self.strategy = tf.distribute.MirroredStrategy()
tf.distribute.experimental_set_strategy(self.strategy)
else:
gpus = tf.config.experimental.list_physical_devices('GPU')
print(gpus)
tf.config.experimental.set_visible_devices(gpus[self.cfg['gpu']],
'GPU')
tf.config.experimental.set_memory_growth(gpus[self.cfg['gpu']],
True)
self.strategy = None
if self.model_dtype == tf.float16:
tf.keras.mixed_precision.experimental.set_policy('mixed_float16')
self.global_step = tf.Variable(0,
name='global_step',
trainable=False,
dtype=tf.int64)
def init(self, train_dataset, test_dataset, validation_dataset=None):
if self.strategy is not None:
self.train_dataset = self.strategy.experimental_distribute_dataset(
train_dataset)
else:
self.train_dataset = train_dataset
self.train_iter = iter(self.train_dataset)
if self.strategy is not None:
self.test_dataset = self.strategy.experimental_distribute_dataset(
test_dataset)
else:
self.test_dataset = test_dataset
self.test_iter = iter(self.test_dataset)
if self.strategy is not None and validation_dataset is not None:
self.validation_dataset = self.strategy.experimental_distribute_dataset(
validation_dataset)
else:
self.validation_dataset = validation_dataset
if self.strategy is not None:
this = self
with self.strategy.scope():
this.init_net()
else:
self.init_net()
def init_net(self):
self.l2reg = tf.keras.regularizers.l2(l=0.5 * (0.0001))
input_var = tf.keras.Input(shape=(112, 8, 8))
outputs = self.construct_net(input_var)
self.model = tf.keras.Model(inputs=input_var, outputs=outputs)
# swa_count initialized regardless to make checkpoint code simpler.
self.swa_count = tf.Variable(0., name='swa_count', trainable=False)
self.swa_weights = None
if self.swa_enabled:
# Count of networks accumulated into SWA
self.swa_weights = [
tf.Variable(w, trainable=False) for w in self.model.weights
]
self.active_lr = tf.Variable(0.01, trainable=False)
# All 'new' (TF 2.10 or newer non-legacy) optimizers must have learning_rate updated manually.
self.update_lr_manually = False
# Be sure not to set new_optimizer before TF 2.11, or unless you edit the code to specify a new optimizer explicitly.
if self.cfg['training'].get('new_optimizer'):
self.optimizer = tf.keras.optimizers.SGD(
learning_rate=self.active_lr, momentum=0.9, nesterov=True)
self.update_lr_manually = True
else:
try:
self.optimizer = tf.keras.optimizers.legacy.SGD(
learning_rate=lambda: self.active_lr,
momentum=0.9,
nesterov=True)
except AttributeError:
self.optimizer = tf.keras.optimizers.SGD(
learning_rate=lambda: self.active_lr,
momentum=0.9,
nesterov=True)
self.orig_optimizer = self.optimizer
try:
self.aggregator = self.orig_optimizer.aggregate_gradients
except AttributeError:
self.aggregator = self.orig_optimizer.gradient_aggregator
if self.loss_scale != 1:
self.optimizer = tf.keras.mixed_precision.experimental.LossScaleOptimizer(
self.optimizer, self.loss_scale)
if self.cfg['training'].get('lookahead_optimizer'):
import tensorflow_addons as tfa
self.optimizer = tfa.optimizers.Lookahead(self.optimizer)
def correct_policy(target, output):
output = tf.cast(output, tf.float32)
# Calculate loss on policy head
if self.cfg['training'].get('mask_legal_moves'):
# extract mask for legal moves from target policy
move_is_legal = tf.greater_equal(target, 0)
# replace logits of illegal moves with large negative value (so that it doesn't affect policy of legal moves) without gradient
illegal_filler = tf.zeros_like(output) - 1.0e10
output = tf.where(move_is_legal, output, illegal_filler)
# y_ still has -1 on illegal moves, flush them to 0
target = tf.nn.relu(target)
return target, output
def policy_loss(target, output):
target, output = correct_policy(target, output)
policy_cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
labels=tf.stop_gradient(target), logits=output)
return tf.reduce_mean(input_tensor=policy_cross_entropy)
self.policy_loss_fn = policy_loss
def policy_accuracy(target, output):
target, output = correct_policy(target, output)
return tf.reduce_mean(
tf.cast(
tf.equal(tf.argmax(input=target, axis=1),
tf.argmax(input=output, axis=1)), tf.float32))
self.policy_accuracy_fn = policy_accuracy
def moves_left_mean_error_fn(target, output):
output = tf.cast(output, tf.float32)
return tf.reduce_mean(tf.abs(target - output))
self.moves_left_mean_error = moves_left_mean_error_fn
def policy_entropy(target, output):
target, output = correct_policy(target, output)
softmaxed = tf.nn.softmax(output)
return tf.math.negative(
tf.reduce_mean(
tf.reduce_sum(tf.math.xlogy(softmaxed, softmaxed),
axis=1)))
self.policy_entropy_fn = policy_entropy
def policy_uniform_loss(target, output):
uniform = tf.where(tf.greater_equal(target, 0),
tf.ones_like(target), tf.zeros_like(target))
balanced_uniform = uniform / tf.reduce_sum(
uniform, axis=1, keepdims=True)
target, output = correct_policy(target, output)
policy_cross_entropy = \
tf.nn.softmax_cross_entropy_with_logits(labels=tf.stop_gradient(balanced_uniform),
logits=output)
return tf.reduce_mean(input_tensor=policy_cross_entropy)
self.policy_uniform_loss_fn = policy_uniform_loss
q_ratio = self.cfg['training'].get('q_ratio', 0)
assert 0 <= q_ratio <= 1
# Linear conversion to scalar to compute MSE with, for comparison to old values
wdl = tf.expand_dims(tf.constant([1.0, 0.0, -1.0]), 1)
self.qMix = lambda z, q: q * q_ratio + z * (1 - q_ratio)
# Loss on value head
if self.wdl:
def value_loss(target, output):
output = tf.cast(output, tf.float32)
value_cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
labels=tf.stop_gradient(target), logits=output)
return tf.reduce_mean(input_tensor=value_cross_entropy)
self.value_loss_fn = value_loss
def mse_loss(target, output):
output = tf.cast(output, tf.float32)
scalar_z_conv = tf.matmul(tf.nn.softmax(output), wdl)
scalar_target = tf.matmul(target, wdl)
return tf.reduce_mean(input_tensor=tf.math.squared_difference(
scalar_target, scalar_z_conv))
self.mse_loss_fn = mse_loss
else:
def value_loss(target, output):
return tf.constant(0)
self.value_loss_fn = value_loss
def mse_loss(target, output):
output = tf.cast(output, tf.float32)
scalar_target = tf.matmul(target, wdl)
return tf.reduce_mean(input_tensor=tf.math.squared_difference(
scalar_target, output))
self.mse_loss_fn = mse_loss
if self.moves_left:
def moves_left_loss(target, output):
# Scale the loss to similar range as other losses.
scale = 20.0
target = target / scale
output = tf.cast(output, tf.float32) / scale
if self.strategy is not None:
huber = tf.keras.losses.Huber(
10.0 / scale, reduction=tf.keras.losses.Reduction.NONE)
else:
huber = tf.keras.losses.Huber(10.0 / scale)
return tf.reduce_mean(huber(target, output))
else:
moves_left_loss = None
self.moves_left_loss_fn = moves_left_loss
pol_loss_w = self.cfg['training']['policy_loss_weight']
val_loss_w = self.cfg['training']['value_loss_weight']
if self.moves_left:
moves_loss_w = self.cfg['training']['moves_left_loss_weight']
else:
moves_loss_w = tf.constant(0.0, dtype=tf.float32)
reg_term_w = self.cfg['training'].get('reg_term_weight', 1.0)
def _lossMix(policy, value, moves_left, reg_term):
return pol_loss_w * policy + val_loss_w * value + moves_loss_w * moves_left + reg_term_w * reg_term
self.lossMix = _lossMix
def accuracy(target, output):
output = tf.cast(output, tf.float32)
return tf.reduce_mean(
tf.cast(
tf.equal(tf.argmax(input=target, axis=1),
tf.argmax(input=output, axis=1)), tf.float32))
self.accuracy_fn = accuracy
# Order must match the order in process_inner_loop
self.train_metrics = [
Metric('P', 'Policy Loss'),
Metric('V', 'Value Loss'),
Metric('ML', 'Moves Left Loss'),
Metric('Reg', 'Reg term'),
Metric('Total', 'Total Loss'),
Metric(
'V MSE', 'MSE Loss'
), # Long name here doesn't mention value for backwards compatibility reasons.
]
self.time_start = None
self.last_steps = None
# Order must match the order in calculate_test_summaries_inner_loop
self.test_metrics = [
Metric('P', 'Policy Loss'),
Metric('V', 'Value Loss'),
Metric('ML', 'Moves Left Loss'),
Metric(
'V MSE', 'MSE Loss'
), # Long name here doesn't mention value for backwards compatibility reasons.
Metric('P Acc', 'Policy Accuracy', suffix='%'),
Metric('V Acc', 'Value Accuracy', suffix='%'),
Metric('ML Mean', 'Moves Left Mean Error'),
Metric('P Entropy', 'Policy Entropy'),
Metric('P UL', 'Policy UL'),
]
# Set adaptive learning rate during training
self.cfg['training']['lr_boundaries'].sort()
self.warmup_steps = self.cfg['training'].get('warmup_steps', 0)
self.lr = self.cfg['training']['lr_values'][0]
self.test_writer = tf.summary.create_file_writer(
os.path.join(os.getcwd(),
"leelalogs/{}-test".format(self.cfg['name'])))
self.train_writer = tf.summary.create_file_writer(
os.path.join(os.getcwd(),
"leelalogs/{}-train".format(self.cfg['name'])))
if vars(self).get('validation_dataset', None) is not None:
self.validation_writer = tf.summary.create_file_writer(
os.path.join(
os.getcwd(),
"leelalogs/{}-validation".format(self.cfg['name'])))
if self.swa_enabled:
self.swa_writer = tf.summary.create_file_writer(
os.path.join(os.getcwd(),
"leelalogs/{}-swa-test".format(self.cfg['name'])))
self.swa_validation_writer = tf.summary.create_file_writer(
os.path.join(
os.getcwd(),
"leelalogs/{}-swa-validation".format(self.cfg['name'])))
self.checkpoint = tf.train.Checkpoint(optimizer=self.orig_optimizer,
model=self.model,
global_step=self.global_step,
swa_count=self.swa_count)
self.checkpoint.listed = self.swa_weights
self.manager = tf.train.CheckpointManager(
self.checkpoint,
directory=self.root_dir,
max_to_keep=50,
keep_checkpoint_every_n_hours=24,
checkpoint_name=self.cfg['name'])
def replace_weights(self, proto_filename, ignore_errors=False):
self.net.parse_proto(proto_filename)
filters, blocks = self.net.filters(), self.net.blocks()
if not ignore_errors:
if self.RESIDUAL_FILTERS != filters:
raise ValueError("Number of filters doesn't match the network")
if self.RESIDUAL_BLOCKS != blocks:
raise ValueError("Number of blocks doesn't match the network")
if self.POLICY_HEAD != self.net.pb.format.network_format.policy:
raise ValueError("Policy head type doesn't match the network")
if self.VALUE_HEAD != self.net.pb.format.network_format.value:
raise ValueError("Value head type doesn't match the network")
# List all tensor names we need weights for.
names = []
for weight in self.model.weights:
names.append(weight.name)
new_weights = self.net.get_weights_v2(names)
for weight in self.model.weights:
if 'renorm' in weight.name:
# Renorm variables are not populated.
continue
try:
new_weight = new_weights[weight.name]
except KeyError:
error_string = 'No values for tensor {} in protobuf'.format(
weight.name)
if ignore_errors:
print(error_string)
continue
else:
raise KeyError(error_string)
if reduce(operator.mul, weight.shape.as_list(),
1) != len(new_weight):
error_string = 'Tensor {} has wrong length. Tensorflow shape {}, size in protobuf {}'.format(
weight.name, weight.shape.as_list(), len(new_weight))
if ignore_errors:
print(error_string)
continue
else:
raise KeyError(error_string)
if weight.shape.ndims == 4:
# Rescale rule50 related weights as clients do not normalize the input.
if weight.name == 'input/conv2d/kernel:0' and self.net.pb.format.network_format.input < pb.NetworkFormat.INPUT_112_WITH_CANONICALIZATION_HECTOPLIES:
num_inputs = 112
# 50 move rule is the 110th input, or 109 starting from 0.
rule50_input = 109
for i in range(len(new_weight)):
if (i % (num_inputs * 9)) // 9 == rule50_input:
new_weight[i] = new_weight[i] * 99
# Convolution weights need a transpose
#
# TF (kYXInputOutput)
# [filter_height, filter_width, in_channels, out_channels]
#
# Leela/cuDNN/Caffe (kOutputInputYX)
# [output, input, filter_size, filter_size]
s = weight.shape.as_list()
shape = [s[i] for i in [3, 2, 0, 1]]
new_weight = tf.constant(new_weight, shape=shape)
weight.assign(tf.transpose(a=new_weight, perm=[2, 3, 1, 0]))
elif weight.shape.ndims == 2:
# Fully connected layers are [in, out] in TF
#
# [out, in] in Leela
#
s = weight.shape.as_list()
shape = [s[i] for i in [1, 0]]
new_weight = tf.constant(new_weight, shape=shape)
weight.assign(tf.transpose(a=new_weight, perm=[1, 0]))
else:
# Biases, batchnorm etc
new_weight = tf.constant(new_weight, shape=weight.shape)
weight.assign(new_weight)
# Replace the SWA weights as well, ensuring swa accumulation is reset.
if self.swa_enabled:
self.swa_count.assign(tf.constant(0.))
self.update_swa()
# This should result in identical file to the starting one
# self.save_leelaz_weights('restored.pb.gz')
def restore(self):
if self.manager.latest_checkpoint is not None:
print("Restoring from {0}".format(self.manager.latest_checkpoint))
self.checkpoint.restore(self.manager.latest_checkpoint)
def process_loop(self, batch_size, test_batches, batch_splits=1):
if self.swa_enabled:
# split half of test_batches between testing regular weights and SWA weights
test_batches //= 2
# Make sure that ghost batch norm can be applied
if self.virtual_batch_size and batch_size % self.virtual_batch_size != 0:
# Adjust required batch size for batch splitting.
required_factor = self.virtual_batch_size * self.cfg[
'training'].get('num_batch_splits', 1)
raise ValueError(
'batch_size must be a multiple of {}'.format(required_factor))
# Get the initial steps value in case this is a resume from a step count
# which is not a multiple of total_steps.
steps = self.global_step.read_value()
self.last_steps = steps
self.time_start = time.time()
self.profiling_start_step = None
total_steps = self.cfg['training']['total_steps']
for _ in range(steps % total_steps, total_steps):
self.process(batch_size, test_batches, batch_splits=batch_splits)
@tf.function()
def read_weights(self):
return [w.read_value() for w in self.model.weights]
@tf.function()
def process_inner_loop(self, x, y, z, q, m):
with tf.GradientTape() as tape:
outputs = self.model(x, training=True)
policy = outputs[0]
value = outputs[1]
policy_loss = self.policy_loss_fn(y, policy)
reg_term = sum(self.model.losses)
if self.wdl:
value_ce_loss = self.value_loss_fn(self.qMix(z, q), value)
value_loss = value_ce_loss
else:
value_mse_loss = self.mse_loss_fn(self.qMix(z, q), value)
value_loss = value_mse_loss
if self.moves_left:
moves_left = outputs[2]
moves_left_loss = self.moves_left_loss_fn(m, moves_left)
else:
moves_left_loss = tf.constant(0.)
total_loss = self.lossMix(policy_loss, value_loss, moves_left_loss,
reg_term)
if self.loss_scale != 1:
total_loss = self.optimizer.get_scaled_loss(total_loss)
if self.wdl:
mse_loss = self.mse_loss_fn(self.qMix(z, q), value)
else:
value_loss = self.value_loss_fn(self.qMix(z, q), value)
metrics = [
policy_loss,
value_loss,
moves_left_loss,
reg_term,
total_loss,
# Google's paper scales MSE by 1/4 to a [0, 1] range, so do the same to
# get comparable values.
mse_loss / 4.0,
]
return metrics, tape.gradient(total_loss, self.model.trainable_weights)
@tf.function()
def strategy_process_inner_loop(self, x, y, z, q, m):
metrics, new_grads = self.strategy.run(self.process_inner_loop,
args=(x, y, z, q, m))
metrics = [
self.strategy.reduce(tf.distribute.ReduceOp.MEAN, m, axis=None)
for m in metrics
]
return metrics, new_grads
def apply_grads(self, grads, effective_batch_splits):
grads = [
g[0]
for g in self.aggregator(zip(grads, self.model.trainable_weights))
]
if self.loss_scale != 1:
grads = self.optimizer.get_unscaled_gradients(grads)
max_grad_norm = self.cfg['training'].get(
'max_grad_norm', 10000.0) * effective_batch_splits
grads, grad_norm = tf.clip_by_global_norm(grads, max_grad_norm)
self.optimizer.apply_gradients(zip(grads,
self.model.trainable_weights),
experimental_aggregate_gradients=False)
return grad_norm
@tf.function()
def strategy_apply_grads(self, grads, effective_batch_splits):
grad_norm = self.strategy.run(self.apply_grads,
args=(grads, effective_batch_splits))
grad_norm = self.strategy.reduce(tf.distribute.ReduceOp.MEAN,
grad_norm,
axis=None)
return grad_norm
@tf.function()
def merge_grads(self, grads, new_grads):
return [tf.math.add(a, b) for (a, b) in zip(grads, new_grads)]
@tf.function()
def strategy_merge_grads(self, grads, new_grads):
return self.strategy.run(self.merge_grads, args=(grads, new_grads))
def train_step(self, steps, batch_size, batch_splits):
# need to add 1 to steps because steps will be incremented after gradient update
if (steps +
1) % self.cfg['training']['train_avg_report_steps'] == 0 or (
steps + 1) % self.cfg['training']['total_steps'] == 0:
before_weights = self.read_weights()
# Run training for this batch
grads = None
for _ in range(batch_splits):
x, y, z, q, m = next(self.train_iter)
if self.strategy is not None:
metrics, new_grads = self.strategy_process_inner_loop(
x, y, z, q, m)
else:
metrics, new_grads = self.process_inner_loop(x, y, z, q, m)
if not grads:
grads = new_grads
else:
if self.strategy is not None:
grads = self.strategy_merge_grads(grads, new_grads)
else:
grads = self.merge_grads(grads, new_grads)
# Keep running averages
for acc, val in zip(self.train_metrics, metrics):
acc.accumulate(val)
# Gradients of batch splits are summed, not averaged like usual, so need to scale lr accordingly to correct for this.
effective_batch_splits = batch_splits
if self.strategy is not None:
effective_batch_splits = batch_splits * self.strategy.num_replicas_in_sync
self.active_lr.assign(self.lr / effective_batch_splits)
if self.update_lr_manually:
self.orig_optimizer.learning_rate = self.active_lr
if self.strategy is not None:
grad_norm = self.strategy_apply_grads(grads,
effective_batch_splits)
else:
grad_norm = self.apply_grads(grads, effective_batch_splits)
# Note: grads variable at this point has not been unscaled or
# had clipping applied. Since no code after this point depends
# upon that it seems fine for now.
# Update steps.
self.global_step.assign_add(1)
steps = self.global_step.read_value()
if steps % self.cfg['training'][
'train_avg_report_steps'] == 0 or steps % self.cfg['training'][
'total_steps'] == 0:
time_end = time.time()
speed = 0
if self.time_start:
elapsed = time_end - self.time_start
steps_elapsed = steps - self.last_steps
speed = batch_size * (tf.cast(steps_elapsed, tf.float32) /
elapsed)
print("step {}, lr={:g}".format(steps, self.lr), end='')
for metric in self.train_metrics:
print(" {}={:g}{}".format(metric.short_name, metric.get(),
metric.suffix),
end='')
print(" ({:g} pos/s)".format(speed))
after_weights = self.read_weights()
with self.train_writer.as_default():
for metric in self.train_metrics:
tf.summary.scalar(metric.long_name,
metric.get(),
step=steps)
tf.summary.scalar("LR", self.lr, step=steps)
tf.summary.scalar("Gradient norm",
grad_norm / effective_batch_splits,
step=steps)
self.compute_update_ratio(before_weights, after_weights, steps)
self.train_writer.flush()
self.time_start = time_end
self.last_steps = steps
for metric in self.train_metrics:
metric.reset()
return steps
def process(self, batch_size, test_batches, batch_splits):
# Get the initial steps value before we do a training step.
steps = self.global_step.read_value()
# By default disabled since 0 != 10.
if steps % self.cfg['training'].get('profile_step_freq',
1) == self.cfg['training'].get(
'profile_step_offset', 10):
self.profiling_start_step = steps
tf.profiler.experimental.start(
os.path.join(os.getcwd(),
"leelalogs/{}-profile".format(self.cfg['name'])))
# Run test before first step to see delta since end of last run.
if steps % self.cfg['training']['total_steps'] == 0:
with tf.profiler.experimental.Trace("Test", step_num=steps + 1):
# Steps is given as one higher than current in order to avoid it
# being equal to the value the end of a run is stored against.
self.calculate_test_summaries(test_batches, steps + 1)
if self.swa_enabled:
self.calculate_swa_summaries(test_batches, steps + 1)
# Determine learning rate
lr_values = self.cfg['training']['lr_values']
lr_boundaries = self.cfg['training']['lr_boundaries']
steps_total = steps % self.cfg['training']['total_steps']
self.lr = lr_values[bisect.bisect_right(lr_boundaries, steps_total)]
if self.warmup_steps > 0 and steps < self.warmup_steps:
self.lr = self.lr * tf.cast(steps + 1,
tf.float32) / self.warmup_steps
with tf.profiler.experimental.Trace("Train", step_num=steps):
steps = self.train_step(steps, batch_size, batch_splits)
if self.swa_enabled and steps % self.cfg['training']['swa_steps'] == 0:
self.update_swa()
# Calculate test values every 'test_steps', but also ensure there is
# one at the final step so the delta to the first step can be calculated.
if steps % self.cfg['training']['test_steps'] == 0 or steps % self.cfg[
'training']['total_steps'] == 0:
with tf.profiler.experimental.Trace("Test", step_num=steps):
self.calculate_test_summaries(test_batches, steps)
if self.swa_enabled:
self.calculate_swa_summaries(test_batches, steps)
if self.validation_dataset is not None and (
steps % self.cfg['training']['validation_steps'] == 0
or steps % self.cfg['training']['total_steps'] == 0):
with tf.profiler.experimental.Trace("Validate", step_num=steps):
if self.swa_enabled:
self.calculate_swa_validations(steps)
else:
self.calculate_test_validations(steps)
# Save session and weights at end, and also optionally every 'checkpoint_steps'.
if steps % self.cfg['training']['total_steps'] == 0 or (
'checkpoint_steps' in self.cfg['training']
and steps % self.cfg['training']['checkpoint_steps'] == 0):
evaled_steps = steps.numpy()
self.manager.save(checkpoint_number=evaled_steps)
print("Model saved in file: {}".format(
self.manager.latest_checkpoint))
path = os.path.join(self.root_dir, self.cfg['name'])
leela_path = path + "-" + str(evaled_steps)
swa_path = path + "-swa-" + str(evaled_steps)
self.net.pb.training_params.training_steps = evaled_steps
self.save_leelaz_weights(leela_path)
if self.swa_enabled:
self.save_swa_weights(swa_path)
if self.profiling_start_step is not None and (
steps >= self.profiling_start_step +
self.cfg['training'].get('profile_step_count', 0)
or steps % self.cfg['training']['total_steps'] == 0):
tf.profiler.experimental.stop()
self.profiling_start_step = None
def calculate_swa_summaries(self, test_batches, steps):
backup = self.read_weights()
for (swa, w) in zip(self.swa_weights, self.model.weights):
w.assign(swa.read_value())
true_test_writer, self.test_writer = self.test_writer, self.swa_writer
print('swa', end=' ')
self.calculate_test_summaries(test_batches, steps)
self.test_writer = true_test_writer
for (old, w) in zip(backup, self.model.weights):