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

[Example,BugFix] Add a Async gym env example #2139

Merged
merged 3 commits into from
Apr 30, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
init
  • Loading branch information
vmoens committed Apr 30, 2024
commit 9aec120007a656c2c3d2e754060c7ac2ab21e22c
84 changes: 84 additions & 0 deletions examples/envs/gym-async-info-reader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

"""
A toy example of executing a Gym environment asynchronously and gathering the info properly.
"""
import argparse

import gymnasium as gym
import numpy as np
from gymnasium import spaces

parser = argparse.ArgumentParser()
parser.add_argument("--use_wrapper", action="store_true")

# Create the dummy environment
class CustomEnv(gym.Env):
def __init__(self, render_mode=None):
self.observation_space = spaces.Box(low=-np.inf, high=np.inf, shape=(3,))
self.action_space = spaces.Box(low=-np.inf, high=np.inf, shape=(1,))

def _get_info(self):
return {"field1": self.state**2}

def _get_obs(self):
return self.state.copy()

def reset(self, seed=None, options=None):
# We need the following line to seed self.np_random
super().reset(seed=seed)
self.state = np.zeros(self.observation_space.shape)
observation = self._get_obs()
info = self._get_info()
return observation, info

def step(self, action):
self.state += action.item()
truncated = False
terminated = False
reward = 1 if terminated else 0 # Binary sparse rewards
observation = self._get_obs()
info = self._get_info()
return observation, reward, terminated, truncated, info


if __name__ == "__main__":
import torch
from torchrl.data.tensor_specs import UnboundedContinuousTensorSpec
from torchrl.envs import check_env_specs, GymEnv, GymWrapper

args = parser.parse_args()

num_envs = 10

if args.use_wrapper:
# Option 1: using GymWrapper
env = gym.vector.AsyncVectorEnv([lambda: CustomEnv() for _ in range(num_envs)])
env = GymWrapper(env, device="cpu")
else:
# Option 2: using GymEnv directly
gym.register("Custom-v0", CustomEnv)
env = GymEnv("Custom-v0", num_envs=num_envs)

keys = ["field1"]
specs = [
UnboundedContinuousTensorSpec(shape=(num_envs, 3), dtype=torch.float64),
]

reader = lambda info, tensordict: tensordict.set("field1", np.stack(info["field1"]))
env.set_info_dict_reader(info_dict_reader=reader)

# We need to unlock the specs to make them writable
env.observation_spec.unlock_()
env.observation_spec["field1"] = specs[0]
env.observation_spec.lock_()

# Check that we did a good job
check_env_specs(env)

td = env.reset()
print(td)
print(td["field1"])
10 changes: 8 additions & 2 deletions torchrl/data/tensor_specs.py
Original file line number Diff line number Diff line change
Expand Up @@ -1597,12 +1597,18 @@ def __init__(
if high is not None:
raise TypeError(self.CONFLICTING_KWARGS.format("high", "maximum"))
high = kwargs.pop("maximum")
warnings.warn("Maximum is deprecated since v0.4.0, using high instead.", category=DeprecationWarning)
warnings.warn(
"Maximum is deprecated since v0.4.0, using high instead.",
category=DeprecationWarning,
)
if "minimum" in kwargs:
if low is not None:
raise TypeError(self.CONFLICTING_KWARGS.format("low", "minimum"))
low = kwargs.pop("minimum")
warnings.warn("Minimum is deprecated since v0.4.0, using low instead.", category=DeprecationWarning)
warnings.warn(
"Minimum is deprecated since v0.4.0, using low instead.",
category=DeprecationWarning,
)
domain = kwargs.pop("domain", "continuous")
if len(kwargs):
raise TypeError(f"Got unrecognised kwargs {tuple(kwargs.keys())}.")
Expand Down
Loading