-
Notifications
You must be signed in to change notification settings - Fork 418
[Feature] Add info dict key-spec pairs to observation_spec #504
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
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
327fd3c
Add info dict key-spec pairs to observation_spec
tcbegley 67eb999
Add test for info_dict_reader
tcbegley 8277d1b
Merge remote-tracking branch 'upstream/main' into info-key-specs
tcbegley 5d77d78
Add additional tests
tcbegley b765de6
Format code
tcbegley f8e73d7
Fix test
tcbegley File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,20 +5,38 @@ | |
|
|
||
| from __future__ import annotations | ||
|
|
||
| import abc | ||
| import warnings | ||
| from typing import Optional, Union, Tuple, Any, Dict | ||
| from typing import List, Optional, Sequence, Union, Tuple, Any, Dict | ||
|
|
||
| import numpy as np | ||
| import torch | ||
|
|
||
| from torchrl.data import TensorDict | ||
| from torchrl.data.tensor_specs import TensorSpec, UnboundedContinuousTensorSpec | ||
| from torchrl.data.tensordict.tensordict import TensorDictBase | ||
| from torchrl.envs.common import _EnvWrapper | ||
|
|
||
| __all__ = ["GymLikeEnv", "default_info_dict_reader"] | ||
|
|
||
|
|
||
| class default_info_dict_reader: | ||
| class BaseInfoDictReader(metaclass=abc.ABCMeta): | ||
| """ | ||
| Base class for info-readers. | ||
| """ | ||
|
|
||
| @abc.abstractmethod | ||
| def __call__( | ||
| self, info_dict: Dict[str, Any], tensordict: TensorDictBase | ||
| ) -> TensorDictBase: | ||
| raise NotImplementedError | ||
|
|
||
| @abc.abstractproperty | ||
| def info_spec(self) -> Dict[str, TensorSpec]: | ||
| raise NotImplementedError | ||
|
|
||
|
|
||
| class default_info_dict_reader(BaseInfoDictReader): | ||
| """ | ||
| Default info-key reader. | ||
|
|
||
|
|
@@ -39,11 +57,30 @@ class default_info_dict_reader: | |
|
|
||
| """ | ||
|
|
||
| def __init__(self, keys=None): | ||
| def __init__( | ||
| self, | ||
| keys: List[str] = None, | ||
| spec: Union[Sequence[TensorSpec], Dict[str, TensorSpec]] = None, | ||
| ): | ||
| if keys is None: | ||
| keys = [] | ||
| self.keys = keys | ||
|
|
||
| if isinstance(spec, Sequence): | ||
| if len(spec) != len(self.keys): | ||
| raise ValueError( | ||
| "If specifying specs for info keys with a sequence, the " | ||
| "length of the sequence must match the number of keys" | ||
| ) | ||
| self._info_spec = dict(zip(self.keys, spec)) | ||
| else: | ||
| if spec is None: | ||
| spec = {} | ||
|
|
||
| self._info_spec = { | ||
| key: spec.get(key, UnboundedContinuousTensorSpec()) for key in self.keys | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. MyPy gives me a warning here because |
||
| } | ||
|
|
||
| def __call__( | ||
| self, info_dict: Dict[str, Any], tensordict: TensorDictBase | ||
| ) -> TensorDictBase: | ||
|
|
@@ -57,9 +94,13 @@ def __call__( | |
| tensordict[key] = info_dict[key] | ||
| return tensordict | ||
|
|
||
| @property | ||
| def info_spec(self) -> Dict[str, TensorSpec]: | ||
| return self._info_spec | ||
|
|
||
|
|
||
| class GymLikeEnv(_EnvWrapper): | ||
| _info_dict_reader: callable | ||
| _info_dict_reader: BaseInfoDictReader | ||
|
|
||
| """ | ||
| A gym-like env is an environment whose behaviour is similar to gym environments in what | ||
|
|
@@ -216,7 +257,7 @@ def _output_transform(self, step_outputs_tuple: Tuple) -> Tuple: | |
| ) | ||
| return step_outputs_tuple | ||
|
|
||
| def set_info_dict_reader(self, info_dict_reader: callable) -> GymLikeEnv: | ||
| def set_info_dict_reader(self, info_dict_reader: BaseInfoDictReader) -> GymLikeEnv: | ||
| """ | ||
| Sets an info_dict_reader function. This function should take as input an | ||
| info_dict dictionary and the tensordict returned by the step function, and | ||
|
|
@@ -240,6 +281,8 @@ def set_info_dict_reader(self, info_dict_reader: callable) -> GymLikeEnv: | |
|
|
||
| """ | ||
| self.info_dict_reader = info_dict_reader | ||
| for info_key, spec in info_dict_reader.info_spec.items(): | ||
| self.observation_spec[info_key] = spec | ||
| return self | ||
|
|
||
| def __repr__(self) -> str: | ||
|
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
is there something else I could be checking here?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
you could do
assert env.observation_spec["x_position"].is_in(tensordict["x_position"])There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
it's essentially testing that x_position is what it's supposed to be
Another thing we could do is set up a screwed up tensor spec (e.g. one that has wrong shape or wrong dtype) and check that this assertion raises an error
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I just added some additional tests as you suggested, although it wasn't raising an error at any stage, just returning false for
Would you have expected an exception at some point?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
no but yes if you put an assert if front of it :p