-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
173 lines (131 loc) · 5.21 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
import os
import shutil
from IPython import embed
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
class MLP(nn.Module):
def __init__(self, input_size, hidden_size, output_size, dropout_rate,
intermediate_activation, final_activation):
super(MLP, self).__init__()
hidden_size = [input_size] + hidden_size + [output_size]
intermediate_activation = getattr(nn, intermediate_activation)
final_activation = getattr(nn, final_activation, None)
layers = []
for i in range(len(hidden_size) - 1):
layers.append(nn.Linear(*hidden_size[i:i + 2]))
if dropout_rate != 0:
layers.append(nn.Dropout(p=dropout_rate))
if i != len(hidden_size) - 2:
layers.append(intermediate_activation())
elif final_activation:
layers.append(final_activation())
self.layers = nn.Sequential(*layers)
def forward(self, x):
return self.layers(x)
# class Policy(nn.Module):
# def __init__(self, config):
# super(Policy, self).__init__()
# hs1 = config.input_size * 10
# hs3 = config.output_size * 10
# hs2 = int(np.round(np.sqrt(hs1 * hs3)))
# config.hidden_size = [hs1, hs2, hs3]
# self.mean_mlp = MLP(**config)
# self.log_std = nn.Parameter(torch.zeros(config.output_size))
# def forward(self, x):
# mean = self.mean_mlp(x)
# std = self.log_std.exp()
# return mean, std
class Policy(nn.Module):
def __init__(self, config):
super(Policy, self).__init__()
hs1 = config.input_size * 10
hs3 = config.output_size * 10
hs2 = int(np.round(np.sqrt(hs1 * hs3)))
config.hidden_size = [hs1, hs2, hs3]
self.mlp = MLP(**config)
def forward(self, x):
prob = self.mlp(x)
return prob
class Value(nn.Module):
def __init__(self, config):
super(Value, self).__init__()
hs1 = config.input_size * 10
hs3 = 5
hs2 = int(np.round(np.sqrt(hs1 * hs3)))
config.hidden_size = [hs1, hs2, hs3]
config.output_size = 1
self.mlp = MLP(**config)
def forward(self, x):
value = self.mlp(x)
return value
class Model:
def __init__(self, config, verbose=True):
self.config = config
count_parameters = lambda m: sum(p.numel() for p in m.parameters())
self.policy = Policy(config.policy)
self.policy.cuda()
if verbose:
print(self.policy)
print('# of parameters: {}\n'.format(count_parameters(self.policy)))
self.value = Value(config.value)
self.value.cuda()
if verbose:
print(self.value)
print('# of parameters: {}\n'.format(count_parameters(self.value)))
# self.optimizer = getattr(optim, config.optimizer.algorithm)([{
# 'params': self.policy.parameters(),
# 'lr': config.optimizer.policy_learning_rate
# }, {
# 'params': self.value.parameters(),
# 'lr': config.optimizer.value_learning_rate
# }])
self.policy_optimizer = getattr(optim, config.policy_optimizer.algorithm)(
self.policy.parameters(), lr=config.policy_optimizer.learning_rate)
self.value_optimizer = getattr(optim, config.value_optimizer.algorithm)(
self.value.parameters(), lr=config.value_optimizer.learning_rate)
if config.ckpt_path:
self.load_state(config.ckpt_path)
def set_train(self):
self.policy.train()
self.value.train()
def set_eval(self):
self.policy.eval()
self.value.eval()
# def select_action(self, obs):
# mean, std = self.policy(obs)
# act = torch.normal(mean, std)
# val = self.value(obs)
# return mean, std, act, val
def select_action(self, obs):
prob = self.policy(obs)
act = prob.multinomial(1).data[0, 0]
val = self.value(obs)
return prob, act, val
def get_policy_state(self):
return self.policy.state_dict()
def set_policy_state(self, state):
self.policy.load_state_dict(state)
def load_state(self, ckpt_path):
print('Loading model state from {}'.format(ckpt_path))
ckpt = torch.load(ckpt_path)
print(ckpt['info'])
self.policy.load_state_dict(ckpt['policy_state'])
self.value.load_state_dict(ckpt['value_state'])
self.policy_optimizer.load_state_dict(ckpt['policy_optimizer_state'])
self.value_optimizer.load_state_dict(ckpt['value_optimizer_state'])
def save_state(self, info, ckpt_path, is_best):
torch.save({
'info': info,
'policy_state': self.policy.state_dict(),
'value_state': self.value.state_dict(),
'policy_optimizer_state': self.policy_optimizer.state_dict(),
'value_optimizer_state': self.value_optimizer.state_dict()
}, ckpt_path)
if is_best:
best_ckpt_path = os.path.join(os.path.dirname(ckpt_path),
'best_model.ckpt')
shutil.copy(ckpt_path, best_ckpt_path)