-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathutils.py
268 lines (212 loc) · 9.46 KB
/
utils.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
import cv2
import math
import json
import gym
import numpy as np
import pygame
from stable_baselines3.common.callbacks import BaseCallback
from stable_baselines3.common.logger import HParam
def write_json(data, path):
config_dict = {}
with open(path, 'w', encoding='utf-8') as f:
for k, v in data.items():
if isinstance(v, str) and v.isnumeric():
config_dict[k] = int(v)
elif isinstance(v, dict):
config_dict[k] = dict()
for k_inner, v_inner in v.items():
config_dict[k][k_inner] = v_inner.__str__()
config_dict[k] = str(config_dict[k])
else:
config_dict[k] = v.__str__()
json.dump(config_dict, f, indent=4)
class VideoRecorder():
def __init__(self, filename, frame_size, fps=30):
fourcc = cv2.VideoWriter_fourcc(*'XVID')
self.video_writer = cv2.VideoWriter(filename, fourcc, int(fps), (frame_size[1], frame_size[0]))
def add_frame(self, frame):
self.video_writer.write(cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
def release(self):
self.video_writer.release()
def __del__(self):
self.release()
class HParamCallback(BaseCallback):
def __init__(self, config):
"""
Saves the hyperparameters and metrics at the start of the training, and logs them to TensorBoard.
"""
super().__init__()
self.config = config
def _on_training_start(self) -> None:
hparam_dict = {}
for k, v in self.config.items():
if isinstance(v, str) and v.isnumeric():
hparam_dict[k] = int(v)
elif isinstance(v, dict):
hparam_dict[k] = dict()
for k_inner, v_inner in v.items():
hparam_dict[k][k_inner] = v_inner.__str__()
hparam_dict[k] = str(hparam_dict[k])
else:
hparam_dict[k] = v.__str__()
# define the metrics that will appear in the `HPARAMS` Tensorboard tab by referencing their tag
# Tensorbaord will find & display metrics from the `SCALARS` tab
metric_dict = {
"rollout/ep_len_mean": 0,
"train/value_loss": 0,
}
self.logger.record(
"hparams",
HParam(hparam_dict, metric_dict),
exclude=("stdout", "log", "json", "csv"),
)
def _on_step(self) -> bool:
return True
class TensorboardCallback(BaseCallback):
"""
Custom callback for plotting additional values in tensorboard.
"""
def __init__(self, verbose=0):
super().__init__(verbose)
def _on_step(self) -> bool:
# Log scalar value (here a random variable)
if self.locals['dones'][0]:
self.logger.record("custom/total_reward", self.locals['infos'][0]['total_reward'])
self.logger.record("custom/routes_completed", self.locals['infos'][0]['routes_completed'])
self.logger.record("custom/total_distance", self.locals['infos'][0]['total_distance'])
self.logger.record("custom/avg_center_dev", self.locals['infos'][0]['avg_center_dev'])
self.logger.record("custom/avg_speed", self.locals['infos'][0]['avg_speed'])
self.logger.record("custom/mean_reward", self.locals['infos'][0]['mean_reward'])
self.logger.dump(self.num_timesteps)
return True
class VideoRecorderCallback(BaseCallback):
def __init__(self, video_path, frame_size, video_length=-1, fps=30, skip_frame=1, verbose=0):
super().__init__(verbose)
self.video_recorder = VideoRecorder(video_path, frame_size, fps)
self.max_length = video_length
self.skip_frame = skip_frame
def _on_step(self) -> bool:
# Add frame to video
if self.max_length != -1 and self.num_timesteps > self.max_length:
self.video_recorder.release()
return False
# Skip every 4 frames to reduce video size
if self.num_timesteps % self.skip_frame != 0:
return True
display = self.training_env.unwrapped.envs[0].env.display
frame = np.array(pygame.surfarray.array3d(display), dtype=np.uint8).transpose([1, 0, 2])
self.video_recorder.add_frame(frame)
return True
def _on_training_end(self) -> None:
self.video_recorder.release()
def lr_schedule(initial_value: float, end_value: float, rate: float):
"""
Learning rate schedule:
Exponential decay by factors of 10 from initial_value to end_value.
:param initial_value: Initial learning rate.
:param rate: Exponential rate of decay. High values mean fast early drop in LR
:param end_value: The final value of the learning rate.
:return: schedule that computes current learning rate depending on remaining progress
"""
def func(progress_remaining: float) -> float:
"""
Progress will decrease from 1 (beginning) to 0.
:param progress_remaining: A float value between 0 and 1 that represents the remaining progress.
:return: The current learning rate.
"""
if progress_remaining <= 0:
return end_value
return end_value + (initial_value - end_value) * (10 ** (rate * math.log10(progress_remaining)))
func.__str__ = lambda: f"lr_schedule({initial_value}, {end_value}, {rate})"
lr_schedule.__str__ = lambda: f"lr_schedule({initial_value}, {end_value}, {rate})"
return func
class HistoryWrapperObsDict(gym.Wrapper):
# History Wrapper from rl-baselines3-zoo
# https://github.com/DLR-RM/rl-baselines3-zoo/blob/10de3a8804b14b4ea605b487ae7d8117c52901c4/rl_zoo3/wrappers.py
"""
History Wrapper for dict observation.
:param env:
:param horizon: Number of steps to keep in the history.
"""
def __init__(self, env: gym.Env, horizon: int = 2, obs_key: str = 'vae_latent') -> object:
self.obs_key = obs_key
assert isinstance(env.observation_space.spaces[obs_key], gym.spaces.Box)
print("Wrapping the env with HistoryWrapperObsDict.")
wrapped_obs_space = env.observation_space.spaces[self.obs_key]
wrapped_action_space = env.action_space
low_obs = np.repeat(wrapped_obs_space.low, horizon, axis=-1)
high_obs = np.repeat(wrapped_obs_space.high, horizon, axis=-1)
low_action = np.repeat(wrapped_action_space.low, horizon, axis=-1)
high_action = np.repeat(wrapped_action_space.high, horizon, axis=-1)
low = np.concatenate((low_obs, low_action))
high = np.concatenate((high_obs, high_action))
# Overwrite the observation space
env.observation_space.spaces[obs_key] = gym.spaces.Box(low=low, high=high, dtype=wrapped_obs_space.dtype)
super().__init__(env)
self.horizon = horizon
self.low_action, self.high_action = low_action, high_action
self.low_obs, self.high_obs = low_obs, high_obs
self.low, self.high = low, high
self.obs_history = np.zeros(low_obs.shape, low_obs.dtype)
self.action_history = np.zeros(low_action.shape, low_action.dtype)
def _create_obs_from_history(self):
return np.concatenate((self.obs_history, self.action_history))
def reset(self):
# Flush the history
self.obs_history[...] = 0
self.action_history[...] = 0
obs_dict = self.env.reset()
obs = obs_dict[self.obs_key]
self.obs_history[..., -obs.shape[-1]:] = obs
obs_dict[self.obs_key] = self._create_obs_from_history()
return obs_dict
def step(self, action):
obs_dict, reward, done, info = self.env.step(action)
obs = obs_dict[self.obs_key]
last_ax_size = obs.shape[-1]
self.obs_history = np.roll(self.obs_history, shift=-last_ax_size, axis=-1)
self.obs_history[..., -obs.shape[-1]:] = obs
self.action_history = np.roll(self.action_history, shift=-action.shape[-1], axis=-1)
self.action_history[..., -action.shape[-1]:] = action
obs_dict[self.obs_key] = self._create_obs_from_history()
return obs_dict, reward, done, info
class FrameSkip(gym.Wrapper):
"""
Return only every ``skip``-th frame (frameskipping)
:param env: the environment
:param skip: number of ``skip``-th frame
"""
def __init__(self, env: gym.Env, skip: int = 4):
super().__init__(env)
print("Wrapping the env with FrameSkip.")
self._skip = skip
def step(self, action: np.ndarray):
"""
Step the environment with the given action
Repeat action, sum reward.
:param action: the action
:return: observation, reward, done, information
"""
total_reward = 0.0
done = None
for _ in range(self._skip):
obs, reward, done, info = self.env.step(action)
total_reward += reward
if done:
break
return obs, total_reward, done, info
def reset(self):
return self.env.reset()
def parse_wrapper_class(wrapper_class_str: str):
"""
Parse a string to a wrapper class.
:param wrapper_class_str: (str) The string to parse.
:return: (type) The wrapper class and its parameters.
"""
wrap_class, wrap_params = wrapper_class_str.split("_", 1)
wrap_params = wrap_params.split("_")
wrap_params = [int(param) if param.isnumeric() else param for param in wrap_params]
if wrap_class == "HistoryWrapperObsDict":
return HistoryWrapperObsDict, wrap_params
elif wrap_class == "FrameSkip":
return FrameSkip, wrap_params