-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathmain.py
517 lines (441 loc) · 18.4 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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
"""
Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the CC BY-NC license found in the
LICENSE.md file in the root directory of this source tree.
"""
from torch.utils.tensorboard import SummaryWriter
import argparse
import pickle
import random
import time
import gym
import d4rl
import torch
import numpy as np
import utils
from replay_buffer import ReplayBuffer
from lamb import Lamb
from stable_baselines3.common.vec_env import SubprocVecEnv
from pathlib import Path
from data import create_dataloader
from decision_transformer.models.decision_transformer import DecisionTransformer
from evaluation import create_vec_eval_episodes_fn, vec_evaluate_episode_rtg
from trainer import SequenceTrainer
from logger import Logger
MAX_EPISODE_LEN = 1000
class Experiment:
def __init__(self, variant):
self.state_dim, self.act_dim, self.action_range = self._get_env_spec(variant)
self.offline_trajs, self.state_mean, self.state_std = self._load_dataset(
variant["env"]
)
# initialize by offline trajs
self.replay_buffer = ReplayBuffer(variant["replay_size"], self.offline_trajs)
self.aug_trajs = []
self.device = variant.get("device", "cuda")
self.target_entropy = -self.act_dim
self.model = DecisionTransformer(
state_dim=self.state_dim,
act_dim=self.act_dim,
action_range=self.action_range,
max_length=variant["K"],
eval_context_length=variant["eval_context_length"],
max_ep_len=MAX_EPISODE_LEN,
hidden_size=variant["embed_dim"],
n_layer=variant["n_layer"],
n_head=variant["n_head"],
n_inner=4 * variant["embed_dim"],
activation_function=variant["activation_function"],
n_positions=1024,
resid_pdrop=variant["dropout"],
attn_pdrop=variant["dropout"],
stochastic_policy=True,
ordering=variant["ordering"],
init_temperature=variant["init_temperature"],
target_entropy=self.target_entropy,
).to(device=self.device)
self.optimizer = Lamb(
self.model.parameters(),
lr=variant["learning_rate"],
weight_decay=variant["weight_decay"],
eps=1e-8,
)
self.scheduler = torch.optim.lr_scheduler.LambdaLR(
self.optimizer, lambda steps: min((steps + 1) / variant["warmup_steps"], 1)
)
self.log_temperature_optimizer = torch.optim.Adam(
[self.model.log_temperature],
lr=1e-4,
betas=[0.9, 0.999],
)
# track the training progress and
# training/evaluation/online performance in all the iterations
self.pretrain_iter = 0
self.online_iter = 0
self.total_transitions_sampled = 0
self.variant = variant
self.reward_scale = 1.0 if "antmaze" in variant["env"] else 0.001
self.logger = Logger(variant)
def _get_env_spec(self, variant):
env = gym.make(variant["env"])
state_dim = env.observation_space.shape[0]
act_dim = env.action_space.shape[0]
action_range = [
float(env.action_space.low.min()) + 1e-6,
float(env.action_space.high.max()) - 1e-6,
]
env.close()
return state_dim, act_dim, action_range
def _save_model(self, path_prefix, is_pretrain_model=False):
to_save = {
"model_state_dict": self.model.state_dict(),
"optimizer_state_dict": self.optimizer.state_dict(),
"scheduler_state_dict": self.scheduler.state_dict(),
"pretrain_iter": self.pretrain_iter,
"online_iter": self.online_iter,
"args": self.variant,
"total_transitions_sampled": self.total_transitions_sampled,
"np": np.random.get_state(),
"python": random.getstate(),
"pytorch": torch.get_rng_state(),
"log_temperature_optimizer_state_dict": self.log_temperature_optimizer.state_dict(),
}
with open(f"{path_prefix}/model.pt", "wb") as f:
torch.save(to_save, f)
print(f"\nModel saved at {path_prefix}/model.pt")
if is_pretrain_model:
with open(f"{path_prefix}/pretrain_model.pt", "wb") as f:
torch.save(to_save, f)
print(f"Model saved at {path_prefix}/pretrain_model.pt")
def _load_model(self, path_prefix):
if Path(f"{path_prefix}/model.pt").exists():
with open(f"{path_prefix}/model.pt", "rb") as f:
checkpoint = torch.load(f)
self.model.load_state_dict(checkpoint["model_state_dict"])
self.optimizer.load_state_dict(checkpoint["optimizer_state_dict"])
self.scheduler.load_state_dict(checkpoint["scheduler_state_dict"])
self.log_temperature_optimizer.load_state_dict(
checkpoint["log_temperature_optimizer_state_dict"]
)
self.pretrain_iter = checkpoint["pretrain_iter"]
self.online_iter = checkpoint["online_iter"]
self.total_transitions_sampled = checkpoint["total_transitions_sampled"]
np.random.set_state(checkpoint["np"])
random.setstate(checkpoint["python"])
torch.set_rng_state(checkpoint["pytorch"])
print(f"Model loaded at {path_prefix}/model.pt")
def _load_dataset(self, env_name):
dataset_path = f"./data/{env_name}.pkl"
with open(dataset_path, "rb") as f:
trajectories = pickle.load(f)
states, traj_lens, returns = [], [], []
for path in trajectories:
states.append(path["observations"])
traj_lens.append(len(path["observations"]))
returns.append(path["rewards"].sum())
traj_lens, returns = np.array(traj_lens), np.array(returns)
# used for input normalization
states = np.concatenate(states, axis=0)
state_mean, state_std = np.mean(states, axis=0), np.std(states, axis=0) + 1e-6
num_timesteps = sum(traj_lens)
print("=" * 50)
print(f"Starting new experiment: {env_name}")
print(f"{len(traj_lens)} trajectories, {num_timesteps} timesteps found")
print(f"Average return: {np.mean(returns):.2f}, std: {np.std(returns):.2f}")
print(f"Max return: {np.max(returns):.2f}, min: {np.min(returns):.2f}")
print(f"Average length: {np.mean(traj_lens):.2f}, std: {np.std(traj_lens):.2f}")
print(f"Max length: {np.max(traj_lens):.2f}, min: {np.min(traj_lens):.2f}")
print("=" * 50)
sorted_inds = np.argsort(returns) # lowest to highest
num_trajectories = 1
timesteps = traj_lens[sorted_inds[-1]]
ind = len(trajectories) - 2
while ind >= 0 and timesteps + traj_lens[sorted_inds[ind]] < num_timesteps:
timesteps += traj_lens[sorted_inds[ind]]
num_trajectories += 1
ind -= 1
sorted_inds = sorted_inds[-num_trajectories:]
trajectories = [trajectories[ii] for ii in sorted_inds]
return trajectories, state_mean, state_std
def _augment_trajectories(
self,
online_envs,
target_explore,
n,
randomized=False,
):
max_ep_len = MAX_EPISODE_LEN
with torch.no_grad():
# generate init state
target_return = [target_explore * self.reward_scale] * online_envs.num_envs
returns, lengths, trajs = vec_evaluate_episode_rtg(
online_envs,
self.state_dim,
self.act_dim,
self.model,
max_ep_len=max_ep_len,
reward_scale=self.reward_scale,
target_return=target_return,
mode="normal",
state_mean=self.state_mean,
state_std=self.state_std,
device=self.device,
use_mean=False,
)
self.replay_buffer.add_new_trajs(trajs)
self.aug_trajs += trajs
self.total_transitions_sampled += np.sum(lengths)
return {
"aug_traj/return": np.mean(returns),
"aug_traj/length": np.mean(lengths),
}
def pretrain(self, eval_envs, loss_fn):
print("\n\n\n*** Pretrain ***")
eval_fns = [
create_vec_eval_episodes_fn(
vec_env=eval_envs,
eval_rtg=self.variant["eval_rtg"],
state_dim=self.state_dim,
act_dim=self.act_dim,
state_mean=self.state_mean,
state_std=self.state_std,
device=self.device,
use_mean=True,
reward_scale=self.reward_scale,
)
]
trainer = SequenceTrainer(
model=self.model,
optimizer=self.optimizer,
log_temperature_optimizer=self.log_temperature_optimizer,
scheduler=self.scheduler,
device=self.device,
)
writer = (
SummaryWriter(self.logger.log_path) if self.variant["log_to_tb"] else None
)
while self.pretrain_iter < self.variant["max_pretrain_iters"]:
# in every iteration, prepare the data loader
dataloader = create_dataloader(
trajectories=self.offline_trajs,
num_iters=self.variant["num_updates_per_pretrain_iter"],
batch_size=self.variant["batch_size"],
max_len=self.variant["K"],
state_dim=self.state_dim,
act_dim=self.act_dim,
state_mean=self.state_mean,
state_std=self.state_std,
reward_scale=self.reward_scale,
action_range=self.action_range,
)
train_outputs = trainer.train_iteration(
loss_fn=loss_fn,
dataloader=dataloader,
)
eval_outputs, eval_reward = self.evaluate(eval_fns)
outputs = {"time/total": time.time() - self.start_time}
outputs.update(train_outputs)
outputs.update(eval_outputs)
self.logger.log_metrics(
outputs,
iter_num=self.pretrain_iter,
total_transitions_sampled=self.total_transitions_sampled,
writer=writer,
)
self._save_model(
path_prefix=self.logger.log_path,
is_pretrain_model=True,
)
self.pretrain_iter += 1
def evaluate(self, eval_fns):
eval_start = time.time()
self.model.eval()
outputs = {}
for eval_fn in eval_fns:
o = eval_fn(self.model)
outputs.update(o)
outputs["time/evaluation"] = time.time() - eval_start
eval_reward = outputs["evaluation/return_mean_gm"]
return outputs, eval_reward
def online_tuning(self, online_envs, eval_envs, loss_fn):
print("\n\n\n*** Online Finetuning ***")
trainer = SequenceTrainer(
model=self.model,
optimizer=self.optimizer,
log_temperature_optimizer=self.log_temperature_optimizer,
scheduler=self.scheduler,
device=self.device,
)
eval_fns = [
create_vec_eval_episodes_fn(
vec_env=eval_envs,
eval_rtg=self.variant["eval_rtg"],
state_dim=self.state_dim,
act_dim=self.act_dim,
state_mean=self.state_mean,
state_std=self.state_std,
device=self.device,
use_mean=True,
reward_scale=self.reward_scale,
)
]
writer = (
SummaryWriter(self.logger.log_path) if self.variant["log_to_tb"] else None
)
while self.online_iter < self.variant["max_online_iters"]:
outputs = {}
augment_outputs = self._augment_trajectories(
online_envs,
self.variant["online_rtg"],
n=self.variant["num_online_rollouts"],
)
outputs.update(augment_outputs)
dataloader = create_dataloader(
trajectories=self.replay_buffer.trajectories,
num_iters=self.variant["num_updates_per_online_iter"],
batch_size=self.variant["batch_size"],
max_len=self.variant["K"],
state_dim=self.state_dim,
act_dim=self.act_dim,
state_mean=self.state_mean,
state_std=self.state_std,
reward_scale=self.reward_scale,
action_range=self.action_range,
)
# finetuning
is_last_iter = self.online_iter == self.variant["max_online_iters"] - 1
if (self.online_iter + 1) % self.variant[
"eval_interval"
] == 0 or is_last_iter:
evaluation = True
else:
evaluation = False
train_outputs = trainer.train_iteration(
loss_fn=loss_fn,
dataloader=dataloader,
)
outputs.update(train_outputs)
if evaluation:
eval_outputs, eval_reward = self.evaluate(eval_fns)
outputs.update(eval_outputs)
outputs["time/total"] = time.time() - self.start_time
# log the metrics
self.logger.log_metrics(
outputs,
iter_num=self.pretrain_iter + self.online_iter,
total_transitions_sampled=self.total_transitions_sampled,
writer=writer,
)
self._save_model(
path_prefix=self.logger.log_path,
is_pretrain_model=False,
)
self.online_iter += 1
def __call__(self):
utils.set_seed_everywhere(args.seed)
import d4rl
def loss_fn(
a_hat_dist,
a,
attention_mask,
entropy_reg,
):
# a_hat is a SquashedNormal Distribution
log_likelihood = a_hat_dist.log_likelihood(a)[attention_mask > 0].mean()
entropy = a_hat_dist.entropy().mean()
loss = -(log_likelihood + entropy_reg * entropy)
return (
loss,
-log_likelihood,
entropy,
)
def get_env_builder(seed, env_name, target_goal=None):
def make_env_fn():
import d4rl
env = gym.make(env_name)
env.seed(seed)
if hasattr(env.env, "wrapped_env"):
env.env.wrapped_env.seed(seed)
elif hasattr(env.env, "seed"):
env.env.seed(seed)
else:
pass
env.action_space.seed(seed)
env.observation_space.seed(seed)
if target_goal:
env.set_target_goal(target_goal)
print(f"Set the target goal to be {env.target_goal}")
return env
return make_env_fn
print("\n\nMaking Eval Env.....")
env_name = self.variant["env"]
if "antmaze" in env_name:
env = gym.make(env_name)
target_goal = env.target_goal
env.close()
print(f"Generated the fixed target goal: {target_goal}")
else:
target_goal = None
eval_envs = SubprocVecEnv(
[
get_env_builder(i, env_name=env_name, target_goal=target_goal)
for i in range(self.variant["num_eval_episodes"])
]
)
self.start_time = time.time()
if self.variant["max_pretrain_iters"]:
self.pretrain(eval_envs, loss_fn)
if self.variant["max_online_iters"]:
print("\n\nMaking Online Env.....")
online_envs = SubprocVecEnv(
[
get_env_builder(i + 100, env_name=env_name, target_goal=target_goal)
for i in range(self.variant["num_online_rollouts"])
]
)
self.online_tuning(online_envs, eval_envs, loss_fn)
online_envs.close()
eval_envs.close()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--seed", type=int, default=10)
parser.add_argument("--env", type=str, default="hopper-medium-v2")
# model options
parser.add_argument("--K", type=int, default=20)
parser.add_argument("--embed_dim", type=int, default=512)
parser.add_argument("--n_layer", type=int, default=4)
parser.add_argument("--n_head", type=int, default=4)
parser.add_argument("--activation_function", type=str, default="relu")
parser.add_argument("--dropout", type=float, default=0.1)
parser.add_argument("--eval_context_length", type=int, default=5)
# 0: no pos embedding others: absolute ordering
parser.add_argument("--ordering", type=int, default=0)
# shared evaluation options
parser.add_argument("--eval_rtg", type=int, default=3600)
parser.add_argument("--num_eval_episodes", type=int, default=10)
# shared training options
parser.add_argument("--init_temperature", type=float, default=0.1)
parser.add_argument("--batch_size", type=int, default=256)
parser.add_argument("--learning_rate", "-lr", type=float, default=1e-4)
parser.add_argument("--weight_decay", "-wd", type=float, default=5e-4)
parser.add_argument("--warmup_steps", type=int, default=10000)
# pretraining options
parser.add_argument("--max_pretrain_iters", type=int, default=1)
parser.add_argument("--num_updates_per_pretrain_iter", type=int, default=5000)
# finetuning options
parser.add_argument("--max_online_iters", type=int, default=1500)
parser.add_argument("--online_rtg", type=int, default=7200)
parser.add_argument("--num_online_rollouts", type=int, default=1)
parser.add_argument("--replay_size", type=int, default=1000)
parser.add_argument("--num_updates_per_online_iter", type=int, default=300)
parser.add_argument("--eval_interval", type=int, default=10)
# environment options
parser.add_argument("--device", type=str, default="cuda")
parser.add_argument("--log_to_tb", "-w", type=bool, default=True)
parser.add_argument("--save_dir", type=str, default="./exp")
parser.add_argument("--exp_name", type=str, default="default")
args = parser.parse_args()
utils.set_seed_everywhere(args.seed)
experiment = Experiment(vars(args))
print("=" * 50)
experiment()