forked from DanHrmti/ECRL
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
298 lines (242 loc) · 12.6 KB
/
main.py
File metadata and controls
298 lines (242 loc) · 12.6 KB
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
"""
Main
Author: Dan Haramati
"""
import os
import time
import yaml
from pathlib import Path
import argparse
import isaacgym
import numpy as np
from stable_baselines3.common.env_checker import check_env
from stable_baselines3.common.noise import NormalActionNoise
import wandb
from td3_agent import TD3HER
from policies import CustomTD3Policy, EITActor, EITCritic, SMORLActor, SMORLCritic, MLPActor, MLPCritic
from isaac_panda_push_env import IsaacPandaPush
from isaac_env_wrappers import IsaacPandaPushGoalSB3Wrapper
from multi_her_replay_buffer import MultiHerReplayBuffer
from utils import load_pretrained_rep_model, load_latent_classifier, check_config, get_run_name
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="ECRL Training")
parser.add_argument("-c", "--config_dir", type=str, default='config/n_cubes', help="path to config files")
args = parser.parse_args()
#################################
# Config #
#################################
config_dir = args.config_dir
# load config files
config = yaml.safe_load(Path(f'{config_dir}/Config.yaml').read_text())
isaac_env_cfg = yaml.safe_load(Path(f'{config_dir}/IsaacPandaPushConfig.yaml').read_text())
policy_config = yaml.safe_load(Path('config/PolicyConfig.yaml').read_text())
check_config(config, isaac_env_cfg, policy_config)
############ WANDB #############
if config['WANDB']['log']:
# initialize weights & biases run
wandb_run = wandb.init(
entity="",
project="ECRL",
sync_tensorboard=False,
settings=wandb.Settings(start_method="fork"),
)
#################################
# random seed
seed = np.random.randint(50000)
print(f"\nRandom seed: {seed}")
# run name
name = get_run_name(config, isaac_env_cfg, seed)
if config['WANDB']['log']:
wandb_run.name = name
print(f"Run Name: {name}")
# output directories
results_dir = './results'
if not os.path.isdir(results_dir):
os.makedirs(results_dir)
print(f"Created directory {results_dir}")
models_dir = './model_chkpts'
if not os.path.isdir(models_dir):
os.makedirs(models_dir)
print(f"Created directory {models_dir}")
model_save_dir = models_dir + f'/model_{name}_{seed}'
#################################
# Representation #
#################################
latent_rep_model = load_pretrained_rep_model(dir_path=config['Model']['latentRepPath'], model_type=config['Model']['obsMode'])
latent_classifier = load_latent_classifier(config, num_objects=isaac_env_cfg["env"]["numObjects"])
#################################
# Environment #
#################################
print(f"Setting up environment...")
# create environments
envs = IsaacPandaPush(
cfg=isaac_env_cfg,
rl_device=f"cuda:{config['cudaDevice']}",
sim_device=f"cuda:{config['cudaDevice']}",
graphics_device_id=config['cudaDevice'],
headless=True,
virtual_screen_capture=False,
force_render=False,
)
# wrap enviroments for GoalEnv and SB3 compatibility
env = IsaacPandaPushGoalSB3Wrapper(
env=envs,
obs_mode=config['Model']['obsMode'],
n_views=config['Model']['numViews'],
latent_rep_model=latent_rep_model,
latent_classifier=latent_classifier,
reward_cfg=config['Reward']['GT'],
smorl=(config['Model']['method'] == 'SMORL'),
)
if config['envCheck']:
check_env(env, warn=True, skip_render_check=True) # verify SB3 compatibility
print(f"Finished setting up environment")
#################################
# Policy #
#################################
policy_kwargs = policy_config[config['Model']['method']][config['Model']['obsType']]
if config['Model']['method'] == 'ECRL':
policy_kwargs['actor_class'] = EITActor
policy_kwargs['critic_class'] = EITCritic
elif config['Model']['method'] == 'SMORL':
policy_kwargs['actor_class'] = SMORLActor
policy_kwargs['critic_class'] = SMORLCritic
elif config['Model']['method'] == 'Unstructured':
policy_kwargs['actor_class'] = MLPActor
policy_kwargs['critic_class'] = MLPCritic
else:
raise NotImplementedError(f"Method type '{config['Model']['method']}' is not supported")
#################################
# Model & Training #
#################################
# Training parameters
epoch_episodes = config['Training']['epochEpisodes']
epoch_timesteps = config['Training']['epochEpisodes'] * env.horizon
total_timesteps = ((config['Training']['totalTimesteps'][env.num_objects-1] // epoch_timesteps) + 1) * epoch_timesteps
if config['collectData']:
total_timesteps = config['collectDataNumTimesteps']
# Exploration Params
# Action noise
action_dim = env.action_space.shape[-1]
action_noise_sigma = config['Training']['actionNoiseSigma']
action_noise = NormalActionNoise(mean=np.zeros(action_dim), sigma=action_noise_sigma * np.ones(action_dim))
# Epsilon greedy
exploration_epsilon = config['Training']['explorationEpsilon']
# Noise schedule: [fraction of initial value at end of schedule, episode start decay, episode end decay]
if env.push_t:
exploration_schedule = [0.5, 30 * epoch_episodes, 40 * epoch_episodes]
elif env.num_objects == 1:
exploration_schedule = [0.5, 10 * epoch_episodes, 20 * epoch_episodes]
elif env.num_objects == 2:
exploration_schedule = [0.5, 20 * epoch_episodes, 30 * epoch_episodes]
elif env.num_objects == 3:
exploration_schedule = [0.5, 30 * epoch_episodes, 40 * epoch_episodes]
else:
exploration_schedule = [0.5, 30 * epoch_episodes, 40 * epoch_episodes] # default
# Model
model = TD3HER(
env=env, # wrapped IsaacGym environment
policy=CustomTD3Policy, # policy class
policy_kwargs=policy_kwargs, # policy and Q-function related parameters
learning_rate=config['Training']['learningRate'], # learning rate for agent Adam optimizer
batch_size=config['Training']['batchSize'],
tau=config['Training']['tau'], # soft update coefficient
gamma=config['Training']['gamma'], # discount factor
a_reg_coef=config['Training']['actionRegCoefficient'], # action regularization coefficient for actor loss
buffer_size=min(total_timesteps, config['Training']['bufferSize'][env.num_objects-1]) if not config["collectData"] else total_timesteps, # size of the replay buffer
replay_buffer_class=MultiHerReplayBuffer, # use TD3 with HER
replay_buffer_kwargs=dict( # HER parameters:
n_sampled_goal=0 if env.ordered_push else 4, # real-to-relabled transition ratio
goal_selection_strategy="future", # sample from states after current in same episode
online_sampling=True, # sample a new goal with each minibatch
max_episode_length=env.horizon, # maximum number of steps in episode
handle_timeout_termination=True, # removes termination signals due to timeout
),
chamfer_reward=config['Model']['ChamferReward'], # if False, use GT reward from environment
chamfer_reward_kwargs=config['Reward']['Chamfer'],
learning_starts=(config['Training']['warmupEpisodes'] * env.horizon) if not config['collectData'] else total_timesteps, # how many steps of the model to collect transitions for before learning starts
train_freq=(env.horizon, "step"), # frequency for model update, should determine choice of number of parallel envs
gradient_steps=int(env.num_envs * env.horizon * config['Training']['utdRatio']), # gradient steps per train_freq (default=-1, 1 gradient step for each env step)
action_noise=action_noise, # initial action noise
exploration_epsilon=exploration_epsilon, # initial probability for uniform action
exploration_schedule=exploration_schedule,
policy_eval_freq=epoch_episodes if not config['collectData'] else None, # frequency in episodes to evaluate policy on
num_eval_episodes=config['Evaluation']['numEvalEpisodes'], # number of episodes to evaluate policy on
eval_max_episode_length=config['Evaluation'].get('maxEvalEpisodeLen', 50*env.num_objects),
smorl_meta_n_steps=config['Evaluation']['SMORLMetaNumSteps'], # number of consecutive steps attempting to solve each SMORL goal before cycling to the next goal
model_save_freq=epoch_episodes,
model_save_dir=model_save_dir,
seed=seed,
device=f"cuda:{config['cudaDevice']}", # "auto" = use GPU if available
_init_setup_model=True, # build the network at the creation of the instance
wandb_log=config['WANDB']['log'],
wandb_log_policy_stats=config['WANDB']['logPolicyStats'], # setting to False saves a lot of time in training
episode_vis_freq=((config['WANDB']['episodeVisFreq'] // env.num_envs) * env.num_envs), # frequency in episodes to visualize policy on WANDB
)
########## WANDB ##########
if config['WANDB']['log']:
# Hyper-parameters
wandb.config.update(dict(
seed=model.seed,
obs_mode=model.obs_mode,
lr=model.learning_rate,
bs=model.batch_size,
tau=model.tau,
gamma=model.gamma,
a_reg_coef=model.a_reg_coef,
action_noise=model.an_sigma_init,
exp_epsilon=model.epsilon_init,
buffer_size=model.buffer_size,
her_ratio=model.replay_buffer.her_ratio,
epoch_episodes=epoch_episodes,
horizon=env.horizon,
warmup_episodes=config['Training']['warmupEpisodes'],
total_timesteps=total_timesteps,
utd_ratio=config['Training']['utdRatio'],
reward_scale=env.reward_scale,
chamfer_reward=config['Model']['ChamferReward'],
))
if config['Model']['obsMode'] not in ['vae', 'state_unstruct']:
wandb.config.update(dict(
# Policy related parameters
h_dim=policy_config[config['Model']['method']][config['Model']['obsType']]["actor_kwargs"]["h_dim"],
embed_dim=policy_config[config['Model']['method']][config['Model']['obsType']]["actor_kwargs"]["embed_dim"],
n_head=policy_config[config['Model']['method']][config['Model']['obsType']]["actor_kwargs"]["n_head"],
masking=policy_config[config['Model']['method']][config['Model']['obsType']]["actor_kwargs"]["masking"] if config['Model']['obsMode'] == "dlp" else None,
))
if config['Model']['obsMode'] in ['dlp', 'vae', 'slot']:
wandb.config.update(dict(latent_rep_chkpt=config['Model']['latentRepPath']))
# Tags
wandb_run.tags = wandb_run.tags + (f"{env.num_objects}Obj",)
if env.num_objects != env.num_colors:
wandb_run.tags = wandb_run.tags + (f"{env.num_colors}Color",)
if config['Model']['ChamferReward']:
wandb_run.tags = wandb_run.tags + ('ChamferReward',)
for key in ["AdjacentGoals", "OrderedPush", "PushT", "RandColor", "RandNumObj"]:
if key in isaac_env_cfg["env"] and isaac_env_cfg["env"][key]:
wandb_run.tags = wandb_run.tags + (key,)
if env.small_table:
wandb_run.tags = wandb_run.tags + ("SmallTable", )
###########################
# training
print("\nTraining started")
start_time = time.time()
model.learn(total_timesteps=total_timesteps, log_interval=None)
env.close()
print("Training finished")
print(f"Elapsed time: {(time.time() - start_time) / 3600:5.2f}h")
# post Training
print(f"Saving model to {model_save_dir}")
model.save(model_save_dir)
if config["collectData"]: # save media to pretrain representation model
data_save_dir = results_dir + f'/{env.num_objects}C_{total_timesteps}ts_res{isaac_env_cfg["env"]["cameraRes"]}'
print(f"Saving image data to {data_save_dir}")
info = model.replay_buffer.info_buffer.copy()
total_episodes = len(info) * env.num_envs # assumes size of replay buffer is <= amount of data collected
obs_shape = info[0][0][0]['image'].shape
transitions = np.zeros(np.append([total_episodes, model.horizon], obs_shape), dtype=np.uint8)
for e in range(len(info)):
for i in range(model.horizon):
for env_idx in range(env.num_envs):
transitions[env.num_envs * e + env_idx][i] = info[e][i][env_idx]['image']
np.save(data_save_dir, transitions)