-
Notifications
You must be signed in to change notification settings - Fork 3
/
ESCHER.py
1671 lines (1453 loc) · 71.4 KB
/
ESCHER.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
# Original code from OpenSpiel Deep CFR implementation:
# https://github.com/deepmind/open_spiel/blob/master/open_spiel/python/algorithms/deep_cfr_tf2.py
# Original Deep CFR code copyright 2019 DeepMind Technologies Limited
# ESCHER Code copyright 2022 Stephen McAleer
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implements ESCHER.
The algorithm defines `regret`, `value`, and `average policy` networks.
The regret network is trained to estimate the cumulative regret for an infostate-action pair.
The policy at each timestep comes from performing regret matching on the estimated cumulative regret.
The value network is trained to estimate the value of a game under the current joint policy conditioned
on a history (state).
The average policy network is trained to estimate the average policy over all timesteps.
To train these networks we use three reservoir buffers, one for each network.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from datetime import datetime
import collections
import contextlib
import os
import random
import numpy as np
import tensorflow as tf
from open_spiel.python import policy
from open_spiel.python.algorithms import exploitability
import pyspiel
import time
# The size of the shuffle buffer used to reshuffle part of the data each
# epoch within one training iteration
REGRET_TRAIN_SHUFFLE_SIZE = 100000
VALUE_TRAIN_SHUFFLE_SIZE = 100000
AVERAGE_POLICY_TRAIN_SHUFFLE_SIZE = 1000000
def battleship_history_tensor(state):
"""
Important! Only works for
board_width = 2,
board_height = 2,
ship_sizes = [1;2],
num_shots = 4,
allow_repeated_shots = False
"""
# first 4 spots are location of a for player 0
# next 4 spots are location of b for player 0
# next 4 spots are all of player 0's actions
# then repeat for player 1
history = state.history()
history_tensor = np.zeros(2 * (4 + 4 + 4))
b_map = {4: 0, 6: 1, 8: 2, 9: 3}
for i in range(len(history)):
if i == 0: # a for player 0
action = history[i] - 4
history_tensor[action] = 1
elif i == 1: # a for player 1
action = history[i] - 4
history_tensor[12 + action] = 1
elif i == 2: # b for player 0
action = b_map[history[i]]
history_tensor[4 + action] = 1
elif i == 3:
action = b_map[history[i]]
history_tensor[12 + 4 + action] = 1
else:
action = history[i]
if i % 2 == 0:
history_tensor[8 + action] = 1
else:
history_tensor[12 + 8 + action] = 1
return history_tensor
def battleship_infostate_tensor(state, player):
"""
Important! Only works for
board_width = 2,
board_height = 2,
ship_sizes = [1;2],
num_shots = 4,
allow_repeated_shots = False
"""
# first 4 spots are location of a for player
# next 4 spots are location of b for player
# next 4 spots are for player's actions that are hits
# next 4 spots are for player's actions that are water
# next 4 spots are for player's actions that are sinks
# next 4 spots are all of other player's actions
string_to_index_map = {
'0_0': 0,
'0_1': 1,
'1_0': 2,
'1_1': 3,
}
info_tensor = np.zeros(6 * 4)
info_list = state.information_state_string(player).split("/")
for i in range(len(info_list)):
info = info_list[i]
if i == 1:
assert info[0] == 'h' or info[0] == 'v'
index = string_to_index_map[info[-3:]]
info_tensor[index] = 1
if i == 2:
assert info[0] == 'h' or info[0] == 'v'
index = string_to_index_map[info[-3:]]
info_tensor[index + 4] = 1
if i > 2:
if info[0] == 's':
index = string_to_index_map[info[-5:-2]]
if info[-1] == 'H':
info_tensor[index + 2 * 4] = 1
elif info[-1] == 'W':
info_tensor[index + 3 * 4] = 1
elif info[-1] == 'S':
info_tensor[index + 4 * 4] = 1
else:
print(info, "unexpected infostate")
return None
elif info[0] == 'o':
index = string_to_index_map[info[-3:]]
info_tensor[index + 5 * 4] = 1
else:
print(info, 'unexpected infostate')
return None
return info_tensor
def get_oshi_hist_obs(obs_tensor, current_player, num_coins, last_action):
last_action_array = np.zeros(num_coins + 1)
if current_player == 1:
assert obs_tensor[1] == 1
last_action_array[last_action] = 1
return np.append(obs_tensor, last_action_array)
def get_markov_soccer_hist_obs(obs_tensor, current_player, last_action):
last_action_array = np.zeros(5)
if current_player == 1:
assert obs_tensor[1] == 1
last_action_array[last_action] = 1
return np.append(obs_tensor, last_action_array)
class ReservoirBuffer(object):
"""Allows uniform sampling over a stream of data.
This class supports the storage of arbitrary elements, such as observation
tensors, integer actions, etc.
See https://en.wikipedia.org/wiki/Reservoir_sampling for more details.
"""
def __init__(self, reservoir_buffer_capacity):
self._reservoir_buffer_capacity = reservoir_buffer_capacity
self._data = []
self._add_calls = 0
def add(self, element):
"""Potentially adds `element` to the reservoir buffer.
Args:
element: data to be added to the reservoir buffer.
"""
if len(self._data) < self._reservoir_buffer_capacity:
self._data.append(element)
else:
idx = np.random.randint(0, self._add_calls + 1)
if idx < self._reservoir_buffer_capacity:
self._data[idx] = element
self._add_calls += 1
def sample(self, num_samples):
"""Returns `num_samples` uniformly sampled from the buffer.
Args:
num_samples: `int`, number of samples to draw.
Returns:
An iterable over `num_samples` random elements of the buffer.
Raises:
ValueError: If there are less than `num_samples` elements in the buffer
"""
if len(self._data) < num_samples:
raise ValueError('{} elements could not be sampled from size {}'.format(
num_samples, len(self._data)))
return random.sample(self._data, num_samples)
def clear(self):
self._data = []
self._add_calls = 0
def __len__(self):
return len(self._data)
def __iter__(self):
return iter(self._data)
@property
def data(self):
return self._data
def get_data(self):
return self._data
def shuffle_data(self):
random.shuffle(self._data)
def get_num_calls(self):
return self._add_calls
class SkipDense(tf.keras.layers.Layer):
"""Dense Layer with skip connection."""
def __init__(self, units, **kwargs):
super().__init__(**kwargs)
self.hidden = tf.keras.layers.Dense(units, kernel_initializer='he_normal')
def call(self, x):
return self.hidden(x) + x
class PolicyNetwork(tf.keras.Model):
"""Implements the policy network as an MLP.
Implements the policy network as a MLP with skip connections in adjacent
layers with the same number of units, except for the last hidden connection
where a layer normalization is applied.
"""
def __init__(self,
input_size,
policy_network_layers,
num_actions,
activation='leakyrelu',
**kwargs):
super().__init__(**kwargs)
self._input_size = input_size
self._num_actions = num_actions
if activation == 'leakyrelu':
self.activation = tf.keras.layers.LeakyReLU(alpha=0.2)
elif activation == 'relu':
self.activation = tf.keras.layers.ReLU()
else:
self.activation = activation
self.softmax = tf.keras.layers.Softmax()
self.hidden = []
prevunits = 0
for units in policy_network_layers[:-1]:
if prevunits == units:
self.hidden.append(SkipDense(units))
else:
self.hidden.append(
tf.keras.layers.Dense(units, kernel_initializer='he_normal'))
prevunits = units
self.normalization = tf.keras.layers.LayerNormalization()
self.lastlayer = tf.keras.layers.Dense(
policy_network_layers[-1], kernel_initializer='he_normal')
self.out_layer = tf.keras.layers.Dense(num_actions)
@tf.function
def call(self, inputs):
"""Applies Policy Network.
Args:
inputs: Tuple representing (info_state, legal_action_mask)
Returns:
Action probabilities
"""
x, mask = inputs
for layer in self.hidden:
x = layer(x)
x = self.activation(x)
x = self.normalization(x)
x = self.lastlayer(x)
x = self.activation(x)
x = self.out_layer(x)
x = tf.where(mask == 1, x, -10e20)
x = self.softmax(x)
return x
class RegretNetwork(tf.keras.Model):
"""Implements the regret network as an MLP.
Implements the regret network as an MLP with skip connections in
adjacent layers with the same number of units, except for the last hidden
connection where a layer normalization is applied.
"""
def __init__(self,
input_size,
regret_network_layers,
num_actions,
activation='leakyrelu',
**kwargs):
super().__init__(**kwargs)
self._input_size = input_size
self._num_actions = num_actions
if activation == 'leakyrelu':
self.activation = tf.keras.layers.LeakyReLU(alpha=0.2)
elif activation == 'relu':
self.activation = tf.keras.layers.ReLU()
else:
self.activation = activation
self.hidden = []
prevunits = 0
for units in regret_network_layers[:-1]:
if prevunits == units:
self.hidden.append(SkipDense(units))
else:
self.hidden.append(
tf.keras.layers.Dense(units, kernel_initializer='he_normal'))
prevunits = units
self.normalization = tf.keras.layers.LayerNormalization()
self.lastlayer = tf.keras.layers.Dense(
regret_network_layers[-1], kernel_initializer='he_normal')
self.out_layer = tf.keras.layers.Dense(num_actions)
@tf.function
def call(self, inputs):
"""Applies Regret Network.
Args:
inputs: Tuple representing (info_state, legal_action_mask)
Returns:
Cumulative regret for each info_state action
"""
x, mask = inputs
for layer in self.hidden:
x = layer(x)
x = self.activation(x)
x = self.normalization(x)
x = self.lastlayer(x)
x = self.activation(x)
x = self.out_layer(x)
x = mask * x
return x
class ValueNetwork(tf.keras.Model):
"""Implements the history value network as an MLP.
Implements the history value network as an MLP with skip connections in
adjacent layers with the same number of units, except for the last hidden
connection where a layer normalization is applied.
"""
def __init__(self,
input_size,
val_network_layers,
activation='leakyrelu',
**kwargs):
super().__init__(**kwargs)
self._input_size = input_size
if activation == 'leakyrelu':
self.activation = tf.keras.layers.LeakyReLU(alpha=0.2)
elif activation == 'relu':
self.activation = tf.keras.layers.ReLU()
else:
self.activation = activation
self.hidden = []
prevunits = 0
for units in val_network_layers[:-1]:
if prevunits == units:
self.hidden.append(SkipDense(units))
else:
self.hidden.append(
tf.keras.layers.Dense(units, kernel_initializer='he_normal'))
prevunits = units
self.normalization = tf.keras.layers.LayerNormalization()
self.lastlayer = tf.keras.layers.Dense(
val_network_layers[-1], kernel_initializer='he_normal')
self.out_layer = tf.keras.layers.Dense(1)
@tf.function
def call(self, inputs):
"""Applies Value Network.
Args:
inputs: Tuple representing (info_state, legal_action_mask)
Returns:
Cumulative regret for each info_state action
"""
x, mask = inputs
for layer in self.hidden:
x = layer(x)
x = self.activation(x)
x = self.normalization(x)
x = self.lastlayer(x)
x = self.activation(x)
x = self.out_layer(x)
return x
class ESCHERSolver(policy.Policy):
def __init__(self,
game,
policy_network_layers=(256, 128),
regret_network_layers=(256, 128),
value_network_layers=(256, 128),
num_iterations: int = 100,
num_traversals: int = 130000,
num_val_fn_traversals: int = 100,
learning_rate: float = 1e-3,
batch_size_regret: int = 10000,
batch_size_value: int = 2024,
batch_size_average_policy: int = 10000,
markov_soccer: bool = False,
phantom_ttt=False,
dark_hex: bool = False,
memory_capacity: int = int(1e5),
policy_network_train_steps: int = 15000,
regret_network_train_steps: int = 5000,
value_network_train_steps: int = 4048,
check_exploitability_every: int = 20,
reinitialize_regret_networks: bool = True,
reinitialize_value_network: bool = True,
save_regret_networks: str = None,
append_legal_actions_mask=False,
save_average_policy_memories: str = None,
save_policy_weights=True,
expl: float = 1.0,
val_expl: float = 0.01,
importance_sampling_threshold: float = 100.,
importance_sampling: bool = True,
clear_value_buffer: bool = True,
val_bootstrap=False,
oshi_zumo=False,
use_balanced_probs: bool = False,
battleship=False,
starting_coins=8,
val_op_prob=0.,
infer_device='cpu',
debug_val=False,
play_against_random=False,
train_device='cpu',
experiment_string=None,
all_actions=True,
random_policy_path=None,
*args, **kwargs):
"""Initialize the ESCHER algorithm.
Args:
game: Open Spiel game.
policy_network_layers: (list[int]) Layer sizes of average_policy net MLP.
regret_network_layers: (list[int]) Layer sizes of regret net MLP.
value_network_layers: (list[int]) Layer sizes of value net MLP.
num_iterations: Number of iterations.
num_traversals: Number of traversals per iteration.
num_val_fn_traversals: Number of history value function traversals per iteration
learning_rate: Learning rate.
batch_size_regret: (int) Batch size to sample from regret memories.
batch_size_average_policy: (int) Batch size to sample from average_policy memories.
memory_capacity: Number of samples that can be stored in memory.
policy_network_train_steps: Number of policy network training steps (one
policy training iteration at the end).
regret_network_train_steps: Number of regret network training steps
(per iteration).
reinitialize_regret_networks: Whether to re-initialize the regret
network before training on each iteration.
save_regret_networks: If provided, all regret network itearations
are saved in the given folder. This can be useful to implement SD-CFR
https://arxiv.org/abs/1901.07621
save_average_policy_memories: saves the collected average_policy memories as a
tfrecords file in the given location. This is not affected by
memory_capacity. All memories are saved to disk and not kept in memory
infer_device: device used for TF-operations in the traversal branch.
Format is anything accepted by tf.device
train_device: device used for TF-operations in the NN training steps.
Format is anything accepted by tf.device
"""
all_players = list(range(game.num_players()))
super().__init__(game, all_players)
self._game = game
self._save_policy_weights = save_policy_weights
self._compute_exploitability = True
self._markov_soccer = markov_soccer
self._dark_hex = dark_hex
self._phantom_ttt = phantom_ttt
self._play_against_random = play_against_random
self._append_legal_actions_mask = append_legal_actions_mask
self._num_random_games = 2000
if self._markov_soccer or self._dark_hex or self._phantom_ttt:
self._compute_exploitability = False
self._play_against_random = True
if game.get_type().dynamics == pyspiel.GameType.Dynamics.SIMULTANEOUS:
# `_traverse_game_tree` does not take into account this option.
raise ValueError('Simulatenous games are not supported.')
self._batch_size_regret = batch_size_regret
self._batch_size_value = batch_size_value
self._batch_size_average_policy = batch_size_average_policy
self._policy_network_train_steps = policy_network_train_steps
self._regret_network_train_steps = regret_network_train_steps
self._value_network_train_steps = value_network_train_steps
self._policy_network_layers = policy_network_layers
self._regret_network_layers = regret_network_layers
self._value_network_layers = value_network_layers
self._num_players = game.num_players()
self._root_node = self._game.new_initial_state()
self._starting_coins = starting_coins
self._oshi_zumo = oshi_zumo
self._battleship = battleship
if self._oshi_zumo:
observation_tensor = self._root_node.observation_tensor(0)
self._embedding_size = len(observation_tensor)
elif self._battleship:
observation_tensor = battleship_infostate_tensor(self._root_node, 0)
self._embedding_size = len(observation_tensor)
elif self._markov_soccer:
self._embedding_size = len(self._root_node.observation_tensor(0))
else:
self._embedding_size = len(self._root_node.information_state_tensor(0))
if self._oshi_zumo:
hist_state = get_oshi_hist_obs(self._root_node.observation_tensor(0), 0, starting_coins, 0)
elif self._markov_soccer:
hist_state = get_markov_soccer_hist_obs(self._root_node.observation_tensor(0), 0, 0)
elif self._battleship:
hist_state = battleship_history_tensor(self._root_node)
else:
hist_state = np.append(self._root_node.information_state_tensor(0),
self._root_node.information_state_tensor(1))
self._value_embedding_size = len(hist_state)
self._num_iterations = num_iterations
self._num_traversals = num_traversals
self._num_val_fn_traversals = num_val_fn_traversals
self._reinitialize_regret_networks = reinitialize_regret_networks
self._reinit_value_network = reinitialize_value_network
self._num_actions = game.num_distinct_actions()
self._iteration = 1
self._learning_rate = learning_rate
self._save_regret_networks = save_regret_networks
self._save_average_policy_memories = save_average_policy_memories
self._infer_device = infer_device
self._train_device = train_device
self._memories_tfrecordpath = None
self._memories_tfrecordfile = None
self._check_exploitability_every = check_exploitability_every
self._expl = expl
self._val_expl = val_expl
self._importance_sampling = importance_sampling
self._importance_sampling_threshold = importance_sampling_threshold
self._clear_value_buffer = clear_value_buffer
self._nodes_visited = 0
self._example_info_state = [None, None]
self._example_hist_state = None
self._example_legal_actions_mask = [None, None]
self._squared_errors = []
self._squared_errors_child = []
self._balanced_probs = {}
self._use_balanced_probs = use_balanced_probs
self._val_op_prob = val_op_prob
self._val_bootstrap = val_bootstrap
self._debug_val = debug_val
self._experiment_string = experiment_string
self._all_actions = all_actions
self._random_policy_path = random_policy_path
# Initialize file save locations
if self._save_regret_networks:
os.makedirs(self._save_regret_networks, exist_ok=True)
if self._save_average_policy_memories:
if os.path.isdir(self._save_average_policy_memories):
self._memories_tfrecordpath = os.path.join(
self._save_average_policy_memories, 'average_policy_memories.tfrecord')
else:
os.makedirs(
os.path.split(self._save_average_policy_memories)[0], exist_ok=True)
self._memories_tfrecordpath = self._save_average_policy_memories
# Initialize policy network, loss, optimizer
self._reinitialize_policy_network()
# Initialize regret networks, losses, optimizers
self._regret_networks = []
self._regret_networks_train = []
self._loss_regrets = []
self._optimizer_regrets = []
self._regret_train_step = []
for player in range(self._num_players):
with tf.device(self._infer_device):
self._regret_networks.append(
RegretNetwork(self._embedding_size, self._regret_network_layers,
self._num_actions))
with tf.device(self._train_device):
self._regret_networks_train.append(
RegretNetwork(self._embedding_size,
self._regret_network_layers, self._num_actions))
self._loss_regrets.append(tf.keras.losses.MeanSquaredError())
self._optimizer_regrets.append(
tf.keras.optimizers.Adam(learning_rate=learning_rate))
self._regret_train_step.append(self._get_regret_train_graph(player))
self._create_memories(memory_capacity)
# Initialize value networks, losses, optimizers
self._val_network = ValueNetwork(self._value_embedding_size, self._value_network_layers)
self._val_network_train = ValueNetwork(self._value_embedding_size, self._value_network_layers)
self._loss_value = tf.keras.losses.MeanSquaredError()
self._optimizer_value = tf.keras.optimizers.Adam(learning_rate=learning_rate)
self._value_train_step = self._get_value_train_graph()
self._value_test_step = self._get_value_test_graph()
def _reinitialize_policy_network(self):
"""Reinitalize policy network and optimizer for training."""
with tf.device(self._train_device):
self._policy_network = PolicyNetwork(self._embedding_size,
self._policy_network_layers,
self._num_actions)
self._optimizer_policy = tf.keras.optimizers.Adam(
learning_rate=self._learning_rate)
self._loss_policy = tf.keras.losses.MeanSquaredError()
def _reinitialize_regret_network(self, player):
"""Reinitalize player's regret network and optimizer for training."""
with tf.device(self._train_device):
self._regret_networks_train[player] = RegretNetwork(
self._embedding_size, self._regret_network_layers,
self._num_actions)
self._optimizer_regrets[player] = tf.keras.optimizers.Adam(
learning_rate=self._learning_rate)
self._regret_train_step[player] = (
self._get_regret_train_graph(player))
def get_example_info_state(self, player):
return self._example_info_state[player]
def get_example_hist_state(self):
return self._example_hist_state
def get_example_legal_actions_mask(self, player):
return self._example_legal_actions_mask[player]
def _reinitialize_value_network(self):
"""Reinitalize player's value network and optimizer for training."""
with tf.device(self._train_device):
self._val_network_train = ValueNetwork(
self._value_embedding_size, self._value_network_layers)
self._optimizer_value = tf.keras.optimizers.Adam(
learning_rate=self._learning_rate)
self._value_train_step = (self._get_value_train_graph())
@property
def regret_buffers(self):
return self._regret_memories
@property
def average_policy_buffer(self):
return self._average_policy_memories
def clear_regret_buffers(self):
for p in range(self._num_players):
self._regret_memories[p].clear()
def _create_memories(self, memory_capacity):
"""Create memory buffers and associated feature descriptions."""
self._average_policy_memories = ReservoirBuffer(memory_capacity)
self._regret_memories = [
ReservoirBuffer(memory_capacity) for _ in range(self._num_players)
]
self._value_memory = ReservoirBuffer(memory_capacity)
self._value_memory_test = ReservoirBuffer(memory_capacity)
self._average_policy_feature_description = {
'info_state': tf.io.FixedLenFeature([self._embedding_size], tf.float32),
'action_probs': tf.io.FixedLenFeature([self._num_actions], tf.float32),
'iteration': tf.io.FixedLenFeature([1], tf.float32),
'legal_actions': tf.io.FixedLenFeature([self._num_actions], tf.float32)
}
self._regret_feature_description = {
'info_state': tf.io.FixedLenFeature([self._embedding_size], tf.float32),
'iteration': tf.io.FixedLenFeature([1], tf.float32),
'samp_regret': tf.io.FixedLenFeature([self._num_actions], tf.float32),
'legal_actions': tf.io.FixedLenFeature([self._num_actions], tf.float32)
}
self._value_feature_description = {
'hist_state': tf.io.FixedLenFeature([self._value_embedding_size], tf.float32),
'iteration': tf.io.FixedLenFeature([1], tf.float32),
'samp_value': tf.io.FixedLenFeature([1], tf.float32),
'legal_actions': tf.io.FixedLenFeature([self._num_actions], tf.float32),
}
def get_val_weights(self):
return self._val_network.get_weights()
def set_val_weights(self, weights):
self._val_network.set_weights(weights)
def get_num_calls(self):
num_calls = 0
for p in range(self._num_players):
num_calls += self._regret_memories[p].get_num_calls()
return num_calls
def set_iteration(self, iteration):
self._iteration = iteration
def get_weights(self):
regret_weights = [self._regret_networks[player].get_weights() for player in range(self._num_players)]
return regret_weights
def get_policy_weights(self):
policy_weights = self._policy_network.get_weights()
return policy_weights
def set_policy_weights(self, policy_weights):
self._reinitialize_policy_network()
self._policy_network.set_weights(policy_weights)
def get_regret_memories(self, player):
return self._regret_memories[player].get_data()
def get_value_memory(self):
return self._value_memory.get_data()
def clear_value_memory(self):
self._value_memory.clear()
def get_value_memory_test(self):
return self._value_memory_test.get_data()
def get_average_policy_memories(self):
return self._average_policy_memories.get_data()
def get_num_nodes(self):
return self._nodes_visited
def get_squared_errors(self):
return self._squared_errors
def reset_squared_errors(self):
self._squared_errors = []
def get_squared_errors_child(self):
return self._squared_errors_child
def reset_squared_errors_child(self):
self._squared_errors_child = []
def clear_val_memories_test(self):
self._value_memory_test.clear()
def clear_val_memories(self):
self._value_memory.clear()
def traverse_game_tree_n_times(self, n, p, train_regret=False, train_value=False,
track_mean_squares=True, on_policy_prob=0., expl=0.6, val_test=False):
for i in range(n):
if i > 0:
track_mean_squares = False
self._traverse_game_tree(self._root_node, p, my_reach=1.0, opp_reach=1.0, sample_reach=1.0,
my_sample_reach=1.0, train_regret=train_regret, train_value=train_value,
track_mean_squares=track_mean_squares, on_policy_prob=on_policy_prob,
expl=expl, val_test=val_test)
def init_regret_net(self):
# initialize regret network
for p in range(self._num_players):
example_info_state = self.get_example_info_state(p)
example_legal_actions_mask = self.get_example_legal_actions_mask(p)
self.traverse_game_tree_n_times(1, p, track_mean_squares=False)
self._init_main_regret_network(example_info_state, example_legal_actions_mask, p)
def init_val_net(self):
example_hist_state = self.get_example_hist_state()
example_legal_actions_mask = self.get_example_legal_actions_mask(0)
self._init_main_val_network(example_hist_state, example_legal_actions_mask)
def play_game_against_random(self):
# play one game per player
reward = 0
for player in [0, 1]:
state = self._game.new_initial_state()
while not state.is_terminal():
if state.is_chance_node():
outcomes, probs = zip(*state.chance_outcomes())
aidx = np.random.choice(range(len(outcomes)), p=probs)
action = outcomes[aidx]
else:
cur_player = state.current_player()
legal_actions = state.legal_actions(cur_player)
legal_actions_mask = tf.constant(
state.legal_actions_mask(cur_player), dtype=tf.float32)
obs = tf.constant(state.observation_tensor(), dtype=tf.float32)
if len(obs.shape) == 1:
obs = tf.expand_dims(obs, axis=0)
if cur_player == player:
probs = self._policy_network((obs, legal_actions_mask), training=False)
probs = probs.numpy()[0]
probs /= probs.sum()
action = np.random.choice(range(state.num_distinct_actions()), p=probs)
elif cur_player == 1 - player:
action = random.choice(state.legal_actions())
else:
print("Got player ", str(cur_player))
break
state.apply_action(action)
reward += state.returns()[player]
return reward
def play_n_games_against_random(self, n):
total_reward = 0
for i in range(n):
reward = self.play_game_against_random()
total_reward += reward
return total_reward / (2 * n)
def print_mse(self):
# track MSE
squared_errors = self.get_squared_errors()
self.reset_squared_errors()
squared_errors_child = self.get_squared_errors_child()
self.reset_squared_errors_child()
print(sum(squared_errors) / len(squared_errors), "Mean Squared Errors")
print(sum(squared_errors_child) / len(squared_errors_child), "Mean Squared Errors Child")
def solve(self, save_path_convs=None):
"""Solution logic for Deep CFR."""
regret_losses = collections.defaultdict(list)
value_losses = []
str(datetime.now())
timestr = "{:%Y_%m_%d_%H_%M_%S}".format(datetime.now())
if self._use_balanced_probs:
self._get_balanced_probs(self._root_node)
with tf.device(self._infer_device):
with contextlib.ExitStack() as stack:
if self._save_average_policy_memories:
self._memories_tfrecordfile = stack.enter_context(
tf.io.TFRecordWriter(self._memories_tfrecordpath))
convs = []
nodes = []
self.traverse_game_tree_n_times(1, 0, track_mean_squares=False)
for i in range(self._num_iterations + 1):
print(i)
start = time.time()
if self._experiment_string is not None:
print(self._experiment_string)
# init weights
self.init_regret_net()
self.init_val_net()
# train val function
self.traverse_game_tree_n_times(self._num_val_fn_traversals, 0,
train_value=True,
track_mean_squares=False,
on_policy_prob=self._val_op_prob,
expl=self._val_expl)
self.traverse_game_tree_n_times(20, 0, train_value=True, track_mean_squares=False,
on_policy_prob=self._val_op_prob,
expl=self._val_expl,
val_test=True)
val_traj_time = time.time()
print(val_traj_time - start, 'val trajectory time')
if self._reinit_value_network:
self._reinitialize_value_network()
value_losses.append(self._learn_value_network())
print(value_losses[-1], 'val loss')
test_loss = self._get_value_test_loss()
print(test_loss, 'test loss')
if self._clear_value_buffer:
self.clear_val_memories_test()
self.clear_val_memories()
val_train_time = time.time()
print(val_train_time - val_traj_time, 'val train time')
# train regret network
if self._oshi_zumo or self._battleship or self._markov_soccer or self._dark_hex or self._phantom_ttt:
track_mse = False
else:
track_mse = True
for p in range(self._num_players):
regret_start_time = time.time()
results = []
self.traverse_game_tree_n_times(self._num_traversals, p,
train_regret=True,
track_mean_squares=track_mse,
expl=self._expl)
num_nodes = self.get_num_nodes()
regret_traj_time = time.time()
print(regret_traj_time - regret_start_time, 'regret trajectory time')
if self._reinitialize_regret_networks:
self._reinitialize_regret_network(p)
regret_losses[p].append(self._learn_regret_network(p))
if self._save_regret_networks:
os.makedirs(self._save_regret_networks, exist_ok=True)
self._regret_networks[p].save(
os.path.join(self._save_regret_networks,
f'regretnet_p{p}_it{self._iteration:04}'))
print(time.time() - regret_traj_time, 'regret train time')
if not any([self._oshi_zumo, self._battleship, self._markov_soccer, self._dark_hex,
self._phantom_ttt]):
self.print_mse()
total_regret_time = time.time()
print(total_regret_time - val_train_time, 'total regret time')
# check exploitability
self._iteration += 1
if i % self._check_exploitability_every == 0:
exp_start_time = time.time()
self._reinitialize_policy_network()
policy_loss = self._learn_average_policy_network()
if self._save_policy_weights:
save_path_model = save_path_convs + "/" + timestr
os.makedirs(save_path_model, exist_ok=True)
model_path = save_path_model + "/policy_nodes_" + str(num_nodes)
self._policy_network.save_weights(model_path)
print("saved policy to ", model_path)
self.save_policy_network(model_path + "full_model")
print("saved policy to ", model_path + "full_model")
if self._play_against_random:
start_time = time.time()
avg_reward = self.play_n_games_against_random(self._num_random_games)
print(avg_reward, "Average reward against random\n")
if self._markov_soccer:
nfsp_avg_rew = self._run_n_episodes_against_nfsp(self._num_random_games)
print(time.time() - start_time, "eval time")
print(nfsp_avg_rew, "Average reward against nfsp\n")
if self._compute_exploitability:
conv = exploitability.nash_conv(self._game, policy.tabular_policy_from_callable(
self._game, self.action_probabilities))
convs.append(conv)
nodes.append(num_nodes)
if save_path_convs:
convs_path = save_path_convs + "_convs.npy"
nodes_path = save_path_convs + "_nodes.npy"
np.save(convs_path, np.array(convs))
np.save(nodes_path, np.array(nodes))
print(self._iteration, num_nodes, conv)
print(time.time() - exp_start_time, 'exp time')
# Train policy network.
policy_loss = self._learn_average_policy_network()
return regret_losses, policy_loss, convs, nodes
def save_policy_network(self, outputfolder):
"""Saves the policy network to the given folder."""
os.makedirs(outputfolder, exist_ok=True)
self._policy_network.save(outputfolder)
def train_policy_network_from_file(self,
tfrecordpath,
iteration=None,
batch_size_average_policy=None,
policy_network_train_steps=None,
reinitialize_policy_network=True):
"""Trains the policy network from a previously stored tfrecords-file."""
self._memories_tfrecordpath = tfrecordpath
if iteration:
self._iteration = iteration
if batch_size_average_policy:
self._batch_size_average_policy = batch_size_average_policy
if policy_network_train_steps:
self._policy_network_train_steps = policy_network_train_steps
if reinitialize_policy_network:
self._reinitialize_policy_network()