-
Notifications
You must be signed in to change notification settings - Fork 1
/
o_train_pursuit_vs_random_evasion.py
476 lines (304 loc) · 18.5 KB
/
o_train_pursuit_vs_random_evasion.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
import os
import time
import argparse
import copy
import random
import numpy as np
import torch
from lib.environment.pursuit_evasion_o import MatrixWorld as Environment
from lib.utils.experiment_logger import ExperimentLogger
from lib.utils.models import ModelMLP
from lib.utils.models import ModelPolicySafe
from lib.utils.models import ModelPolicy
from lib.utils.models import ModelActorCritic
from lib.actor_critic.trainer_agent import TrainerAgent
def parse_args():
parser = argparse.ArgumentParser()
##################################################
# Log parameters.
data_log_folder = os.path.join("data", os.path.basename(__file__)[:-3])
os.makedirs(data_log_folder, exist_ok=True)
parser.add_argument("--data_log_folder", type=str, default=data_log_folder)
parser.add_argument("--resume_model", action="store_true", default=False)
parser.add_argument("--resume_model_name_actor", type=str,
default=os.path.join(data_log_folder, 'model_actor.pth'))
parser.add_argument("--resume_model_name_critic", type=str,
default=os.path.join(data_log_folder, 'model_critic.pth'))
##################################################
# Environment parameters.
parser.add_argument("--world_size", type=int, default=40)
parser.add_argument("--n_pursuers", type=int, default=8)
parser.add_argument("--n_evaders", type=int, default=30)
##################################################
# General experiment parameters.
parser.add_argument("--seed", type=int, default=0)
parser.add_argument("--render", type=bool, default=False)
parser.add_argument("--n_epochs", type=int, default=5000,
help="Epoch is different from episode. "
"An epoch can collect experiences of more than one or less than one episodes.")
parser.add_argument("--steps_per_epoch", type=int, default=500,
help="steps_per_epoch is different from max_episode_length.")
parser.add_argument("--max_episode_length", type=int, default=500)
if torch.cuda.device_count() > 1:
device = torch.device('cuda:1')
elif torch.cuda.is_available():
device = torch.device('cuda:0')
else:
device = torch.device('cpu')
parser.add_argument("--device", type=torch.device, default=device)
parser.add_argument("--save_model_frequency", type=int, default=100)
parser.add_argument("--model_name_frequency", type=int, default=500)
parser.add_argument("--log_performance_frequency", type=int, default=1,
help="time duration between successive log printing.")
##################################################
# Model parameters.
parser.add_argument("--use_initialization", action='store_false', default=True,
help="True if not specified. Use it will converge faster without loss of final performance.")
parser.add_argument("--with_layer_normalization", action='store_false', default=False,
help="True if not specified. Generally, with it, learning is more stable and better. "
"But not good for pursuit-evasion-o (inefficient learning, unstable).")
parser.add_argument("--with_obstacle_avoidance_mask", action='store_false', default=False,
help="True if not specified. Perfect obstacle avoidance. "
"But not good for pursuit-evasion-o (less stable).")
##################################################
# Algorithm parameters.
parser.add_argument("--gamma", type=float, default=0.99)
parser.add_argument("--gae_lam", type=float, default=0.97,
help="General advantage estimation (GAE) parameter.")
parser.add_argument("--lr_policy", type=float, default=3e-4)
parser.add_argument("--lr_value", type=float, default=1e-3)
parser.add_argument("--train_iterations_policy", type=int, default=1)
parser.add_argument("--train_iterations_value", type=int, default=5)
parser.add_argument("--entropy_coefficient", type=float, default=0, help="or try 0.01")
parser.add_argument("--use_gradient_norm", action='store_true', default=False, help="Trick")
parser.add_argument("--max_gradient_norm", type=float, default=10, help="Trick")
return parser.parse_args()
class RunExperiment:
def __init__(self, args):
self.args = args
self.logger = ExperimentLogger(self.args.data_log_folder)
# Share parameters.
# Value may change with time.
self.n_evaders = self.args.n_evaders
self.n_pursuers = self.args.n_pursuers
# step_1_create_environment.
self.env = None
self.dim_observation = None
self.dim_action = None
# step_3_create_trainer_agent
self.evader = None
self.pursuer = None
# step_4_experiment_over_epoch
self.epoch_counter = 0
self.episode_timestep_counter = 0
self.dim_observation_actor = 0
self.dim_observation_critic = 0
# step_4_2_update_model
self.loss_value_pursuer = 0
self.loss_policy_pursuer = 0
pass
def run(self):
self.step_1_create_environment()
self.step_2_set_random_seed()
self.step_3_create_trainer_agent()
self.step_4_experiment_over_epoch()
def step_1_create_environment(self):
self.env = Environment(world_rows=self.args.world_size, world_columns=self.args.world_size,
n_evaders=self.args.n_evaders, n_pursuers=self.args.n_pursuers,
fov_scope=11,
max_env_cycles=self.args.max_episode_length,
save_path=os.path.join(self.args.data_log_folder, "frames"))
self.dim_observation_actor = (self.env.fov_scope, self.env.fov_scope, 3)
self.dim_observation_critic = self.env.fov_scope * self.env.fov_scope * 3
self.dim_action = self.env.n_actions
def step_2_set_random_seed(self):
"""
- First, create an environment instance.
- Second, set random seed, including that for the environment.
- Third, do all the other things.
"""
seed = self.args.seed + 10000
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
self.env.reset(seed=seed)
def step_3_create_trainer_agent(self):
# Use args parameter to initialize.
self.evader = self.step_3_1_create_trainer_agent(self.args.n_evaders)
self.pursuer = self.step_3_1_create_trainer_agent(self.args.n_pursuers)
def step_3_1_create_trainer_agent(self, n_agents):
model_actor_critic = self.step_3_1_1_initialize_model_actor_critic(dim_input_actor=self.dim_observation_actor,
dim_input_critic=self.dim_observation_critic,
dim_output=self.dim_action)
agents = TrainerAgent(model_actor_critic=model_actor_critic,
buffer_size=self.args.steps_per_epoch,
n_agents=n_agents,
dim_observation_actor=self.dim_observation_actor,
dim_observation_critic=self.dim_observation_critic,
configuration=self.args)
return agents
def step_3_1_1_initialize_model_actor_critic(self, dim_input_actor, dim_input_critic, dim_output):
# Policy.
if self.args.with_obstacle_avoidance_mask:
model_policy = ModelPolicySafe(dim_input=dim_input_actor,
dim_output=dim_output,
hidden_sizes=(400, 300),
with_layer_normalization=self.args.with_layer_normalization,
use_initialization=self.args.use_initialization,
obstacle_channel=[2])
else:
model_policy = ModelPolicy(dim_input=dim_input_actor,
dim_output=dim_output,
hidden_sizes=(400, 300),
with_layer_normalization=self.args.with_layer_normalization,
use_initialization=self.args.use_initialization)
# Value.
model_value = ModelMLP(dim_input=dim_input_critic, dim_output=1, hidden_sizes=(400, 300),
with_layer_normalization=self.args.with_layer_normalization,
use_initialization=self.args.use_initialization)
if self.args.resume_model:
model_policy.load_state_dict(torch.load(self.args.resume_model_name_actor, map_location=self.args.device))
model_value.load_state_dict(torch.load(self.args.resume_model_name_critic, map_location=self.args.device))
# Actor critic.
model_actor_critic = ModelActorCritic(model_policy=model_policy,
model_value=model_value).to(self.args.device)
return model_actor_critic
def step_4_experiment_over_epoch(self):
for i_epoch in range(self.args.n_epochs):
start_epoch_time = time.time()
self.step_4_1_experiment_of_an_epoch()
self.step_4_2_update_model()
self.step_4_3_log_info_of_epoch(time.time() - start_epoch_time)
# Update.
self.epoch_counter += 1
pass
def step_4_1_experiment_of_an_epoch(self):
observations, rewards, game_done, info = self.env.reset()
for timestep in range(self.args.steps_per_epoch):
if self.args.render:
self.env.render()
# 1. Agents make decisions.
observations_actor_evader, observations_critic_evader = \
self.step_4_1_1_preprocessing_observation(observations["evader"])
actions_evader, values_evader, actions_log_probability_evader = \
self.evader.model_actor_critic(observations_actor_evader, observations_critic_evader)
observations_actor_pursuer, observations_critic_pursuer = \
self.step_4_1_1_preprocessing_observation(observations["pursuer"])
actions_pursuer, values_pursuer, actions_log_probability_pursuer = \
self.pursuer.model_actor_critic(observations_actor_pursuer, observations_critic_pursuer)
# 2. Env update and get observation.
next_observations, rewards, dones, info = self.env.step(actions_pursuer=actions_pursuer,
actions_evader=actions_evader)
# 3. Update episode process record.
self.episode_timestep_counter += 1
self.logger.update_episode_additive_performance(key="reward_pursuer", value=np.mean(rewards["pursuer"]))
self.logger.update_episode_additive_performance(key="n_collisions_pursuers_with_obstacles",
value=info["n_collisions_pursuers_with_obstacles"])
self.logger.update_episode_additive_performance(key="n_collisions_pursuers_with_pursuers",
value=info["n_collisions_pursuers_with_pursuers"])
self.logger.update_episode_additive_performance(key="n_collisions_pursuers_with_evaders",
value=info["n_collisions_pursuers_with_evaders"])
# 4. Store agents' experience in buffer.
self.pursuer.buffer.store(swarm_observations_actor=observations_actor_pursuer,
swarm_observations_critic=observations_critic_pursuer,
swarm_actions=actions_pursuer,
swarm_rewards=torch.tensor(rewards["pursuer"], device=self.args.device),
swarm_values=values_pursuer,
swarm_actions_log_probability=actions_log_probability_pursuer,
swarm_agent_active_index=info["pursuers_last_active_index"])
# 5. Update the observation memory.
observations = next_observations
# 6. Identify the game status and post-processing if done.
observations = self.step_4_1_2_identify_and_terminate_an_episode(timestep, dones, observations, info)
pass
def step_4_1_1_preprocessing_observation(self, observations):
# (n_agents, fov, fov, 3).
observations_actor = torch.as_tensor(observations, dtype=torch.double, device=self.args.device)
# (n_agents, fov * fov * 3).
flatten_dim = observations.shape[-3] * observations.shape[-2] * observations.shape[-1]
n_dim = len(observations.shape)
if n_dim > 4:
observations_critic = observations.reshape(*observations.shape[:-3], flatten_dim)
elif n_dim == 4:
observations_critic = observations.reshape(observations.shape[0], flatten_dim)
else:
observations_critic = observations.reshape(flatten_dim)
observations_critic = torch.as_tensor(observations_critic, dtype=torch.double, device=self.args.device)
return observations_actor, observations_critic
def step_4_1_2_identify_and_terminate_an_episode(self, timestep, dones, observations, info):
# 6. Identify the game status.
episode_timeout = (self.episode_timestep_counter == self.args.max_episode_length)
episode_terminal = dones["game_done"] or episode_timeout
# Specific number of experiences in an epoch have already been collected,
# terminate this epoch (and prepare to start the next one).
epoch_ended = (timestep == (self.args.steps_per_epoch - 1))
# 7. Finish the experience collecting process if conditions are satisfied.
for idx_pursuer, done_pursuer in enumerate(dones["pursuer"]):
last_global_idx_active_pursuer = info["pursuers_last_active_index"][idx_pursuer]
if done_pursuer:
last_value_pursuer = torch.zeros((1,), dtype=torch.double, device=self.args.device)
self.pursuer.buffer.finish_path_by_index(last_value_pursuer, last_global_idx_active_pursuer)
elif episode_timeout or epoch_ended:
idx_active_pursuer = info["pursuers_active_index"].tolist().index(last_global_idx_active_pursuer)
observation_actor_pursuer, observation_critic_pursuer = \
self.step_4_1_1_preprocessing_observation(observations["pursuer"][idx_active_pursuer])
_, last_value_pursuer, _ = self.pursuer.model_actor_critic(observation_actor_pursuer,
observation_critic_pursuer)
self.pursuer.buffer.finish_path_by_index(last_value_pursuer, last_global_idx_active_pursuer)
if episode_terminal or epoch_ended:
if self.args.render:
self.env.render()
# 7. Finish the experience collecting process if conditions are satisfied.
# if episode_timeout or epoch_ended:
#
# observations_actor_pursuer, observations_critic_pursuer = \
# self.step_4_1_1_preprocessing_observation(observations["pursuer"])
#
# _, last_values_pursuer, _ = self.pursuer.model_actor_critic(observations_actor_pursuer,
# observations_critic_pursuer)
#
# else:
#
# last_values_pursuer = torch.zeros((self.args.n_pursuers,), dtype=torch.double, device=self.args.device)
#
# self.pursuer.buffer.finish_path(last_values_pursuer)
# 9. When a complete episode is finished, log info and reset episode logger.
# Otherwise, just reset the episode performance logger.
if episode_terminal:
self.logger.update_episode_additive_performance(key="capture_rate", value=info["capture_rate"])
self.logger.update_episode_additive_performance(key="episode_length",
value=self.episode_timestep_counter)
self.logger.end_episode_additive_performance()
else:
self.logger.reset_episode_additive_performance()
# Reset.
self.episode_timestep_counter = 0
observations, rewards, game_done, info = self.env.reset()
return observations
def step_4_2_update_model(self):
self.loss_policy_pursuer, self.loss_value_pursuer = self.pursuer.update_model()
self.logger.update_epoch_performance(key="loss_value_pursuer", value=self.loss_value_pursuer)
self.logger.update_epoch_performance(key="loss_policy_pursuer", value=self.loss_policy_pursuer)
if (self.epoch_counter % self. args.save_model_frequency == 0) or \
(self.epoch_counter == self.args.n_epochs - 1):
model_name_prefix = os.path.join(self.args.data_log_folder,
"Epoch" + str(self.args.model_name_frequency) + "x" +
str(self.epoch_counter // self.args.model_name_frequency))
model_name_actor_prefix = model_name_prefix + "model_actor"
model_name_critic_prefix = model_name_prefix + "model_critic"
model_filename_actor_pursuer = model_name_actor_prefix + "_pursuer.pth"
model_filename_critic_pursuer = model_name_critic_prefix + "_pursuer.pth"
torch.save(self.pursuer.model_actor_critic.model_policy.state_dict(), model_filename_actor_pursuer)
torch.save(self.pursuer.model_actor_critic.model_value.state_dict(), model_filename_critic_pursuer)
def step_4_3_log_info_of_epoch(self, epoch_time):
self.logger.update_epoch_performance(key="epoch_time_s", value=epoch_time)
if (self.epoch_counter % self.args.log_performance_frequency == 0) or \
(self.epoch_counter == self.args.n_epochs - 1):
self.logger.log_dump_epoch_performance(epoch_counter=self.epoch_counter)
else:
self.logger.reset_epoch_performance()
if __name__ == "__main__":
all_args = parse_args()
run_an_experiment = RunExperiment(all_args)
run_an_experiment.run()
print("COMPLETE!")