-
Notifications
You must be signed in to change notification settings - Fork 93
/
ppo_stage2.py
215 lines (169 loc) · 7.27 KB
/
ppo_stage2.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
import os
import logging
import sys
import numpy as np
import rospy
import torch
import socket
import torch.nn as nn
from mpi4py import MPI
from torch.optim import Adam
from torch.autograd import Variable
from collections import deque
from model.net import MLPPolicy, CNNPolicy
from stage_world2 import StageWorld
from model.ppo import ppo_update_stage2, generate_train_data
from model.ppo import generate_action, transform_buffer
from model.utils import get_group_terminal, get_filter_index
MAX_EPISODES = 5000
LASER_BEAM = 512
LASER_HIST = 3
HORIZON = 128
GAMMA = 0.99
LAMDA = 0.95
BATCH_SIZE = 512
EPOCH = 4
COEFF_ENTROPY = 5e-4
CLIP_VALUE = 0.1
NUM_ENV = 44
OBS_SIZE = 512
ACT_SIZE = 2
LEARNING_RATE = 5e-5
def run(comm, env, policy, policy_path, action_bound, optimizer):
rate = rospy.Rate(40)
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()
group_terminal = False
ep_reward = 0
liveflag = True
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 group_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)
if liveflag == True:
env.control_vel(real_action)
# rate.sleep()
rospy.sleep(0.001)
# get informtion
r, terminal, result = env.get_reward_and_terminate(step)
step += 1
if liveflag == True:
ep_reward += r
if terminal == True:
liveflag = False
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)
terminal_list = comm.bcast(terminal_list, root=0)
group_terminal = get_group_terminal(terminal_list, env.index)
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)
filter_index = get_filter_index(d_batch)
# print len(filter_index)
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_stage2(policy=policy, optimizer=optimizer, batch_size=BATCH_SIZE, memory=memory, filter_index=filter_index,
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
state = state_next
if env.index == 0:
if global_update != 0 and global_update % 20 == 0:
torch.save(policy.state_dict(), policy_path + '/stage2_{}.pth'.format(global_update))
logger.info('########################## model saved when update {} times#########'
'################'.format(global_update))
logger.info('Env %02d, Goal (%05.1f, %05.1f), Episode %05d, setp %03d, Reward %-5.1f, %s,' % \
(env.index, env.goal_point[0], env.goal_point[1], id, step-1, ep_reward, 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 + '/stage2.pth'
if os.path.exists(file):
logger.info('####################################')
logger.info('############Loading Model###########')
logger.info('####################################')
state_dict = torch.load(file)
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:
import traceback
traceback.print_exc()