dist_utils.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. # mypy: ignore-errors
  2. import re
  3. import sys
  4. import time
  5. from functools import partial, wraps
  6. from typing import Tuple
  7. import torch.distributed as dist
  8. import torch.distributed.rpc as rpc
  9. from torch.distributed.rpc import _rref_context_get_debug_info
  10. from torch.testing._internal.common_utils import FILE_SCHEMA, TEST_WITH_TSAN
  11. if not dist.is_available():
  12. print("c10d not available, skipping tests", file=sys.stderr)
  13. sys.exit(0)
  14. INIT_METHOD_TEMPLATE = FILE_SCHEMA + "{file_name}"
  15. def dist_init(
  16. old_test_method=None,
  17. setup_rpc: bool = True,
  18. clean_shutdown: bool = True,
  19. faulty_messages=None,
  20. messages_to_delay=None,
  21. ):
  22. """
  23. We use this decorator for setting up and tearing down state since
  24. MultiProcessTestCase runs each `test*` method in a separate process and
  25. each process just runs the `test*` method without actually calling
  26. 'setUp' and 'tearDown' methods of unittest.
  27. Note: pass the string representation of MessageTypes that should be used
  28. with the faulty agent's send function. By default, all retriable messages
  29. ("RREF_FORK_REQUEST", "RREF_CHILD_ACCEPT", "RREF_USER_DELETE",
  30. "CLEANUP_AUTOGRAD_CONTEXT_REQ") will use the faulty send (this default is
  31. set from faulty_rpc_agent_test_fixture.py).
  32. """
  33. # If we use dist_init without arguments (ex: @dist_init), old_test_method is
  34. # appropriately set and we return the wrapper appropriately. On the other
  35. # hand if dist_init has arguments (ex: @dist_init(clean_shutdown=False)),
  36. # old_test_method is None and we return a functools.partial which is the real
  37. # decorator that is used and as a result we recursively call dist_init with
  38. # old_test_method and the rest of the arguments appropriately set.
  39. if old_test_method is None:
  40. return partial(
  41. dist_init,
  42. setup_rpc=setup_rpc,
  43. clean_shutdown=clean_shutdown,
  44. faulty_messages=faulty_messages,
  45. messages_to_delay=messages_to_delay,
  46. )
  47. @wraps(old_test_method)
  48. def new_test_method(self, *arg, **kwargs):
  49. # Setting _ignore_rref_leak to make sure OwnerRRefs are properly deleted
  50. # in tests.
  51. import torch.distributed.rpc.api as api
  52. api._ignore_rref_leak = False
  53. self.worker_id = self.rank
  54. self.setup_fault_injection(faulty_messages, messages_to_delay)
  55. rpc_backend_options = self.rpc_backend_options
  56. if setup_rpc:
  57. if TEST_WITH_TSAN:
  58. # TSAN runs much slower.
  59. rpc_backend_options.rpc_timeout = rpc.constants.DEFAULT_RPC_TIMEOUT_SEC * 5
  60. rpc.constants.DEFAULT_SHUTDOWN_TIMEOUT = 60
  61. rpc.init_rpc(
  62. name="worker%d" % self.rank,
  63. backend=self.rpc_backend,
  64. rank=self.rank,
  65. world_size=self.world_size,
  66. rpc_backend_options=rpc_backend_options,
  67. )
  68. return_value = old_test_method(self, *arg, **kwargs)
  69. if setup_rpc:
  70. rpc.shutdown(graceful=clean_shutdown)
  71. return return_value
  72. return new_test_method
  73. def noop() -> None:
  74. pass
  75. def wait_until_node_failure(rank: int, expected_error_regex: str = ".*") -> str:
  76. """
  77. Loops until an RPC to the given rank fails. This is used to
  78. indicate that the node has failed in unit tests.
  79. Args:
  80. rank (int): Rank of the node expected to fail
  81. expected_error_regex (optional, str): Regex of exception message expected. Useful to ensure a specific failure
  82. occurs, not just any.
  83. """
  84. while True:
  85. try:
  86. rpc.rpc_sync(f"worker{rank}", noop, args=())
  87. time.sleep(0.1)
  88. except Exception as e:
  89. if re.search(pattern=expected_error_regex, string=str(e)):
  90. return str(e)
  91. def wait_until_pending_futures_and_users_flushed(timeout: int = 20) -> None:
  92. """
  93. The RRef protocol holds forkIds of rrefs in a map until those forks are
  94. confirmed by the owner. The message confirming the fork may arrive after
  95. our tests check whether this map is empty, which leads to failures and
  96. flaky tests. to_here also does not guarantee that we have finished
  97. processind the owner's confirmation message for the RRef. This function
  98. loops until the map is empty, which means the messages have been received
  99. as processed. Call this function before asserting the map returned by
  100. _get_debug_info is empty.
  101. """
  102. start = time.time()
  103. while True:
  104. debug_info = _rref_context_get_debug_info()
  105. num_pending_futures = int(debug_info["num_pending_futures"])
  106. num_pending_users = int(debug_info["num_pending_users"])
  107. if num_pending_futures == 0 and num_pending_users == 0:
  108. break
  109. time.sleep(0.1)
  110. if time.time() - start > timeout:
  111. raise ValueError(
  112. f"Timed out waiting to flush pending futures and users, "
  113. f"had {num_pending_futures} pending futures and {num_pending_users} pending users"
  114. )
  115. def get_num_owners_and_forks() -> Tuple[str, str]:
  116. """
  117. Retrieves number of OwnerRRefs and forks on this node from
  118. _rref_context_get_debug_info.
  119. """
  120. rref_dbg_info = _rref_context_get_debug_info()
  121. num_owners = rref_dbg_info["num_owner_rrefs"]
  122. num_forks = rref_dbg_info["num_forks"]
  123. return num_owners, num_forks
  124. def wait_until_owners_and_forks_on_rank(
  125. num_owners: int, num_forks: int, rank: int, timeout: int = 20
  126. ) -> None:
  127. """
  128. Waits until timeout for num_forks and num_owners to exist on the rank. Used
  129. to ensure proper deletion of RRefs in tests.
  130. """
  131. start = time.time()
  132. while True:
  133. num_owners_on_rank, num_forks_on_rank = rpc.rpc_sync(
  134. worker_name(rank), get_num_owners_and_forks, args=(), timeout=5
  135. )
  136. num_owners_on_rank = int(num_owners_on_rank)
  137. num_forks_on_rank = int(num_forks_on_rank)
  138. if num_owners_on_rank == num_owners and num_forks_on_rank == num_forks:
  139. return
  140. time.sleep(1)
  141. if time.time() - start > timeout:
  142. raise ValueError(
  143. f"Timed out waiting {timeout} sec for {num_owners} owners and {num_forks} forks on rank,"
  144. f" had {num_owners_on_rank} owners and {num_forks_on_rank} forks"
  145. )
  146. def initialize_pg(init_method, rank: int, world_size: int) -> None:
  147. # This is for tests using `dist.barrier`.
  148. if not dist.is_initialized():
  149. dist.init_process_group(
  150. backend="gloo",
  151. init_method=init_method,
  152. rank=rank,
  153. world_size=world_size,
  154. )
  155. def worker_name(rank: int) -> str:
  156. return f"worker{rank}"
  157. def get_function_event(function_events, partial_event_name):
  158. """
  159. Returns the first event that matches partial_event_name in the provided
  160. function_events. These function_events should be the output of
  161. torch.autograd.profiler.function_events().
  162. Args:
  163. function_events: function_events returned by the profiler.
  164. event_name (str): partial key that the event was profiled with.
  165. """
  166. event = [event for event in function_events if partial_event_name in event.name][0] # noqa: RUF015
  167. return event