-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathintrinsic_qbert.py
2638 lines (2484 loc) · 118 KB
/
intrinsic_qbert.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import torch
import torch.nn as nn
import torch.optim as optim
import torch.autograd as autograd
import torch.nn.functional as F
import os
from os.path import basename, splitext
import numpy as np
import time
import sentencepiece as spm
from statistics import mean
from jericho import *
from jericho.template_action_generator import TemplateActionGenerator
from jericho.util import unabbreviate, clean
import jericho.defines
import copy
# from representations import StateAction
from models import QBERT
from env import *
from vec_env import *
import logger
import random
# from extraction import kgextraction
# torch.backends.cudnn.deterministic = True
# torch.backends.cudnn.benchmark = False
device = torch.device("cuda")
# explain RL
from xRL_templates import XRL
def configure_logger(log_dir):
logger.configure(log_dir, format_strs=["log"])
global tb
tb = logger.Logger(
log_dir,
[
logger.make_output_format("tensorboard", log_dir),
logger.make_output_format("csv", log_dir),
logger.make_output_format("stdout", log_dir),
],
)
global log
logger.set_level(60)
log = logger.log
class QBERTTrainer(object):
"""
QBERT main class.
"""
def __init__(self, params, args):
print("----- Initiating ----- ")
print("----- step 1 configure logger")
self.seed = params["seed"]
torch.manual_seed(params["seed"])
np.random.seed(params["seed"])
random.seed(params["seed"])
configure_logger(params["output_dir"])
log("Parameters {}".format(params))
self.params = params
self.chkpt_path = os.path.dirname(self.params["checkpoint_path"])
if not os.path.exists(self.chkpt_path):
os.mkdir(self.chkpt_path)
print("----- step 2 load pre-collected things")
self.sp = spm.SentencePieceProcessor()
self.sp.Load(params["spm_file"])
# askbert_args = {'input_text': '', 'length': 10, 'batch_size': 1, 'temperature': 1, 'model_name': '117M',
# 'seed': 0, 'nsamples': 10, 'cutoffs': "6.5 -7 -5", 'write_sfdp': False, 'random': False}
# self.extraction = kgextraction.World([], [], [], askbert_args)
self.askbert = params["extraction"]
print("----- step 3 build QBERTEnv")
kg_env = QBERTEnv(
rom_path=params["rom_file_path"],
seed=params["seed"],
spm_model=self.sp,
tsv_file=params["tsv_file"],
attr_file=params["attr_file"],
step_limit=params["reset_steps"],
stuck_steps=params["stuck_steps"],
gat=params["gat"],
askbert=self.askbert,
clear_kg=params["clear_kg_on_reset"],
subKG_type=params["subKG_type"],
)
self.vec_env = VecEnv(
num_envs=params["batch_size"],
env=kg_env,
openie_path=params["openie_path"],
redis_db_path=params["redis_db_path"],
buffer_size=params["buffer_size"],
askbert=params["extraction"],
training_type=params["training_type"],
clear_kg=params["clear_kg_on_reset"],
)
env = FrotzEnv(params["rom_file_path"])
# self.binding = env.bindings
self.binding = jericho.load_bindings(params["rom_file_path"])
self.max_word_length = self.binding["max_word_length"]
self.template_generator = TemplateActionGenerator(self.binding)
print("----- step 4 build FrotzEnv and templace generator")
self.max_game_score = env.get_max_score()
self.cur_reload_state = env.get_state()
self.vocab_act, self.vocab_act_rev = load_vocab(env)
print("----- step 5 build Qbert model")
self.model = QBERT(
params,
self.template_generator.templates,
self.max_word_length,
self.vocab_act,
self.vocab_act_rev,
len(self.sp),
gat=self.params["gat"],
argmax_sig=self.params["argmax_sig"]
).cuda()
print("----- step 6 set training parameters")
self.batch_size = params["batch_size"]
if params["preload_weights"]:
print("preload_weights are => ", params["preload_weights"])
self.model = torch.load(self.params["preload_weights"])["model"]
self.optimizer = optim.Adam(self.model.parameters(), lr=params["lr"])
self.loss_fn1 = nn.BCELoss()
self.loss_fn2 = nn.BCEWithLogitsLoss()
self.loss_fn3 = nn.MSELoss()
self.chained_logger = params["chained_logger"]
self.total_steps = 0
#####BBB#####
self.early_stop_score = params["early_stop_score"]
self.early_stop_score_count = params["early_stop_score_count"]
self.eval_mode = params["eval_mode"]
print("----- Init finished! ----- ")
self.tsv_file = self.load_vocab_kge(params["tsv_file"])
# explain RL
self.random_action = params["random_action"]
# print('self.random_action', self.random_action)
if self.random_action:
xRL_file_path = "/Q-BERT/qbert/logs/xRL_sd" + str(self.seed) + "_random_" + params['game_name'] +".txt"
xRL_obs_file_path = "/Q-BERT/qbert/logs/xRL_obs_sd" + str(self.seed) + "_random_" + params['game_name'] +".txt"
xRL_kg_file_dir = "/Q-BERT/qbert/logs/KG_sd" + str(self.seed) + "_random" + "_" + params['game_name']
else:
xRL_file_path = "/Q-BERT/qbert/logs/xRL_sd" + str(self.seed) + "_" + params['game_name'] +".txt"
xRL_obs_file_path = "/Q-BERT/qbert/logs/xRL_obs_sd" + str(self.seed) + "_" + params['game_name'] +".txt"
xRL_kg_file_dir = "/Q-BERT/qbert/logs/KG_sd" + str(self.seed) + "_" + params['game_name']
if not os.path.exists(xRL_kg_file_dir):
os.makedirs(xRL_kg_file_dir)
self.XRL = XRL(
file_path=xRL_file_path,
tsv_file=self.tsv_file,
args=args,
obs_file_path=xRL_obs_file_path,
spm_file=params["spm_file"],
kg_file_dir=xRL_kg_file_dir,
)
self.random_action = False
def log_file(self, str):
with open(self.chained_logger, "a+") as fh:
fh.write(str)
def generate_targets(self, admissible, objs):
"""
Generates ground-truth targets for admissible actions.
:param admissible: List-of-lists of admissible actions. Batch_size x Admissible
:param objs: List-of-lists of interactive objects. Batch_size x Objs
:returns: template targets and object target tensors
"""
tmpl_target = []
obj_targets = []
for adm in admissible:
obj_t = set()
cur_t = [0] * len(self.template_generator.templates)
for a in adm:
cur_t[a.template_id] = 1
obj_t.update(a.obj_ids)
tmpl_target.append(cur_t)
obj_targets.append(list(obj_t))
tmpl_target_tt = torch.FloatTensor(tmpl_target).cuda()
# Note: Adjusted to use the objects in the admissible actions only
object_mask_target = []
for objl in obj_targets: # in objs
cur_objt = [0] * len(self.vocab_act)
for o in objl:
cur_objt[o] = 1
object_mask_target.append([[cur_objt], [cur_objt]])
obj_target_tt = torch.FloatTensor(object_mask_target).squeeze().cuda()
return tmpl_target_tt, obj_target_tt
def generate_graph_mask(self, graph_infos):
assert len(graph_infos) == self.batch_size
mask_all = []
# TODO use graph dropout for masking here
for graph_info in graph_infos:
mask = [0] * len(self.vocab_act.keys())
# Case 1 (default): KG as mask
if self.params["masking"] == "kg":
# Uses the knowledge graph as the mask.
graph_state = graph_info.graph_state
ents = set()
for u, v in graph_state.edges:
ents.add(u)
ents.add(v)
# print('graph-mask', u,v)
# Build mask: only use those related to entities
for ent in ents:
for ent_word in ent.split():
if ent_word[: self.max_word_length] in self.vocab_act_rev:
idx = self.vocab_act_rev[ent_word[: self.max_word_length]]
mask[idx] = 1
if self.params["mask_dropout"] != 0:
drop = random.sample(
range(0, len(self.vocab_act.keys()) - 1),
int(self.params["mask_dropout"] * len(self.vocab_act.keys())),
)
for i in drop:
mask[i] = 1
# Case 2: interactive objects ground truth as the mask.
elif self.params["masking"] == "interactive":
# Uses interactive objects grount truth as the mask.
for o in graph_info.objs:
o = o[: self.max_word_length]
if o in self.vocab_act_rev.keys() and o != "":
mask[self.vocab_act_rev[o]] = 1
if self.params["mask_dropout"] != 0:
drop = random.sample(
range(0, len(self.vocab_act.keys()) - 1),
int(
self.params["mask_dropout"] * len(self.vocab_act.keys())
),
)
for i in drop:
mask[i] = 1
# Case 3: no mask.
elif self.params["masking"] == "none":
# No mask at all.
mask = [1] * len(self.vocab_act.keys())
else:
assert False, "Unrecognized masking {}".format(self.params["masking"])
# print('mask ===>', mask)
mask_all.append(mask)
return torch.BoolTensor(mask_all).cuda().detach()
def discount_reward(self, transitions, last_values):
returns, advantages = [], []
R = last_values.data
for t in reversed(range(len(transitions))):
_, _, values, rewards, done_masks, _, _, _, _, _, _ = transitions[t]
R = rewards + self.params["gamma"] * R * done_masks
adv = R - values
returns.append(R)
advantages.append(adv)
return returns[::-1], advantages[::-1]
def goexplore_train(
self, obs, infos, graph_infos, max_steps, INTRINSIC_MOTIVTATION
):
start = time.time()
transitions = []
if obs == None:
obs, infos, graph_infos = self.vec_env.go_reset()
for step in range(1, max_steps + 1):
self.total_steps += 1
tb.logkv("Step", self.total_steps)
obs_reps = np.array([g.ob_rep for g in graph_infos])
graph_mask_tt = self.generate_graph_mask(graph_infos)
graph_state_reps = [g.graph_state_rep for g in graph_infos]
if self.params["reward_type"] == "game_only":
scores = [info["score"] for info in infos]
elif self.params["reward_type"] == "IM_only":
scores = np.array(
[
int(
len(INTRINSIC_MOTIVTATION[i])
* self.params["intrinsic_motivation_factor"]
)
for i in range(self.params["batch_size"])
]
)
elif self.params["reward_type"] == "game_and_IM":
scores = np.array(
[
infos[i]["score"]
+ (
len(INTRINSIC_MOTIVTATION[i])
* (
(infos[i]["score"] + self.params["epsilon"])
/ self.max_game_score
)
)
for i in range(self.params["batch_size"])
]
)
(
tmpl_pred_tt,
obj_pred_tt,
dec_obj_tt,
dec_tmpl_tt,
value,
dec_steps,
output_gat,
query_important,
) = self.model(obs_reps, scores, graph_state_reps, graph_mask_tt)
tb.logkv_mean("Value", value.mean().item())
# Log some of the predictions and ground truth values
topk_tmpl_probs, topk_tmpl_idxs = F.softmax(tmpl_pred_tt[0]).topk(5)
topk_tmpls = [
self.template_generator.templates[t] for t in topk_tmpl_idxs.tolist()
]
tmpl_pred_str = ", ".join(
[
"{} {:.3f}".format(tmpl, prob)
for tmpl, prob in zip(topk_tmpls, topk_tmpl_probs.tolist())
]
)
admissible = [g.admissible_actions for g in graph_infos]
# print('admissible', admissible)
objs = [g.objs for g in graph_infos]
tmpl_gt_tt, obj_mask_gt_tt = self.generate_targets(admissible, objs)
gt_tmpls = [
self.template_generator.templates[i]
for i in tmpl_gt_tt[0]
.nonzero()
.squeeze()
.cpu()
.numpy()
.flatten()
.tolist()
]
gt_objs = [
self.vocab_act[i]
for i in obj_mask_gt_tt[0, 0]
.nonzero()
.squeeze()
.cpu()
.numpy()
.flatten()
.tolist()
]
log("TmplPred: {} GT: {}".format(tmpl_pred_str, ", ".join(gt_tmpls)))
topk_o1_probs, topk_o1_idxs = F.softmax(obj_pred_tt[0, 0]).topk(5)
topk_o1 = [self.vocab_act[o] for o in topk_o1_idxs.tolist()]
o1_pred_str = ", ".join(
[
"{} {:.3f}".format(o, prob)
for o, prob in zip(topk_o1, topk_o1_probs.tolist())
]
)
graph_mask_str = [
self.vocab_act[i]
for i in graph_mask_tt[0]
.nonzero()
.squeeze()
.cpu()
.numpy()
.flatten()
.tolist()
]
log(
"ObjtPred: {} GT: {} Mask: {}".format(
o1_pred_str, ", ".join(gt_objs), ", ".join(graph_mask_str)
)
)
chosen_actions = self.decode_actions(dec_tmpl_tt, dec_obj_tt)
# Chooses random valid-actions to execute
obs, rewards, dones, infos, graph_infos = self.vec_env.go_step(
chosen_actions
)
# print('obs =>', obs)
edges = [set(graph_info.graph_state.edges) for graph_info in graph_infos]
size_updates = [0] * self.params["batch_size"]
for i, s in enumerate(INTRINSIC_MOTIVTATION):
orig_size = len(s)
s.update(edges[i])
size_updates[i] = len(s) - orig_size
rewards = list(rewards)
for i in range(self.params["batch_size"]):
if self.params["reward_type"] == "IM_only":
rewards[i] = (
size_updates[i] * self.params["intrinsic_motivation_factor"]
)
elif self.params["reward_type"] == "game_and_IM":
rewards[i] += (
size_updates[i] * self.params["intrinsic_motivation_factor"]
)
rewards = tuple(rewards)
tb.logkv_mean(
"TotalStepsPerEpisode",
sum([i["steps"] for i in infos]) / float(len(graph_infos)),
)
tb.logkv_mean("Valid", infos[0]["valid"])
log(
"Act: {}, Rew {}, Score {}, Done {}, Value {:.3f}".format(
chosen_actions[0],
rewards[0],
infos[0]["score"],
dones[0],
value[0].item(),
)
)
log("Obs: {}".format(clean(obs[0])))
if dones[0]:
log("Step {} EpisodeScore {}\n".format(step, infos[0]["score"]))
for done, info in zip(dones, infos):
if done:
tb.logkv_mean("EpisodeScore", info["score"])
rew_tt = torch.FloatTensor(rewards).cuda().unsqueeze(1)
done_mask_tt = (~torch.tensor(dones)).float().cuda().unsqueeze(1)
self.model.reset_hidden(done_mask_tt)
transitions.append(
(
tmpl_pred_tt,
obj_pred_tt,
value,
rew_tt,
done_mask_tt,
tmpl_gt_tt,
dec_tmpl_tt,
dec_obj_tt,
obj_mask_gt_tt,
graph_mask_tt,
dec_steps,
)
)
if len(transitions) >= self.params["bptt"]:
tb.logkv("StepsPerSecond", float(step) / (time.time() - start))
self.model.clone_hidden()
obs_reps = np.array([g.ob_rep for g in graph_infos])
graph_mask_tt = self.generate_graph_mask(graph_infos)
graph_state_reps = [g.graph_state_rep for g in graph_infos]
# scores = [info['score'] for info in infos]
if self.params["reward_type"] == "game_only":
scores = [info["score"] for info in infos]
elif self.params["reward_type"] == "IM_only":
scores = np.array(
[
int(
len(INTRINSIC_MOTIVTATION[i])
* self.params["intrinsic_motivation_factor"]
)
for i in range(self.params["batch_size"])
]
)
elif self.params["reward_type"] == "game_and_IM":
print('scores =>', infos[i]["score"])
scores = np.array(
[
infos[i]["score"]
+ (
len(INTRINSIC_MOTIVTATION[i])
* (
(infos[i]["score"] + self.params["epsilon"])
/ self.max_game_score
)
)
for i in range(self.params["batch_size"])
]
)
_, _, _, _, next_value, _, output_gat, query_important = self.model(
obs_reps, scores, graph_state_reps, graph_mask_tt
)
returns, advantages = self.discount_reward(transitions, next_value)
log(
"Returns: ",
", ".join(["{:.3f}".format(a[0].item()) for a in returns]),
)
log(
"Advants: ",
", ".join(["{:.3f}".format(a[0].item()) for a in advantages]),
)
tb.logkv_mean("Advantage", advantages[-1].median().item())
loss = self.update(transitions, returns, advantages)
del transitions[:]
self.model.restore_hidden()
if step % self.params["checkpoint_interval"] == 0:
parameters = {"model": self.model}
torch.save(
parameters, os.path.join(self.params["output_dir"], "qbert" + str(self.seed) + ".pt")
)
# self.vec_env.close_extras()
return (
obs,
rewards,
dones,
infos,
graph_infos,
scores,
chosen_actions,
INTRINSIC_MOTIVTATION,
)
def train(self, max_steps):
file_kg = open('/Q-BERT/qbert/logs/train_alpha_' +str(self.params['alpha_gat']) +'_' + game +'.txt', "w")
print("=== === === start training!!! === === ===")
start = time.time()
if self.params["training_type"] == "chained":
self.log_file(
"BEGINNING OF TRAINING: patience={}, max_n_steps_back={}\n".format(
self.params["patience"], self.params["buffer_size"]
)
)
frozen_policies = []
transitions = []
self.back_step = -1
previous_best_seen_score = float("-inf")
previous_best_step = 0
previous_best_state = None
previous_best_snapshot = None
previous_best_ACTUAL_score = 0
self.cur_reload_step = 0
force_reload = [False] * self.params["batch_size"]
last_edges = None
self.valid_track = np.zeros(self.params["batch_size"])
self.stagnant_steps = 0
INTRINSIC_MOTIVTATION = [set() for i in range(self.params["batch_size"])]
obs, infos, graph_infos, env_str = self.vec_env.reset()
snap_obs = obs[0]
snap_info = infos[0]
snap_graph_reps = None
# print (obs)
# print (infos)
# print (graph_infos)
# early stop counting#
best_scores = [0] * self.batch_size # 8 env
for step in range(1, max_steps + 1):
# Step 1: build model inputs
wallclock = time.time()
if any(force_reload) and self.params["training_type"] == "chained":
num_reload = force_reload.count(True)
t_obs = np.array(obs)
t_obs[force_reload] = [snap_obs] * num_reload
obs = tuple(t_obs)
t_infos = np.array(infos)
t_infos[force_reload] = [snap_info] * num_reload
infos = tuple(t_infos)
t_graphs = list(graph_infos)
# namedtuple gets lost in np.array
t_updates = self.vec_env.load_from(
self.cur_reload_state, force_reload, snap_graph_reps, snap_obs
)
for i in range(self.params["batch_size"]):
if force_reload[i]:
t_graphs[i] = t_updates[i]
graph_infos = tuple(t_graphs)
force_reload = [False] * self.params["batch_size"]
tb.logkv("Step", step)
obs_reps = np.array([g.ob_rep for g in graph_infos])
graph_mask_tt = self.generate_graph_mask(graph_infos)
graph_state_reps = [g.graph_state_rep for g in graph_infos]
if self.params["reward_type"] == "game_only":
scores = [info["score"] for info in infos]
elif self.params["reward_type"] == "IM_only":
scores = np.array(
[
int(
len(INTRINSIC_MOTIVTATION[i])
* self.params["intrinsic_motivation_factor"]
)
for i in range(self.params["batch_size"])
]
)
elif self.params["reward_type"] == "game_and_IM":
scores = np.array(
[
infos[i]["score"]
+ (
len(INTRINSIC_MOTIVTATION[i])
* (
(infos[i]["score"] + self.params["epsilon"])
/ self.max_game_score
)
)
for i in range(self.params["batch_size"])
]
)
# print('!!!score', scores)
# print('graph_infos ===>', graph_infos)
graph_rep_1 = [g.graph_state_rep_1 for g in graph_infos]
graph_rep_2 = [g.graph_state_rep_2 for g in graph_infos]
graph_rep_3 = [g.graph_state_rep_3 for g in graph_infos]
graph_rep_4 = [g.graph_state_rep_4 for g in graph_infos]
graph_rep = [g.graph_state_rep for g in graph_infos]
adj0 = torch.IntTensor(graph_rep[0][1]).cuda()
# print('graph_shape=>', len(torch.nonzero(adj0 > 0)))
# save logs
# print('state_gat', self.model.state_gat.state_ent_emb.weight.sum(dim=-1).sum())
file_kg.write('\n')
file_kg.write('=' * 30 + '\n')
file_kg.write('STEP: ' + str(step) + '\n')
file_kg.write(obs + '\n')
# file_kg.write('BEST >' + str(best_scores) + '\n')
# file_kg.write('BEST w/o KG >' + str([infos[i]["score"] for i in range(len(infos))]) + '\n')
# file_kg.write('Embedding sum: ' + str(float(self.model.state_gat.state_ent_emb.weight.sum(dim=-1).sum().cpu().detach().numpy())) + '\n')
# file_kg.write('>>>Full-graph: \n')
# file_kg.write('Length:' + str(len([g.graph_state.edges for g in graph_infos][0])) + '\n')
# file_kg.write(str([g.graph_state.edges for g in graph_infos][0]) + '\n')
# file_kg.write('>>>Subgraph_1: \n')
# file_kg.write('Length: ' + str(len([g.graph_state_1.edges for g in graph_infos][0])) + '\n')
# file_kg.write(str([g.graph_state_1.edges for g in graph_infos][0]) + '\n')
#
# file_kg.write('>>>Subgraph_2: \n')
# file_kg.write('Length: ' + str(len([g.graph_state_2.edges for g in graph_infos][0])) + '\n')
# file_kg.write(str([g.graph_state_2.edges for g in graph_infos][0]) + '\n')
# file_kg.write('>>>Subgraph_3: \n')
# file_kg.write('Length: ' + str(len([g.graph_state_3.edges for g in graph_infos][0])) + '\n')
# file_kg.write(str([g.graph_state_3.edges for g in graph_infos][0]) + '\n')
# file_kg.write('>>>Subgraph_4: \n')
# file_kg.write('Length: ' + str(len([g.graph_state_4.edges for g in graph_infos][0])) + '\n')
# file_kg.write(str([g.graph_state_4.edges for g in graph_infos][0]) + '\n')
file_kg.flush()
# Step 2: predict probs, actual items
(
tmpl_pred_tt,
obj_pred_tt,
dec_obj_tt,
dec_tmpl_tt,
value,
dec_steps,
output_gat,
query_important,
) = self.model(
obs_reps,
scores,
graph_state_reps,
graph_rep_1,
graph_rep_2,
graph_rep_3,
graph_rep_4,
graph_mask_tt,
)
# tmpl_pred_tt, obj_pred_tt, dec_obj_tt, dec_tmpl_tt, value, dec_steps = self.model(
# obs_reps, scores, graph_state_reps, graph_mask_tt)
tb.logkv_mean("Value", value.mean().item())
# Step 3: Log the predictions and ground truth values
# Log the predictions and ground truth values
topk_tmpl_probs, topk_tmpl_idxs = F.softmax(tmpl_pred_tt[0]).topk(5)
topk_tmpls = [
self.template_generator.templates[t] for t in topk_tmpl_idxs.tolist()
]
tmpl_pred_str = ", ".join(
[
"{} {:.3f}".format(tmpl, prob)
for tmpl, prob in zip(topk_tmpls, topk_tmpl_probs.tolist())
]
)
# Step 4: Generate the ground truth and object mask
admissible = [g.admissible_actions for g in graph_infos]
objs = [g.objs for g in graph_infos]
tmpl_gt_tt, obj_mask_gt_tt = self.generate_targets(admissible, objs)
# Step 5 Log template/object predictions/ground_truth
gt_tmpls = [
self.template_generator.templates[i]
for i in tmpl_gt_tt[0]
.nonzero()
.squeeze()
.cpu()
.numpy()
.flatten()
.tolist()
]
gt_objs = [
self.vocab_act[i]
for i in obj_mask_gt_tt[0, 0]
.nonzero()
.squeeze()
.cpu()
.numpy()
.flatten()
.tolist()
]
log("TmplPred: {} GT: {}".format(tmpl_pred_str, ", ".join(gt_tmpls)))
topk_o1_probs, topk_o1_idxs = F.softmax(obj_pred_tt[0, 0]).topk(5)
topk_o1 = [self.vocab_act[o] for o in topk_o1_idxs.tolist()]
o1_pred_str = ", ".join(
[
"{} {:.3f}".format(o, prob)
for o, prob in zip(topk_o1, topk_o1_probs.tolist())
]
)
# graph_mask_str = [self.vocab_act[i] for i in graph_mask_tt[0].nonzero().squeeze().cpu().numpy().flatten().tolist()]
log(
"ObjtPred: {} GT: {}".format(o1_pred_str, ", ".join(gt_objs))
) # , ', '.join(graph_mask_str)))
chosen_actions = self.decode_actions(dec_tmpl_tt, dec_obj_tt)
# stepclock = time.time()
# Step 6: Next step
obs, rewards, dones, infos, graph_infos, env_str = self.vec_env.step(
chosen_actions
)
# print('rewards =>', rewards)
# print('stepclock', time.time() - stepclock)
self.valid_track += [info["valid"] for info in infos]
self.stagnant_steps += 1
force_reload = list(dones)
edges = [set(graph_info.graph_state.edges) for graph_info in graph_infos]
size_updates = [0] * self.params["batch_size"]
for i, s in enumerate(INTRINSIC_MOTIVTATION):
orig_size = len(s)
s.update(edges[i])
size_updates[i] = len(s) - orig_size
rewards = list(rewards)
for i in range(self.params["batch_size"]):
if self.params["reward_type"] == "IM_only":
rewards[i] = (
size_updates[i] * self.params["intrinsic_motivation_factor"]
)
elif self.params["reward_type"] == "game_and_IM":
rewards[i] += (
size_updates[i] * self.params["intrinsic_motivation_factor"]
)
rewards = tuple(rewards)
if last_edges:
stayed_same = [
1
if (
len(edges[i] - last_edges[i])
<= self.params["kg_diff_threshold"]
)
else 0
for i in range(self.params["batch_size"])
]
# print ("stayed_same: {}".format(stayed_same))
valid_kg_update = (
last_edges
and sum(stayed_same) / self.params["batch_size"]
> self.params["kg_diff_batch_percentage"]
)
last_edges = edges
snapshot = self.vec_env.get_snapshot()
real_scores = np.array([infos[i]["score"] for i in range(len(rewards))])
if self.params["reward_type"] == "game_only":
scores = [info["score"] for info in infos]
elif self.params["reward_type"] == "IM_only":
scores = np.array(
[
int(
len(INTRINSIC_MOTIVTATION[i])
* self.params["intrinsic_motivation_factor"]
)
for i in range(self.params["batch_size"])
]
)
elif self.params["reward_type"] == "game_and_IM":
scores = np.array(
[
infos[i]["score"]
+ (
len(INTRINSIC_MOTIVTATION[i])
* (
(infos[i]["score"] + self.params["epsilon"])
/ self.max_game_score
)
)
for i in range(self.params["batch_size"])
]
)
cur_max_score_idx = np.argmax(scores)
if (
scores[cur_max_score_idx] > previous_best_seen_score
and self.params["training_type"] == "chained"
): # or valid_kg_update:
print("New Reward Founded OR KG updated")
previous_best_step = step
previous_best_state = env_str[cur_max_score_idx]
previous_best_seen_score = scores[cur_max_score_idx]
previous_best_snapshot = snapshot[cur_max_score_idx]
self.back_step = -1
self.valid_track = np.zeros(self.params["batch_size"])
self.stagnant_steps = 0
print("\tepoch: {}".format(previous_best_step))
print("\tnew score: {}".format(previous_best_seen_score))
print("\tthis info: {}".format(infos[cur_max_score_idx]))
self.log_file(
"New High Score Founded: step:{}, new_score:{}, infos:{}\n".format(
previous_best_step,
previous_best_seen_score,
infos[cur_max_score_idx],
)
)
previous_best_ACTUAL_score = max(
np.max(real_scores), previous_best_ACTUAL_score
)
print(
"step {}: scores: {}, best_real_score: {}".format(
step, scores, previous_best_ACTUAL_score
)
)
tb.logkv_mean(
"TotalStepsPerEpisode",
sum([i["steps"] for i in infos]) / float(len(graph_infos)),
)
tb.logkv_mean("Valid", infos[0]["valid"])
log(
"Act: {}, Rew {}, Score {}, Done {}, Value {:.3f}".format(
chosen_actions[0],
rewards[0],
infos[0]["score"],
dones[0],
value[0].item(),
)
)
log("Obs: {}".format(clean(obs[0])))
if dones[0]:
log("Step {} EpisodeScore {}\n".format(step, infos[0]["score"]))
for done, info in zip(dones, infos):
if done:
tb.logkv_mean("EpisodeScore", info["score"])
# Step 8: append into transitions
rew_tt = torch.FloatTensor(rewards).cuda().unsqueeze(1)
done_mask_tt = (~torch.tensor(dones)).float().cuda().unsqueeze(1)
self.model.reset_hidden(done_mask_tt)
transitions.append(
(
tmpl_pred_tt,
obj_pred_tt,
value,
rew_tt,
done_mask_tt,
tmpl_gt_tt,
dec_tmpl_tt,
dec_obj_tt,
obj_mask_gt_tt,
graph_mask_tt,
dec_steps,
)
)
# Step 9: update model per 8 steps
if len(transitions) >= self.params["bptt"]:
tb.logkv("StepsPerSecond", float(step) / (time.time() - start))
self.model.clone_hidden()
obs_reps = np.array([g.ob_rep for g in graph_infos])
graph_mask_tt = self.generate_graph_mask(graph_infos)
graph_state_reps = [g.graph_state_rep for g in graph_infos]
graph_rep_1 = [g.graph_state_rep_1 for g in graph_infos]
graph_rep_2 = [g.graph_state_rep_2 for g in graph_infos]
graph_rep_3 = [g.graph_state_rep_3 for g in graph_infos]
graph_rep_4 = [g.graph_state_rep_4 for g in graph_infos]
if self.params["reward_type"] == "game_only":
scores = [info["score"] for info in infos]
elif self.params["reward_type"] == "IM_only":
scores = np.array(
[
int(
len(INTRINSIC_MOTIVTATION[i])
* self.params["intrinsic_motivation_factor"]
)
for i in range(self.params["batch_size"])
]
)
elif self.params["reward_type"] == "game_and_IM":
scores = np.array(
[
infos[i]["score"]
+ (
len(INTRINSIC_MOTIVTATION[i])
* (
(infos[i]["score"] + self.params["epsilon"])
/ self.max_game_score
)
)
for i in range(self.params["batch_size"])
]
)
_, _, _, _, next_value, _, output_gat, query_important = self.model(
obs_reps,
scores,
graph_state_reps,
graph_rep_1,
graph_rep_2,
graph_rep_3,
graph_rep_4,
graph_mask_tt,
)
returns, advantages = self.discount_reward(transitions, next_value)
log(
"Returns: ",
", ".join(["{:.3f}".format(a[0].item()) for a in returns]),
)
log(
"Advants: ",
", ".join(["{:.3f}".format(a[0].item()) for a in advantages]),
)
tb.logkv_mean("Advantage", advantages[-1].median().item())
loss = self.update(transitions, returns, advantages)
print("next_value ===>", next_value)
del transitions[:]
self.model.restore_hidden()
if step % self.params["checkpoint_interval"] == 0:
parameters = {"model": self.model}
torch.save(
parameters, os.path.join(self.params["output_dir"], "qbert" + str(self.seed) + ".pt")
)
#########EARLY STOP#############
early_stop_count = 0
print("best_scores history =>", best_scores)
for idx, score in enumerate(scores):
best_scores[idx] = max(score, best_scores[idx])
if best_scores[idx] < self.early_stop_score:
early_stop_count += 1
print("early_stop counts are => ", early_stop_count)
if early_stop_count <= self.early_stop_score_count:
parameters = {"model": self.model}
torch.save(
parameters, os.path.join(self.params["output_dir"], "qbert" + str(self.seed) + ".pt")
)
break
#########EARLY STOP#############
bottleneck = self.params["training_type"] == "chained" and (
(
self.stagnant_steps >= self.params["patience"]
and not self.params["patience_valid_only"]
)
or (
self.params["patience_valid_only"]
and sum(self.valid_track >= self.params["patience"])
>= self.params["batch_size"] * self.params["patience_batch_factor"]
)
)
if bottleneck:
bottleneck_sig = True
print("Bottleneck detected at step: {}".format(step))
# new_backstep += 1
# new_back_step = (step - previous_best_step - self.params['patience']) // self.params['patience']
self.back_step += 1
if self.back_step == 0:
self.vec_env.import_snapshot(previous_best_snapshot)
cur_time = time.strftime("%Y%m%d-%H%M%S")
torch.save(
self.model.state_dict(),
os.path.join(self.chkpt_path, "{}.pt".format(cur_time)),
)
frozen_policies.append((cur_time, previous_best_state))
# INTRINSIC_MOTIVTATION= [set() for i in range(self.params['batch_size'])]
self.log_file(
"Current model saved at: model/checkpoints/{}.pt\n".format(
cur_time
)
)