collective_utils.py 12 KB

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