Tianshou/tianshou/env/venv_wrappers.py
Michael Panchenko b900fdf6f2
Remove kwargs in policy init (#950)
Closes #947 

This removes all kwargs from all policy constructors. While doing that,
I also improved several names and added a whole lot of TODOs.

## Functional changes:

1. Added possibility to pass None as `critic2` and `critic2_optim`. In
fact, the default behavior then should cover the absolute majority of
cases
2. Added a function called `clone_optimizer` as a temporary measure to
support passing `critic2_optim=None`

## Breaking changes:

1. `action_space` is no longer optional. In fact, it already was
non-optional, as there was a ValueError in BasePolicy.init. So now
several examples were fixed to reflect that
2. `reward_normalization` removed from DDPG and children. It was never
allowed to pass it as `True` there, an error would have been raised in
`compute_n_step_reward`. Now I removed it from the interface
3. renamed `critic1` and similar to `critic`, in order to have uniform
interfaces. Note that the `critic` in DDPG was optional for the sole
reason that child classes used `critic1`. I removed this optionality
(DDPG can't do anything with `critic=None`)
4. Several renamings of fields (mostly private to public, so backwards
compatible)

## Additional changes: 
1. Removed type and default declaration from docstring. This kind of
duplication is really not necessary
2. Policy constructors are now only called using named arguments, not a
fragile mixture of positional and named as before
5. Minor beautifications in typing and code 
6. Generally shortened docstrings and made them uniform across all
policies (hopefully)

## Comment:

With these changes, several problems in tianshou's inheritance hierarchy
become more apparent. I tried highlighting them for future work.

---------

Co-authored-by: Dominik Jain <d.jain@appliedai.de>
2023-10-08 08:57:03 -07:00

121 lines
3.7 KiB
Python

from typing import Any
import numpy as np
import torch
from tianshou.env.utils import gym_new_venv_step_type
from tianshou.env.venvs import GYM_RESERVED_KEYS, BaseVectorEnv
from tianshou.utils import RunningMeanStd
class VectorEnvWrapper(BaseVectorEnv):
"""Base class for vectorized environments wrapper."""
# Note: No super call because this is a wrapper with overridden __getattribute__
# It's not a "true" subclass of BaseVectorEnv but it does extend its interface, so
# it can be used as a drop-in replacement
# noinspection PyMissingConstructor
def __init__(self, venv: BaseVectorEnv) -> None:
self.venv = venv
self.is_async = venv.is_async
def __len__(self) -> int:
return len(self.venv)
def __getattribute__(self, key: str) -> Any:
if key in GYM_RESERVED_KEYS: # reserved keys in gym.Env
return getattr(self.venv, key)
return super().__getattribute__(key)
def get_env_attr(
self,
key: str,
id: int | list[int] | np.ndarray | None = None,
) -> list[Any]:
return self.venv.get_env_attr(key, id)
def set_env_attr(
self,
key: str,
value: Any,
id: int | list[int] | np.ndarray | None = None,
) -> None:
return self.venv.set_env_attr(key, value, id)
def reset(
self,
id: int | list[int] | np.ndarray | None = None,
**kwargs: Any,
) -> tuple[np.ndarray, dict | list[dict]]:
return self.venv.reset(id, **kwargs)
def step(
self,
action: np.ndarray | torch.Tensor,
id: int | list[int] | np.ndarray | None = None,
) -> gym_new_venv_step_type:
return self.venv.step(action, id)
def seed(self, seed: int | list[int] | None = None) -> list[list[int] | None]:
return self.venv.seed(seed)
def render(self, **kwargs: Any) -> list[Any]:
return self.venv.render(**kwargs)
def close(self) -> None:
self.venv.close()
class VectorEnvNormObs(VectorEnvWrapper):
"""An observation normalization wrapper for vectorized environments.
:param update_obs_rms: whether to update obs_rms. Default to True.
"""
def __init__(self, venv: BaseVectorEnv, update_obs_rms: bool = True) -> None:
super().__init__(venv)
# initialize observation running mean/std
self.update_obs_rms = update_obs_rms
self.obs_rms = RunningMeanStd()
def reset(
self,
id: int | list[int] | np.ndarray | None = None,
**kwargs: Any,
) -> tuple[np.ndarray, dict | list[dict]]:
obs, info = self.venv.reset(id, **kwargs)
if isinstance(obs, tuple): # type: ignore
raise TypeError(
"Tuple observation space is not supported. ",
"Please change it to array or dict space",
)
if self.obs_rms and self.update_obs_rms:
self.obs_rms.update(obs)
obs = self._norm_obs(obs)
return obs, info
def step(
self,
action: np.ndarray | torch.Tensor,
id: int | list[int] | np.ndarray | None = None,
) -> gym_new_venv_step_type:
step_results = self.venv.step(action, id)
if self.obs_rms and self.update_obs_rms:
self.obs_rms.update(step_results[0])
return (self._norm_obs(step_results[0]), *step_results[1:])
def _norm_obs(self, obs: np.ndarray) -> np.ndarray:
if self.obs_rms:
return self.obs_rms.norm(obs) # type: ignore
return obs
def set_obs_rms(self, obs_rms: RunningMeanStd) -> None:
"""Set with given observation running mean/std."""
self.obs_rms = obs_rms
def get_obs_rms(self) -> RunningMeanStd:
"""Return observation running mean/std."""
return self.obs_rms