collective_utils.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. #!/usr/bin/env python3
  2. """
  3. A set of primitive functions for performing collective ops.
  4. Each should also handle single rank scenario.
  5. """
  6. from __future__ import annotations
  7. from dataclasses import dataclass
  8. from typing import Any, Callable, cast, Generic, List, Optional, Tuple, TypeVar, Union
  9. import torch.distributed as dist
  10. T = TypeVar("T")
  11. @dataclass
  12. class SyncPayload(Generic[T]):
  13. stage_name: Optional[str]
  14. success: bool
  15. payload: T
  16. exception: Optional[Exception] = None
  17. def broadcast(
  18. data_or_fn: Union[T, Callable[[], T]],
  19. *,
  20. success: bool = True,
  21. stage_name: Optional[str] = None,
  22. rank: int = 0,
  23. pg: Optional[dist.ProcessGroup] = None,
  24. ) -> T:
  25. """
  26. Broadcasts the data payload from rank 0 to all other ranks.
  27. Or if a function is passed, execute it in rank 0 and broadcast result to all other ranks.
  28. Can be used to broadcast a failure signal to stop all ranks.
  29. If the function raises an exception, all ranks will raise.
  30. Args:
  31. data_or_fn: the data to broadcast or function to execute and broadcast result.
  32. success: False to stop all ranks.
  33. stage_name: the name of the logical stage for synchronization and debugging
  34. rank: rank to broadcast data or execute function and broadcast resutls.
  35. pg: the process group for sync
  36. Throws:
  37. RuntimeError from original exception trace
  38. Returns:
  39. the value after synchronization
  40. Example usage:
  41. >> id = broadcast(data_or_fn=allocate_id, rank=0, pg=ext_pg.my_pg)
  42. """
  43. if not success and data_or_fn is not None:
  44. raise AssertionError("Data or Function is expected to be None if not successful")
  45. payload: Optional[T] = None
  46. exception : Optional[Exception] = None
  47. # if no pg is passed then execute if rank is 0
  48. if (pg is None and rank == 0) or (pg is not None and pg.rank() == rank):
  49. # determine if it is an executable function or data payload only
  50. if callable(data_or_fn):
  51. try:
  52. payload = data_or_fn()
  53. except Exception as e:
  54. success = False
  55. exception = e
  56. else:
  57. payload = data_or_fn
  58. # broadcast the exception type if any to all ranks for failure categorization
  59. sync_obj = SyncPayload(
  60. stage_name=stage_name,
  61. success=success,
  62. payload=payload,
  63. exception=exception,
  64. )
  65. if pg is not None:
  66. broadcast_list = [sync_obj]
  67. dist.broadcast_object_list(broadcast_list, src=rank, group=pg)
  68. assert len(broadcast_list) == 1
  69. sync_obj = broadcast_list[0]
  70. # failure in any rank will trigger a throw in every rank.
  71. if not sync_obj.success:
  72. error_msg = f"Rank {rank} failed"
  73. if stage_name is not None:
  74. error_msg += f": stage {sync_obj.stage_name}"
  75. if sync_obj.exception is not None:
  76. error_msg += f": exception {sync_obj.exception}"
  77. raise RuntimeError(error_msg) from sync_obj.exception
  78. return cast(T, sync_obj.payload)
  79. def all_gather(
  80. data_or_fn: Union[T, Callable[[], T]],
  81. stage_name: Optional[str] = None,
  82. pg: Optional[dist.ProcessGroup] = None,
  83. ) -> List[T]:
  84. """
  85. A simple all_gather primitive with basic synchronization guard logic,
  86. by checking payload from all ranks has the same stage name.
  87. Args:
  88. data_or_fn: the data to be all gathered across ranks or function to be executed
  89. stage_name: the sync stage name for out-of-sync protection
  90. pg: the process group for sync
  91. Throws:
  92. RuntimeError from original exception trace
  93. Returns:
  94. a list of synced data from all ranks
  95. Example usage:
  96. >> all_ids = all_gather(data_or_fn=allocate_id, pg=ext_pg.my_pg)
  97. """
  98. payload: Optional[T] = None
  99. exception : Optional[Exception] = None
  100. success = True
  101. # determine if it is an executable function or data payload only
  102. if callable(data_or_fn):
  103. try:
  104. payload = data_or_fn()
  105. except Exception as e:
  106. success = False
  107. exception = e
  108. else:
  109. payload = data_or_fn
  110. sync_obj = SyncPayload(
  111. stage_name=stage_name,
  112. success=success,
  113. payload=payload,
  114. exception=exception,
  115. )
  116. if pg is not None:
  117. # List of success/failure across all ranks.
  118. total_list = [None] * dist.get_world_size(pg)
  119. all_gather_object_enforce_type(pg, total_list, sync_obj)
  120. # Each rank will throw RuntimeError in case of failure on any rank.
  121. stage_name = cast(SyncPayload[T], total_list[0]).stage_name
  122. exception_list: List[Tuple[int, Exception]] = []
  123. ret_list: List[T] = []
  124. error_msg: str = ""
  125. for i, sp in enumerate(cast(List[SyncPayload[T]], total_list)):
  126. if sp.stage_name != stage_name:
  127. error_msg += (
  128. f"Unexpected stage name received from rank {i}: {sp.stage_name} "
  129. )
  130. continue
  131. if not sp.success and sp.exception is not None:
  132. exception_list.append((i, sp.exception))
  133. continue
  134. ret_list.append(sp.payload)
  135. if len(exception_list) > 0:
  136. raise RuntimeError( # type: ignore[misc]
  137. error_msg, exception_list) from exception_list[0]
  138. return ret_list
  139. else:
  140. if not sync_obj.success:
  141. raise RuntimeError(
  142. f"all_gather failed with exception {sync_obj.exception}",
  143. ) from sync_obj.exception
  144. return [sync_obj.payload] # type: ignore[list-item]
  145. # Note: use Any for typing for now so users can pass in
  146. # either a list of None or target type placeholders
  147. # otherwise pyre would complain
  148. def all_gather_object_enforce_type(
  149. pg: dist.ProcessGroup,
  150. # pyre-fixme[2]: Parameter must have a type that does not contain `Any`
  151. object_list: List[Any],
  152. # pyre-fixme[2]: Parameter must have a type other than `Any`
  153. obj: Any,
  154. # pyre-fixme[2]: Parameter must have a type that does not contain `Any`
  155. type_checker: Callable[[Any, Any], bool] = lambda x, y: type(x) == type(y),
  156. ) -> None:
  157. """
  158. Similar to plain all_gather_object but with additional type checking
  159. AFTER gather is done to ensure basic consistency.
  160. If check does not pass, all ranks will fail with exception.
  161. This is generally to prevent conditional logic leading to
  162. unexpected messages being received. This is considered fatal code error,
  163. but due to logic stacks this might happen implicitly in practice.
  164. The default check does not check sub type (considered different)
  165. or covariance (considered same) but users can pass in custom checker
  166. if more complicated check is needed.
  167. """
  168. dist.all_gather_object(object_list, obj, group=pg)
  169. # conservative check
  170. list_len = len(object_list)
  171. if list_len == 0:
  172. return
  173. first_obj = object_list[0]
  174. for i in range(1, list_len):
  175. if not type_checker(first_obj, object_list[i]):
  176. raise TypeError(
  177. f"Object type at index {i} is {type(object_list[i])}, "
  178. f"while first object type is {type(first_obj)}"
  179. )