utils.py 12 KB

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