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

[BugFix] Account for composite actions in gym #2718

Merged
merged 1 commit into from
Jan 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
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
74 changes: 73 additions & 1 deletion test/test_libs.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import importlib.util
import urllib.error

from gym.core import ObsType

_has_isaac = importlib.util.find_spec("isaacgym") is not None

if _has_isaac:
Expand All @@ -23,7 +25,7 @@
from contextlib import nullcontext
from pathlib import Path
from sys import platform
from typing import Optional, Union
from typing import Optional, Tuple, Union
from unittest import mock

import numpy as np
Expand Down Expand Up @@ -634,6 +636,76 @@ def test_torchrl_to_gym(self, backend, numpy):
finally:
set_gym_backend(gb).set()

@implement_for("gym", None, "0.26")
def test_gym_dict_action_space(self):
pytest.skip("tested for gym > 0.26 - no backward issue")

@implement_for("gym", "0.26", None)
def test_gym_dict_action_space(self): # noqa: F811
import gym
from gym import Env

class CompositeActionEnv(Env):
def __init__(self):
self.action_space = gym.spaces.Dict(
a0=gym.spaces.Discrete(2), a1=gym.spaces.Box(-1, 1)
)
self.observation_space = gym.spaces.Box(-1, 1)

def step(self, action):
return (0.5, 0.0, False, False, {})

def reset(
self,
*,
seed: Optional[int] = None,
options: Optional[dict] = None,
) -> Tuple[ObsType, dict]:
return (0.0, {})

env = CompositeActionEnv()
torchrl_env = GymWrapper(env)
assert isinstance(torchrl_env.action_spec, Composite)
assert len(torchrl_env.action_keys) == 2
r = torchrl_env.rollout(10)
assert isinstance(r[0]["a0"], torch.Tensor)
assert isinstance(r[0]["a1"], torch.Tensor)
assert r[0]["observation"] == 0
assert r[1]["observation"] == 0.5

@implement_for("gymnasium")
def test_gym_dict_action_space(self): # noqa: F811
import gymnasium as gym
from gymnasium import Env

class CompositeActionEnv(Env):
def __init__(self):
self.action_space = gym.spaces.Dict(
a0=gym.spaces.Discrete(2), a1=gym.spaces.Box(-1, 1)
)
self.observation_space = gym.spaces.Box(-1, 1)

def step(self, action):
return (0.5, 0.0, False, False, {})

def reset(
self,
*,
seed: Optional[int] = None,
options: Optional[dict] = None,
) -> Tuple[ObsType, dict]:
return (0.0, {})

env = CompositeActionEnv()
torchrl_env = GymWrapper(env)
assert isinstance(torchrl_env.action_spec, Composite)
assert len(torchrl_env.action_keys) == 2
r = torchrl_env.rollout(10)
assert isinstance(r[0]["a0"], torch.Tensor)
assert isinstance(r[0]["a1"], torch.Tensor)
assert r[0]["observation"] == 0
assert r[1]["observation"] == 0.5

@pytest.mark.parametrize(
"env_name",
[
Expand Down
5 changes: 4 additions & 1 deletion torchrl/envs/gym_like.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,10 @@ def read_obs(
return observations

def _step(self, tensordict: TensorDictBase) -> TensorDictBase:
action = tensordict.get(self.action_key)
if len(self.action_keys) == 1:
action = tensordict.get(self.action_key)
else:
action = tensordict.select(*self.action_keys).to_dict()
if self._convert_actions_to_numpy:
action = self.read_action(action)

Expand Down
Loading