-
Notifications
You must be signed in to change notification settings - Fork 4
/
model.py
executable file
·351 lines (279 loc) · 11.3 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
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
import torch
import torch.nn as nn
import numpy as np
from torchvision import transforms
from a2c_ppo_acktr.distributions import Categorical, DiagGaussian, Bernoulli
from a2c_ppo_acktr.utils import init
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, zero_last_layer=False, base=None,
base_kwargs=None, dist=None):
super(Policy, self).__init__()
if base_kwargs is None:
base_kwargs = {}
if base is None:
if isinstance(obs_shape[0], tuple):
base = E2EBase
elif len(obs_shape) == 3:
base = CNNBase
elif len(obs_shape) == 1:
base = MLPBase
else:
raise NotImplementedError
self.base = base(obs_shape, **base_kwargs)
else:
self.base = base
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, zll=zero_last_layer)
elif action_space.__class__.__name__ == "MultiBinary":
num_outputs = action_space.shape[0]
self.dist = Bernoulli(self.base.output_size, num_outputs)
else:
raise NotImplementedError
if dist is not None:
self.dist = dist
@property
def is_recurrent(self):
return self.base.is_recurrent
@property
def recurrent_hidden_state_size(self):
"""Size of rnn_hx."""
return self.base.recurrent_hidden_state_size
def forward(self, inputs, rnn_hxs, masks):
raise NotImplementedError
def act(self, inputs, rnn_hxs, masks, deterministic=False):
value, actor_features, rnn_hxs = self.base(inputs, rnn_hxs, 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, rnn_hxs
def get_value(self, inputs, rnn_hxs, masks):
value, _, _ = self.base(inputs, rnn_hxs, masks)
return value
def evaluate_actions(self, inputs, rnn_hxs, masks, action):
value, actor_features, rnn_hxs = self.base(inputs, rnn_hxs, 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, rnn_hxs
class NNBase(nn.Module):
def __init__(self, recurrent, recurrent_input_size, hidden_size):
super(NNBase, self).__init__()
self._hidden_size = hidden_size
self._recurrent = recurrent
if recurrent:
self.gru = nn.GRU(recurrent_input_size, hidden_size)
for name, param in self.gru.named_parameters():
if 'bias' in name:
nn.init.constant_(param, 0)
elif 'weight' in name:
nn.init.orthogonal_(param)
@property
def is_recurrent(self):
return self._recurrent
@property
def recurrent_hidden_state_size(self):
if self._recurrent:
return self._hidden_size
return 1
@property
def output_size(self):
return self._hidden_size
def _forward_gru(self, x, hxs, masks):
if x.size(0) == hxs.size(0):
x, hxs = self.gru(x.unsqueeze(0), (hxs * masks).unsqueeze(0))
x = x.squeeze(0)
hxs = hxs.squeeze(0)
else:
# x is a (T, N, -1) tensor that has been flatten to (T * N, -1)
N = hxs.size(0)
T = int(x.size(0) / N)
# unflatten
x = x.view(T, N, x.size(1))
# Same deal with masks
masks = masks.view(T, N)
# Let's figure out which steps in the sequence have a zero for any agent
# We will always assume t=0 has a zero in it as that makes the logic cleaner
has_zeros = ((masks[1:] == 0.0)
.any(dim=-1)
.nonzero()
.squeeze()
.cpu())
# +1 to correct the masks[1:]
if has_zeros.dim() == 0:
# Deal with scalar
has_zeros = [has_zeros.item() + 1]
else:
has_zeros = (has_zeros + 1).numpy().tolist()
# add t=0 and t=T to the list
has_zeros = [0] + has_zeros + [T]
hxs = hxs.unsqueeze(0)
outputs = []
for i in range(len(has_zeros) - 1):
# We can now process steps that don't have any zeros in masks together!
# This is much faster
start_idx = has_zeros[i]
end_idx = has_zeros[i + 1]
rnn_scores, hxs = self.gru(
x[start_idx:end_idx],
hxs * masks[start_idx].view(1, -1, 1)
)
outputs.append(rnn_scores)
# assert len(outputs) == T
# x is a (T, N, -1) tensor
x = torch.cat(outputs, dim=0)
# flatten
x = x.view(T * N, -1)
hxs = hxs.squeeze(0)
return x, hxs
class CNNBase(NNBase):
def __init__(self, obs_shape, recurrent=False, hidden_size=512):
super(CNNBase, self).__init__(recurrent, hidden_size, hidden_size)
num_inputs = obs_shape[0]
init_ = lambda m: init(m,
nn.init.orthogonal_,
lambda x: nn.init.constant_(x, 0),
nn.init.calculate_gain('relu'))
self.main = nn.Sequential( # 84 x 84 128
init_(nn.Conv2d(num_inputs, 32, 3, stride=2)), # 63 x 63
nn.ReLU(),
init_(nn.Conv2d(32, 48, 3, stride=2)), # 31 * 31
nn.ReLU(),
init_(nn.Conv2d(48, 64, 3, stride=2)), # 15 x 15
nn.ReLU(),
init_(nn.Conv2d(64, 128, 3, stride=2)), # 7 x 7
nn.ReLU(),
init_(nn.Conv2d(128, 64, 3, stride=1)), # 5 x 5
nn.ReLU(),
Flatten(),
init_(nn.Linear(64 * 5 * 5, hidden_size)),
nn.ReLU()
)
init_ = lambda m: init(m,
nn.init.orthogonal_,
lambda x: nn.init.constant_(x, 0))
self.critic_linear = init_(nn.Linear(hidden_size, 1))
self.train()
def forward(self, inputs, rnn_hxs, masks):
x = self.main(inputs / 255.0)
if self.is_recurrent:
x, rnn_hxs = self._forward_gru(x, rnn_hxs, masks)
return self.critic_linear(x), x, rnn_hxs
class MLPBase(NNBase):
def __init__(self, obs_shape, recurrent=False, hidden_size=64):
num_inputs = obs_shape[0]
super(MLPBase, self).__init__(recurrent, num_inputs, hidden_size)
if recurrent:
num_inputs = hidden_size
init_ = lambda m: init(m,
nn.init.orthogonal_,
lambda x: nn.init.constant_(x, 0),
np.sqrt(2))
self.actor = nn.Sequential(
init_(nn.Linear(num_inputs, hidden_size)),
nn.Tanh(),
init_(nn.Linear(hidden_size, hidden_size)),
nn.Tanh(),
init_(nn.Linear(hidden_size, hidden_size)),
nn.Tanh()
)
self.critic = nn.Sequential(
init_(nn.Linear(num_inputs, hidden_size)),
nn.Tanh(),
init_(nn.Linear(hidden_size, hidden_size)),
nn.Tanh(),
init_(nn.Linear(hidden_size, hidden_size)),
nn.Tanh()
)
self.critic_linear = init_(nn.Linear(hidden_size, 1))
self.train()
def forward(self, inputs, rnn_hxs, masks):
x = inputs
if self.is_recurrent:
x, rnn_hxs = self._forward_gru(x, rnn_hxs, masks)
hidden_critic = self.critic(x)
hidden_actor = self.actor(x)
return self.critic_linear(hidden_critic), hidden_actor, rnn_hxs
class E2EBase(NNBase):
def __init__(self, obs_shape, recurrent=False, hidden_size=64):
super(E2EBase, self).__init__(False, hidden_size, hidden_size)
image_obs_shape, state_obs_shape = obs_shape
self.conv_layers = nn.Sequential( # 128 x 128
(nn.Conv2d(image_obs_shape[0], 64, 3, padding=1)),
nn.ReLU(inplace=True),
(nn.Conv2d(64, 64, 3, padding=1)),
nn.ReLU(inplace=True),
nn.MaxPool2d(2), # 64
(nn.Conv2d(64, 128, 3, padding=1)),
nn.ReLU(inplace=True),
(nn.Conv2d(128, 128, 3, padding=1)),
nn.ReLU(inplace=True),
nn.MaxPool2d(2), # 32
(nn.Conv2d(128, 256, 3, padding=1)),
nn.ReLU(inplace=True),
(nn.Conv2d(256, 256, 3, padding=1)),
nn.ReLU(inplace=True),
(nn.Conv2d(256, 256, 3, padding=1)),
nn.ReLU(inplace=True),
nn.MaxPool2d(2), # 16
(nn.Conv2d(256, 512, 3, padding=1)),
nn.ReLU(inplace=True),
(nn.Conv2d(512, 512, 3, padding=1)),
nn.ReLU(inplace=True),
(nn.Conv2d(512, 512, 3, padding=1)),
nn.ReLU(inplace=True),
nn.MaxPool2d(2), # 8
(nn.Conv2d(512, 512, 3, padding=1)),
nn.ReLU(inplace=True),
(nn.Conv2d(512, 512, 3, padding=1)),
nn.ReLU(inplace=True),
(nn.Conv2d(512, 512, 3, padding=1)),
nn.ReLU(inplace=True),
nn.MaxPool2d(2), # 4
)
self.flatten = Flatten()
init_ = lambda m: init(m, nn.init.orthogonal_, lambda x: nn.init.constant_(x, 0),
np.sqrt(2))
self.actor = nn.Sequential(
init_(nn.Linear(4 * 4 * 512 + 7, 256)),
nn.Tanh(),
init_(nn.Linear(256, 256)),
nn.Tanh(),
init_(nn.Linear(256, 256)),
nn.Tanh(),
init_(nn.Linear(256, hidden_size)),
nn.Tanh(),
)
self.critic = nn.Sequential(
init_(nn.Linear(64 + state_obs_shape[0], 256)),
nn.Tanh(),
init_(nn.Linear(256, 256)),
nn.Tanh(),
init_(nn.Linear(256, 256)),
nn.Tanh(),
init_(nn.Linear(256, 1)),
)
self.normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
self.train()
def forward(self, inputs, rnn_hxs, masks):
images, state = inputs.items
joint_angles = state[:, :7]
for i in range(images.size(0)):
images[i] = self.normalize(images[i].cpu() / 255.0).to(images.device)
conv_output = self.flatten(self.conv_layers(images))
x = torch.cat((conv_output, joint_angles), dim=1)
actor_features = self.actor(x)
x = torch.cat((actor_features, state), dim=1)
value = self.critic(x)
return value, actor_features, rnn_hxs