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] Fix Gym Categorical/One-hot issues #1482

Merged
merged 8 commits into from
Sep 3, 2023
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
Prev Previous commit
Next Next commit
lint
  • Loading branch information
vmoens committed Sep 2, 2023
commit 1332824f8c80a8bb6b2cb57c5514587e04c37d50
10 changes: 2 additions & 8 deletions test/test_libs.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,17 +294,11 @@ def info_reader(info, tensordict):

def test_one_hot_and_categorical(self):
# tests that one-hot and categorical work ok when an integer is expected as action
cliff_walking = GymEnv(
'CliffWalking-v0',
categorical_action_encoding=True
)
cliff_walking = GymEnv("CliffWalking-v0", categorical_action_encoding=True)
cliff_walking.rollout(10)
check_env_specs(cliff_walking)

cliff_walking = GymEnv(
'CliffWalking-v0',
categorical_action_encoding=False
)
cliff_walking = GymEnv("CliffWalking-v0", categorical_action_encoding=False)
cliff_walking.rollout(10)
check_env_specs(cliff_walking)

Expand Down
7 changes: 2 additions & 5 deletions torchrl/data/tensor_specs.py
Original file line number Diff line number Diff line change
Expand Up @@ -1261,9 +1261,6 @@ def to_numpy(self, val: torch.Tensor, safe: bool = None) -> np.ndarray:
for _v in val.view(-1):
vals.append(inv_reg[int(_v)])
return np.array(vals).reshape(tuple(val.shape))
if val.size == 1:
# some envs require an integer for indexing
val = int(val)
return val

def index(self, index: INDEX_TYPING, tensor_to_index: torch.Tensor) -> torch.Tensor:
Expand Down Expand Up @@ -2099,8 +2096,8 @@ def __eq__(self, other):
def to_numpy(self, val: torch.Tensor, safe: bool = None) -> dict:
if safe is None:
safe = _CHECK_SPEC_ENCODE
if not val.shape and not safe:
return val.item()
# if not val.shape and not safe:
# return val.item()
return super().to_numpy(val, safe)

def to_one_hot(self, val: torch.Tensor, safe: bool = None) -> torch.Tensor:
Expand Down
10 changes: 10 additions & 0 deletions torchrl/envs/libs/gym.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,16 @@ def _build_env(
env = self._build_gym_env(env, pixels_only)
return env

def read_action(self, action):
action = super().read_action(action)
if (
isinstance(self.action_spec, (OneHotDiscreteTensorSpec, DiscreteTensorSpec))
and action.size == 1
):
# some envs require an integer for indexing
action = int(action)
Copy link

@mjlaali mjlaali Sep 3, 2023

Choose a reason for hiding this comment

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

tiny: You may want to use action.item() as it is more efficient
scalar = np.array([1])
timeit.timeit(lambda: scalar.item())

0.05105495895259082

timeit.timeit(lambda: int(scalar))

0.34526545903645456

Moreover, it seems this functionality will be deprecated in future:

DeprecationWarning: Conversion of an array with ndim > 0 to a scalar is deprecated, and will error in future. Ensure you extract a single element from your array before performing this operation. (Deprecated NumPy 1.25.)

return action

@implement_for("gym", None, "0.19.0")
def _build_gym_env(self, env, pixels_only): # noqa: F811
from .utils import GymPixelObservationWrapper as PixelObservationWrapper
Expand Down