-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathrllib_model_torch.py
2302 lines (1924 loc) · 92.1 KB
/
rllib_model_torch.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import logging
from math import floor
from black import out
import numpy as np
import os
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.torch.torch_modelv2 import TorchModelV2
from ray.rllib.models.torch.misc import SlimFC, SlimConv2d,normc_initializer
from ray.rllib.policy.rnn_sequencing import add_time_dimension
from ray.rllib.utils.annotations import override
# from ray.rllib.utils.framework import get_activation_fn
from ray.rllib.utils import try_import_torch
from ray.rllib.models import ModelCatalog
torch, nn = try_import_torch()
import torch.nn.functional as F
logger = logging.getLogger(__name__)
def softmax_normalized(x, dim):
x_hat = x-torch.max(x, dim=dim)[0].unsqueeze(-1)
return F.softmax(x_hat, dim=dim)
def get_activation_fn(name=None):
if name in ["linear", None]:
return None
if name in ["swish", "silu"]:
from ray.rllib.utils.torch_ops import Swish
return Swish
if name == "relu":
return nn.ReLU
if name == "tanh":
return nn.Tanh
if name == "sigmoid":
return nn.Sigmoid
if name == "elu":
return nn.ELU
raise ValueError("Unknown activation ({})={}!".format(name))
def create_layer(layer_type, layers, size_in, size_out, append_log_std=False):
output_layer = None
lstm_layer = None
if layer_type == "mlp":
param = {
"size_in": size_in,
"size_out": size_out,
"layers": layers,
"append_log_std": append_log_std,
}
output_layer = FC(**param)
elif layer_type == "lstm":
## TODO: needed to be fixed by layers
assert layers[0]["type"] == "lstm"
hidden_size = layers[0]["hidden_size"]
num_layers = layers[0]["num_layers"]
lstm_layer = nn.LSTM(
input_size=size_in,
hidden_size=hidden_size,
num_layers=num_layers,
batch_first=True,
)
''' For the compatibility of the previous config '''
output_activation = layers[0].get("output_activation")
if output_activation:
if output_activation == "linear":
output_layer = nn.Sequential(
nn.Linear(
in_features=hidden_size,
out_features=size_out,
),
)
elif output_activation == "tanh":
output_layer = nn.Sequential(
nn.Linear(
in_features=hidden_size,
out_features=size_out,
),
nn.Tanh(),
)
else:
raise NotImplementedError
output_layers = layers[0].get("output_layers")
if output_layers:
param = {
"size_in": hidden_size,
"size_out": size_out,
"layers": output_layers,
"append_log_std": append_log_std,
}
output_layer = FC(**param)
else:
raise NotImplementedError
assert output_layer is not None
return output_layer, lstm_layer
def forward_layer(obs, seq_lens=None, state=None, state_cnt=None, output_layer=None, lstm_layer=None):
if lstm_layer is None and output_layer is None:
out = obs
elif lstm_layer is None and output_layer is not None:
out = output_layer(obs)
elif lstm_layer is not None and output_layer is not None:
assert seq_lens is not None and state is not None and state_cnt is not None
out, state_cnt = process_lstm(obs, seq_lens, state, state_cnt, output_layer, lstm_layer)
else:
raise Exception("Invalid Inputs")
return out, state_cnt
def process_lstm(obs, seq_lens, state, state_cnt, output_layer, lstm_layer):
if isinstance(seq_lens, np.ndarray):
seq_lens = torch.Tensor(seq_lens).int()
if seq_lens is not None:
max_seq_len = obs.shape[0] // seq_lens.shape[0]
# max_seq_len=torch.max(seq_lens)
input_lstm = add_time_dimension(
obs,
max_seq_len=max_seq_len,
framework="torch",
time_major=False,
)
'''
Assume that the shape of state is
(batch, num_layers * num_directions, hidden_size). So we change
the first axis with the second axis.
'''
h_lstm, c_lstm = state[state_cnt], state[state_cnt+1]
h_lstm = h_lstm.reshape(h_lstm.shape[1], h_lstm.shape[0], h_lstm.shape[2])
c_lstm = c_lstm.reshape(c_lstm.shape[1], c_lstm.shape[0], c_lstm.shape[2])
output_lstm, (h_lstm, c_lstm) = lstm_layer(input_lstm, (h_lstm, c_lstm))
output_lstm = output_lstm.reshape(-1, output_lstm.shape[-1])
out = output_layer(output_lstm)
'''
Change the first and second axes of the output state so that
it matches to the assumption
'''
h_lstm = h_lstm.reshape(h_lstm.shape[1], h_lstm.shape[0], h_lstm.shape[2])
c_lstm = c_lstm.reshape(c_lstm.shape[1], c_lstm.shape[0], c_lstm.shape[2])
state[state_cnt] = h_lstm
state[state_cnt+1] = c_lstm
state_cnt += 2
return out, state_cnt
class Normalizer(nn.Module):
def __init__(self, mu, std):
super().__init__()
self.set_val(mu, std)
def set_val(self, mu, std):
assert mu.shape[-1] == std.shape[-1]
self.mu = mu
self.std = std
def forward(self, x):
assert x.shape[-1] == self.mu.shape[-1]
return (x - self.mu) / self.std
class Denormalizer(nn.Module):
def __init__(self, mu, std):
super().__init__()
self.set_val(mu, std)
def set_val(self, mu, std):
assert mu.shape[-1] == std.shape[-1]
self.mu = mu
self.std = std
def forward(self, x):
assert x.shape[-1] == self.mu.shape[-1]
return (x + self.mu) * self.std
class AppendLogStd(nn.Module):
'''
An appending layer for log_std.
'''
def __init__(self, type, init_val, dim):
super().__init__()
self.type = type
if np.isscalar(init_val):
init_val = init_val * np.ones(dim)
elif isinstance(init_val, (np.ndarray, list)):
assert len(init_val) == dim
else:
raise NotImplementedError
self.init_val = init_val
if self.type=="constant":
self.log_std = torch.Tensor(init_val)
elif self.type=="state_independent":
self.log_std = torch.nn.Parameter(
torch.Tensor(init_val))
self.register_parameter("log_std", self.log_std)
else:
raise NotImplementedError
def set_val(self, val):
assert self.type=="constant", \
"Change value is only allowed in constant logstd"
assert np.isscalar(val), \
"Only scalar is currently supported"
self.log_std[:] = val
def forward(self, x):
assert x.shape[-1] == self.log_std.shape[-1]
shape = list(x.shape)
for i in range(0, len(shape)-1):
shape[i] = 1
log_std = torch.reshape(self.log_std, shape)
shape = list(x.shape)
shape[-1] = 1
log_std = log_std.repeat(shape)
out = torch.cat([x, log_std], axis=-1)
return out
class Hardmax(nn.Module):
def __init__(self, num_classes):
super().__init__()
self.num_classes = num_classes
def forward(self, x):
idx = torch.argmax(x, dim=1)
# print(x.shape)
# print(idx, self.num_classes)
y = F.one_hot(idx, num_classes=self.num_classes)
# print(y)
return y
def get_initializer(info):
if info['name'] == "normc":
return normc_initializer(info['std'])
elif info['name'] == 'xavier_normal':
def initializer(tensor):
return nn.init.xavier_normal_(tensor, gain=info['gain'])
return initializer
elif info['name'] == 'xavier_uniform':
def initializer(tensor):
return nn.init.xavier_uniform_(tensor, gain=info['gain'])
return initializer
else:
raise NotImplementedError
class FC(nn.Module):
'''
A network with fully connected layers.
'''
def __init__(self, size_in, size_out, layers, append_log_std=False,
log_std_type='constant', sample_std=1.0):
super().__init__()
nn_layers = []
prev_layer_size = size_in
for l in layers:
layer_type = l['type']
if layer_type == 'fc':
assert isinstance(l['hidden_size'] , int) or l['hidden_size'] =='output'
hidden_size = l['hidden_size'] if l['hidden_size'] != 'output' else size_out
layer = SlimFC(
in_size=prev_layer_size,
out_size=hidden_size,
initializer=get_initializer(l['init_weight']),
activation_fn=get_activation_fn(l['activation'])
)
prev_layer_size = hidden_size
elif layer_type in ['bn', 'batch_norm']:
layer = nn.BatchNorm1d(prev_layer_size)
elif layer_type in ['sm', 'softmax']:
layer = nn.Softmax(dim=1)
elif layer_type in ['hm', 'hardmax']:
layer = Hardmax(num_classes=prev_layer_size)
else:
raise NotImplementedError(
"Unknown Layer Type:", layer_type)
nn_layers.append(layer)
if append_log_std:
nn_layers.append(AppendLogStd(
type=log_std_type,
init_val=np.log(sample_std),
dim=size_out))
self._model = nn.Sequential(*nn_layers)
def forward(self, x):
return self._model(x)
def save_weights(self, file):
torch.save(self.state_dict(), file)
def load_weights(self, file):
self.load_state_dict(torch.load(file))
self.eval()
'''
A policy that generates action and value with FCNN
'''
DEFAULT_CONFIG = {
"log_std_type": "constant",
"sample_std": 1.0,
"interaction_out_channel":3,
"interaction_fc_out_shape":128,
"interaction_net_type":"conv",
"interaction_layers":[
{"type": "conv","channel_out":10,"kernel":5,"stride":2,"padding":2,"activation": "relu", "init_weight": {"name": "normc", "std": 1.0}},
{"type": "mp", "kernel":3,"stride":1,"padding":0},
{"type": "conv","channel_out":"output","kernel":3,"stride":1,"padding":1,"activation": "relu", "init_weight": {"name": "normc", "std": 1.0}},
],
"interaction_fc_layers":[
{"type": "fc", "hidden_size": "out", "activation": "relu", "init_weight": {"name": "normc", "std": 1.0}},
],
"policy_fn_layers": [
{"type": "fc", "hidden_size": 256, "activation": "relu", "init_weight": {"name": "normc", "std": 1.0}},
{"type": "fc", "hidden_size": 256, "activation": "relu", "init_weight": {"name": "normc", "std": 1.0}},
{"type": "fc", "hidden_size": "output", "activation": "linear", "init_weight": {"name": "normc", "std": 0.01}},
],
"log_std_fn_hiddens": [64, 64],
"log_std_fn_activations": ["relu", "relu", "linear"],
"log_std_fn_init_weights": [1.0, 1.0, 0.01],
"log_std_fn_base": 0.0,
"value_fn_layers": [
{"type": "fc", "hidden_size": 256, "activation": "relu", "init_weight": {"name": "normc", "std": 1.0}},
{"type": "fc", "hidden_size": 256, "activation": "relu", "init_weight": {"name": "normc", "std": 1.0}},
{"type": "fc", "hidden_size": "output", "activation": "linear", "init_weight": {"name": "normc", "std": 0.01}},
],
"interaction_obs_dim" : None,
"interaction_obs_num" : None,
"interaction_feature_dim": None,
}
"""Generic fully connected network."""
def __init__(self, obs_space, action_space, num_outputs, model_config,
name, **model_kwargs):
TorchModelV2.__init__(self, obs_space, action_space, num_outputs,
model_config, name)
nn.Module.__init__(self)
''' Load and check configuarations '''
custom_model_config = InteractionPolicy.DEFAULT_CONFIG.copy()
custom_model_config_by_user = model_config.get("custom_model_config")
if custom_model_config_by_user:
custom_model_config.update(custom_model_config_by_user)
'''
constant
log_std will not change during the training
state_independent
log_std will be learned during the training
but it does not depend on the state of the agent
state_dependent:
log_std will be learned during the training
and it depens on the state of the agent
'''
log_std_type = custom_model_config.get("log_std_type")
assert log_std_type in \
["constant", "state_independent", "state_dependent"]
sample_std = custom_model_config.get("sample_std")
assert np.array(sample_std).all() > 0.0, \
"The value shoulde be positive"
assert num_outputs % 2 == 0, (
"num_outputs must be divisible by two", num_outputs)
num_outputs = num_outputs//2
append_log_std = (log_std_type != "state_dependent")
policy_fn_layers = custom_model_config.get("policy_fn_layers")
value_fn_layers = custom_model_config.get("value_fn_layers")
interaction_layers = custom_model_config.get("interaction_layers")
interaction_out_channel = custom_model_config.get("interaction_out_channel")
interaction_fc_out_shape = custom_model_config.get("interaction_fc_out_shape")
interaction_fc_layers = custom_model_config.get("interaction_fc_layers")
self.interaction_net_type = custom_model_config.get("interaction_net_type")
self._interaction_obs_dim = custom_model_config.get("interaction_obs_dim")
self._interaction_obs_num = custom_model_config.get("interaction_obs_num")
self._interaction_feature_dim = custom_model_config.get("interaction_feature_dim")
self._sparse_interaction = custom_model_config.get("sparse_interaction")
dim_state = int(np.product(obs_space.shape))
self._dim_fc = dim_state - self._interaction_obs_dim*self._interaction_obs_num
print("Interaction Network Dimension: \nFC Input: %d, \nInteraction Input Dim: %d \nInteraction Input Num %d"%(self._dim_fc,self._interaction_obs_dim,self._interaction_obs_num))
if self.interaction_net_type=="conv":
def compute_conv_out_flat_dim(dim_in,layers):
new_dim = dim_in
for l in layers:
if l['type']=='conv' or l['type']=='mp':
k = l['kernel']
s = l['stride']
p = l['padding']
new_dim = floor((new_dim-k+2*p)/s)+1
else:
continue
return new_dim*new_dim*interaction_out_channel
def conv2d_fc_fn(params):
out_shape = compute_conv_out_flat_dim(self._interaction_feature_dim[0],params['layers'])
conv_fn = Conv2D(**params)
l = interaction_fc_layers[0]
fc_fn = SlimFC(
in_size=out_shape,
out_size=interaction_fc_out_shape,
initializer=get_initializer(l['init_weight']),
activation_fn=get_activation_fn(l['activation'])
)
out_fn = nn.Sequential(conv_fn,fc_fn)
return out_fn
conv_params = {
"channel_in":3,
"channel_out":interaction_out_channel,
"layers":interaction_layers,
}
self._pos_interaction_net = conv2d_fc_fn(conv_params)
self._vel_interaction_net = conv2d_fc_fn(conv_params)
self._pos_interaction_net_vf = conv2d_fc_fn(conv_params)
self._vel_interaction_net_vf = conv2d_fc_fn(conv_params)
downstream_in_size = self._dim_fc+self._interaction_obs_num*interaction_fc_out_shape*2 + self._interaction_obs_num *self._interaction_feature_dim[0]*self._interaction_feature_dim[1]
elif self.interaction_net_type == "gcn":
num_nodes_per_batch = self._interaction_feature_dim[0]
gnn_params = {
"channel_in":6,
"channel_out":interaction_out_channel,
"out_dim": interaction_fc_out_shape,
"num_nodes_per_batch":num_nodes_per_batch,
"gcn_layers" : interaction_layers,
"fc_layers" : interaction_fc_layers
}
self._interaction_net = GCN(**gnn_params)
self._interaction_net_vf = GCN(**gnn_params)
downstream_in_size = self._dim_fc+self._interaction_obs_num*interaction_fc_out_shape
print("Downstream Size Total: %d \nFC dim: %d, \nInteraction Output: %d"%(downstream_in_size,self._dim_fc,self._interaction_obs_num*interaction_fc_out_shape*2))
elif self.interaction_net_type == "gat":
num_nodes_per_batch = self._interaction_feature_dim[0]
gnn_params = {
"channel_in":self._interaction_feature_dim[1],
"channel_out":interaction_out_channel,
"edge_dim":self._interaction_feature_dim[1],
"out_dim": interaction_fc_out_shape,
"num_nodes_per_batch":num_nodes_per_batch,
"gcn_layers" : interaction_layers,
"fc_layers" : interaction_fc_layers
}
self._interaction_net = GAT(**gnn_params)
self._interaction_net_vf = GAT(**gnn_params)
downstream_in_size = self._dim_fc+self._interaction_obs_num*interaction_fc_out_shape
print("Downstream Size Total: %d \nFC dim: %d, \nInteraction Output: %d"%(downstream_in_size,self._dim_fc,self._interaction_obs_num*interaction_fc_out_shape*2))
elif self.interaction_net_type == "fc":
downstream_in_size = dim_state
''' Construct the policy function '''
param = {
"size_in": downstream_in_size,
"size_out": num_outputs,
"layers": policy_fn_layers,
"append_log_std": append_log_std,
"log_std_type": log_std_type,
"sample_std": sample_std
}
self._policy_fn = FC(**param)
''' Construct the value function '''
param = {
"size_in": downstream_in_size,
"size_out": 1,
"layers": value_fn_layers,
"append_log_std": False
}
self._value_fn = FC(**param)
''' Keep the latest output of the value function '''
self._cur_value = None
@override(TorchModelV2)
def forward(self, input_dict, state, seq_lens):
obs = input_dict["obs_flat"].float()
obs = obs.reshape(obs.shape[0], -1)
if self.interaction_net_type=="conv":
assert self._sparse_interaction == False ## Don't want to use the sparse state representation
pf_outs = []
vf_outs = []
for i in range(self._interaction_obs_num):
seg_length = self._interaction_obs_dim
seg = obs[:,self._dim_fc+i*seg_length:self._dim_fc+(i+1)*seg_length]
interaction_point_dim = self._interaction_feature_dim[0]*self._interaction_feature_dim[1]
seg_interaction_points = seg[:,:interaction_point_dim]
seg = seg[:, interaction_point_dim:]
seg = seg.reshape(seg.shape[0],self._interaction_feature_dim[0],self._interaction_feature_dim[0],self._interaction_feature_dim[1])
seg = torch.moveaxis(seg,-1,1)
seg_pos_info = seg[:,:3,:,:]
seg_vel_info = seg[:,3:,:,:]
pos_out_pf = self._pos_interaction_net(seg_pos_info)
vel_out_pf = self._vel_interaction_net(seg_vel_info)
pos_out_vf = self._pos_interaction_net_vf(seg_pos_info)
vel_out_vf = self._vel_interaction_net_vf(seg_vel_info)
pf_outs.append(seg_interaction_points)
pf_outs.append(pos_out_pf)
pf_outs.append(vel_out_pf)
vf_outs.append(seg_interaction_points)
vf_outs.append(pos_out_vf)
vf_outs.append(vel_out_vf)
pf_outs.append(obs[:,:self._dim_fc])
vf_outs.append(obs[:,:self._dim_fc])
pf_obs = torch.cat(pf_outs, axis=-1)
vf_obs = torch.cat(vf_outs, axis=-1)
elif self.interaction_net_type == "gat":
assert self._sparse_interaction == True ## Must use the sparse state representation
pf_outs = []
vf_outs = []
max_edges = self._interaction_feature_dim[0] * self._interaction_feature_dim[0]
for i in range(self._interaction_obs_num):
seg_length = self._interaction_obs_dim
seg = obs[:,self._dim_fc+i*seg_length:self._dim_fc+(i+1)*seg_length]
interaction_point_dim = self._interaction_feature_dim[0]*self._interaction_feature_dim[1]
num_edges = seg[:,interaction_point_dim].to(torch.long)
total_num_edges = self._interaction_feature_dim[0]*self._interaction_feature_dim[0]
seg_interaction_points = seg[:,:interaction_point_dim]
seg_interaction_points = seg_interaction_points.reshape(seg_interaction_points.shape[0],self._interaction_feature_dim[0],self._interaction_feature_dim[1])
seg_interaction_edges_connectivity = seg[:,interaction_point_dim+1:interaction_point_dim+1+total_num_edges*2]
seg_interaction_edges_connectivity = seg_interaction_edges_connectivity.reshape(seg_interaction_edges_connectivity.shape[0],2,total_num_edges)
seg_interaction_edges_connectivity = seg_interaction_edges_connectivity[:,:,:max_edges]
seg_interaction_edges_connectivity = seg_interaction_edges_connectivity.to(torch.long)
seg_interaction_edges_features = seg[:,interaction_point_dim+1+total_num_edges*2:]
seg_interaction_edges_features = seg_interaction_edges_features.reshape(seg_interaction_edges_features.shape[0],-1,self._interaction_feature_dim[1])
seg_interaction_edges_features = seg_interaction_edges_features[:,:max_edges,:]
batch_edge_index = Batch.from_data_list([Data(x=seg_interaction_points[j],edge_attr=seg_interaction_edges_features[j,:num_edges[j],:],edge_index=seg_interaction_edges_connectivity[j,:,:num_edges[j]],num_nodes=self._interaction_feature_dim[0]) for j in range(seg_interaction_edges_features.shape[0])])
pf_out = self._interaction_net(batch_edge_index.x,batch_edge_index.edge_index,batch_edge_index.edge_attr)
vf_out = self._interaction_net_vf(batch_edge_index.x,batch_edge_index.edge_index,batch_edge_index.edge_attr)
pf_outs.append(pf_out)
vf_outs.append(vf_out)
pf_outs.append(obs[:,:self._dim_fc])
vf_outs.append(obs[:,:self._dim_fc])
pf_obs = torch.cat(pf_outs, axis=-1)
vf_obs = torch.cat(vf_outs, axis=-1)
elif self.interaction_net_type=="gcn":
assert self._sparse_interaction == True ## Must use the sparse state representation
pf_outs = []
vf_outs = []
max_edges = self._interaction_feature_dim[0] * self._interaction_feature_dim[0]
for i in range(self._interaction_obs_num):
seg_length = self._interaction_obs_dim
seg = obs[:,self._dim_fc+i*seg_length:self._dim_fc+(i+1)*seg_length]
interaction_point_dim = self._interaction_feature_dim[0]*self._interaction_feature_dim[1]
num_edges = seg[:,interaction_point_dim].to(torch.long)
total_num_edges = self._interaction_feature_dim[0]*self._interaction_feature_dim[0]
seg_interaction_points = seg[:,:interaction_point_dim]
seg_interaction_points = seg_interaction_points.reshape(seg_interaction_points.shape[0],self._interaction_feature_dim[0],self._interaction_feature_dim[1])
seg_interaction_edges_connectivity = seg[:,interaction_point_dim+1:interaction_point_dim+1+total_num_edges*2]
seg_interaction_edges_connectivity = seg_interaction_edges_connectivity.reshape(seg_interaction_edges_connectivity.shape[0],2,total_num_edges)
seg_interaction_edges_connectivity = seg_interaction_edges_connectivity[:,:,:max_edges]
seg_interaction_edges_connectivity = seg_interaction_edges_connectivity.to(torch.long)
seg_interaction_edges_features = seg[:,interaction_point_dim+1+total_num_edges*2:]
seg_interaction_edges_features = seg_interaction_edges_features.reshape(seg_interaction_edges_features.shape[0],-1,self._interaction_feature_dim[1])
seg_interaction_edges_features = seg_interaction_edges_features[:,:max_edges,:]
batch_edge_index = Batch.from_data_list([Data(x=seg_interaction_points[j],edge_attr=seg_interaction_edges_features[j,:num_edges[j],:],edge_index=seg_interaction_edges_connectivity[j,:,:num_edges[j]],num_nodes=self._interaction_feature_dim[0]) for j in range(seg_interaction_edges_features.shape[0])])
pf_out = self._interaction_net(batch_edge_index.x,batch_edge_index.edge_index)
vf_out = self._interaction_net_vf(batch_edge_index.x,batch_edge_index.edge_index)
pf_outs.append(pf_out)
vf_outs.append(vf_out)
pf_outs.append(obs[:,:self._dim_fc])
vf_outs.append(obs[:,:self._dim_fc])
pf_obs = torch.cat(pf_outs, axis=-1)
vf_obs = torch.cat(vf_outs, axis=-1)
else:
assert self._sparse_interaction == False ## Don't want to use the sparse state representation
pf_obs = obs
vf_obs = obs
logits = self._policy_fn(pf_obs)
self._cur_value = self._value_fn(vf_obs).squeeze(1)
return logits, state
@override(TorchModelV2)
def value_function(self):
assert self._cur_value is not None, "must call forward() first"
return self._cur_value
def save_policy_weights(self, file):
torch.save(self._policy_fn.state_dict(), file)
# print(self._policy_fn.state_dict())
# print(self._value_fn.state_dict())
def load_policy_weights(self, file):
self._policy_fn.load_state_dict(torch.load(file))
self._policy_fn.eval()
def get_attention_weight(self):
return self._interaction_net._attention_weight
class FullyConnectedPolicy(TorchModelV2, nn.Module):
'''
A policy that generates action and value with FCNN
'''
DEFAULT_CONFIG = {
"log_std_type": "constant",
"sample_std": 1.0,
"policy_fn_type": "mlp",
"policy_fn_layers": [
{"type": "fc", "hidden_size": 256, "activation": "relu", "init_weight": {"name": "normc", "std": 1.0}},
{"type": "fc", "hidden_size": 256, "activation": "relu", "init_weight": {"name": "normc", "std": 1.0}},
{"type": "fc", "hidden_size": "output", "activation": "linear", "init_weight": {"name": "normc", "std": 0.01}},
],
"log_std_fn_hiddens": [64, 64],
"log_std_fn_activations": ["relu", "relu", "linear"],
"log_std_fn_init_weights": [1.0, 1.0, 0.01],
"log_std_fn_base": 0.0,
"value_fn_layers": [
{"type": "fc", "hidden_size": 256, "activation": "relu", "init_weight": {"name": "normc", "std": 1.0}},
{"type": "fc", "hidden_size": 256, "activation": "relu", "init_weight": {"name": "normc", "std": 1.0}},
{"type": "fc", "hidden_size": "output", "activation": "linear", "init_weight": {"name": "normc", "std": 0.01}},
],
}
"""Generic fully connected network."""
def __init__(self, obs_space, action_space, num_outputs, model_config,
name, **model_kwargs):
TorchModelV2.__init__(self, obs_space, action_space, num_outputs,
model_config, name)
nn.Module.__init__(self)
''' Load and check configuarations '''
custom_model_config = FullyConnectedPolicy.DEFAULT_CONFIG.copy()
custom_model_config_by_user = model_config.get("custom_model_config")
if custom_model_config_by_user:
custom_model_config.update(custom_model_config_by_user)
'''
constant
log_std will not change during the training
state_independent
log_std will be learned during the training
but it does not depend on the state of the agent
state_dependent:
log_std will be learned during the training
and it depens on the state of the agent
'''
log_std_type = custom_model_config.get("log_std_type")
assert log_std_type in \
["constant", "state_independent", "state_dependent"]
sample_std = custom_model_config.get("sample_std")
assert np.array(sample_std).all() > 0.0, \
"The value shoulde be positive"
assert num_outputs % 2 == 0, (
"num_outputs must be divisible by two", num_outputs)
num_outputs = num_outputs//2
append_log_std = (log_std_type != "state_dependent")
policy_fn_type = custom_model_config.get("policy_fn_type")
policy_fn_layers = custom_model_config.get("policy_fn_layers")
value_fn_layers = custom_model_config.get("value_fn_layers")
dim_state = int(np.product(obs_space.shape))
''' Construct the policy function '''
if policy_fn_type == "mlp":
param = {
"size_in": dim_state,
"size_out": num_outputs,
"layers": policy_fn_layers,
"append_log_std": append_log_std,
"log_std_type": log_std_type,
"sample_std": sample_std
}
self._policy_fn = FC(**param)
else:
raise NotImplementedError
''' Construct the value function '''
param = {
"size_in": dim_state,
"size_out": 1,
"layers": value_fn_layers,
"append_log_std": False
}
self._value_fn = FC(**param)
''' Keep the latest output of the value function '''
self._cur_value = None
''' Construct log_std function if necessary '''
self._log_std_fn = None
if log_std_type == "state_dependent":
log_std_fn_hiddens = \
custom_model_config.get("log_std_fn_hiddens")
log_std_fn_activations = \
custom_model_config.get("log_std_fn_activations")
log_std_fn_init_weights = \
custom_model_config.get("log_std_fn_init_weights")
self._log_std_fn_base = np.log(sample_std)
assert len(log_std_fn_hiddens) > 0
assert len(log_std_fn_hiddens)+1 == len(log_std_fn_activations)
assert len(log_std_fn_hiddens)+1 == len(log_std_fn_init_weights)
param_log_std_fn = {
"size_in": dim_state,
"size_out": num_outputs,
"hiddens": log_std_fn_hiddens,
"activations": log_std_fn_activations,
"init_weights": log_std_fn_init_weights,
"append_log_std": False,
}
self._log_std_fn = net_cls(**param_log_std_fn)
@override(TorchModelV2)
def forward(self, input_dict, state, seq_lens):
obs = input_dict["obs_flat"].float()
obs = obs.reshape(obs.shape[0], -1)
logits = self._policy_fn(obs)
self._cur_value = self._value_fn(obs).squeeze(1)
if self._log_std_fn is not None:
log_std = self._log_std_fn_base + self._log_std_fn(obs)
logits = torch.cat([logits, log_std], axis=-1)
return logits, state
@override(TorchModelV2)
def value_function(self):
assert self._cur_value is not None, "must call forward() first"
return self._cur_value
def save_policy_weights(self, file):
torch.save(self._policy_fn.state_dict(), file)
# print(self._policy_fn.state_dict())
# print(self._value_fn.state_dict())
def load_policy_weights(self, file):
self._policy_fn.load_state_dict(torch.load(file))
self._policy_fn.eval()
class MOEPolicyBase(TorchModelV2, nn.Module):
'''
A base policy with Mixture-of-Experts structure
'''
DEFAULT_CONFIG = {
"log_std_type": "constant",
"sample_std": 1.0,
"expert_size_in": None,
"expert_hiddens": [
[128, 128],
[128, 128],
[128, 128],
],
"expert_activations": [
["relu", "relu", "linear"],
["relu", "relu", "linear"],
["relu", "relu", "linear"],
],
"expert_init_weights": [
[1.0, 1.0, 0.01],
[1.0, 1.0, 0.01],
[1.0, 1.0, 0.01],
],
"expert_log_std_types": [
'constant',
'constant',
'constant',
],
"expert_sample_stds": [
0.2,
0.2,
0.2,
],
"expert_checkpoints": [
None,
None,
None,
],
"expert_learnable": [
True,
True,
True,
],
"use_helper": False,
"helper_hiddens": [
[64, 64],
[64, 64],
[64, 64],
],
"helper_activations": [
["tanh", "tanh", "tanh"],
["tanh", "tanh", "tanh"],
["tanh", "tanh", "tanh"],
],
"helper_init_weights": [
[1.0, 1.0, 0.01],
[1.0, 1.0, 0.01],
[1.0, 1.0, 0.01],
],
"helper_checkpoints": [
None,
None,
None,
],
"helper_learnable": [
True,
True,
True,
],
"helper_range": 1.0,
"gate_fn_type": "mlp",
"gate_fn_hiddens": [128, 128],
"gate_fn_activations": ["relu", "relu", "linear"],
"gate_fn_init_weights": [1.0, 1.0, 0.01],
"gate_fn_learnable": True,
"gate_fn_autoreg": False,
"gate_fn_autoreg_alpha": 0.95,
"value_fn_hiddens": [128, 128],
"value_fn_activations": ["relu", "relu", "linear"],
"value_fn_init_weights": [1.0, 1.0, 0.01],
}
def __init__(self, obs_space, action_space, num_outputs, model_config,
name, **model_kwargs):
TorchModelV2.__init__(self, obs_space, action_space, num_outputs,
model_config, name)
nn.Module.__init__(self)
''' Load and check configuarations '''
assert num_outputs % 2 == 0, (
"num_outputs must be divisible by two", num_outputs)
dim_action_mean = num_outputs // 2
dim_action_std = num_outputs // 2
custom_model_config = MOEPolicyBase.DEFAULT_CONFIG.copy()
custom_model_config_by_user = model_config.get("custom_model_config")
if custom_model_config_by_user:
custom_model_config.update(custom_model_config_by_user)
self._model_config = custom_model_config
expert_size_in = self._model_config.get("expert_size_in")
expert_hiddens = self._model_config.get("expert_hiddens")
expert_activations = self._model_config.get("expert_activations")
expert_init_weights = self._model_config.get("expert_init_weights")
expert_log_std_types = self._model_config.get("expert_log_std_types")
expert_sample_stds = self._model_config.get("expert_sample_stds")
expert_checkpoints = self._model_config.get("expert_checkpoints")
expert_learnable = self._model_config.get("expert_learnable")
use_helper = self._model_config.get("use_helper")
if use_helper:
helper_hiddens = self._model_config.get("helper_hiddens")
helper_activations = self._model_config.get("helper_activations")
helper_init_weights = self._model_config.get("helper_init_weights")
helper_checkpoints = self._model_config.get("helper_checkpoints")
helper_learnable = self._model_config.get("helper_learnable")
self._helper_range = self._model_config.get("helper_range")
assert len(helper_hiddens) == len(expert_hiddens)
assert len(helper_activations) == len(expert_activations)
assert len(helper_init_weights) == len(expert_init_weights)
assert len(helper_checkpoints) == len(expert_checkpoints)
assert len(helper_learnable) == len(expert_learnable)
gate_fn_type = self._model_config.get("gate_fn_type")
gate_fn_hiddens = self._model_config.get("gate_fn_hiddens")
gate_fn_activations = self._model_config.get("gate_fn_activations")
gate_fn_init_weights = self._model_config.get("gate_fn_init_weights")
gate_fn_autoreg = self._model_config.get("gate_fn_autoreg")
gate_fn_autoreg_alpha = self._model_config.get("gate_fn_autoreg_alpha")
value_fn_hiddens = self._model_config.get("value_fn_hiddens")
value_fn_activations = self._model_config.get("value_fn_activations")
value_fn_init_weights = self._model_config.get("value_fn_init_weights")
project_dir = self._model_config.get('project_dir')
num_experts = len(expert_hiddens)
dim_state = int(np.product(obs_space.shape))
dim_state_expert = dim_state if expert_size_in is None else expert_size_in
''' Construct the gate function '''
self._gate_fn_type = gate_fn_type
self._gate_fn_autoreg = gate_fn_autoreg
self._gate_fn_autoreg_alpha = gate_fn_autoreg_alpha
if gate_fn_autoreg:
assert gate_fn_type == "mlp"
assert gate_fn_autoreg_alpha > 0.0
if gate_fn_type == "mlp":
self._gate_fn = FC(
size_in=dim_state,
size_out=num_experts,
hiddens=gate_fn_hiddens,
activations=gate_fn_activations,
init_weights=gate_fn_init_weights,
append_log_std=False)
elif gate_fn_type == "lstm":
self._gate_fn_lstm_hidden_size = gate_fn_hiddens[0]
self._gate_fn_lstm_num_layers = len(gate_fn_hiddens)
self._gate_fn_lstm = nn.LSTM(
input_size=dim_state,
hidden_size=self._gate_fn_lstm_hidden_size,
num_layers=self._gate_fn_lstm_num_layers,
batch_first=True,
)
self._gate_fn = nn.Linear(
in_features=self._gate_fn_lstm_hidden_size,
out_features=num_experts
)
else:
raise NotImplementedError
''' Construct experts '''
experts = []
helpers = []
for i in range(num_experts):
append_log_std = False if expert_log_std_types[i]=='none' else True
sample_std = expert_sample_stds[i] if append_log_std else None
''' Expert definition '''
expert = FC(
size_in=dim_state_expert,