utils.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. # mypy: allow-untyped-defs
  2. import cProfile
  3. import inspect
  4. import io
  5. import itertools
  6. import os
  7. import warnings
  8. from collections.abc import Callable, Sequence
  9. from contextlib import contextmanager
  10. from functools import wraps
  11. from pstats import Stats
  12. from typing import Any, cast, TypeVar
  13. import torch
  14. import torch.distributed as dist
  15. from torch.distributed._shard.sharded_tensor import ShardedTensor
  16. from torch.distributed._shard.sharded_tensor.shard import Shard
  17. from .api import (
  18. _is_wrapped_exception,
  19. _wrap_exception,
  20. CheckpointException,
  21. WRAPPED_EXCEPTION,
  22. )
  23. from .metadata import MetadataIndex, STATE_DICT_TYPE
  24. __all__ = ["find_tensor_shard", "find_state_dict_object"]
  25. T = TypeVar("T")
  26. R = TypeVar("R")
  27. def _get_failure_dict(
  28. results: list[T | WRAPPED_EXCEPTION],
  29. ) -> dict[int, WRAPPED_EXCEPTION]:
  30. return cast(
  31. dict[int, WRAPPED_EXCEPTION],
  32. {i: err for i, err in enumerate(results) if _is_wrapped_exception(err)},
  33. )
  34. def _all_gather_keys(
  35. local_dict: dict[str, Any], group: dist.ProcessGroup | None = None
  36. ) -> set[str]:
  37. """Gathers all keys, and returns them sorted."""
  38. keys = list(local_dict.keys())
  39. gathered_keys: list[list[str]] = [None] * dist.get_world_size(group) # type: ignore[list-item]
  40. dist.all_gather_object(gathered_keys, keys, group=group)
  41. return set(itertools.chain.from_iterable(gathered_keys))
  42. def _assert_same_keys(
  43. state_dict: dict[str, Any], process_group: dist.ProcessGroup | None = None
  44. ) -> None:
  45. """
  46. Asserts that all ranks have the same keys in their state dict.
  47. This is a collective call which requires all ranks in ``process_group`` to
  48. join. It will also induce cross-rank communication and block CPU.
  49. """
  50. if dist.get_world_size(process_group) == 1:
  51. return
  52. all_keys = _all_gather_keys(state_dict, process_group)
  53. my_keys = set(state_dict.keys())
  54. diff = all_keys - my_keys
  55. if len(diff) > 0:
  56. raise AssertionError(
  57. f"Key(s) present in other ranks but not this one, difference: {diff}"
  58. )
  59. class _DistWrapper:
  60. """
  61. This is a wrapper around PG that provides a series of features around object collectives.
  62. It works without distributed initialized, where most collectives turns into nops.
  63. All variants that take functions are exception robust, meaning that if one or more
  64. ranks raise errors, all ranks will observe those.
  65. """
  66. def __init__(
  67. self,
  68. group: dist.ProcessGroup | None,
  69. use_dist: bool,
  70. coordinator_rank: int,
  71. ):
  72. self.group = group
  73. self.use_dist = use_dist
  74. self.coordinator_rank = coordinator_rank
  75. if self.use_dist:
  76. self.global_coordinator_rank = (
  77. dist.get_global_rank(group, coordinator_rank)
  78. if group is not None
  79. else coordinator_rank
  80. )
  81. self.rank = dist.get_rank(group)
  82. self.is_coordinator = self.rank == coordinator_rank
  83. else:
  84. self.global_coordinator_rank = 0
  85. self.rank = 0
  86. self.is_coordinator = True
  87. def get_rank(self) -> int:
  88. return self.rank
  89. def get_world_size(self) -> int:
  90. if self.use_dist:
  91. return dist.get_world_size(self.group)
  92. return 1
  93. def broadcast_object(self, object: T | None) -> T:
  94. """Implement functionality similar to c10d::broadcast_object_list but without distributed enabled."""
  95. object_list = [object]
  96. if self.use_dist:
  97. dist.broadcast_object_list(
  98. object_list=object_list,
  99. group=self.group,
  100. src=self.global_coordinator_rank,
  101. )
  102. return cast(T, object_list[0])
  103. def gather_object(self, object: T) -> list[T] | None:
  104. """Implement functionality similar to c10d::gather_object but without distributed enabled."""
  105. if self.use_dist:
  106. gather_objs = (
  107. cast(list[T], [None] * dist.get_world_size(self.group))
  108. if self.is_coordinator
  109. else None
  110. )
  111. dist.gather_object(
  112. obj=object,
  113. object_gather_list=gather_objs if self.is_coordinator else None,
  114. dst=self.global_coordinator_rank,
  115. group=self.group,
  116. )
  117. result = gather_objs
  118. else:
  119. result = [object]
  120. return result
  121. def all_gather_object(self, object: T) -> list[T]:
  122. """Implement functionality similar to c10d::all_gather_object but without distributed enabled."""
  123. if self.use_dist:
  124. gather_objs = cast(list[T], [None] * dist.get_world_size(self.group))
  125. dist.all_gather_object(
  126. object_list=gather_objs, obj=object, group=self.group
  127. )
  128. else:
  129. gather_objs = [object]
  130. return gather_objs
  131. def scatter_object(self, object_list: list[T] | None) -> T:
  132. """Implement functionality similar to c10d::scatter_object but without distributed enabled."""
  133. if self.use_dist:
  134. gather_result = cast(list[T], [None])
  135. dist.scatter_object_list(
  136. scatter_object_output_list=gather_result,
  137. scatter_object_input_list=object_list if self.is_coordinator else None,
  138. src=self.global_coordinator_rank,
  139. group=self.group,
  140. )
  141. local_reply = gather_result[0]
  142. else:
  143. if object_list is None:
  144. raise AssertionError("object_list is None")
  145. local_reply = object_list[0]
  146. return local_reply
  147. def reduce_scatter(
  148. self,
  149. step: str,
  150. map_fun: Callable[[], T],
  151. reduce_fun: Callable[[list[T]], list[R]],
  152. ) -> R:
  153. """
  154. Compute a value on each rank, then do centralized reduce on a single rank, followed by a scatter.
  155. This method operates in the following way:
  156. Run ``map_fun`` on all ranks
  157. Gather results on rank 0
  158. Call ``reduce_fun`` on all those values
  159. Scatter to each rank part of the result.
  160. """
  161. local_data: WRAPPED_EXCEPTION | T
  162. try:
  163. local_data = map_fun()
  164. except BaseException as e: # noqa: B036
  165. local_data = _wrap_exception(e)
  166. all_data = self.gather_object(local_data)
  167. all_results: list[R | CheckpointException] | None = None
  168. if self.is_coordinator:
  169. if all_data is None:
  170. raise AssertionError("all_data is None")
  171. node_failures = _get_failure_dict(all_data)
  172. if len(node_failures) == 0:
  173. try:
  174. # N.B. why can't mypy cast List[R] to List[Union[R, WRAPPED_EXCEPTION]]?
  175. all_results = cast(
  176. list[R | CheckpointException],
  177. reduce_fun(cast(list[T], all_data)),
  178. )
  179. except BaseException as e: # noqa: B036
  180. node_failures[self.rank] = _wrap_exception(e)
  181. if len(node_failures) > 0:
  182. all_results = [
  183. CheckpointException(step, node_failures)
  184. ] * self.get_world_size()
  185. result = self.scatter_object(all_results)
  186. if isinstance(result, CheckpointException):
  187. raise result
  188. return result
  189. def all_reduce(
  190. self,
  191. step: str,
  192. map_fun: Callable[[], T],
  193. reduce_fun: Callable[[list[T]], R],
  194. ) -> R:
  195. """
  196. Compute a value on each rank, then do centralized reduce on a single rank, followed by a broadcast.
  197. This method operates in the following way:
  198. Run ``map_fun`` on all ranks
  199. Gather results on rank 0
  200. Call ``reduce_fun`` on all those values
  201. Broadcast the reduced value to all ranks.
  202. """
  203. local_data: T | WRAPPED_EXCEPTION
  204. try:
  205. local_data = map_fun()
  206. except BaseException as e: # noqa: B036
  207. local_data = _wrap_exception(e)
  208. all_data = self.gather_object(local_data)
  209. result: R | CheckpointException | None = None
  210. if self.is_coordinator:
  211. if all_data is None:
  212. raise AssertionError("all_data is None")
  213. node_failures = _get_failure_dict(all_data)
  214. if len(node_failures) == 0:
  215. try:
  216. result = reduce_fun(cast(list[T], all_data))
  217. except BaseException as e: # noqa: B036
  218. node_failures[self.rank] = _wrap_exception(e)
  219. if len(node_failures) > 0:
  220. result = CheckpointException(step, node_failures)
  221. # pyrefly: ignore [bad-argument-type]
  222. final_result = self.broadcast_object(result)
  223. if isinstance(final_result, CheckpointException):
  224. raise final_result
  225. return cast(R, final_result)
  226. def all_gather(
  227. self,
  228. step: str,
  229. map_fun: Callable[[], T],
  230. ) -> list[T]:
  231. """
  232. Compute a value on each rank, then all_gather them.
  233. This method operates in the following way:
  234. Run ``map_cp`` on all ranks
  235. all_gather the values to all ranks
  236. """
  237. result: T | WRAPPED_EXCEPTION
  238. try:
  239. result = map_fun()
  240. except BaseException as e: # noqa: B036
  241. result = _wrap_exception(e)
  242. all_results = self.all_gather_object(result)
  243. node_failures = _get_failure_dict(all_results)
  244. if len(node_failures) > 0:
  245. raise CheckpointException(step, node_failures)
  246. return cast(list[T], all_results)
  247. def broadcast(
  248. self,
  249. step: str,
  250. map_fun: Callable[[], T],
  251. ) -> T:
  252. """
  253. Compute a value on rank 0 and broadcast it.
  254. This method operates in the following way:
  255. Run ``map_cp`` on rank 0
  256. broadcast the value
  257. """
  258. result: T | CheckpointException | None = None
  259. if self.is_coordinator:
  260. try:
  261. result = map_fun()
  262. except BaseException as e: # noqa: B036
  263. result = CheckpointException(step, {self.rank: _wrap_exception(e)})
  264. # pyrefly: ignore [bad-argument-type]
  265. final_result = self.broadcast_object(result)
  266. if isinstance(final_result, CheckpointException):
  267. raise final_result
  268. return cast(T, final_result)
  269. def barrier(self) -> None:
  270. """
  271. Add a synchronization point across all processes when using distributed.
  272. If torch.distributed is initialized, this function will invoke a barrier across the global process group.
  273. If torch.distributed is not initialized, this function is a no-op.
  274. """
  275. if not self.use_dist:
  276. return
  277. dist.barrier(group=self.group)
  278. def _find_shard(tensor: ShardedTensor, index: MetadataIndex) -> Shard:
  279. if index.offset is None:
  280. raise ValueError(
  281. f"Cannot lookup {index.fqn} since its a ShardedTensor and no offset was provided"
  282. )
  283. shards = tensor.local_shards()
  284. # index fast path
  285. if index.index is not None:
  286. if (
  287. len(shards) > index.index
  288. and torch.Size(shards[index.index].metadata.shard_offsets) == index.offset
  289. ):
  290. return shards[index.index]
  291. for shard in shards:
  292. if torch.Size(shard.metadata.shard_offsets) == index.offset:
  293. return shard
  294. raise ValueError(f"Could not find shard at '{index.offset}' for FQN: '{index.fqn}'")
  295. def find_tensor_shard(tensor: torch.Tensor, index: MetadataIndex) -> torch.Tensor:
  296. if hasattr(tensor, "__get_tensor_shard__"):
  297. # DTensor implements _Checkpointable
  298. return tensor.__get_tensor_shard__(index) # type: ignore[attr-defined]
  299. if isinstance(tensor, ShardedTensor):
  300. return _find_shard(tensor, index).tensor
  301. if index.offset is not None:
  302. # special case looking up a tensor by origin
  303. if index.offset == torch.Size([0] * len(tensor.size())):
  304. return tensor
  305. raise ValueError(
  306. f"FQN: '{index.fqn}' is not a ShardedTensor, can't find by offset: '{index.offset}'"
  307. )
  308. return tensor
  309. def find_state_dict_object(state_dict: STATE_DICT_TYPE, index: MetadataIndex) -> Any:
  310. if index.fqn not in state_dict:
  311. raise ValueError(f"Could not find FQN: '{index.fqn}'")
  312. obj = state_dict[index.fqn]
  313. if isinstance(obj, torch.Tensor):
  314. return find_tensor_shard(obj, index)
  315. elif index.offset is not None:
  316. raise ValueError(
  317. f"FQN: '{index.fqn}' is not a ShardedTensor, can't find by offset: '{index.offset}'"
  318. )
  319. return obj
  320. def _element_wise_add(a: Sequence[int], b: Sequence[int]) -> list[int]:
  321. return [i_a + i_b for i_a, i_b in zip(a, b)]
  322. def _element_wise_sub(a: Sequence[int], b: Sequence[int]) -> list[int]:
  323. return [i_a - i_b for i_a, i_b in zip(a, b)]
  324. class _ReaderView(io.IOBase):
  325. def __init__(self, base_stream: io.IOBase, offset: int, len: int):
  326. super().__init__()
  327. self.offset = offset
  328. self.len = len
  329. self.base_stream = base_stream
  330. self.seek(0)
  331. def seek(self, offset: int, whence: int = os.SEEK_SET, /) -> int:
  332. if whence == os.SEEK_SET:
  333. offset = self.offset + offset
  334. elif whence == os.SEEK_END:
  335. whence = os.SEEK_SET
  336. offset = (self.offset + self.len) - offset
  337. return self.base_stream.seek(offset, whence)
  338. def tell(self) -> int:
  339. return self.base_stream.tell() - self.offset
  340. def readable(self) -> bool:
  341. return self.base_stream.readable()
  342. def seekable(self) -> bool:
  343. return self.base_stream.seekable()
  344. def readinto(self, b):
  345. max_size = self.len - self.tell()
  346. if max_size == 0:
  347. return 0
  348. if len(b) > max_size:
  349. b = memoryview(b)[:max_size]
  350. return self.base_stream.readinto(b) # type: ignore[attr-defined]
  351. def read(self, size=-1):
  352. max_size = self.len - self.tell()
  353. if size == -1 or size > max_size:
  354. size = max_size
  355. return self.base_stream.read(size)
  356. def _create_file_view(file: io.IOBase, offset: int, length: int) -> io.IOBase:
  357. # FIXME (kumpera) torch.load fails if we wrap with io.BufferedReader
  358. return _ReaderView(file, offset, length)
  359. def _normalize_device_info(device_type: str, device_id: int) -> str:
  360. """Device info normalization."""
  361. if device_type == "cpu":
  362. return "cpu"
  363. return f"{device_type}:{device_id}"
  364. # TODO: integrate with distributed logging flag
  365. ENABLE_PROFILE = False
  366. @contextmanager
  367. def _profile():
  368. # Only log the profiling when it is enable and is on rank0 or dist is not
  369. # available.
  370. if ENABLE_PROFILE and (not dist.is_available() or dist.get_rank() == 0):
  371. profiler = cProfile.Profile()
  372. profiler.enable()
  373. try:
  374. yield
  375. finally:
  376. profiler.disable()
  377. stats = Stats(profiler)
  378. stats.sort_stats("time").print_stats(10)
  379. else:
  380. yield
  381. def _api_bc_check(func):
  382. @wraps(func)
  383. def inner_func(*args, **kwargs) -> Any:
  384. if len(args) == 2:
  385. warnings.warn(
  386. f"The argument order of {func.__name__} has been changed. "
  387. "Please check the document to avoid future breakages.",
  388. stacklevel=2,
  389. )
  390. sig = inspect.signature(func)
  391. kwonlyargs = [
  392. p.name for p in sig.parameters.values() if p.kind == p.KEYWORD_ONLY
  393. ]
  394. if "storage_writer" in kwonlyargs:
  395. if "storage_writer" in kwargs:
  396. raise AssertionError(f"storage_writer in kwargs: {(args, kwargs)}")
  397. kwargs["storage_writer"] = args[1]
  398. elif "storage_reader" in kwonlyargs:
  399. if "storage_reader" in kwargs:
  400. raise AssertionError(f"storage_reader in kwargs: {(args, kwargs)}")
  401. kwargs["storage_reader"] = args[1]
  402. else:
  403. raise RuntimeError(f"Unexpected kwonlyargs = {kwonlyargs}")
  404. return func(args[0], **kwargs)
  405. else:
  406. return func(*args, **kwargs)
  407. return inner_func