collective_utils.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. import importlib
  8. import logging
  9. from collections import defaultdict
  10. from dataclasses import dataclass
  11. from typing import Any, Callable, cast, Generic, Optional, TYPE_CHECKING, TypeVar, Union
  12. if TYPE_CHECKING:
  13. from collections.abc import Iterable
  14. import torch
  15. import torch.distributed as dist
  16. __all__: list[str] = [
  17. "SyncPayload",
  18. "broadcast",
  19. "all_gather",
  20. "all_gather_object_enforce_type",
  21. ]
  22. logger = logging.getLogger(__name__)
  23. T = TypeVar("T")
  24. @dataclass
  25. class SyncPayload(Generic[T]):
  26. stage_name: Optional[str]
  27. success: bool
  28. payload: T
  29. exception: Optional[Exception] = None
  30. def broadcast(
  31. data_or_fn: Union[T, Callable[[], T]],
  32. *,
  33. success: bool = True,
  34. stage_name: Optional[str] = None,
  35. rank: int = 0,
  36. pg: Optional[dist.ProcessGroup] = None,
  37. ) -> T:
  38. """
  39. Broadcasts the data payload from rank 0 to all other ranks.
  40. Or if a function is passed, execute it in rank 0 and broadcast result to all other ranks.
  41. Can be used to broadcast a failure signal to stop all ranks.
  42. If the function raises an exception, all ranks will raise.
  43. Args:
  44. data_or_fn: the data to broadcast or function to execute and broadcast result.
  45. success: False to stop all ranks.
  46. stage_name: the name of the logical stage for synchronization and debugging
  47. rank: rank to broadcast data or execute function and broadcast results.
  48. pg: the process group for sync
  49. Throws:
  50. RuntimeError from original exception trace
  51. Returns:
  52. the value after synchronization
  53. Example usage:
  54. >> id = broadcast(data_or_fn=allocate_id, rank=0, pg=ext_pg.my_pg)
  55. """
  56. if not success and data_or_fn is not None:
  57. raise AssertionError(
  58. "Data or Function is expected to be None if not successful"
  59. )
  60. payload: Optional[T] = None
  61. exception: Optional[Exception] = None
  62. # if no pg is passed then execute if rank is 0
  63. if (pg is None and rank == 0) or (pg is not None and pg.rank() == rank):
  64. # determine if it is an executable function or data payload only
  65. if callable(data_or_fn):
  66. try:
  67. payload = data_or_fn()
  68. except Exception as e:
  69. success = False
  70. exception = e
  71. else:
  72. payload = data_or_fn
  73. # broadcast the exception type if any to all ranks for failure categorization
  74. sync_obj = SyncPayload(
  75. stage_name=stage_name,
  76. success=success,
  77. payload=payload,
  78. exception=exception,
  79. )
  80. if pg is not None:
  81. broadcast_list = [sync_obj]
  82. dist.broadcast_object_list(broadcast_list, src=rank, group=pg)
  83. assert len(broadcast_list) == 1
  84. sync_obj = broadcast_list[0]
  85. # failure in any rank will trigger a throw in every rank.
  86. if not sync_obj.success:
  87. error_msg = f"Rank {rank} failed"
  88. if stage_name is not None:
  89. error_msg += f": stage {sync_obj.stage_name}"
  90. if sync_obj.exception is not None:
  91. error_msg += f": exception {sync_obj.exception}"
  92. raise RuntimeError(error_msg) from sync_obj.exception
  93. return cast(T, sync_obj.payload)
  94. def all_gather(
  95. data_or_fn: Union[T, Callable[[], T]],
  96. stage_name: Optional[str] = None,
  97. pg: Optional[dist.ProcessGroup] = None,
  98. ) -> list[T]:
  99. """
  100. A simple all_gather primitive with basic synchronization guard logic,
  101. by checking payload from all ranks has the same stage name.
  102. Args:
  103. data_or_fn: the data to be all gathered across ranks or function to be executed
  104. stage_name: the sync stage name for out-of-sync protection
  105. pg: the process group for sync
  106. Throws:
  107. RuntimeError from original exception trace
  108. Returns:
  109. a list of synced data from all ranks
  110. Example usage:
  111. >> all_ids = all_gather(data_or_fn=allocate_id, pg=ext_pg.my_pg)
  112. """
  113. payload: Optional[T] = None
  114. exception: Optional[Exception] = None
  115. success = True
  116. # determine if it is an executable function or data payload only
  117. if callable(data_or_fn):
  118. try:
  119. payload = data_or_fn()
  120. except Exception as e:
  121. success = False
  122. exception = e
  123. else:
  124. payload = data_or_fn
  125. sync_obj = SyncPayload(
  126. stage_name=stage_name,
  127. success=success,
  128. payload=payload,
  129. exception=exception,
  130. )
  131. if pg is not None:
  132. # List of success/failure across all ranks.
  133. total_list = [None] * dist.get_world_size(pg)
  134. all_gather_object_enforce_type(pg, total_list, sync_obj)
  135. # Each rank will throw RuntimeError in case of failure on any rank.
  136. stage_name = cast(SyncPayload[T], total_list[0]).stage_name
  137. exception_list: list[tuple[int, Exception]] = []
  138. ret_list: list[T] = []
  139. error_msg: str = ""
  140. for i, sp in enumerate(cast(list[SyncPayload[T]], total_list)):
  141. if sp.stage_name != stage_name:
  142. error_msg += (
  143. f"Unexpected stage name received from rank {i}: {sp.stage_name} "
  144. )
  145. continue
  146. if not sp.success and sp.exception is not None:
  147. exception_list.append((i, sp.exception))
  148. continue
  149. ret_list.append(sp.payload)
  150. if len(exception_list) > 0:
  151. raise RuntimeError( # type: ignore[misc]
  152. error_msg, exception_list
  153. ) from exception_list[0]
  154. return ret_list
  155. else:
  156. if not sync_obj.success:
  157. raise RuntimeError(
  158. f"all_gather failed with exception {sync_obj.exception}",
  159. ) from sync_obj.exception
  160. return [sync_obj.payload] # type: ignore[list-item]
  161. # Note: use Any for typing for now so users can pass in
  162. # either a list of None or target type placeholders
  163. # otherwise pyre would complain
  164. def all_gather_object_enforce_type(
  165. pg: dist.ProcessGroup,
  166. # pyre-fixme[2]: Parameter must have a type that does not contain `Any`
  167. object_list: list[Any],
  168. # pyre-fixme[2]: Parameter must have a type other than `Any`
  169. obj: Any,
  170. # pyre-fixme[2]: Parameter must have a type that does not contain `Any`
  171. type_checker: Callable[[Any, Any], bool] = lambda x, y: type(x) == type(y),
  172. ) -> None:
  173. """
  174. Similar to plain all_gather_object but with additional type checking
  175. AFTER gather is done to ensure basic consistency.
  176. If check does not pass, all ranks will fail with exception.
  177. This is generally to prevent conditional logic leading to
  178. unexpected messages being received. This is considered fatal code error,
  179. but due to logic stacks this might happen implicitly in practice.
  180. The default check does not check sub type (considered different)
  181. or covariance (considered same) but users can pass in custom checker
  182. if more complicated check is needed.
  183. """
  184. dist.all_gather_object(object_list, obj, group=pg)
  185. # conservative check
  186. list_len = len(object_list)
  187. if list_len == 0:
  188. return
  189. first_obj = object_list[0]
  190. for i in range(1, list_len):
  191. if not type_checker(first_obj, object_list[i]):
  192. raise TypeError(
  193. f"Object type at index {i} is {type(object_list[i])}, "
  194. f"while first object type is {type(first_obj)}"
  195. )
  196. def _summarize_ranks(ranks: Iterable[int]) -> str:
  197. ranks = sorted(ranks)
  198. assert min(ranks) >= 0, "ranks should all be positive"
  199. assert len(set(ranks)) == len(ranks), "ranks should not contain duplicates"
  200. curr: Optional[Union[int, range]] = None
  201. ranges = []
  202. while ranks:
  203. x = ranks.pop(0)
  204. if curr is None:
  205. curr = x
  206. elif isinstance(curr, int):
  207. if x == curr + 1:
  208. curr = range(curr, x + 1, 1)
  209. else:
  210. step = x - curr
  211. curr = range(curr, x + step, step)
  212. else:
  213. assert isinstance(curr, range)
  214. if x == curr.stop:
  215. curr = range(curr.start, curr.stop + curr.step, curr.step)
  216. else:
  217. ranges.append(curr)
  218. curr = x
  219. if isinstance(curr, int):
  220. ranges.append(range(curr, curr + 1, 1))
  221. elif isinstance(curr, range):
  222. ranges.append(curr)
  223. result = []
  224. for r in ranges:
  225. if len(r) == 1:
  226. result.append(f"{r.start}")
  227. elif r.step == 1:
  228. result.append(f"{r.start}:{r.stop}")
  229. else:
  230. result.append(f"{r.start}:{r.stop}:{r.step}")
  231. return ",".join(result)
  232. def _check_philox_rng_sync(
  233. generator: torch.Generator, group: dist.ProcessGroup
  234. ) -> tuple[dict[Any, set], str]:
  235. local_state = generator.get_state()
  236. all_states = [torch.empty_like(local_state) for _ in range(group.size())]
  237. torch.distributed.all_gather(all_states, local_state)
  238. seeds_offsets = [
  239. (state[:8].view(torch.uint64).item(), state[8:].view(torch.uint64).item())
  240. for state in all_states
  241. ]
  242. seed_offset_ranks = defaultdict(set)
  243. for rank, (seed, offset) in enumerate(seeds_offsets):
  244. seed_offset_ranks[(seed, offset)].add(rank)
  245. return seed_offset_ranks, "(Seed, Offset)"
  246. def _check_cpu_rng_sync(
  247. generator: torch.Generator, group: dist.ProcessGroup
  248. ) -> tuple[dict[Any, set], str]:
  249. # seed is returned as uint64_t from C impl, so may not fit in torch int64 tensor directly.
  250. state_tensor = generator.get_state()
  251. all_state_tensors = [torch.empty_like(state_tensor) for _ in range(group.size())]
  252. torch.distributed.all_gather(all_state_tensors, state_tensor)
  253. state_ranks = defaultdict(set)
  254. for rank, state_tensor in enumerate(all_state_tensors):
  255. # Summarize the state vector of the CPU rng.
  256. # The properties that matter most are (1) its different if there is a state difference, (2) its printable
  257. # (see desync table- not viable to print whole state vector of size 5k)
  258. state_ranks[torch.hash_tensor(state_tensor).item()].add(rank)
  259. return state_ranks, "Generator state hash"
  260. def _check_rng_sync_internal(
  261. generator: torch.Generator, group: dist.ProcessGroup
  262. ) -> tuple[dict[Any, set], str]:
  263. if generator.device.type == "cuda":
  264. return _check_philox_rng_sync(generator, group)
  265. elif generator.device.type == "cpu":
  266. return _check_cpu_rng_sync(generator, group)
  267. else:
  268. raise NotImplementedError(
  269. f"Unsupported generator device: {generator.device.type}"
  270. )
  271. def _desync_table_str(tag: str, value_ranks: dict[Any, set[int]]) -> str:
  272. headers = ["Ranks", f"{tag} values"]
  273. rank_values = [
  274. [_summarize_ranks(ranks), str(value)] for value, ranks in value_ranks.items()
  275. ]
  276. if importlib.util.find_spec("tabulate"):
  277. from tabulate import tabulate
  278. return tabulate(rank_values, headers=headers)
  279. row_str = "\n".join([str(row) for row in rank_values])
  280. return str(f"{headers}\n{row_str}")
  281. def _check_rng_sync(
  282. generator: torch.Generator, group: dist.ProcessGroup
  283. ) -> Optional[str]:
  284. value_ranks, value_header = _check_rng_sync_internal(generator, group)
  285. log_str = None
  286. if len(value_ranks) > 1:
  287. log_str = f"Generator desync detected:\n{_desync_table_str(value_header, value_ranks)}"
  288. logger.error(log_str)
  289. return log_str