-
Notifications
You must be signed in to change notification settings - Fork 3
/
auxillary_policy.py
718 lines (636 loc) · 29.4 KB
/
auxillary_policy.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
"""
Setup for agent training code w/ auxillary loss.
"""
from typing import Dict, List, Tuple, Type, Union, Optional, Any
import gym
import torch
from torch import nn
from stable_baselines3.common.type_aliases import TensorDict
from stable_baselines3.common.utils import get_device
from stable_baselines3.common.torch_layers import BaseFeaturesExtractor
from sb3_contrib.common.recurrent.policies import RecurrentActorCriticPolicy
from stable_baselines3.common.type_aliases import Schedule
from sb3_contrib.common.recurrent.type_aliases import RNNStates
from stable_baselines3.common.distributions import Distribution
class AutoEncoder(nn.Module):
def __init__(self):
super(AutoEncoder, self).__init__()
self.cnn = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=3, stride=1, padding=0),
nn.ReLU(),
nn.Flatten()
)
self.latent = nn.Linear(64, 16)
self.fc_recover = nn.Linear(16, 16)
self.act_fn=nn.ReLU()
self.fc_recover2 = nn.Linear(16,16)
def forward(self, x):
x=x.reshape((-1,1,4,4))
x=self.act_fn(self.latent(self.cnn(x)))
recovered=self.fc_recover2(self.act_fn(self.fc_recover(x)))
return recovered
class LanguageEncoder(nn.Module):
def __init__(self):
super(LanguageEncoder, self).__init__()
self.cnn = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=3, stride=1, padding=0),
nn.ReLU(),
nn.Flatten()
)
self.latent = nn.Linear(64, 16)
self.fc_language = nn.Linear(16, 768)
self.fc_language2= nn.Linear(768,768)
self.act_fn=nn.ReLU()
def forward(self, x):
x=x.reshape((-1,1,4,4))
x=self.act_fn(self.latent(self.cnn(x)))
language=self.fc_language2(self.act_fn(self.fc_language(x)))
return language
class ProgramEncoder(nn.Module):
def __init__(self):
super(ProgramEncoder, self).__init__()
self.cnn = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=3, stride=1, padding=0),
nn.ReLU(),
nn.Flatten()
)
self.latent = nn.Linear(64, 16)
self.fc_program = nn.Linear(16, 64)
self.fc_program2= nn.Linear(64,64)
self.act_fn=nn.ReLU()
def forward(self, x):
x=x.reshape((-1,1,4,4))
x=self.act_fn(self.latent(self.cnn(x)))
program=self.fc_program2(self.act_fn(self.fc_program(x)))
return program
class DualFeatureExtractor(BaseFeaturesExtractor):
def __init__(self, observation_space: gym.spaces.Box):
super(DualFeatureExtractor, self).__init__(observation_space, features_dim=33)
self.visual_encoder=LanguageEncoder()
def forward(self, observations: torch.Tensor) -> torch.Tensor:
observation_board=observations[:,768:]
visual_input=torch.reshape(observation_board[:,:16],(-1,1,4,4))
prev_output=observation_board[:,16:]
visual_output=self.visual_encoder.act_fn(self.visual_encoder.latent(self.visual_encoder.cnn(visual_input)))
total_output=torch.cat([visual_output,prev_output],dim=1)
predicted_language=self.visual_encoder.fc_language2(self.visual_encoder.act_fn(self.visual_encoder.fc_language(visual_output)))
return total_output, predicted_language
class ProgramDualFeatureExtractor(BaseFeaturesExtractor):
def __init__(self, observation_space: gym.spaces.Box):
super(ProgramDualFeatureExtractor, self).__init__(observation_space, features_dim=33)
self.visual_encoder=ProgramEncoder()
def forward(self, observations: torch.Tensor) -> torch.Tensor:
observation_board=observations[:,64:]
visual_input=torch.reshape(observation_board[:,:16],(-1,1,4,4))
prev_output=observation_board[:,16:]
visual_output=self.visual_encoder.act_fn(self.visual_encoder.latent(self.visual_encoder.cnn(visual_input)))
total_output=torch.cat([visual_output,prev_output],dim=1)
predicted_program=self.visual_encoder.fc_program2(self.visual_encoder.act_fn(self.visual_encoder.fc_program(visual_output)))
return total_output, predicted_program
class AutoDualFeatureExtractor(BaseFeaturesExtractor):
def __init__(self, observation_space: gym.spaces.Box):
super(AutoDualFeatureExtractor, self).__init__(observation_space, features_dim=33)
self.visual_encoder=AutoEncoder()
def forward(self, observations: torch.Tensor) -> torch.Tensor:
observation_board=observations[:,16:]
visual_input=torch.reshape(observation_board[:,:16],(-1,1,4,4))
prev_output=observation_board[:,16:]
visual_output=self.visual_encoder.act_fn(self.visual_encoder.latent(self.visual_encoder.cnn(visual_input)))
total_output=torch.cat([visual_output,prev_output],dim=1)
predicted_language=self.visual_encoder.fc_recover2(self.visual_encoder.act_fn(self.visual_encoder.fc_recover(visual_output)))
#print(predicted_language.shape)
return total_output, predicted_language
class DualFeatureRecurrentActorCriticPolicy(RecurrentActorCriticPolicy):
"""
MultiInputActorClass policy class for actor-critic algorithms (has both policy and value prediction).
Used by A2C, PPO and the likes.
:param observation_space: Observation space
:param action_space: Action space
:param lr_schedule: Learning rate schedule (could be constant)
:param net_arch: The specification of the policy and value networks.
:param activation_fn: Activation function
:param ortho_init: Whether to use or not orthogonal initialization
:param use_sde: Whether to use State Dependent Exploration or not
:param log_std_init: Initial value for the log standard deviation
:param full_std: Whether to use (n_features x n_actions) parameters
for the std instead of only (n_features,) when using gSDE
:param sde_net_arch: Network architecture for extracting features
when using gSDE. If None, the latent features from the policy will be used.
Pass an empty list to use the states as features.
:param use_expln: Use ``expln()`` function instead of ``exp()`` to ensure
a positive standard deviation (cf paper). It allows to keep variance
above zero and prevent it from growing too fast. In practice, ``exp()`` is usually enough.
:param squash_output: Whether to squash the output using a tanh function,
this allows to ensure boundaries when using gSDE.
:param features_extractor_class: Features extractor to use.
:param features_extractor_kwargs: Keyword arguments
to pass to the features extractor.
:param normalize_images: Whether to normalize images or not,
dividing by 255.0 (True by default)
:param optimizer_class: The optimizer to use,
``torch.optim.Adam`` by default
:param optimizer_kwargs: Additional keyword arguments,
excluding the learning rate, to pass to the optimizer
"""
def __init__(
self,
observation_space: gym.spaces.Space,
action_space: gym.spaces.Space,
lr_schedule: Schedule,
net_arch: Optional[List[Union[int, Dict[str, List[int]]]]] = None,
activation_fn: Type[nn.Module] = nn.Tanh,
ortho_init: bool = True,
use_sde: bool = False,
log_std_init: float = 0.0,
full_std: bool = True,
sde_net_arch: Optional[List[int]] = None,
use_expln: bool = False,
squash_output: bool = False,
features_extractor_class: Type[BaseFeaturesExtractor] = DualFeatureExtractor,
features_extractor_kwargs: Optional[Dict[str, Any]] = None,
normalize_images: bool = True,
optimizer_class: Type[torch.optim.Optimizer] = torch.optim.Adam,
optimizer_kwargs: Optional[Dict[str, Any]] = None,
lstm_hidden_size: int = 64,
n_lstm_layers: int = 1,
enable_critic_lstm: bool = False,
):
super().__init__(
observation_space,
action_space,
lr_schedule,
net_arch,
activation_fn,
ortho_init,
use_sde,
log_std_init,
full_std,
sde_net_arch,
use_expln,
squash_output,
features_extractor_class,
features_extractor_kwargs,
normalize_images,
optimizer_class,
optimizer_kwargs,
lstm_hidden_size,
n_lstm_layers,
enable_critic_lstm,
)
def forward(
self,
obs: torch.Tensor,
lstm_states: RNNStates,
episode_starts: torch.Tensor,
deterministic: bool = False,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, RNNStates]:
"""
Forward pass in all the networks (actor and critic)
:param obs: Observation
:param deterministic: Whether to sample or use deterministic actions
:return: action, value and log probability of the action
"""
# Preprocess the observation if needed
features,features_lang = self.extract_features(obs)
# latent_pi, latent_vf = self.mlp_extractor(features)
latent_pi, lstm_states_pi = self._process_sequence(features, lstm_states.pi, episode_starts, self.lstm_actor)
if self.lstm_critic is not None:
latent_vf, lstm_states_vf = self._process_sequence(features, lstm_states.vf, episode_starts, self.lstm_critic)
elif self.shared_lstm:
# Re-use LSTM features but do not backpropagate
latent_vf = latent_pi.detach()
lstm_states_vf = (lstm_states_pi[0].detach(), lstm_states_pi[1].detach())
else:
latent_vf = self.critic(features)
lstm_states_vf = lstm_states_pi
latent_pi = self.mlp_extractor.forward_actor(latent_pi)
latent_vf = self.mlp_extractor.forward_critic(latent_vf)
# Evaluate the values for the given observations
values = self.value_net(latent_vf)
distribution = self._get_action_dist_from_latent(latent_pi)
actions = distribution.get_actions(deterministic=deterministic)
log_prob = distribution.log_prob(actions)
return actions, values, log_prob, RNNStates(lstm_states_pi, lstm_states_vf)
def get_distribution(
self,
obs: torch.Tensor,
lstm_states: Tuple[torch.Tensor, torch.Tensor],
episode_starts: torch.Tensor,
) -> Tuple[Distribution, Tuple[torch.Tensor, ...]]:
"""
Get the current policy distribution given the observations.
:param obs:
:return: the action distribution and new hidden states.
"""
features,features_lang = self.extract_features(obs)
latent_pi, lstm_states = self._process_sequence(features, lstm_states, episode_starts, self.lstm_actor)
latent_pi = self.mlp_extractor.forward_actor(latent_pi)
return self._get_action_dist_from_latent(latent_pi), lstm_states
def predict_values(
self,
obs: torch.Tensor,
lstm_states: Tuple[torch.Tensor, torch.Tensor],
episode_starts: torch.Tensor,
) -> torch.Tensor:
"""
Get the estimated values according to the current policy given the observations.
:param obs:
:return: the estimated values.
"""
features,features_lang = self.extract_features(obs)
if self.lstm_critic is not None:
latent_vf, lstm_states_vf = self._process_sequence(features, lstm_states, episode_starts, self.lstm_critic)
elif self.shared_lstm:
# Use LSTM from the actor
latent_pi, _ = self._process_sequence(features, lstm_states, episode_starts, self.lstm_actor)
latent_vf = latent_pi.detach()
else:
latent_vf = self.critic(features)
latent_vf = self.mlp_extractor.forward_critic(latent_vf)
return self.value_net(latent_vf)
def evaluate_actions(
self,
obs: torch.tensor,
actions: torch.Tensor,
lstm_states: RNNStates,
episode_starts: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""
Evaluate actions according to the current policy,
given the observations.
:param obs:
:param actions:
:return: estimated value, log likelihood of taking those actions
and entropy of the action distribution.
"""
# Preprocess the observation if needed
features,features_lang = self.extract_features(obs)
latent_pi, _ = self._process_sequence(features, lstm_states.pi, episode_starts, self.lstm_actor)
if self.lstm_critic is not None:
latent_vf, _ = self._process_sequence(features, lstm_states.vf, episode_starts, self.lstm_critic)
elif self.shared_lstm:
latent_vf = latent_pi.detach()
else:
latent_vf = self.critic(features)
latent_pi = self.mlp_extractor.forward_actor(latent_pi)
latent_vf = self.mlp_extractor.forward_critic(latent_vf)
distribution = self._get_action_dist_from_latent(latent_pi)
log_prob = distribution.log_prob(actions)
values = self.value_net(latent_vf)
return values, log_prob, distribution.entropy(), features_lang
class ProgramDualFeatureRecurrentActorCriticPolicy(RecurrentActorCriticPolicy):
"""
MultiInputActorClass policy class for actor-critic algorithms (has both policy and value prediction).
Used by A2C, PPO and the likes.
:param observation_space: Observation space
:param action_space: Action space
:param lr_schedule: Learning rate schedule (could be constant)
:param net_arch: The specification of the policy and value networks.
:param activation_fn: Activation function
:param ortho_init: Whether to use or not orthogonal initialization
:param use_sde: Whether to use State Dependent Exploration or not
:param log_std_init: Initial value for the log standard deviation
:param full_std: Whether to use (n_features x n_actions) parameters
for the std instead of only (n_features,) when using gSDE
:param sde_net_arch: Network architecture for extracting features
when using gSDE. If None, the latent features from the policy will be used.
Pass an empty list to use the states as features.
:param use_expln: Use ``expln()`` function instead of ``exp()`` to ensure
a positive standard deviation (cf paper). It allows to keep variance
above zero and prevent it from growing too fast. In practice, ``exp()`` is usually enough.
:param squash_output: Whether to squash the output using a tanh function,
this allows to ensure boundaries when using gSDE.
:param features_extractor_class: Features extractor to use.
:param features_extractor_kwargs: Keyword arguments
to pass to the features extractor.
:param normalize_images: Whether to normalize images or not,
dividing by 255.0 (True by default)
:param optimizer_class: The optimizer to use,
``torch.optim.Adam`` by default
:param optimizer_kwargs: Additional keyword arguments,
excluding the learning rate, to pass to the optimizer
"""
def __init__(
self,
observation_space: gym.spaces.Space,
action_space: gym.spaces.Space,
lr_schedule: Schedule,
net_arch: Optional[List[Union[int, Dict[str, List[int]]]]] = None,
activation_fn: Type[nn.Module] = nn.Tanh,
ortho_init: bool = True,
use_sde: bool = False,
log_std_init: float = 0.0,
full_std: bool = True,
sde_net_arch: Optional[List[int]] = None,
use_expln: bool = False,
squash_output: bool = False,
features_extractor_class: Type[BaseFeaturesExtractor] = ProgramDualFeatureExtractor,
features_extractor_kwargs: Optional[Dict[str, Any]] = None,
normalize_images: bool = True,
optimizer_class: Type[torch.optim.Optimizer] = torch.optim.Adam,
optimizer_kwargs: Optional[Dict[str, Any]] = None,
lstm_hidden_size: int = 64,
n_lstm_layers: int = 1,
enable_critic_lstm: bool = False,
):
super().__init__(
observation_space,
action_space,
lr_schedule,
net_arch,
activation_fn,
ortho_init,
use_sde,
log_std_init,
full_std,
sde_net_arch,
use_expln,
squash_output,
features_extractor_class,
features_extractor_kwargs,
normalize_images,
optimizer_class,
optimizer_kwargs,
lstm_hidden_size,
n_lstm_layers,
enable_critic_lstm,
)
def forward(
self,
obs: torch.Tensor,
lstm_states: RNNStates,
episode_starts: torch.Tensor,
deterministic: bool = False,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, RNNStates]:
"""
Forward pass in all the networks (actor and critic)
:param obs: Observation
:param deterministic: Whether to sample or use deterministic actions
:return: action, value and log probability of the action
"""
# Preprocess the observation if needed
features,features_lang = self.extract_features(obs)
# latent_pi, latent_vf = self.mlp_extractor(features)
latent_pi, lstm_states_pi = self._process_sequence(features, lstm_states.pi, episode_starts, self.lstm_actor)
if self.lstm_critic is not None:
latent_vf, lstm_states_vf = self._process_sequence(features, lstm_states.vf, episode_starts, self.lstm_critic)
elif self.shared_lstm:
# Re-use LSTM features but do not backpropagate
latent_vf = latent_pi.detach()
lstm_states_vf = (lstm_states_pi[0].detach(), lstm_states_pi[1].detach())
else:
latent_vf = self.critic(features)
lstm_states_vf = lstm_states_pi
latent_pi = self.mlp_extractor.forward_actor(latent_pi)
latent_vf = self.mlp_extractor.forward_critic(latent_vf)
# Evaluate the values for the given observations
values = self.value_net(latent_vf)
distribution = self._get_action_dist_from_latent(latent_pi)
actions = distribution.get_actions(deterministic=deterministic)
log_prob = distribution.log_prob(actions)
return actions, values, log_prob, RNNStates(lstm_states_pi, lstm_states_vf)
def get_distribution(
self,
obs: torch.Tensor,
lstm_states: Tuple[torch.Tensor, torch.Tensor],
episode_starts: torch.Tensor,
) -> Tuple[Distribution, Tuple[torch.Tensor, ...]]:
"""
Get the current policy distribution given the observations.
:param obs:
:return: the action distribution and new hidden states.
"""
features,features_lang = self.extract_features(obs)
latent_pi, lstm_states = self._process_sequence(features, lstm_states, episode_starts, self.lstm_actor)
latent_pi = self.mlp_extractor.forward_actor(latent_pi)
return self._get_action_dist_from_latent(latent_pi), lstm_states
def predict_values(
self,
obs: torch.Tensor,
lstm_states: Tuple[torch.Tensor, torch.Tensor],
episode_starts: torch.Tensor,
) -> torch.Tensor:
"""
Get the estimated values according to the current policy given the observations.
:param obs:
:return: the estimated values.
"""
features,features_lang = self.extract_features(obs)
if self.lstm_critic is not None:
latent_vf, lstm_states_vf = self._process_sequence(features, lstm_states, episode_starts, self.lstm_critic)
elif self.shared_lstm:
# Use LSTM from the actor
latent_pi, _ = self._process_sequence(features, lstm_states, episode_starts, self.lstm_actor)
latent_vf = latent_pi.detach()
else:
latent_vf = self.critic(features)
latent_vf = self.mlp_extractor.forward_critic(latent_vf)
return self.value_net(latent_vf)
def evaluate_actions(
self,
obs: torch.tensor,
actions: torch.Tensor,
lstm_states: RNNStates,
episode_starts: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""
Evaluate actions according to the current policy,
given the observations.
:param obs:
:param actions:
:return: estimated value, log likelihood of taking those actions
and entropy of the action distribution.
"""
# Preprocess the observation if needed
features,features_lang = self.extract_features(obs)
latent_pi, _ = self._process_sequence(features, lstm_states.pi, episode_starts, self.lstm_actor)
if self.lstm_critic is not None:
latent_vf, _ = self._process_sequence(features, lstm_states.vf, episode_starts, self.lstm_critic)
elif self.shared_lstm:
latent_vf = latent_pi.detach()
else:
latent_vf = self.critic(features)
latent_pi = self.mlp_extractor.forward_actor(latent_pi)
latent_vf = self.mlp_extractor.forward_critic(latent_vf)
distribution = self._get_action_dist_from_latent(latent_pi)
log_prob = distribution.log_prob(actions)
values = self.value_net(latent_vf)
return values, log_prob, distribution.entropy(), features_lang
class AutoDualFeatureRecurrentActorCriticPolicy(RecurrentActorCriticPolicy):
"""
MultiInputActorClass policy class for actor-critic algorithms (has both policy and value prediction).
Used by A2C, PPO and the likes.
:param observation_space: Observation space
:param action_space: Action space
:param lr_schedule: Learning rate schedule (could be constant)
:param net_arch: The specification of the policy and value networks.
:param activation_fn: Activation function
:param ortho_init: Whether to use or not orthogonal initialization
:param use_sde: Whether to use State Dependent Exploration or not
:param log_std_init: Initial value for the log standard deviation
:param full_std: Whether to use (n_features x n_actions) parameters
for the std instead of only (n_features,) when using gSDE
:param sde_net_arch: Network architecture for extracting features
when using gSDE. If None, the latent features from the policy will be used.
Pass an empty list to use the states as features.
:param use_expln: Use ``expln()`` function instead of ``exp()`` to ensure
a positive standard deviation (cf paper). It allows to keep variance
above zero and prevent it from growing too fast. In practice, ``exp()`` is usually enough.
:param squash_output: Whether to squash the output using a tanh function,
this allows to ensure boundaries when using gSDE.
:param features_extractor_class: Features extractor to use.
:param features_extractor_kwargs: Keyword arguments
to pass to the features extractor.
:param normalize_images: Whether to normalize images or not,
dividing by 255.0 (True by default)
:param optimizer_class: The optimizer to use,
``torch.optim.Adam`` by default
:param optimizer_kwargs: Additional keyword arguments,
excluding the learning rate, to pass to the optimizer
"""
def __init__(
self,
observation_space: gym.spaces.Space,
action_space: gym.spaces.Space,
lr_schedule: Schedule,
net_arch: Optional[List[Union[int, Dict[str, List[int]]]]] = None,
activation_fn: Type[nn.Module] = nn.Tanh,
ortho_init: bool = True,
use_sde: bool = False,
log_std_init: float = 0.0,
full_std: bool = True,
sde_net_arch: Optional[List[int]] = None,
use_expln: bool = False,
squash_output: bool = False,
features_extractor_class: Type[BaseFeaturesExtractor] = AutoDualFeatureExtractor,
features_extractor_kwargs: Optional[Dict[str, Any]] = None,
normalize_images: bool = True,
optimizer_class: Type[torch.optim.Optimizer] = torch.optim.Adam,
optimizer_kwargs: Optional[Dict[str, Any]] = None,
lstm_hidden_size: int = 64,
n_lstm_layers: int = 1,
enable_critic_lstm: bool = False,
):
super().__init__(
observation_space,
action_space,
lr_schedule,
net_arch,
activation_fn,
ortho_init,
use_sde,
log_std_init,
full_std,
sde_net_arch,
use_expln,
squash_output,
features_extractor_class,
features_extractor_kwargs,
normalize_images,
optimizer_class,
optimizer_kwargs,
lstm_hidden_size,
n_lstm_layers,
enable_critic_lstm,
)
def forward(
self,
obs: torch.Tensor,
lstm_states: RNNStates,
episode_starts: torch.Tensor,
deterministic: bool = False,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, RNNStates]:
"""
Forward pass in all the networks (actor and critic)
:param obs: Observation
:param deterministic: Whether to sample or use deterministic actions
:return: action, value and log probability of the action
"""
# Preprocess the observation if needed
features,features_lang = self.extract_features(obs)
# latent_pi, latent_vf = self.mlp_extractor(features)
latent_pi, lstm_states_pi = self._process_sequence(features, lstm_states.pi, episode_starts, self.lstm_actor)
if self.lstm_critic is not None:
latent_vf, lstm_states_vf = self._process_sequence(features, lstm_states.vf, episode_starts, self.lstm_critic)
elif self.shared_lstm:
# Re-use LSTM features but do not backpropagate
latent_vf = latent_pi.detach()
lstm_states_vf = (lstm_states_pi[0].detach(), lstm_states_pi[1].detach())
else:
latent_vf = self.critic(features)
lstm_states_vf = lstm_states_pi
latent_pi = self.mlp_extractor.forward_actor(latent_pi)
latent_vf = self.mlp_extractor.forward_critic(latent_vf)
# Evaluate the values for the given observations
values = self.value_net(latent_vf)
distribution = self._get_action_dist_from_latent(latent_pi)
actions = distribution.get_actions(deterministic=deterministic)
log_prob = distribution.log_prob(actions)
return actions, values, log_prob, RNNStates(lstm_states_pi, lstm_states_vf)
def get_distribution(
self,
obs: torch.Tensor,
lstm_states: Tuple[torch.Tensor, torch.Tensor],
episode_starts: torch.Tensor,
) -> Tuple[Distribution, Tuple[torch.Tensor, ...]]:
"""
Get the current policy distribution given the observations.
:param obs:
:return: the action distribution and new hidden states.
"""
features,features_lang = self.extract_features(obs)
latent_pi, lstm_states = self._process_sequence(features, lstm_states, episode_starts, self.lstm_actor)
latent_pi = self.mlp_extractor.forward_actor(latent_pi)
return self._get_action_dist_from_latent(latent_pi), lstm_states
def predict_values(
self,
obs: torch.Tensor,
lstm_states: Tuple[torch.Tensor, torch.Tensor],
episode_starts: torch.Tensor,
) -> torch.Tensor:
"""
Get the estimated values according to the current policy given the observations.
:param obs:
:return: the estimated values.
"""
features,features_lang = self.extract_features(obs)
if self.lstm_critic is not None:
latent_vf, lstm_states_vf = self._process_sequence(features, lstm_states, episode_starts, self.lstm_critic)
elif self.shared_lstm:
# Use LSTM from the actor
latent_pi, _ = self._process_sequence(features, lstm_states, episode_starts, self.lstm_actor)
latent_vf = latent_pi.detach()
else:
latent_vf = self.critic(features)
latent_vf = self.mlp_extractor.forward_critic(latent_vf)
return self.value_net(latent_vf)
def evaluate_actions(
self,
obs: torch.tensor,
actions: torch.Tensor,
lstm_states: RNNStates,
episode_starts: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""
Evaluate actions according to the current policy,
given the observations.
:param obs:
:param actions:
:return: estimated value, log likelihood of taking those actions
and entropy of the action distribution.
"""
# Preprocess the observation if needed
features,features_lang = self.extract_features(obs)
latent_pi, _ = self._process_sequence(features, lstm_states.pi, episode_starts, self.lstm_actor)
if self.lstm_critic is not None:
latent_vf, _ = self._process_sequence(features, lstm_states.vf, episode_starts, self.lstm_critic)
elif self.shared_lstm:
latent_vf = latent_pi.detach()
else:
latent_vf = self.critic(features)
latent_pi = self.mlp_extractor.forward_actor(latent_pi)
latent_vf = self.mlp_extractor.forward_critic(latent_vf)
distribution = self._get_action_dist_from_latent(latent_pi)
log_prob = distribution.log_prob(actions)
values = self.value_net(latent_vf)
return values, log_prob, distribution.entropy(), features_lang