maxhuettenrauch 522f7fbf98
Feature/dataclasses (#996)
This PR adds strict typing to the output of `update` and `learn` in all
policies. This will likely be the last large refactoring PR before the
next release (0.6.0, not 1.0.0), so it requires some attention. Several
difficulties were encountered on the path to that goal:

1. The policy hierarchy is actually "broken" in the sense that the keys
of dicts that were output by `learn` did not follow the same enhancement
(inheritance) pattern as the policies. This is a real problem and should
be addressed in the near future. Generally, several aspects of the
policy design and hierarchy might deserve a dedicated discussion.
2. Each policy needs to be generic in the stats return type, because one
might want to extend it at some point and then also extend the stats.
Even within the source code base this pattern is necessary in many
places.
3. The interaction between learn and update is a bit quirky, we
currently handle it by having update modify special field inside
TrainingStats, whereas all other fields are handled by learn.
4. The IQM module is a policy wrapper and required a
TrainingStatsWrapper. The latter relies on a bunch of black magic.

They were addressed by:
1. Live with the broken hierarchy, which is now made visible by bounds
in generics. We use type: ignore where appropriate.
2. Make all policies generic with bounds following the policy
inheritance hierarchy (which is incorrect, see above). We experimented a
bit with nested TrainingStats classes, but that seemed to add more
complexity and be harder to understand. Unfortunately, mypy thinks that
the code below is wrong, wherefore we have to add `type: ignore` to the
return of each `learn`

```python

T = TypeVar("T", bound=int)


def f() -> T:
  return 3
```

3. See above
4. Write representative tests for the `TrainingStatsWrapper`. Still, the
black magic might cause nasty surprises down the line (I am not proud of
it)...

Closes #933

---------

Co-authored-by: Maximilian Huettenrauch <m.huettenrauch@appliedai.de>
Co-authored-by: Michael Panchenko <m.panchenko@appliedai.de>
2023-12-30 11:09:03 +01:00

60 lines
1.8 KiB
Python

from dataclasses import dataclass
from typing import Any, TypeVar
from torch import nn
from tianshou.data.types import RolloutBatchProtocol
from tianshou.policy import C51Policy
from tianshou.policy.modelfree.c51 import C51TrainingStats
from tianshou.utils.net.discrete import NoisyLinear
# TODO: this is a hacky thing interviewing side-effects and a return. Should improve.
def _sample_noise(model: nn.Module) -> bool:
"""Sample the random noises of NoisyLinear modules in the model.
Returns True if at least one NoisyLinear submodule was found.
:param model: a PyTorch module which may have NoisyLinear submodules.
:returns: True if model has at least one NoisyLinear submodule;
otherwise, False.
"""
sampled_any_noise = False
for m in model.modules():
if isinstance(m, NoisyLinear):
m.sample()
sampled_any_noise = True
return sampled_any_noise
@dataclass(kw_only=True)
class RainbowTrainingStats(C51TrainingStats):
loss: float
TRainbowTrainingStats = TypeVar("TRainbowTrainingStats", bound=RainbowTrainingStats)
# TODO: is this class worth keeping? It barely does anything
class RainbowPolicy(C51Policy[TRainbowTrainingStats]):
"""Implementation of Rainbow DQN. arXiv:1710.02298.
Same parameters as :class:`~tianshou.policy.C51Policy`.
.. seealso::
Please refer to :class:`~tianshou.policy.C51Policy` for more detailed
explanation.
"""
def learn(
self,
batch: RolloutBatchProtocol,
*args: Any,
**kwargs: Any,
) -> TRainbowTrainingStats:
_sample_noise(self.model)
if self._target and _sample_noise(self.model_old):
self.model_old.train() # so that NoisyLinear takes effect
return super().learn(batch, **kwargs)