-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
178 lines (161 loc) · 6.04 KB
/
train.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
import argparse
import datetime
import os
import ipdb
import numpy as np
import wandb
import yaml
import time
from gcbfplus.algo import make_algo
from gcbfplus.env import make_env
from gcbfplus.trainer.trainer import Trainer
from gcbfplus.trainer.utils import is_connected
def train(args):
print(f"> Running train.py {args}")
# set up environment variables and seed
os.environ["XLA_PYTHON_CLIENT_PREALLOCATE"] = "false"
if not is_connected():
os.environ["WANDB_MODE"] = "offline"
np.random.seed(args.seed)
if args.debug:
os.environ["WANDB_MODE"] = "disabled"
os.environ["JAX_DISABLE_JIT"] = "True"
# create environments
env = make_env(
env_id=args.env,
num_agents=args.num_agents,
num_obs=args.obs,
n_rays=args.n_rays,
area_size=args.area_size,
use_connect=args.use_connect,
reconfig_connect=args.reconfig_connect,
use_leader=args.use_leader
)
env_test = make_env(
env_id=args.env,
num_agents=args.num_agents,
num_obs=args.obs,
n_rays=args.n_rays,
area_size=args.area_size,
use_connect=args.use_connect,
reconfig_connect=args.reconfig_connect,
use_leader=args.use_leader
)
# create low level controller
algo = make_algo(
algo=args.algo,
env=env,
node_dim=env.node_dim,
edge_dim=env.edge_dim,
state_dim=env.state_dim,
action_dim=env.action_dim,
n_agents=env.num_agents,
gnn_layers=args.gnn_layers,
batch_size=256,
buffer_size=args.buffer_size,
horizon=args.horizon,
lr_actor=args.lr_actor,
lr_cbf=args.lr_cbf,
alpha=args.alpha,
eps=0.02,
inner_epoch=8,
loss_action_coef=args.loss_action_coef,
loss_unsafe_coef=args.loss_unsafe_coef,
loss_safe_coef=args.loss_safe_coef,
loss_h_dot_coef=args.loss_h_dot_coef,
max_grad_norm=2.0,
seed=args.seed,
dim_factor=args.dim_factor,
)
# set up logger
time.sleep(np.random.randint(0, 10))
time.sleep(np.random.random())
start_time = datetime.datetime.now()
start_time = start_time.strftime("%Y%m%d%H%M%S")
if not os.path.exists(args.log_dir):
os.makedirs(args.log_dir)
if not os.path.exists(f"{args.log_dir}/{args.env}"):
os.makedirs(f"{args.log_dir}/{args.env}")
if not os.path.exists(f"{args.log_dir}/{args.env}/{args.algo}"):
os.makedirs(f"{args.log_dir}/{args.env}/{args.algo}")
while True:
try:
start_time = datetime.datetime.now()
start_time = start_time.strftime("%Y%m%d%H%M%S")
os.makedirs(f"{args.log_dir}/{args.env}/{args.algo}/seed{args.seed}_{start_time}")
break
except:
time.sleep(np.random.randint(0, 10))
time.sleep(np.random.random())
log_dir = f"{args.log_dir}/{args.env}/{args.algo}/seed{args.seed}_{start_time}"
run_name = f"{args.algo}_{args.env}_{start_time}" if args.name is None else args.name
print('Saving log in directory: ', log_dir)
# get training parameters
train_params = {
"run_name": run_name,
"training_steps": args.steps,
"eval_interval": args.eval_interval,
"eval_epi": args.eval_epi,
"save_interval": args.save_interval,
}
# create trainer
trainer = Trainer(
env=env,
env_test=env_test,
algo=algo,
log_dir=log_dir,
n_env_train=args.n_env_train,
n_env_test=args.n_env_test,
seed=args.seed,
params=train_params,
save_log=not args.debug,
)
# save config
wandb.config.update(args)
wandb.config.update(algo.config)
if not args.debug:
with open(f"{log_dir}/config.yaml", "w") as f:
yaml.dump(args, f)
yaml.dump(algo.config, f)
# start training
trainer.train()
def main():
parser = argparse.ArgumentParser()
# custom arguments
parser.add_argument("-n", "--num-agents", type=int, default=8)
parser.add_argument("--algo", type=str, default="gcbf+")
parser.add_argument("--env", type=str, default="SimpleCar")
parser.add_argument("--seed", type=int, default=0)
parser.add_argument("--steps", type=int, default=1000)
parser.add_argument("--name", type=str, default=None)
parser.add_argument("--debug", action="store_true", default=False)
parser.add_argument("--obs", type=int, default=None)
parser.add_argument("--n-rays", type=int, default=32)
parser.add_argument("--area-size", type=float, required=True)
# gcbf / gcbf+ arguments
parser.add_argument("--gnn-layers", type=int, default=1)
parser.add_argument("--alpha", type=float, default=1.0)
parser.add_argument("--horizon", type=int, default=32)
parser.add_argument("--lr-actor", type=float, default=3e-5)
parser.add_argument("--lr-cbf", type=float, default=3e-5)
parser.add_argument("--loss-action-coef", type=float, default=0.0001)
parser.add_argument("--loss-unsafe-coef", type=float, default=1.0)
parser.add_argument("--loss-safe-coef", type=float, default=1.0)
parser.add_argument("--loss-h-dot-coef", type=float, default=0.01)
parser.add_argument("--buffer-size", type=int, default=512)
# default arguments
parser.add_argument("--n-env-train", type=int, default=16)
parser.add_argument("--n-env-test", type=int, default=32)
parser.add_argument("--log-dir", type=str, default="./logs")
parser.add_argument("--eval-interval", type=int, default=1)
parser.add_argument("--eval-epi", type=int, default=1)
parser.add_argument("--save-interval", type=int, default=100)
parser.add_argument("--use_connect", action="store_true", default=False)
parser.add_argument("--reconfig_connect", action="store_true", default=False)
parser.add_argument("--use_leader", action="store_true", default=False)
parser.add_argument("--dim_factor", type=int, default=2)
args = parser.parse_args()
train(args)
if __name__ == "__main__":
# with ipdb.launch_ipdb_on_exception():
main()