rollout_worker.py 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006
  1. import copy
  2. import importlib.util
  3. import logging
  4. import os
  5. import platform
  6. import socket
  7. import threading
  8. from collections import defaultdict
  9. from types import FunctionType
  10. from typing import (
  11. TYPE_CHECKING,
  12. Any,
  13. Callable,
  14. Collection,
  15. Dict,
  16. List,
  17. Optional,
  18. Set,
  19. Tuple,
  20. Type,
  21. Union,
  22. )
  23. from gymnasium.spaces import Space
  24. import ray
  25. from ray import ObjectRef, cloudpickle as pickle
  26. from ray.rllib.connectors.util import (
  27. create_connectors_for_policy,
  28. maybe_get_filters_for_syncing,
  29. )
  30. from ray.rllib.core.rl_module import validate_module_id
  31. from ray.rllib.core.rl_module.rl_module import RLModuleSpec
  32. from ray.rllib.env.base_env import BaseEnv, convert_to_base_env
  33. from ray.rllib.env.env_context import EnvContext
  34. from ray.rllib.env.env_runner import EnvRunner
  35. from ray.rllib.env.external_multi_agent_env import ExternalMultiAgentEnv
  36. from ray.rllib.env.multi_agent_env import MultiAgentEnv
  37. from ray.rllib.env.wrappers.atari_wrappers import is_atari, wrap_deepmind
  38. from ray.rllib.evaluation.metrics import RolloutMetrics
  39. from ray.rllib.evaluation.sampler import SyncSampler
  40. from ray.rllib.models import ModelCatalog
  41. from ray.rllib.models.preprocessors import Preprocessor
  42. from ray.rllib.offline import (
  43. D4RLReader,
  44. DatasetReader,
  45. DatasetWriter,
  46. InputReader,
  47. IOContext,
  48. JsonReader,
  49. JsonWriter,
  50. MixedInput,
  51. NoopOutput,
  52. OutputWriter,
  53. ShuffledInput,
  54. )
  55. from ray.rllib.policy.policy import Policy, PolicySpec
  56. from ray.rllib.policy.policy_map import PolicyMap
  57. from ray.rllib.policy.sample_batch import (
  58. DEFAULT_POLICY_ID,
  59. MultiAgentBatch,
  60. concat_samples,
  61. convert_ma_batch_to_sample_batch,
  62. )
  63. from ray.rllib.policy.torch_policy import TorchPolicy
  64. from ray.rllib.policy.torch_policy_v2 import TorchPolicyV2
  65. from ray.rllib.utils import force_list
  66. from ray.rllib.utils.annotations import OldAPIStack, override
  67. from ray.rllib.utils.debug import summarize, update_global_seed_if_necessary
  68. from ray.rllib.utils.error import ERR_MSG_NO_GPUS, HOWTO_CHANGE_CONFIG
  69. from ray.rllib.utils.filter import Filter, NoFilter
  70. from ray.rllib.utils.framework import try_import_tf, try_import_torch
  71. from ray.rllib.utils.from_config import from_config
  72. from ray.rllib.utils.policy import create_policy_for_framework
  73. from ray.rllib.utils.sgd import do_minibatch_sgd
  74. from ray.rllib.utils.tf_run_builder import _TFRunBuilder
  75. from ray.rllib.utils.tf_utils import (
  76. get_gpu_devices as get_tf_gpu_devices,
  77. get_tf_eager_cls_if_necessary,
  78. )
  79. from ray.rllib.utils.typing import (
  80. AgentID,
  81. EnvCreator,
  82. EnvType,
  83. ModelGradients,
  84. ModelWeights,
  85. MultiAgentPolicyConfigDict,
  86. PartialAlgorithmConfigDict,
  87. PolicyID,
  88. PolicyState,
  89. SampleBatchType,
  90. T,
  91. )
  92. from ray.tune.registry import registry_contains_input, registry_get_input
  93. from ray.util.annotations import PublicAPI
  94. from ray.util.debug import disable_log_once_globally, enable_periodic_logging, log_once
  95. from ray.util.iter import ParallelIteratorWorker
  96. if TYPE_CHECKING:
  97. from ray.rllib.algorithms.algorithm_config import AlgorithmConfig
  98. from ray.rllib.callbacks.callbacks import RLlibCallback
  99. tf1, tf, tfv = try_import_tf()
  100. torch, _ = try_import_torch()
  101. logger = logging.getLogger(__name__)
  102. # Handle to the current rollout worker, which will be set to the most recently
  103. # created RolloutWorker in this process. This can be helpful to access in
  104. # custom env or policy classes for debugging or advanced use cases.
  105. _global_worker: Optional["RolloutWorker"] = None
  106. @OldAPIStack
  107. def get_global_worker() -> "RolloutWorker":
  108. """Returns a handle to the active rollout worker in this process."""
  109. global _global_worker
  110. return _global_worker
  111. def _update_env_seed_if_necessary(
  112. env: EnvType, seed: int, worker_idx: int, vector_idx: int
  113. ):
  114. """Set a deterministic random seed on environment.
  115. NOTE: this may not work with remote environments (issue #18154).
  116. """
  117. if seed is None:
  118. return
  119. # A single RL job is unlikely to have more than 10K
  120. # rollout workers.
  121. max_num_envs_per_env_runner: int = 1000
  122. assert (
  123. worker_idx < max_num_envs_per_env_runner
  124. ), "Too many envs per worker. Random seeds may collide."
  125. computed_seed: int = worker_idx * max_num_envs_per_env_runner + vector_idx + seed
  126. # Gymnasium.env.
  127. # This will silently fail for most Farama-foundation gymnasium environments.
  128. # (they do nothing and return None per default)
  129. if not hasattr(env, "reset"):
  130. if log_once("env_has_no_reset_method"):
  131. logger.info(f"Env {env} doesn't have a `reset()` method. Cannot seed.")
  132. else:
  133. try:
  134. env.reset(seed=computed_seed)
  135. except Exception:
  136. logger.info(
  137. f"Env {env} doesn't support setting a seed via its `reset()` "
  138. "method! Implement this method as `reset(self, *, seed=None, "
  139. "options=None)` for it to abide to the correct API. Cannot seed."
  140. )
  141. @OldAPIStack
  142. class RolloutWorker(ParallelIteratorWorker, EnvRunner):
  143. """Common experience collection class.
  144. This class wraps a policy instance and an environment class to
  145. collect experiences from the environment. You can create many replicas of
  146. this class as Ray actors to scale RL training.
  147. This class supports vectorized and multi-agent policy evaluation (e.g.,
  148. VectorEnv, MultiAgentEnv, etc.)
  149. .. testcode::
  150. :skipif: True
  151. # Create a rollout worker and using it to collect experiences.
  152. import gymnasium as gym
  153. from ray.rllib.evaluation.rollout_worker import RolloutWorker
  154. from ray.rllib.algorithms.ppo.ppo_tf_policy import PPOTF1Policy
  155. worker = RolloutWorker(
  156. env_creator=lambda _: gym.make("CartPole-v1"),
  157. default_policy_class=PPOTF1Policy)
  158. print(worker.sample())
  159. # Creating a multi-agent rollout worker
  160. from gymnasium.spaces import Discrete, Box
  161. import random
  162. MultiAgentTrafficGrid = ...
  163. worker = RolloutWorker(
  164. env_creator=lambda _: MultiAgentTrafficGrid(num_cars=25),
  165. config=AlgorithmConfig().multi_agent(
  166. policies={
  167. # Use an ensemble of two policies for car agents
  168. "car_policy1":
  169. (PGTFPolicy, Box(...), Discrete(...),
  170. AlgorithmConfig.overrides(gamma=0.99)),
  171. "car_policy2":
  172. (PGTFPolicy, Box(...), Discrete(...),
  173. AlgorithmConfig.overrides(gamma=0.95)),
  174. # Use a single shared policy for all traffic lights
  175. "traffic_light_policy":
  176. (PGTFPolicy, Box(...), Discrete(...), {}),
  177. },
  178. policy_mapping_fn=(
  179. lambda agent_id, episode, **kwargs:
  180. random.choice(["car_policy1", "car_policy2"])
  181. if agent_id.startswith("car_") else "traffic_light_policy"),
  182. ),
  183. )
  184. print(worker.sample())
  185. .. testoutput::
  186. SampleBatch({
  187. "obs": [[...]], "actions": [[...]], "rewards": [[...]],
  188. "terminateds": [[...]], "truncateds": [[...]], "new_obs": [[...]]}
  189. )
  190. MultiAgentBatch({
  191. "car_policy1": SampleBatch(...),
  192. "car_policy2": SampleBatch(...),
  193. "traffic_light_policy": SampleBatch(...)}
  194. )
  195. """
  196. def __init__(
  197. self,
  198. *,
  199. env_creator: EnvCreator,
  200. validate_env: Optional[Callable[[EnvType, EnvContext], None]] = None,
  201. config: Optional["AlgorithmConfig"] = None,
  202. worker_index: int = 0,
  203. num_workers: Optional[int] = None,
  204. recreated_worker: bool = False,
  205. log_dir: Optional[str] = None,
  206. spaces: Optional[Dict[PolicyID, Tuple[Space, Space]]] = None,
  207. default_policy_class: Optional[Type[Policy]] = None,
  208. dataset_shards: Optional[List[ray.data.Dataset]] = None,
  209. **kwargs,
  210. ):
  211. """Initializes a RolloutWorker instance.
  212. Args:
  213. env_creator: Function that returns a gym.Env given an EnvContext
  214. wrapped configuration.
  215. validate_env: Optional callable to validate the generated
  216. environment (only on worker=0).
  217. worker_index: For remote workers, this should be set to a
  218. non-zero and unique value. This index is passed to created envs
  219. through EnvContext so that envs can be configured per worker.
  220. recreated_worker: Whether this worker is a recreated one. Workers are
  221. recreated by an Algorithm (via EnvRunnerGroup) in case
  222. `restart_failed_env_runners=True` and one of the original workers (or
  223. an already recreated one) has failed. They don't differ from original
  224. workers other than the value of this flag (`self.recreated_worker`).
  225. log_dir: Directory where logs can be placed.
  226. spaces: An optional space dict mapping policy IDs
  227. to (obs_space, action_space)-tuples. This is used in case no
  228. Env is created on this RolloutWorker.
  229. """
  230. self._original_kwargs: dict = locals().copy()
  231. del self._original_kwargs["self"]
  232. global _global_worker
  233. _global_worker = self
  234. from ray.rllib.algorithms.algorithm_config import AlgorithmConfig
  235. # Default config needed?
  236. if config is None or isinstance(config, dict):
  237. config = AlgorithmConfig().update_from_dict(config or {})
  238. # Freeze config, so no one else can alter it from here on.
  239. config.freeze()
  240. # Set extra python env variables before calling super constructor.
  241. if config.extra_python_environs_for_driver and worker_index == 0:
  242. for key, value in config.extra_python_environs_for_driver.items():
  243. os.environ[key] = str(value)
  244. elif config.extra_python_environs_for_worker and worker_index > 0:
  245. for key, value in config.extra_python_environs_for_worker.items():
  246. os.environ[key] = str(value)
  247. def gen_rollouts():
  248. while True:
  249. yield self.sample()
  250. ParallelIteratorWorker.__init__(self, gen_rollouts, False)
  251. EnvRunner.__init__(self, config=config)
  252. self.num_workers = (
  253. num_workers if num_workers is not None else self.config.num_env_runners
  254. )
  255. # In case we are reading from distributed datasets, store the shards here
  256. # and pick our shard by our worker-index.
  257. self._ds_shards = dataset_shards
  258. self.worker_index: int = worker_index
  259. # Lock to be able to lock this entire worker
  260. # (via `self.lock()` and `self.unlock()`).
  261. # This might be crucial to prevent a race condition in case
  262. # `config.policy_states_are_swappable=True` and you are using an Algorithm
  263. # with a learner thread. In this case, the thread might update a policy
  264. # that is being swapped (during the update) by the Algorithm's
  265. # training_step's `RolloutWorker.get_weights()` call (to sync back the
  266. # new weights to all remote workers).
  267. self._lock = threading.Lock()
  268. if (
  269. tf1
  270. and (config.framework_str == "tf2" or config.enable_tf1_exec_eagerly)
  271. # This eager check is necessary for certain all-framework tests
  272. # that use tf's eager_mode() context generator.
  273. and not tf1.executing_eagerly()
  274. ):
  275. tf1.enable_eager_execution()
  276. if self.config.log_level:
  277. logging.getLogger("ray.rllib").setLevel(self.config.log_level)
  278. if self.worker_index > 1:
  279. disable_log_once_globally() # only need 1 worker to log
  280. elif self.config.log_level == "DEBUG":
  281. enable_periodic_logging()
  282. env_context = EnvContext(
  283. self.config.env_config,
  284. worker_index=self.worker_index,
  285. vector_index=0,
  286. num_workers=self.num_workers,
  287. remote=self.config.remote_worker_envs,
  288. recreated_worker=recreated_worker,
  289. )
  290. self.env_context = env_context
  291. self.config: AlgorithmConfig = config
  292. self.callbacks: RLlibCallback = self.config.callbacks_class()
  293. self.recreated_worker: bool = recreated_worker
  294. # Setup current policy_mapping_fn. Start with the one from the config, which
  295. # might be None in older checkpoints (nowadays AlgorithmConfig has a proper
  296. # default for this); Need to cover this situation via the backup lambda here.
  297. self.policy_mapping_fn = (
  298. lambda agent_id, episode, worker, **kw: DEFAULT_POLICY_ID
  299. )
  300. self.set_policy_mapping_fn(self.config.policy_mapping_fn)
  301. self.env_creator: EnvCreator = env_creator
  302. # Resolve possible auto-fragment length.
  303. configured_rollout_fragment_length = self.config.get_rollout_fragment_length(
  304. worker_index=self.worker_index
  305. )
  306. self.total_rollout_fragment_length: int = (
  307. configured_rollout_fragment_length * self.config.num_envs_per_env_runner
  308. )
  309. self.preprocessing_enabled: bool = not config._disable_preprocessor_api
  310. self.last_batch: Optional[SampleBatchType] = None
  311. self.global_vars: dict = {
  312. # TODO(sven): Make this per-policy!
  313. "timestep": 0,
  314. # Counter for performed gradient updates per policy in `self.policy_map`.
  315. # Allows for compiling metrics on the off-policy'ness of an update given
  316. # that the number of gradient updates of the sampling policies are known
  317. # to the learner (and can be compared to the learner version of the same
  318. # policy).
  319. "num_grad_updates_per_policy": defaultdict(int),
  320. }
  321. # If seed is provided, add worker index to it and 10k iff evaluation worker.
  322. self.seed = (
  323. None
  324. if self.config.seed is None
  325. else self.config.seed
  326. + self.worker_index
  327. + self.config.in_evaluation * 10000
  328. )
  329. # Update the global seed for numpy/random/tf-eager/torch if we are not
  330. # the local worker, otherwise, this was already done in the Algorithm
  331. # object itself.
  332. if self.worker_index > 0:
  333. update_global_seed_if_necessary(self.config.framework_str, self.seed)
  334. # A single environment provided by the user (via config.env). This may
  335. # also remain None.
  336. # 1) Create the env using the user provided env_creator. This may
  337. # return a gym.Env (incl. MultiAgentEnv), an already vectorized
  338. # VectorEnv, BaseEnv, ExternalEnv, or an ActorHandle (remote env).
  339. # 2) Wrap - if applicable - with Atari/rendering wrappers.
  340. # 3) Seed the env, if necessary.
  341. # 4) Vectorize the existing single env by creating more clones of
  342. # this env and wrapping it with the RLlib BaseEnv class.
  343. self.env = self.make_sub_env_fn = None
  344. # Create a (single) env for this worker.
  345. if not (
  346. self.worker_index == 0
  347. and self.num_workers > 0
  348. and not self.config.create_local_env_runner
  349. ):
  350. # Run the `env_creator` function passing the EnvContext.
  351. self.env = env_creator(copy.deepcopy(self.env_context))
  352. clip_rewards = self.config.clip_rewards
  353. if self.env is not None:
  354. # Custom validation function given, typically a function attribute of the
  355. # Algorithm.
  356. if validate_env is not None:
  357. validate_env(self.env, self.env_context)
  358. # We can't auto-wrap a BaseEnv.
  359. if isinstance(self.env, (BaseEnv, ray.actor.ActorHandle)):
  360. def wrap(env):
  361. return env
  362. # Atari type env and "deepmind" preprocessor pref.
  363. elif is_atari(self.env) and self.config.preprocessor_pref == "deepmind":
  364. # Deepmind wrappers already handle all preprocessing.
  365. self.preprocessing_enabled = False
  366. # If clip_rewards not explicitly set to False, switch it
  367. # on here (clip between -1.0 and 1.0).
  368. if self.config.clip_rewards is None:
  369. clip_rewards = True
  370. # Framestacking is used.
  371. use_framestack = self.config.model.get("framestack") is True
  372. def wrap(env):
  373. env = wrap_deepmind(
  374. env,
  375. dim=self.config.model.get("dim"),
  376. framestack=use_framestack,
  377. noframeskip=self.config.env_config.get("frameskip", 0) == 1,
  378. )
  379. return env
  380. elif self.config.preprocessor_pref is None:
  381. # Only turn off preprocessing
  382. self.preprocessing_enabled = False
  383. def wrap(env):
  384. return env
  385. else:
  386. def wrap(env):
  387. return env
  388. # Wrap env through the correct wrapper.
  389. self.env: EnvType = wrap(self.env)
  390. # Ideally, we would use the same make_sub_env() function below
  391. # to create self.env, but wrap(env) and self.env has a cyclic
  392. # dependency on each other right now, so we would settle on
  393. # duplicating the random seed setting logic for now.
  394. _update_env_seed_if_necessary(self.env, self.seed, self.worker_index, 0)
  395. # Call custom callback function `on_sub_environment_created`.
  396. self.callbacks.on_sub_environment_created(
  397. worker=self,
  398. sub_environment=self.env,
  399. env_context=self.env_context,
  400. )
  401. self.make_sub_env_fn = self._get_make_sub_env_fn(
  402. env_creator, env_context, validate_env, wrap, self.seed
  403. )
  404. self.spaces = spaces
  405. self.default_policy_class = default_policy_class
  406. self.policy_dict, self.is_policy_to_train = self.config.get_multi_agent_setup(
  407. env=self.env,
  408. spaces=self.spaces,
  409. default_policy_class=self.default_policy_class,
  410. )
  411. self.policy_map: Optional[PolicyMap] = None
  412. # TODO(jungong) : clean up after non-connector env_runner is fully deprecated.
  413. self.preprocessors: Dict[PolicyID, Preprocessor] = None
  414. # Check available number of GPUs.
  415. num_gpus = (
  416. self.config.num_gpus
  417. if self.worker_index == 0
  418. else self.config.num_gpus_per_env_runner
  419. )
  420. # Error if we don't find enough GPUs.
  421. if (
  422. ray.is_initialized()
  423. and ray._private.worker._mode() != ray._private.worker.LOCAL_MODE
  424. and not config._fake_gpus
  425. ):
  426. devices = []
  427. if self.config.framework_str in ["tf2", "tf"]:
  428. devices = get_tf_gpu_devices()
  429. elif self.config.framework_str == "torch":
  430. devices = list(range(torch.cuda.device_count()))
  431. if len(devices) < num_gpus:
  432. raise RuntimeError(
  433. ERR_MSG_NO_GPUS.format(len(devices), devices) + HOWTO_CHANGE_CONFIG
  434. )
  435. # Warn, if running in local-mode and actual GPUs (not faked) are
  436. # requested.
  437. elif (
  438. ray.is_initialized()
  439. and ray._private.worker._mode() == ray._private.worker.LOCAL_MODE
  440. and num_gpus > 0
  441. and not self.config._fake_gpus
  442. ):
  443. logger.warning(
  444. "You are running ray with `local_mode=True`, but have "
  445. f"configured {num_gpus} GPUs to be used! In local mode, "
  446. f"Policies are placed on the CPU and the `num_gpus` setting "
  447. f"is ignored."
  448. )
  449. self.filters: Dict[PolicyID, Filter] = defaultdict(NoFilter)
  450. # If RLModule API is enabled, multi_rl_module_spec holds the specs of the
  451. # RLModules.
  452. self.multi_rl_module_spec = None
  453. self._update_policy_map(policy_dict=self.policy_dict)
  454. # Update Policy's view requirements from Model, only if Policy directly
  455. # inherited from base `Policy` class. At this point here, the Policy
  456. # must have it's Model (if any) defined and ready to output an initial
  457. # state.
  458. for pol in self.policy_map.values():
  459. if not pol._model_init_state_automatically_added:
  460. pol._update_model_view_requirements_from_init_state()
  461. if (
  462. self.config.is_multi_agent
  463. and self.env is not None
  464. and not isinstance(
  465. self.env,
  466. (BaseEnv, ExternalMultiAgentEnv, MultiAgentEnv, ray.actor.ActorHandle),
  467. )
  468. ):
  469. raise ValueError(
  470. f"You are running a multi-agent setup, but the env {self.env} is not a "
  471. f"subclass of BaseEnv, MultiAgentEnv, ActorHandle, or "
  472. f"ExternalMultiAgentEnv!"
  473. )
  474. if self.worker_index == 0:
  475. logger.info("Built filter map: {}".format(self.filters))
  476. # This RolloutWorker has no env.
  477. if self.env is None:
  478. self.async_env = None
  479. # Use a custom env-vectorizer and call it providing self.env.
  480. elif "custom_vector_env" in self.config:
  481. self.async_env = self.config.custom_vector_env(self.env)
  482. # Default: Vectorize self.env via the make_sub_env function. This adds
  483. # further clones of self.env and creates a RLlib BaseEnv (which is
  484. # vectorized under the hood).
  485. else:
  486. # Always use vector env for consistency even if num_envs_per_env_runner=1.
  487. self.async_env: BaseEnv = convert_to_base_env(
  488. self.env,
  489. make_env=self.make_sub_env_fn,
  490. num_envs=self.config.num_envs_per_env_runner,
  491. remote_envs=self.config.remote_worker_envs,
  492. remote_env_batch_wait_ms=self.config.remote_env_batch_wait_ms,
  493. worker=self,
  494. restart_failed_sub_environments=(
  495. self.config.restart_failed_sub_environments
  496. ),
  497. )
  498. # `truncate_episodes`: Allow a batch to contain more than one episode
  499. # (fragments) and always make the batch `rollout_fragment_length`
  500. # long.
  501. rollout_fragment_length_for_sampler = configured_rollout_fragment_length
  502. if self.config.batch_mode == "truncate_episodes":
  503. pack = True
  504. # `complete_episodes`: Never cut episodes and sampler will return
  505. # exactly one (complete) episode per poll.
  506. else:
  507. assert self.config.batch_mode == "complete_episodes"
  508. rollout_fragment_length_for_sampler = float("inf")
  509. pack = False
  510. # Create the IOContext for this worker.
  511. self.io_context: IOContext = IOContext(
  512. log_dir, self.config, self.worker_index, self
  513. )
  514. render = False
  515. if self.config.render_env is True and (
  516. self.num_workers == 0 or self.worker_index == 1
  517. ):
  518. render = True
  519. if self.env is None:
  520. self.sampler = None
  521. else:
  522. self.sampler = SyncSampler(
  523. worker=self,
  524. env=self.async_env,
  525. clip_rewards=clip_rewards,
  526. rollout_fragment_length=rollout_fragment_length_for_sampler,
  527. count_steps_by=self.config.count_steps_by,
  528. callbacks=self.callbacks,
  529. multiple_episodes_in_batch=pack,
  530. normalize_actions=self.config.normalize_actions,
  531. clip_actions=self.config.clip_actions,
  532. observation_fn=self.config.observation_fn,
  533. sample_collector_class=self.config.sample_collector,
  534. render=render,
  535. )
  536. self.input_reader: InputReader = self._get_input_creator_from_config()(
  537. self.io_context
  538. )
  539. self.output_writer: OutputWriter = self._get_output_creator_from_config()(
  540. self.io_context
  541. )
  542. # The current weights sequence number (version). May remain None for when
  543. # not tracking weights versions.
  544. self.weights_seq_no: Optional[int] = None
  545. @override(EnvRunner)
  546. def make_env(self):
  547. # Override this method, b/c it's abstract and must be overridden.
  548. # However, we see no point in implementing it for the old API stack any longer
  549. # (the RolloutWorker class will be deprecated soon).
  550. raise NotImplementedError
  551. @override(EnvRunner)
  552. def assert_healthy(self):
  553. is_healthy = self.policy_map and self.input_reader and self.output_writer
  554. assert is_healthy, (
  555. f"RolloutWorker {self} (idx={self.worker_index}; "
  556. f"num_workers={self.num_workers}) not healthy!"
  557. )
  558. @override(EnvRunner)
  559. def sample(self, **kwargs) -> SampleBatchType:
  560. """Returns a batch of experience sampled from this worker.
  561. This method must be implemented by subclasses.
  562. Returns:
  563. A columnar batch of experiences (e.g., tensors) or a MultiAgentBatch.
  564. .. testcode::
  565. :skipif: True
  566. import gymnasium as gym
  567. from ray.rllib.evaluation.rollout_worker import RolloutWorker
  568. from ray.rllib.algorithms.ppo.ppo_tf_policy import PPOTF1Policy
  569. worker = RolloutWorker(
  570. env_creator=lambda _: gym.make("CartPole-v1"),
  571. default_policy_class=PPOTF1Policy,
  572. config=AlgorithmConfig(),
  573. )
  574. print(worker.sample())
  575. .. testoutput::
  576. SampleBatch({"obs": [...], "action": [...], ...})
  577. """
  578. if self.config.fake_sampler and self.last_batch is not None:
  579. return self.last_batch
  580. elif self.input_reader is None:
  581. raise ValueError(
  582. "RolloutWorker has no `input_reader` object! "
  583. "Cannot call `sample()`. You can try setting "
  584. "`create_local_env_runner` to True."
  585. )
  586. if log_once("sample_start"):
  587. logger.info(
  588. "Generating sample batch of size {}".format(
  589. self.total_rollout_fragment_length
  590. )
  591. )
  592. batches = [self.input_reader.next()]
  593. steps_so_far = (
  594. batches[0].count
  595. if self.config.count_steps_by == "env_steps"
  596. else batches[0].agent_steps()
  597. )
  598. # In truncate_episodes mode, never pull more than 1 batch per env.
  599. # This avoids over-running the target batch size.
  600. if (
  601. self.config.batch_mode == "truncate_episodes"
  602. and not self.config.offline_sampling
  603. ):
  604. max_batches = self.config.num_envs_per_env_runner
  605. else:
  606. max_batches = float("inf")
  607. while steps_so_far < self.total_rollout_fragment_length and (
  608. len(batches) < max_batches
  609. ):
  610. batch = self.input_reader.next()
  611. steps_so_far += (
  612. batch.count
  613. if self.config.count_steps_by == "env_steps"
  614. else batch.agent_steps()
  615. )
  616. batches.append(batch)
  617. batch = concat_samples(batches)
  618. self.callbacks.on_sample_end(worker=self, samples=batch)
  619. # Always do writes prior to compression for consistency and to allow
  620. # for better compression inside the writer.
  621. self.output_writer.write(batch)
  622. if log_once("sample_end"):
  623. logger.info("Completed sample batch:\n\n{}\n".format(summarize(batch)))
  624. if self.config.compress_observations:
  625. batch.compress(bulk=self.config.compress_observations == "bulk")
  626. if self.config.fake_sampler:
  627. self.last_batch = batch
  628. return batch
  629. @override(EnvRunner)
  630. def get_spaces(self) -> Dict[str, Tuple[Space, Space]]:
  631. spaces = self.foreach_policy(
  632. lambda p, pid: (pid, p.observation_space, p.action_space)
  633. )
  634. spaces = {e[0]: (getattr(e[1], "original_space", e[1]), e[2]) for e in spaces}
  635. # Try to add the actual env's obs/action spaces.
  636. env_spaces = self.foreach_env(
  637. lambda env: (env.observation_space, env.action_space)
  638. )
  639. if env_spaces:
  640. from ray.rllib.env import INPUT_ENV_SPACES
  641. spaces[INPUT_ENV_SPACES] = env_spaces[0]
  642. return spaces
  643. @ray.method(num_returns=2)
  644. def sample_with_count(self) -> Tuple[SampleBatchType, int]:
  645. """Same as sample() but returns the count as a separate value.
  646. Returns:
  647. A columnar batch of experiences (e.g., tensors) and the
  648. size of the collected batch.
  649. .. testcode::
  650. :skipif: True
  651. import gymnasium as gym
  652. from ray.rllib.evaluation.rollout_worker import RolloutWorker
  653. from ray.rllib.algorithms.ppo.ppo_tf_policy import PPOTF1Policy
  654. worker = RolloutWorker(
  655. env_creator=lambda _: gym.make("CartPole-v1"),
  656. default_policy_class=PPOTFPolicy)
  657. print(worker.sample_with_count())
  658. .. testoutput::
  659. (SampleBatch({"obs": [...], "action": [...], ...}), 3)
  660. """
  661. batch = self.sample()
  662. return batch, batch.count
  663. def learn_on_batch(self, samples: SampleBatchType) -> Dict:
  664. """Update policies based on the given batch.
  665. This is the equivalent to apply_gradients(compute_gradients(samples)),
  666. but can be optimized to avoid pulling gradients into CPU memory.
  667. Args:
  668. samples: The SampleBatch or MultiAgentBatch to learn on.
  669. Returns:
  670. Dictionary of extra metadata from compute_gradients().
  671. .. testcode::
  672. :skipif: True
  673. import gymnasium as gym
  674. from ray.rllib.evaluation.rollout_worker import RolloutWorker
  675. from ray.rllib.algorithms.ppo.ppo_tf_policy import PPOTF1Policy
  676. worker = RolloutWorker(
  677. env_creator=lambda _: gym.make("CartPole-v1"),
  678. default_policy_class=PPOTF1Policy)
  679. batch = worker.sample()
  680. info = worker.learn_on_batch(samples)
  681. """
  682. if log_once("learn_on_batch"):
  683. logger.info(
  684. "Training on concatenated sample batches:\n\n{}\n".format(
  685. summarize(samples)
  686. )
  687. )
  688. info_out = {}
  689. if isinstance(samples, MultiAgentBatch):
  690. builders = {}
  691. to_fetch = {}
  692. for pid, batch in samples.policy_batches.items():
  693. if self.is_policy_to_train is not None and not self.is_policy_to_train(
  694. pid, samples
  695. ):
  696. continue
  697. # Decompress SampleBatch, in case some columns are compressed.
  698. batch.decompress_if_needed()
  699. policy = self.policy_map[pid]
  700. tf_session = policy.get_session()
  701. if tf_session and hasattr(policy, "_build_learn_on_batch"):
  702. builders[pid] = _TFRunBuilder(tf_session, "learn_on_batch")
  703. to_fetch[pid] = policy._build_learn_on_batch(builders[pid], batch)
  704. else:
  705. info_out[pid] = policy.learn_on_batch(batch)
  706. info_out.update({pid: builders[pid].get(v) for pid, v in to_fetch.items()})
  707. else:
  708. if self.is_policy_to_train is None or self.is_policy_to_train(
  709. DEFAULT_POLICY_ID, samples
  710. ):
  711. info_out.update(
  712. {
  713. DEFAULT_POLICY_ID: self.policy_map[
  714. DEFAULT_POLICY_ID
  715. ].learn_on_batch(samples)
  716. }
  717. )
  718. if log_once("learn_out"):
  719. logger.debug("Training out:\n\n{}\n".format(summarize(info_out)))
  720. return info_out
  721. def sample_and_learn(
  722. self,
  723. expected_batch_size: int,
  724. num_sgd_iter: int,
  725. sgd_minibatch_size: str,
  726. standardize_fields: List[str],
  727. ) -> Tuple[dict, int]:
  728. """Sample and batch and learn on it.
  729. This is typically used in combination with distributed allreduce.
  730. Args:
  731. expected_batch_size: Expected number of samples to learn on.
  732. num_sgd_iter: Number of SGD iterations.
  733. sgd_minibatch_size: SGD minibatch size.
  734. standardize_fields: List of sample fields to normalize.
  735. Returns:
  736. A tuple consisting of a dictionary of extra metadata returned from
  737. the policies' `learn_on_batch()` and the number of samples
  738. learned on.
  739. """
  740. batch = self.sample()
  741. assert batch.count == expected_batch_size, (
  742. "Batch size possibly out of sync between workers, expected:",
  743. expected_batch_size,
  744. "got:",
  745. batch.count,
  746. )
  747. logger.info(
  748. "Executing distributed minibatch SGD "
  749. "with epoch size {}, minibatch size {}".format(
  750. batch.count, sgd_minibatch_size
  751. )
  752. )
  753. info = do_minibatch_sgd(
  754. batch,
  755. self.policy_map,
  756. self,
  757. num_sgd_iter,
  758. sgd_minibatch_size,
  759. standardize_fields,
  760. )
  761. return info, batch.count
  762. def compute_gradients(
  763. self,
  764. samples: SampleBatchType,
  765. single_agent: bool = None,
  766. ) -> Tuple[ModelGradients, dict]:
  767. """Returns a gradient computed w.r.t the specified samples.
  768. Uses the Policy's/ies' compute_gradients method(s) to perform the
  769. calculations. Skips policies that are not trainable as per
  770. `self.is_policy_to_train()`.
  771. Args:
  772. samples: The SampleBatch or MultiAgentBatch to compute gradients
  773. for using this worker's trainable policies.
  774. Returns:
  775. In the single-agent case, a tuple consisting of ModelGradients and
  776. info dict of the worker's policy.
  777. In the multi-agent case, a tuple consisting of a dict mapping
  778. PolicyID to ModelGradients and a dict mapping PolicyID to extra
  779. metadata info.
  780. Note that the first return value (grads) can be applied as is to a
  781. compatible worker using the worker's `apply_gradients()` method.
  782. .. testcode::
  783. :skipif: True
  784. import gymnasium as gym
  785. from ray.rllib.evaluation.rollout_worker import RolloutWorker
  786. from ray.rllib.algorithms.ppo.ppo_tf_policy import PPOTF1Policy
  787. worker = RolloutWorker(
  788. env_creator=lambda _: gym.make("CartPole-v1"),
  789. default_policy_class=PPOTF1Policy)
  790. batch = worker.sample()
  791. grads, info = worker.compute_gradients(samples)
  792. """
  793. if log_once("compute_gradients"):
  794. logger.info("Compute gradients on:\n\n{}\n".format(summarize(samples)))
  795. if single_agent is True:
  796. samples = convert_ma_batch_to_sample_batch(samples)
  797. grad_out, info_out = self.policy_map[DEFAULT_POLICY_ID].compute_gradients(
  798. samples
  799. )
  800. info_out["batch_count"] = samples.count
  801. return grad_out, info_out
  802. # Treat everything as is multi-agent.
  803. samples = samples.as_multi_agent()
  804. # Calculate gradients for all policies.
  805. grad_out, info_out = {}, {}
  806. if self.config.framework_str == "tf":
  807. for pid, batch in samples.policy_batches.items():
  808. if self.is_policy_to_train is not None and not self.is_policy_to_train(
  809. pid, samples
  810. ):
  811. continue
  812. policy = self.policy_map[pid]
  813. builder = _TFRunBuilder(policy.get_session(), "compute_gradients")
  814. grad_out[pid], info_out[pid] = policy._build_compute_gradients(
  815. builder, batch
  816. )
  817. grad_out = {k: builder.get(v) for k, v in grad_out.items()}
  818. info_out = {k: builder.get(v) for k, v in info_out.items()}
  819. else:
  820. for pid, batch in samples.policy_batches.items():
  821. if self.is_policy_to_train is not None and not self.is_policy_to_train(
  822. pid, samples
  823. ):
  824. continue
  825. grad_out[pid], info_out[pid] = self.policy_map[pid].compute_gradients(
  826. batch
  827. )
  828. info_out["batch_count"] = samples.count
  829. if log_once("grad_out"):
  830. logger.info("Compute grad info:\n\n{}\n".format(summarize(info_out)))
  831. return grad_out, info_out
  832. def apply_gradients(
  833. self,
  834. grads: Union[ModelGradients, Dict[PolicyID, ModelGradients]],
  835. ) -> None:
  836. """Applies the given gradients to this worker's models.
  837. Uses the Policy's/ies' apply_gradients method(s) to perform the
  838. operations.
  839. Args:
  840. grads: Single ModelGradients (single-agent case) or a dict
  841. mapping PolicyIDs to the respective model gradients
  842. structs.
  843. .. testcode::
  844. :skipif: True
  845. import gymnasium as gym
  846. from ray.rllib.evaluation.rollout_worker import RolloutWorker
  847. from ray.rllib.algorithms.ppo.ppo_tf_policy import PPOTF1Policy
  848. worker = RolloutWorker(
  849. env_creator=lambda _: gym.make("CartPole-v1"),
  850. default_policy_class=PPOTF1Policy)
  851. samples = worker.sample()
  852. grads, info = worker.compute_gradients(samples)
  853. worker.apply_gradients(grads)
  854. """
  855. if log_once("apply_gradients"):
  856. logger.info("Apply gradients:\n\n{}\n".format(summarize(grads)))
  857. # Grads is a dict (mapping PolicyIDs to ModelGradients).
  858. # Multi-agent case.
  859. if isinstance(grads, dict):
  860. for pid, g in grads.items():
  861. if self.is_policy_to_train is None or self.is_policy_to_train(
  862. pid, None
  863. ):
  864. self.policy_map[pid].apply_gradients(g)
  865. # Grads is a ModelGradients type. Single-agent case.
  866. elif self.is_policy_to_train is None or self.is_policy_to_train(
  867. DEFAULT_POLICY_ID, None
  868. ):
  869. self.policy_map[DEFAULT_POLICY_ID].apply_gradients(grads)
  870. @override(EnvRunner)
  871. def get_metrics(self) -> List[RolloutMetrics]:
  872. """Returns the thus-far collected metrics from this worker's rollouts.
  873. Returns:
  874. List of RolloutMetrics collected thus-far.
  875. """
  876. # Get metrics from sampler (if any).
  877. if self.sampler is not None:
  878. out = self.sampler.get_metrics()
  879. else:
  880. out = []
  881. return out
  882. def foreach_env(self, func: Callable[[EnvType], T]) -> List[T]:
  883. """Calls the given function with each sub-environment as arg.
  884. Args:
  885. func: The function to call for each underlying
  886. sub-environment (as only arg).
  887. Returns:
  888. The list of return values of all calls to `func([env])`.
  889. """
  890. if self.async_env is None:
  891. return []
  892. envs = self.async_env.get_sub_environments()
  893. # Empty list (not implemented): Call function directly on the
  894. # BaseEnv.
  895. if not envs:
  896. return [func(self.async_env)]
  897. # Call function on all underlying (vectorized) sub environments.
  898. else:
  899. return [func(e) for e in envs]
  900. def foreach_env_with_context(
  901. self, func: Callable[[EnvType, EnvContext], T]
  902. ) -> List[T]:
  903. """Calls given function with each sub-env plus env_ctx as args.
  904. Args:
  905. func: The function to call for each underlying
  906. sub-environment and its EnvContext (as the args).
  907. Returns:
  908. The list of return values of all calls to `func([env, ctx])`.
  909. """
  910. if self.async_env is None:
  911. return []
  912. envs = self.async_env.get_sub_environments()
  913. # Empty list (not implemented): Call function directly on the
  914. # BaseEnv.
  915. if not envs:
  916. return [func(self.async_env, self.env_context)]
  917. # Call function on all underlying (vectorized) sub environments.
  918. else:
  919. ret = []
  920. for i, e in enumerate(envs):
  921. ctx = self.env_context.copy_with_overrides(vector_index=i)
  922. ret.append(func(e, ctx))
  923. return ret
  924. def get_policy(self, policy_id: PolicyID = DEFAULT_POLICY_ID) -> Optional[Policy]:
  925. """Return policy for the specified id, or None.
  926. Args:
  927. policy_id: ID of the policy to return. None for DEFAULT_POLICY_ID
  928. (in the single agent case).
  929. Returns:
  930. The policy under the given ID (or None if not found).
  931. """
  932. return self.policy_map.get(policy_id)
  933. def add_policy(
  934. self,
  935. policy_id: PolicyID,
  936. policy_cls: Optional[Type[Policy]] = None,
  937. policy: Optional[Policy] = None,
  938. *,
  939. observation_space: Optional[Space] = None,
  940. action_space: Optional[Space] = None,
  941. config: Optional[PartialAlgorithmConfigDict] = None,
  942. policy_state: Optional[PolicyState] = None,
  943. policy_mapping_fn=None,
  944. policies_to_train: Optional[
  945. Union[Collection[PolicyID], Callable[[PolicyID, SampleBatchType], bool]]
  946. ] = None,
  947. module_spec: Optional[RLModuleSpec] = None,
  948. ) -> Policy:
  949. """Adds a new policy to this RolloutWorker.
  950. Args:
  951. policy_id: ID of the policy to add.
  952. policy_cls: The Policy class to use for constructing the new Policy.
  953. Note: Only one of `policy_cls` or `policy` must be provided.
  954. policy: The Policy instance to add to this algorithm.
  955. Note: Only one of `policy_cls` or `policy` must be provided.
  956. observation_space: The observation space of the policy to add.
  957. action_space: The action space of the policy to add.
  958. config: The config overrides for the policy to add.
  959. policy_state: Optional state dict to apply to the new
  960. policy instance, right after its construction.
  961. policy_mapping_fn: An optional (updated) policy mapping function
  962. to use from here on. Note that already ongoing episodes will
  963. not change their mapping but will use the old mapping till
  964. the end of the episode.
  965. policies_to_train: An optional collection of policy IDs to be
  966. trained or a callable taking PolicyID and - optionally -
  967. SampleBatchType and returning a bool (trainable or not?).
  968. If None, will keep the existing setup in place.
  969. Policies, whose IDs are not in the list (or for which the
  970. callable returns False) will not be updated.
  971. module_spec: In the new RLModule API we need to pass in the module_spec for
  972. the new module that is supposed to be added. Knowing the policy spec is
  973. not sufficient.
  974. Returns:
  975. The newly added policy.
  976. Raises:
  977. ValueError: If both `policy_cls` AND `policy` are provided.
  978. KeyError: If the given `policy_id` already exists in this worker's
  979. PolicyMap.
  980. """
  981. validate_module_id(policy_id, error=False)
  982. if module_spec is not None:
  983. raise ValueError(
  984. "If you pass in module_spec to the policy, the RLModule API needs "
  985. "to be enabled."
  986. )
  987. if policy_id in self.policy_map:
  988. raise KeyError(
  989. f"Policy ID '{policy_id}' already exists in policy map! "
  990. "Make sure you use a Policy ID that has not been taken yet."
  991. " Policy IDs that are already in your policy map: "
  992. f"{list(self.policy_map.keys())}"
  993. )
  994. if (policy_cls is None) == (policy is None):
  995. raise ValueError(
  996. "Only one of `policy_cls` or `policy` must be provided to "
  997. "RolloutWorker.add_policy()!"
  998. )
  999. if policy is None:
  1000. policy_dict_to_add, _ = self.config.get_multi_agent_setup(
  1001. policies={
  1002. policy_id: PolicySpec(
  1003. policy_cls, observation_space, action_space, config
  1004. )
  1005. },
  1006. env=self.env,
  1007. spaces=self.spaces,
  1008. default_policy_class=self.default_policy_class,
  1009. )
  1010. else:
  1011. policy_dict_to_add = {
  1012. policy_id: PolicySpec(
  1013. type(policy),
  1014. policy.observation_space,
  1015. policy.action_space,
  1016. policy.config,
  1017. )
  1018. }
  1019. self.policy_dict.update(policy_dict_to_add)
  1020. self._update_policy_map(
  1021. policy_dict=policy_dict_to_add,
  1022. policy=policy,
  1023. policy_states={policy_id: policy_state},
  1024. single_agent_rl_module_spec=module_spec,
  1025. )
  1026. self.set_policy_mapping_fn(policy_mapping_fn)
  1027. if policies_to_train is not None:
  1028. self.set_is_policy_to_train(policies_to_train)
  1029. return self.policy_map[policy_id]
  1030. def remove_policy(
  1031. self,
  1032. *,
  1033. policy_id: PolicyID = DEFAULT_POLICY_ID,
  1034. policy_mapping_fn: Optional[Callable[[AgentID], PolicyID]] = None,
  1035. policies_to_train: Optional[
  1036. Union[Collection[PolicyID], Callable[[PolicyID, SampleBatchType], bool]]
  1037. ] = None,
  1038. ) -> None:
  1039. """Removes a policy from this RolloutWorker.
  1040. Args:
  1041. policy_id: ID of the policy to be removed. None for
  1042. DEFAULT_POLICY_ID.
  1043. policy_mapping_fn: An optional (updated) policy mapping function
  1044. to use from here on. Note that already ongoing episodes will
  1045. not change their mapping but will use the old mapping till
  1046. the end of the episode.
  1047. policies_to_train: An optional collection of policy IDs to be
  1048. trained or a callable taking PolicyID and - optionally -
  1049. SampleBatchType and returning a bool (trainable or not?).
  1050. If None, will keep the existing setup in place.
  1051. Policies, whose IDs are not in the list (or for which the
  1052. callable returns False) will not be updated.
  1053. """
  1054. if policy_id not in self.policy_map:
  1055. raise ValueError(f"Policy ID '{policy_id}' not in policy map!")
  1056. del self.policy_map[policy_id]
  1057. del self.preprocessors[policy_id]
  1058. self.set_policy_mapping_fn(policy_mapping_fn)
  1059. if policies_to_train is not None:
  1060. self.set_is_policy_to_train(policies_to_train)
  1061. def set_policy_mapping_fn(
  1062. self,
  1063. policy_mapping_fn: Optional[Callable[[AgentID, Any], PolicyID]] = None,
  1064. ) -> None:
  1065. """Sets `self.policy_mapping_fn` to a new callable (if provided).
  1066. Args:
  1067. policy_mapping_fn: The new mapping function to use. If None,
  1068. will keep the existing mapping function in place.
  1069. """
  1070. if policy_mapping_fn is not None:
  1071. self.policy_mapping_fn = policy_mapping_fn
  1072. if not callable(self.policy_mapping_fn):
  1073. raise ValueError("`policy_mapping_fn` must be a callable!")
  1074. def set_is_policy_to_train(
  1075. self,
  1076. is_policy_to_train: Union[
  1077. Collection[PolicyID], Callable[[PolicyID, Optional[SampleBatchType]], bool]
  1078. ],
  1079. ) -> None:
  1080. """Sets `self.is_policy_to_train()` to a new callable.
  1081. Args:
  1082. is_policy_to_train: A collection of policy IDs to be
  1083. trained or a callable taking PolicyID and - optionally -
  1084. SampleBatchType and returning a bool (trainable or not?).
  1085. If None, will keep the existing setup in place.
  1086. Policies, whose IDs are not in the list (or for which the
  1087. callable returns False) will not be updated.
  1088. """
  1089. # If collection given, construct a simple default callable returning True
  1090. # if the PolicyID is found in the list/set of IDs.
  1091. if not callable(is_policy_to_train):
  1092. assert isinstance(is_policy_to_train, (list, set, tuple)), (
  1093. "ERROR: `is_policy_to_train`must be a [list|set|tuple] or a "
  1094. "callable taking PolicyID and SampleBatch and returning "
  1095. "True|False (trainable or not?)."
  1096. )
  1097. pols = set(is_policy_to_train)
  1098. def is_policy_to_train(pid, batch=None):
  1099. return pid in pols
  1100. self.is_policy_to_train = is_policy_to_train
  1101. @PublicAPI(stability="alpha")
  1102. def get_policies_to_train(
  1103. self, batch: Optional[SampleBatchType] = None
  1104. ) -> Set[PolicyID]:
  1105. """Returns all policies-to-train, given an optional batch.
  1106. Loops through all policies currently in `self.policy_map` and checks
  1107. the return value of `self.is_policy_to_train(pid, batch)`.
  1108. Args:
  1109. batch: An optional SampleBatchType for the
  1110. `self.is_policy_to_train(pid, [batch]?)` check.
  1111. Returns:
  1112. The set of currently trainable policy IDs, given the optional
  1113. `batch`.
  1114. """
  1115. return {
  1116. pid
  1117. for pid in self.policy_map.keys()
  1118. if self.is_policy_to_train is None or self.is_policy_to_train(pid, batch)
  1119. }
  1120. def for_policy(
  1121. self,
  1122. func: Callable[[Policy, Optional[Any]], T],
  1123. policy_id: Optional[PolicyID] = DEFAULT_POLICY_ID,
  1124. **kwargs,
  1125. ) -> T:
  1126. """Calls the given function with the specified policy as first arg.
  1127. Args:
  1128. func: The function to call with the policy as first arg.
  1129. policy_id: The PolicyID of the policy to call the function with.
  1130. Keyword Args:
  1131. kwargs: Additional kwargs to be passed to the call.
  1132. Returns:
  1133. The return value of the function call.
  1134. """
  1135. return func(self.policy_map[policy_id], **kwargs)
  1136. def foreach_policy(
  1137. self, func: Callable[[Policy, PolicyID, Optional[Any]], T], **kwargs
  1138. ) -> List[T]:
  1139. """Calls the given function with each (policy, policy_id) tuple.
  1140. Args:
  1141. func: The function to call with each (policy, policy ID) tuple.
  1142. Keyword Args:
  1143. kwargs: Additional kwargs to be passed to the call.
  1144. Returns:
  1145. The list of return values of all calls to
  1146. `func([policy, pid, **kwargs])`.
  1147. """
  1148. return [func(policy, pid, **kwargs) for pid, policy in self.policy_map.items()]
  1149. def foreach_policy_to_train(
  1150. self, func: Callable[[Policy, PolicyID, Optional[Any]], T], **kwargs
  1151. ) -> List[T]:
  1152. """
  1153. Calls the given function with each (policy, policy_id) tuple.
  1154. Only those policies/IDs will be called on, for which
  1155. `self.is_policy_to_train()` returns True.
  1156. Args:
  1157. func: The function to call with each (policy, policy ID) tuple,
  1158. for only those policies that `self.is_policy_to_train`
  1159. returns True.
  1160. Keyword Args:
  1161. kwargs: Additional kwargs to be passed to the call.
  1162. Returns:
  1163. The list of return values of all calls to
  1164. `func([policy, pid, **kwargs])`.
  1165. """
  1166. return [
  1167. # Make sure to only iterate over keys() and not items(). Iterating over
  1168. # items will access policy_map elements even for pids that we do not need,
  1169. # i.e. those that are not in policy_to_train. Access to policy_map elements
  1170. # can cause disk access for policies that were offloaded to disk. Since
  1171. # these policies will be skipped in the for-loop accessing them is
  1172. # unnecessary, making subsequent disk access unnecessary.
  1173. func(self.policy_map[pid], pid, **kwargs)
  1174. for pid in self.policy_map.keys()
  1175. if self.is_policy_to_train is None or self.is_policy_to_train(pid, None)
  1176. ]
  1177. def sync_filters(self, new_filters: dict) -> None:
  1178. """Changes self's filter to given and rebases any accumulated delta.
  1179. Args:
  1180. new_filters: Filters with new state to update local copy.
  1181. """
  1182. assert all(k in new_filters for k in self.filters)
  1183. for k in self.filters:
  1184. self.filters[k].sync(new_filters[k])
  1185. def get_filters(self, flush_after: bool = False) -> Dict:
  1186. """Returns a snapshot of filters.
  1187. Args:
  1188. flush_after: Clears the filter buffer state.
  1189. Returns:
  1190. Dict for serializable filters
  1191. """
  1192. return_filters = {}
  1193. for k, f in self.filters.items():
  1194. return_filters[k] = f.as_serializable()
  1195. if flush_after:
  1196. f.reset_buffer()
  1197. return return_filters
  1198. def get_state(self) -> dict:
  1199. filters = self.get_filters(flush_after=True)
  1200. policy_states = {}
  1201. for pid in self.policy_map.keys():
  1202. # If required by the user, only capture policies that are actually
  1203. # trainable. Otherwise, capture all policies (for saving to disk).
  1204. if (
  1205. not self.config.checkpoint_trainable_policies_only
  1206. or self.is_policy_to_train is None
  1207. or self.is_policy_to_train(pid)
  1208. ):
  1209. policy_states[pid] = self.policy_map[pid].get_state()
  1210. return {
  1211. # List all known policy IDs here for convenience. When an Algorithm gets
  1212. # restored from a checkpoint, it will not have access to the list of
  1213. # possible IDs as each policy is stored in its own sub-dir
  1214. # (see "policy_states").
  1215. "policy_ids": list(self.policy_map.keys()),
  1216. # Note that this field will not be stored in the algorithm checkpoint's
  1217. # state file, but each policy will get its own state file generated in
  1218. # a sub-dir within the algo's checkpoint dir.
  1219. "policy_states": policy_states,
  1220. # Also store current mapping fn and which policies to train.
  1221. "policy_mapping_fn": self.policy_mapping_fn,
  1222. "is_policy_to_train": self.is_policy_to_train,
  1223. # TODO: Filters will be replaced by connectors.
  1224. "filters": filters,
  1225. }
  1226. def set_state(self, state: dict) -> None:
  1227. # Backward compatibility (old checkpoints' states would have the local
  1228. # worker state as a bytes object, not a dict).
  1229. if isinstance(state, bytes):
  1230. state = pickle.loads(state)
  1231. # TODO: Once filters are handled by connectors, get rid of the "filters"
  1232. # key in `state` entirely (will be part of the policies then).
  1233. self.sync_filters(state["filters"])
  1234. # Support older checkpoint versions (< 1.0), in which the policy_map
  1235. # was stored under the "state" key, not "policy_states".
  1236. policy_states = (
  1237. state["policy_states"] if "policy_states" in state else state["state"]
  1238. )
  1239. for pid, policy_state in policy_states.items():
  1240. # If - for some reason - we have an invalid PolicyID in the state,
  1241. # this might be from an older checkpoint (pre v1.0). Just warn here.
  1242. validate_module_id(pid, error=False)
  1243. if pid not in self.policy_map:
  1244. spec = policy_state.get("policy_spec", None)
  1245. if spec is None:
  1246. logger.warning(
  1247. f"PolicyID '{pid}' was probably added on-the-fly (not"
  1248. " part of the static `multagent.policies` config) and"
  1249. " no PolicySpec objects found in the pickled policy "
  1250. f"state. Will not add `{pid}`, but ignore it for now."
  1251. )
  1252. else:
  1253. policy_spec = (
  1254. PolicySpec.deserialize(spec) if isinstance(spec, dict) else spec
  1255. )
  1256. self.add_policy(
  1257. policy_id=pid,
  1258. policy_cls=policy_spec.policy_class,
  1259. observation_space=policy_spec.observation_space,
  1260. action_space=policy_spec.action_space,
  1261. config=policy_spec.config,
  1262. )
  1263. if pid in self.policy_map:
  1264. self.policy_map[pid].set_state(policy_state)
  1265. # Also restore mapping fn and which policies to train.
  1266. if "policy_mapping_fn" in state:
  1267. self.set_policy_mapping_fn(state["policy_mapping_fn"])
  1268. if state.get("is_policy_to_train") is not None:
  1269. self.set_is_policy_to_train(state["is_policy_to_train"])
  1270. def get_weights(
  1271. self,
  1272. policies: Optional[Collection[PolicyID]] = None,
  1273. inference_only: bool = False,
  1274. ) -> Dict[PolicyID, ModelWeights]:
  1275. """Returns each policies' model weights of this worker.
  1276. Args:
  1277. policies: List of PolicyIDs to get the weights from.
  1278. Use None for all policies.
  1279. inference_only: This argument is only added for interface
  1280. consistency with the new api stack.
  1281. Returns:
  1282. Dict mapping PolicyIDs to ModelWeights.
  1283. .. testcode::
  1284. :skipif: True
  1285. from ray.rllib.evaluation.rollout_worker import RolloutWorker
  1286. # Create a RolloutWorker.
  1287. worker = ...
  1288. weights = worker.get_weights()
  1289. print(weights)
  1290. .. testoutput::
  1291. {"default_policy": {"layer1": array(...), "layer2": ...}}
  1292. """
  1293. if policies is None:
  1294. policies = list(self.policy_map.keys())
  1295. policies = force_list(policies)
  1296. return {
  1297. # Make sure to only iterate over keys() and not items(). Iterating over
  1298. # items will access policy_map elements even for pids that we do not need,
  1299. # i.e. those that are not in policies. Access to policy_map elements can
  1300. # cause disk access for policies that were offloaded to disk. Since these
  1301. # policies will be skipped in the for-loop accessing them is unnecessary,
  1302. # making subsequent disk access unnecessary.
  1303. pid: self.policy_map[pid].get_weights()
  1304. for pid in self.policy_map.keys()
  1305. if pid in policies
  1306. }
  1307. def set_weights(
  1308. self,
  1309. weights: Dict[PolicyID, ModelWeights],
  1310. global_vars: Optional[Dict] = None,
  1311. weights_seq_no: Optional[int] = None,
  1312. ) -> None:
  1313. """Sets each policies' model weights of this worker.
  1314. Args:
  1315. weights: Dict mapping PolicyIDs to the new weights to be used.
  1316. global_vars: An optional global vars dict to set this
  1317. worker to. If None, do not update the global_vars.
  1318. weights_seq_no: If needed, a sequence number for the weights version
  1319. can be passed into this method. If not None, will store this seq no
  1320. (in self.weights_seq_no) and in future calls - if the seq no did not
  1321. change wrt. the last call - will ignore the call to save on performance.
  1322. .. testcode::
  1323. :skipif: True
  1324. from ray.rllib.evaluation.rollout_worker import RolloutWorker
  1325. # Create a RolloutWorker.
  1326. worker = ...
  1327. weights = worker.get_weights()
  1328. # Set `global_vars` (timestep) as well.
  1329. worker.set_weights(weights, {"timestep": 42})
  1330. """
  1331. # Only update our weights, if no seq no given OR given seq no is different
  1332. # from ours.
  1333. if weights_seq_no is None or weights_seq_no != self.weights_seq_no:
  1334. # If per-policy weights are object refs, `ray.get()` them first.
  1335. if weights and isinstance(next(iter(weights.values())), ObjectRef):
  1336. actual_weights = ray.get(list(weights.values()))
  1337. weights = {
  1338. pid: actual_weights[i] for i, pid in enumerate(weights.keys())
  1339. }
  1340. for pid, w in weights.items():
  1341. if pid in self.policy_map:
  1342. self.policy_map[pid].set_weights(w)
  1343. elif log_once("set_weights_on_non_existent_policy"):
  1344. logger.warning(
  1345. "`RolloutWorker.set_weights()` used with weights from "
  1346. f"policyID={pid}, but this policy cannot be found on this "
  1347. f"worker! Skipping ..."
  1348. )
  1349. self.weights_seq_no = weights_seq_no
  1350. if global_vars:
  1351. self.set_global_vars(global_vars)
  1352. def get_global_vars(self) -> dict:
  1353. """Returns the current `self.global_vars` dict of this RolloutWorker.
  1354. Returns:
  1355. The current `self.global_vars` dict of this RolloutWorker.
  1356. .. testcode::
  1357. :skipif: True
  1358. from ray.rllib.evaluation.rollout_worker import RolloutWorker
  1359. # Create a RolloutWorker.
  1360. worker = ...
  1361. global_vars = worker.get_global_vars()
  1362. print(global_vars)
  1363. .. testoutput::
  1364. {"timestep": 424242}
  1365. """
  1366. return self.global_vars
  1367. def set_global_vars(
  1368. self,
  1369. global_vars: dict,
  1370. policy_ids: Optional[List[PolicyID]] = None,
  1371. ) -> None:
  1372. """Updates this worker's and all its policies' global vars.
  1373. Updates are done using the dict's update method.
  1374. Args:
  1375. global_vars: The global_vars dict to update the `self.global_vars` dict
  1376. from.
  1377. policy_ids: Optional list of Policy IDs to update. If None, will update all
  1378. policies on the to-be-updated workers.
  1379. .. testcode::
  1380. :skipif: True
  1381. worker = ...
  1382. global_vars = worker.set_global_vars(
  1383. ... {"timestep": 4242})
  1384. """
  1385. # Handle per-policy values.
  1386. global_vars_copy = global_vars.copy()
  1387. gradient_updates_per_policy = global_vars_copy.pop(
  1388. "num_grad_updates_per_policy", {}
  1389. )
  1390. self.global_vars["num_grad_updates_per_policy"].update(
  1391. gradient_updates_per_policy
  1392. )
  1393. # Only update explicitly provided policies or those that that are being
  1394. # trained, in order to avoid superfluous access of policies, which might have
  1395. # been offloaded to the object store.
  1396. # Important b/c global vars are constantly being updated.
  1397. for pid in policy_ids if policy_ids is not None else self.policy_map.keys():
  1398. if self.is_policy_to_train is None or self.is_policy_to_train(pid, None):
  1399. self.policy_map[pid].on_global_var_update(
  1400. dict(
  1401. global_vars_copy,
  1402. # If count is None, Policy won't update the counter.
  1403. **{"num_grad_updates": gradient_updates_per_policy.get(pid)},
  1404. )
  1405. )
  1406. # Update all other global vars.
  1407. self.global_vars.update(global_vars_copy)
  1408. @override(EnvRunner)
  1409. def stop(self) -> None:
  1410. """Releases all resources used by this RolloutWorker."""
  1411. # If we have an env -> Release its resources.
  1412. if self.env is not None:
  1413. self.async_env.stop()
  1414. # Close all policies' sessions (if tf static graph).
  1415. for policy in self.policy_map.cache.values():
  1416. sess = policy.get_session()
  1417. # Closes the tf session, if any.
  1418. if sess is not None:
  1419. sess.close()
  1420. def lock(self) -> None:
  1421. """Locks this RolloutWorker via its own threading.Lock."""
  1422. self._lock.acquire()
  1423. def unlock(self) -> None:
  1424. """Unlocks this RolloutWorker via its own threading.Lock."""
  1425. self._lock.release()
  1426. def setup_torch_data_parallel(
  1427. self, url: str, world_rank: int, world_size: int, backend: str
  1428. ) -> None:
  1429. """Join a torch process group for distributed SGD."""
  1430. logger.info(
  1431. "Joining process group, url={}, world_rank={}, "
  1432. "world_size={}, backend={}".format(url, world_rank, world_size, backend)
  1433. )
  1434. torch.distributed.init_process_group(
  1435. backend=backend, init_method=url, rank=world_rank, world_size=world_size
  1436. )
  1437. for pid, policy in self.policy_map.items():
  1438. if not isinstance(policy, (TorchPolicy, TorchPolicyV2)):
  1439. raise ValueError(
  1440. "This policy does not support torch distributed", policy
  1441. )
  1442. policy.distributed_world_size = world_size
  1443. def creation_args(self) -> dict:
  1444. """Returns the kwargs dict used to create this worker."""
  1445. return self._original_kwargs
  1446. def get_host(self) -> str:
  1447. """Returns the hostname of the process running this evaluator."""
  1448. return platform.node()
  1449. def get_node_ip(self) -> str:
  1450. """Returns the IP address of the node that this worker runs on."""
  1451. return ray.util.get_node_ip_address()
  1452. def find_free_port(self) -> int:
  1453. """Finds a free port on the node that this worker runs on."""
  1454. from ray._common.network_utils import find_free_port
  1455. return find_free_port(socket.AF_INET)
  1456. def _update_policy_map(
  1457. self,
  1458. *,
  1459. policy_dict: MultiAgentPolicyConfigDict,
  1460. policy: Optional[Policy] = None,
  1461. policy_states: Optional[Dict[PolicyID, PolicyState]] = None,
  1462. single_agent_rl_module_spec: Optional[RLModuleSpec] = None,
  1463. ) -> None:
  1464. """Updates the policy map (and other stuff) on this worker.
  1465. It performs the following:
  1466. 1. It updates the observation preprocessors and updates the policy_specs
  1467. with the postprocessed observation_spaces.
  1468. 2. It updates the policy_specs with the complete algorithm_config (merged
  1469. with the policy_spec's config).
  1470. 3. If needed it will update the self.multi_rl_module_spec on this worker
  1471. 3. It updates the policy map with the new policies
  1472. 4. It updates the filter dict
  1473. 5. It calls the on_create_policy() hook of the callbacks on the newly added
  1474. policies.
  1475. Args:
  1476. policy_dict: The policy dict to update the policy map with.
  1477. policy: The policy to update the policy map with.
  1478. policy_states: The policy states to update the policy map with.
  1479. single_agent_rl_module_spec: The RLModuleSpec to add to the
  1480. MultiRLModuleSpec. If None, the config's
  1481. `get_default_rl_module_spec` method's output will be used to create
  1482. the policy with.
  1483. """
  1484. # Update the input policy dict with the postprocessed observation spaces and
  1485. # merge configs. Also updates the preprocessor dict.
  1486. updated_policy_dict = self._get_complete_policy_specs_dict(policy_dict)
  1487. # Builds the self.policy_map dict
  1488. self._build_policy_map(
  1489. policy_dict=updated_policy_dict,
  1490. policy=policy,
  1491. policy_states=policy_states,
  1492. )
  1493. # Initialize the filter dict
  1494. self._update_filter_dict(updated_policy_dict)
  1495. # Call callback policy init hooks (only if the added policy did not exist
  1496. # before).
  1497. if policy is None:
  1498. self._call_callbacks_on_create_policy()
  1499. if self.worker_index == 0:
  1500. logger.info(f"Built policy map: {self.policy_map}")
  1501. logger.info(f"Built preprocessor map: {self.preprocessors}")
  1502. def _get_complete_policy_specs_dict(
  1503. self, policy_dict: MultiAgentPolicyConfigDict
  1504. ) -> MultiAgentPolicyConfigDict:
  1505. """Processes the policy dict and creates a new copy with the processed attrs.
  1506. This processes the observation_space and prepares them for passing to rl module
  1507. construction. It also merges the policy configs with the algorithm config.
  1508. During this processing, we will also construct the preprocessors dict.
  1509. """
  1510. from ray.rllib.algorithms.algorithm_config import AlgorithmConfig
  1511. updated_policy_dict = copy.deepcopy(policy_dict)
  1512. # If our preprocessors dict does not exist yet, create it here.
  1513. self.preprocessors = self.preprocessors or {}
  1514. # Loop through given policy-dict and add each entry to our map.
  1515. for name, policy_spec in sorted(updated_policy_dict.items()):
  1516. logger.debug("Creating policy for {}".format(name))
  1517. # Policy brings its own complete AlgorithmConfig -> Use it for this policy.
  1518. if isinstance(policy_spec.config, AlgorithmConfig):
  1519. merged_conf = policy_spec.config
  1520. else:
  1521. # Update the general config with the specific config
  1522. # for this particular policy.
  1523. merged_conf: "AlgorithmConfig" = self.config.copy(copy_frozen=False)
  1524. merged_conf.update_from_dict(policy_spec.config or {})
  1525. # Update num_workers and worker_index.
  1526. merged_conf.worker_index = self.worker_index
  1527. # Preprocessors.
  1528. obs_space = policy_spec.observation_space
  1529. # Initialize preprocessor for this policy to None.
  1530. self.preprocessors[name] = None
  1531. if self.preprocessing_enabled:
  1532. # Policies should deal with preprocessed (automatically flattened)
  1533. # observations if preprocessing is enabled.
  1534. preprocessor = ModelCatalog.get_preprocessor_for_space(
  1535. obs_space,
  1536. merged_conf.model,
  1537. include_multi_binary=False,
  1538. )
  1539. # Original observation space should be accessible at
  1540. # obs_space.original_space after this step.
  1541. if preprocessor is not None:
  1542. obs_space = preprocessor.observation_space
  1543. policy_spec.config = merged_conf
  1544. policy_spec.observation_space = obs_space
  1545. return updated_policy_dict
  1546. def _update_policy_dict_with_multi_rl_module(
  1547. self, policy_dict: MultiAgentPolicyConfigDict
  1548. ) -> MultiAgentPolicyConfigDict:
  1549. for name, policy_spec in policy_dict.items():
  1550. policy_spec.config["__multi_rl_module_spec"] = self.multi_rl_module_spec
  1551. return policy_dict
  1552. def _build_policy_map(
  1553. self,
  1554. *,
  1555. policy_dict: MultiAgentPolicyConfigDict,
  1556. policy: Optional[Policy] = None,
  1557. policy_states: Optional[Dict[PolicyID, PolicyState]] = None,
  1558. ) -> None:
  1559. """Adds the given policy_dict to `self.policy_map`.
  1560. Args:
  1561. policy_dict: The MultiAgentPolicyConfigDict to be added to this
  1562. worker's PolicyMap.
  1563. policy: If the policy to add already exists, user can provide it here.
  1564. policy_states: Optional dict from PolicyIDs to PolicyStates to
  1565. restore the states of the policies being built.
  1566. """
  1567. # If our policy_map does not exist yet, create it here.
  1568. self.policy_map = self.policy_map or PolicyMap(
  1569. capacity=self.config.policy_map_capacity,
  1570. policy_states_are_swappable=self.config.policy_states_are_swappable,
  1571. )
  1572. # Loop through given policy-dict and add each entry to our map.
  1573. for name, policy_spec in sorted(policy_dict.items()):
  1574. # Create the actual policy object.
  1575. if policy is None:
  1576. new_policy = create_policy_for_framework(
  1577. policy_id=name,
  1578. policy_class=get_tf_eager_cls_if_necessary(
  1579. policy_spec.policy_class, policy_spec.config
  1580. ),
  1581. merged_config=policy_spec.config,
  1582. observation_space=policy_spec.observation_space,
  1583. action_space=policy_spec.action_space,
  1584. worker_index=self.worker_index,
  1585. seed=self.seed,
  1586. )
  1587. else:
  1588. new_policy = policy
  1589. self.policy_map[name] = new_policy
  1590. restore_states = (policy_states or {}).get(name, None)
  1591. # Set the state of the newly created policy before syncing filters, etc.
  1592. if restore_states:
  1593. new_policy.set_state(restore_states)
  1594. def _update_filter_dict(self, policy_dict: MultiAgentPolicyConfigDict) -> None:
  1595. """Updates the filter dict for the given policy_dict."""
  1596. for name, policy_spec in sorted(policy_dict.items()):
  1597. new_policy = self.policy_map[name]
  1598. # Note(jungong) : We should only create new connectors for the
  1599. # policy iff we are creating a new policy from scratch. i.e,
  1600. # we should NOT create new connectors when we already have the
  1601. # policy object created before this function call or have the
  1602. # restoring states from the caller.
  1603. # Also note that we cannot just check the existence of connectors
  1604. # to decide whether we should create connectors because we may be
  1605. # restoring a policy that has 0 connectors configured.
  1606. if (
  1607. new_policy.agent_connectors is None
  1608. or new_policy.action_connectors is None
  1609. ):
  1610. # TODO(jungong) : revisit this. It will be nicer to create
  1611. # connectors as the last step of Policy.__init__().
  1612. create_connectors_for_policy(new_policy, policy_spec.config)
  1613. maybe_get_filters_for_syncing(self, name)
  1614. def _call_callbacks_on_create_policy(self):
  1615. """Calls the on_create_policy callback for each policy in the policy map."""
  1616. for name, policy in self.policy_map.items():
  1617. self.callbacks.on_create_policy(policy_id=name, policy=policy)
  1618. def _get_input_creator_from_config(self):
  1619. def valid_module(class_path):
  1620. if (
  1621. isinstance(class_path, str)
  1622. and not os.path.isfile(class_path)
  1623. and "." in class_path
  1624. ):
  1625. module_path, class_name = class_path.rsplit(".", 1)
  1626. try:
  1627. spec = importlib.util.find_spec(module_path)
  1628. if spec is not None:
  1629. return True
  1630. except (ModuleNotFoundError, ValueError):
  1631. print(
  1632. f"module {module_path} not found while trying to get "
  1633. f"input {class_path}"
  1634. )
  1635. return False
  1636. # A callable returning an InputReader object to use.
  1637. if isinstance(self.config.input_, FunctionType):
  1638. return self.config.input_
  1639. # Use RLlib's Sampler classes (SyncSampler).
  1640. elif self.config.input_ == "sampler":
  1641. return lambda ioctx: ioctx.default_sampler_input()
  1642. # Ray Dataset input -> Use `config.input_config` to construct DatasetReader.
  1643. elif self.config.input_ == "dataset":
  1644. assert self._ds_shards is not None
  1645. # Input dataset shards should have already been prepared.
  1646. # We just need to take the proper shard here.
  1647. return lambda ioctx: DatasetReader(
  1648. self._ds_shards[self.worker_index], ioctx
  1649. )
  1650. # Dict: Mix of different input methods with different ratios.
  1651. elif isinstance(self.config.input_, dict):
  1652. return lambda ioctx: ShuffledInput(
  1653. MixedInput(self.config.input_, ioctx), self.config.shuffle_buffer_size
  1654. )
  1655. # A pre-registered input descriptor (str).
  1656. elif isinstance(self.config.input_, str) and registry_contains_input(
  1657. self.config.input_
  1658. ):
  1659. return registry_get_input(self.config.input_)
  1660. # D4RL input.
  1661. elif "d4rl" in self.config.input_:
  1662. env_name = self.config.input_.split(".")[-1]
  1663. return lambda ioctx: D4RLReader(env_name, ioctx)
  1664. # Valid python module (class path) -> Create using `from_config`.
  1665. elif valid_module(self.config.input_):
  1666. return lambda ioctx: ShuffledInput(
  1667. from_config(self.config.input_, ioctx=ioctx)
  1668. )
  1669. # JSON file or list of JSON files -> Use JsonReader (shuffled).
  1670. else:
  1671. return lambda ioctx: ShuffledInput(
  1672. JsonReader(self.config.input_, ioctx), self.config.shuffle_buffer_size
  1673. )
  1674. def _get_output_creator_from_config(self):
  1675. if isinstance(self.config.output, FunctionType):
  1676. return self.config.output
  1677. elif self.config.output is None:
  1678. return lambda ioctx: NoopOutput()
  1679. elif self.config.output == "dataset":
  1680. return lambda ioctx: DatasetWriter(
  1681. ioctx, compress_columns=self.config.output_compress_columns
  1682. )
  1683. elif self.config.output == "logdir":
  1684. return lambda ioctx: JsonWriter(
  1685. ioctx.log_dir,
  1686. ioctx,
  1687. max_file_size=self.config.output_max_file_size,
  1688. compress_columns=self.config.output_compress_columns,
  1689. )
  1690. else:
  1691. return lambda ioctx: JsonWriter(
  1692. self.config.output,
  1693. ioctx,
  1694. max_file_size=self.config.output_max_file_size,
  1695. compress_columns=self.config.output_compress_columns,
  1696. )
  1697. def _get_make_sub_env_fn(
  1698. self, env_creator, env_context, validate_env, env_wrapper, seed
  1699. ):
  1700. def _make_sub_env_local(vector_index):
  1701. # Used to created additional environments during environment
  1702. # vectorization.
  1703. # Create the env context (config dict + meta-data) for
  1704. # this particular sub-env within the vectorized one.
  1705. env_ctx = env_context.copy_with_overrides(vector_index=vector_index)
  1706. # Create the sub-env.
  1707. env = env_creator(env_ctx)
  1708. # Custom validation function given by user.
  1709. if validate_env is not None:
  1710. validate_env(env, env_ctx)
  1711. # Use our wrapper, defined above.
  1712. env = env_wrapper(env)
  1713. # Make sure a deterministic random seed is set on
  1714. # all the sub-environments if specified.
  1715. _update_env_seed_if_necessary(
  1716. env, seed, env_context.worker_index, vector_index
  1717. )
  1718. return env
  1719. if not env_context.remote:
  1720. def _make_sub_env_remote(vector_index):
  1721. sub_env = _make_sub_env_local(vector_index)
  1722. self.callbacks.on_sub_environment_created(
  1723. worker=self,
  1724. sub_environment=sub_env,
  1725. env_context=env_context.copy_with_overrides(
  1726. worker_index=env_context.worker_index,
  1727. vector_index=vector_index,
  1728. remote=False,
  1729. ),
  1730. )
  1731. return sub_env
  1732. return _make_sub_env_remote
  1733. else:
  1734. return _make_sub_env_local