-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.py
271 lines (188 loc) · 7.27 KB
/
util.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
import os
import cv2
import gym
import random
import numpy as np
import errno
import math
import torch
from torch.autograd import Variable
from replay_memory import ExpReplay
from rank_based_prioritized_replay import RankBasedPrioritizedReplay
from ddqn_rankPriority_learn import ddqn_compute_y
use_cuda = torch.cuda.is_available()
FloatTensor = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor
IntTensor = torch.cuda.IntTensor if use_cuda else torch.IntTensor
LongTensor = torch.cuda.LongTensor if use_cuda else torch.LongTensor
ByteTensor = torch.cuda.ByteTensor if use_cuda else torch.ByteTensor
Tensor = FloatTensor
def preprocessing_old(current_screen):
current_screen_yuv = cv2.cvtColor(current_screen, cv2.COLOR_BGR2YUV)
current_y, current_u, current_v = cv2.split(current_screen_yuv) #image size 210 x 160
luminance = cv2.resize(current_y, (84,110)) #resize to 110 x 84
luminance = luminance[21:-5,:] #remove the score
return luminance
def get_screen_old(env):
screen = env.render(mode='rgb_array')
screen = preprocessing_old(screen)
screen = np.expand_dims(screen, 0)
return torch.from_numpy(curr_state).unsqueeze(0).type(Tensor)
def play_game_old(env, num_frames, action=0, evaluate=False):
state_reward = 0
state_done = False
state_obs = np.zeros((num_frames, 84, 84))
for frame in range(num_frames):
curr_obs, reward, done, _ = env.step(action)
curr_obs_post = preprocessing_old(curr_obs)
state_obs[frame,:,:] = curr_obs_post
state_done = state_done | done
state_reward += reward
if state_done:
state_reward += -1
if state_reward < -1 and not evaluate:
state_reward = -1
elif state_reward > 1 and not evaluate:
state_reward = 1
state_obs = state_obs / 255
state_obs = torch.from_numpy(state_obs).unsqueeze(0).type(Tensor)
return state_obs, state_reward, state_done, _
def preprocessing(current_screen):
current_screen_yuv = cv2.cvtColor(current_screen, cv2.COLOR_BGR2YUV)
current_y, current_u, current_v = cv2.split(current_screen_yuv) #image size 210 x 160
current_y = cv2.copyMakeBorder(current_y, 0,0, 25,25, cv2.BORDER_CONSTANT)
luminance = cv2.resize(current_y, (84,84))
return luminance
def get_screen(env):
screen = env.render(mode='rgb_array')
screen = preprocessing(screen)
screen = np.expand_dims(screen, 0)
return torch.from_numpy(curr_state).unsqueeze(0).type(Tensor)
def play_game(env, num_frames, action=0, evaluate=False):
state_reward = 0
state_done = False
state_obs = np.zeros((num_frames, 84, 84))
for frame in range(num_frames):
curr_obs, reward, done, _ = env.step(action)
curr_obs_post = preprocessing(curr_obs)
state_obs[frame,:,:] = curr_obs_post
state_done = state_done | done
state_reward += reward
if state_done:
state_reward += -1
if state_reward < -1 and not evaluate:
state_reward = -1
elif state_reward > 1 and not evaluate:
state_reward = 1
state_obs = state_obs / 255
state_obs = torch.from_numpy(state_obs).unsqueeze(0).type(Tensor)
return state_obs, state_reward, state_done, _
def get_Q_value(model, action, current_state):
q_value = model(Variable(current_state, volatile=True).type(FloatTensor)).gather(1, action).data[0,0]
return q_value
def get_greedy_action(model, current_state):
output = model(Variable(current_state, volatile=True).type(FloatTensor)).data.max(1)[1].view(1,1) #volatile = True means inference mode aka no learning
return output
def initialize_replay(env, rp_start, rp_size, frames_per_state):
exp_replay = ExpReplay(rp_size)
episodes_count = 0
env.reset()
num_actions = env.action_space.n
current_state, _, _, _ = play_game(env, frames_per_state)
while episodes_count < rp_start:
action = LongTensor([[random.randrange(num_actions)]])
curr_obs, reward, done, _ = play_game(env, frames_per_state, action[0][0])
reward = Tensor([reward])
exp_replay.push(current_state, action, reward, curr_obs)
current_state = curr_obs
episodes_count+= 1
if done:
env.reset()
current_state, _, _, _ = play_game(env, frames_per_state)
print('Replay Memory initialized for training...')
return exp_replay
def initialize_replay_resume(env, rp_start, rp_size, frames_per_state, model):
exp_replay = ExpReplay(rp_size)
episodes_count = 0
env.reset()
num_actions = env.action_space.n
current_state, _, _, _ = play_game(env, frames_per_state)
while episodes_count < rp_start:
action = get_greedy_action(model, current_state)
curr_obs, reward, done, _ = play_game(env, frames_per_state, action[0][0])
reward = Tensor([reward])
exp_replay.push(current_state, action, reward, curr_obs)
current_state = curr_obs
episodes_count+= 1
if done:
env.reset()
current_state, _, _, _ = play_game(env, frames_per_state)
print('Replay Memory re-initialized for training...')
return exp_replay
def get_index_from_checkpoint_path(checkpoint):
"""
Get index from checkpoint filepath.
Example of the filepath: /work/raymond/ddqn/saved_weights/ddqn_weights_9750000.pth
"""
key = checkpoint.split('/')
chck_file = key[len(key)-1]
chck_filename = chck_file.split('.')[0]
chck_filename_key = chck_filename.split('_')
chck_index = chck_filename_key[2]
return int(chck_index)
def get_index_from_checkpoint_file(checkpoint):
"""
Get index from checkpoint file.
Example of the filepath: ddqn_weights_9750000.pth
"""
chck_filename = checkpoint.split('.')[0]
chck_filename_key = chck_filename.split('_')
chck_index = chck_filename_key[2]
return int(chck_index)
def initialize_rank_replay(env, rp_start, rp_size, frames_per_state,
model, target, gamma, prob_alpha):
exp_replay = RankBasedPrioritizedReplay(rp_size)
episodes_count = 0
env.reset()
num_actions = env.action_space.n
current_state, _, _, _ = play_game(env, frames_per_state)
while episodes_count < rp_start:
action = LongTensor([[random.randrange(num_actions)]])
curr_obs, reward, done, _ = play_game(env, frames_per_state, action[0][0])
reward = Tensor([[reward]])
td_error = 1
exp_replay.push(current_state, action, reward, curr_obs, td_error)
# current_state_ex = curr_obs_ex
episodes_count+= 1.0
if done:
env.reset()
current_state, _, _, _ = play_game(env, frames_per_state)
print('Rank Prioritized Replay initialized for training...')
return exp_replay
#TODO: initialize_rank_replay_resume
# def initialize_rank_replay_resume(env, rp_start, rp_size, frames_per_state,
# model, target, gamma, batch_size):
# exp_replay = RankBasedPrioritizedReplay(rp_size)
# episodes_count = 0
# env.reset()
# num_actions = env.action_space.n
# current_state, _, _, _ = play_game(env, frames_per_state)
# while episodes_count < rp_start:
# action = get_greedy_action(model, current_state)
# curr_obs, reward, done, _ = play_game(env, frames_per_state, action[0][0])
# reward = Tensor([[reward]])
# #compute td-error for one sample
# td_error = ddqn_compute_y(batch_size=1, batch=batch, model=model, target=target, gamma=gamma)
# exp_replay.push(current_state, action, reward, curr_obs, td_error)
# current_state = curr_obs
# episodes_count+= 1
# if done:
# env.reset()
# current_state, _, _, _ = play_game(env, frames_per_state)
# print('Rank Prioritized Replay re-initialized for training...')
# return exp_replay
def make_sure_path_exists(path):
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise