Energetic26 commited on
Commit
22b374f
·
1 Parent(s): 60ab5f6
Files changed (4) hide show
  1. Loader.py +73 -0
  2. PPO_HypConfig.py +489 -0
  3. Trainer.py +68 -0
  4. runner_trainer.py +219 -0
Loader.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from stable_baselines3 import PPO
3
+ import gym
4
+
5
+
6
+
7
+
8
+ class MegaLoader:
9
+ def __init__(self, env_name, algo, directory):
10
+ self.env_name = env_name
11
+ self.env = gym.make(self.env_name)
12
+ self.env.reset()
13
+
14
+ self.algorithm = algo
15
+ self.directory = directory
16
+
17
+ def model_selector(self, all_models_dir):
18
+ # print( os.listdir(all_models_dir)[-1])
19
+ return os.listdir(all_models_dir)[-1]
20
+
21
+ # return whole file name properly, with date and all
22
+ pass
23
+
24
+ def load(self, execution_number, no_of_episodes):
25
+ # Input :-
26
+ # 1. execution_number -
27
+ # 2. no_of_episodes -
28
+ # 3.
29
+
30
+ # Returns :-
31
+ # Dictionary with the following items
32
+ # 1. total_return [int]
33
+ # 2. return_per_episode [list]
34
+ # 3.
35
+ # 3.
36
+ # 3.
37
+ # 3.
38
+
39
+ total_return = 0
40
+ return_per_episode = []
41
+ info_per_episode = []
42
+
43
+ all_models_dir = f"model/{self.directory}/{execution_number}"
44
+
45
+ model_no = self.model_selector(all_models_dir)
46
+ model_dir = f"{all_models_dir}/{model_no}"
47
+
48
+ model = PPO.load(model_dir, env=self.env)
49
+
50
+ for ep in range(no_of_episodes):
51
+ obs = self.env.reset()
52
+ done = False
53
+ info = ""
54
+ episode_return = 0
55
+
56
+ while not done:
57
+ action, _states = model.predict(obs)
58
+ obs, rewards, done, info = self.env.step(action)
59
+ episode_return += rewards
60
+
61
+ # self.env.render()
62
+
63
+ return_per_episode.append(episode_return)
64
+ total_return += episode_return
65
+ info_per_episode.append(info)
66
+
67
+ model_test_info = {
68
+ "total_return": total_return,
69
+ "return_per_episode": return_per_episode,
70
+ "info_per_episode": info_per_episode,
71
+ }
72
+
73
+ return model_test_info
PPO_HypConfig.py ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import optuna
3
+ import numpy as np
4
+
5
+ ## change default to "selector" for that parameter
6
+ ## there are specifications for what type should be there, see that and do final design. FOr exxample --> learning_rate (Union[float, Callable[[float], float]])
7
+ ## Fix TENSORBOARD_LOG
8
+ ## Generate a number/code that is unique to each hyperparmeter configuration
9
+
10
+
11
+
12
+ # import stable_baselines3.common.schedules as schedules
13
+
14
+
15
+
16
+ #####################################################################
17
+ ## LEARNING RATE SCHEDULER (learning_rate) ##
18
+ #####################################################################
19
+ # Currently random, make it categorical and pass parameters using dictionary properly
20
+
21
+ class Learning_Rate_Scheduler:
22
+ # remove this default function later
23
+ # Make this categorical
24
+ # send params in __init__ for all class's functions --> def __init__(self, i, params):
25
+ # always call through
26
+
27
+
28
+ def __init__(self):
29
+ self.low = 1e-5
30
+ self.high = 1e-2
31
+ self.log = True
32
+ #do this for all
33
+
34
+ def default(self):
35
+ return random.random() / 1000
36
+
37
+ def opt(self, trial):
38
+ return trial.suggest_float("learning_rate", self.low, self.high, log=self.log)
39
+
40
+ def step_decay(optimizer, initial_lr=0.001, drop_rate=0.1, epochs_drop=10):
41
+ return
42
+ scheduler = lr_scheduler.StepLR(optimizer, step_size=epochs_drop, gamma=drop_rate)
43
+ return scheduler
44
+
45
+ def exp_decay(optimizer, initial_lr=0.001, decay_rate=0.96):
46
+ return
47
+ scheduler = lr_scheduler.ExponentialLR(optimizer, gamma=decay_rate)
48
+ return scheduler
49
+
50
+ def cosine_anneal(optimizer, initial_lr=0.001, epochs=100):
51
+ return
52
+ scheduler = lr_scheduler.CosineAnnealingLR(optimizer, T_max=epochs)
53
+ return scheduler
54
+
55
+ def reduce_on_plateau(optimizer, mode='min', factor=0.1, patience=10, verbose=False):
56
+ return
57
+ scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode=mode, factor=factor, patience=patience, verbose=verbose)
58
+ return scheduler
59
+
60
+ def cyclical_lr(optimizer, step_size=2000, base_lr=1e-3, max_lr=6e-3, mode='triangular', gamma=1.):
61
+ return
62
+ scheduler = lr_scheduler.CyclicLR(optimizer, base_lr=base_lr, max_lr=max_lr, step_size_up=step_size,
63
+ mode=mode, gamma=gamma)
64
+ return scheduler
65
+
66
+ def warmup_lr(optimizer, factor=10, warmup_epochs=5):
67
+ return
68
+ def lr_lambda(current_epoch):
69
+ if current_epoch < warmup_epochs:
70
+ return factor
71
+ else:
72
+ return 1.0
73
+ scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda)
74
+ return scheduler
75
+
76
+ def one_cycle_lr(optimizer, num_steps, lr_range=(1e-4, 1e-2), momentum_range=(0.85, 0.95)):
77
+ return
78
+ scheduler = lr_scheduler.OneCycleLR(optimizer, max_lr=lr_range[1], total_steps=num_steps,
79
+ pct_start=0.3, anneal_strategy='cos', cycle_momentum=True,
80
+ base_momentum=momentum_range[0], max_momentum=momentum_range[1])
81
+ return scheduler
82
+
83
+ def constant_schedule(self, lr=3e-4):
84
+ return schedules.constant_schedule(3e-4)
85
+
86
+ def linear_schedule(self, initial_value=1e6, final_value=3e-4, n_timsteps=1e-4):
87
+ return schedules.linear_schedule(initial_value, final_value, n_timsteps)
88
+
89
+ def piecewise_schedule(self, schedule_pieces):
90
+ return schedules.piecewise_schedule(schedule_pieces)
91
+
92
+ def cosine_schedule(self, initial_lr=3e-4, final_lr=1e-4, total_timesteps=1e6): # check if this cosine annealing
93
+ return schedules.cosine_schedule(initial_lr, final_lr, total_timesteps)
94
+
95
+ def linear_warmup_schedule(self):
96
+ warmup_timesteps = 1e5
97
+ learning_rate_schedule = schedules.linear_schedule(9e5, 0, 3e-4)
98
+ learning_rate = schedules.linear_warmup(learning_rate_schedule, warmup_timesteps, 0)
99
+ return learning_rate
100
+
101
+ def combined_scheduler(self):
102
+ pass
103
+
104
+
105
+
106
+ #####################################################################
107
+ ## POLICY(policy) ##
108
+ #####################################################################
109
+ # Categorical
110
+ class PolicySelector:
111
+ def __init__(self):
112
+ pass
113
+
114
+ def opt(self, trial):
115
+ return "MlpPolicy"
116
+
117
+ def default(self):
118
+ return self.MlpPolicy()
119
+
120
+ def MlpPolicy(self):
121
+ return "MlpPolicy"
122
+
123
+ def CnnPolicy(self):
124
+ return "CnnPolicy"
125
+
126
+ def MultiInputPolicy(self):
127
+ return "MultiInputPolicy"
128
+
129
+
130
+ #####################################################################
131
+ ## UPDATE PER STEPS (n_steps) ##
132
+ #####################################################################
133
+ #Refine the search space --> dont just do 2^i in between also there might be peak
134
+
135
+ class StepsPerUpdate:
136
+
137
+ def __init__(self):
138
+ self.max_size = 2048
139
+
140
+ pass
141
+
142
+ def opt(self, trial):
143
+ return 2 ** trial.suggest_int("n_steps", 10, 12)
144
+
145
+ def default(self):
146
+ return random.randint(1, self.max_size)
147
+
148
+ #####################################################################
149
+ ## BATCH SIZE (batch_size) ##
150
+ #####################################################################
151
+
152
+ class BatchSize:
153
+ def __init__(self):
154
+ self.max_size = 64
155
+ pass
156
+
157
+ def opt(self, trial):
158
+ return 2 ** trial.suggest_int("batch_size", 5, 8)
159
+
160
+ def default(self):
161
+ self.max_size=26
162
+ return random.randint(1, self.max_size)
163
+
164
+ #####################################################################
165
+ ## No. OF EPOCHS WHEN OPTIMIZING SURROGATE LOSS (n_epochs) ##
166
+ #####################################################################
167
+ # Higher the better
168
+
169
+ class NoOfEpochs:
170
+ def __init__(self):
171
+ self.max_size = 10
172
+ pass
173
+
174
+ def opt(self, trial):
175
+ return trial.suggest_int("n_epochs", 5, 10)
176
+
177
+ def default(self):
178
+ return random.randint(1, self.max_size)
179
+
180
+
181
+ #####################################################################
182
+ ## DISCOUNT FACTOR (gamma) ##
183
+ #####################################################################
184
+
185
+ class DiscountFactor:
186
+ def __init__(self):
187
+ self.max_size = 10
188
+
189
+ def opt(self, trial):
190
+ return trial.suggest_float("gamma", 0.9, 0.999)
191
+
192
+ def default(self):
193
+ return random.random()
194
+
195
+ #####################################################################
196
+ ## BIAS-VARIANCE TRADEOFF for GENERALIZED ADVANTAGE ESTIMATOR ##
197
+ #####################################################################
198
+
199
+ class BiasVarianceTradeoff:
200
+ def __init__(self):
201
+ pass
202
+
203
+ def opt(self, trial):
204
+ return trial.suggest_float("bvtradeoff", 0.9, 0.99)
205
+
206
+ def default(self):
207
+ return random.random()
208
+
209
+ #####################################################################
210
+ ## CLIPPING FUNCTION (clip_range) ##
211
+ #####################################################################
212
+ # Can be a function of progress
213
+
214
+ class ClipRange:
215
+ def __init__(self):
216
+ pass
217
+
218
+ def opt(self, trial):
219
+ return trial.suggest_float("clip_range", 0.1, 0.3)
220
+
221
+ def default(self):
222
+ return random.random()
223
+
224
+
225
+ #####################################################################
226
+ ## CLIPPING RANGE for Value Function (clip_range_vf) ##
227
+ #####################################################################
228
+
229
+ class ClipRangeVF:
230
+ def __init__(self):
231
+ pass
232
+
233
+ def opt(self, trial):
234
+ return trial.suggest_float("clip_range_vf", 0.1, 0.3)
235
+
236
+ def default(self):
237
+ return random.random()
238
+
239
+
240
+ #####################################################################
241
+ ## NORMALIZE ADVANTAGE(normalize_advantage) ##
242
+ #####################################################################
243
+
244
+ class NormalizeAdvantage:
245
+ def __init__(self):
246
+ pass
247
+
248
+ def opt(self, trial):
249
+ return False
250
+
251
+ def default(self):
252
+ return True
253
+
254
+
255
+ #####################################################################
256
+ ## ENTROPY COEFFICIENT (ent_coef) ##
257
+ #####################################################################
258
+
259
+ class EntropyCoefficient:
260
+ def __init__(self):
261
+ pass
262
+
263
+ def opt(self, trial):
264
+ return trial.suggest_float("ent_coef", 0, 0.01)
265
+
266
+ def default(self):
267
+ return 0
268
+
269
+
270
+ #####################################################################
271
+ ## VALUE FUNCTION COEFFICIENT (vf_coef) ##
272
+ #####################################################################
273
+
274
+ class ValueFunctionCoefficient:
275
+ def __init__(self):
276
+ pass
277
+
278
+ def opt(self, trial):
279
+ return trial.suggest_float("vf_coef", 0.25, 0.75)
280
+
281
+ def default(self):
282
+ return 0.5
283
+
284
+ #####################################################################
285
+ ## MAXIMUM VALUE for Gradient Clipping (max_grad_norm) ##
286
+ #####################################################################
287
+
288
+ class MaxGradNorm:
289
+ def __init__(self):
290
+ pass
291
+
292
+ def opt(self, trial):
293
+ return trial.suggest_float("max_grad_norm", 0.3, 1)
294
+
295
+ def default(self):
296
+ return 0.5
297
+
298
+
299
+ #####################################################################
300
+ ## USE ? Generalized State Dependent Exploration ##
301
+ #####################################################################
302
+
303
+ class BoolGeneralizedStateDependentExploration:
304
+ def __init__(self):
305
+ pass
306
+
307
+ def opt(self, trial):
308
+ return False
309
+
310
+ def default(self):
311
+ return False
312
+
313
+
314
+ #####################################################################
315
+ ## SAMPLE NEW NOISE MATRIX(sde_sample_freq) ##
316
+ #####################################################################
317
+
318
+ class SDESampleFrequency:
319
+ def __init__(self):
320
+ pass
321
+
322
+ def opt(self, trial):
323
+ return -1
324
+
325
+ def default(self):
326
+ return -1
327
+
328
+
329
+ #####################################################################
330
+ ## LIMIT KL-Divergence (target_kl) ##
331
+ #####################################################################
332
+
333
+ class TargetKL:
334
+ def __init__(self):
335
+ pass
336
+
337
+ def opt(self, trial):
338
+ return trial.suggest_float("target_kl", 0.01, 0.05)
339
+
340
+ def default(self):
341
+ return None
342
+
343
+
344
+ #####################################################################
345
+ ## TENSORBOARD_LOG ##
346
+ #####################################################################
347
+
348
+ # class TensorBoardLog:
349
+ # def __init__(self):
350
+ # pass
351
+
352
+ # def opt(self, trial):
353
+ # return
354
+
355
+ # def default(self):
356
+ # return None
357
+
358
+
359
+ #####################################################################
360
+ ## POLICY_KWARGS (policy_kwargs) ##
361
+ #####################################################################
362
+
363
+ class PolicyKWargs:
364
+ def __init__(self):
365
+ pass
366
+
367
+ def opt(self, trial):
368
+ return None
369
+
370
+ def default(self):
371
+ return None
372
+
373
+
374
+ #####################################################################
375
+ ## SEED (seed) ##
376
+ #####################################################################
377
+
378
+ class Seed:
379
+ def __init__(self):
380
+ pass
381
+
382
+ def opt(self, trial):
383
+ return trial.suggest_int("seed", 1, 10)
384
+
385
+ def default(self):
386
+ return None
387
+
388
+
389
+ all_policy = [
390
+ "MlpPolicy",
391
+ "CnnPolicy",
392
+ "MultiInputPolicy",
393
+ ]
394
+
395
+ # ~!@ environment is fixed {maybe we can find stronger relations between hyperparameters across other environments}
396
+ # Very important idea
397
+
398
+
399
+ all_classes_in_this_file = [
400
+ 'BatchSize',
401
+ 'BiasVarianceTradeoff',
402
+ 'BoolGeneralizedStateDependentExploration',
403
+ 'ClipRange',
404
+ 'ClipRangeVF',
405
+ 'DiscountFactor',
406
+ 'EntropyCoefficient',
407
+ 'Learning_Rate_Scheduler',
408
+ 'MaxGradNorm',
409
+ 'MegaHandler',
410
+ 'NoOfEpochs',
411
+ 'NormalizeAdvantage',
412
+ 'PolicyKWargs',
413
+ 'PolicySelector',
414
+ 'SDESampleFrequency',
415
+ 'Seed',
416
+ 'StepsPerUpdate',
417
+ 'TargetKL',
418
+ 'TensorBoardLog',
419
+ 'ValueFunctionCoefficient'
420
+ ]
421
+
422
+ def request_next_HypConfig(env, tb_logs):
423
+ hyps = dict()
424
+
425
+ hyps["policy"] = PolicySelector().default()
426
+ hyps["env"] = env
427
+ hyps["learning_rate"] = Learning_Rate_Scheduler().default()
428
+ hyps["n_steps"] = StepsPerUpdate().default()
429
+ hyps["batch_size"] = BatchSize().default()
430
+ hyps["n_epochs"] = NoOfEpochs().default()
431
+ hyps["gamma"] = DiscountFactor().default()
432
+ hyps["gae_lambda"] = BiasVarianceTradeoff().default()
433
+ hyps["clip_range"] = ClipRange().default()
434
+ hyps["clip_range_vf"] = ClipRangeVF().default()
435
+ hyps["normalize_advantage"] = NormalizeAdvantage().default()
436
+ hyps["ent_coef"] = EntropyCoefficient().default()
437
+ hyps["vf_coef"] = ValueFunctionCoefficient().default()
438
+ hyps["max_grad_norm"] = MaxGradNorm().default()
439
+ hyps["use_sde"] = BoolGeneralizedStateDependentExploration().default()
440
+ hyps["sde_sample_freq"] = SDESampleFrequency().default()
441
+ hyps["target_kl"] = TargetKL().default()
442
+ hyps["tensorboard_log"] = tb_logs
443
+ hyps["policy_kwargs"] = PolicyKWargs().default()
444
+ hyps["verbose"] = 0
445
+ hyps["seed"] = Seed().default()
446
+ hyps["device"] = 'auto'
447
+ hyps["_init_setup_model"] = True
448
+
449
+ return hyps
450
+
451
+
452
+
453
+
454
+
455
+ #####################################################################
456
+ ## MEGA HANDLER (handler of all classes below) ##
457
+ #####################################################################
458
+ class MegaHandler:
459
+ def __init__(slef):
460
+ pass
461
+
462
+ def request_next_HypConfig(self, trial, env, tb_logs):
463
+ hyps = dict()
464
+
465
+ hyps["policy"] = PolicySelector().opt(trial)
466
+ hyps["env"] = env
467
+ hyps["learning_rate"] = Learning_Rate_Scheduler().opt(trial)
468
+ hyps["n_steps"] = StepsPerUpdate().opt(trial)
469
+ hyps["batch_size"] = BatchSize().opt(trial)
470
+ hyps["n_epochs"] = NoOfEpochs().opt(trial)
471
+ hyps["gamma"] = DiscountFactor().opt(trial)
472
+ hyps["gae_lambda"] = BiasVarianceTradeoff().opt(trial)
473
+ hyps["clip_range"] = ClipRange().opt(trial)
474
+ hyps["clip_range_vf"] = ClipRangeVF().opt(trial)
475
+ hyps["normalize_advantage"] = NormalizeAdvantage().opt(trial)
476
+ hyps["ent_coef"] = EntropyCoefficient().opt(trial)
477
+ hyps["vf_coef"] = ValueFunctionCoefficient().opt(trial)
478
+ hyps["max_grad_norm"] = MaxGradNorm().opt(trial)
479
+ hyps["use_sde"] = BoolGeneralizedStateDependentExploration().opt(trial)
480
+ hyps["sde_sample_freq"] = SDESampleFrequency().opt(trial)
481
+ hyps["target_kl"] = TargetKL().opt(trial)
482
+ hyps["tensorboard_log"] = tb_logs
483
+ hyps["policy_kwargs"] = PolicyKWargs().opt(trial)
484
+ hyps["verbose"] = 0
485
+ hyps["seed"] = 1
486
+ hyps["device"] = 'auto'
487
+ hyps["_init_setup_model"] = True
488
+
489
+ return hyps
Trainer.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import datetime
3
+ import gym
4
+ import json
5
+
6
+ from stable_baselines3 import PPO
7
+ import optuna
8
+
9
+ def check_json_exists(filename):
10
+ try:
11
+ open(filename, 'r')
12
+ except:
13
+ main = {
14
+ "env" : "RoadRunner-v0",
15
+ "algo" : "PPO",
16
+ "policy" : "MlpPolicy",
17
+ "counter" : 0,
18
+ }
19
+ with open(filename, "w") as f:
20
+ json.dump(main, f)
21
+
22
+ check_json_exists("previous_request.json")
23
+
24
+ class MegaTrainer:
25
+ def __init__(self, env_name, algo):
26
+ with open("previous_request.json", "r") as f:
27
+ self.data = json.loads(f.read())
28
+
29
+ self.env_name = env_name
30
+ self.algorithm = algo
31
+ self.counter = self.data["counter"] + 1
32
+
33
+ self.env = gym.make(self.env_name)
34
+ self.env.reset()
35
+
36
+ self.data["counter"] += 1
37
+ with open("previous_request.json", "w") as f:
38
+ json.dump(self.data, f)
39
+
40
+ def make_directories(self, models_dir, logdir):
41
+ if(not os.path.exists(models_dir)):
42
+ os.makedirs(models_dir)
43
+
44
+ if(not os.path.exists(logdir)):
45
+ os.makedirs(logdir)
46
+
47
+ def learn(self, timestep, iterations, hyps, directory, trial):
48
+ model_dir = f"model/{directory}/{self.counter}"
49
+ logdir = f"logs/{directory}"
50
+ self.make_directories(model_dir, logdir)
51
+
52
+ model = PPO(**hyps)
53
+
54
+ for i in range(1, iterations+1):
55
+ if(trial.should_prune()):
56
+ raise optuna.TrialPruned()
57
+ dt = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S-%f")
58
+ model.learn(total_timesteps=timestep, reset_num_timesteps=False, tb_log_name=str(self.counter))
59
+ model.save(model_dir+f"/{dt}_{timestep*i}")
60
+
61
+ return self.counter
62
+
63
+
64
+
65
+
66
+
67
+ if(__name__=="__main__"):
68
+ load_from_json("previous_request.json")
runner_trainer.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import plotly.offline as pyo
2
+
3
+ import logging
4
+ import sys
5
+
6
+ import optuna
7
+ from sklearn import model_selection
8
+
9
+ from scipy.stats import randint, uniform
10
+
11
+ import gym
12
+
13
+ from Trainer import *
14
+ from PPO_HypConfig import *
15
+ from Loader import *
16
+
17
+ all_optimizers =[
18
+ 'optuna',
19
+ 'sklearn'
20
+ ]
21
+
22
+ class Dummy:
23
+ def __init__(self):
24
+ pass
25
+
26
+ def fit(self):
27
+ pass
28
+
29
+ class OptunaTuner:
30
+ def __init__(self, env_name, algo, directory, optimizer, ts, iterations, n_trials, counter):
31
+ self.env_name = env_name
32
+ self.algorithm = algo
33
+ self.directory = directory
34
+ self.optimizer = optimizer
35
+ self.timestep = ts
36
+ self.iterations = iterations
37
+ self.n_trials = n_trials
38
+ self.exe_number = counter
39
+
40
+ def create_study_db(self):
41
+ optuna.logging.get_logger("optuna").addHandler(logging.StreamHandler(sys.stdout))
42
+ study_name = f"study-{self.exe_number}" # Unique identifier of the study.
43
+
44
+ storage_dir = f"logs/{self.directory}"
45
+ if(not os.path.exists(storage_dir)):
46
+ os.makedirs(storage_dir)
47
+ storage_name = f"sqlite:///{storage_dir}/{study_name}.db"
48
+
49
+ return study_name, storage_name
50
+
51
+ def select_pruner(self):
52
+ return None
53
+
54
+ def select_sampler(self):
55
+ return None
56
+
57
+ def study_loader(self):
58
+ study_name = f"study-{self.exe_number}" # Unique identifier of the study.
59
+ storage_dir = f"logs/{self.directory}"
60
+ storage_name = f"sqlite:///{storage_dir}/{study_name}.db"
61
+
62
+ study = optuna.load_study(
63
+ study_name=study_name,
64
+ storage=storage_name
65
+ )
66
+
67
+ trials_df = study.trials_dataframe()
68
+ print(trials_df.head())
69
+
70
+ return study
71
+
72
+ def study_summaries(self):
73
+ study_name = f"study-{self.exe_number}" # Unique identifier of the study.
74
+ storage_dir = f"logs/{self.directory}"
75
+ storage_name = f"sqlite:///{storage_dir}/{study_name}.db"
76
+
77
+ summary = optuna.get_all_study_summaries(
78
+ storage_name, include_best_trial=True
79
+ )
80
+ print(summary)
81
+ for i,j in enumerate(summary):
82
+ print(f"-----------STUDY-{i}-----------")
83
+ for attribute in [attr for attr in dir(j) if not attr.startswith('__')]:
84
+ if(attribute=="system_attrs" or attribute=="user_attrs"):
85
+ continue
86
+ print(attribute, ':', getattr(j, attribute))
87
+ print()
88
+ pass
89
+
90
+ def under_testing_py(self):
91
+ study = self.study_loader()
92
+ trial = study.ask()
93
+ try:
94
+ optuna.testing.objectives.fail_objective(trial)
95
+ except ValueError:
96
+ print("Objective function failed!")
97
+
98
+ ## To Prune
99
+ optuna.testing.objectives.pruned_objective(trial)
100
+
101
+ ## Dummy trial
102
+ study = optuna.testing.visualization.prepare_study_with_trials()
103
+
104
+ def under_terminators(self):
105
+
106
+ pass
107
+
108
+ def return_study(self, bool_store_study=True, bool_select_pruner=True, bool_select_sampler=True):
109
+ study_name, storage_name, selected_pruner, selected_sampler = [None] * 4
110
+ if(bool_store_study):
111
+ study_name, storage_name = self.create_study_db()
112
+
113
+ if(bool_select_pruner):
114
+ selected_pruner = self.select_pruner()
115
+
116
+ if(bool_select_sampler):
117
+ selected_sampler = self.select_sampler()
118
+
119
+ lie = storage_name is not None
120
+
121
+ study = optuna.create_study(
122
+ storage=storage_name,
123
+ sampler=selected_sampler,
124
+ pruner=selected_pruner,
125
+ study_name=study_name,
126
+ direction='maximize',
127
+ load_if_exists=lie,
128
+ directions=None
129
+ )
130
+ return study
131
+
132
+ def call_optuna(self, store_study=True):
133
+ study = self.return_study()
134
+ study.optimize(self.objective, n_trials=self.n_trials)
135
+
136
+ def objective(self, trial):
137
+ m = MegaTrainer(self.env_name, self.algorithm)
138
+ counter = m.learn(
139
+ self.timestep,
140
+ self.iterations,
141
+ MegaHandler().request_next_HypConfig(trial, m.env, f"logs/{self.directory}"),
142
+ self.directory,
143
+ trial=trial
144
+ )
145
+
146
+ m_load = MegaLoader(self.env_name, self.algorithm, self.directory)
147
+ return m_load.load(counter, self.n_trials)["total_return"]
148
+
149
+ def visul(self):
150
+ study = self.study_loader()
151
+ if(not "_optimization_history.py"):
152
+ pyo.plot(optuna.visualization.plot_optimization_history(study))
153
+
154
+ if(not "_timeline.py"):
155
+ pyo.plot(optuna.visualization.plot_timeline(study))
156
+
157
+ if(not "_slice.py"):
158
+ pyo.plot(optuna.visualization.plot_slice(study))
159
+
160
+ if(not "_pareto_front.py"): ## this is used for multi-objective study
161
+ pyo.plot(optuna.visualization.plot_pareto_front(study))
162
+
163
+ if(not "_param_importances.py"):
164
+ pyo.plot(optuna.visualization.plot_param_importances(study))
165
+
166
+ if(not "_parallel_coordinate.py"):
167
+ pyo.plot(optuna.visualization.plot_parallel_coordinate(study))
168
+
169
+ if(not "_intermediate_values.py"):
170
+ pyo.plot(optuna.visualization.plot_intermediate_values(study))
171
+
172
+ if(not "_edf.py"):
173
+ pyo.plot(optuna.visualization.plot_edf(study))
174
+
175
+ if(not "_contour.py"):
176
+ pyo.plot(optuna.visualization.plot_contour(study))
177
+
178
+ class HyperPilotRL:
179
+ def __init__(self, env_name, algo, optimizer, timesteps, iterations, n_trials, counter):
180
+ self.env_name = env_name
181
+ self.algorithm = algo
182
+ self.directory = f"{optimizer}/{counter}/{env_name}/{algo}"
183
+ self.optimizer = optimizer
184
+ self.timestep = timesteps
185
+ self.iterations = iterations
186
+ self.n_trials = n_trials
187
+ self.execution_number = counter
188
+
189
+ if(self.optimizer == "optuna"):
190
+ o = OptunaTuner(env_name, algo, self.directory, optimizer, timesteps, iterations, n_trials, counter)
191
+ o.call_optuna()
192
+ o.study_summaries()
193
+ # o.visul()
194
+ elif(self.optimizer == "default"):
195
+ pass
196
+
197
+ else:
198
+ raise NameError("Enter optimizer is not supported.\nAvailable optimizers are", all_optimizers)
199
+
200
+ ## optimizer = ['optuna']
201
+
202
+ def learning_curve():
203
+ pass
204
+
205
+ def cutoff_learn_according_to_max_time_allocation():
206
+ pass
207
+
208
+ if(__name__=="__main__"):
209
+ h = HyperPilotRL(
210
+ "CartPole-v1",
211
+ "PPO",
212
+ "optuna",
213
+ timesteps=1000,
214
+ iterations=100,
215
+ n_trials=10,
216
+ counter=102644
217
+ )
218
+
219
+