-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathregistration.py
299 lines (248 loc) · 9.84 KB
/
registration.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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
"""Registers environments within gymnasium for optional modules."""
from __future__ import annotations
from collections import defaultdict
from functools import partial
from typing import Any, Callable, Mapping, NamedTuple, Sequence
import numpy as np
from gymnasium.envs.registration import register, registry
from shimmy.utils.envs_configs import (
ALL_ATARI_GAMES,
BSUITE_ENVS,
DM_CONTROL_MANIPULATION_ENVS,
DM_CONTROL_SUITE_ENVS,
LEGACY_ATARI_GAMES,
)
def _register_bsuite_envs():
"""Registers all bsuite environments in gymnasium."""
try:
import bsuite
except ImportError:
return
from bsuite.environments import Environment
from shimmy.bsuite_compatibility import BSuiteCompatibilityV0
# Add generic environment support
def _make_bsuite_generic_env(env: Environment, render_mode: str):
return BSuiteCompatibilityV0(env, render_mode=render_mode)
register("bsuite/compatibility-env-v0", _make_bsuite_generic_env)
# register all prebuilt envs
def _make_bsuite_env(env_id: str, **env_kwargs: Mapping[str, Any]):
env = bsuite.load(env_id, env_kwargs)
return BSuiteCompatibilityV0(env)
# non deterministic envs
nondeterministic = ["deep_sea", "bandit", "discounting_chain"]
for env_id in BSUITE_ENVS:
register(
f"bsuite/{env_id}-v0",
partial(_make_bsuite_env, env_id=env_id),
nondeterministic=env_id in nondeterministic,
)
def _register_dm_control_envs():
"""Registers all dm-control environments in gymnasium."""
try:
import dm_control
except ImportError:
return
from shimmy.dm_control_compatibility import DmControlCompatibilityV0
# Add generic environment support
def _make_dm_control_generic_env(env, **render_kwargs):
return DmControlCompatibilityV0(env, **render_kwargs)
register("dm_control/compatibility-env-v0", _make_dm_control_generic_env)
# Register all suite environments
import dm_control.suite
def _make_dm_control_suite_env(
domain_name: str,
task_name: str,
task_kwargs: dict[str, Any] | None = None,
environment_kwargs: dict[str, Any] | None = None,
visualize_reward: bool = False,
**render_kwargs,
):
"""The entry_point function for registration of dm-control environments."""
env = dm_control.suite.load(
domain_name=domain_name,
task_name=task_name,
task_kwargs=task_kwargs,
environment_kwargs=environment_kwargs,
visualize_reward=visualize_reward,
)
return DmControlCompatibilityV0(env, **render_kwargs)
for _domain_name, _task_name in DM_CONTROL_SUITE_ENVS:
register(
f"dm_control/{_domain_name}-{_task_name}-v0",
partial(
_make_dm_control_suite_env,
domain_name=_domain_name,
task_name=_task_name,
),
)
# Register all example locomotion environments
# Listed in https://github.com/deepmind/dm_control/blob/main/dm_control/locomotion/examples/examples_test.py
from dm_control import composer
from dm_control.locomotion.examples import basic_cmu_2019, basic_rodent_2020
def _make_dm_control_example_locomotion_env(
env_fn: Callable[[np.random.RandomState | None], composer.Environment],
random_state: np.random.RandomState | None = None,
**render_kwargs,
):
return DmControlCompatibilityV0(env_fn(random_state), **render_kwargs)
for locomotion_env, nondeterministic in (
(basic_cmu_2019.cmu_humanoid_run_walls, False),
(basic_cmu_2019.cmu_humanoid_run_gaps, False),
(basic_cmu_2019.cmu_humanoid_go_to_target, False),
(basic_cmu_2019.cmu_humanoid_maze_forage, True),
(basic_cmu_2019.cmu_humanoid_heterogeneous_forage, True),
(basic_rodent_2020.rodent_escape_bowl, False),
(basic_rodent_2020.rodent_run_gaps, False),
(basic_rodent_2020.rodent_maze_forage, True),
(basic_rodent_2020.rodent_two_touch, True),
# (cmu_2020_tracking.cmu_humanoid_tracking, False),
):
register(
f"dm_control/{locomotion_env.__name__.title().replace('_', '')}-v0",
partial(_make_dm_control_example_locomotion_env, env_fn=locomotion_env),
nondeterministic=nondeterministic,
)
# Register all manipulation environments
import dm_control.manipulation
def _make_dm_control_manipulation_env(env_name: str, **render_kwargs):
env = dm_control.manipulation.load(env_name)
return DmControlCompatibilityV0(env, **render_kwargs)
for env_name in DM_CONTROL_MANIPULATION_ENVS:
register(
f"dm_control/{env_name}-v0",
partial(_make_dm_control_manipulation_env, env_name=env_name),
nondeterministic=env_name.startswith("reassemble_5_bricks_random_order"),
)
class GymFlavour(NamedTuple):
"""A Gym Flavour."""
suffix: str
kwargs: Mapping[str, Any] | Callable[[str], Mapping[str, Any]]
class GymConfig(NamedTuple):
"""A Gym Configuration."""
version: str
kwargs: Mapping[str, Any]
flavours: Sequence[GymFlavour]
def _register_atari_configs(
roms: Sequence[str],
obs_types: Sequence[str],
configs: Sequence[GymConfig],
prefix: str = "",
):
from ale_py.roms import utils as rom_utils
for rom in roms:
for obs_type in obs_types:
for config in configs:
for flavour in config.flavours:
name = rom_utils.rom_id_to_name(rom)
if obs_type == "ram":
name = f"{name}-ram"
# Parse config kwargs
if callable(config.kwargs):
config_kwargs = config.kwargs(rom)
else:
config_kwargs = config.kwargs
# Parse flavour kwargs
if callable(flavour.kwargs):
flavour_kwargs = flavour.kwargs(rom)
else:
flavour_kwargs = flavour.kwargs
# Register the environment
register(
id=f"{prefix}{name}{flavour.suffix}-{config.version}",
entry_point="shimmy.atari_env:AtariEnv",
kwargs={
"game": rom,
"obs_type": obs_type,
**config_kwargs,
**flavour_kwargs,
},
)
def _register_atari_envs():
try:
import ale_py
except ImportError:
return
frameskip: dict[str, int] = defaultdict(lambda: 4, [("space_invaders", 3)])
configs = [
GymConfig(
version="v0",
kwargs={
"repeat_action_probability": 0.25,
"full_action_space": False,
"max_num_frames_per_episode": 108_000,
},
flavours=[
# Default for v0 has 10k steps, no idea why...
GymFlavour("", {"frameskip": (2, 5)}),
# Deterministic has 100k steps, close to the standard of 108k (30 mins gameplay)
GymFlavour("Deterministic", lambda rom: {"frameskip": frameskip[rom]}),
# NoFrameSkip imposes a max episode steps of frameskip * 100k, weird...
GymFlavour("NoFrameskip", {"frameskip": 1}),
],
),
GymConfig(
version="v4",
kwargs={
"repeat_action_probability": 0.0,
"full_action_space": False,
"max_num_frames_per_episode": 108_000,
},
flavours=[
# Unlike v0, v4 has 100k max episode steps
GymFlavour("", {"frameskip": (2, 5)}),
GymFlavour("Deterministic", lambda rom: {"frameskip": frameskip[rom]}),
# Same weird frameskip * 100k max steps for v4?
GymFlavour("NoFrameskip", {"frameskip": 1}),
],
),
]
_register_atari_configs(
LEGACY_ATARI_GAMES, obs_types=("rgb", "ram"), configs=configs
)
# max_episode_steps is 108k frames which is 30 mins of gameplay.
# This corresponds to 108k / 4 = 27,000 steps
configs = [
GymConfig(
version="v5",
kwargs={
"repeat_action_probability": 0.25,
"full_action_space": False,
"frameskip": 4,
"max_num_frames_per_episode": 108_000,
},
flavours=[GymFlavour("", {})],
)
]
_register_atari_configs(
ALL_ATARI_GAMES, obs_types=("rgb", "ram"), configs=configs, prefix="ALE/"
)
def _register_dm_lab():
try:
import deepmind_lab
except ImportError:
return
from shimmy.dm_lab_compatibility import DmLabCompatibilityV0
def _make_dm_lab_env(
env_id: str, observations, config: dict[str, Any], renderer: str
):
env = deepmind_lab.Lab(env_id, observations, config=config, renderer=renderer)
return DmLabCompatibilityV0(env)
register(id="DmLabCompatibility-v0", entry_point=_make_dm_lab_env)
def register_gymnasium_envs():
"""This function is called when gymnasium is imported."""
if "GymV26Environment-v0" in registry:
registry.pop("GymV26Environment-v0")
register(
id="GymV26Environment-v0",
entry_point="shimmy.openai_gym_compatibility:GymV26CompatibilityV0",
)
if "GymV21Environment-v0" in registry:
registry.pop("GymV21Environment-v0")
register(
id="GymV21Environment-v0",
entry_point="shimmy.openai_gym_compatibility:GymV21CompatibilityV0",
)
_register_bsuite_envs()
_register_dm_control_envs()
_register_atari_envs()
_register_dm_lab()