-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain_agent.py
401 lines (341 loc) · 14.8 KB
/
train_agent.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
# general imports
import torch as th
import yaml
import numpy as np
import random
import os
import pickle
# training imports
import wandb
from rl_zoo3.utils import linear_schedule
from skill_models import *
from stable_baselines3.common.env_util import make_atari_env
from stable_baselines3.common.vec_env import VecFrameStack, VecTransposeImage
from feature_extractors import LinearConcatExtractor, FixedLinearConcatExtractor, \
CNNConcatExtractor, CombineExtractor, \
DotProductAttentionExtractor, WeightSharingAttentionExtractor, \
ReservoirConcatExtractor
from stable_baselines3.common.callbacks import EvalCallback, StopTrainingOnRewardThreshold, \
StopTrainingOnNoModelImprovement
from wandb.integration.sb3 import WandbCallback
import tensorflow as tf
# utility imports
from utils.args import parse_args
from stable_baselines3 import DQN, PPO
# use this instead of classical PPO in case you want to use the custom PPO implementation with attention weights entropy loss, eventually change the coefficient
#from utils.custom_ppo import PPO
# ---------------------------------- MAIN ----------------------------------
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1' # ignore tensorflow warnings about CPU
args = parse_args()
seed = None
if args.seed is not None:
seed = args.seed
tf.random.set_seed(seed)
np.random.seed(seed)
random.seed(seed)
skilled_agent = args.use_skill == "True"
alg = args.alg
tb_log_name = alg if not skilled_agent else "S" + alg
debug = args.debug == "True"
device = f"cuda:{args.device}" if args.device != "cpu" else "cpu"
if not torch.cuda.is_available() and device != "cpu":
print("CUDA not available, using CPU")
device = "cpu"
env = args.env.lower()
env_name = args.env
if alg == "DQN":
with open("configs/atari_dqn.yaml", 'r') as file:
config = yaml.safe_load(file)["config"]
else:
with open(f'configs/{env}.yaml', 'r') as file:
config = yaml.safe_load(file)["config"]
if "_" in env_name:
env_name = env_name.replace("_", "")
config["f_ext_kwargs"]["device"] = device #do not comment this, it is the parameter passed to the feature extractor
config["game"] = env_name
config["net_arch_pi"] = args.pi
config["net_arch_vf"] = args.vf
expert = args.use_expert == "True"
version = "3-5 entropy" # change for future experiments
tags = [f'game:{config["game"]}', f'version:{version}', f'seed:{seed}', f'alg:{alg}']
string = "pi:"
for el in config["net_arch_pi"]:
string += str(el) + "-"
tags.append(string)
string = "vf:"
for el in config["net_arch_vf"]:
string += str(el) + "-"
tags.append(string)
game_id = env_name + "NoFrameskip-v4"
logdir = "./tensorboard_logs"
gamelogs = f"{logdir}/{env_name}"
if not os.path.exists(logdir):
os.makedirs(logdir)
if not os.path.exists(gamelogs):
os.makedirs(gamelogs)
vec_env = make_atari_env(game_id, n_envs=config["n_envs"], seed=seed)
vec_env = VecFrameStack(vec_env, n_stack=config["n_stacks"])
vec_env = VecTransposeImage(vec_env)
skills = []
skills.append(get_state_rep_uns(env_name, device, expert=expert))
skills.append(get_object_keypoints_encoder(env_name, device, load_only_model=True, expert=expert))
skills.append(get_object_keypoints_keynet(env_name, device, load_only_model=True, expert=expert))
skills.append(get_video_object_segmentation(env_name, device, load_only_model=True, expert=expert))
# skills.append(get_autoencoder(env_name, device, expert=expert)) # autoencoder skill used also in attention mechanism extractors as context
# skills.append(get_image_completion(env_name, device, expert=expert))
# skills.append(get_frame_prediction(env_name, device, expert=expert))
f_ext_kwargs = config["f_ext_kwargs"]
sample_obs = vec_env.observation_space.sample()
sample_obs = torch.tensor(sample_obs).to(device)
sample_obs = sample_obs.unsqueeze(0)
# print("sample obs shape", sample_obs.shape)
features_dim = 256
if skilled_agent:
tags.append(f'ext:{args.extractor}')
if args.extractor == "lin_concat_ext":
config["f_ext_name"] = "lin_concat_ext"
config["f_ext_class"] = LinearConcatExtractor
tb_log_name += "_lin"
ext = LinearConcatExtractor(observation_space=vec_env.observation_space, skills=skills, device=device)
features_dim = ext.get_dimension(sample_obs)
if args.extractor == "fixed_lin_concat_ext":
config["f_ext_name"] = "fixed_lin_concat_ext"
config["f_ext_class"] = FixedLinearConcatExtractor
f_ext_kwargs["fixed_dim"] = args.fd
tags.append(f"fixed_dim:{f_ext_kwargs['fixed_dim']}")
tb_log_name += "_fixedlin"
ext = FixedLinearConcatExtractor(observation_space=vec_env.observation_space, skills=skills, device=device,
fixed_dim=f_ext_kwargs["fixed_dim"])
features_dim = ext.get_dimension(sample_obs)
if args.extractor == "cnn_concat_ext":
config["f_ext_name"] = "cnn_concat_ext"
config["f_ext_class"] = CNNConcatExtractor
f_ext_kwargs["num_conv_layers"] = args.cv
tb_log_name += "_cnn"
ext = CNNConcatExtractor(vec_env.observation_space, skills=skills, device=device)
features_dim = ext.get_dimension(sample_obs)
tags.append(f"cnn_layers:{args.cv}")
if args.extractor == "combine_ext":
config["f_ext_name"] = "combine_ext"
config["f_ext_class"] = CombineExtractor
f_ext_kwargs["num_linear_skills"] = 1
tb_log_name += "_comb"
ext = CombineExtractor(vec_env.observation_space, skills=skills, device=device,
num_linear_skills=f_ext_kwargs["num_linear_skills"])
features_dim = ext.get_dimension(sample_obs)
if args.extractor == "dotproduct_attention_ext":
config["f_ext_name"] = "dotproduct_attention_ext"
config["f_ext_class"] = DotProductAttentionExtractor
features_dim = args.fd
tb_log_name += "_dpae"
f_ext_kwargs["game"] = env_name
f_ext_kwargs["expert"] = expert
tags.append(f"fixed_dim:{features_dim}")
if args.extractor == "wsharing_attention_ext":
config["f_ext_name"] = "wsharing_attention_ext"
config["f_ext_class"] = WeightSharingAttentionExtractor
features_dim = args.fd
tb_log_name += "_wsae"
f_ext_kwargs["game"] = env_name
f_ext_kwargs["expert"] = expert
tags.append(f"fixed_dim:{features_dim}")
if args.extractor == "reservoir_concat_ext":
config["f_ext_name"] = "reservoir_concat_ext"
config["f_ext_class"] = ReservoirConcatExtractor
tb_log_name += "_reservoir"
max_batch_size = max(config["net_arch_pi"][0], config["net_arch_vf"][0])
f_ext_kwargs["max_batch_size"] = max_batch_size
# dato che concateno le skill come nel linear, uso LinearConcatExt per prendere la dimensione
ext = LinearConcatExtractor(vec_env.observation_space, skills=skills, device=device)
input_features_dim = ext.get_dimension(sample_obs)
reservoir_output_dim = args.ro # output dimension of the reservoir WARNING: if it is too big memory error
features_dim = reservoir_output_dim
f_ext_kwargs["input_features_dim"] = input_features_dim
tags.append(f"res_size:{args.ro}")
f_ext_kwargs["skills"] = skills
f_ext_kwargs["features_dim"] = features_dim
if skilled_agent:
if alg == "PPO":
policy_kwargs = dict(
features_extractor_class=config["f_ext_class"],
features_extractor_kwargs=f_ext_kwargs,
net_arch={
'pi': config["net_arch_pi"],
'vf': config["net_arch_vf"]
},
#activation_fn=th.nn.ReLU, # use ReLU in case of multiple layers for the policy learning network
)
if alg == "DQN":
policy_kwargs = dict(
features_extractor_class=config["f_ext_class"],
features_extractor_kwargs=f_ext_kwargs,
)
else:
policy_kwargs = None
if debug:
if alg == "PPO":
model = PPO("CnnPolicy",
vec_env,
learning_rate=linear_schedule(config["learning_rate"]),
n_steps=128,
n_epochs=4,
batch_size=config["batch_size"],
clip_range=linear_schedule(config["clip_range"]),
normalize_advantage=config["normalize"],
ent_coef=config["ent_coef"],
vf_coef=config["vf_coef"],
policy_kwargs=policy_kwargs,
verbose=0,
device=device,
)
if alg == "DQN":
model = DQN("CnnPolicy",
vec_env,
buffer_size=config["buffer_size"],
learning_rate=config["learning_rate"],
batch_size=config["batch_size"],
learning_starts=config["learning_starts"],
target_update_interval=config["target_update_interval"],
train_freq=config["train_freq"],
gradient_steps=config["gradient_steps"],
exploration_fraction=config["exploration_fraction"],
exploration_final_eps=config["exploration_final_eps"],
optimize_memory_usage=config["optimize_memory_usage"],
policy_kwargs=policy_kwargs,
verbose=0,
device=device,
)
model.learn(1000)
else:
run = wandb.init(
project="sb3-skillcomp",
config=config,
sync_tensorboard=True, # auto-upload sb3's tensorboard metrics
monitor_gym=True, # auto-upload the videos of agents playing the game
name=f"{config['f_ext_name']}__{config['game']}",
group=f"{config['game']}",
tags=tags
# save_code = True, # optional
)
vec_env = make_atari_env(game_id, n_envs=config["n_envs"], monitor_dir=f"monitor/{run.id}")
vec_env = VecFrameStack(vec_env, n_stack=config["n_stacks"])
vec_env = VecTransposeImage(vec_env)
vec_eval_env = make_atari_env(game_id, n_envs=config["n_envs"])
vec_eval_env = VecFrameStack(vec_eval_env, n_stack=config["n_stacks"])
vec_eval_env = VecTransposeImage(vec_eval_env)
if alg == "PPO":
model = PPO("CnnPolicy",
vec_env,
learning_rate=linear_schedule(config["learning_rate"]),
n_steps=128,
n_epochs=4,
batch_size=config["batch_size"],
clip_range=linear_schedule(config["clip_range"]),
normalize_advantage=config["normalize"],
ent_coef=config["ent_coef"],
vf_coef=config["vf_coef"],
policy_kwargs=policy_kwargs,
tensorboard_log=gamelogs,
verbose=0,
device=device,
)
if alg == "DQN":
model = DQN("CnnPolicy",
vec_env,
buffer_size=config["buffer_size"],
learning_rate=config["learning_rate"],
batch_size=config["batch_size"],
learning_starts=config["learning_starts"],
target_update_interval=config["target_update_interval"],
train_freq=config["train_freq"],
gradient_steps=config["gradient_steps"],
exploration_fraction=config["exploration_fraction"],
exploration_final_eps=config["exploration_final_eps"],
optimize_memory_usage=config["optimize_memory_usage"],
policy_kwargs=policy_kwargs,
tensorboard_log=gamelogs,
verbose=0,
device=device,
)
# model.learn(config["n_timesteps"], tb_log_name=tb_log_name)
#stop_train_callback = StopTrainingOnNoModelImprovement(max_no_improvement_evals=5, min_evals=5, verbose=0)
# if env_name == "Pong":
# if not skilled_agent:
# eval_callback = EvalCallback(
# vec_eval_env,
# n_eval_episodes=10,
# best_model_save_path=f"models/{run.id}",
# log_path=gamelogs,
# eval_freq=5000 * config["n_envs"],
# verbose=0
# )
# else:
# callback_on_best = StopTrainingOnRewardThreshold(reward_threshold=21, verbose=0)
# eval_callback = EvalCallback(
# vec_eval_env,
# n_eval_episodes=10,
# best_model_save_path=f"models/{run.id}",
# log_path=gamelogs,
# eval_freq=5000 * config["n_envs"],
# callback_on_new_best=callback_on_best,
# callback_after_eval=stop_train_callback,
# verbose=0
#
# )
# else:
# if not skilled_agent:
# eval_callback = EvalCallback(
# vec_eval_env,
# n_eval_episodes=10,
# best_model_save_path=f"models/{run.id}",
# log_path=gamelogs,
# eval_freq=5000 * config["n_envs"],
# verbose=0
#
# )
# else:
# eval_callback = EvalCallback(
# vec_eval_env,
# n_eval_episodes=10,
# best_model_save_path=f"models/{run.id}",
# log_path=gamelogs,
# eval_freq=5000 * config["n_envs"],
# callback_after_eval=stop_train_callback,
# verbose=0
# )
eval_callback = EvalCallback(
vec_eval_env,
n_eval_episodes=100,
best_model_save_path=f"models/{run.id}",
log_path=gamelogs,
eval_freq=5000 * config["n_envs"],
verbose=0
)
callbacks = [
WandbCallback(
verbose=0
),
eval_callback
]
model.learn(
config["n_timesteps"],
callback=callbacks
)
run.finish()
# in case you want to save the attention training weights in order to visualize them
# if hasattr(model.policy.features_extractor, "training_weights"):
# training_weights = model.policy.features_extractor.training_weights
#
# with open(f'{env}_attention_weights.pkl', 'wb') as f:
# pickle.dump(training_weights, f)
# in case you want to print some information about the model like the number of parameters
# print("net_arch:", model.policy.net_arch)
# print("share_feature_extractor:", model.policy.share_features_extractor)
# print("feature_extractor:", model.policy.features_extractor)
#
# if skilled_agent:
# print("num_skills:", len(model.policy.features_extractor.skills))
# for s in model.policy.features_extractor.skills:
# print(s.name, "is training", s.skill_model.training)
#
# print("params:", sum(p.numel() for p in model.policy.parameters() if p.requires_grad))