policy.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. import logging
  2. from typing import (
  3. TYPE_CHECKING,
  4. Callable,
  5. Dict,
  6. List,
  7. Optional,
  8. Tuple,
  9. Type,
  10. Union,
  11. )
  12. import gymnasium as gym
  13. import numpy as np
  14. import tree # pip install dm_tree
  15. import ray.cloudpickle as pickle
  16. from ray._common.deprecation import Deprecated
  17. from ray.rllib.core.rl_module import validate_module_id
  18. from ray.rllib.models.preprocessors import ATARI_OBS_SHAPE
  19. from ray.rllib.policy.policy import PolicySpec
  20. from ray.rllib.policy.sample_batch import SampleBatch
  21. from ray.rllib.utils.annotations import DeveloperAPI, OldAPIStack
  22. from ray.rllib.utils.framework import try_import_tf
  23. from ray.rllib.utils.typing import (
  24. ActionConnectorDataType,
  25. AgentConnectorDataType,
  26. AgentConnectorsOutput,
  27. PartialAlgorithmConfigDict,
  28. PolicyState,
  29. TensorStructType,
  30. TensorType,
  31. )
  32. from ray.util import log_once
  33. if TYPE_CHECKING:
  34. from ray.rllib.policy.policy import Policy
  35. logger = logging.getLogger(__name__)
  36. tf1, tf, tfv = try_import_tf()
  37. @OldAPIStack
  38. def create_policy_for_framework(
  39. policy_id: str,
  40. policy_class: Type["Policy"],
  41. merged_config: PartialAlgorithmConfigDict,
  42. observation_space: gym.Space,
  43. action_space: gym.Space,
  44. worker_index: int = 0,
  45. session_creator: Optional[Callable[[], "tf1.Session"]] = None,
  46. seed: Optional[int] = None,
  47. ):
  48. """Framework-specific policy creation logics.
  49. Args:
  50. policy_id: Policy ID.
  51. policy_class: Policy class type.
  52. merged_config: Complete policy config.
  53. observation_space: Observation space of env.
  54. action_space: Action space of env.
  55. worker_index: Index of worker holding this policy. Default is 0.
  56. session_creator: An optional tf1.Session creation callable.
  57. seed: Optional random seed.
  58. """
  59. from ray.rllib.algorithms.algorithm_config import AlgorithmConfig
  60. if isinstance(merged_config, AlgorithmConfig):
  61. merged_config = merged_config.to_dict()
  62. # add policy_id to merged_config
  63. merged_config["__policy_id"] = policy_id
  64. framework = merged_config.get("framework", "tf")
  65. # Tf.
  66. if framework in ["tf2", "tf"]:
  67. var_scope = policy_id + (f"_wk{worker_index}" if worker_index else "")
  68. # For tf static graph, build every policy in its own graph
  69. # and create a new session for it.
  70. if framework == "tf":
  71. with tf1.Graph().as_default():
  72. # Session creator function provided manually -> Use this one to
  73. # create the tf1 session.
  74. if session_creator:
  75. sess = session_creator()
  76. # Use a default session creator, based only on our `tf_session_args` in
  77. # the config.
  78. else:
  79. sess = tf1.Session(
  80. config=tf1.ConfigProto(**merged_config["tf_session_args"])
  81. )
  82. with sess.as_default():
  83. # Set graph-level seed.
  84. if seed is not None:
  85. tf1.set_random_seed(seed)
  86. with tf1.variable_scope(var_scope):
  87. return policy_class(
  88. observation_space, action_space, merged_config
  89. )
  90. # For tf-eager: no graph, no session.
  91. else:
  92. with tf1.variable_scope(var_scope):
  93. return policy_class(observation_space, action_space, merged_config)
  94. # Non-tf: No graph, no session.
  95. else:
  96. return policy_class(observation_space, action_space, merged_config)
  97. @OldAPIStack
  98. def parse_policy_specs_from_checkpoint(
  99. path: str,
  100. ) -> Tuple[PartialAlgorithmConfigDict, Dict[str, PolicySpec], Dict[str, PolicyState]]:
  101. """Read and parse policy specifications from a checkpoint file.
  102. Args:
  103. path: Path to a policy checkpoint.
  104. Returns:
  105. A tuple of: base policy config, dictionary of policy specs, and
  106. dictionary of policy states.
  107. """
  108. with open(path, "rb") as f:
  109. checkpoint_dict = pickle.load(f)
  110. # Policy data is contained as a serialized binary blob under their
  111. # ID keys.
  112. w = pickle.loads(checkpoint_dict["worker"])
  113. policy_config = w["policy_config"]
  114. policy_states = w.get("policy_states", w["state"])
  115. serialized_policy_specs = w["policy_specs"]
  116. policy_specs = {
  117. id: PolicySpec.deserialize(spec) for id, spec in serialized_policy_specs.items()
  118. }
  119. return policy_config, policy_specs, policy_states
  120. @OldAPIStack
  121. def local_policy_inference(
  122. policy: "Policy",
  123. env_id: str,
  124. agent_id: str,
  125. obs: TensorStructType,
  126. reward: Optional[float] = None,
  127. terminated: Optional[bool] = None,
  128. truncated: Optional[bool] = None,
  129. info: Optional[Dict] = None,
  130. explore: bool = None,
  131. timestep: Optional[int] = None,
  132. ) -> TensorStructType:
  133. """Run a connector enabled policy using environment observation.
  134. policy_inference manages policy and agent/action connectors,
  135. so the user does not have to care about RNN state buffering or
  136. extra fetch dictionaries.
  137. Note that connectors are intentionally run separately from
  138. compute_actions_from_input_dict(), so we can have the option
  139. of running per-user connectors on the client side in a
  140. server-client deployment.
  141. Args:
  142. policy: Policy object used in inference.
  143. env_id: Environment ID. RLlib builds environments' trajectories internally with
  144. connectors based on this, i.e. one trajectory per (env_id, agent_id) tuple.
  145. agent_id: Agent ID. RLlib builds agents' trajectories internally with connectors
  146. based on this, i.e. one trajectory per (env_id, agent_id) tuple.
  147. obs: Environment observation to base the action on.
  148. reward: Reward that is potentially used during inference. If not required,
  149. may be left empty. Some policies have ViewRequirements that require this.
  150. This can be set to zero at the first inference step - for example after
  151. calling gmy.Env.reset.
  152. terminated: `Terminated` flag that is potentially used during inference. If not
  153. required, may be left None. Some policies have ViewRequirements that
  154. require this extra information.
  155. truncated: `Truncated` flag that is potentially used during inference. If not
  156. required, may be left None. Some policies have ViewRequirements that
  157. require this extra information.
  158. info: Info that is potentially used durin inference. If not required,
  159. may be left empty. Some policies have ViewRequirements that require this.
  160. explore: Whether to pick an exploitation or exploration action
  161. (default: None -> use self.config["explore"]).
  162. timestep: The current (sampling) time step.
  163. Returns:
  164. List of outputs from policy forward pass.
  165. """
  166. assert (
  167. policy.agent_connectors
  168. ), "policy_inference only works with connector enabled policies."
  169. __check_atari_obs_space(obs)
  170. # Put policy in inference mode, so we don't spend time on training
  171. # only transformations.
  172. policy.agent_connectors.in_eval()
  173. policy.action_connectors.in_eval()
  174. # TODO(jungong) : support multiple env, multiple agent inference.
  175. input_dict = {SampleBatch.NEXT_OBS: obs}
  176. if reward is not None:
  177. input_dict[SampleBatch.REWARDS] = reward
  178. if terminated is not None:
  179. input_dict[SampleBatch.TERMINATEDS] = terminated
  180. if truncated is not None:
  181. input_dict[SampleBatch.TRUNCATEDS] = truncated
  182. if info is not None:
  183. input_dict[SampleBatch.INFOS] = info
  184. acd_list: List[AgentConnectorDataType] = [
  185. AgentConnectorDataType(env_id, agent_id, input_dict)
  186. ]
  187. ac_outputs: List[AgentConnectorsOutput] = policy.agent_connectors(acd_list)
  188. outputs = []
  189. for ac in ac_outputs:
  190. policy_output = policy.compute_actions_from_input_dict(
  191. ac.data.sample_batch,
  192. explore=explore,
  193. timestep=timestep,
  194. )
  195. # Note (Kourosh): policy output is batched, the AgentConnectorDataType should
  196. # not be batched during inference. This is the assumption made in AgentCollector
  197. policy_output = tree.map_structure(lambda x: x[0], policy_output)
  198. action_connector_data = ActionConnectorDataType(
  199. env_id, agent_id, ac.data.raw_dict, policy_output
  200. )
  201. if policy.action_connectors:
  202. acd = policy.action_connectors(action_connector_data)
  203. actions = acd.output
  204. else:
  205. actions = policy_output[0]
  206. outputs.append(actions)
  207. # Notify agent connectors with this new policy output.
  208. # Necessary for state buffering agent connectors, for example.
  209. policy.agent_connectors.on_policy_output(action_connector_data)
  210. return outputs
  211. @OldAPIStack
  212. def compute_log_likelihoods_from_input_dict(
  213. policy: "Policy", batch: Union[SampleBatch, Dict[str, TensorStructType]]
  214. ):
  215. """Returns log likelihood for actions in given batch for policy.
  216. Computes likelihoods by passing the observations through the current
  217. policy's `compute_log_likelihoods()` method
  218. Args:
  219. batch: The SampleBatch or MultiAgentBatch to calculate action
  220. log likelihoods from. This batch/batches must contain OBS
  221. and ACTIONS keys.
  222. Returns:
  223. The probabilities of the actions in the batch, given the
  224. observations and the policy.
  225. """
  226. num_state_inputs = 0
  227. for k in batch.keys():
  228. if k.startswith("state_in_"):
  229. num_state_inputs += 1
  230. state_keys = ["state_in_{}".format(i) for i in range(num_state_inputs)]
  231. log_likelihoods: TensorType = policy.compute_log_likelihoods(
  232. actions=batch[SampleBatch.ACTIONS],
  233. obs_batch=batch[SampleBatch.OBS],
  234. state_batches=[batch[k] for k in state_keys],
  235. prev_action_batch=batch.get(SampleBatch.PREV_ACTIONS),
  236. prev_reward_batch=batch.get(SampleBatch.PREV_REWARDS),
  237. actions_normalized=policy.config.get("actions_in_input_normalized", False),
  238. )
  239. return log_likelihoods
  240. @DeveloperAPI
  241. @Deprecated(new="Policy.from_checkpoint([checkpoint path], [policy IDs]?)", error=True)
  242. def load_policies_from_checkpoint(path, policy_ids=None):
  243. pass
  244. def __check_atari_obs_space(obs):
  245. # TODO(Artur): Remove this after we have migrated deepmind style preprocessing into
  246. # connectors (and don't auto-wrap in RW anymore)
  247. if any(
  248. o.shape == ATARI_OBS_SHAPE if isinstance(o, np.ndarray) else False
  249. for o in tree.flatten(obs)
  250. ):
  251. if log_once("warn_about_possibly_non_wrapped_atari_env"):
  252. logger.warning(
  253. "The observation you fed into local_policy_inference() has "
  254. "dimensions (210, 160, 3), which is the standard for atari "
  255. "environments. If RLlib raises an error including a related "
  256. "dimensionality mismatch, you may need to use "
  257. "ray.rllib.env.wrappers.atari_wrappers.wrap_deepmind to wrap "
  258. "you environment."
  259. )
  260. # @OldAPIStack
  261. validate_policy_id = validate_module_id