internal.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. # mypy: allow-untyped-defs
  2. import collections
  3. import copyreg
  4. import io
  5. import pickle
  6. import sys
  7. import threading
  8. import traceback
  9. from enum import Enum
  10. import torch
  11. import torch.distributed as dist
  12. from torch._C._distributed_rpc import _get_current_rpc_agent
  13. __all__ = ["RPCExecMode", "serialize", "deserialize", "PythonUDF", "RemoteException"]
  14. # Thread local tensor tables to store tensors while pickling torch.Tensor
  15. # objects
  16. _thread_local_tensor_tables = threading.local()
  17. _pickler = pickle.Pickler
  18. _unpickler = pickle.Unpickler
  19. class RPCExecMode(Enum):
  20. SYNC = "sync"
  21. ASYNC = "async"
  22. ASYNC_JIT = "async_jit"
  23. REMOTE = "remote"
  24. class _InternalRPCPickler:
  25. r"""
  26. This class provides serialize() and deserialize() interfaces to serialize
  27. data to be "binary string + tensor table" format
  28. So for RPC python UDF function and args, non tensor data will be serialized
  29. into regular binary string, tensor data will be put into thread local tensor
  30. tables, this serialization format is consistent with builtin operator and args
  31. using JIT pickler. This format will make tensor handling in C++ much easier,
  32. e.g. attach tensor to distributed autograd graph in C++
  33. """
  34. def __init__(self):
  35. # Ignore type error because dispatch_table is defined in third-party package
  36. self._dispatch_table = copyreg.dispatch_table.copy() # type: ignore[attr-defined]
  37. self._dispatch_table[torch.Tensor] = self._tensor_reducer
  38. # Used for registering customized picklers.
  39. self._class_reducer_dict = {}
  40. def _register_reducer(self, obj_class, reducer):
  41. # For the same class, only register the reducer once.
  42. if obj_class not in self._class_reducer_dict:
  43. self._class_reducer_dict[obj_class] = reducer
  44. @classmethod
  45. def _tensor_receiver(cls, tensor_index):
  46. global _thread_local_tensor_tables
  47. return _thread_local_tensor_tables.recv_tables[tensor_index]
  48. def _tensor_reducer(self, tensor):
  49. global _thread_local_tensor_tables
  50. _thread_local_tensor_tables.send_tables.append(tensor)
  51. tensor_index = len(_thread_local_tensor_tables.send_tables) - 1
  52. return (_InternalRPCPickler._tensor_receiver, (tensor_index,))
  53. @classmethod
  54. def _py_rref_receiver(cls, rref_fork_data):
  55. return dist.rpc.PyRRef._deserialize(rref_fork_data)
  56. def _py_rref_reducer(self, py_rref):
  57. rref_fork_data = py_rref._serialize()
  58. return (_InternalRPCPickler._py_rref_receiver, (rref_fork_data,))
  59. def _rref_reducer(self, rref):
  60. return self._py_rref_reducer(rref)
  61. @classmethod
  62. def _script_module_receiver(cls, script_module_serialized):
  63. """
  64. Given a serialized representation of a ScriptModule created with torch.jit.save,
  65. loads and returns the ScriptModule.
  66. """
  67. f = io.BytesIO(script_module_serialized)
  68. m = torch.jit.load(f)
  69. return m
  70. def _script_module_reducer(self, script_module):
  71. """
  72. Serializes a ScriptModule.
  73. """
  74. f = io.BytesIO()
  75. torch.jit.save(script_module, f)
  76. return (_InternalRPCPickler._script_module_receiver, (f.getvalue(),))
  77. def serialize(self, obj):
  78. r"""
  79. Serialize non tensor data into binary string, tensor data into
  80. tensor table
  81. """
  82. f = io.BytesIO()
  83. p = _pickler(f)
  84. p.dispatch_table = self._dispatch_table
  85. # rpc api could accept user picklers inheriting from _InternalRPCPickler to serialize rref,
  86. # user picklers could have different initialization function from _InternalRPCPickler,
  87. # but all the user picklers should call serialize() and use _rref_reducer to pickle rref
  88. # in python. also, when _internal_rpc_pickler is imported to rpc/api.py, rpc.RRef is not
  89. # compiled yet, it is not good place to access rpc.RRef inside _InternalRPCPickler constructor,
  90. # so putting rref's dispatch table here
  91. #
  92. # The return value of a `rpc.remote(..)` call is type of `rpc.PyRRef`.
  93. # The deserialized RRef object on an RPC receiver side is type of `rpc.PyRRef`.
  94. # Ignore type error because dispatch_table is defined in third-party package
  95. p.dispatch_table[dist.rpc.PyRRef] = self._py_rref_reducer # type: ignore[index]
  96. # An RRef created locally by RRef Python constructor is type of `rpc.RRef`.
  97. # Ignore type error because dispatch_table is defined in third-party package
  98. p.dispatch_table[dist.rpc.RRef] = self._rref_reducer # type: ignore[index]
  99. # Add dispatch pickling for ScriptModule or its subclass.
  100. if isinstance(obj, torch.jit.ScriptModule):
  101. # Ignore type error because dispatch_table is defined in third-party package
  102. p.dispatch_table[obj.__class__] = self._script_module_reducer # type: ignore[index]
  103. # Install customized picklers.
  104. for class_name in self._class_reducer_dict.keys():
  105. p.dispatch_table[class_name] = self._class_reducer_dict[class_name] # type: ignore[index]
  106. # save _thread_local_tensor_tables.send_tables if it is in nested call
  107. global _thread_local_tensor_tables
  108. if hasattr(_thread_local_tensor_tables, "send_tables"):
  109. old_send_tables = _thread_local_tensor_tables.send_tables
  110. else:
  111. old_send_tables = None
  112. _thread_local_tensor_tables.send_tables = []
  113. p.dump(obj)
  114. # restore _thread_local_tensor_tables.send_tables if return
  115. # from nested call, otherwise clean up the table
  116. tensors = _thread_local_tensor_tables.send_tables
  117. if old_send_tables is not None:
  118. _thread_local_tensor_tables.send_tables = old_send_tables
  119. else:
  120. del _thread_local_tensor_tables.send_tables
  121. return (f.getvalue(), tensors)
  122. def deserialize(self, binary_data, tensor_table):
  123. r"""
  124. Deserialize binary string + tensor table to original obj
  125. """
  126. # save _thread_local_tensor_tables.recv_tables if it is in nested call
  127. global _thread_local_tensor_tables
  128. if hasattr(_thread_local_tensor_tables, "recv_tables"):
  129. old_recv_tables = _thread_local_tensor_tables.recv_tables
  130. else:
  131. old_recv_tables = None
  132. _thread_local_tensor_tables.recv_tables = tensor_table
  133. try:
  134. unpickler = _unpickler(io.BytesIO(binary_data))
  135. ret = unpickler.load()
  136. except AttributeError as e:
  137. # Occurs when function is not found on module/class during
  138. # unpickling.
  139. except_str = (
  140. str(e)
  141. + """ Default RPC pickler does not serialize
  142. function code. Ensure that UDFs are defined on both caller and
  143. callee modules."""
  144. )
  145. ret = AttributeError(except_str)
  146. # Ensure the stack trace gets preserved
  147. ret.__cause__ = e
  148. # restore _thread_local_tensor_tables.recv_tables if return
  149. # from nested call, otherwise clean up the table
  150. if old_recv_tables is not None:
  151. _thread_local_tensor_tables.recv_tables = old_recv_tables
  152. else:
  153. del _thread_local_tensor_tables.recv_tables
  154. return ret
  155. # Create _internal_rpc_pickler only once to initialize _dispatch_table only once
  156. _internal_rpc_pickler = _InternalRPCPickler()
  157. def serialize(obj):
  158. return _internal_rpc_pickler.serialize(obj)
  159. def deserialize(binary_data, tensor_table):
  160. return _internal_rpc_pickler.deserialize(binary_data, tensor_table)
  161. def _run_function(python_udf):
  162. r"""
  163. This function is exclusively called from C++.
  164. See ``torch/csrc/distributed/rpc/python_rpc_handler.cpp``.
  165. Runs a Python UDF and returns its return value.
  166. Wraps any exception in ``RemoteException`` if the function raises.
  167. """
  168. try:
  169. if isinstance(python_udf, AttributeError):
  170. raise python_udf
  171. result = python_udf.func(*python_udf.args, **python_udf.kwargs)
  172. except Exception as e:
  173. # except str = exception info + traceback string
  174. except_str = (
  175. f"On {_get_current_rpc_agent().get_worker_info()}:\n"
  176. f"{repr(e)}\n{traceback.format_exc()}"
  177. )
  178. print(except_str, file=sys.stderr)
  179. result = RemoteException(except_str, type(e))
  180. return result
  181. def _handle_exception(result):
  182. if isinstance(result, RemoteException):
  183. exception_msg = result.msg.encode("utf-8").decode("unicode_escape")
  184. # We wrap exception re-creation here in case some exception classes
  185. # cannot be constructed directly from a string.
  186. exc = None
  187. try:
  188. exc = result.exception_type(exception_msg)
  189. except BaseException as e:
  190. raise RuntimeError( # noqa: B904
  191. f"Failed to create original exception type. Error msg was {str(e)}"
  192. f" Original exception on remote side was {exception_msg}"
  193. ) from e
  194. if exc is not None:
  195. raise exc
  196. def _build_rpc_profiling_key(
  197. exec_type, func_name, current_worker_name, dst_worker_name
  198. ):
  199. """
  200. Builds the key that RPC calls are profiled with using the autograd profiler.
  201. This will be the name of the corresponding Event recorded in the profiler.
  202. Args:
  203. exec_type (RPCExecMode): Type of RPC/RRef call
  204. func_name (str): Name of function being profiled.
  205. current_worker_name (str): Name of current worker.
  206. dst_worker_name (str): Name of the destination worker.
  207. Returns:
  208. String representing profiling key
  209. """
  210. profile_key = f"rpc_{exec_type.value}#{func_name}({current_worker_name} -> {dst_worker_name})"
  211. return profile_key
  212. def _start_record_function(exec_type, func_name, current_worker_name, dest_worker_name):
  213. """
  214. This function should be called from RPC/RRef functions to create a
  215. RecordFunction object for profiling. This function also runs the before
  216. callbacks that start the profiling, though the user is responsible for
  217. running the appropriate callbacks when the function to be profiled finishes.
  218. Args:
  219. exec_type (RPCExecMode): Type of RPC/RRef call
  220. func_name (str): Name of function being profiled.
  221. current_worker_name (str): Name of current worker.
  222. dest_worker_name (str): Name of the destination worker.
  223. Returns:
  224. An instance of `torch.autograd._RecordFunction`.
  225. """
  226. assert torch.autograd._profiler_enabled(), "Autograd profiler should be enabled."
  227. profile_key = f"rpc_{exec_type.value}#{str(func_name)}({current_worker_name} -> {dest_worker_name})"
  228. rf = torch.autograd._RecordFunction() # type: ignore[attr-defined]
  229. torch.autograd._run_before_callbacks(rf, profile_key) # type: ignore[attr-defined]
  230. return rf
  231. PythonUDF = collections.namedtuple("PythonUDF", ["func", "args", "kwargs"])
  232. RemoteException = collections.namedtuple("RemoteException", ["msg", "exception_type"])