forked from irom-princeton/dppo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
multi_step.py
281 lines (239 loc) · 8.7 KB
/
multi_step.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
"""
Multi-step wrapper. Allow executing multiple environmnt steps. Returns stacked observation and optionally stacked previous action.
Modified from https://github.com/real-stanford/diffusion_policy/blob/main/diffusion_policy/gym_util/multistep_wrapper.py
TODO: allow cond_steps != img_cond_steps (should be implemented in training scripts, not here)
"""
import gym
from typing import Optional
from gym import spaces
import numpy as np
from collections import defaultdict, deque
def stack_repeated(x, n):
return np.repeat(np.expand_dims(x, axis=0), n, axis=0)
def repeated_box(box_space, n):
return spaces.Box(
low=stack_repeated(box_space.low, n),
high=stack_repeated(box_space.high, n),
shape=(n,) + box_space.shape,
dtype=box_space.dtype,
)
def repeated_space(space, n):
if isinstance(space, spaces.Box):
return repeated_box(space, n)
elif isinstance(space, spaces.Dict):
result_space = spaces.Dict()
for key, value in space.items():
result_space[key] = repeated_space(value, n)
return result_space
else:
raise RuntimeError(f"Unsupported space type {type(space)}")
def take_last_n(x, n):
x = list(x)
n = min(len(x), n)
return np.array(x[-n:])
def dict_take_last_n(x, n):
result = dict()
for key, value in x.items():
result[key] = take_last_n(value, n)
return result
def aggregate(data, method="max"):
if method == "max":
# equivalent to any
return np.max(data)
elif method == "min":
# equivalent to all
return np.min(data)
elif method == "mean":
return np.mean(data)
elif method == "sum":
return np.sum(data)
else:
raise NotImplementedError()
def stack_last_n_obs(all_obs, n_steps):
"""Apply padding"""
assert len(all_obs) > 0
all_obs = list(all_obs)
result = np.zeros((n_steps,) + all_obs[-1].shape, dtype=all_obs[-1].dtype)
start_idx = -min(n_steps, len(all_obs))
result[start_idx:] = np.array(all_obs[start_idx:])
if n_steps > len(all_obs):
# pad
result[:start_idx] = result[start_idx]
return result
class MultiStep(gym.Wrapper):
def __init__(
self,
env,
n_obs_steps=1,
n_action_steps=1,
max_episode_steps=None,
reward_agg_method="sum", # never use other types
prev_action=True,
reset_within_step=False,
pass_full_observations=False,
verbose=False,
**kwargs,
):
super().__init__(env)
self._single_action_space = env.action_space
self._action_space = repeated_space(env.action_space, n_action_steps)
self._observation_space = repeated_space(env.observation_space, n_obs_steps)
self.max_episode_steps = max_episode_steps
self.n_obs_steps = n_obs_steps
self.n_action_steps = n_action_steps
self.reward_agg_method = reward_agg_method
self.prev_action = prev_action
self.reset_within_step = reset_within_step
self.pass_full_observations = pass_full_observations
self.verbose = verbose
def reset(
self,
seed: Optional[int] = None,
return_info: bool = False,
options: dict = {},
):
"""Resets the environment."""
obs = self.env.reset(
seed=seed,
options=options,
return_info=return_info,
)
self.obs = deque([obs], maxlen=max(self.n_obs_steps + 1, self.n_action_steps))
if self.prev_action:
self.action = deque(
[self._single_action_space.sample()], maxlen=self.n_obs_steps
)
self.reward = list()
self.done = list()
self.info = defaultdict(lambda: deque(maxlen=self.n_obs_steps + 1))
obs = self._get_obs(self.n_obs_steps)
self.cnt = 0
return obs
def step(self, action):
"""
actions: (n_action_steps,) + action_shape
"""
if action.ndim == 1: # in case action_steps = 1
action = action[None]
truncated = False
terminated = False
for act_step, act in enumerate(action):
self.cnt += 1
if terminated or truncated:
break
# done does not differentiate terminal and truncation
observation, reward, done, info = self.env.step(act)
self.obs.append(observation)
self.action.append(act)
self.reward.append(reward)
# in gym, timelimit wrapper is automatically used given env._spec.max_episode_steps
if "TimeLimit.truncated" not in info:
if done:
terminated = True
elif (
self.max_episode_steps is not None
) and self.cnt >= self.max_episode_steps:
truncated = True
else:
truncated = info["TimeLimit.truncated"]
terminated = done
done = truncated or terminated
self.done.append(done)
self._add_info(info)
observation = self._get_obs(self.n_obs_steps)
reward = aggregate(self.reward, self.reward_agg_method)
done = aggregate(self.done, "max")
info = dict_take_last_n(self.info, self.n_obs_steps)
if self.pass_full_observations:
info["full_obs"] = self._get_obs(act_step + 1)
# In mujoco case, done can happen within the loop above
if self.reset_within_step and self.done[-1]:
# need to save old observation in the case of truncation only, for bootstrapping
if truncated:
info["final_obs"] = observation
# reset
observation = (
self.reset()
) # TODO: arguments? this cannot handle video recording right now since needs to pass in options
self.verbose and print("Reset env within wrapper.")
# reset reward and done for next step
self.reward = list()
self.done = list()
return observation, reward, terminated, truncated, info
def _get_obs(self, n_steps=1):
"""
Output (n_steps,) + obs_shape
"""
assert len(self.obs) > 0
if isinstance(self.observation_space, spaces.Box):
return stack_last_n_obs(self.obs, n_steps)
elif isinstance(self.observation_space, spaces.Dict):
result = dict()
for key in self.observation_space.keys():
result[key] = stack_last_n_obs([obs[key] for obs in self.obs], n_steps)
return result
else:
raise RuntimeError("Unsupported space type")
def get_prev_action(self, n_steps=None):
if n_steps is None:
n_steps = self.n_obs_steps - 1 # exclude current step
assert len(self.action) > 0
return stack_last_n_obs(self.action, n_steps)
def _add_info(self, info):
for key, value in info.items():
self.info[key].append(value)
def render(self, **kwargs):
"""Not the best design"""
return self.env.render(**kwargs)
if __name__ == "__main__":
import os
from omegaconf import OmegaConf
import json
os.environ["MUJOCO_GL"] = "egl"
cfg = OmegaConf.load("cfg/robomimic/finetune/can/ft_ppo_diffusion_mlp_img.yaml")
shape_meta = cfg["shape_meta"]
import robomimic.utils.env_utils as EnvUtils
import robomimic.utils.obs_utils as ObsUtils
import matplotlib.pyplot as plt
from env.gym_utils.wrapper.robomimic_image import RobomimicImageWrapper
wrappers = cfg.env.wrappers
obs_modality_dict = {
"low_dim": (
wrappers.robomimic_image.low_dim_keys
if "robomimic_image" in wrappers
else wrappers.robomimic_lowdim.low_dim_keys
),
"rgb": (
wrappers.robomimic_image.image_keys
if "robomimic_image" in wrappers
else None
),
}
if obs_modality_dict["rgb"] is None:
obs_modality_dict.pop("rgb")
ObsUtils.initialize_obs_modality_mapping_from_dict(obs_modality_dict)
with open(cfg.robomimic_env_cfg_path, "r") as f:
env_meta = json.load(f)
env = EnvUtils.create_env_from_metadata(
env_meta=env_meta,
render=False,
render_offscreen=False,
use_image_obs=True,
)
env.env.hard_reset = False
wrapper = MultiStep(
env=RobomimicImageWrapper(
env=env,
shape_meta=shape_meta,
image_keys=["robot0_eye_in_hand_image"],
),
n_obs_steps=1,
n_action_steps=1,
)
wrapper.seed(0)
obs = wrapper.reset()
print(obs.keys())
img = wrapper.render()
wrapper.close()
plt.imshow(img)
plt.savefig("test.png")