-
Notifications
You must be signed in to change notification settings - Fork 31
/
model.py
232 lines (194 loc) · 7.38 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
import torch.nn.functional as F
import torch.nn as nn
import torch
import torch.optim as optim
import numpy as np
import math
from torch.nn import init
class NoisyLinear(nn.Module):
"""Factorised Gaussian NoisyNet"""
def __init__(self, in_features, out_features, sigma0=0.5):
super().__init__()
self.in_features = in_features
self.out_features = out_features
self.weight = nn.Parameter(torch.Tensor(out_features, in_features))
self.bias = nn.Parameter(torch.Tensor(out_features))
self.noisy_weight = nn.Parameter(
torch.Tensor(out_features, in_features))
self.noisy_bias = nn.Parameter(torch.Tensor(out_features))
self.noise_std = sigma0 / math.sqrt(self.in_features)
self.reset_parameters()
self.register_noise()
def register_noise(self):
in_noise = torch.FloatTensor(self.in_features)
out_noise = torch.FloatTensor(self.out_features)
noise = torch.FloatTensor(self.out_features, self.in_features)
self.register_buffer('in_noise', in_noise)
self.register_buffer('out_noise', out_noise)
self.register_buffer('noise', noise)
def sample_noise(self):
self.in_noise.normal_(0, self.noise_std)
self.out_noise.normal_(0, self.noise_std)
self.noise = torch.mm(
self.out_noise.view(-1, 1), self.in_noise.view(1, -1))
def reset_parameters(self):
stdv = 1. / math.sqrt(self.weight.size(1))
self.weight.data.uniform_(-stdv, stdv)
self.noisy_weight.data.uniform_(-stdv, stdv)
if self.bias is not None:
self.bias.data.uniform_(-stdv, stdv)
self.noisy_bias.data.uniform_(-stdv, stdv)
def forward(self, x):
"""
Note: noise will be updated if x is not volatile
"""
normal_y = nn.functional.linear(x, self.weight, self.bias)
if self.training:
# update the noise once per update
self.sample_noise()
noisy_weight = self.noisy_weight * self.noise
noisy_bias = self.noisy_bias * self.out_noise
noisy_y = nn.functional.linear(x, noisy_weight, noisy_bias)
return noisy_y + normal_y
def __repr__(self):
return self.__class__.__name__ + '(' \
+ 'in_features=' + str(self.in_features) \
+ ', out_features=' + str(self.out_features) + ')'
class Flatten(nn.Module):
def forward(self, input):
return input.view(input.size(0), -1)
class CnnActorCriticNetwork(nn.Module):
def __init__(self, input_size, output_size, use_noisy_net=False):
super(CnnActorCriticNetwork, self).__init__()
if use_noisy_net:
print('use NoisyNet')
linear = NoisyLinear
else:
linear = nn.Linear
self.feature = nn.Sequential(
nn.Conv2d(
in_channels=4,
out_channels=32,
kernel_size=8,
stride=4),
nn.LeakyReLU(),
nn.Conv2d(
in_channels=32,
out_channels=64,
kernel_size=4,
stride=2),
nn.LeakyReLU(),
nn.Conv2d(
in_channels=64,
out_channels=64,
kernel_size=3,
stride=1),
nn.LeakyReLU(),
Flatten(),
linear(
7 * 7 * 64,
512),
nn.LeakyReLU()
)
self.actor = nn.Sequential(
linear(512, 512),
nn.LeakyReLU(),
linear(512, output_size)
)
self.critic = nn.Sequential(
linear(512, 512),
nn.LeakyReLU(),
linear(512, 1)
)
for p in self.modules():
if isinstance(p, nn.Conv2d):
init.orthogonal_(p.weight, np.sqrt(2))
p.bias.data.zero_()
if isinstance(p, nn.Linear):
init.orthogonal_(p.weight, np.sqrt(2))
p.bias.data.zero_()
for i in range(len(self.actor)):
if type(self.actor[i]) == nn.Linear:
init.orthogonal_(self.actor[i].weight, 0.01)
self.actor[i].bias.data.zero_()
for i in range(len(self.critic)):
if type(self.critic[i]) == nn.Linear:
init.orthogonal_(self.critic[i].weight, 0.01)
self.critic[i].bias.data.zero_()
def forward(self, state):
x = self.feature(state)
policy = self.actor(x)
value = self.critic(x)
return policy, value
class ICMModel(nn.Module):
def __init__(self, input_size, output_size, use_cuda=True):
super(ICMModel, self).__init__()
self.input_size = input_size
self.output_size = output_size
self.device = torch.device('cuda' if use_cuda else 'cpu')
feature_output = 7 * 7 * 64
self.feature = nn.Sequential(
nn.Conv2d(
in_channels=4,
out_channels=32,
kernel_size=8,
stride=4),
nn.LeakyReLU(),
nn.Conv2d(
in_channels=32,
out_channels=64,
kernel_size=4,
stride=2),
nn.LeakyReLU(),
nn.Conv2d(
in_channels=64,
out_channels=64,
kernel_size=3,
stride=1),
nn.LeakyReLU(),
Flatten(),
nn.Linear(feature_output, 512)
)
self.inverse_net = nn.Sequential(
nn.Linear(512 * 2, 512),
nn.ReLU(),
nn.Linear(512, output_size)
)
self.residual = [nn.Sequential(
nn.Linear(output_size + 512, 512),
nn.LeakyReLU(),
nn.Linear(512, 512),
).to(self.device)] * 8
self.forward_net_1 = nn.Sequential(
nn.Linear(output_size + 512, 512),
nn.LeakyReLU()
)
self.forward_net_2 = nn.Sequential(
nn.Linear(output_size + 512, 512),
)
for p in self.modules():
if isinstance(p, nn.Conv2d):
init.kaiming_uniform_(p.weight)
p.bias.data.zero_()
if isinstance(p, nn.Linear):
init.kaiming_uniform_(p.weight, a=1.0)
p.bias.data.zero_()
def forward(self, inputs):
state, next_state, action = inputs
encode_state = self.feature(state)
encode_next_state = self.feature(next_state)
# get pred action
pred_action = torch.cat((encode_state, encode_next_state), 1)
pred_action = self.inverse_net(pred_action)
# ---------------------
# get pred next state
pred_next_state_feature_orig = torch.cat((encode_state, action), 1)
pred_next_state_feature_orig = self.forward_net_1(pred_next_state_feature_orig)
# residual
for i in range(4):
pred_next_state_feature = self.residual[i * 2](torch.cat((pred_next_state_feature_orig, action), 1))
pred_next_state_feature_orig = self.residual[i * 2 + 1](
torch.cat((pred_next_state_feature, action), 1)) + pred_next_state_feature_orig
pred_next_state_feature = self.forward_net_2(torch.cat((pred_next_state_feature_orig, action), 1))
real_next_state_feature = encode_next_state
return real_next_state_feature, pred_next_state_feature, pred_action