utils.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. # mypy: allow-untyped-defs
  2. import dataclasses
  3. import traceback
  4. from collections import OrderedDict
  5. from collections.abc import Container
  6. from typing import Any, Callable, Optional, overload, TypeVar
  7. import torch
  8. import torch.distributed as dist
  9. from torch import nn
  10. from torch.nn.utils.rnn import PackedSequence
  11. __all__ = [] # type: ignore[var-annotated]
  12. def _pack_kwargs(*args: Any, **kwargs: Any) -> tuple[tuple[Any, ...], tuple[str, ...]]:
  13. """
  14. Turn argument list into separate key list and value list (unpack_kwargs does the opposite).
  15. Inspiration: https://github.com/facebookresearch/fairscale/blob/eeb6684/fairscale/internal/containers.py#L70
  16. Usage::
  17. kwarg_keys, flat_args = pack_kwargs(1, 2, a=3, b=4)
  18. assert kwarg_keys == ("a", "b")
  19. assert flat_args == (1, 2, 3, 4)
  20. args, kwargs = unpack_kwargs(kwarg_keys, flat_args)
  21. assert args == (1, 2)
  22. assert kwargs == {"a": 3, "b": 4}
  23. Returns:
  24. Tuple[Tuple[Any, ...], Tuple[str, ...]]: The first tuple element gives
  25. gives both positional args and kwarg values, where the positional args
  26. proceed kwarg values and kwarg values are ordered consistently with the
  27. kwarg keys. The second tuple element gives the kwarg keys.
  28. The second tuple element's length is at most the first tuple element's length.
  29. """
  30. kwarg_keys: list[str] = []
  31. flat_args: list[Any] = list(args)
  32. for k, v in kwargs.items():
  33. kwarg_keys.append(k)
  34. flat_args.append(v)
  35. return tuple(flat_args), tuple(kwarg_keys)
  36. def _cast_forward_inputs(
  37. dtype: Optional[torch.dtype],
  38. *args: Any,
  39. **kwargs: Any,
  40. ) -> tuple[Any, Any]:
  41. """
  42. Cast floating point tensors in ``args`` and ``kwargs`` to ``input_dtype``.
  43. This respects the existing ``requires_grad`` on the tensors.
  44. """
  45. if dtype is None:
  46. return args, kwargs
  47. def cast_fn(x: torch.Tensor) -> torch.Tensor:
  48. if not torch.is_floating_point(x) or x.dtype == dtype:
  49. return x
  50. return x.to(dtype)
  51. return (_apply_to_tensors(cast_fn, args), _apply_to_tensors(cast_fn, kwargs))
  52. def _unpack_kwargs(
  53. flat_args: tuple[Any, ...], kwarg_keys: tuple[str, ...]
  54. ) -> tuple[tuple[Any, ...], dict[str, Any]]:
  55. """See _pack_kwargs."""
  56. assert len(kwarg_keys) <= len(flat_args), (
  57. f"too many keys {len(kwarg_keys)} vs. {len(flat_args)}"
  58. )
  59. if len(kwarg_keys) == 0:
  60. return flat_args, {}
  61. args = flat_args[: -len(kwarg_keys)]
  62. kwargs = dict(zip(kwarg_keys, flat_args[-len(kwarg_keys) :]))
  63. return args, kwargs
  64. S = TypeVar("S", dict, list, tuple)
  65. T = TypeVar("T", torch.Tensor, PackedSequence)
  66. @overload
  67. def _recursive_to(
  68. inputs: S, target_device: torch.device, use_side_stream_for_tensor_copies: bool
  69. ) -> list[S]: ...
  70. @overload
  71. def _recursive_to(
  72. inputs: T, target_device: torch.device, use_side_stream_for_tensor_copies: bool
  73. ) -> tuple[T]: ...
  74. def _recursive_to(inputs, target_device, use_side_stream_for_tensor_copies):
  75. r"""Recursively moves input to the target_device."""
  76. def to_map(obj):
  77. if isinstance(obj, (torch.Tensor, PackedSequence)):
  78. device = obj.data.device if isinstance(obj, PackedSequence) else obj.device
  79. if device == target_device:
  80. return (obj,)
  81. if not use_side_stream_for_tensor_copies:
  82. return (obj.to(target_device),)
  83. else:
  84. # If the custom module is not registered to torch, stream is not used for acceleration
  85. if device.type == "cpu":
  86. return (obj.to(target_device),)
  87. from torch.nn.parallel._functions import _get_stream
  88. # Perform CPU -> target_device copies in a background stream. This code is
  89. # motivated from similar logic in torch/nn/parallel/_functions.py
  90. stream = _get_stream(target_device)
  91. with stream:
  92. output = obj.to(target_device)
  93. # synchronize with the copy stream
  94. with torch.accelerator.device_index(target_device.index):
  95. current_stream = torch.accelerator.current_stream()
  96. # Sync the current stream with the copy stream
  97. current_stream.wait_stream(stream)
  98. # Ensure tensor memory is not reused until work on
  99. # main stream is complete
  100. if isinstance(obj, PackedSequence):
  101. output.data.record_stream(current_stream) # type: ignore[arg-type]
  102. else:
  103. assert isinstance(output, torch.Tensor)
  104. output.record_stream(current_stream) # type: ignore[arg-type]
  105. return (output,)
  106. from torch.nn.parallel.scatter_gather import _is_namedtuple
  107. if _is_namedtuple(obj):
  108. return [type(obj)(*args) for args in zip(*map(to_map, obj))]
  109. if isinstance(obj, tuple) and len(obj) > 0:
  110. return list(zip(*map(to_map, obj)))
  111. if isinstance(obj, list) and len(obj) > 0:
  112. return [list(i) for i in zip(*map(to_map, obj))]
  113. if isinstance(obj, dict) and len(obj) > 0:
  114. return [type(obj)(i) for i in zip(*map(to_map, obj.items()))]
  115. return [obj]
  116. # Avoid reference cycle
  117. try:
  118. res = to_map(inputs)
  119. finally:
  120. to_map = None # type: ignore[assignment]
  121. return res
  122. def _p_assert(cond: Any, s: str, raise_assertion_error: bool = True) -> None:
  123. """Alternate to ``assert`` when in the backward context to print the error message ``s`` since otherwise, it is swallowed."""
  124. if not cond:
  125. print(s)
  126. traceback.print_stack()
  127. if raise_assertion_error:
  128. raise AssertionError(s)
  129. def _alloc_storage(tensor: torch.Tensor, size: torch.Size) -> None:
  130. """
  131. Allocate storage for ``tensor`` with the given size.
  132. Returns:
  133. bool: ``True`` if this method allocated storage and ``False`` if the
  134. storage was already allocated.
  135. """
  136. with torch.no_grad():
  137. if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
  138. already_allocated = tensor._typed_storage()._size() == size.numel()
  139. if not already_allocated:
  140. tensor_storage_size = tensor._typed_storage()._size()
  141. _p_assert(
  142. tensor_storage_size == 0,
  143. "Tensor storage should have been resized to be 0 but got PLACEHOLDEr",
  144. )
  145. tensor._typed_storage()._resize_(size.numel())
  146. def _free_storage(tensor: torch.Tensor):
  147. """
  148. Frees the underlying storage of ``tensor``.
  149. Returns:
  150. bool: ``True`` if the method freed the storage and ``False`` if the
  151. storage was already freed.
  152. """
  153. with torch.no_grad():
  154. if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
  155. already_freed = tensor._typed_storage()._size() == 0
  156. if not already_freed:
  157. _p_assert(
  158. tensor.storage_offset() == 0,
  159. "Freeing a tensor's storage is unsafe when it is not the sole occupant\n"
  160. f"storage offset: {tensor.storage_offset()}\n"
  161. f"storage size: {tensor._typed_storage()._size()}\n"
  162. f"tensor shape: {tensor.shape}",
  163. )
  164. tensor._typed_storage()._resize_(0)
  165. Q = TypeVar("Q")
  166. R = TypeVar("R", dict, list, tuple, set, OrderedDict, PackedSequence, Any)
  167. @overload
  168. def _apply_to_tensors(
  169. fn: Callable[[torch.Tensor], Q], container: torch.Tensor
  170. ) -> Q: ...
  171. @overload
  172. def _apply_to_tensors(fn: Callable[[torch.Tensor], Any], container: R) -> R: ...
  173. def _apply_to_tensors(fn, container):
  174. """Recursively apply to all tensor in different kinds of container types."""
  175. def apply(x):
  176. from torch.nn.parallel.scatter_gather import _is_namedtuple
  177. if isinstance(x, torch.Tensor):
  178. return fn(x)
  179. elif hasattr(x, "__dataclass_fields__"):
  180. dc = dataclasses.replace(x)
  181. changes = {
  182. f.name: apply(getattr(dc, f.name)) for f in dataclasses.fields(dc)
  183. }
  184. return dataclasses.replace(dc, **changes)
  185. elif isinstance(x, OrderedDict):
  186. od = x.__class__()
  187. for key, value in x.items():
  188. od[key] = apply(value)
  189. return od
  190. elif isinstance(x, PackedSequence):
  191. apply(x.data)
  192. return x
  193. elif isinstance(x, dict):
  194. return {key: apply(value) for key, value in x.items()}
  195. elif _is_namedtuple(x):
  196. res = (apply(el) for el in x)
  197. return type(x)(*res)
  198. elif isinstance(x, (list, tuple, set)):
  199. return type(x)(apply(el) for el in x)
  200. else:
  201. return x
  202. return apply(container)
  203. def _to_kwargs(
  204. inputs: tuple[Any, ...],
  205. kwargs: Optional[dict[str, Any]],
  206. target_device: torch.device,
  207. use_side_stream_for_tensor_copies: bool,
  208. ) -> tuple[tuple[Any, ...], tuple[dict[str, Any], ...]]:
  209. moved_inputs = (
  210. _recursive_to(inputs, target_device, use_side_stream_for_tensor_copies)
  211. if inputs
  212. else []
  213. )
  214. moved_kwargs = (
  215. _recursive_to(kwargs, target_device, use_side_stream_for_tensor_copies)
  216. if kwargs
  217. else []
  218. )
  219. if len(moved_inputs) < len(moved_kwargs):
  220. moved_inputs.extend([() for _ in range(len(moved_kwargs) - len(inputs))])
  221. elif len(moved_kwargs) < len(moved_inputs):
  222. moved_kwargs.extend([{} for _ in range(len(moved_inputs) - len(moved_kwargs))])
  223. return tuple(moved_inputs), tuple(moved_kwargs)
  224. def _verify_param_shape_across_processes(
  225. process_group: dist.ProcessGroup,
  226. tensors: list[torch.Tensor],
  227. logger: Optional["dist.Logger"] = None,
  228. ):
  229. return dist._verify_params_across_processes(process_group, tensors, logger)
  230. def _sync_module_states(
  231. module: nn.Module,
  232. process_group: dist.ProcessGroup,
  233. broadcast_bucket_size: int,
  234. src: int,
  235. params_and_buffers_to_ignore: Container[str],
  236. broadcast_buffers: bool = True,
  237. ) -> None:
  238. """
  239. Sync ``module``'s parameters and buffers state.
  240. Syncs ``module``'s parameters and buffers state so that all ranks contain
  241. the same module state across all ranks. Note that this API assumes that all
  242. parameter shapes are consistent before running the synchronization. This can
  243. be checked with ``_verify_param_shape_across_processes``.
  244. """
  245. module_states: list[torch.Tensor] = []
  246. for name, param in module.named_parameters():
  247. if name not in params_and_buffers_to_ignore:
  248. module_states.append(param.detach())
  249. if broadcast_buffers:
  250. for name, buffer in module.named_buffers():
  251. if name not in params_and_buffers_to_ignore:
  252. module_states.append(buffer.detach())
  253. _sync_params_and_buffers(process_group, module_states, broadcast_bucket_size, src)
  254. def _sync_params_and_buffers(
  255. process_group: dist.ProcessGroup,
  256. module_states: list[torch.Tensor],
  257. broadcast_bucket_size: int,
  258. src: int,
  259. ) -> None:
  260. """Synchronize ``module_states`` (list of tensors) across all processes by broadcasting them from rank 0."""
  261. if len(module_states) > 0:
  262. dist._broadcast_coalesced(
  263. process_group, module_states, broadcast_bucket_size, src
  264. )
  265. def _replace_by_prefix(
  266. state_dict: dict[str, Any],
  267. old_prefix: str,
  268. new_prefix: str,
  269. ) -> None:
  270. """
  271. Replace all keys that match a given old_prefix with a new_prefix (in-place).
  272. Usage::
  273. state_dict = {"layer.xyz": torch.tensor(1)}
  274. replace_by_prefix_(state_dict, "layer.", "module.layer.")
  275. assert state_dict == {"module.layer.xyz": torch.tensor(1)}
  276. """
  277. if old_prefix == new_prefix:
  278. raise ValueError("old_prefix and new_prefix must be distinct")
  279. for key in list(state_dict.keys()):
  280. if not key.startswith(old_prefix):
  281. continue
  282. new_key = new_prefix + key[len(old_prefix) :]
  283. state_dict[new_key] = state_dict[key]
  284. del state_dict[key]
  285. def _data_ptr_allocated(tensor: torch.Tensor) -> bool:
  286. return tensor.untyped_storage().data_ptr() > 0
  287. def _get_root_modules(modules: list[nn.Module]) -> list[nn.Module]:
  288. """
  289. Returns the modules in ``modules`` that are root modules (i.e.
  290. parent-less) with respect to the set ``modules``. In other words, these
  291. are the modules in ``modules`` that are the not child of any other
  292. module in ``modules``.
  293. """
  294. root_modules: list[nn.Module] = []
  295. module_to_modules: dict[nn.Module, set[nn.Module]] = {
  296. module: set(module.modules()) for module in modules
  297. }
  298. for candidate_module in modules:
  299. is_root_module = True
  300. for module, _modules in module_to_modules.items():
  301. is_child_module = (
  302. candidate_module is not module and candidate_module in _modules
  303. )
  304. if is_child_module:
  305. is_root_module = False
  306. break
  307. if is_root_module:
  308. root_modules.append(candidate_module)
  309. return root_modules