|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# |
| 3 | +# This source code is licensed under the MIT license found in the |
| 4 | +# LICENSE file in the root directory of this source tree. |
| 5 | +import importlib.util |
| 6 | + |
| 7 | +import itertools |
| 8 | +import warnings |
| 9 | +from typing import Any, Dict, List, Union |
| 10 | + |
| 11 | +import numpy as np |
| 12 | +import torch |
| 13 | + |
| 14 | +from tensordict import TensorDictBase |
| 15 | +from torchrl.envs import make_composite_from_td |
| 16 | +from torchrl.envs.libs.gym import GymWrapper |
| 17 | + |
| 18 | +_has_isaac = importlib.util.find_spec("isaacgym") is not None |
| 19 | + |
| 20 | + |
| 21 | +class IsaacGymWrapper(GymWrapper): |
| 22 | + """Wrapper for IsaacGymEnvs environments. |
| 23 | +
|
| 24 | + The original library can be found `here <https://github.com/NVIDIA-Omniverse/IsaacGymEnvs>`_ |
| 25 | + and is based on IsaacGym which can be downloaded `through NVIDIA's webpage <https://developer.nvidia.com/isaac-gym>_`. |
| 26 | +
|
| 27 | + .. note:: IsaacGym environments cannot be executed consecutively, ie. instantiating one |
| 28 | + environment after another (even if it has been cleared) will cause |
| 29 | + CUDA memory issues. We recommend creating one environment per process only. |
| 30 | + If you need more than one environment, the best way to achieve that is |
| 31 | + to spawn them across processes. |
| 32 | +
|
| 33 | + .. note:: IsaacGym works on CUDA devices by essence. Make sure your machine |
| 34 | + has GPUs available and the required setup for IsaacGym (eg, Ubuntu 20.04). |
| 35 | +
|
| 36 | + """ |
| 37 | + |
| 38 | + def __init__( |
| 39 | + self, env: "isaacgymenvs.tasks.base.vec_task.Env", **kwargs |
| 40 | + ): # noqa: F821 |
| 41 | + warnings.warn( |
| 42 | + "IsaacGym environment support is an experimental feature that may change in the future." |
| 43 | + ) |
| 44 | + num_envs = env.num_envs |
| 45 | + super().__init__( |
| 46 | + env, torch.device(env.device), batch_size=torch.Size([num_envs]), **kwargs |
| 47 | + ) |
| 48 | + if not hasattr(self, "task"): |
| 49 | + # by convention in IsaacGymEnvs |
| 50 | + self.task = env.__name__ |
| 51 | + |
| 52 | + def _make_specs(self, env: "gym.Env") -> None: # noqa: F821 |
| 53 | + super()._make_specs(env, batch_size=self.batch_size) |
| 54 | + self.done_spec = self.done_spec.squeeze(-1) |
| 55 | + self.observation_spec["obs"] = self.observation_spec["observation"] |
| 56 | + del self.observation_spec["observation"] |
| 57 | + |
| 58 | + data = self.rollout(3).get("next")[..., 0] |
| 59 | + del data[self.reward_key] |
| 60 | + del data[self.done_key] |
| 61 | + specs = make_composite_from_td(data) |
| 62 | + |
| 63 | + obs_spec = self.observation_spec |
| 64 | + obs_spec.unlock_() |
| 65 | + obs_spec.update(specs) |
| 66 | + obs_spec.lock_() |
| 67 | + self.__dict__["_observation_spec"] = obs_spec |
| 68 | + |
| 69 | + @classmethod |
| 70 | + def _make_envs(cls, *, task, num_envs, device, seed=None, headless=True, **kwargs): |
| 71 | + import isaacgym # noqa |
| 72 | + import isaacgymenvs # noqa |
| 73 | + |
| 74 | + envs = isaacgymenvs.make( |
| 75 | + seed=seed, |
| 76 | + task=task, |
| 77 | + num_envs=num_envs, |
| 78 | + sim_device=str(device), |
| 79 | + rl_device=str(device), |
| 80 | + headless=headless, |
| 81 | + **kwargs, |
| 82 | + ) |
| 83 | + return envs |
| 84 | + |
| 85 | + def _set_seed(self, seed: int) -> int: |
| 86 | + # as of #665c32170d84b4be66722eea405a1e08b6e7f761 the seed points nowhere in gym.make for IsaacGymEnvs |
| 87 | + return seed |
| 88 | + |
| 89 | + def read_action(self, action): |
| 90 | + """Reads the action obtained from the input TensorDict and transforms it in the format expected by the contained environment. |
| 91 | +
|
| 92 | + Args: |
| 93 | + action (Tensor or TensorDict): an action to be taken in the environment |
| 94 | +
|
| 95 | + Returns: an action in a format compatible with the contained environment. |
| 96 | +
|
| 97 | + """ |
| 98 | + return action |
| 99 | + |
| 100 | + def read_done(self, done): |
| 101 | + """Done state reader. |
| 102 | +
|
| 103 | + Reads a done state and returns a tuple containing: |
| 104 | + - a done state to be set in the environment |
| 105 | + - a boolean value indicating whether the frame_skip loop should be broken |
| 106 | +
|
| 107 | + Args: |
| 108 | + done (np.ndarray, boolean or other format): done state obtained from the environment |
| 109 | +
|
| 110 | + """ |
| 111 | + return done.bool(), done.any() |
| 112 | + |
| 113 | + def read_reward(self, total_reward, step_reward): |
| 114 | + """Reads a reward and the total reward so far (in the frame skip loop) and returns a sum of the two. |
| 115 | +
|
| 116 | + Args: |
| 117 | + total_reward (torch.Tensor or TensorDict): total reward so far in the step |
| 118 | + step_reward (reward in the format provided by the inner env): reward of this particular step |
| 119 | +
|
| 120 | + """ |
| 121 | + return total_reward + step_reward |
| 122 | + |
| 123 | + def read_obs( |
| 124 | + self, observations: Union[Dict[str, Any], torch.Tensor, np.ndarray] |
| 125 | + ) -> Dict[str, Any]: |
| 126 | + """Reads an observation from the environment and returns an observation compatible with the output TensorDict. |
| 127 | +
|
| 128 | + Args: |
| 129 | + observations (observation under a format dictated by the inner env): observation to be read. |
| 130 | +
|
| 131 | + """ |
| 132 | + if isinstance(observations, dict): |
| 133 | + if "state" in observations and "observation" not in observations: |
| 134 | + # we rename "state" in "observation" as "observation" is the conventional name |
| 135 | + # for single observation in torchrl. |
| 136 | + # naming it 'state' will result in envs that have a different name for the state vector |
| 137 | + # when queried with and without pixels |
| 138 | + observations["observation"] = observations.pop("state") |
| 139 | + if not isinstance(observations, (TensorDictBase, dict)): |
| 140 | + (key,) = itertools.islice(self.observation_spec.keys(True, True), 1) |
| 141 | + observations = {key: observations} |
| 142 | + return observations |
| 143 | + |
| 144 | + |
| 145 | +class IsaacGymEnv(IsaacGymWrapper): |
| 146 | + """A TorchRL Env interface for IsaacGym environments. |
| 147 | +
|
| 148 | + See :class:`~.IsaacGymWrapper` for more information. |
| 149 | +
|
| 150 | + Examples: |
| 151 | + >>> env = IsaacGymEnv(task="Ant", num_envs=2000, device="cuda:0") |
| 152 | + >>> rollout = env.rollout(3) |
| 153 | + >>> assert env.batch_size == (2000,) |
| 154 | +
|
| 155 | + """ |
| 156 | + |
| 157 | + @property |
| 158 | + def available_envs(cls) -> List[str]: |
| 159 | + import isaacgymenvs # noqa |
| 160 | + |
| 161 | + return list(isaacgymenvs.tasks.isaacgym_task_map.keys()) |
| 162 | + |
| 163 | + def __init__(self, task=None, *, env=None, num_envs, device, **kwargs): |
| 164 | + if env is not None and task is not None: |
| 165 | + raise RuntimeError("Cannot provide both `task` and `env` arguments.") |
| 166 | + elif env is not None: |
| 167 | + task = env |
| 168 | + envs = self._make_envs(task=task, num_envs=num_envs, device=device, **kwargs) |
| 169 | + self.task = task |
| 170 | + super().__init__(envs, **kwargs) |
0 commit comments