policy.py 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696
  1. import json
  2. import logging
  3. import os
  4. import platform
  5. from abc import ABCMeta, abstractmethod
  6. from typing import (
  7. Any,
  8. Callable,
  9. Collection,
  10. Dict,
  11. List,
  12. Optional,
  13. Tuple,
  14. Type,
  15. Union,
  16. )
  17. import gymnasium as gym
  18. import numpy as np
  19. import tree # pip install dm_tree
  20. from gymnasium.spaces import Box
  21. from packaging import version
  22. import ray
  23. import ray.cloudpickle as pickle
  24. from ray._common.deprecation import (
  25. DEPRECATED_VALUE,
  26. deprecation_warning,
  27. )
  28. from ray.actor import ActorHandle
  29. from ray.rllib.models.action_dist import ActionDistribution
  30. from ray.rllib.models.catalog import ModelCatalog
  31. from ray.rllib.models.modelv2 import ModelV2
  32. from ray.rllib.policy.sample_batch import SampleBatch
  33. from ray.rllib.policy.view_requirement import ViewRequirement
  34. from ray.rllib.utils.annotations import (
  35. OldAPIStack,
  36. OverrideToImplementCustomLogic,
  37. OverrideToImplementCustomLogic_CallToSuperRecommended,
  38. is_overridden,
  39. )
  40. from ray.rllib.utils.checkpoints import (
  41. CHECKPOINT_VERSION,
  42. get_checkpoint_info,
  43. try_import_msgpack,
  44. )
  45. from ray.rllib.utils.exploration.exploration import Exploration
  46. from ray.rllib.utils.framework import try_import_tf, try_import_torch
  47. from ray.rllib.utils.from_config import from_config
  48. from ray.rllib.utils.numpy import convert_to_numpy
  49. from ray.rllib.utils.serialization import (
  50. deserialize_type,
  51. space_from_dict,
  52. space_to_dict,
  53. )
  54. from ray.rllib.utils.spaces.space_utils import (
  55. get_base_struct_from_space,
  56. get_dummy_batch_for_space,
  57. unbatch,
  58. )
  59. from ray.rllib.utils.tensor_dtype import get_np_dtype
  60. from ray.rllib.utils.tf_utils import get_tf_eager_cls_if_necessary
  61. from ray.rllib.utils.typing import (
  62. AgentID,
  63. AlgorithmConfigDict,
  64. ModelGradients,
  65. ModelWeights,
  66. PolicyID,
  67. PolicyState,
  68. T,
  69. TensorStructType,
  70. TensorType,
  71. )
  72. from ray.tune import Checkpoint
  73. tf1, tf, tfv = try_import_tf()
  74. torch, _ = try_import_torch()
  75. logger = logging.getLogger(__name__)
  76. @OldAPIStack
  77. class PolicySpec:
  78. """A policy spec used in the "config.multiagent.policies" specification dict.
  79. As values (keys are the policy IDs (str)). E.g.:
  80. config:
  81. multiagent:
  82. policies: {
  83. "pol1": PolicySpec(None, Box, Discrete(2), {"lr": 0.0001}),
  84. "pol2": PolicySpec(config={"lr": 0.001}),
  85. }
  86. """
  87. def __init__(
  88. self, policy_class=None, observation_space=None, action_space=None, config=None
  89. ):
  90. # If None, use the Algorithm's default policy class stored under
  91. # `Algorithm._policy_class`.
  92. self.policy_class = policy_class
  93. # If None, use the env's observation space. If None and there is no Env
  94. # (e.g. offline RL), an error is thrown.
  95. self.observation_space = observation_space
  96. # If None, use the env's action space. If None and there is no Env
  97. # (e.g. offline RL), an error is thrown.
  98. self.action_space = action_space
  99. # Overrides defined keys in the main Algorithm config.
  100. # If None, use {}.
  101. self.config = config
  102. def __eq__(self, other: "PolicySpec"):
  103. return (
  104. self.policy_class == other.policy_class
  105. and self.observation_space == other.observation_space
  106. and self.action_space == other.action_space
  107. and self.config == other.config
  108. )
  109. def get_state(self) -> Dict[str, Any]:
  110. """Returns the state of a `PolicyDict` as a dict."""
  111. return (
  112. self.policy_class,
  113. self.observation_space,
  114. self.action_space,
  115. self.config,
  116. )
  117. @classmethod
  118. def from_state(cls, state: Dict[str, Any]) -> "PolicySpec":
  119. """Builds a `PolicySpec` from a state."""
  120. policy_spec = PolicySpec()
  121. policy_spec.__dict__.update(state)
  122. return policy_spec
  123. def serialize(self) -> Dict:
  124. from ray.rllib.algorithms.registry import get_policy_class_name
  125. # Try to figure out a durable name for this policy.
  126. cls = get_policy_class_name(self.policy_class)
  127. if cls is None:
  128. logger.warning(
  129. f"Can not figure out a durable policy name for {self.policy_class}. "
  130. f"You are probably trying to checkpoint a custom policy. "
  131. f"Raw policy class may cause problems when the checkpoint needs to "
  132. "be loaded in the future. To fix this, make sure you add your "
  133. "custom policy in rllib.algorithms.registry.POLICIES."
  134. )
  135. cls = self.policy_class
  136. return {
  137. "policy_class": cls,
  138. "observation_space": space_to_dict(self.observation_space),
  139. "action_space": space_to_dict(self.action_space),
  140. # TODO(jungong) : try making the config dict durable by maybe
  141. # getting rid of all the fields that are not JSON serializable.
  142. "config": self.config,
  143. }
  144. @classmethod
  145. def deserialize(cls, spec: Dict) -> "PolicySpec":
  146. if isinstance(spec["policy_class"], str):
  147. # Try to recover the actual policy class from durable name.
  148. from ray.rllib.algorithms.registry import get_policy_class
  149. policy_class = get_policy_class(spec["policy_class"])
  150. elif isinstance(spec["policy_class"], type):
  151. # Policy spec is already a class type. Simply use it.
  152. policy_class = spec["policy_class"]
  153. else:
  154. raise AttributeError(f"Unknown policy class spec {spec['policy_class']}")
  155. return cls(
  156. policy_class=policy_class,
  157. observation_space=space_from_dict(spec["observation_space"]),
  158. action_space=space_from_dict(spec["action_space"]),
  159. config=spec["config"],
  160. )
  161. @OldAPIStack
  162. class Policy(metaclass=ABCMeta):
  163. """RLlib's base class for all Policy implementations.
  164. Policy is the abstract superclass for all DL-framework specific sub-classes
  165. (e.g. TFPolicy or TorchPolicy). It exposes APIs to
  166. 1. Compute actions from observation (and possibly other) inputs.
  167. 2. Manage the Policy's NN model(s), like exporting and loading their weights.
  168. 3. Postprocess a given trajectory from the environment or other input via the
  169. `postprocess_trajectory` method.
  170. 4. Compute losses from a train batch.
  171. 5. Perform updates from a train batch on the NN-models (this normally includes loss
  172. calculations) either:
  173. a. in one monolithic step (`learn_on_batch`)
  174. b. via batch pre-loading, then n steps of actual loss computations and updates
  175. (`load_batch_into_buffer` + `learn_on_loaded_batch`).
  176. """
  177. def __init__(
  178. self,
  179. observation_space: gym.Space,
  180. action_space: gym.Space,
  181. config: AlgorithmConfigDict,
  182. ):
  183. """Initializes a Policy instance.
  184. Args:
  185. observation_space: Observation space of the policy.
  186. action_space: Action space of the policy.
  187. config: A complete Algorithm/Policy config dict. For the default
  188. config keys and values, see rllib/algorithm/algorithm.py.
  189. """
  190. self.observation_space: gym.Space = observation_space
  191. self.action_space: gym.Space = action_space
  192. # the policy id in the global context.
  193. self.__policy_id = config.get("__policy_id")
  194. # The base struct of the observation/action spaces.
  195. # E.g. action-space = gym.spaces.Dict({"a": Discrete(2)}) ->
  196. # action_space_struct = {"a": Discrete(2)}
  197. self.observation_space_struct = get_base_struct_from_space(observation_space)
  198. self.action_space_struct = get_base_struct_from_space(action_space)
  199. self.config: AlgorithmConfigDict = config
  200. self.framework = self.config.get("framework")
  201. # Create the callbacks object to use for handling custom callbacks.
  202. from ray.rllib.callbacks.callbacks import RLlibCallback
  203. callbacks = self.config.get("callbacks")
  204. if isinstance(callbacks, RLlibCallback):
  205. self.callbacks = callbacks()
  206. elif isinstance(callbacks, (str, type)):
  207. try:
  208. self.callbacks: "RLlibCallback" = deserialize_type(
  209. self.config.get("callbacks")
  210. )()
  211. except Exception:
  212. pass # TEST
  213. else:
  214. self.callbacks: "RLlibCallback" = RLlibCallback()
  215. # The global timestep, broadcast down from time to time from the
  216. # local worker to all remote workers.
  217. self.global_timestep: int = 0
  218. # The number of gradient updates this policy has undergone.
  219. self.num_grad_updates: int = 0
  220. # The action distribution class to use for action sampling, if any.
  221. # Child classes may set this.
  222. self.dist_class: Optional[Type] = None
  223. # Initialize view requirements.
  224. self.init_view_requirements()
  225. # Whether the Model's initial state (method) has been added
  226. # automatically based on the given view requirements of the model.
  227. self._model_init_state_automatically_added = False
  228. # Connectors.
  229. self.agent_connectors = None
  230. self.action_connectors = None
  231. @staticmethod
  232. def from_checkpoint(
  233. checkpoint: Union[str, Checkpoint],
  234. policy_ids: Optional[Collection[PolicyID]] = None,
  235. ) -> Union["Policy", Dict[PolicyID, "Policy"]]:
  236. """Creates new Policy instance(s) from a given Policy or Algorithm checkpoint.
  237. Note: This method must remain backward compatible from 2.1.0 on, wrt.
  238. checkpoints created with Ray 2.0.0 or later.
  239. Args:
  240. checkpoint: The path (str) to a Policy or Algorithm checkpoint directory
  241. or an AIR Checkpoint (Policy or Algorithm) instance to restore
  242. from.
  243. If checkpoint is a Policy checkpoint, `policy_ids` must be None
  244. and only the Policy in that checkpoint is restored and returned.
  245. If checkpoint is an Algorithm checkpoint and `policy_ids` is None,
  246. will return a list of all Policy objects found in
  247. the checkpoint, otherwise a list of those policies in `policy_ids`.
  248. policy_ids: List of policy IDs to extract from a given Algorithm checkpoint.
  249. If None and an Algorithm checkpoint is provided, will restore all
  250. policies found in that checkpoint. If a Policy checkpoint is given,
  251. this arg must be None.
  252. Returns:
  253. An instantiated Policy, if `checkpoint` is a Policy checkpoint. A dict
  254. mapping PolicyID to Policies, if `checkpoint` is an Algorithm checkpoint.
  255. In the latter case, returns all policies within the Algorithm if
  256. `policy_ids` is None, else a dict of only those Policies that are in
  257. `policy_ids`.
  258. """
  259. checkpoint_info = get_checkpoint_info(checkpoint)
  260. # Algorithm checkpoint: Extract one or more policies from it and return them
  261. # in a dict (mapping PolicyID to Policy instances).
  262. if checkpoint_info["type"] == "Algorithm":
  263. from ray.rllib.algorithms.algorithm import Algorithm
  264. policies = {}
  265. # Old Algorithm checkpoints: State must be completely retrieved from:
  266. # algo state file -> worker -> "state".
  267. if checkpoint_info["checkpoint_version"] < version.Version("1.0"):
  268. with open(checkpoint_info["state_file"], "rb") as f:
  269. state = pickle.load(f)
  270. # In older checkpoint versions, the policy states are stored under
  271. # "state" within the worker state (which is pickled in itself).
  272. worker_state = pickle.loads(state["worker"])
  273. policy_states = worker_state["state"]
  274. for pid, policy_state in policy_states.items():
  275. # Get spec and config, merge config with
  276. serialized_policy_spec = worker_state["policy_specs"][pid]
  277. policy_config = Algorithm.merge_algorithm_configs(
  278. worker_state["policy_config"], serialized_policy_spec["config"]
  279. )
  280. serialized_policy_spec.update({"config": policy_config})
  281. policy_state.update({"policy_spec": serialized_policy_spec})
  282. policies[pid] = Policy.from_state(policy_state)
  283. # Newer versions: Get policy states from "policies/" sub-dirs.
  284. elif checkpoint_info["policy_ids"] is not None:
  285. for policy_id in checkpoint_info["policy_ids"]:
  286. if policy_ids is None or policy_id in policy_ids:
  287. policy_checkpoint_info = get_checkpoint_info(
  288. os.path.join(
  289. checkpoint_info["checkpoint_dir"],
  290. "policies",
  291. policy_id,
  292. )
  293. )
  294. assert policy_checkpoint_info["type"] == "Policy"
  295. with open(policy_checkpoint_info["state_file"], "rb") as f:
  296. policy_state = pickle.load(f)
  297. policies[policy_id] = Policy.from_state(policy_state)
  298. return policies
  299. # Policy checkpoint: Return a single Policy instance.
  300. else:
  301. msgpack = None
  302. if checkpoint_info.get("format") == "msgpack":
  303. msgpack = try_import_msgpack(error=True)
  304. with open(checkpoint_info["state_file"], "rb") as f:
  305. if msgpack is not None:
  306. state = msgpack.load(f)
  307. else:
  308. state = pickle.load(f)
  309. return Policy.from_state(state)
  310. @staticmethod
  311. def from_state(state: PolicyState) -> "Policy":
  312. """Recovers a Policy from a state object.
  313. The `state` of an instantiated Policy can be retrieved by calling its
  314. `get_state` method. This only works for the V2 Policy classes (EagerTFPolicyV2,
  315. SynamicTFPolicyV2, and TorchPolicyV2). It contains all information necessary
  316. to create the Policy. No access to the original code (e.g. configs, knowledge of
  317. the policy's class, etc..) is needed.
  318. Args:
  319. state: The state to recover a new Policy instance from.
  320. Returns:
  321. A new Policy instance.
  322. """
  323. serialized_pol_spec: Optional[dict] = state.get("policy_spec")
  324. if serialized_pol_spec is None:
  325. raise ValueError(
  326. "No `policy_spec` key was found in given `state`! "
  327. "Cannot create new Policy."
  328. )
  329. pol_spec = PolicySpec.deserialize(serialized_pol_spec)
  330. actual_class = get_tf_eager_cls_if_necessary(
  331. pol_spec.policy_class,
  332. pol_spec.config,
  333. )
  334. if pol_spec.config["framework"] == "tf":
  335. from ray.rllib.policy.tf_policy import TFPolicy
  336. return TFPolicy._tf1_from_state_helper(state)
  337. # Create the new policy.
  338. new_policy = actual_class(
  339. # Note(jungong) : we are intentionally not using keyward arguments here
  340. # because some policies name the observation space parameter obs_space,
  341. # and some others name it observation_space.
  342. pol_spec.observation_space,
  343. pol_spec.action_space,
  344. pol_spec.config,
  345. )
  346. # Set the new policy's state (weights, optimizer vars, exploration state,
  347. # etc..).
  348. new_policy.set_state(state)
  349. # Return the new policy.
  350. return new_policy
  351. def init_view_requirements(self):
  352. """Maximal view requirements dict for `learn_on_batch()` and
  353. `compute_actions` calls.
  354. Specific policies can override this function to provide custom
  355. list of view requirements.
  356. """
  357. # Maximal view requirements dict for `learn_on_batch()` and
  358. # `compute_actions` calls.
  359. # View requirements will be automatically filtered out later based
  360. # on the postprocessing and loss functions to ensure optimal data
  361. # collection and transfer performance.
  362. view_reqs = self._get_default_view_requirements()
  363. if not hasattr(self, "view_requirements"):
  364. self.view_requirements = view_reqs
  365. else:
  366. for k, v in view_reqs.items():
  367. if k not in self.view_requirements:
  368. self.view_requirements[k] = v
  369. def get_connector_metrics(self) -> Dict:
  370. """Get metrics on timing from connectors."""
  371. return {
  372. "agent_connectors": {
  373. name + "_ms": 1000 * timer.mean
  374. for name, timer in self.agent_connectors.timers.items()
  375. },
  376. "action_connectors": {
  377. name + "_ms": 1000 * timer.mean
  378. for name, timer in self.agent_connectors.timers.items()
  379. },
  380. }
  381. def reset_connectors(self, env_id) -> None:
  382. """Reset action- and agent-connectors for this policy."""
  383. self.agent_connectors.reset(env_id=env_id)
  384. self.action_connectors.reset(env_id=env_id)
  385. def compute_single_action(
  386. self,
  387. obs: Optional[TensorStructType] = None,
  388. state: Optional[List[TensorType]] = None,
  389. *,
  390. prev_action: Optional[TensorStructType] = None,
  391. prev_reward: Optional[TensorStructType] = None,
  392. info: dict = None,
  393. input_dict: Optional[SampleBatch] = None,
  394. episode=None,
  395. explore: Optional[bool] = None,
  396. timestep: Optional[int] = None,
  397. # Kwars placeholder for future compatibility.
  398. **kwargs,
  399. ) -> Tuple[TensorStructType, List[TensorType], Dict[str, TensorType]]:
  400. """Computes and returns a single (B=1) action value.
  401. Takes an input dict (usually a SampleBatch) as its main data input.
  402. This allows for using this method in case a more complex input pattern
  403. (view requirements) is needed, for example when the Model requires the
  404. last n observations, the last m actions/rewards, or a combination
  405. of any of these.
  406. Alternatively, in case no complex inputs are required, takes a single
  407. `obs` values (and possibly single state values, prev-action/reward
  408. values, etc..).
  409. Args:
  410. obs: Single observation.
  411. state: List of RNN state inputs, if any.
  412. prev_action: Previous action value, if any.
  413. prev_reward: Previous reward, if any.
  414. info: Info object, if any.
  415. input_dict: A SampleBatch or input dict containing the
  416. single (unbatched) Tensors to compute actions. If given, it'll
  417. be used instead of `obs`, `state`, `prev_action|reward`, and
  418. `info`.
  419. episode: This provides access to all of the internal episode state,
  420. which may be useful for model-based or multi-agent algorithms.
  421. explore: Whether to pick an exploitation or
  422. exploration action
  423. (default: None -> use self.config["explore"]).
  424. timestep: The current (sampling) time step.
  425. Keyword Args:
  426. kwargs: Forward compatibility placeholder.
  427. Returns:
  428. Tuple consisting of the action, the list of RNN state outputs (if
  429. any), and a dictionary of extra features (if any).
  430. """
  431. # Build the input-dict used for the call to
  432. # `self.compute_actions_from_input_dict()`.
  433. if input_dict is None:
  434. input_dict = {SampleBatch.OBS: obs}
  435. if state is not None:
  436. for i, s in enumerate(state):
  437. input_dict[f"state_in_{i}"] = s
  438. if prev_action is not None:
  439. input_dict[SampleBatch.PREV_ACTIONS] = prev_action
  440. if prev_reward is not None:
  441. input_dict[SampleBatch.PREV_REWARDS] = prev_reward
  442. if info is not None:
  443. input_dict[SampleBatch.INFOS] = info
  444. # Batch all data in input dict.
  445. input_dict = tree.map_structure_with_path(
  446. lambda p, s: (
  447. s
  448. if p == "seq_lens"
  449. else s.unsqueeze(0)
  450. if torch and isinstance(s, torch.Tensor)
  451. else np.expand_dims(s, 0)
  452. ),
  453. input_dict,
  454. )
  455. episodes = None
  456. if episode is not None:
  457. episodes = [episode]
  458. out = self.compute_actions_from_input_dict(
  459. input_dict=SampleBatch(input_dict),
  460. episodes=episodes,
  461. explore=explore,
  462. timestep=timestep,
  463. )
  464. # Some policies don't return a tuple, but always just a single action.
  465. # E.g. ES and ARS.
  466. if not isinstance(out, tuple):
  467. single_action = out
  468. state_out = []
  469. info = {}
  470. # Normal case: Policy should return (action, state, info) tuple.
  471. else:
  472. batched_action, state_out, info = out
  473. single_action = unbatch(batched_action)
  474. assert len(single_action) == 1
  475. single_action = single_action[0]
  476. # Return action, internal state(s), infos.
  477. return (
  478. single_action,
  479. tree.map_structure(lambda x: x[0], state_out),
  480. tree.map_structure(lambda x: x[0], info),
  481. )
  482. def compute_actions_from_input_dict(
  483. self,
  484. input_dict: Union[SampleBatch, Dict[str, TensorStructType]],
  485. explore: Optional[bool] = None,
  486. timestep: Optional[int] = None,
  487. episodes=None,
  488. **kwargs,
  489. ) -> Tuple[TensorType, List[TensorType], Dict[str, TensorType]]:
  490. """Computes actions from collected samples (across multiple-agents).
  491. Takes an input dict (usually a SampleBatch) as its main data input.
  492. This allows for using this method in case a more complex input pattern
  493. (view requirements) is needed, for example when the Model requires the
  494. last n observations, the last m actions/rewards, or a combination
  495. of any of these.
  496. Args:
  497. input_dict: A SampleBatch or input dict containing the Tensors
  498. to compute actions. `input_dict` already abides to the
  499. Policy's as well as the Model's view requirements and can
  500. thus be passed to the Model as-is.
  501. explore: Whether to pick an exploitation or exploration
  502. action (default: None -> use self.config["explore"]).
  503. timestep: The current (sampling) time step.
  504. episodes: This provides access to all of the internal episodes'
  505. state, which may be useful for model-based or multi-agent
  506. algorithms.
  507. Keyword Args:
  508. kwargs: Forward compatibility placeholder.
  509. Returns:
  510. actions: Batch of output actions, with shape like
  511. [BATCH_SIZE, ACTION_SHAPE].
  512. state_outs: List of RNN state output
  513. batches, if any, each with shape [BATCH_SIZE, STATE_SIZE].
  514. info: Dictionary of extra feature batches, if any, with shape like
  515. {"f1": [BATCH_SIZE, ...], "f2": [BATCH_SIZE, ...]}.
  516. """
  517. # Default implementation just passes obs, prev-a/r, and states on to
  518. # `self.compute_actions()`.
  519. state_batches = [s for k, s in input_dict.items() if k.startswith("state_in")]
  520. return self.compute_actions(
  521. input_dict[SampleBatch.OBS],
  522. state_batches,
  523. prev_action_batch=input_dict.get(SampleBatch.PREV_ACTIONS),
  524. prev_reward_batch=input_dict.get(SampleBatch.PREV_REWARDS),
  525. info_batch=input_dict.get(SampleBatch.INFOS),
  526. explore=explore,
  527. timestep=timestep,
  528. episodes=episodes,
  529. **kwargs,
  530. )
  531. @abstractmethod
  532. def compute_actions(
  533. self,
  534. obs_batch: Union[List[TensorStructType], TensorStructType],
  535. state_batches: Optional[List[TensorType]] = None,
  536. prev_action_batch: Union[List[TensorStructType], TensorStructType] = None,
  537. prev_reward_batch: Union[List[TensorStructType], TensorStructType] = None,
  538. info_batch: Optional[Dict[str, list]] = None,
  539. episodes: Optional[List] = None,
  540. explore: Optional[bool] = None,
  541. timestep: Optional[int] = None,
  542. **kwargs,
  543. ) -> Tuple[TensorType, List[TensorType], Dict[str, TensorType]]:
  544. """Computes actions for the current policy.
  545. Args:
  546. obs_batch: Batch of observations.
  547. state_batches: List of RNN state input batches, if any.
  548. prev_action_batch: Batch of previous action values.
  549. prev_reward_batch: Batch of previous rewards.
  550. info_batch: Batch of info objects.
  551. episodes: List of Episode objects, one for each obs in
  552. obs_batch. This provides access to all of the internal
  553. episode state, which may be useful for model-based or
  554. multi-agent algorithms.
  555. explore: Whether to pick an exploitation or exploration action.
  556. Set to None (default) for using the value of
  557. `self.config["explore"]`.
  558. timestep: The current (sampling) time step.
  559. Keyword Args:
  560. kwargs: Forward compatibility placeholder
  561. Returns:
  562. actions: Batch of output actions, with shape like
  563. [BATCH_SIZE, ACTION_SHAPE].
  564. state_outs (List[TensorType]): List of RNN state output
  565. batches, if any, each with shape [BATCH_SIZE, STATE_SIZE].
  566. info (List[dict]): Dictionary of extra feature batches, if any,
  567. with shape like
  568. {"f1": [BATCH_SIZE, ...], "f2": [BATCH_SIZE, ...]}.
  569. """
  570. raise NotImplementedError
  571. def compute_log_likelihoods(
  572. self,
  573. actions: Union[List[TensorType], TensorType],
  574. obs_batch: Union[List[TensorType], TensorType],
  575. state_batches: Optional[List[TensorType]] = None,
  576. prev_action_batch: Optional[Union[List[TensorType], TensorType]] = None,
  577. prev_reward_batch: Optional[Union[List[TensorType], TensorType]] = None,
  578. actions_normalized: bool = True,
  579. in_training: bool = True,
  580. ) -> TensorType:
  581. """Computes the log-prob/likelihood for a given action and observation.
  582. The log-likelihood is calculated using this Policy's action
  583. distribution class (self.dist_class).
  584. Args:
  585. actions: Batch of actions, for which to retrieve the
  586. log-probs/likelihoods (given all other inputs: obs,
  587. states, ..).
  588. obs_batch: Batch of observations.
  589. state_batches: List of RNN state input batches, if any.
  590. prev_action_batch: Batch of previous action values.
  591. prev_reward_batch: Batch of previous rewards.
  592. actions_normalized: Is the given `actions` already normalized
  593. (between -1.0 and 1.0) or not? If not and
  594. `normalize_actions=True`, we need to normalize the given
  595. actions first, before calculating log likelihoods.
  596. in_training: Whether to use the forward_train() or forward_exploration() of
  597. the underlying RLModule.
  598. Returns:
  599. Batch of log probs/likelihoods, with shape: [BATCH_SIZE].
  600. """
  601. raise NotImplementedError
  602. @OverrideToImplementCustomLogic_CallToSuperRecommended
  603. def postprocess_trajectory(
  604. self,
  605. sample_batch: SampleBatch,
  606. other_agent_batches: Optional[
  607. Dict[AgentID, Tuple["Policy", SampleBatch]]
  608. ] = None,
  609. episode=None,
  610. ) -> SampleBatch:
  611. """Implements algorithm-specific trajectory postprocessing.
  612. This will be called on each trajectory fragment computed during policy
  613. evaluation. Each fragment is guaranteed to be only from one episode.
  614. The given fragment may or may not contain the end of this episode,
  615. depending on the `batch_mode=truncate_episodes|complete_episodes`,
  616. `rollout_fragment_length`, and other settings.
  617. Args:
  618. sample_batch: batch of experiences for the policy,
  619. which will contain at most one episode trajectory.
  620. other_agent_batches: In a multi-agent env, this contains a
  621. mapping of agent ids to (policy, agent_batch) tuples
  622. containing the policy and experiences of the other agents.
  623. episode: An optional multi-agent episode object to provide
  624. access to all of the internal episode state, which may
  625. be useful for model-based or multi-agent algorithms.
  626. Returns:
  627. The postprocessed sample batch.
  628. """
  629. # The default implementation just returns the same, unaltered batch.
  630. return sample_batch
  631. @OverrideToImplementCustomLogic
  632. def loss(
  633. self, model: ModelV2, dist_class: ActionDistribution, train_batch: SampleBatch
  634. ) -> Union[TensorType, List[TensorType]]:
  635. """Loss function for this Policy.
  636. Override this method in order to implement custom loss computations.
  637. Args:
  638. model: The model to calculate the loss(es).
  639. dist_class: The action distribution class to sample actions
  640. from the model's outputs.
  641. train_batch: The input batch on which to calculate the loss.
  642. Returns:
  643. Either a single loss tensor or a list of loss tensors.
  644. """
  645. raise NotImplementedError
  646. def learn_on_batch(self, samples: SampleBatch) -> Dict[str, TensorType]:
  647. """Perform one learning update, given `samples`.
  648. Either this method or the combination of `compute_gradients` and
  649. `apply_gradients` must be implemented by subclasses.
  650. Args:
  651. samples: The SampleBatch object to learn from.
  652. Returns:
  653. Dictionary of extra metadata from `compute_gradients()`.
  654. .. testcode::
  655. :skipif: True
  656. policy, sample_batch = ...
  657. policy.learn_on_batch(sample_batch)
  658. """
  659. # The default implementation is simply a fused `compute_gradients` plus
  660. # `apply_gradients` call.
  661. grads, grad_info = self.compute_gradients(samples)
  662. self.apply_gradients(grads)
  663. return grad_info
  664. def learn_on_batch_from_replay_buffer(
  665. self, replay_actor: ActorHandle, policy_id: PolicyID
  666. ) -> Dict[str, TensorType]:
  667. """Samples a batch from given replay actor and performs an update.
  668. Args:
  669. replay_actor: The replay buffer actor to sample from.
  670. policy_id: The ID of this policy.
  671. Returns:
  672. Dictionary of extra metadata from `compute_gradients()`.
  673. """
  674. # Sample a batch from the given replay actor.
  675. # Note that for better performance (less data sent through the
  676. # network), this policy should be co-located on the same node
  677. # as `replay_actor`. Such a co-location step is usually done during
  678. # the Algorithm's `setup()` phase.
  679. batch = ray.get(replay_actor.replay.remote(policy_id=policy_id))
  680. if batch is None:
  681. return {}
  682. # Send to own learn_on_batch method for updating.
  683. # TODO: hack w/ `hasattr`
  684. if hasattr(self, "devices") and len(self.devices) > 1:
  685. self.load_batch_into_buffer(batch, buffer_index=0)
  686. return self.learn_on_loaded_batch(offset=0, buffer_index=0)
  687. else:
  688. return self.learn_on_batch(batch)
  689. def load_batch_into_buffer(self, batch: SampleBatch, buffer_index: int = 0) -> int:
  690. """Bulk-loads the given SampleBatch into the devices' memories.
  691. The data is split equally across all the Policy's devices.
  692. If the data is not evenly divisible by the batch size, excess data
  693. should be discarded.
  694. Args:
  695. batch: The SampleBatch to load.
  696. buffer_index: The index of the buffer (a MultiGPUTowerStack) to use
  697. on the devices. The number of buffers on each device depends
  698. on the value of the `num_multi_gpu_tower_stacks` config key.
  699. Returns:
  700. The number of tuples loaded per device.
  701. """
  702. raise NotImplementedError
  703. def get_num_samples_loaded_into_buffer(self, buffer_index: int = 0) -> int:
  704. """Returns the number of currently loaded samples in the given buffer.
  705. Args:
  706. buffer_index: The index of the buffer (a MultiGPUTowerStack)
  707. to use on the devices. The number of buffers on each device
  708. depends on the value of the `num_multi_gpu_tower_stacks` config
  709. key.
  710. Returns:
  711. The number of tuples loaded per device.
  712. """
  713. raise NotImplementedError
  714. def learn_on_loaded_batch(self, offset: int = 0, buffer_index: int = 0):
  715. """Runs a single step of SGD on an already loaded data in a buffer.
  716. Runs an SGD step over a slice of the pre-loaded batch, offset by
  717. the `offset` argument (useful for performing n minibatch SGD
  718. updates repeatedly on the same, already pre-loaded data).
  719. Updates the model weights based on the averaged per-device gradients.
  720. Args:
  721. offset: Offset into the preloaded data. Used for pre-loading
  722. a train-batch once to a device, then iterating over
  723. (subsampling through) this batch n times doing minibatch SGD.
  724. buffer_index: The index of the buffer (a MultiGPUTowerStack)
  725. to take the already pre-loaded data from. The number of buffers
  726. on each device depends on the value of the
  727. `num_multi_gpu_tower_stacks` config key.
  728. Returns:
  729. The outputs of extra_ops evaluated over the batch.
  730. """
  731. raise NotImplementedError
  732. def compute_gradients(
  733. self, postprocessed_batch: SampleBatch
  734. ) -> Tuple[ModelGradients, Dict[str, TensorType]]:
  735. """Computes gradients given a batch of experiences.
  736. Either this in combination with `apply_gradients()` or
  737. `learn_on_batch()` must be implemented by subclasses.
  738. Args:
  739. postprocessed_batch: The SampleBatch object to use
  740. for calculating gradients.
  741. Returns:
  742. grads: List of gradient output values.
  743. grad_info: Extra policy-specific info values.
  744. """
  745. raise NotImplementedError
  746. def apply_gradients(self, gradients: ModelGradients) -> None:
  747. """Applies the (previously) computed gradients.
  748. Either this in combination with `compute_gradients()` or
  749. `learn_on_batch()` must be implemented by subclasses.
  750. Args:
  751. gradients: The already calculated gradients to apply to this
  752. Policy.
  753. """
  754. raise NotImplementedError
  755. def get_weights(self) -> ModelWeights:
  756. """Returns model weights.
  757. Note: The return value of this method will reside under the "weights"
  758. key in the return value of Policy.get_state(). Model weights are only
  759. one part of a Policy's state. Other state information contains:
  760. optimizer variables, exploration state, and global state vars such as
  761. the sampling timestep.
  762. Returns:
  763. Serializable copy or view of model weights.
  764. """
  765. raise NotImplementedError
  766. def set_weights(self, weights: ModelWeights) -> None:
  767. """Sets this Policy's model's weights.
  768. Note: Model weights are only one part of a Policy's state. Other
  769. state information contains: optimizer variables, exploration state,
  770. and global state vars such as the sampling timestep.
  771. Args:
  772. weights: Serializable copy or view of model weights.
  773. """
  774. raise NotImplementedError
  775. def get_exploration_state(self) -> Dict[str, TensorType]:
  776. """Returns the state of this Policy's exploration component.
  777. Returns:
  778. Serializable information on the `self.exploration` object.
  779. """
  780. return self.exploration.get_state()
  781. def is_recurrent(self) -> bool:
  782. """Whether this Policy holds a recurrent Model.
  783. Returns:
  784. True if this Policy has an RNN-based Model.
  785. """
  786. return False
  787. def num_state_tensors(self) -> int:
  788. """The number of internal states needed by the RNN-Model of the Policy.
  789. Returns:
  790. int: The number of RNN internal states kept by this Policy's Model.
  791. """
  792. return 0
  793. def get_initial_state(self) -> List[TensorType]:
  794. """Returns initial RNN state for the current policy.
  795. Returns:
  796. List[TensorType]: Initial RNN state for the current policy.
  797. """
  798. return []
  799. @OverrideToImplementCustomLogic_CallToSuperRecommended
  800. def get_state(self) -> PolicyState:
  801. """Returns the entire current state of this Policy.
  802. Note: Not to be confused with an RNN model's internal state.
  803. State includes the Model(s)' weights, optimizer weights,
  804. the exploration component's state, as well as global variables, such
  805. as sampling timesteps.
  806. Note that the state may contain references to the original variables.
  807. This means that you may need to deepcopy() the state before mutating it.
  808. Returns:
  809. Serialized local state.
  810. """
  811. state = {
  812. # All the policy's weights.
  813. "weights": self.get_weights(),
  814. # The current global timestep.
  815. "global_timestep": self.global_timestep,
  816. # The current num_grad_updates counter.
  817. "num_grad_updates": self.num_grad_updates,
  818. }
  819. # Add this Policy's spec so it can be retreived w/o access to the original
  820. # code.
  821. policy_spec = PolicySpec(
  822. policy_class=type(self),
  823. observation_space=self.observation_space,
  824. action_space=self.action_space,
  825. config=self.config,
  826. )
  827. state["policy_spec"] = policy_spec.serialize()
  828. # Checkpoint connectors state as well if enabled.
  829. connector_configs = {}
  830. if self.agent_connectors:
  831. connector_configs["agent"] = self.agent_connectors.to_state()
  832. if self.action_connectors:
  833. connector_configs["action"] = self.action_connectors.to_state()
  834. state["connector_configs"] = connector_configs
  835. return state
  836. def restore_connectors(self, state: PolicyState):
  837. """Restore agent and action connectors if configs available.
  838. Args:
  839. state: The new state to set this policy to. Can be
  840. obtained by calling `self.get_state()`.
  841. """
  842. # To avoid a circular dependency problem cause by SampleBatch.
  843. from ray.rllib.connectors.util import restore_connectors_for_policy
  844. connector_configs = state.get("connector_configs", {})
  845. if "agent" in connector_configs:
  846. self.agent_connectors = restore_connectors_for_policy(
  847. self, connector_configs["agent"]
  848. )
  849. logger.debug("restoring agent connectors:")
  850. logger.debug(self.agent_connectors.__str__(indentation=4))
  851. if "action" in connector_configs:
  852. self.action_connectors = restore_connectors_for_policy(
  853. self, connector_configs["action"]
  854. )
  855. logger.debug("restoring action connectors:")
  856. logger.debug(self.action_connectors.__str__(indentation=4))
  857. @OverrideToImplementCustomLogic_CallToSuperRecommended
  858. def set_state(self, state: PolicyState) -> None:
  859. """Restores the entire current state of this Policy from `state`.
  860. Args:
  861. state: The new state to set this policy to. Can be
  862. obtained by calling `self.get_state()`.
  863. """
  864. if "policy_spec" in state:
  865. policy_spec = PolicySpec.deserialize(state["policy_spec"])
  866. # Assert spaces remained the same.
  867. if (
  868. policy_spec.observation_space is not None
  869. and policy_spec.observation_space != self.observation_space
  870. ):
  871. logger.warning(
  872. "`observation_space` in given policy state ("
  873. f"{policy_spec.observation_space}) does not match this Policy's "
  874. f"observation space ({self.observation_space})."
  875. )
  876. if (
  877. policy_spec.action_space is not None
  878. and policy_spec.action_space != self.action_space
  879. ):
  880. logger.warning(
  881. "`action_space` in given policy state ("
  882. f"{policy_spec.action_space}) does not match this Policy's "
  883. f"action space ({self.action_space})."
  884. )
  885. # Override config, if part of the spec.
  886. if policy_spec.config:
  887. self.config = policy_spec.config
  888. # Override NN weights.
  889. self.set_weights(state["weights"])
  890. self.restore_connectors(state)
  891. def apply(
  892. self,
  893. func: Callable[["Policy", Optional[Any], Optional[Any]], T],
  894. *args,
  895. **kwargs,
  896. ) -> T:
  897. """Calls the given function with this Policy instance.
  898. Useful for when the Policy class has been converted into a ActorHandle
  899. and the user needs to execute some functionality (e.g. add a property)
  900. on the underlying policy object.
  901. Args:
  902. func: The function to call, with this Policy as first
  903. argument, followed by args, and kwargs.
  904. args: Optional additional args to pass to the function call.
  905. kwargs: Optional additional kwargs to pass to the function call.
  906. Returns:
  907. The return value of the function call.
  908. """
  909. return func(self, *args, **kwargs)
  910. def on_global_var_update(self, global_vars: Dict[str, TensorType]) -> None:
  911. """Called on an update to global vars.
  912. Args:
  913. global_vars: Global variables by str key, broadcast from the
  914. driver.
  915. """
  916. # Store the current global time step (sum over all policies' sample
  917. # steps).
  918. # Make sure, we keep global_timestep as a Tensor for tf-eager
  919. # (leads to memory leaks if not doing so).
  920. if self.framework == "tf2":
  921. self.global_timestep.assign(global_vars["timestep"])
  922. else:
  923. self.global_timestep = global_vars["timestep"]
  924. # Update our lifetime gradient update counter.
  925. num_grad_updates = global_vars.get("num_grad_updates")
  926. if num_grad_updates is not None:
  927. self.num_grad_updates = num_grad_updates
  928. def export_checkpoint(
  929. self,
  930. export_dir: str,
  931. filename_prefix=DEPRECATED_VALUE,
  932. *,
  933. policy_state: Optional[PolicyState] = None,
  934. checkpoint_format: str = "cloudpickle",
  935. ) -> None:
  936. """Exports Policy checkpoint to a local directory and returns an AIR Checkpoint.
  937. Args:
  938. export_dir: Local writable directory to store the AIR Checkpoint
  939. information into.
  940. policy_state: An optional PolicyState to write to disk. Used by
  941. `Algorithm.save_checkpoint()` to save on the additional
  942. `self.get_state()` calls of its different Policies.
  943. checkpoint_format: Either one of 'cloudpickle' or 'msgpack'.
  944. .. testcode::
  945. :skipif: True
  946. from ray.rllib.algorithms.ppo import PPOTorchPolicy
  947. policy = PPOTorchPolicy(...)
  948. policy.export_checkpoint("/tmp/export_dir")
  949. """
  950. # `filename_prefix` should not longer be used as new Policy checkpoints
  951. # contain more than one file with a fixed filename structure.
  952. if filename_prefix != DEPRECATED_VALUE:
  953. deprecation_warning(
  954. old="Policy.export_checkpoint(filename_prefix=...)",
  955. error=True,
  956. )
  957. if checkpoint_format not in ["cloudpickle", "msgpack"]:
  958. raise ValueError(
  959. f"Value of `checkpoint_format` ({checkpoint_format}) must either be "
  960. "'cloudpickle' or 'msgpack'!"
  961. )
  962. if policy_state is None:
  963. policy_state = self.get_state()
  964. # Write main policy state file.
  965. os.makedirs(export_dir, exist_ok=True)
  966. if checkpoint_format == "cloudpickle":
  967. policy_state["checkpoint_version"] = CHECKPOINT_VERSION
  968. state_file = "policy_state.pkl"
  969. with open(os.path.join(export_dir, state_file), "w+b") as f:
  970. pickle.dump(policy_state, f)
  971. else:
  972. from ray.rllib.algorithms.algorithm_config import AlgorithmConfig
  973. msgpack = try_import_msgpack(error=True)
  974. policy_state["checkpoint_version"] = str(CHECKPOINT_VERSION)
  975. # Serialize the config for msgpack dump'ing.
  976. policy_state["policy_spec"]["config"] = AlgorithmConfig._serialize_dict(
  977. policy_state["policy_spec"]["config"]
  978. )
  979. state_file = "policy_state.msgpck"
  980. with open(os.path.join(export_dir, state_file), "w+b") as f:
  981. msgpack.dump(policy_state, f)
  982. # Write RLlib checkpoint json.
  983. with open(os.path.join(export_dir, "rllib_checkpoint.json"), "w") as f:
  984. json.dump(
  985. {
  986. "type": "Policy",
  987. "checkpoint_version": str(policy_state["checkpoint_version"]),
  988. "format": checkpoint_format,
  989. "state_file": state_file,
  990. "ray_version": ray.__version__,
  991. "ray_commit": ray.__commit__,
  992. },
  993. f,
  994. )
  995. # Add external model files, if required.
  996. if self.config["export_native_model_files"]:
  997. self.export_model(os.path.join(export_dir, "model"))
  998. def export_model(self, export_dir: str, onnx: Optional[int] = None) -> None:
  999. """Exports the Policy's Model to local directory for serving.
  1000. Note: The file format will depend on the deep learning framework used.
  1001. See the child classed of Policy and their `export_model`
  1002. implementations for more details.
  1003. Args:
  1004. export_dir: Local writable directory.
  1005. onnx: If given, will export model in ONNX format. The
  1006. value of this parameter set the ONNX OpSet version to use.
  1007. Raises:
  1008. ValueError: If a native DL-framework based model (e.g. a keras Model)
  1009. cannot be saved to disk for various reasons.
  1010. """
  1011. raise NotImplementedError
  1012. def import_model_from_h5(self, import_file: str) -> None:
  1013. """Imports Policy from local file.
  1014. Args:
  1015. import_file: Local readable file.
  1016. """
  1017. raise NotImplementedError
  1018. def get_session(self) -> Optional["tf1.Session"]:
  1019. """Returns tf.Session object to use for computing actions or None.
  1020. Note: This method only applies to TFPolicy sub-classes. All other
  1021. sub-classes should expect a None to be returned from this method.
  1022. Returns:
  1023. The tf Session to use for computing actions and losses with
  1024. this policy or None.
  1025. """
  1026. return None
  1027. def get_host(self) -> str:
  1028. """Returns the computer's network name.
  1029. Returns:
  1030. The computer's networks name or an empty string, if the network
  1031. name could not be determined.
  1032. """
  1033. return platform.node()
  1034. def _get_num_gpus_for_policy(self) -> int:
  1035. """Decide on the number of CPU/GPU nodes this policy should run on.
  1036. Return:
  1037. 0 if policy should run on CPU. >0 if policy should run on 1 or
  1038. more GPUs.
  1039. """
  1040. worker_idx = self.config.get("worker_index", 0)
  1041. fake_gpus = self.config.get("_fake_gpus", False)
  1042. if (
  1043. ray._private.worker._mode() == ray._private.worker.LOCAL_MODE
  1044. and not fake_gpus
  1045. ):
  1046. # If in local debugging mode, and _fake_gpus is not on.
  1047. num_gpus = 0
  1048. elif worker_idx == 0:
  1049. # If head node, take num_gpus.
  1050. num_gpus = self.config["num_gpus"]
  1051. else:
  1052. # If worker node, take `num_gpus_per_env_runner`.
  1053. num_gpus = self.config["num_gpus_per_env_runner"]
  1054. if num_gpus == 0:
  1055. dev = "CPU"
  1056. else:
  1057. dev = "{} {}".format(num_gpus, "fake-GPUs" if fake_gpus else "GPUs")
  1058. logger.info(
  1059. "Policy (worker={}) running on {}.".format(
  1060. worker_idx if worker_idx > 0 else "local", dev
  1061. )
  1062. )
  1063. return num_gpus
  1064. def _create_exploration(self) -> Exploration:
  1065. """Creates the Policy's Exploration object.
  1066. This method only exists b/c some Algorithms do not use TfPolicy nor
  1067. TorchPolicy, but inherit directly from Policy. Others inherit from
  1068. TfPolicy w/o using DynamicTFPolicy.
  1069. Returns:
  1070. Exploration: The Exploration object to be used by this Policy.
  1071. """
  1072. if getattr(self, "exploration", None) is not None:
  1073. return self.exploration
  1074. exploration = from_config(
  1075. Exploration,
  1076. self.config.get("exploration_config", {"type": "StochasticSampling"}),
  1077. action_space=self.action_space,
  1078. policy_config=self.config,
  1079. model=getattr(self, "model", None),
  1080. num_workers=self.config.get("num_env_runners", 0),
  1081. worker_index=self.config.get("worker_index", 0),
  1082. framework=getattr(self, "framework", self.config.get("framework", "tf")),
  1083. )
  1084. return exploration
  1085. def _get_default_view_requirements(self):
  1086. """Returns a default ViewRequirements dict.
  1087. Note: This is the base/maximum requirement dict, from which later
  1088. some requirements will be subtracted again automatically to streamline
  1089. data collection, batch creation, and data transfer.
  1090. Returns:
  1091. ViewReqDict: The default view requirements dict.
  1092. """
  1093. # Default view requirements (equal to those that we would use before
  1094. # the trajectory view API was introduced).
  1095. return {
  1096. SampleBatch.OBS: ViewRequirement(space=self.observation_space),
  1097. SampleBatch.NEXT_OBS: ViewRequirement(
  1098. data_col=SampleBatch.OBS,
  1099. shift=1,
  1100. space=self.observation_space,
  1101. used_for_compute_actions=False,
  1102. ),
  1103. SampleBatch.ACTIONS: ViewRequirement(
  1104. space=self.action_space, used_for_compute_actions=False
  1105. ),
  1106. # For backward compatibility with custom Models that don't specify
  1107. # these explicitly (will be removed by Policy if not used).
  1108. SampleBatch.PREV_ACTIONS: ViewRequirement(
  1109. data_col=SampleBatch.ACTIONS, shift=-1, space=self.action_space
  1110. ),
  1111. SampleBatch.REWARDS: ViewRequirement(),
  1112. # For backward compatibility with custom Models that don't specify
  1113. # these explicitly (will be removed by Policy if not used).
  1114. SampleBatch.PREV_REWARDS: ViewRequirement(
  1115. data_col=SampleBatch.REWARDS, shift=-1
  1116. ),
  1117. SampleBatch.TERMINATEDS: ViewRequirement(),
  1118. SampleBatch.TRUNCATEDS: ViewRequirement(),
  1119. SampleBatch.INFOS: ViewRequirement(used_for_compute_actions=False),
  1120. SampleBatch.EPS_ID: ViewRequirement(),
  1121. SampleBatch.UNROLL_ID: ViewRequirement(),
  1122. SampleBatch.AGENT_INDEX: ViewRequirement(),
  1123. SampleBatch.T: ViewRequirement(),
  1124. }
  1125. def _initialize_loss_from_dummy_batch(
  1126. self,
  1127. auto_remove_unneeded_view_reqs: bool = True,
  1128. stats_fn=None,
  1129. ) -> None:
  1130. """Performs test calls through policy's model and loss.
  1131. NOTE: This base method should work for define-by-run Policies such as
  1132. torch and tf-eager policies.
  1133. If required, will thereby detect automatically, which data views are
  1134. required by a) the forward pass, b) the postprocessing, and c) the loss
  1135. functions, and remove those from self.view_requirements that are not
  1136. necessary for these computations (to save data storage and transfer).
  1137. Args:
  1138. auto_remove_unneeded_view_reqs: Whether to automatically
  1139. remove those ViewRequirements records from
  1140. self.view_requirements that are not needed.
  1141. stats_fn (Optional[Callable[[Policy, SampleBatch], Dict[str,
  1142. TensorType]]]): An optional stats function to be called after
  1143. the loss.
  1144. """
  1145. if self.config.get("_disable_initialize_loss_from_dummy_batch", False):
  1146. return
  1147. # Signal Policy that currently we do not like to eager/jit trace
  1148. # any function calls. This is to be able to track, which columns
  1149. # in the dummy batch are accessed by the different function (e.g.
  1150. # loss) such that we can then adjust our view requirements.
  1151. self._no_tracing = True
  1152. # Save for later so that loss init does not change global timestep
  1153. global_ts_before_init = int(convert_to_numpy(self.global_timestep))
  1154. sample_batch_size = min(
  1155. max(self.batch_divisibility_req * 4, 32),
  1156. self.config["train_batch_size"], # Don't go over the asked batch size.
  1157. )
  1158. self._dummy_batch = self._get_dummy_batch_from_view_requirements(
  1159. sample_batch_size
  1160. )
  1161. self._lazy_tensor_dict(self._dummy_batch)
  1162. explore = False
  1163. actions, state_outs, extra_outs = self.compute_actions_from_input_dict(
  1164. self._dummy_batch, explore=explore
  1165. )
  1166. for key, view_req in self.view_requirements.items():
  1167. if key not in self._dummy_batch.accessed_keys:
  1168. view_req.used_for_compute_actions = False
  1169. # Add all extra action outputs to view reqirements (these may be
  1170. # filtered out later again, if not needed for postprocessing or loss).
  1171. for key, value in extra_outs.items():
  1172. self._dummy_batch[key] = value
  1173. if key not in self.view_requirements:
  1174. if isinstance(value, (dict, np.ndarray)):
  1175. # the assumption is that value is a nested_dict of np.arrays leaves
  1176. space = get_gym_space_from_struct_of_tensors(value)
  1177. self.view_requirements[key] = ViewRequirement(
  1178. space=space, used_for_compute_actions=False
  1179. )
  1180. else:
  1181. raise ValueError(
  1182. "policy.compute_actions_from_input_dict() returns an "
  1183. "extra action output that is neither a numpy array nor a dict."
  1184. )
  1185. for key in self._dummy_batch.accessed_keys:
  1186. if key not in self.view_requirements:
  1187. self.view_requirements[key] = ViewRequirement()
  1188. self.view_requirements[key].used_for_compute_actions = False
  1189. # TODO (kourosh) Why did we use to make used_for_compute_actions True here?
  1190. new_batch = self._get_dummy_batch_from_view_requirements(sample_batch_size)
  1191. # Make sure the dummy_batch will return numpy arrays when accessed
  1192. self._dummy_batch.set_get_interceptor(None)
  1193. # try to re-use the output of the previous run to avoid overriding things that
  1194. # would break (e.g. scale = 0 of Normal distribution cannot be zero)
  1195. for k in new_batch:
  1196. if k not in self._dummy_batch:
  1197. self._dummy_batch[k] = new_batch[k]
  1198. # Make sure the book-keeping of dummy_batch keys are reset to correcly track
  1199. # what is accessed, what is added and what's deleted from now on.
  1200. self._dummy_batch.accessed_keys.clear()
  1201. self._dummy_batch.deleted_keys.clear()
  1202. self._dummy_batch.added_keys.clear()
  1203. if self.exploration:
  1204. # Policies with RLModules don't have an exploration object.
  1205. self.exploration.postprocess_trajectory(self, self._dummy_batch)
  1206. postprocessed_batch = self.postprocess_trajectory(self._dummy_batch)
  1207. seq_lens = None
  1208. if state_outs:
  1209. B = 4 # For RNNs, have B=4, T=[depends on sample_batch_size]
  1210. i = 0
  1211. while "state_in_{}".format(i) in postprocessed_batch:
  1212. postprocessed_batch["state_in_{}".format(i)] = postprocessed_batch[
  1213. "state_in_{}".format(i)
  1214. ][:B]
  1215. if "state_out_{}".format(i) in postprocessed_batch:
  1216. postprocessed_batch["state_out_{}".format(i)] = postprocessed_batch[
  1217. "state_out_{}".format(i)
  1218. ][:B]
  1219. i += 1
  1220. seq_len = sample_batch_size // B
  1221. seq_lens = np.array([seq_len for _ in range(B)], dtype=np.int32)
  1222. postprocessed_batch[SampleBatch.SEQ_LENS] = seq_lens
  1223. # Switch on lazy to-tensor conversion on `postprocessed_batch`.
  1224. train_batch = self._lazy_tensor_dict(postprocessed_batch)
  1225. # Calling loss, so set `is_training` to True.
  1226. train_batch.set_training(True)
  1227. if seq_lens is not None:
  1228. train_batch[SampleBatch.SEQ_LENS] = seq_lens
  1229. train_batch.count = self._dummy_batch.count
  1230. # Call the loss function, if it exists.
  1231. # TODO(jungong) : clean up after all agents get migrated.
  1232. # We should simply do self.loss(...) here.
  1233. if self._loss is not None:
  1234. self._loss(self, self.model, self.dist_class, train_batch)
  1235. elif is_overridden(self.loss) and not self.config["in_evaluation"]:
  1236. self.loss(self.model, self.dist_class, train_batch)
  1237. # Call the stats fn, if given.
  1238. # TODO(jungong) : clean up after all agents get migrated.
  1239. # We should simply do self.stats_fn(train_batch) here.
  1240. if stats_fn is not None:
  1241. stats_fn(self, train_batch)
  1242. if hasattr(self, "stats_fn") and not self.config["in_evaluation"]:
  1243. self.stats_fn(train_batch)
  1244. # Re-enable tracing.
  1245. self._no_tracing = False
  1246. # Add new columns automatically to view-reqs.
  1247. if auto_remove_unneeded_view_reqs:
  1248. # Add those needed for postprocessing and training.
  1249. all_accessed_keys = (
  1250. train_batch.accessed_keys
  1251. | self._dummy_batch.accessed_keys
  1252. | self._dummy_batch.added_keys
  1253. )
  1254. for key in all_accessed_keys:
  1255. if key not in self.view_requirements and key != SampleBatch.SEQ_LENS:
  1256. self.view_requirements[key] = ViewRequirement(
  1257. used_for_compute_actions=False
  1258. )
  1259. if self._loss or is_overridden(self.loss):
  1260. # Tag those only needed for post-processing (with some
  1261. # exceptions).
  1262. for key in self._dummy_batch.accessed_keys:
  1263. if (
  1264. key not in train_batch.accessed_keys
  1265. and key in self.view_requirements
  1266. and key not in self.model.view_requirements
  1267. and key
  1268. not in [
  1269. SampleBatch.EPS_ID,
  1270. SampleBatch.AGENT_INDEX,
  1271. SampleBatch.UNROLL_ID,
  1272. SampleBatch.TERMINATEDS,
  1273. SampleBatch.TRUNCATEDS,
  1274. SampleBatch.REWARDS,
  1275. SampleBatch.INFOS,
  1276. SampleBatch.T,
  1277. ]
  1278. ):
  1279. self.view_requirements[key].used_for_training = False
  1280. # Remove those not needed at all (leave those that are needed
  1281. # by Sampler to properly execute sample collection). Also always leave
  1282. # TERMINATEDS, TRUNCATEDS, REWARDS, INFOS, no matter what.
  1283. for key in list(self.view_requirements.keys()):
  1284. if (
  1285. key not in all_accessed_keys
  1286. and key
  1287. not in [
  1288. SampleBatch.EPS_ID,
  1289. SampleBatch.AGENT_INDEX,
  1290. SampleBatch.UNROLL_ID,
  1291. SampleBatch.TERMINATEDS,
  1292. SampleBatch.TRUNCATEDS,
  1293. SampleBatch.REWARDS,
  1294. SampleBatch.INFOS,
  1295. SampleBatch.T,
  1296. ]
  1297. and key not in self.model.view_requirements
  1298. ):
  1299. # If user deleted this key manually in postprocessing
  1300. # fn, warn about it and do not remove from
  1301. # view-requirements.
  1302. if key in self._dummy_batch.deleted_keys:
  1303. logger.warning(
  1304. "SampleBatch key '{}' was deleted manually in "
  1305. "postprocessing function! RLlib will "
  1306. "automatically remove non-used items from the "
  1307. "data stream. Remove the `del` from your "
  1308. "postprocessing function.".format(key)
  1309. )
  1310. # If we are not writing output to disk, save to erase
  1311. # this key to save space in the sample batch.
  1312. elif self.config["output"] is None:
  1313. del self.view_requirements[key]
  1314. if type(self.global_timestep) is int:
  1315. self.global_timestep = global_ts_before_init
  1316. elif isinstance(self.global_timestep, tf.Variable):
  1317. self.global_timestep.assign(global_ts_before_init)
  1318. else:
  1319. raise ValueError(
  1320. "Variable self.global_timestep of policy {} needs to be "
  1321. "either of type `int` or `tf.Variable`, "
  1322. "but is of type {}.".format(self, type(self.global_timestep))
  1323. )
  1324. def maybe_remove_time_dimension(self, input_dict: Dict[str, TensorType]):
  1325. """Removes a time dimension for recurrent RLModules.
  1326. Args:
  1327. input_dict: The input dict.
  1328. Returns:
  1329. The input dict with a possibly removed time dimension.
  1330. """
  1331. raise NotImplementedError
  1332. def _get_dummy_batch_from_view_requirements(
  1333. self, batch_size: int = 1
  1334. ) -> SampleBatch:
  1335. """Creates a numpy dummy batch based on the Policy's view requirements.
  1336. Args:
  1337. batch_size: The size of the batch to create.
  1338. Returns:
  1339. Dict[str, TensorType]: The dummy batch containing all zero values.
  1340. """
  1341. ret = {}
  1342. for view_col, view_req in self.view_requirements.items():
  1343. data_col = view_req.data_col or view_col
  1344. # Flattened dummy batch.
  1345. if (isinstance(view_req.space, (gym.spaces.Tuple, gym.spaces.Dict))) and (
  1346. (
  1347. data_col == SampleBatch.OBS
  1348. and not self.config["_disable_preprocessor_api"]
  1349. )
  1350. or (
  1351. data_col == SampleBatch.ACTIONS
  1352. and not self.config.get("_disable_action_flattening")
  1353. )
  1354. ):
  1355. _, shape = ModelCatalog.get_action_shape(
  1356. view_req.space, framework=self.config["framework"]
  1357. )
  1358. ret[view_col] = np.zeros((batch_size,) + shape[1:], np.float32)
  1359. # Non-flattened dummy batch.
  1360. else:
  1361. # Range of indices on time-axis, e.g. "-50:-1".
  1362. if isinstance(view_req.space, gym.spaces.Space):
  1363. time_size = (
  1364. len(view_req.shift_arr) if len(view_req.shift_arr) > 1 else None
  1365. )
  1366. ret[view_col] = get_dummy_batch_for_space(
  1367. view_req.space, batch_size=batch_size, time_size=time_size
  1368. )
  1369. else:
  1370. ret[view_col] = [view_req.space for _ in range(batch_size)]
  1371. # Due to different view requirements for the different columns,
  1372. # columns in the resulting batch may not all have the same batch size.
  1373. return SampleBatch(ret)
  1374. def _update_model_view_requirements_from_init_state(self):
  1375. """Uses Model's (or this Policy's) init state to add needed ViewReqs.
  1376. Can be called from within a Policy to make sure RNNs automatically
  1377. update their internal state-related view requirements.
  1378. Changes the `self.view_requirements` dict.
  1379. """
  1380. self._model_init_state_automatically_added = True
  1381. model = getattr(self, "model", None)
  1382. obj = model or self
  1383. if model and not hasattr(model, "view_requirements"):
  1384. model.view_requirements = {
  1385. SampleBatch.OBS: ViewRequirement(space=self.observation_space)
  1386. }
  1387. view_reqs = obj.view_requirements
  1388. # Add state-ins to this model's view.
  1389. init_state = []
  1390. if hasattr(obj, "get_initial_state") and callable(obj.get_initial_state):
  1391. init_state = obj.get_initial_state()
  1392. else:
  1393. # Add this functionality automatically for new native model API.
  1394. if (
  1395. tf
  1396. and isinstance(model, tf.keras.Model)
  1397. and "state_in_0" not in view_reqs
  1398. ):
  1399. obj.get_initial_state = lambda: [
  1400. np.zeros_like(view_req.space.sample())
  1401. for k, view_req in model.view_requirements.items()
  1402. if k.startswith("state_in_")
  1403. ]
  1404. else:
  1405. obj.get_initial_state = lambda: []
  1406. if "state_in_0" in view_reqs:
  1407. self.is_recurrent = lambda: True
  1408. # Make sure auto-generated init-state view requirements get added
  1409. # to both Policy and Model, no matter what.
  1410. view_reqs = [view_reqs] + (
  1411. [self.view_requirements] if hasattr(self, "view_requirements") else []
  1412. )
  1413. for i, state in enumerate(init_state):
  1414. # Allow `state` to be either a Space (use zeros as initial values)
  1415. # or any value (e.g. a dict or a non-zero tensor).
  1416. fw = (
  1417. np
  1418. if isinstance(state, np.ndarray)
  1419. else torch
  1420. if torch and torch.is_tensor(state)
  1421. else None
  1422. )
  1423. if fw:
  1424. space = (
  1425. Box(-1.0, 1.0, shape=state.shape) if fw.all(state == 0.0) else state
  1426. )
  1427. else:
  1428. space = state
  1429. for vr in view_reqs:
  1430. # Only override if user has not already provided
  1431. # custom view-requirements for state_in_n.
  1432. if "state_in_{}".format(i) not in vr:
  1433. vr["state_in_{}".format(i)] = ViewRequirement(
  1434. "state_out_{}".format(i),
  1435. shift=-1,
  1436. used_for_compute_actions=True,
  1437. batch_repeat_value=self.config.get("model", {}).get(
  1438. "max_seq_len", 1
  1439. ),
  1440. space=space,
  1441. )
  1442. # Only override if user has not already provided
  1443. # custom view-requirements for state_out_n.
  1444. if "state_out_{}".format(i) not in vr:
  1445. vr["state_out_{}".format(i)] = ViewRequirement(
  1446. space=space, used_for_training=True
  1447. )
  1448. def __repr__(self):
  1449. return type(self).__name__
  1450. @OldAPIStack
  1451. def get_gym_space_from_struct_of_tensors(
  1452. value: Union[Dict, Tuple, List, TensorType],
  1453. batched_input=True,
  1454. ) -> gym.Space:
  1455. start_idx = 1 if batched_input else 0
  1456. struct = tree.map_structure(
  1457. lambda x: gym.spaces.Box(
  1458. -1.0, 1.0, shape=x.shape[start_idx:], dtype=get_np_dtype(x)
  1459. ),
  1460. value,
  1461. )
  1462. space = get_gym_space_from_struct_of_spaces(struct)
  1463. return space
  1464. @OldAPIStack
  1465. def get_gym_space_from_struct_of_spaces(value: Union[Dict, Tuple]) -> gym.spaces.Dict:
  1466. if isinstance(value, dict):
  1467. return gym.spaces.Dict(
  1468. {k: get_gym_space_from_struct_of_spaces(v) for k, v in value.items()}
  1469. )
  1470. elif isinstance(value, (tuple, list)):
  1471. return gym.spaces.Tuple([get_gym_space_from_struct_of_spaces(v) for v in value])
  1472. else:
  1473. assert isinstance(value, gym.spaces.Space), (
  1474. f"The struct of spaces should only contain dicts, tiples and primitive "
  1475. f"gym spaces. Space is of type {type(value)}"
  1476. )
  1477. return value