-
Notifications
You must be signed in to change notification settings - Fork 1
/
online_bnn_trpo.py
228 lines (170 loc) · 8.02 KB
/
online_bnn_trpo.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
# -*- coding: utf-8 -*-
"""
online_bnn_trpo.py
Created on : February 28, 2019
Author : anonymous
Name : Anonymous
"""
import tensorflow as tf
import numpy as np
import pickle
import sys
import os
import argparse
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "lib", "pysgmcmc")))
from lib.utils.misc import *
from lib.utils.rllab_env_rollout import IterativeData
from lib.utils.env_helpers import get_env
from models.training_dyn import TrainingDynamics
# import logging
logger_lvl = logging.getLogger()
logger_lvl.setLevel(logging.DEBUG)
def run_main(params_dir, output_dir, policy_type):
""" Init data """
all_params = load_params(params_dir)
dump_params(all_params, output_dir)
env = get_env(all_params["env"])
n_states = env.observation_space.shape[0]
n_actions = env.action_space.shape[0]
n_inputs = env.observation_space.shape[0] + env.action_space.shape[0]
n_outputs = env.observation_space.shape[0]
n_timestep = all_params["n_timestep"]
n_training = all_params["sample_train_size"]
n_validate = all_params["sample_valid_size"]
logging.info("Environment #States %d, #Actions %d", n_states, n_actions)
""" Iterative data """
data_generator = IterativeData(n_states, n_actions, n_timestep,
n_training=n_training, n_validate=n_validate,
rollout_params=all_params["rollout_params"])
""" TF session """
sess = tf.InteractiveSession()
""" Load dynamics """
training = TrainingDynamics(n_inputs, n_outputs, n_timestep,
action_bounds=env.action_space.bounds, session=sess,
model_type=all_params["model"],
dynamic_params=all_params["dynamics_params"],
dynamic_opt_params=all_params["dynamics_opt_params"])
start_itr = 0
if all_params["restore_dir"]:
logging.info("Restoring dynamics %s" % all_params["restore_dir"])
xu_training, y_training, xu_validate, y_validate = pickle.load(open("%s/rollout.pkl"
% all_params["restore_dir"], "rb"))
if "init_only" in all_params and all_params["init_only"]:
init_lfd_traj = all_params["init_lfd_traj"]
xu_training = xu_training[-init_lfd_traj * n_timestep:]
y_training = y_training[-init_lfd_traj * n_timestep:]
# xu_validate = xu_validate[:n_validate]
# y_validate = y_validate[:n_validate]
start_itr = len(xu_training) // n_training
training.add_data(xu_training[:, :n_states], xu_training[:, n_states:], y_training)
if "restore_dynamics" in all_params and all_params["restore_dynamics"]:
training.restore(all_params["restore_dir"])
else:
training.run(xu_validate, y_validate, params=all_params["dynamics_opt_params"])
data_generator.set_offline(xu_training, y_training, xu_validate, y_validate)
""" Load policy """
if policy_type == "lstm":
from policy.nn_lstm_policy import NNPolicy
else:
from policy.nn_policy import NNPolicy
""" Load policy """
nn_policy = NNPolicy(sess, env, training, n_timestep, n_states, n_actions,
log_dir=output_dir,
policy_params=all_params["policy_params"],
policy_opt_params=all_params["policy_opt_params"])
if all_params["restore_dir"]:
if not all_params["init_only"] and all_params["restore_policy"]:
nn_policy.policy_saver.restore(sess, os.path.join(all_params["restore_dir"], 'policy.ckpt'))
# else:
# nn_policy.optimize_policy()
""" RL step """
start_itr, end_iter = start_itr, all_params["sweep_iters"]
for itr in range(start_itr, end_iter):
logging.info("Iteration %d" % itr)
""" Rollout and add data """
# if ("init_only" in all_params and all_params["init_only"] and itr > start_itr) or not all_params["init_only"]:
# data_generator.rollout(nn_policy)
data_generator.rollout(nn_policy)
x_tr, u_tr, y_tr, x_va, u_va, y_va = data_generator.fetch_data(itr)
# Dump data
pickle.dump((data_generator.xu_training, data_generator.y_training,
data_generator.xu_validate, data_generator.y_validate),
open("%s/rollout.pkl" % output_dir, 'wb'))
if itr == start_itr:
training.add_data(x_tr, u_tr, y_tr)
else:
training.fit(x_tr, u_tr, y_tr)
logging.info("Current training, validate: %d, %d" % (training.y.shape[0], y_va.shape[0]))
""" Optimize dynamics """
xu_va = np.hstack((x_va, u_va))
xu_new = np.hstack((x_tr, u_tr))
y_new = y_tr
if itr == start_itr:
training.run(xu_va, y_va, params=all_params["dynamics_opt_params"])
else:
if "init_only" in all_params and all_params["init_only"]:
xu_all = np.vstack((xu_new, xu_training))
y_all = np.vstack((y_new, y_training))
else:
xu_all, y_all = xu_new, y_new
training.run(xu_va, y_va, xu_all, y_all, params=all_params["dynamics_opt_params"])
training.save(output_dir)
logging.info("Saved dynamics %s" % output_dir)
# data_generator.plot_traj(training, iter=itr, n_sample=10,
# data_path=os.path.join(output_dir, 'bnn_trpo'))
training._log_covariances()
""" Optimize Policy """
est_costs, real_costs = nn_policy.optimize_policy()
with open("%s/policy_log.txt" % output_dir, 'a') as f:
f.write("iter %d\n"
"\t val [%s]\n"
"\t real [%s]\n"
"\t final real %.3f\n" % (itr,
" ".join(map(str, est_costs)),
" ".join(map(str, real_costs[:-1])),
real_costs[-1]))
# data_generator.plot_fictitious_traj(training, nn_policy,
# data_path=os.path.join(output_dir, 'fict_samp_i%02d' % itr))
# Add data after training
if itr > start_itr:
training.add_data(x_tr, u_tr, y_tr, fit=False)
# for itr in range(start_itr, end_iter):
# data_generator.plot_traj(training, iter=itr, n_sample=10,
# data_path=os.path.join(output_dir, 'all_bnn_trpo'))
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument('-a', '--params',
required=True,
help="Path to parameters file")
parser.add_argument('-o', '--outputdir',
required=True,
help="Output directory")
parser.add_argument('-l', '--logdir',
required=False,
help="Path to log file")
parser.add_argument('-g', '--gpu',
required=False,
default="0",
help="GPU")
parser.add_argument('-p', '--policy',
required=False,
default="bnn",
help="Policy type [bnn, lstm]")
args = parser.parse_args()
params_dir = args.params
log_dir = args.logdir
output_dir = args.outputdir
gpu = args.gpu
policy = args.policy
os.environ["CUDA_VISIBLE_DEVICES"] = gpu
if log_dir:
logging.basicConfig(filename=log_dir,
filemode='w',
format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
datefmt='%H:%M:%S',
level=logging.DEBUG)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
run_main(params_dir, output_dir, policy)
if __name__ == "__main__":
main(sys.argv[1:])