Closed marcusfechner closed 3 months ago
Hello, I think it is somehow an issue with gym. The workaround should be the one present in the RL Zoo: https://github.com/DLR-RM/rl-baselines3-zoo/blob/aa3814530ba8c5263267979bf14499734bfef86d/rl_zoo3/exp_manager.py#L612-L616
Thank you so much @araffin. Works like a charm. Here is the modified code for all other people.
from typing import Callable
import gymnasium as gym
from gymnasium.envs.registration import register
from minigrid.wrappers import ImgObsWrapper
from stable_baselines3.common.utils import set_random_seed
from stable_baselines3.common.vec_env import DummyVecEnv, SubprocVecEnv
def register_minigrid_envs():
"""Register custom Minigrid environments.
"""
register(
id="MiniGrid-Dynamic-Obstacles-Random-16x16-v0",
entry_point="minigrid.envs:DynamicObstaclesEnv",
kwargs={"size": 16, "agent_start_pos": None, "n_obstacles": 5},
)
def make_env(env_id: str, rank: int, seed: int = 0) -> Callable:
"""
Utility function for multiprocessed env.
:param env_id: (str) the environment ID
:param num_env: (int) the number of environment you wish to have in subprocesses
:param seed: (int) the inital seed for RNG
:param rank: (int) index of the subprocess
:return: (Callable)
"""
spec = gym.spec(env_id)
# Define make_env here, so it works with subprocesses
# when the registry was modified with `--gym-packages`
# See https://github.com/HumanCompatibleAI/imitation/pull/160
def make_env(**kwargs) -> gym.Env:
return spec.make(**kwargs)
def _init() -> gym.Env:
env = make_env()
env = ImgObsWrapper(env)
env.reset(seed=seed + rank)
return env
set_random_seed(seed)
return _init
if __name__ == "__main__":
register_minigrid_envs()
env_name = "MiniGrid-Dynamic-Obstacles-Random-16x16-v0"
dummy_vec_env = DummyVecEnv([make_env(env_name, rank=i) for i in range(2)])
print("Dummy vector environments work with custom registered environments. :)")
subproc_vec_env = SubprocVecEnv([make_env(env_name, rank=i) for i in range(2)])
print("Multiprocessing vector environments now work with custom registered environments. :)")
good to hear =) another solution might be to use the "package:env-id" syntax when registering the env.
🐛 Bug
Hi,
I found it very strange, that when I register custom environments they are not found when using SubprocVecEnv. I guess it has to do with how things are handles with multiprocessing. A temporary, but unsave hotfix would be to set
SubprocVecEnv(..., start_method="fork")
.I would highly appreciate any help or feedback, because this is driving me crazy. Furthermore I looked into using the gymnasium.vector.SyncVectorEnv, which works upon creation, but is not compatible with SB3.
Thanks for your help, Marcus
Package install:
Code example
Relevant log output / Error message
System Info
pygame 2.5.2 (SDL 2.28.3, Python 3.10.13) Hello from the pygame community. https://www.pygame.org/contribute.html
Checklist