2020-10-15 18:21:30 +02:00
|
|
|
import gym
|
2019-06-03 06:49:24 +08:00
|
|
|
import logging
|
2021-07-10 18:05:25 -04:00
|
|
|
import importlib.util
|
2019-06-03 06:49:24 +08:00
|
|
|
from types import FunctionType
|
2020-10-15 18:21:30 +02:00
|
|
|
from typing import Callable, Dict, List, Optional, Tuple, Type, TypeVar, Union
|
2019-06-03 06:49:24 +08:00
|
|
|
|
2020-03-07 14:47:58 -08:00
|
|
|
import ray
|
2022-01-26 07:00:46 -08:00
|
|
|
from ray import data
|
2021-05-03 14:23:28 -07:00
|
|
|
from ray.actor import ActorHandle
|
2021-07-15 05:51:24 -04:00
|
|
|
from ray.rllib.evaluation.rollout_worker import RolloutWorker
|
2021-05-16 17:35:10 +02:00
|
|
|
from ray.rllib.env.base_env import BaseEnv
|
|
|
|
from ray.rllib.env.env_context import EnvContext
|
2019-06-03 06:49:24 +08:00
|
|
|
from ray.rllib.offline import NoopOutput, JsonReader, MixedInput, JsonWriter, \
|
2022-01-26 07:00:46 -08:00
|
|
|
ShuffledInput, D4RLReader, DatasetReader, DatasetWriter
|
2021-07-15 05:51:24 -04:00
|
|
|
from ray.rllib.policy.policy import Policy, PolicySpec
|
2020-06-11 14:29:57 +02:00
|
|
|
from ray.rllib.utils import merge_dicts
|
2021-05-16 17:35:10 +02:00
|
|
|
from ray.rllib.utils.annotations import DeveloperAPI
|
2020-06-11 14:29:57 +02:00
|
|
|
from ray.rllib.utils.framework import try_import_tf
|
2021-07-10 18:05:25 -04:00
|
|
|
from ray.rllib.utils.from_config import from_config
|
2022-01-25 14:16:58 +01:00
|
|
|
from ray.rllib.utils.typing import EnvCreator, EnvType, PolicyID, \
|
|
|
|
TrainerConfigDict
|
2021-07-10 18:05:25 -04:00
|
|
|
from ray.tune.registry import registry_contains_input, registry_get_input
|
2019-06-03 06:49:24 +08:00
|
|
|
|
2020-06-30 10:13:20 +02:00
|
|
|
tf1, tf, tfv = try_import_tf()
|
2019-06-03 06:49:24 +08:00
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2020-06-19 13:09:05 -07:00
|
|
|
# Generic type var for foreach_* methods.
|
|
|
|
T = TypeVar("T")
|
|
|
|
|
2019-06-03 06:49:24 +08:00
|
|
|
|
|
|
|
@DeveloperAPI
|
2020-01-02 17:42:13 -08:00
|
|
|
class WorkerSet:
|
2021-10-29 12:03:56 +02:00
|
|
|
"""Set of RolloutWorkers with n @ray.remote workers and one local worker.
|
2019-06-03 06:49:24 +08:00
|
|
|
|
2021-10-29 12:03:56 +02:00
|
|
|
Where n may be 0.
|
2019-06-03 06:49:24 +08:00
|
|
|
"""
|
|
|
|
|
2021-12-04 13:26:33 +01:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
*,
|
2022-01-25 14:16:58 +01:00
|
|
|
env_creator: Optional[EnvCreator] = None,
|
2021-12-04 13:26:33 +01:00
|
|
|
validate_env: Optional[Callable[[EnvType], None]] = None,
|
|
|
|
policy_class: Optional[Type[Policy]] = None,
|
|
|
|
trainer_config: Optional[TrainerConfigDict] = None,
|
|
|
|
num_workers: int = 0,
|
|
|
|
local_worker: bool = True,
|
|
|
|
logdir: Optional[str] = None,
|
|
|
|
_setup: bool = True,
|
|
|
|
):
|
2021-10-29 12:03:56 +02:00
|
|
|
"""Initializes a WorkerSet instance.
|
2019-06-03 06:49:24 +08:00
|
|
|
|
2020-09-20 11:27:02 +02:00
|
|
|
Args:
|
2021-10-29 12:03:56 +02:00
|
|
|
env_creator: Function that returns env given env config.
|
|
|
|
validate_env: Optional callable to validate the generated
|
|
|
|
environment (only on worker=0).
|
|
|
|
policy_class: An optional Policy class. If None, PolicySpecs can be
|
|
|
|
generated automatically by using the Trainer's default class
|
|
|
|
of via a given multi-agent policy config dict.
|
|
|
|
trainer_config: Optional dict that extends the common config of
|
|
|
|
the Trainer class.
|
|
|
|
num_workers: Number of remote rollout workers to create.
|
2021-12-04 13:26:33 +01:00
|
|
|
local_worker: Whether to create a local (non @ray.remote) worker
|
|
|
|
in the returned set as well (default: True). If `num_workers`
|
|
|
|
is 0, always create a local worker.
|
2021-10-29 12:03:56 +02:00
|
|
|
logdir: Optional logging directory for workers.
|
|
|
|
_setup: Whether to setup workers. This is only for testing.
|
2019-06-03 06:49:24 +08:00
|
|
|
"""
|
|
|
|
|
|
|
|
if not trainer_config:
|
|
|
|
from ray.rllib.agents.trainer import COMMON_CONFIG
|
|
|
|
trainer_config = COMMON_CONFIG
|
|
|
|
|
|
|
|
self._env_creator = env_creator
|
2020-08-20 17:05:57 +02:00
|
|
|
self._policy_class = policy_class
|
2019-06-03 06:49:24 +08:00
|
|
|
self._remote_config = trainer_config
|
|
|
|
self._logdir = logdir
|
|
|
|
|
|
|
|
if _setup:
|
2021-12-04 13:26:33 +01:00
|
|
|
# Force a local worker if num_workers == 0 (no remote workers).
|
|
|
|
# Otherwise, this WorkerSet would be empty.
|
|
|
|
self._local_worker = None
|
|
|
|
if num_workers == 0:
|
|
|
|
local_worker = True
|
|
|
|
|
2019-06-03 06:49:24 +08:00
|
|
|
self._local_config = merge_dicts(
|
|
|
|
trainer_config,
|
|
|
|
{"tf_session_args": trainer_config["local_tf_session_args"]})
|
|
|
|
|
2022-01-26 07:00:46 -08:00
|
|
|
if trainer_config["input"] == "dataset":
|
|
|
|
# Create the set of dataset readers to be shared by all the
|
|
|
|
# rollout workers.
|
|
|
|
self._ds, self._ds_shards = self._get_dataset_and_shards(
|
|
|
|
trainer_config, num_workers, local_worker)
|
|
|
|
else:
|
|
|
|
self._ds = None
|
|
|
|
self._ds_shards = None
|
|
|
|
|
2021-12-04 13:26:33 +01:00
|
|
|
# Create a number of @ray.remote workers.
|
2020-08-24 15:29:55 -04:00
|
|
|
self._remote_workers = []
|
|
|
|
self.add_workers(num_workers)
|
|
|
|
|
2021-12-04 13:26:33 +01:00
|
|
|
# Create a local worker, if needed.
|
2021-09-23 10:54:37 +02:00
|
|
|
# If num_workers > 0 and we don't have an env on the local worker,
|
|
|
|
# get the observation- and action spaces for each policy from
|
|
|
|
# the first remote worker (which does have an env).
|
2021-12-04 13:26:33 +01:00
|
|
|
if local_worker and self._remote_workers and \
|
2021-09-23 10:54:37 +02:00
|
|
|
not trainer_config.get("create_env_on_driver") and \
|
|
|
|
(not trainer_config.get("observation_space") or
|
|
|
|
not trainer_config.get("action_space")):
|
2020-10-15 18:21:30 +02:00
|
|
|
remote_spaces = ray.get(self.remote_workers(
|
|
|
|
)[0].foreach_policy.remote(
|
|
|
|
lambda p, pid: (pid, p.observation_space, p.action_space)))
|
2020-12-09 20:49:21 +01:00
|
|
|
spaces = {
|
|
|
|
e[0]: (getattr(e[1], "original_space", e[1]), e[2])
|
|
|
|
for e in remote_spaces
|
|
|
|
}
|
2021-07-22 10:59:13 -04:00
|
|
|
# Try to add the actual env's obs/action spaces.
|
|
|
|
try:
|
|
|
|
env_spaces = ray.get(self.remote_workers(
|
|
|
|
)[0].foreach_env.remote(
|
|
|
|
lambda env: (env.observation_space, env.action_space))
|
|
|
|
)[0]
|
|
|
|
spaces["__env__"] = env_spaces
|
|
|
|
except Exception:
|
|
|
|
pass
|
2021-09-23 10:54:37 +02:00
|
|
|
|
|
|
|
logger.info("Inferred observation/action spaces from remote "
|
|
|
|
f"worker (local worker has no env): {spaces}")
|
2020-10-15 18:21:30 +02:00
|
|
|
else:
|
|
|
|
spaces = None
|
|
|
|
|
2021-12-04 13:26:33 +01:00
|
|
|
if local_worker:
|
|
|
|
self._local_worker = self._make_worker(
|
|
|
|
cls=RolloutWorker,
|
|
|
|
env_creator=env_creator,
|
|
|
|
validate_env=validate_env,
|
|
|
|
policy_cls=self._policy_class,
|
|
|
|
worker_index=0,
|
|
|
|
num_workers=num_workers,
|
|
|
|
config=self._local_config,
|
|
|
|
spaces=spaces,
|
|
|
|
)
|
2019-06-03 06:49:24 +08:00
|
|
|
|
2020-06-19 13:09:05 -07:00
|
|
|
def local_worker(self) -> RolloutWorker:
|
2021-10-29 12:03:56 +02:00
|
|
|
"""Returns the local rollout worker."""
|
2019-06-03 06:49:24 +08:00
|
|
|
return self._local_worker
|
|
|
|
|
2021-05-03 14:23:28 -07:00
|
|
|
def remote_workers(self) -> List[ActorHandle]:
|
2021-10-29 12:03:56 +02:00
|
|
|
"""Returns a list of remote rollout workers."""
|
2019-06-03 06:49:24 +08:00
|
|
|
return self._remote_workers
|
|
|
|
|
2021-12-21 08:39:05 +01:00
|
|
|
def sync_weights(self,
|
|
|
|
policies: Optional[List[PolicyID]] = None,
|
|
|
|
from_worker: Optional[RolloutWorker] = None) -> None:
|
2021-10-29 12:03:56 +02:00
|
|
|
"""Syncs model weights from the local worker to all remote workers.
|
|
|
|
|
|
|
|
Args:
|
2021-12-21 08:39:05 +01:00
|
|
|
policies: Optional list of PolicyIDs to sync weights for.
|
|
|
|
If None (default), sync weights to/from all policies.
|
|
|
|
from_worker: Optional RolloutWorker instance to sync from.
|
|
|
|
If None (default), sync from this WorkerSet's local worker.
|
2021-10-29 12:03:56 +02:00
|
|
|
"""
|
2021-12-21 08:39:05 +01:00
|
|
|
if self.local_worker() is None and from_worker is None:
|
|
|
|
raise TypeError(
|
|
|
|
"No `local_worker` in WorkerSet, must provide `from_worker` "
|
|
|
|
"arg in `sync_weights()`!")
|
|
|
|
|
|
|
|
# Only sync if we have remote workers or `from_worker` is provided.
|
|
|
|
if self.remote_workers() or from_worker is not None:
|
|
|
|
weights = (from_worker
|
|
|
|
or self.local_worker()).get_weights(policies)
|
2022-01-10 11:22:55 +01:00
|
|
|
# Put weights only once into object store and use same object
|
|
|
|
# ref to synch to all workers.
|
2021-12-21 08:39:05 +01:00
|
|
|
weights_ref = ray.put(weights)
|
|
|
|
# Sync to all remote workers in this WorkerSet.
|
|
|
|
for to_worker in self.remote_workers():
|
|
|
|
to_worker.set_weights.remote(weights_ref)
|
|
|
|
|
2022-01-10 11:22:55 +01:00
|
|
|
# If `from_worker` is provided, also sync to this WorkerSet's
|
|
|
|
# local worker.
|
2021-12-21 08:39:05 +01:00
|
|
|
if from_worker is not None and self.local_worker() is not None:
|
|
|
|
self.local_worker().set_weights(weights)
|
2020-03-07 14:47:58 -08:00
|
|
|
|
2020-06-19 13:09:05 -07:00
|
|
|
def add_workers(self, num_workers: int) -> None:
|
2021-09-23 10:54:37 +02:00
|
|
|
"""Creates and adds a number of remote workers to this worker set.
|
2020-02-11 00:22:07 +01:00
|
|
|
|
2021-10-29 12:03:56 +02:00
|
|
|
Can be called several times on the same WorkerSet to add more
|
|
|
|
RolloutWorkers to the set.
|
|
|
|
|
2020-02-11 00:22:07 +01:00
|
|
|
Args:
|
2021-10-29 12:03:56 +02:00
|
|
|
num_workers: The number of remote Workers to add to this
|
2020-02-11 00:22:07 +01:00
|
|
|
WorkerSet.
|
|
|
|
"""
|
2019-06-03 06:49:24 +08:00
|
|
|
remote_args = {
|
|
|
|
"num_cpus": self._remote_config["num_cpus_per_worker"],
|
|
|
|
"num_gpus": self._remote_config["num_gpus_per_worker"],
|
|
|
|
"resources": self._remote_config["custom_resources_per_worker"],
|
|
|
|
}
|
|
|
|
cls = RolloutWorker.as_remote(**remote_args).remote
|
|
|
|
self._remote_workers.extend([
|
2020-10-06 20:28:16 +02:00
|
|
|
self._make_worker(
|
|
|
|
cls=cls,
|
|
|
|
env_creator=self._env_creator,
|
|
|
|
validate_env=None,
|
2020-10-15 18:21:30 +02:00
|
|
|
policy_cls=self._policy_class,
|
2020-10-06 20:28:16 +02:00
|
|
|
worker_index=i + 1,
|
2020-10-15 18:21:30 +02:00
|
|
|
num_workers=num_workers,
|
2021-06-23 09:09:01 +02:00
|
|
|
config=self._remote_config,
|
|
|
|
) for i in range(num_workers)
|
2019-06-03 06:49:24 +08:00
|
|
|
])
|
|
|
|
|
2021-05-03 14:23:28 -07:00
|
|
|
def reset(self, new_remote_workers: List[ActorHandle]) -> None:
|
2021-10-29 12:03:56 +02:00
|
|
|
"""Hard overrides the remote workers in this set with the given one.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
new_remote_workers: A list of new RolloutWorkers
|
|
|
|
(as `ActorHandles`) to use as remote workers.
|
|
|
|
"""
|
2019-06-03 06:49:24 +08:00
|
|
|
self._remote_workers = new_remote_workers
|
|
|
|
|
2020-06-19 13:09:05 -07:00
|
|
|
def stop(self) -> None:
|
2021-10-29 12:03:56 +02:00
|
|
|
"""Calls `stop` on all rollout workers (including the local one)."""
|
2020-10-28 17:23:06 -04:00
|
|
|
try:
|
|
|
|
self.local_worker().stop()
|
|
|
|
tids = [w.stop.remote() for w in self.remote_workers()]
|
|
|
|
ray.get(tids)
|
|
|
|
except Exception:
|
2021-10-29 12:03:56 +02:00
|
|
|
logger.exception("Failed to stop workers!")
|
2020-10-28 17:23:06 -04:00
|
|
|
finally:
|
|
|
|
for w in self.remote_workers():
|
|
|
|
w.__ray_terminate__.remote()
|
2019-06-03 06:49:24 +08:00
|
|
|
|
|
|
|
@DeveloperAPI
|
2020-06-19 13:09:05 -07:00
|
|
|
def foreach_worker(self, func: Callable[[RolloutWorker], T]) -> List[T]:
|
2021-10-29 12:03:56 +02:00
|
|
|
"""Calls the given function with each worker instance as arg.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
func: The function to call for each worker (as only arg).
|
2019-06-03 06:49:24 +08:00
|
|
|
|
2021-10-29 12:03:56 +02:00
|
|
|
Returns:
|
|
|
|
The list of return values of all calls to `func([worker])`.
|
|
|
|
"""
|
2021-12-04 13:26:33 +01:00
|
|
|
local_result = []
|
2021-12-21 08:39:05 +01:00
|
|
|
if self.local_worker() is not None:
|
2021-12-04 13:26:33 +01:00
|
|
|
local_result = [func(self.local_worker())]
|
2020-05-21 10:16:18 -07:00
|
|
|
remote_results = ray.get(
|
2019-06-03 06:49:24 +08:00
|
|
|
[w.apply.remote(func) for w in self.remote_workers()])
|
|
|
|
return local_result + remote_results
|
|
|
|
|
|
|
|
@DeveloperAPI
|
2020-06-19 13:09:05 -07:00
|
|
|
def foreach_worker_with_index(
|
|
|
|
self, func: Callable[[RolloutWorker, int], T]) -> List[T]:
|
2021-10-29 12:03:56 +02:00
|
|
|
"""Calls `func` with each worker instance and worker idx as args.
|
2019-06-03 06:49:24 +08:00
|
|
|
|
|
|
|
The index will be passed as the second arg to the given function.
|
2021-10-29 12:03:56 +02:00
|
|
|
|
|
|
|
Args:
|
|
|
|
func: The function to call for each worker and its index
|
|
|
|
(as args). The local worker has index 0, all remote workers
|
|
|
|
have indices > 0.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
The list of return values of all calls to `func([worker, idx])`.
|
|
|
|
The first entry in this list are the results of the local
|
|
|
|
worker, followed by all remote workers' results.
|
2019-06-03 06:49:24 +08:00
|
|
|
"""
|
2021-12-04 13:26:33 +01:00
|
|
|
local_result = []
|
2021-10-29 12:03:56 +02:00
|
|
|
# Local worker: Index=0.
|
2021-12-21 08:39:05 +01:00
|
|
|
if self.local_worker() is not None:
|
2021-12-04 13:26:33 +01:00
|
|
|
local_result = [func(self.local_worker(), 0)]
|
2021-10-29 12:03:56 +02:00
|
|
|
# Remote workers: Index > 0.
|
2020-05-21 10:16:18 -07:00
|
|
|
remote_results = ray.get([
|
2019-06-03 06:49:24 +08:00
|
|
|
w.apply.remote(func, i + 1)
|
|
|
|
for i, w in enumerate(self.remote_workers())
|
|
|
|
])
|
|
|
|
return local_result + remote_results
|
|
|
|
|
2020-02-11 00:22:07 +01:00
|
|
|
@DeveloperAPI
|
2020-06-19 13:09:05 -07:00
|
|
|
def foreach_policy(self, func: Callable[[Policy, PolicyID], T]) -> List[T]:
|
2021-10-29 12:03:56 +02:00
|
|
|
"""Calls `func` with each worker's (policy, PolicyID) tuple.
|
|
|
|
|
|
|
|
Note that in the multi-agent case, each worker may have more than one
|
|
|
|
policy.
|
2020-02-11 00:22:07 +01:00
|
|
|
|
|
|
|
Args:
|
2021-10-29 12:03:56 +02:00
|
|
|
func: A function - taking a Policy and its ID - that is
|
2020-02-11 00:22:07 +01:00
|
|
|
called on all workers' Policies.
|
|
|
|
|
|
|
|
Returns:
|
2021-10-29 12:03:56 +02:00
|
|
|
The list of return values of func over all workers' policies. The
|
|
|
|
length of this list is:
|
|
|
|
(num_workers + 1 (local-worker)) *
|
|
|
|
[num policies in the multi-agent config dict].
|
|
|
|
The local workers' results are first, followed by all remote
|
|
|
|
workers' results
|
2020-02-11 00:22:07 +01:00
|
|
|
"""
|
2021-12-04 13:26:33 +01:00
|
|
|
results = []
|
2021-12-21 08:39:05 +01:00
|
|
|
if self.local_worker() is not None:
|
2021-12-04 13:26:33 +01:00
|
|
|
results = self.local_worker().foreach_policy(func)
|
2021-05-16 17:35:10 +02:00
|
|
|
ray_gets = []
|
2020-02-11 00:22:07 +01:00
|
|
|
for worker in self.remote_workers():
|
2021-05-16 17:35:10 +02:00
|
|
|
ray_gets.append(
|
2020-02-11 00:22:07 +01:00
|
|
|
worker.apply.remote(lambda w: w.foreach_policy(func)))
|
2021-05-16 17:35:10 +02:00
|
|
|
remote_results = ray.get(ray_gets)
|
|
|
|
for r in remote_results:
|
|
|
|
results.extend(r)
|
|
|
|
return results
|
2020-02-11 00:22:07 +01:00
|
|
|
|
2020-04-30 01:18:09 -07:00
|
|
|
@DeveloperAPI
|
2020-06-19 13:09:05 -07:00
|
|
|
def trainable_policies(self) -> List[PolicyID]:
|
2021-10-29 12:03:56 +02:00
|
|
|
"""Returns the list of trainable policy ids."""
|
2021-12-21 08:39:05 +01:00
|
|
|
if self.local_worker() is not None:
|
|
|
|
return self.local_worker().policies_to_train
|
2021-12-04 13:26:33 +01:00
|
|
|
else:
|
|
|
|
raise NotImplementedError
|
2020-04-30 01:18:09 -07:00
|
|
|
|
2020-02-11 00:22:07 +01:00
|
|
|
@DeveloperAPI
|
2020-06-19 13:09:05 -07:00
|
|
|
def foreach_trainable_policy(
|
|
|
|
self, func: Callable[[Policy, PolicyID], T]) -> List[T]:
|
2020-02-11 00:22:07 +01:00
|
|
|
"""Apply `func` to all workers' Policies iff in `policies_to_train`.
|
|
|
|
|
|
|
|
Args:
|
2021-10-29 12:03:56 +02:00
|
|
|
func: A function - taking a Policy and its ID - that is
|
2020-02-11 00:22:07 +01:00
|
|
|
called on all workers' Policies in `worker.policies_to_train`.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
List[any]: The list of n return values of all
|
|
|
|
`func([trainable policy], [ID])`-calls.
|
|
|
|
"""
|
2021-12-04 13:26:33 +01:00
|
|
|
results = []
|
2021-12-21 08:39:05 +01:00
|
|
|
if self.local_worker() is not None:
|
2021-12-04 13:26:33 +01:00
|
|
|
results = self.local_worker().foreach_trainable_policy(func)
|
2021-05-16 17:35:10 +02:00
|
|
|
ray_gets = []
|
2020-02-11 00:22:07 +01:00
|
|
|
for worker in self.remote_workers():
|
2021-05-16 17:35:10 +02:00
|
|
|
ray_gets.append(
|
2020-02-11 00:22:07 +01:00
|
|
|
worker.apply.remote(
|
|
|
|
lambda w: w.foreach_trainable_policy(func)))
|
2021-05-16 17:35:10 +02:00
|
|
|
remote_results = ray.get(ray_gets)
|
|
|
|
for r in remote_results:
|
|
|
|
results.extend(r)
|
|
|
|
return results
|
|
|
|
|
|
|
|
@DeveloperAPI
|
2021-10-29 10:46:52 +02:00
|
|
|
def foreach_env(self, func: Callable[[EnvType], List[T]]) -> List[List[T]]:
|
2021-11-17 21:40:16 +01:00
|
|
|
"""Calls `func` with all workers' sub-environments as args.
|
2021-05-16 17:35:10 +02:00
|
|
|
|
2021-10-29 10:46:52 +02:00
|
|
|
An "underlying sub environment" is a single clone of an env within
|
|
|
|
a vectorized environment.
|
|
|
|
`func` takes a single underlying sub environment as arg, e.g. a
|
|
|
|
gym.Env object.
|
2021-05-16 17:35:10 +02:00
|
|
|
|
|
|
|
Args:
|
2021-10-29 12:03:56 +02:00
|
|
|
func: A function - taking an EnvType (normally a gym.Env object)
|
|
|
|
as arg and returning a list of lists of return values, one
|
|
|
|
value per underlying sub-environment per each worker.
|
2021-05-16 17:35:10 +02:00
|
|
|
|
|
|
|
Returns:
|
2021-10-29 12:03:56 +02:00
|
|
|
The list (workers) of lists (sub environments) of results.
|
2021-05-16 17:35:10 +02:00
|
|
|
"""
|
2021-12-04 13:26:33 +01:00
|
|
|
local_results = []
|
2021-12-21 08:39:05 +01:00
|
|
|
if self.local_worker() is not None:
|
2021-12-04 13:26:33 +01:00
|
|
|
local_results = [self.local_worker().foreach_env(func)]
|
2021-05-16 17:35:10 +02:00
|
|
|
ray_gets = []
|
|
|
|
for worker in self.remote_workers():
|
|
|
|
ray_gets.append(worker.foreach_env.remote(func))
|
|
|
|
return local_results + ray.get(ray_gets)
|
|
|
|
|
|
|
|
@DeveloperAPI
|
|
|
|
def foreach_env_with_context(
|
|
|
|
self,
|
|
|
|
func: Callable[[BaseEnv, EnvContext], List[T]]) -> List[List[T]]:
|
2021-11-17 21:40:16 +01:00
|
|
|
"""Calls `func` with all workers' sub-environments and env_ctx as args.
|
2021-05-16 17:35:10 +02:00
|
|
|
|
2021-10-29 10:46:52 +02:00
|
|
|
An "underlying sub environment" is a single clone of an env within
|
|
|
|
a vectorized environment.
|
|
|
|
`func` takes a single underlying sub environment and the env_context
|
|
|
|
as args.
|
2021-05-16 17:35:10 +02:00
|
|
|
|
|
|
|
Args:
|
2021-10-29 12:03:56 +02:00
|
|
|
func: A function - taking a BaseEnv object and an EnvContext as
|
|
|
|
arg - and returning a list of lists of return values over envs
|
2021-05-16 17:35:10 +02:00
|
|
|
of the worker.
|
|
|
|
|
|
|
|
Returns:
|
2021-10-29 12:03:56 +02:00
|
|
|
The list (1 item per workers) of lists (1 item per sub-environment)
|
|
|
|
of results.
|
2021-05-16 17:35:10 +02:00
|
|
|
"""
|
2021-12-04 13:26:33 +01:00
|
|
|
local_results = []
|
2021-12-21 08:39:05 +01:00
|
|
|
if self.local_worker() is not None:
|
2021-12-04 13:26:33 +01:00
|
|
|
local_results = [
|
|
|
|
self.local_worker().foreach_env_with_context(func)
|
|
|
|
]
|
2021-05-16 17:35:10 +02:00
|
|
|
ray_gets = []
|
|
|
|
for worker in self.remote_workers():
|
|
|
|
ray_gets.append(worker.foreach_env_with_context.remote(func))
|
|
|
|
return local_results + ray.get(ray_gets)
|
2020-02-11 00:22:07 +01:00
|
|
|
|
2019-06-03 06:49:24 +08:00
|
|
|
@staticmethod
|
2020-06-19 13:09:05 -07:00
|
|
|
def _from_existing(local_worker: RolloutWorker,
|
2021-05-03 14:23:28 -07:00
|
|
|
remote_workers: List[ActorHandle] = None):
|
2020-08-20 17:05:57 +02:00
|
|
|
workers = WorkerSet(
|
|
|
|
env_creator=None,
|
|
|
|
policy_class=None,
|
|
|
|
trainer_config={},
|
|
|
|
_setup=False)
|
2019-06-03 06:49:24 +08:00
|
|
|
workers._local_worker = local_worker
|
|
|
|
workers._remote_workers = remote_workers or []
|
|
|
|
return workers
|
|
|
|
|
2022-01-26 07:00:46 -08:00
|
|
|
def _get_dataset_and_shards(self, config: TrainerConfigDict,
|
|
|
|
num_workers: int, local_worker: bool)\
|
|
|
|
-> (ray.data.dataset.Dataset,
|
|
|
|
List[ray.data.dataset.Dataset]):
|
|
|
|
assert config["input"] == "dataset"
|
|
|
|
assert "input_config" in config, (
|
|
|
|
"Must specify input_config dict if using Dataset input.")
|
|
|
|
|
|
|
|
input_config = config["input_config"]
|
|
|
|
if (not input_config.get("format", None)
|
|
|
|
or not input_config.get("path", None)):
|
|
|
|
raise ValueError(
|
|
|
|
"Must specify format and path via input_config key"
|
|
|
|
" when using Ray dataset input.")
|
|
|
|
|
|
|
|
format = input_config["format"]
|
|
|
|
path = input_config["path"]
|
|
|
|
if format == "json":
|
|
|
|
dataset = data.read_json(path)
|
|
|
|
elif format == "parquet":
|
|
|
|
dataset = data.read_parquet(path)
|
|
|
|
else:
|
|
|
|
raise ValueError("Un-supported Ray dataset format: ", format)
|
|
|
|
|
|
|
|
# Local worker will be responsible for sampling.
|
|
|
|
if local_worker and num_workers == 0:
|
|
|
|
# Dataset is the only shard we need.
|
|
|
|
return dataset, [dataset]
|
|
|
|
# Remote workers are responsible for sampling:
|
|
|
|
else:
|
|
|
|
# Each remote worker gets 1 shard.
|
|
|
|
# The first None shard is for the local worker, which
|
|
|
|
# shouldn't be doing rollout work anyways.
|
|
|
|
return dataset, [None] + dataset.repartition(
|
|
|
|
num_blocks=num_workers, shuffle=False).split(num_workers)
|
|
|
|
|
2020-06-19 13:09:05 -07:00
|
|
|
def _make_worker(
|
2020-10-15 18:21:30 +02:00
|
|
|
self,
|
|
|
|
*,
|
|
|
|
cls: Callable,
|
2022-01-25 14:16:58 +01:00
|
|
|
env_creator: EnvCreator,
|
2020-10-06 20:28:16 +02:00
|
|
|
validate_env: Optional[Callable[[EnvType], None]],
|
2020-10-15 18:21:30 +02:00
|
|
|
policy_cls: Type[Policy],
|
|
|
|
worker_index: int,
|
|
|
|
num_workers: int,
|
|
|
|
config: TrainerConfigDict,
|
|
|
|
spaces: Optional[Dict[PolicyID, Tuple[gym.spaces.Space,
|
|
|
|
gym.spaces.Space]]] = None,
|
2021-05-03 14:23:28 -07:00
|
|
|
) -> Union[RolloutWorker, ActorHandle]:
|
2019-06-03 06:49:24 +08:00
|
|
|
def session_creator():
|
|
|
|
logger.debug("Creating TF session {}".format(
|
|
|
|
config["tf_session_args"]))
|
2020-06-30 10:13:20 +02:00
|
|
|
return tf1.Session(
|
|
|
|
config=tf1.ConfigProto(**config["tf_session_args"]))
|
2019-06-03 06:49:24 +08:00
|
|
|
|
2021-07-10 18:05:25 -04:00
|
|
|
def valid_module(class_path):
|
|
|
|
if isinstance(class_path, str) and "." in class_path:
|
|
|
|
module_path, class_name = class_path.rsplit(".", 1)
|
|
|
|
try:
|
|
|
|
spec = importlib.util.find_spec(module_path)
|
|
|
|
if spec is not None:
|
|
|
|
return True
|
|
|
|
except (ModuleNotFoundError, ValueError):
|
|
|
|
print(
|
|
|
|
f"module {module_path} not found while trying to get "
|
|
|
|
f"input {class_path}")
|
|
|
|
return False
|
|
|
|
|
2019-06-03 06:49:24 +08:00
|
|
|
if isinstance(config["input"], FunctionType):
|
|
|
|
input_creator = config["input"]
|
|
|
|
elif config["input"] == "sampler":
|
|
|
|
input_creator = (lambda ioctx: ioctx.default_sampler_input())
|
2022-01-26 07:00:46 -08:00
|
|
|
elif config["input"] == "dataset":
|
|
|
|
# Input dataset shards should have already been prepared.
|
|
|
|
# We just need to take the proper shard here.
|
|
|
|
input_creator = (
|
|
|
|
lambda ioctx: DatasetReader(ioctx, self._ds_shards[worker_index])
|
|
|
|
)
|
2019-06-03 06:49:24 +08:00
|
|
|
elif isinstance(config["input"], dict):
|
2020-12-11 22:43:30 +01:00
|
|
|
input_creator = (
|
|
|
|
lambda ioctx: ShuffledInput(MixedInput(config["input"], ioctx),
|
|
|
|
config["shuffle_buffer_size"]))
|
2021-07-10 18:05:25 -04:00
|
|
|
elif isinstance(config["input"], str) and \
|
|
|
|
registry_contains_input(config["input"]):
|
|
|
|
input_creator = registry_get_input(config["input"])
|
2021-01-21 07:43:55 -08:00
|
|
|
elif "d4rl" in config["input"]:
|
2021-07-01 21:35:50 -04:00
|
|
|
env_name = config["input"].split(".")[-1]
|
2021-01-21 07:43:55 -08:00
|
|
|
input_creator = (lambda ioctx: D4RLReader(env_name, ioctx))
|
2021-07-10 18:05:25 -04:00
|
|
|
elif valid_module(config["input"]):
|
|
|
|
input_creator = (lambda ioctx: ShuffledInput(from_config(
|
|
|
|
config["input"], ioctx=ioctx)))
|
2019-06-03 06:49:24 +08:00
|
|
|
else:
|
2020-12-11 22:43:30 +01:00
|
|
|
input_creator = (
|
|
|
|
lambda ioctx: ShuffledInput(JsonReader(config["input"], ioctx),
|
|
|
|
config["shuffle_buffer_size"]))
|
2019-06-03 06:49:24 +08:00
|
|
|
|
|
|
|
if isinstance(config["output"], FunctionType):
|
|
|
|
output_creator = config["output"]
|
|
|
|
elif config["output"] is None:
|
|
|
|
output_creator = (lambda ioctx: NoopOutput())
|
2022-01-26 07:00:46 -08:00
|
|
|
elif config["output"] == "dataset":
|
|
|
|
output_creator = (lambda ioctx: DatasetWriter(
|
|
|
|
ioctx,
|
|
|
|
compress_columns=config["output_compress_columns"]))
|
2019-06-03 06:49:24 +08:00
|
|
|
elif config["output"] == "logdir":
|
|
|
|
output_creator = (lambda ioctx: JsonWriter(
|
|
|
|
ioctx.log_dir,
|
|
|
|
ioctx,
|
|
|
|
max_file_size=config["output_max_file_size"],
|
|
|
|
compress_columns=config["output_compress_columns"]))
|
|
|
|
else:
|
|
|
|
output_creator = (lambda ioctx: JsonWriter(
|
|
|
|
config["output"],
|
|
|
|
ioctx,
|
|
|
|
max_file_size=config["output_max_file_size"],
|
|
|
|
compress_columns=config["output_compress_columns"]))
|
|
|
|
|
|
|
|
if config["input"] == "sampler":
|
|
|
|
input_evaluation = []
|
|
|
|
else:
|
|
|
|
input_evaluation = config["input_evaluation"]
|
|
|
|
|
2021-07-15 05:51:24 -04:00
|
|
|
# Assert everything is correct in "multiagent" config dict (if given).
|
|
|
|
ma_policies = config["multiagent"]["policies"]
|
|
|
|
if ma_policies:
|
|
|
|
for pid, policy_spec in ma_policies.copy().items():
|
2022-01-10 11:19:40 +01:00
|
|
|
assert isinstance(policy_spec, PolicySpec)
|
2021-07-15 05:51:24 -04:00
|
|
|
# Class is None -> Use `policy_cls`.
|
|
|
|
if policy_spec.policy_class is None:
|
|
|
|
ma_policies[pid] = ma_policies[pid]._replace(
|
|
|
|
policy_class=policy_cls)
|
|
|
|
policies = ma_policies
|
|
|
|
|
|
|
|
# Create a policy_spec (MultiAgentPolicyConfigDict),
|
|
|
|
# even if no "multiagent" setup given by user.
|
2020-10-15 18:21:30 +02:00
|
|
|
else:
|
2021-07-15 05:51:24 -04:00
|
|
|
policies = policy_cls
|
2019-06-03 06:49:24 +08:00
|
|
|
|
2020-04-16 16:13:45 +08:00
|
|
|
if worker_index == 0:
|
|
|
|
extra_python_environs = config.get(
|
|
|
|
"extra_python_environs_for_driver", None)
|
|
|
|
else:
|
|
|
|
extra_python_environs = config.get(
|
|
|
|
"extra_python_environs_for_worker", None)
|
|
|
|
|
2020-03-30 23:03:29 +02:00
|
|
|
worker = cls(
|
2020-10-06 20:28:16 +02:00
|
|
|
env_creator=env_creator,
|
|
|
|
validate_env=validate_env,
|
2021-07-15 05:51:24 -04:00
|
|
|
policy_spec=policies,
|
2019-06-03 06:49:24 +08:00
|
|
|
policy_mapping_fn=config["multiagent"]["policy_mapping_fn"],
|
|
|
|
policies_to_train=config["multiagent"]["policies_to_train"],
|
|
|
|
tf_session_creator=(session_creator
|
|
|
|
if config["tf_session_args"] else None),
|
2020-03-14 12:05:04 -07:00
|
|
|
rollout_fragment_length=config["rollout_fragment_length"],
|
2020-12-09 01:41:45 +01:00
|
|
|
count_steps_by=config["multiagent"]["count_steps_by"],
|
2019-06-03 06:49:24 +08:00
|
|
|
batch_mode=config["batch_mode"],
|
|
|
|
episode_horizon=config["horizon"],
|
|
|
|
preprocessor_pref=config["preprocessor_pref"],
|
|
|
|
sample_async=config["sample_async"],
|
|
|
|
compress_observations=config["compress_observations"],
|
|
|
|
num_envs=config["num_envs_per_worker"],
|
2020-05-04 22:13:49 -07:00
|
|
|
observation_fn=config["multiagent"]["observation_fn"],
|
2019-06-03 06:49:24 +08:00
|
|
|
observation_filter=config["observation_filter"],
|
|
|
|
clip_rewards=config["clip_rewards"],
|
2021-06-30 12:32:11 +02:00
|
|
|
normalize_actions=config["normalize_actions"],
|
2019-06-03 06:49:24 +08:00
|
|
|
clip_actions=config["clip_actions"],
|
|
|
|
env_config=config["env_config"],
|
|
|
|
policy_config=config,
|
|
|
|
worker_index=worker_index,
|
2020-10-15 18:21:30 +02:00
|
|
|
num_workers=num_workers,
|
2021-03-23 10:06:06 +01:00
|
|
|
record_env=config["record_env"],
|
2019-06-03 06:49:24 +08:00
|
|
|
log_dir=self._logdir,
|
|
|
|
log_level=config["log_level"],
|
|
|
|
callbacks=config["callbacks"],
|
|
|
|
input_creator=input_creator,
|
|
|
|
input_evaluation=input_evaluation,
|
|
|
|
output_creator=output_creator,
|
|
|
|
remote_worker_envs=config["remote_worker_envs"],
|
|
|
|
remote_env_batch_wait_ms=config["remote_env_batch_wait_ms"],
|
|
|
|
soft_horizon=config["soft_horizon"],
|
2019-08-01 23:37:36 -07:00
|
|
|
no_done_at_end=config["no_done_at_end"],
|
2019-07-18 14:31:34 +08:00
|
|
|
seed=(config["seed"] + worker_index)
|
|
|
|
if config["seed"] is not None else None,
|
2020-05-11 20:24:43 -07:00
|
|
|
fake_sampler=config["fake_sampler"],
|
2020-10-15 18:21:30 +02:00
|
|
|
extra_python_environs=extra_python_environs,
|
|
|
|
spaces=spaces,
|
|
|
|
)
|
2020-03-30 23:03:29 +02:00
|
|
|
|
|
|
|
return worker
|