connector.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. """This file defines base types and common structures for RLlib connectors.
  2. """
  3. import abc
  4. import logging
  5. from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Union
  6. import gymnasium as gym
  7. from ray.rllib.policy.view_requirement import ViewRequirement
  8. from ray.rllib.utils.typing import (
  9. ActionConnectorDataType,
  10. AgentConnectorDataType,
  11. AlgorithmConfigDict,
  12. TensorType,
  13. )
  14. from ray.util.annotations import PublicAPI
  15. if TYPE_CHECKING:
  16. from ray.rllib.policy.policy import Policy
  17. logger = logging.getLogger(__name__)
  18. @PublicAPI(stability="alpha")
  19. class ConnectorContext:
  20. """Data bits that may be needed for running connectors.
  21. Note(jungong) : we need to be really careful with the data fields here.
  22. E.g., everything needs to be serializable, in case we need to fetch them
  23. in a remote setting.
  24. """
  25. # TODO(jungong) : figure out how to fetch these in a remote setting.
  26. # Probably from a policy server when initializing a policy client.
  27. def __init__(
  28. self,
  29. config: AlgorithmConfigDict = None,
  30. initial_states: List[TensorType] = None,
  31. observation_space: gym.Space = None,
  32. action_space: gym.Space = None,
  33. view_requirements: Dict[str, ViewRequirement] = None,
  34. is_policy_recurrent: bool = False,
  35. ):
  36. """Construct a ConnectorContext instance.
  37. Args:
  38. initial_states: States that are used for constructing
  39. the initial input dict for RNN models. [] if a model is not recurrent.
  40. action_space_struct: a policy's action space, in python
  41. data format. E.g., python dict instead of DictSpace, python tuple
  42. instead of TupleSpace.
  43. """
  44. self.config = config or {}
  45. self.initial_states = initial_states or []
  46. self.observation_space = observation_space
  47. self.action_space = action_space
  48. self.view_requirements = view_requirements
  49. self.is_policy_recurrent = is_policy_recurrent
  50. @staticmethod
  51. def from_policy(policy: "Policy") -> "ConnectorContext":
  52. """Build ConnectorContext from a given policy.
  53. Args:
  54. policy: Policy
  55. Returns:
  56. A ConnectorContext instance.
  57. """
  58. return ConnectorContext(
  59. config=policy.config,
  60. initial_states=policy.get_initial_state(),
  61. observation_space=policy.observation_space,
  62. action_space=policy.action_space,
  63. view_requirements=policy.view_requirements,
  64. is_policy_recurrent=policy.is_recurrent(),
  65. )
  66. @PublicAPI(stability="alpha")
  67. class Connector(abc.ABC):
  68. """Connector base class.
  69. A connector is a step of transformation, of either envrionment data before they
  70. get to a policy, or policy output before it is sent back to the environment.
  71. Connectors may be training-aware, for example, behave slightly differently
  72. during training and inference.
  73. All connectors are required to be serializable and implement to_state().
  74. """
  75. def __init__(self, ctx: ConnectorContext):
  76. # Default is training mode.
  77. self._is_training = True
  78. def in_training(self):
  79. self._is_training = True
  80. def in_eval(self):
  81. self._is_training = False
  82. def __str__(self, indentation: int = 0):
  83. return " " * indentation + self.__class__.__name__
  84. def to_state(self) -> Tuple[str, Any]:
  85. """Serialize a connector into a JSON serializable Tuple.
  86. to_state is required, so that all Connectors are serializable.
  87. Returns:
  88. A tuple of connector's name and its serialized states.
  89. String should match the name used to register the connector,
  90. while state can be any single data structure that contains the
  91. serialized state of the connector. If a connector is stateless,
  92. state can simply be None.
  93. """
  94. # Must implement by each connector.
  95. return NotImplementedError
  96. @staticmethod
  97. def from_state(self, ctx: ConnectorContext, params: Any) -> "Connector":
  98. """De-serialize a JSON params back into a Connector.
  99. from_state is required, so that all Connectors are serializable.
  100. Args:
  101. ctx: Context for constructing this connector.
  102. params: Serialized states of the connector to be recovered.
  103. Returns:
  104. De-serialized connector.
  105. """
  106. # Must implement by each connector.
  107. return NotImplementedError
  108. @PublicAPI(stability="alpha")
  109. class AgentConnector(Connector):
  110. """Connector connecting user environments to RLlib policies.
  111. An agent connector transforms a list of agent data in AgentConnectorDataType
  112. format into a new list in the same AgentConnectorDataTypes format.
  113. The input API is designed so agent connectors can have access to all the
  114. agents assigned to a particular policy.
  115. AgentConnectorDataTypes can be used to specify arbitrary type of env data,
  116. Example:
  117. Represent a list of agent data from one env step() call.
  118. .. testcode::
  119. import numpy as np
  120. ac = AgentConnectorDataType(
  121. env_id="env_1",
  122. agent_id=None,
  123. data={
  124. "agent_1": np.array([1, 2, 3]),
  125. "agent_2": np.array([4, 5, 6]),
  126. }
  127. )
  128. Or a single agent data ready to be preprocessed.
  129. .. testcode::
  130. ac = AgentConnectorDataType(
  131. env_id="env_1",
  132. agent_id="agent_1",
  133. data=np.array([1, 2, 3]),
  134. )
  135. We can also adapt a simple stateless function into an agent connector by
  136. using register_lambda_agent_connector:
  137. .. testcode::
  138. import numpy as np
  139. from ray.rllib.connectors.agent.lambdas import (
  140. register_lambda_agent_connector
  141. )
  142. TimesTwoAgentConnector = register_lambda_agent_connector(
  143. "TimesTwoAgentConnector", lambda data: data * 2
  144. )
  145. # More complicated agent connectors can be implemented by extending this
  146. # AgentConnector class:
  147. class FrameSkippingAgentConnector(AgentConnector):
  148. def __init__(self, n):
  149. self._n = n
  150. self._frame_count = default_dict(str, default_dict(str, int))
  151. def reset(self, env_id: str):
  152. del self._frame_count[env_id]
  153. def __call__(
  154. self, ac_data: List[AgentConnectorDataType]
  155. ) -> List[AgentConnectorDataType]:
  156. ret = []
  157. for d in ac_data:
  158. assert d.env_id and d.agent_id, "Skipping works per agent!"
  159. count = self._frame_count[ac_data.env_id][ac_data.agent_id]
  160. self._frame_count[ac_data.env_id][ac_data.agent_id] = (
  161. count + 1
  162. )
  163. if count % self._n == 0:
  164. ret.append(d)
  165. return ret
  166. As shown, an agent connector may choose to emit an empty list to stop input
  167. observations from being further prosessed.
  168. """
  169. def reset(self, env_id: str):
  170. """Reset connector state for a specific environment.
  171. For example, at the end of an episode.
  172. Args:
  173. env_id: required. ID of a user environment. Required.
  174. """
  175. pass
  176. def on_policy_output(self, output: ActionConnectorDataType):
  177. """Callback on agent connector of policy output.
  178. This is useful for certain connectors, for example RNN state buffering,
  179. where the agent connect needs to be aware of the output of a policy
  180. forward pass.
  181. Args:
  182. ctx: Context for running this connector call.
  183. output: Env and agent IDs, plus data output from policy forward pass.
  184. """
  185. pass
  186. def __call__(
  187. self, acd_list: List[AgentConnectorDataType]
  188. ) -> List[AgentConnectorDataType]:
  189. """Transform a list of data items from env before they reach policy.
  190. Args:
  191. ac_data: List of env and agent IDs, plus arbitrary data items from
  192. an environment or upstream agent connectors.
  193. Returns:
  194. A list of transformed data items in AgentConnectorDataType format.
  195. The shape of a returned list does not have to match that of the input list.
  196. An AgentConnector may choose to derive multiple outputs for a single piece
  197. of input data, for example multi-agent obs -> multiple single agent obs.
  198. Agent connectors may also choose to skip emitting certain inputs,
  199. useful for connectors such as frame skipping.
  200. """
  201. assert isinstance(
  202. acd_list, (list, tuple)
  203. ), "Input to agent connectors are list of AgentConnectorDataType."
  204. # Default implementation. Simply call transform on each agent connector data.
  205. return [self.transform(d) for d in acd_list]
  206. def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType:
  207. """Transform a single agent connector data item.
  208. Args:
  209. data: Env and agent IDs, plus arbitrary data item from a single agent
  210. of an environment.
  211. Returns:
  212. A transformed piece of agent connector data.
  213. """
  214. raise NotImplementedError
  215. @PublicAPI(stability="alpha")
  216. class ActionConnector(Connector):
  217. """Action connector connects policy outputs including actions,
  218. to user environments.
  219. An action connector transforms a single piece of policy output in
  220. ActionConnectorDataType format, which is basically PolicyOutputType plus env and
  221. agent IDs.
  222. Any functions that operate directly on PolicyOutputType can be easily adapted
  223. into an ActionConnector by using register_lambda_action_connector.
  224. Example:
  225. .. testcode::
  226. from ray.rllib.connectors.action.lambdas import (
  227. register_lambda_action_connector
  228. )
  229. ZeroActionConnector = register_lambda_action_connector(
  230. "ZeroActionsConnector",
  231. lambda actions, states, fetches: (
  232. np.zeros_like(actions), states, fetches
  233. )
  234. )
  235. More complicated action connectors can also be implemented by sub-classing
  236. this ActionConnector class.
  237. """
  238. def __call__(self, ac_data: ActionConnectorDataType) -> ActionConnectorDataType:
  239. """Transform policy output before they are sent to a user environment.
  240. Args:
  241. ac_data: Env and agent IDs, plus policy output.
  242. Returns:
  243. The processed action connector data.
  244. """
  245. return self.transform(ac_data)
  246. def transform(self, ac_data: ActionConnectorDataType) -> ActionConnectorDataType:
  247. """Implementation of the actual transform.
  248. Users should override transform instead of __call__ directly.
  249. Args:
  250. ac_data: Env and agent IDs, plus policy output.
  251. Returns:
  252. The processed action connector data.
  253. """
  254. raise NotImplementedError
  255. @PublicAPI(stability="alpha")
  256. class ConnectorPipeline(abc.ABC):
  257. """Utility class for quick manipulation of a connector pipeline."""
  258. def __init__(self, ctx: ConnectorContext, connectors: List[Connector]):
  259. self.connectors = connectors
  260. def in_training(self):
  261. for c in self.connectors:
  262. c.in_training()
  263. def in_eval(self):
  264. for c in self.connectors:
  265. c.in_eval()
  266. def remove(self, name: str):
  267. """Remove a connector by <name>
  268. Args:
  269. name: name of the connector to be removed.
  270. """
  271. idx = -1
  272. for i, c in enumerate(self.connectors):
  273. if c.__class__.__name__ == name:
  274. idx = i
  275. break
  276. if idx >= 0:
  277. del self.connectors[idx]
  278. logger.info(f"Removed connector {name} from {self.__class__.__name__}.")
  279. else:
  280. logger.warning(f"Trying to remove a non-existent connector {name}.")
  281. def insert_before(self, name: str, connector: Connector):
  282. """Insert a new connector before connector <name>
  283. Args:
  284. name: name of the connector before which a new connector
  285. will get inserted.
  286. connector: a new connector to be inserted.
  287. """
  288. idx = -1
  289. for idx, c in enumerate(self.connectors):
  290. if c.__class__.__name__ == name:
  291. break
  292. if idx < 0:
  293. raise ValueError(f"Can not find connector {name}")
  294. self.connectors.insert(idx, connector)
  295. logger.info(
  296. f"Inserted {connector.__class__.__name__} before {name} "
  297. f"to {self.__class__.__name__}."
  298. )
  299. def insert_after(self, name: str, connector: Connector):
  300. """Insert a new connector after connector <name>
  301. Args:
  302. name: name of the connector after which a new connector
  303. will get inserted.
  304. connector: a new connector to be inserted.
  305. """
  306. idx = -1
  307. for idx, c in enumerate(self.connectors):
  308. if c.__class__.__name__ == name:
  309. break
  310. if idx < 0:
  311. raise ValueError(f"Can not find connector {name}")
  312. self.connectors.insert(idx + 1, connector)
  313. logger.info(
  314. f"Inserted {connector.__class__.__name__} after {name} "
  315. f"to {self.__class__.__name__}."
  316. )
  317. def prepend(self, connector: Connector):
  318. """Append a new connector at the beginning of a connector pipeline.
  319. Args:
  320. connector: a new connector to be appended.
  321. """
  322. self.connectors.insert(0, connector)
  323. logger.info(
  324. f"Added {connector.__class__.__name__} to the beginning of "
  325. f"{self.__class__.__name__}."
  326. )
  327. def append(self, connector: Connector):
  328. """Append a new connector at the end of a connector pipeline.
  329. Args:
  330. connector: a new connector to be appended.
  331. """
  332. self.connectors.append(connector)
  333. logger.info(
  334. f"Added {connector.__class__.__name__} to the end of "
  335. f"{self.__class__.__name__}."
  336. )
  337. def __str__(self, indentation: int = 0):
  338. return "\n".join(
  339. [" " * indentation + self.__class__.__name__]
  340. + [c.__str__(indentation + 4) for c in self.connectors]
  341. )
  342. def __getitem__(self, key: Union[str, int, type]):
  343. """Returns a list of connectors that fit 'key'.
  344. If key is a number n, we return a list with the nth element of this pipeline.
  345. If key is a Connector class or a string matching the class name of a
  346. Connector class, we return a list of all connectors in this pipeline matching
  347. the specified class.
  348. Args:
  349. key: The key to index by
  350. Returns: The Connector at index `key`.
  351. """
  352. # In case key is a class
  353. if not isinstance(key, str):
  354. if isinstance(key, slice):
  355. raise NotImplementedError(
  356. "Slicing of ConnectorPipeline is currently not supported."
  357. )
  358. elif isinstance(key, int):
  359. return [self.connectors[key]]
  360. elif isinstance(key, type):
  361. results = []
  362. for c in self.connectors:
  363. if issubclass(c.__class__, key):
  364. results.append(c)
  365. return results
  366. else:
  367. raise NotImplementedError(
  368. "Indexing by {} is currently not supported.".format(type(key))
  369. )
  370. results = []
  371. for c in self.connectors:
  372. if c.__class__.__name__ == key:
  373. results.append(c)
  374. return results