-
Notifications
You must be signed in to change notification settings - Fork 0
/
Agent.py
1757 lines (1353 loc) · 63.1 KB
/
Agent.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
from AbstractPlayer import AbstractPlayer
from Types import *
from planning.Translator import Translator
from planning.Planning import Planning
from utils.Types import LEARNING_SSO_TYPE
from planning.parser import Parser
import subprocess
import random
import numpy as np
import tensorflow as tf
import pickle
import sys
import glob
import time
# LearningModelFastRep.py is actually a little slower than LearningModel.py
from LearningModel import DQNetwork
from PrioritizedExperienceReplay import Memory
class Agent(AbstractPlayer):
NUM_GEMS_FOR_EXIT = 9
DESC_FILE = 'planning/problem.txt'
OUT_FILE = 'planning/plan.txt'
def __init__(self):
"""
load_path = 'SavedDatasets/dataset_BoulderDash_120.dat'
with open(load_path, 'rb') as file:
curr_dataset = pickle.load(file)
curr_sample = curr_dataset[0]
curr_state = curr_sample[2]
one_hot_grid_subgoals = []
for i in range(curr_state.shape[0]):
for j in range(curr_state.shape[1]):
if curr_state[i][j][4] == 1:
print(1, end =" ")
#one_hot_grid_subgoals.append((j, i))
else:
print(0, end =" ")
print("\n")
#print("Subgoals guardados:", curr_sample[3])
#print("Subgoals del one-hot-grid:", one_hot_grid_subgoals)
sys.exit()
"""
# ---------- EXIT ----------------
"""
Agent constructor
Creates a new agent and sets SSO type to JSON
"""
AbstractPlayer.__init__(self)
self.lastSsoType = LEARNING_SSO_TYPE.JSON
# Attributes different for every game
# Game in {'BoulderDash', 'IceAndFire', 'Catapults'}
self.game_playing="BoulderDash"
# Config file in {'config/boulderdash.yaml', 'config/ice-and-fire.yaml', 'config/catapults.yaml'}
if self.game_playing == 'BoulderDash':
self.config_file='config/boulderdash.yaml'
elif self.game_playing == 'IceAndFire':
self.config_file='config/ice-and-fire.yaml'
else: # Catapults
self.config_file='config/catapults.yaml'
self.planning = Planning(self.config_file)
# The number of actions an invalid plan is associated, i.e., when
# there is no plan for the selected subgoal
self.num_actions_invalid_plan = 1000
# << Choose execution mode >>
# - 'create_dataset' -> It doesn't train any model. Just creates the dataset (experience replay) and saves it
# - 'train' -> It loads the saved dataset, trains the model with it, and saves the trained model.
# It doesn't add any sample to the experience replay
# - 'test' -> It loads the trained model and tests it on the validation levels, obtaining the metrics.
self.EXECUTION_MODE="test"
# Size of the dataset to train the model on
self.dataset_size_for_training=200
# Name of the DQNetwork. Also used for creating the name of file to save and load the model from
# Add the name of the game being played!!!
self.network_name="DQN_Final_Results_ESWA_fc-128_1_gamma-0.7_alfa-1e-05_its-1200000_BoulderDash_10"
self.network_name=self.network_name + "_lvs={}".format(self.dataset_size_for_training)
# Name of the saved model file to load (without the number of training steps part)
self.model_load_path = "./SavedModels/" + self.network_name + ".ckpt"
# Seed for selecting which levels to train the model on
self.level_seed=318032
# <Model Hyperparameters>
# Automatically changed by ejecutar_pruebas.py!
# Architecture
# First conv layer
self.l1_num_filt=32
self.l1_window=[4, 4]
self.l1_strides=[2, 2]
self.l1_padding_type="VALID"
# Second conv layer
self.l2_num_filt=64
self.l2_window=[4, 4]
self.l2_strides=[2, 2]
self.l2_padding_type="VALID"
# Third conv layer
self.l3_num_filt=64
self.l3_window=[3, 3]
self.l3_strides=[1, 1]
self.l3_padding_type="VALID"
# Fourth conv layer
self.l4_num_filt=-1
self.l4_window=[3, 3]
self.l4_strides=[1, 1]
self.l4_padding_type="VALID"
# Fifth conv layer
self.l5_num_filt=-1
self.l5_window=[3, 3]
self.l5_strides=[1, 1]
self.l5_padding_type="VALID"
# Sixth conv layer
self.l6_num_filt=-1
self.l6_window=[3, 3]
self.l6_strides=[1, 1]
self.l6_padding_type="VALID"
self.l7_num_filt=-1
self.l7_window=[3, 3]
self.l7_strides=[1, 1]
self.l7_padding_type="VALID"
self.l8_num_filt=-1
self.l8_window=[3, 3]
self.l8_strides=[1, 1]
self.l8_padding_type="VALID"
self.l9_num_filt=-1
self.l9_window=[3, 3]
self.l9_strides=[1, 1]
self.l9_padding_type="VALID"
self.l10_num_filt=-1
self.l10_window=[3, 3]
self.l10_strides=[1, 1]
self.l10_padding_type="VALID"
self.l11_num_filt=-1
self.l11_window=[3, 3]
self.l11_strides=[1, 1]
self.l11_padding_type="SAME"
self.l12_num_filt=-1
self.l12_window=[3, 3]
self.l12_strides=[1, 1]
self.l12_padding_type="VALID"
self.l13_num_filt=-1
self.l13_window=[3, 3]
self.l13_strides=[1, 1]
self.l13_padding_type="SAME"
self.l14_num_filt=-1
self.l14_window=[3, 3]
self.l14_strides=[1, 1]
self.l14_padding_type="VALID"
self.l15_num_filt=-1
self.l15_window=[3, 3]
self.l15_strides=[1, 1]
self.l15_padding_type="VALID"
self.l16_num_filt=-1
self.l16_window=[3, 3]
self.l16_strides=[1, 1]
self.l16_padding_type="VALID"
self.l17_num_filt=-1
self.l17_window=[3, 3]
self.l17_strides=[1, 1]
self.l17_padding_type="SAME"
self.l18_num_filt=-1
self.l18_window=[3, 3]
self.l18_strides=[1, 1]
self.l18_padding_type="VALID"
self.l19_num_filt=-1
self.l19_window=[3, 3]
self.l19_strides=[1, 1]
self.l19_padding_type="VALID"
self.l20_num_filt=-1
self.l20_window=[3, 3]
self.l20_strides=[1, 1]
self.l20_padding_type="VALID"
# Number of units of the first and second fully-connected layers
self.fc_num_unis=[128, 1, 1, 1]
# Training params
self.learning_rate=1e-05
# Don't use dropout?
self.dropout_prob=0.0
self.num_train_its=1200000
self.batch_size=32
self.use_BN=True
# Extra params
# Number of training its before copying the DQNetwork's weights to the target network
# default max_tau was 250
self.max_tau=10000
# Discount rate for Deep Q-Learning
self.gamma=0.7
# Sample size. It depends on the game being played. The format is (rows, cols, number of observations + 1)
# Sizes: BoulderDash=[13, 26, 7], IceAndFire=[14, 16, 10] , Catapults=[16, 16, 9]
if self.game_playing == 'BoulderDash':
self.sample_size=[13, 26, 7]
elif self.game_playing == 'IceAndFire':
self.sample_size=[14, 16, 10]
else: # Catapults
self.sample_size=[16, 16, 9]
if self.EXECUTION_MODE == 'create_dataset':
# Attribute that stores agent's experience to implement experience replay (for training)
# Each element is a tuple (s, res, r, s') corresponding to:
# - s -> start_state and chosen subgoal ((game state, chosen subgoal) one-hot encoded). Shape = (-1, 13, 26, 9).
# - res -> list of three elements containing the resources the agent has at the state s.
# - r -> length of the plan from the start_state to the chosen subgoal.
# - s' -> state of the game just after the agent has achieved the chosen subgoal.
# It's an instance of the SerializableStateObservation (sso) class.
self.memory = []
self.total_num_samples = 0 # Total number of sample collected, even if they were not unique (thus not added to the datasets)
self.sample_hashes = set() # Hashes of unique samples already collected
# Path of the file to save the experience replay to
id_dataset=195
self.dataset_save_path = 'SavedDatasets/' + 'dataset_{}_{}.dat'.format(self.game_playing, id_dataset)
# Path of the file which contains the number of samples of each saved dataset
self.datasets_sizes_file_path = 'SavedDatasets/Datasets Sizes.txt'
# Size of the experience replay to save. It is saved when the total number of samples collected reaches
# 'self.num_total_samples_for_saving_dataset' or when the unique number of samples (len(self.memory)) reaches
# 'self.num_unique_samples_for_saving_dataset'
self.num_total_samples_for_saving_dataset = 1000
self.num_unique_samples_for_saving_dataset = 500
elif self.EXECUTION_MODE == 'train':
# Name of the saved model file (without the number of dataset size part)
self.model_save_path = "./SavedModels/" + self.network_name + ".ckpt"
# Array with samples
self.memory = []
# Prioritized Experience Replay
self.PER = None
# Folder where the datasets are stored
self.datasets_folder = 'SavedDatasets'
# Period for saving the trained model -> the model is saved every X training iterations
self.num_its_each_model_save = 10000000 # Only save final model # 100000 # <Cambiar>
# If true, PER is used. Otherwise, random sampling is used.
self.use_PER=True
# Each time self.model.train is called, this variable controls how many train
# repetitions are performed
# To use more repetitions per train call, the learning rate must be reduced
self.num_repetitions_each_train_call = 20
# If it does not equal 0, then the model with the corresponding num its is loaded
# (instead of creating a new one) and training resumes
self.num_train_its_model_to_load_train=0
else: # Test
# Goal Selection Mode: "best" -> select the best one using the trained model,
# "random" -> select a random one (corresponds with the random model)
# "greedy" -> plans to every subgoal and selects the one with the shortest plan
# Automatically changed by the scripts!
self.goal_selection_mode="best"
# Create Learning Model unles goal selection model is random
if self.goal_selection_mode == "best":
# DQNetwork
self.model = DQNetwork(writer_name=self.network_name,
sample_size = self.sample_size,
l1_num_filt = self.l1_num_filt, l1_window = self.l1_window, l1_strides = self.l1_strides,
l1_padding_type = self.l1_padding_type,
l2_num_filt = self.l2_num_filt, l2_window = self.l2_window, l2_strides = self.l2_strides,
l2_padding_type = self.l2_padding_type,
l3_num_filt = self.l3_num_filt, l3_window = self.l3_window, l3_strides = self.l3_strides,
l3_padding_type = self.l3_padding_type,
l4_num_filt = self.l4_num_filt, l4_window = self.l4_window, l4_strides = self.l4_strides,
l4_padding_type = self.l4_padding_type,
l5_num_filt = self.l5_num_filt, l5_window = self.l5_window, l5_strides = self.l5_strides,
l5_padding_type = self.l5_padding_type,
l6_num_filt = self.l6_num_filt, l6_window = self.l6_window, l6_strides = self.l6_strides,
l6_padding_type = self.l6_padding_type,
l7_num_filt = self.l7_num_filt, l7_window = self.l7_window, l7_strides = self.l7_strides,
l7_padding_type = self.l7_padding_type,
l8_num_filt = self.l8_num_filt, l8_window = self.l8_window, l8_strides = self.l8_strides,
l8_padding_type = self.l8_padding_type,
l9_num_filt = self.l9_num_filt, l9_window = self.l9_window, l9_strides = self.l9_strides,
l9_padding_type = self.l9_padding_type,
l10_num_filt = self.l10_num_filt, l10_window = self.l10_window, l10_strides = self.l10_strides,
l10_padding_type = self.l10_padding_type,
l11_num_filt = self.l11_num_filt, l11_window = self.l11_window, l11_strides = self.l11_strides,
l11_padding_type = self.l11_padding_type,
l12_num_filt = self.l12_num_filt, l12_window = self.l12_window, l12_strides = self.l12_strides,
l12_padding_type = self.l12_padding_type,
l13_num_filt = self.l13_num_filt, l13_window = self.l13_window, l13_strides = self.l13_strides,
l13_padding_type = self.l13_padding_type,
l14_num_filt = self.l14_num_filt, l14_window = self.l14_window, l14_strides = self.l14_strides,
l14_padding_type = self.l14_padding_type,
l15_num_filt = self.l15_num_filt, l15_window = self.l15_window, l15_strides = self.l15_strides,
l15_padding_type = self.l15_padding_type,
l16_num_filt = self.l16_num_filt, l16_window = self.l16_window, l16_strides = self.l16_strides,
l16_padding_type = self.l16_padding_type,
l17_num_filt = self.l17_num_filt, l17_window = self.l17_window, l17_strides = self.l17_strides,
l17_padding_type = self.l17_padding_type,
l18_num_filt = self.l18_num_filt, l18_window = self.l18_window, l18_strides = self.l18_strides,
l18_padding_type = self.l18_padding_type,
l19_num_filt = self.l19_num_filt, l19_window = self.l19_window, l19_strides = self.l19_strides,
l19_padding_type = self.l19_padding_type,
l20_num_filt = self.l20_num_filt, l20_window = self.l20_window, l20_strides = self.l20_strides,
l20_padding_type = self.l20_padding_type,
fc_num_units = self.fc_num_unis, dropout_prob = 0.0,
learning_rate = self.learning_rate,
use_BN=self.use_BN, game_playing=self.game_playing)
# Number training its of the model to load
# Automatically changed by ejecutar_pruebas.py!
self.num_train_its_model=1200000
# <Load the already-trained model in order to test performance>
self.model.load_model(path = self.model_load_path, num_it = self.num_train_its_model)
# Number of test levels the agent is playing. If it's 1, the agent exits after playing only the first test level
# Automatically changed by ejecutar_pruebas.py!
self.num_test_levels=1
# If True, the agent has already finished the first test level and is playing the second one
self.playing_second_test_level = False
def init(self, sso, elapsedTimer):
"""
* Public method to be called at the start of every level of a game.
* Perform any level-entry initialization here.
* @param sso Phase Observation of the current game.
* @param elapsedTimer Timer, which is 1s by default. Modified to 1000s.
Check utils/CompetitionParameters.py for more info.
"""
self.translator = Translator(sso, self.config_file)
# Create empty mem_sample
if self.EXECUTION_MODE == 'create_dataset':
self.mem_sample = []
# Create new empty action list
# This action list corresponds to the plan found by the planner
self.action_list = []
# See if it's training or validation time
self.is_training = not sso.isValidation # It's the opposite to sso.isValidation
# If it's validation/test phase, count the number of actions used
# to beat the current level and the number of incorrect subgoals
# (not eligible) the agent selects
if self.EXECUTION_MODE == 'test' and not self.is_training:
self.num_actions_lv = 0
self.num_incorrect_subgoals = 0
# Measure the goal selection + planning times
self.total_time_planning_curr_lv = 0
self.total_time_goal_selec_curr_lv = 0
def act(self, sso, elapsedTimer):
"""
Method used to determine the next move to be performed by the agent.
This method can be used to identify the current state of the game and all
relevant details, then to choose the desired course of action.
@param sso Observation of the current state of the game to be used in deciding
the next action to be taken by the agent.
@param elapsedTimer Timer, which is 40ms by default. Modified to 500s.
Check utils/CompetitionParameters.py for more info.
@return The action to be performed by the agent.
"""
# <Train the model without playing the game (EXECUTION_MODE == 'train')>
if self.EXECUTION_MODE == 'train':
# Load dataset of current size
self.load_dataset(self.datasets_folder, self.game_playing, num_levels=self.dataset_size_for_training, seed=self.level_seed)
# Shuffle dataset (only if we are using random sampling)
# DO NOT USE random.shuffle (it does not work well with numpy arrays)
if not self.use_PER:
np.random.shuffle(self.memory)
# Create Prioritized Experience Replay
if self.use_PER:
self.PER = Memory(len(self.memory), self.memory)
# Create Learning model
tf.reset_default_graph() # Clear Tensorflow Graph and Variables
# DQNetwork
self.model = DQNetwork(writer_name=self.network_name,
sample_size = self.sample_size,
l1_num_filt = self.l1_num_filt, l1_window = self.l1_window, l1_strides = self.l1_strides,
l1_padding_type = self.l1_padding_type,
l2_num_filt = self.l2_num_filt, l2_window = self.l2_window, l2_strides = self.l2_strides,
l2_padding_type = self.l2_padding_type,
l3_num_filt = self.l3_num_filt, l3_window = self.l3_window, l3_strides = self.l3_strides,
l3_padding_type = self.l3_padding_type,
l4_num_filt = self.l4_num_filt, l4_window = self.l4_window, l4_strides = self.l4_strides,
l4_padding_type = self.l4_padding_type,
l5_num_filt = self.l5_num_filt, l5_window = self.l5_window, l5_strides = self.l5_strides,
l5_padding_type = self.l5_padding_type,
l6_num_filt = self.l6_num_filt, l6_window = self.l6_window, l6_strides = self.l6_strides,
l6_padding_type = self.l6_padding_type,
l7_num_filt = self.l7_num_filt, l7_window = self.l7_window, l7_strides = self.l7_strides,
l7_padding_type = self.l7_padding_type,
l8_num_filt = self.l8_num_filt, l8_window = self.l8_window, l8_strides = self.l8_strides,
l8_padding_type = self.l8_padding_type,
l9_num_filt = self.l9_num_filt, l9_window = self.l9_window, l9_strides = self.l9_strides,
l9_padding_type = self.l9_padding_type,
l10_num_filt = self.l10_num_filt, l10_window = self.l10_window, l10_strides = self.l10_strides,
l10_padding_type = self.l10_padding_type,
l11_num_filt = self.l11_num_filt, l11_window = self.l11_window, l11_strides = self.l11_strides,
l11_padding_type = self.l11_padding_type,
l12_num_filt = self.l12_num_filt, l12_window = self.l12_window, l12_strides = self.l12_strides,
l12_padding_type = self.l12_padding_type,
l13_num_filt = self.l13_num_filt, l13_window = self.l13_window, l13_strides = self.l13_strides,
l13_padding_type = self.l13_padding_type,
l14_num_filt = self.l14_num_filt, l14_window = self.l14_window, l14_strides = self.l14_strides,
l14_padding_type = self.l14_padding_type,
l15_num_filt = self.l15_num_filt, l15_window = self.l15_window, l15_strides = self.l15_strides,
l15_padding_type = self.l15_padding_type,
l16_num_filt = self.l16_num_filt, l16_window = self.l16_window, l16_strides = self.l16_strides,
l16_padding_type = self.l16_padding_type,
l17_num_filt = self.l17_num_filt, l17_window = self.l17_window, l17_strides = self.l17_strides,
l17_padding_type = self.l17_padding_type,
l18_num_filt = self.l18_num_filt, l18_window = self.l18_window, l18_strides = self.l18_strides,
l18_padding_type = self.l18_padding_type,
l19_num_filt = self.l19_num_filt, l19_window = self.l19_window, l19_strides = self.l19_strides,
l19_padding_type = self.l19_padding_type,
l20_num_filt = self.l20_num_filt, l20_window = self.l20_window, l20_strides = self.l20_strides,
l20_padding_type = self.l20_padding_type,
fc_num_units = self.fc_num_unis, dropout_prob = self.dropout_prob,
learning_rate = self.learning_rate,
use_BN=self.use_BN, game_playing=self.game_playing)
# Current training iteration
curr_it = 0
# Target Network
# Used to predict the Q targets. It is upgraded every max_tau updates.
# Use the same tf.session as the main DQNetwork
self.target_network = DQNetwork(name="TargetNetwork",
sess = self.model.sess,
create_writer = False,
sample_size = self.sample_size,
l1_num_filt = self.l1_num_filt, l1_window = self.l1_window, l1_strides = self.l1_strides,
l1_padding_type = self.l1_padding_type,
l2_num_filt = self.l2_num_filt, l2_window = self.l2_window, l2_strides = self.l2_strides,
l2_padding_type = self.l2_padding_type,
l3_num_filt = self.l3_num_filt, l3_window = self.l3_window, l3_strides = self.l3_strides,
l3_padding_type = self.l3_padding_type,
l4_num_filt = self.l4_num_filt, l4_window = self.l4_window, l4_strides = self.l4_strides,
l4_padding_type = self.l4_padding_type,
l5_num_filt = self.l5_num_filt, l5_window = self.l5_window, l5_strides = self.l5_strides,
l5_padding_type = self.l5_padding_type,
l6_num_filt = self.l6_num_filt, l6_window = self.l6_window, l6_strides = self.l6_strides,
l6_padding_type = self.l6_padding_type,
l7_num_filt = self.l7_num_filt, l7_window = self.l7_window, l7_strides = self.l7_strides,
l7_padding_type = self.l7_padding_type,
l8_num_filt = self.l8_num_filt, l8_window = self.l8_window, l8_strides = self.l8_strides,
l8_padding_type = self.l8_padding_type,
l9_num_filt = self.l9_num_filt, l9_window = self.l9_window, l9_strides = self.l9_strides,
l9_padding_type = self.l9_padding_type,
l10_num_filt = self.l10_num_filt, l10_window = self.l10_window, l10_strides = self.l10_strides,
l10_padding_type = self.l10_padding_type,
l11_num_filt = self.l11_num_filt, l11_window = self.l11_window, l11_strides = self.l11_strides,
l11_padding_type = self.l11_padding_type,
l12_num_filt = self.l12_num_filt, l12_window = self.l12_window, l12_strides = self.l12_strides,
l12_padding_type = self.l12_padding_type,
l13_num_filt = self.l13_num_filt, l13_window = self.l13_window, l13_strides = self.l13_strides,
l13_padding_type = self.l13_padding_type,
l14_num_filt = self.l14_num_filt, l14_window = self.l14_window, l14_strides = self.l14_strides,
l14_padding_type = self.l14_padding_type,
l15_num_filt = self.l15_num_filt, l15_window = self.l15_window, l15_strides = self.l15_strides,
l15_padding_type = self.l15_padding_type,
l16_num_filt = self.l16_num_filt, l16_window = self.l16_window, l16_strides = self.l16_strides,
l16_padding_type = self.l16_padding_type,
l17_num_filt = self.l17_num_filt, l17_window = self.l17_window, l17_strides = self.l17_strides,
l17_padding_type = self.l17_padding_type,
l18_num_filt = self.l18_num_filt, l18_window = self.l18_window, l18_strides = self.l18_strides,
l18_padding_type = self.l18_padding_type,
l19_num_filt = self.l19_num_filt, l19_window = self.l19_window, l19_strides = self.l19_strides,
l19_padding_type = self.l19_padding_type,
l20_num_filt = self.l20_num_filt, l20_window = self.l20_window, l20_strides = self.l20_strides,
l20_padding_type = self.l20_padding_type,
fc_num_units = self.fc_num_unis, dropout_prob = 0.0,
learning_rate = self.learning_rate,
use_BN=self.use_BN, game_playing=self.game_playing)
# Load checkpoint and resume training
# THE CHECKPOINT HAS TO BE LOADED <<AFTER>> CREATING THE TARGET AND DQN NETWORKS
# Otherwise, the weights of the DQNetwork are reset (god knows why...)
if self.num_train_its_model_to_load_train != 0:
self.model.load_model(path = self.model_load_path, num_it = self.num_train_its_model_to_load_train)
curr_it = self.num_train_its_model_to_load_train # Don't start from train_it=0
# Print the values of the loaded weights (dense layer 1)
# kernel = tf.get_default_graph().get_tensor_by_name('DQNetwork/fc_1/kernel:0')
# print("\n\n >>> Kernel AFTER LOAD MODEL:", self.model.sess.run(kernel)[0,:5])
# Load PER
if self.use_PER:
PER_load_path = "./SavedModels/" + self.network_name + "_{}".format(self.num_train_its_model_to_load_train) + ".tree"
self.PER.load_memory(PER_load_path)
# Initialize target network's weights with those of the DQNetwork
self.update_ops = self.update_target_network() # ONLY CALL THIS ONCE (else new nodes will be added to the graph with each iter)
self.target_network.update_weights(self.update_ops)
num_samples = len(self.memory)
print("\n> Started training of model on {} levels\n".format(self.dataset_size_for_training))
ind_batch = 0 # Index for selecting the next minibatch
# Execute the training of the current model
while curr_it < self.num_train_its:
# Choose next batch from Experience Replay (using PER or random sampling)
# PER
if self.use_PER:
tree_idx, batch, sample_weights = self.PER.sample(self.batch_size)
else: # Random Sampling
if ind_batch+self.batch_size < num_samples:
batch = self.memory[ind_batch:ind_batch+self.batch_size]
ind_batch = (ind_batch + self.batch_size)
else: # Got to the end of the experience replay -> shuffle it and start again
batch = self.memory[ind_batch:]
ind_batch = 0
np.random.shuffle(self.memory)
batch_X = np.array([each[0] for each in batch]) # inputs for the DQNetwork
batch_R = [each[1] for each in batch] # r values (plan lengths)
batch_S = [each[2] for each in batch] # s' values (as one-hot grids)
batch_goal_pos = [each[3] for each in batch] # position of subgoals at states s'
# Calculate Q_targets
Q_targets = []
for r, s, goal_pos in zip(batch_R, batch_S, batch_goal_pos):
# Modify the reward when the current state is terminal (the next
# state s is None)
if self.game_playing != "Catapults":
if s is None:
# Clip rewards to [-200, 200]
if r >= 200: # Goal Selection error (there is no plan to the selected goal or the agent dies)
r = 200
else: # Valid plan -> reward (the agent completes the level)
r = r - 200 # Always equal to -200 or greater than -200 (r is a positive number)
Q_target = r + self.gamma*self.get_min_Q_value(s, goal_pos)
# Use discrete rewards for Catapults (Q_target is always either 200 or -200)
else:
if s is None: # Terminal state
if r >= 200: # Goal Selection error (there is no plan to the select goal or the agent dies)
Q_target = 200
else: # Valid plan -> reward (the agent completes the level)
Q_target = -200
else: # Non-terminal state
Q_target = self.get_min_Q_value(s, goal_pos)
Q_targets.append(Q_target)
# Clip the Q-targets to [-200,200]
Q_targets = np.clip(Q_targets, -200, 200)
Q_targets = np.reshape(Q_targets, (-1, 1))
# Execute one training step
# absolute_errors is used to update the priority scores of the PER
if self.use_PER:
absolute_errors = self.model.train(batch_X, Q_targets, sample_weights, num_its = self.num_repetitions_each_train_call)
else: # If we are not using PER, don't pass sample_weights
self.model.train(batch_X, Q_targets, num_its = self.num_repetitions_each_train_call)
# Update the priority scores of the PER
if self.use_PER:
self.PER.batch_update(tree_idx, absolute_errors)
# Update target network every max_tau training steps
if curr_it % self.max_tau == 0:
# update_ops = self.update_target_network()
self.target_network.update_weights(self.update_ops)
# Save Logs every 1000 training its
if curr_it % 1000 == 0 and curr_it > 0:
self.model.save_logs(batch_X, Q_targets, curr_it)
# Save the model each X training its along with the weights tree (if we are using PER)
if curr_it % self.num_its_each_model_save == 0 and curr_it > 0:
self.model.save_model(path = self.model_save_path, num_it = curr_it)
if self.use_PER:
PER_save_path = "./SavedModels/" + self.network_name + "_{}".format(curr_it) + ".tree"
self.PER.save_memory(PER_save_path)
# Periodically print the progress of the training
if curr_it % 500 == 0 and curr_it > 0:
print("- {} its completed".format(curr_it))
# Update the curr_it taking into account how many train its are performed
# in each self.model.train call
curr_it += self.num_repetitions_each_train_call
# Save the current trained model
self.model.save_model(path = self.model_save_path, num_it = self.num_train_its)
print("\n> Current model saved! Dataset size={} levels\n".format(self.dataset_size_for_training))
# Save PER
if self.use_PER:
PER_save_path = "./SavedModels/" + self.network_name + "_{}".format(self.num_train_its) + ".tree"
self.PER.save_memory(PER_save_path)
# Exit the program after finishing training
print("\nTraining finished!")
self.model.close_session()
sys.exit()
# If the agent is in test mode but is currently at a training level, it escapes the level
if self.EXECUTION_MODE=="test" and self.is_training:
return 'ACTION_ESCAPE'
# <Play the game (EXECUTION_MODE == 'create_dataset' or 'test')>
# Check if the agent can act at the current game state, i.e., execute an action.
# If it can't, the agent returns 'ACTION_NIL'
if not self.can_act(sso):
return 'ACTION_NIL'
# If the plan is empty, get a new one
if len(self.action_list) == 0:
# Get eligible subgoals at the current state
subgoals = self.get_subgoals_positions(sso)
# Make sure no subgoal is at the agent's position
avatar_position = (int(sso.avatarPosition[0] // sso.blockSize),
int(sso.avatarPosition[1] // sso.blockSize))
if avatar_position in subgoals:
subgoals.remove(avatar_position)
# Choose a random subgoal if the agent is randomly exploring
if self.EXECUTION_MODE=="create_dataset":
# Choose a random subgoal until one is attainable (search_plan returns a non-empty plan)
while len(subgoals) > 0 and len(self.action_list) == 0:
ind_subgoal = random.randint(0, len(subgoals) - 1)
chosen_subgoal = subgoals[ind_subgoal]
del subgoals[ind_subgoal] # Delete the chosen subgoal from the list
# If the game is IceAndFire, check how many types of boots the agent has
if self.game_playing == 'IceAndFire':
boots_resources = self.get_boots_resources(sso)
else:
boots_resources = []
# Obtain the plan
self.action_list = self.search_plan(sso, chosen_subgoal, boots_resources)
# Collect samples for the experience replay
self.add_samples_to_memory(sso, chosen_subgoal, len(self.action_list))
self.total_num_samples += 1
# Show the number of samples collected periodically
print("New sample")
if self.total_num_samples % 10 == 0:
print("n_total_samples:", self.total_num_samples)
print("n_unique_samples:", len(self.memory))
# If there is no plan, it means that at the current game state no subgoal is attainable ->
# the agent escapes the level (loses the game)
if len(self.action_list) == 0:
return 'ACTION_ESCAPE'
# Use the Learning model to select a subgoal if the agent is in test/validation phase
else:
ordered_subgoals = False # If true, get_best_subgoals has already been called
# Keep selecting subgoal until one is attainable from the current state of the game
while len(subgoals) > 0 and len(self.action_list) == 0:
# Select the subgoal using either the learning model or randomly (random model)
if self.goal_selection_mode == "best": # Use the model to select the best subgoal
# Order subgoals by their predicted Q_values
if not ordered_subgoals: # Only do it once
ordered_subgoals = True
# Measure goal selection time
start = time.time()
subgoals = self.get_best_subgoals(sso, subgoals)
end = time.time()
if not self.is_training:
self.total_time_goal_selec_curr_lv += end-start
# Get the first subgoal (the one with the smallest Q_value)
chosen_subgoal = subgoals[0]
elif self.goal_selection_mode == "random": # Select subgoals randomly
chosen_subgoal = subgoals[random.randint(0, len(subgoals) - 1)]
# goal selection mode = greedy
else: # Plan to every subgoal and select the one of the shortest plan
# Order subgoals by their plan lengths
if not ordered_subgoals: # Only do it once
ordered_subgoals = True
# Measure planning times
start = time.time()
old_subgoals = subgoals
subgoals = self.order_subgoals_by_plan_length(sso, subgoals)
end = time.time()
if not self.is_training:
self.total_time_planning_curr_lv += end-start
# Get the first subgoal (the one with the smallest plan length)
if len(subgoals) > 0:
chosen_subgoal = subgoals[0]
else: # If there is no valid subgoal, choose any subgoal
chosen_subgoal = old_subgoals[0]
# Remove the selected subgoal from the list of eligible subgoals
if len(subgoals) > 0:
subgoals.remove(chosen_subgoal)
# If the game is IceAndFire, check how many types of boots the agent has
if self.game_playing == 'IceAndFire':
boots_resources = self.get_boots_resources(sso)
else:
boots_resources = []
# Obtain the plan
start = time.time()
self.action_list = self.search_plan(sso, chosen_subgoal, boots_resources)
end = time.time()
# Measure planning time unless the goal selection mode is greedy, because in that case
# we have already planned for each subgoal
# (we could actually obtain a list of plans for each possible subgoal in that case but
# to simplify the code we plan for each subgoal again (even though it's not needed) and
# don't add the planning time)
if not self.is_training and self.goal_selection_mode != "greedy":
self.total_time_planning_curr_lv += end-start
# If there is no valid plan to the chosen subgoal, increment the number of
# non-eligible subgoals selected
if len(self.action_list) == 0:
self.num_incorrect_subgoals += 1
# If none of the subgoals is attainable, the agent is at a dead end ->
# the agent loses the game and escapes the level
if len(self.action_list) == 0:
self.num_incorrect_subgoals = -1 # This represents the agent has lost the game
return 'ACTION_ESCAPE'
# Save dataset and exit the program if the experience replay is the right size
if self.EXECUTION_MODE == 'create_dataset':
if self.total_num_samples >= self.num_total_samples_for_saving_dataset or \
len(self.memory) >= self.num_unique_samples_for_saving_dataset:
self.save_dataset(self.dataset_save_path, self.datasets_sizes_file_path)
# Exit the program with success code
sys.exit()
# Execute Plan
# If a plan has been found, return the first action
if len(self.action_list) > 0:
if not self.is_training: # Count the number of actions used to complete the level
self.num_actions_lv += 1
return self.action_list.pop(0)
else:
print("\n\nEMPTY PLAN\n\n")
return 'ACTION_NIL'
def add_samples_to_memory(self, sso, chosen_subgoal, plan_length):
"""
Method called at the 'create_dataset' phase, when a new plan (empty or not)
has been obtained for a given (sso, chosen_subgoal) pair.
Firstly, it completes the old mem_sample (if needed) and adds it to the experience replay.
Secondly, it creates a new mem_sample and adds the one_hot_matrix and plan_length to it.
If the chosen_subgoal corresponds to the final goal or the plan is invalid,
the new mem_sample is already added to the experience replay. If not, it will be added
the next time this method is called.
Mem samples are of the form (one_hot_grid, plan_length, next_state_one_hot_grid, subgoal_positions_next_state)
@param sso The current state of the game
@param chosen_subgoal The selected subgoal for the current state of the game
@param plan_length The number of actions of the plan obtained for the (sso, chosen_subgoal) pair.
If it's 0, the plan is invalid.
"""
# If the old mem_sample lacks the new state of the game, complete it
# and add it to the experience replay
if len(self.mem_sample) == 2:
# Add the next state (the current state of the game) and the positions of the subgoals
# at that state
self.mem_sample.append(self.encode_game_state(sso.observationGrid, None))
self.mem_sample.append(self.get_subgoals_positions(sso))
self.memory.append(self.mem_sample) # Add old mem_sample to memory
# <Check if the new sample is unique>
# Obtain the hash for the (sso, chosen_subgoal) pair
new_hash = self.get_sso_subgoal_hash(sso, chosen_subgoal)
# If the hash is new, create a new sample
if new_hash not in self.sample_hashes:
# Add the hash
self.sample_hashes.add(new_hash)
# Encode (sso, chosen_subgoal) as a one_hot matrix
one_hot_grid = self.encode_game_state(sso.observationGrid, chosen_subgoal)
# Invalid plan (there is no plan for the chosen_subgoal)
if plan_length == 0:
# If the plan is invalid, its length will be saved as self.num_actions_invalid_plan
plan_length = self.num_actions_invalid_plan
# Save it already to the experience replay (since there is no end state)
self.mem_sample = [one_hot_grid, plan_length, None, None]
self.memory.append(self.mem_sample)
# Valid plan
else:
# Check if the subgoal corresponds to the final goal (exit)
exit = sso.portalsPositions[0][0]
exit_pos_x = int(exit.position.x // sso.blockSize)
exit_pos_y = int(exit.position.y // sso.blockSize)
subgoal_is_final = (exit_pos_x == chosen_subgoal[0] and
exit_pos_y == chosen_subgoal[1])
if subgoal_is_final:
# Save the new sample already to the experience replay (since there is no end state)
self.mem_sample = [one_hot_grid, plan_length, None, None]
self.memory.append(self.mem_sample)
else:
# Create the new, incomplete mem_sample
self.mem_sample = [one_hot_grid, plan_length]
def get_agent_resources(self, sso):
"""
Returns a list with three elements, that contains the resources the agent has in
the state given by sso. These resources depend on the game being played.
"""
# BoulderDash -> [gems]
if self.game_playing == 'BoulderDash':
keys = sso.avatarResources.keys()
if len(keys) > 0:
gem_key = list(sso.avatarResources)[0]
num_gems = sso.avatarResources[gem_key]
else:
num_gems = 0
agent_resources = [num_gems, 0, 0]
# IceAndFire -> [coins, fire_boots, ice_boots]
elif self.game_playing == "IceAndFire":
# Get the number of coins left on the map
coin_itype = 10 # Itype of coins
coins_on_the_map = 0
obs = sso.observationGrid
X_MAX = sso.observationGridNum
Y_MAX = sso.observationGridMaxRow
for y in range(Y_MAX):
for x in range(X_MAX):
observation = sso.observationGrid[x][y][0]
if observation is not None:
if observation.itype == coin_itype:
coins_on_the_map += 1
# Each level always has 10 coins at the start
num_coins_agent = 10 - coins_on_the_map
# Get the boots the agent has
keys = sso.avatarResources.keys()
ice_boot_key = '8' # Keys of each boot in the avatarResources dictionary
fire_boot_key = '9'
ice_boots_agent = 0
fire_boots_agent = 0
# Check if the agent has at least one boot
if len(keys) > 0:
if ice_boot_key in keys: # The agent has ice boots
ice_boots_agent = 1
if fire_boot_key in keys: # The agent has fire boots
fire_boots_agent = 1
agent_resources = [num_coins_agent, fire_boots_agent, ice_boots_agent]
# Catapults -> no resources
else:
agent_resources = [0,0,0]
return agent_resources
def get_subgoals_positions(self, sso):
"""
Method that returns all the eligible subgoals by the agent at the current state of
the game.
Note: the final subgoal is always returned, even if it's not attainable.
@param sso Observation of the current state of the game.
@return The grid positions of the eligible subgoals, as a list of the (x,y) coordinates
of each subgoal.
"""
if self.game_playing == 'BoulderDash':
subgoal_pos = [] # Positions of subgoals
# Final goal
exit = sso.portalsPositions[0][0]
exit_pos = (int(exit.position.x // sso.blockSize), int(exit.position.y // sso.blockSize))
subgoal_pos.append(exit_pos)
# Gems subgoals