n+e 94bfb32cc1
optimize training procedure and improve code coverage (#189)
1. add policy.eval() in all test scripts' "watch performance"
2. remove dict return support for collector preprocess_fn
3. add `__contains__` and `pop` in batch: `key in batch`, `batch.pop(key, deft)`
4. exact n_episode for a list of n_episode limitation and save fake data in cache_buffer when self.buffer is None (#184)
5. fix tensorboard logging: h-axis stands for env step instead of gradient step; add test results into tensorboard
6. add test_returns (both GAE and nstep)
7. change the type-checking order in batch.py and converter.py in order to meet the most often case first
8. fix shape inconsistency for torch.Tensor in replay buffer
9. remove `**kwargs` in ReplayBuffer
10. remove default value in batch.split() and add merge_last argument (#185)
11. improve nstep efficiency
12. add max_batchsize in onpolicy algorithms
13. potential bugfix for subproc.wait
14. fix RecurrentActorProb
15. improve the code-coverage (from 90% to 95%) and remove the dead code
16. fix some incorrect type annotation

The above improvement also increases the training FPS: on my computer, the previous version is only ~1800 FPS and after that, it can reach ~2050 (faster than v0.2.4.post1).
2020-08-27 12:15:18 +08:00

55 lines
1.7 KiB
Python

import gym
import numpy as np
from typing import List, Callable, Tuple, Optional, Any
from tianshou.env.worker import EnvWorker
try:
import ray
except ImportError:
pass
class RayEnvWorker(EnvWorker):
"""Ray worker used in RayVectorEnv."""
def __init__(self, env_fn: Callable[[], gym.Env]) -> None:
super().__init__(env_fn)
self.env = ray.remote(gym.Wrapper).options(num_cpus=0).remote(env_fn())
def __getattr__(self, key: str) -> Any:
return ray.get(self.env.__getattr__.remote(key))
def reset(self) -> Any:
return ray.get(self.env.reset.remote())
@staticmethod
def wait(workers: List['RayEnvWorker'],
wait_num: int,
timeout: Optional[float] = None) -> List['RayEnvWorker']:
results = [x.result for x in workers]
ready_results, _ = ray.wait(results,
num_returns=wait_num, timeout=timeout)
return [workers[results.index(result)] for result in ready_results]
def send_action(self, action: np.ndarray) -> None:
# self.action is actually a handle
self.result = self.env.step.remote(action)
def get_result(self) -> Tuple[
np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
return ray.get(self.result)
def seed(self, seed: Optional[int] = None) -> List[int]:
if hasattr(self.env, 'seed'):
return ray.get(self.env.seed.remote(seed))
return None
def render(self, **kwargs) -> Any:
if hasattr(self.env, 'render'):
return ray.get(self.env.render.remote(**kwargs))
return None
def close_env(self) -> None:
ray.get(self.env.close.remote())