forked from microsoft/oac-explore
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
248 lines (179 loc) · 7.25 KB
/
main.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
import os
import os.path as osp
import argparse
import torch
import utils.pytorch_util as ptu
from replay_buffer import ReplayBuffer
from utils.env_utils import NormalizedBoxEnv, domain_to_epoch, env_producer
from utils.rng import set_global_pkg_rng_state
from launcher_util import run_experiment_here
from path_collector import MdpPathCollector, RemoteMdpPathCollector
from trainer.policies import TanhGaussianPolicy, MakeDeterministic
from trainer.trainer import SACTrainer
from networks import FlattenMlp
from rl_algorithm import BatchRLAlgorithm
import ray
import logging
ray.init(
# If true, then output from all of the worker processes on all nodes will be directed to the driver.
log_to_driver=True,
logging_level=logging.WARNING,
# The amount of memory (in bytes)
object_store_memory=1073741824, # 1g
redis_max_memory=1073741824 # 1g
)
def get_current_branch(dir):
from git import Repo
repo = Repo(dir)
return repo.active_branch.name
def get_policy_producer(obs_dim, action_dim, hidden_sizes):
def policy_producer(deterministic=False):
policy = TanhGaussianPolicy(
obs_dim=obs_dim,
action_dim=action_dim,
hidden_sizes=hidden_sizes,
)
if deterministic:
policy = MakeDeterministic(policy)
return policy
return policy_producer
def get_q_producer(obs_dim, action_dim, hidden_sizes):
def q_producer():
return FlattenMlp(input_size=obs_dim + action_dim,
output_size=1,
hidden_sizes=hidden_sizes, )
return q_producer
def experiment(variant, prev_exp_state=None):
domain = variant['domain']
seed = variant['seed']
expl_env = env_producer(domain, seed)
obs_dim = expl_env.observation_space.low.size
action_dim = expl_env.action_space.low.size
# Get producer function for policy and value functions
M = variant['layer_size']
q_producer = get_q_producer(obs_dim, action_dim, hidden_sizes=[M, M])
policy_producer = get_policy_producer(
obs_dim, action_dim, hidden_sizes=[M, M])
# Finished getting producer
remote_eval_path_collector = RemoteMdpPathCollector.remote(
domain, seed * 10 + 1,
policy_producer
)
expl_path_collector = MdpPathCollector(
expl_env,
)
replay_buffer = ReplayBuffer(
variant['replay_buffer_size'],
ob_space=expl_env.observation_space,
action_space=expl_env.action_space
)
trainer = SACTrainer(
policy_producer,
q_producer,
action_space=expl_env.action_space,
**variant['trainer_kwargs']
)
algorithm = BatchRLAlgorithm(
trainer=trainer,
exploration_data_collector=expl_path_collector,
remote_eval_data_collector=remote_eval_path_collector,
replay_buffer=replay_buffer,
optimistic_exp_hp=variant['optimistic_exp'],
**variant['algorithm_kwargs']
)
algorithm.to(ptu.device)
if prev_exp_state is not None:
expl_path_collector.restore_from_snapshot(
prev_exp_state['exploration'])
ray.get([remote_eval_path_collector.restore_from_snapshot.remote(
prev_exp_state['evaluation_remote'])])
ray.get([remote_eval_path_collector.set_global_pkg_rng_state.remote(
prev_exp_state['evaluation_remote_rng_state']
)])
replay_buffer.restore_from_snapshot(prev_exp_state['replay_buffer'])
trainer.restore_from_snapshot(prev_exp_state['trainer'])
set_global_pkg_rng_state(prev_exp_state['global_pkg_rng_state'])
start_epoch = prev_exp_state['epoch'] + \
1 if prev_exp_state is not None else 0
algorithm.train(start_epoch)
def get_cmd_args():
parser = argparse.ArgumentParser()
parser.add_argument('--seed', type=int, default=0, help='Random seed')
parser.add_argument('--domain', type=str, default='invertedpendulum')
parser.add_argument('--no_gpu', default=False, action='store_true')
parser.add_argument('--base_log_dir', type=str, default='./data')
# optimistic_exp_hyper_param
parser.add_argument('--beta_UB', type=float, default=0.0)
parser.add_argument('--delta', type=float, default=0.0)
# Training param
parser.add_argument('--num_expl_steps_per_train_loop',
type=int, default=1000)
parser.add_argument('--num_trains_per_train_loop', type=int, default=1000)
args = parser.parse_args()
return args
def get_log_dir(args, should_include_base_log_dir=True, should_include_seed=True, should_include_domain=True):
log_dir = osp.join(
get_current_branch('./'),
# Algo kwargs portion
f'num_expl_steps_per_train_loop_{args.num_expl_steps_per_train_loop}_num_trains_per_train_loop_{args.num_trains_per_train_loop}'
# optimistic exploration dependent portion
f'beta_UB_{args.beta_UB}_delta_{args.delta}',
)
if should_include_domain:
log_dir = osp.join(log_dir, args.domain)
if should_include_seed:
log_dir = osp.join(log_dir, f'seed_{args.seed}')
if should_include_base_log_dir:
log_dir = osp.join(args.base_log_dir, log_dir)
return log_dir
if __name__ == "__main__":
# Parameters for the experiment are either listed in variant below
# or can be set through cmdline args and will be added or overrided
# the corresponding attributein variant
variant = dict(
algorithm="SAC",
version="normal",
layer_size=256,
replay_buffer_size=int(1E6),
algorithm_kwargs=dict(
num_eval_steps_per_epoch=5000,
num_trains_per_train_loop=None,
num_expl_steps_per_train_loop=None,
min_num_steps_before_training=10000,
max_path_length=1000,
batch_size=256,
),
trainer_kwargs=dict(
discount=0.99,
soft_target_tau=5e-3,
target_update_period=1,
policy_lr=3E-4,
qf_lr=3E-4,
reward_scale=1,
use_automatic_entropy_tuning=True,
),
optimistic_exp={}
)
args = get_cmd_args()
variant['log_dir'] = get_log_dir(args)
variant['seed'] = args.seed
variant['domain'] = args.domain
variant['algorithm_kwargs']['num_epochs'] = domain_to_epoch(args.domain)
variant['algorithm_kwargs']['num_trains_per_train_loop'] = args.num_trains_per_train_loop
variant['algorithm_kwargs']['num_expl_steps_per_train_loop'] = args.num_expl_steps_per_train_loop
variant['optimistic_exp']['should_use'] = args.beta_UB > 0 or args.delta > 0
variant['optimistic_exp']['beta_UB'] = args.beta_UB
variant['optimistic_exp']['delta'] = args.delta
if torch.cuda.is_available():
gpu_id = int(args.seed % torch.cuda.device_count())
else:
gpu_id = None
run_experiment_here(experiment, variant,
seed=args.seed,
use_gpu=not args.no_gpu and torch.cuda.is_available(),
gpu_id=gpu_id,
# Save the params every snapshot_gap and override previously saved result
snapshot_gap=100,
snapshot_mode='last_every_gap',
log_dir=variant['log_dir']
)