forked from ikostrikov/pytorch-a2c-ppo-acktr-gail
-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
executable file
·170 lines (131 loc) · 4.95 KB
/
model.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
import torch
import torch.nn as nn
import torch.nn.functional as F
from distributions import Categorical, DiagGaussian
from utils import init, init_normc_
class Flatten(nn.Module):
def forward(self, x):
return x.view(x.size(0), -1)
class Policy(nn.Module):
def __init__(self, obs_shape, action_space, recurrent_policy):
super(Policy, self).__init__()
if len(obs_shape) == 3:
self.base = CNNBase(obs_shape[0], recurrent_policy)
elif len(obs_shape) == 1:
assert not recurrent_policy, \
"Recurrent policy is not implemented for the MLP controller"
self.base = MLPBase(obs_shape[0])
else:
raise NotImplementedError
if action_space.__class__.__name__ == "Discrete":
num_outputs = action_space.n
self.dist = Categorical(self.base.output_size, num_outputs)
elif action_space.__class__.__name__ == "Box":
num_outputs = action_space.shape[0]
self.dist = DiagGaussian(self.base.output_size, num_outputs)
else:
raise NotImplementedError
self.state_size = self.base.state_size
def forward(self, inputs, states, masks):
raise NotImplementedError
def act(self, inputs, states, masks, deterministic=False):
value, actor_features, states = self.base(inputs, states, masks)
dist = self.dist(actor_features)
if deterministic:
action = dist.mode()
else:
action = dist.sample()
action_log_probs = dist.log_probs(action)
dist_entropy = dist.entropy().mean()
return value, action, action_log_probs, states
def get_value(self, inputs, states, masks):
value, _, _ = self.base(inputs, states, masks)
return value
def evaluate_actions(self, inputs, states, masks, action):
value, actor_features, states = self.base(inputs, states, masks)
dist = self.dist(actor_features)
action_log_probs = dist.log_probs(action)
dist_entropy = dist.entropy().mean()
return value, action_log_probs, dist_entropy, states
class CNNBase(nn.Module):
def __init__(self, num_inputs, use_gru):
super(CNNBase, self).__init__()
init_ = lambda m: init(m,
nn.init.orthogonal_,
lambda x: nn.init.constant_(x, 0),
nn.init.calculate_gain('relu'))
self.main = nn.Sequential(
init_(nn.Conv2d(num_inputs, 32, 8, stride=4)),
nn.ReLU(),
init_(nn.Conv2d(32, 64, 4, stride=2)),
nn.ReLU(),
init_(nn.Conv2d(64, 32, 3, stride=1)),
nn.ReLU(),
Flatten(),
init_(nn.Linear(32 * 7 * 7, 512)),
nn.ReLU()
)
if use_gru:
self.gru = nn.GRUCell(512, 512)
nn.init.orthogonal_(self.gru.weight_ih.data)
nn.init.orthogonal_(self.gru.weight_hh.data)
self.gru.bias_ih.data.fill_(0)
self.gru.bias_hh.data.fill_(0)
init_ = lambda m: init(m,
nn.init.orthogonal_,
lambda x: nn.init.constant_(x, 0))
self.critic_linear = init_(nn.Linear(512, 1))
self.train()
@property
def state_size(self):
if hasattr(self, 'gru'):
return 512
else:
return 1
@property
def output_size(self):
return 512
def forward(self, inputs, states, masks):
x = self.main(inputs / 255.0)
if hasattr(self, 'gru'):
if inputs.size(0) == states.size(0):
x = states = self.gru(x, states * masks)
else:
x = x.view(-1, states.size(0), x.size(1))
masks = masks.view(-1, states.size(0), 1)
outputs = []
for i in range(x.size(0)):
hx = states = self.gru(x[i], states * masks[i])
outputs.append(hx)
x = torch.cat(outputs, 0)
return self.critic_linear(x), x, states
class MLPBase(nn.Module):
def __init__(self, num_inputs):
super(MLPBase, self).__init__()
init_ = lambda m: init(m,
init_normc_,
lambda x: nn.init.constant_(x, 0))
self.actor = nn.Sequential(
init_(nn.Linear(num_inputs, 64)),
nn.Tanh(),
init_(nn.Linear(64, 64)),
nn.Tanh()
)
self.critic = nn.Sequential(
init_(nn.Linear(num_inputs, 64)),
nn.Tanh(),
init_(nn.Linear(64, 64)),
nn.Tanh()
)
self.critic_linear = init_(nn.Linear(64, 1))
self.train()
@property
def state_size(self):
return 1
@property
def output_size(self):
return 64
def forward(self, inputs, states, masks):
hidden_critic = self.critic(inputs)
hidden_actor = self.actor(inputs)
return self.critic_linear(hidden_critic), hidden_actor, states