class_node.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. from typing import Any, Dict, List, Optional, Tuple, Union
  2. from weakref import ReferenceType
  3. import ray
  4. from ray.dag.constants import (
  5. BIND_INDEX_KEY,
  6. IS_CLASS_METHOD_OUTPUT_KEY,
  7. PARENT_CLASS_NODE_KEY,
  8. PREV_CLASS_METHOD_CALL_KEY,
  9. )
  10. from ray.dag.dag_node import DAGNode
  11. from ray.dag.format_utils import get_dag_node_str
  12. from ray.dag.input_node import InputNode
  13. from ray.util.annotations import DeveloperAPI
  14. @DeveloperAPI
  15. class ClassNode(DAGNode):
  16. """Represents an actor creation in a Ray task DAG."""
  17. def __init__(
  18. self,
  19. cls,
  20. cls_args,
  21. cls_kwargs,
  22. cls_options,
  23. other_args_to_resolve=None,
  24. ):
  25. self._body = cls
  26. self._last_call: Optional["ClassMethodNode"] = None
  27. super().__init__(
  28. cls_args,
  29. cls_kwargs,
  30. cls_options,
  31. other_args_to_resolve=other_args_to_resolve,
  32. )
  33. if self._contains_input_node():
  34. raise ValueError(
  35. "InputNode handles user dynamic input the DAG, and "
  36. "cannot be used as args, kwargs, or other_args_to_resolve "
  37. "in ClassNode constructor because it is not available at "
  38. "class construction or binding time."
  39. )
  40. def _copy_impl(
  41. self,
  42. new_args: List[Any],
  43. new_kwargs: Dict[str, Any],
  44. new_options: Dict[str, Any],
  45. new_other_args_to_resolve: Dict[str, Any],
  46. ):
  47. return ClassNode(
  48. self._body,
  49. new_args,
  50. new_kwargs,
  51. new_options,
  52. other_args_to_resolve=new_other_args_to_resolve,
  53. )
  54. def _execute_impl(self, *args, **kwargs):
  55. """Executor of ClassNode by ray.remote()
  56. Args and kwargs are to match base class signature, but not in the
  57. implementation. All args and kwargs should be resolved and replaced
  58. with value in bound_args and bound_kwargs via bottom-up recursion when
  59. current node is executed.
  60. """
  61. return (
  62. ray.remote(self._body)
  63. .options(**self._bound_options)
  64. .remote(*self._bound_args, **self._bound_kwargs)
  65. )
  66. def _contains_input_node(self) -> bool:
  67. """Check if InputNode is used in children DAGNodes with current node
  68. as the root.
  69. """
  70. children_dag_nodes = self._get_all_child_nodes()
  71. for child in children_dag_nodes:
  72. if isinstance(child, InputNode):
  73. return True
  74. return False
  75. def __getattr__(self, method_name: str):
  76. # User trying to call .bind() without a bind class method
  77. if method_name == "bind" and "bind" not in dir(self._body):
  78. raise AttributeError(f".bind() cannot be used again on {type(self)} ")
  79. # Raise an error if the method is invalid.
  80. getattr(self._body, method_name)
  81. call_node = _UnboundClassMethodNode(self, method_name, {})
  82. return call_node
  83. def __str__(self) -> str:
  84. return get_dag_node_str(self, str(self._body))
  85. class _UnboundClassMethodNode(object):
  86. def __init__(self, actor: ClassNode, method_name: str, options: dict):
  87. # TODO(sang): Theoretically, We should use weakref cuz it is
  88. # a circular dependency but when I used weakref, it fails
  89. # because we cannot serialize the weakref.
  90. self._actor = actor
  91. self._method_name = method_name
  92. self._options = options
  93. def bind(self, *args, **kwargs):
  94. other_args_to_resolve = {
  95. PARENT_CLASS_NODE_KEY: self._actor,
  96. PREV_CLASS_METHOD_CALL_KEY: self._actor._last_call,
  97. }
  98. node = ClassMethodNode(
  99. self._method_name,
  100. args,
  101. kwargs,
  102. self._options,
  103. other_args_to_resolve=other_args_to_resolve,
  104. )
  105. self._actor._last_call = node
  106. return node
  107. def __getattr__(self, attr: str):
  108. if attr == "remote":
  109. raise AttributeError(
  110. ".remote() cannot be used on ClassMethodNodes. Use .bind() instead "
  111. "to express an symbolic actor call."
  112. )
  113. else:
  114. return self.__getattribute__(attr)
  115. def options(self, **options):
  116. self._options = options
  117. return self
  118. class _ClassMethodOutput:
  119. """Represents a class method output in a Ray function DAG."""
  120. def __init__(self, class_method_call: "ClassMethodNode", output_idx: int):
  121. # The upstream class method call that returns multiple values.
  122. self._class_method_call = class_method_call
  123. # The output index of the return value from the upstream class method call.
  124. self._output_idx = output_idx
  125. @property
  126. def class_method_call(self) -> "ClassMethodNode":
  127. return self._class_method_call
  128. @property
  129. def output_idx(self) -> int:
  130. return self._output_idx
  131. @DeveloperAPI
  132. class ClassMethodNode(DAGNode):
  133. """Represents an actor method invocation in a Ray function DAG."""
  134. def __init__(
  135. self,
  136. method_name: str,
  137. method_args: Tuple[Any],
  138. method_kwargs: Dict[str, Any],
  139. method_options: Dict[str, Any],
  140. other_args_to_resolve: Dict[str, Any],
  141. ):
  142. self._bound_args = method_args or []
  143. self._bound_kwargs = method_kwargs or {}
  144. self._bound_options = method_options or {}
  145. self._method_name: str = method_name
  146. # Parse other_args_to_resolve and assign to variables
  147. self._parent_class_node: Union[
  148. ClassNode, ReferenceType["ray._private.actor.ActorHandle"]
  149. ] = other_args_to_resolve.get(PARENT_CLASS_NODE_KEY)
  150. # Used to track lineage of ClassMethodCall to preserve deterministic
  151. # submission and execution order.
  152. self._prev_class_method_call: Optional[
  153. ClassMethodNode
  154. ] = other_args_to_resolve.get(PREV_CLASS_METHOD_CALL_KEY, None)
  155. # The index/order when bind() is called on this class method
  156. self._bind_index: Optional[int] = other_args_to_resolve.get(
  157. BIND_INDEX_KEY, None
  158. )
  159. # Represent if the ClassMethodNode is a class method output. If True,
  160. # the node is a placeholder for a return value from the ClassMethodNode
  161. # that returns multiple values. If False, the node is a class method call.
  162. self._is_class_method_output: bool = other_args_to_resolve.get(
  163. IS_CLASS_METHOD_OUTPUT_KEY, False
  164. )
  165. # Represents the return value from the upstream ClassMethodNode that
  166. # returns multiple values. If the node is a class method call, this is None.
  167. self._class_method_output: Optional[_ClassMethodOutput] = None
  168. if self._is_class_method_output:
  169. # Set the upstream ClassMethodNode and the output index of the return
  170. # value from `method_args`.
  171. self._class_method_output = _ClassMethodOutput(
  172. method_args[0], method_args[1]
  173. )
  174. # The actor creation task dependency is encoded as the first argument,
  175. # and the ordering dependency as the second, which ensures they are
  176. # executed prior to this node.
  177. super().__init__(
  178. method_args,
  179. method_kwargs,
  180. method_options,
  181. other_args_to_resolve=other_args_to_resolve,
  182. )
  183. def _copy_impl(
  184. self,
  185. new_args: List[Any],
  186. new_kwargs: Dict[str, Any],
  187. new_options: Dict[str, Any],
  188. new_other_args_to_resolve: Dict[str, Any],
  189. ):
  190. return ClassMethodNode(
  191. self._method_name,
  192. new_args,
  193. new_kwargs,
  194. new_options,
  195. other_args_to_resolve=new_other_args_to_resolve,
  196. )
  197. def _execute_impl(self, *args, **kwargs):
  198. """Executor of ClassMethodNode by ray.remote()
  199. Args and kwargs are to match base class signature, but not in the
  200. implementation. All args and kwargs should be resolved and replaced
  201. with value in bound_args and bound_kwargs via bottom-up recursion when
  202. current node is executed.
  203. """
  204. if self.is_class_method_call:
  205. method_body = getattr(self._parent_class_node, self._method_name)
  206. # Execute with bound args.
  207. return method_body.options(**self._bound_options).remote(
  208. *self._bound_args,
  209. **self._bound_kwargs,
  210. )
  211. else:
  212. assert self._class_method_output is not None
  213. return self._bound_args[0][self._class_method_output.output_idx]
  214. def __str__(self) -> str:
  215. return get_dag_node_str(self, f"{self._method_name}()")
  216. def __repr__(self) -> str:
  217. return self.__str__()
  218. def get_method_name(self) -> str:
  219. return self._method_name
  220. def _get_bind_index(self) -> int:
  221. return self._bind_index
  222. def _get_remote_method(self, method_name):
  223. method_body = getattr(self._parent_class_node, method_name)
  224. return method_body
  225. def _get_actor_handle(self) -> Optional["ray.actor.ActorHandle"]:
  226. if not isinstance(self._parent_class_node, ray.actor.ActorHandle):
  227. return None
  228. return self._parent_class_node
  229. @property
  230. def num_returns(self) -> int:
  231. """
  232. Return the number of return values from the class method call. If the
  233. node is a class method output, return the number of return values from
  234. the upstream class method call.
  235. """
  236. if self.is_class_method_call:
  237. num_returns = self._bound_options.get("num_returns", None)
  238. if num_returns is None:
  239. method = self._get_remote_method(self._method_name)
  240. num_returns = method.__getstate__()["num_returns"]
  241. return num_returns
  242. else:
  243. assert self._class_method_output is not None
  244. return self._class_method_output.class_method_call.num_returns
  245. @property
  246. def is_class_method_call(self) -> bool:
  247. """
  248. Return True if the node is a class method call, False if the node is a
  249. class method output.
  250. """
  251. return not self._is_class_method_output
  252. @property
  253. def is_class_method_output(self) -> bool:
  254. """
  255. Return True if the node is a class method output, False if the node is a
  256. class method call.
  257. """
  258. return self._is_class_method_output
  259. @property
  260. def class_method_call(self) -> Optional["ClassMethodNode"]:
  261. """
  262. Return the upstream class method call that returns multiple values. If
  263. the node is a class method output, return None.
  264. """
  265. if self._class_method_output is None:
  266. return None
  267. return self._class_method_output.class_method_call
  268. @property
  269. def output_idx(self) -> Optional[int]:
  270. """
  271. Return the output index of the return value from the upstream class
  272. method call that returns multiple values. If the node is a class method
  273. call, return None.
  274. """
  275. if self._class_method_output is None:
  276. return None
  277. return self._class_method_output.output_idx