-
Notifications
You must be signed in to change notification settings - Fork 365
[Refactor] the usage of tensordict keys in loss modules #1175
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
43 commits
Select commit
Hold shift + click to select a range
83dc591
[Refactor] the usage of tensordict keys in loss modules
Blonck 09ced18
Add more loss modules
Blonck bc04cae
Add more loss modules
Blonck 75c8ea1
Refactor remaining loss modules
Blonck 5a74a16
Remove unnecessary tests
Blonck 32725b4
tensordict_keys dict is not longer overwritten from child classes
Blonck ab94848
Merge branch 'main' into refactor_loss_keys
Blonck 802fe48
Harmonize key name for "state_value"
Blonck c6186fc
Polish refactoring
Blonck b694e8c
Merge branch 'main' into refactor_loss_keys
Blonck 9150b74
Apply suggestions from code review
Blonck bcd8a28
Use abstract staticmethod to provide default values
Blonck 6f10920
Merge branch 'main' into refactor_loss_keys
Blonck 67941df
Merge branch 'main' and rename tensordict_keys to loss_keys
Blonck 7f3e129
Use simple set_keys on all loss modules
Blonck 427c1e8
Implement tensor_keys via _AcceptedKeys dataclass
Blonck 66fb949
Extended _AcceptedKeys to all loss modules
Blonck 526ab36
Refactor unit test for tensordict keys
Blonck 08e20da
Merge branch 'main' into refactor_loss_key_advanced
Blonck 0d476ca
WIP
Blonck 9bb616a
Fix .in_keys of ValueEstimatorBase
Blonck 5d00ca0
Move tensordict key logig to base class
Blonck 4db47e5
Fix make_value_estimator of a2c.py
Blonck 6b422f9
Remvove '_key' from keynames in ppo.py + polish
Blonck 317755d
Remvove '_key' from keynames in ddpg.py + polish
Blonck fe9fba0
Fix documentation in advantages.py
Blonck 34091e0
Remvove '_key' from keynames in dqn.py + polish
Blonck 4baa5dc
Remvove '_key' from keynames in dreamer.py + polish
Blonck 4595546
Remvove '_key' from keynames in iql.py and redq.py + polish
Blonck 8ae6ad9
Remove tensor_keys from advantage ctor
Blonck a15e220
Add documentation to a2c.py
Blonck f1187f3
Change documentation of loss modules
Blonck 3e09c58
Add unit test for advantages tensordict keys
Blonck e52a3f2
Merge branch 'main' into refactor_loss_key_advanced
Blonck 2dc81c9
Improve wording of docstrings
Blonck 655c28d
Apply suggestions from code review
Blonck 226d4d3
Merge branch 'pytorch:main' into refactor_loss_keys
Blonck 75d33c6
Apply code review changes
Blonck 4320db6
Merge branch 'main' into refactor_loss_keys_github
Blonck cf4cd09
Change line breaking in docstrings for _AcceptedKeys
Blonck 81c0413
LossModule is not longer an abstract base class.
Blonck 6e753a4
Merge branch 'main' into refactor_loss_keys_github
Blonck cc784a1
Merge branch 'main' into refactor_loss_keys
vmoens 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
Large diffs are not rendered by default.
Oops, something went wrong.
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 |
---|---|---|
|
@@ -7,6 +7,7 @@ | |
|
||
import warnings | ||
from copy import deepcopy | ||
from dataclasses import dataclass | ||
from typing import Iterator, List, Optional, Tuple, Union | ||
|
||
import torch | ||
|
@@ -57,13 +58,47 @@ class LossModule(nn.Module): | |
|
||
By default, the forward method is always decorated with a | ||
gh :class:`torchrl.envs.ExplorationType.MODE` | ||
|
||
To utilize the ability configuring the tensordict keys via | ||
:meth:`~.set_keys()` a subclass must define an _AcceptedKeys dataclass. | ||
This dataclass should include all keys that are intended to be configurable. | ||
In addition, the subclass must implement the | ||
:meth:._forward_value_estimator_keys() method. This function is crucial for | ||
forwarding any altered tensordict keys to the underlying value_estimator. | ||
|
||
Examples: | ||
>>> class MyLoss(LossModule): | ||
>>> @dataclass | ||
>>> class _AcceptedKeys: | ||
>>> action = "action" | ||
>>> | ||
>>> def _forward_value_estimator_keys(self, **kwargs) -> None: | ||
>>> pass | ||
>>> | ||
>>> loss = MyLoss() | ||
>>> loss.set_keys(action="action2") | ||
""" | ||
|
||
@dataclass | ||
class _AcceptedKeys: | ||
"""Maintains default values for all configurable tensordict keys. | ||
|
||
This class defines which tensordict keys can be set using '.set_keys(key_name=key_value)' and their | ||
default values. | ||
""" | ||
|
||
pass | ||
|
||
default_value_estimator: ValueEstimators = None | ||
SEP = "_sep_" | ||
|
||
@property | ||
def tensor_keys(self) -> _AcceptedKeys: | ||
return self._tensor_keys | ||
|
||
def __new__(cls, *args, **kwargs): | ||
cls.forward = set_exploration_type(ExplorationType.MODE)(cls.forward) | ||
cls._tensor_keys = cls._AcceptedKeys() | ||
return super().__new__(cls) | ||
|
||
def __init__(self): | ||
|
@@ -74,6 +109,44 @@ def __init__(self): | |
self.value_type = self.default_value_estimator | ||
# self.register_forward_pre_hook(_parameters_to_tensordict) | ||
|
||
def _set_deprecated_ctor_keys(self, **kwargs) -> None: | ||
"""Helper function to set a tensordict key from a constructor and raise a warning simultaneously.""" | ||
for key, value in kwargs.items(): | ||
if value is not None: | ||
warnings.warn( | ||
f"Setting '{key}' via the constructor is deprecated, use .set_keys(<key>='some_key') instead.", | ||
category=DeprecationWarning, | ||
) | ||
self.set_keys(**{key: value}) | ||
|
||
def set_keys(self, **kwargs) -> None: | ||
"""Set tensordict key names. | ||
|
||
Examples: | ||
>>> from torchrl.objectives import DQNLoss | ||
>>> # initialize the DQN loss | ||
>>> actor = torch.nn.Linear(3, 4) | ||
>>> dqn_loss = DQNLoss(actor, action_space="one-hot") | ||
>>> dqn_loss.set_keys(priority_key="td_error", action_value_key="action_value") | ||
""" | ||
for key, value in kwargs.items(): | ||
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. if we make |
||
if key not in self._AcceptedKeys.__dict__: | ||
raise ValueError(f"{key} it not an accepted tensordict key") | ||
if value is not None: | ||
setattr(self.tensor_keys, key, value) | ||
else: | ||
setattr(self.tensor_keys, key, self.default_keys.key) | ||
|
||
try: | ||
self._forward_value_estimator_keys(**kwargs) | ||
except AttributeError: | ||
raise AttributeError( | ||
"To utilize `.set_keys(...)` for tensordict key configuration, the subclassed loss module " | ||
"must define an _AcceptedKeys dataclass containing all keys intended for configuration. " | ||
"Moreover, the subclass needs to implement `._forward_value_estimator_keys()` method to " | ||
"facilitate forwarding of any modified tensordict keys to the underlying value_estimator." | ||
) | ||
|
||
def forward(self, tensordict: TensorDictBase) -> TensorDictBase: | ||
"""It is designed to read an input TensorDict and return another tensordict with loss keys named "loss*". | ||
|
||
|
Oops, something went wrong.
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.
maybe make this optional (only if _AcceptedKeys is present)?
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.
The current implementation does not prevent users from crafting a loss module that lacks configurable keys, as _AcceptedKeys is defined as an empty set in such cases. However the abstract method prevents users from doing so:
In this case, the set_keys method will not function if supplied with any arguments, a behavior that aligns with my expectations.
We can remove the @AbstractMethod decorator and introducing an error condition if the
.set_keys
method is invoked while _forward_value_estimator_keys() remains undefined by the loss module. This adjustment would ensure an exception is triggered when .set_keys() is called from the custom loss module.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.
Got it
Up to you for the exception. In a way, if someone writes a loss module then calls set_keys without having written a set of keys they're probably way off the road...