Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature] Add support of non-pickable gym env #1615

Merged
merged 3 commits into from
Oct 9, 2023
Merged

Conversation

duburcqa
Copy link
Contributor

@duburcqa duburcqa commented Oct 8, 2023

Description

Currently, trying to instantiate a gym environment that is not pickable will fail. Here is a minimal reproducible example:

from torchrl.envs import GymEnv
penv = GymEnv("gym_jiminy.envs:atlas-pid", num_envs=1, device="cpu")

The trace is the following:

RuntimeError                              Traceback (most recent call last)
Cell In[2], line 1
----> 1 penv = GymEnv("gym_jiminy.envs:atlas-pid", num_envs=1, device="cpu")

File ~/.local/lib/python3.10/site-packages/torchrl/envs/libs/gym.py:391, in _AsyncMeta.__call__(cls, *args, **kwargs)
    390 def __call__(cls, *args, **kwargs):
--> 391     instance: GymWrapper = super().__call__(*args, **kwargs)
    393     # before gym 0.22, there was no final_observation
    394     if instance._is_batched:

File ~/.local/lib/python3.10/site-packages/torchrl/envs/common.py:134, in _EnvPostInit.__call__(cls, *args, **kwargs)
    133 def __call__(cls, *args, **kwargs):
--> 134     instance: EnvBase = super().__call__(*args, **kwargs)
    135     # we create the done spec by adding a done/terminated entry if one is missing
    136     instance._create_done_specs()

File ~/.local/lib/python3.10/site-packages/torchrl/envs/libs/gym.py:949, in GymEnv.__init__(self, env_name, **kwargs)
    947 kwargs["env_name"] = env_name
    948 self._set_gym_args(kwargs)
--> 949 super().__init__(**kwargs)

File ~/.local/lib/python3.10/site-packages/torchrl/envs/libs/gym.py:500, in GymWrapper.__init__(self, env, categorical_action_encoding, **kwargs)
    498         super().__init__(**kwargs)
    499 else:
--> 500     super().__init__(**kwargs)
    501 self._post_init()

File ~/.local/lib/python3.10/site-packages/torchrl/envs/common.py:2028, in _EnvWrapper.__init__(self, dtype, device, batch_size, allow_done_after
   2026 self._constructor_kwargs = kwargs
   2027 self._check_kwargs(kwargs)
-> 2028 self._env = self._build_env(**kwargs)  # writes the self._env attribute
   2029 self._make_specs(self._env)  # writes the self._env attribute
   2030 self.is_closed = False

File ~/.local/lib/python3.10/site-packages/torchrl/envs/libs/gym.py:1019, in GymEnv._build_env(self, env_name, **kwargs)
   1017 env = super()._build_env(env, pixels_only=pixels_only, from_pixels=from_pixels)
   1018 if num_envs > 0:
-> 1019     env = self._async_env([CloudpickleWrapper(lambda: env)] * num_envs)
   1020     self.batch_size = torch.Size([num_envs, *self.batch_size])
   1021 return env

File ~/.local/lib/python3.10/site-packages/torchrl/envs/libs/gym.py:974, in GymEnv._async_env(self, *args, **kwargs)
    973 def _async_env(self, *args, **kwargs):
--> 974     return gym_backend("vector").AsyncVectorEnv(*args, **kwargs)

File ~/.local/lib/python3.10/site-packages/gymnasium/vector/async_vector_env.py:165, in AsyncVectorEnv.__init__(self, env_fns, observation_space,
)
    162         self.processes.append(process)
    164         process.daemon = daemon
--> 165         process.start()
    166         child_pipe.close()
    168 self._state = AsyncState.DEFAULT

File /usr/lib/python3.10/multiprocessing/process.py:121, in BaseProcess.start(self)
    118 assert not _current_process._config.get('daemon'), \
    119        'daemonic processes are not allowed to have children'
    120 _cleanup()
--> 121 self._popen = self._Popen(self)
    122 self._sentinel = self._popen.sentinel
    123 # Avoid a refcycle if the target function holds an indirect
    124 # reference to the process object (see bpo-30775)

File /usr/lib/python3.10/multiprocessing/context.py:288, in SpawnProcess._Popen(process_obj)
    285 @staticmethod
    286 def _Popen(process_obj):
    287     from .popen_spawn_posix import Popen
--> 288     return Popen(process_obj)

File /usr/lib/python3.10/multiprocessing/popen_spawn_posix.py:32, in Popen.__init__(self, process_obj)
     30 def __init__(self, process_obj):
     31     self._fds = []
---> 32     super().__init__(process_obj)

File /usr/lib/python3.10/multiprocessing/popen_fork.py:19, in Popen.__init__(self, process_obj)
     17 self.returncode = None
     18 self.finalizer = None
---> 19 self._launch(process_obj)

File /usr/lib/python3.10/multiprocessing/popen_spawn_posix.py:47, in Popen._launch(self, process_obj)
     45 try:
     46     reduction.dump(prep_data, fp)
---> 47     reduction.dump(process_obj, fp)
     48 finally:
     49     set_spawning_popen(None)

File /usr/lib/python3.10/multiprocessing/reduction.py:60, in dump(obj, file, protocol)
     58 def dump(obj, file, protocol=None):
     59     '''Replacement for pickle.dump() using ForkingPickler.'''
---> 60     ForkingPickler(file, protocol).dump(obj)

File ~/.local/lib/python3.10/site-packages/gymnasium/vector/utils/misc.py:25, in CloudpickleWrapper.__getstate__(self)
     22 """Get the state using `cloudpickle.dumps(self.fn)`."""
     23 import cloudpickle
---> 25 return cloudpickle.dumps(self.fn)

File ~/.local/lib/python3.10/site-packages/cloudpickle/cloudpickle_fast.py:62, in dumps(obj, protocol)
     60 with io.BytesIO() as file:
     61     cp = CloudPickler(file, protocol=protocol)
---> 62     cp.dump(obj)
     63     return file.getvalue()

File ~/.local/lib/python3.10/site-packages/cloudpickle/cloudpickle_fast.py:538, in CloudPickler.dump(self, obj)
    536 def dump(self, obj):
    537     try:
--> 538         return Pickler.dump(self, obj)
    539     except RuntimeError as e:
    540         if "recursion" in e.args[0]:

File ~/.local/lib/python3.10/site-packages/torchrl/data/utils.py:240, in CloudpickleWrapper.__getstate__(self)
    237 def __getstate__(self):
    238     import cloudpickle
--> 240     return cloudpickle.dumps((self.fn, self.kwargs))

File ~/.local/lib/python3.10/site-packages/cloudpickle/cloudpickle_fast.py:62, in dumps(obj, protocol)
     60 with io.BytesIO() as file:
     61     cp = CloudPickler(file, protocol=protocol)
---> 62     cp.dump(obj)
     63     return file.getvalue()

File ~/.local/lib/python3.10/site-packages/cloudpickle/cloudpickle_fast.py:538, in CloudPickler.dump(self, obj)
    536 def dump(self, obj):
    537     try:
--> 538         return Pickler.dump(self, obj)
    539     except RuntimeError as e:
    540         if "recursion" in e.args[0]:

RuntimeError: Pickling of "jiminy_py.core.PeriodicGaussianProcess" instances is not enabled (http://www.boost.org/libs/python/doc/v2/pickle.html)

Types of changes

What types of changes does your code introduce? Remove all that do not apply:

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds core functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation (update in the documentation)
  • Example (update in the folder of examples)

Checklist

Go over all the following points, and put an x in all the boxes that apply.
If you are unsure about any of these, don't hesitate to ask. We are here to help!

  • I have read the CONTRIBUTION guide (required)
  • My change requires a change to the documentation.
  • I have updated the tests accordingly (required for a bug fix or a new feature).
  • I have updated the documentation accordingly.

@facebook-github-bot
Copy link

Hi @duburcqa!

Thank you for your pull request and welcome to our community.

Action Required

In order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you.

Process

In order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA.

Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with CLA signed. The tagging process may take up to 1 hour after signing. Please give it that time before contacting us about it.

If you have received this in error or have any questions, please contact us at [email protected]. Thanks!

@facebook-github-bot facebook-github-bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Oct 8, 2023
@facebook-github-bot
Copy link

Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks!

Copy link
Contributor

@vmoens vmoens left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM thanks for this!
Can you sign the CLA? After that I can merge this

@vmoens vmoens changed the title Add support of non-pickable gym env [Feature] Add support of non-pickable gym env Oct 9, 2023
@vmoens vmoens added the enhancement New feature or request label Oct 9, 2023
@vmoens vmoens merged commit f121701 into pytorch:main Oct 9, 2023
vmoens pushed a commit to hyerra/rl that referenced this pull request Oct 10, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants