forked from Acmece/rl-collision-avoidance
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ppo_stage1.py
204 lines (159 loc) · 6.87 KB
/
ppo_stage1.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
import os
import logging
import sys
import socket
import numpy as np
import rospy
import torch
import torch.nn as nn
from mpi4py import MPI
from torch.optim import Adam
from collections import deque
from model.net import MLPPolicy, CNNPolicy
from stage_world1 import StageWorld
from model.ppo import ppo_update_stage1, generate_train_data
from model.ppo import generate_action
from model.ppo import transform_buffer
MAX_EPISODES = 5000
LASER_BEAM = 512
LASER_HIST = 3
HORIZON = 128
GAMMA = 0.99
LAMDA = 0.95
BATCH_SIZE = 1024
EPOCH = 2
COEFF_ENTROPY = 5e-4
CLIP_VALUE = 0.1
NUM_ENV = 24
OBS_SIZE = 512
ACT_SIZE = 2
LEARNING_RATE = 5e-5
def run(comm, env, policy, policy_path, action_bound, optimizer):
# rate = rospy.Rate(5)
buff = []
global_update = 0
global_step = 0
if env.index == 0:
env.reset_world()
for id in range(MAX_EPISODES):
env.reset_pose()
env.generate_goal_point()
terminal = False
ep_reward = 0
step = 1
obs = env.get_laser_observation()
obs_stack = deque([obs, obs, obs])
goal = np.asarray(env.get_local_goal())
speed = np.asarray(env.get_self_speed())
state = [obs_stack, goal, speed]
while not terminal and not rospy.is_shutdown():
state_list = comm.gather(state, root=0)
# generate actions at rank==0
v, a, logprob, scaled_action=generate_action(env=env, state_list=state_list,
policy=policy, action_bound=action_bound)
# execute actions
real_action = comm.scatter(scaled_action, root=0)
env.control_vel(real_action)
# rate.sleep()
rospy.sleep(0.001)
# get informtion
r, terminal, result = env.get_reward_and_terminate(step)
ep_reward += r
global_step += 1
# get next state
s_next = env.get_laser_observation()
left = obs_stack.popleft()
obs_stack.append(s_next)
goal_next = np.asarray(env.get_local_goal())
speed_next = np.asarray(env.get_self_speed())
state_next = [obs_stack, goal_next, speed_next]
if global_step % HORIZON == 0:
state_next_list = comm.gather(state_next, root=0)
last_v, _, _, _ = generate_action(env=env, state_list=state_next_list, policy=policy,
action_bound=action_bound)
# add transitons in buff and update policy
r_list = comm.gather(r, root=0)
terminal_list = comm.gather(terminal, root=0)
if env.index == 0:
buff.append((state_list, a, r_list, terminal_list, logprob, v))
if len(buff) > HORIZON - 1:
s_batch, goal_batch, speed_batch, a_batch, r_batch, d_batch, l_batch, v_batch = \
transform_buffer(buff=buff)
t_batch, advs_batch = generate_train_data(rewards=r_batch, gamma=GAMMA, values=v_batch,
last_value=last_v, dones=d_batch, lam=LAMDA)
memory = (s_batch, goal_batch, speed_batch, a_batch, l_batch, t_batch, v_batch, r_batch, advs_batch)
ppo_update_stage1(policy=policy, optimizer=optimizer, batch_size=BATCH_SIZE, memory=memory,
epoch=EPOCH, coeff_entropy=COEFF_ENTROPY, clip_value=CLIP_VALUE, num_step=HORIZON,
num_env=NUM_ENV, frames=LASER_HIST,
obs_size=OBS_SIZE, act_size=ACT_SIZE)
buff = []
global_update += 1
step += 1
state = state_next
if env.index == 0:
if global_update != 0 and global_update % 20 == 0:
torch.save(policy.state_dict(), policy_path + '/Stage1_{}'.format(global_update))
logger.info('########################## model saved when update {} times#########'
'################'.format(global_update))
distance = np.sqrt((env.goal_point[0] - env.init_pose[0])**2 + (env.goal_point[1]-env.init_pose[1])**2)
logger.info('Env %02d, Goal (%05.1f, %05.1f), Episode %05d, setp %03d, Reward %-5.1f, Distance %05.1f, %s' % \
(env.index, env.goal_point[0], env.goal_point[1], id + 1, step, ep_reward, distance, result))
logger_cal.info(ep_reward)
if __name__ == '__main__':
# config log
hostname = socket.gethostname()
if not os.path.exists('./log/' + hostname):
os.makedirs('./log/' + hostname)
output_file = './log/' + hostname + '/output.log'
cal_file = './log/' + hostname + '/cal.log'
# config log
logger = logging.getLogger('mylogger')
logger.setLevel(logging.INFO)
file_handler = logging.FileHandler(output_file, mode='a')
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setLevel(logging.INFO)
logger.addHandler(file_handler)
logger.addHandler(stdout_handler)
logger_cal = logging.getLogger('loggercal')
logger_cal.setLevel(logging.INFO)
cal_f_handler = logging.FileHandler(cal_file, mode='a')
file_handler.setLevel(logging.INFO)
logger_cal.addHandler(cal_f_handler)
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
env = StageWorld(512, index=rank, num_env=NUM_ENV)
reward = None
action_bound = [[0, -1], [1, 1]]
# torch.manual_seed(1)
# np.random.seed(1)
if rank == 0:
policy_path = 'policy'
# policy = MLPPolicy(obs_size, act_size)
policy = CNNPolicy(frames=LASER_HIST, action_space=2)
# policy.cuda()
opt = Adam(policy.parameters(), lr=LEARNING_RATE)
mse = nn.MSELoss()
if not os.path.exists(policy_path):
os.makedirs(policy_path)
file = policy_path + '/stage1_2.pth'
if os.path.exists(file):
logger.info('####################################')
logger.info('############Loading Model###########')
logger.info('####################################')
state_dict = torch.load(file, map_location=torch.device('cpu'))
policy.load_state_dict(state_dict)
else:
logger.info('#####################################')
logger.info('############Start Training###########')
logger.info('#####################################')
else:
policy = None
policy_path = None
opt = None
try:
run(comm=comm, env=env, policy=policy, policy_path=policy_path, action_bound=action_bound, optimizer=opt)
except KeyboardInterrupt:
pass