api.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. # mypy: allow-untyped-defs
  2. from contextlib import contextmanager
  3. from typing import Optional
  4. import torch
  5. import torch.distributed as dist
  6. import torch.nn as nn
  7. from torch.distributed import distributed_c10d
  8. from torch.distributed._shard.sharded_tensor import (
  9. ShardedTensor,
  10. )
  11. from .sharding_spec import (
  12. ShardingSpec,
  13. ChunkShardingSpec
  14. )
  15. from .sharding_plan import (
  16. ShardingPlan
  17. )
  18. from .sharder import Sharder
  19. def _shard_tensor(
  20. tensor: torch.Tensor, sharding_spec: ShardingSpec, src_rank=0, process_group=None
  21. ) -> ShardedTensor:
  22. """
  23. Given a :class:`torch.Tensor`, it shards that tensor according to the provided
  24. ``sharding_spec``. ``src_rank`` denotes the source rank which would be
  25. used as the ground truth of the data which would be scattered as shards
  26. across the rest of the ranks.
  27. Args:
  28. tensor (:class:`torch.Tensor`): Tensor needs to be sharded.
  29. sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification
  30. describing how to shard the Tensor.
  31. Keyword args:
  32. src_rank (int, optional): The source rank which is used as the ground truth of
  33. the data for the parameter that would be sharded and scattered
  34. across the rest of the ranks.
  35. Default: 0.
  36. process_group (ProcessGroup, optional): The process group to work on. If None,
  37. the default process group will be used.
  38. Returns:
  39. A :class:`ShardedTensor` sharded from the given tensor.
  40. .. warning::
  41. Only :class:`torch.distributed._shard.sharding_spec.ChunkShardingSpec` is
  42. currently supported as the ``sharding_spec``.
  43. """
  44. if not tensor.is_contiguous():
  45. raise ValueError('input tensor is not a contiguous Tensor')
  46. pg = process_group if process_group is not None else distributed_c10d._get_default_group()
  47. world_size = dist.get_world_size(pg)
  48. current_rank = dist.get_rank(pg)
  49. # Validate src_rank and sharding_spec are same across all ranks.
  50. gathered_list = [None] * world_size
  51. dist.all_gather_object(gathered_list, (src_rank, sharding_spec), group=pg)
  52. for idx, entry in enumerate(gathered_list):
  53. if src_rank != entry[0]: # type: ignore[index]
  54. raise ValueError(
  55. f'src_rank={src_rank} on rank: {current_rank} does not ' # type: ignore[index]
  56. f'match with src_rank={entry[0]} on rank: {idx}')
  57. if sharding_spec != entry[1]: # type: ignore[index]
  58. raise ValueError(
  59. f'sharding_spec={sharding_spec} on rank: {current_rank} does not ' # type: ignore[index]
  60. f'match with sharding_spec={entry[1]} on rank: {idx}')
  61. st = sharding_spec.shard(tensor, src_rank=src_rank, process_group=pg)
  62. return st
  63. def shard_parameter(
  64. module: torch.nn.Module,
  65. param_name: str,
  66. sharding_spec: ShardingSpec,
  67. src_rank=0,
  68. process_group=None):
  69. """
  70. Given a :class:`torch.nn.Module`, a ``param_name`` for a parameter in that
  71. module, it shards that parameter according to the provided
  72. ``sharding_spec``. ``src_rank`` denotes the source rank which would be
  73. used as the ground truth of the data which would be scattered as shards
  74. across the rest of the ranks.
  75. This method replaces ``module.param_name`` with a
  76. :class:`torch.distributed._sharded_tensor.ShardedTensor`
  77. Args:
  78. module (:class:`torch.nn.Module`): Module whose parameter needs to be sharded.
  79. param_name (str): Name of the parameter of ``module`` that needs to be sharded.
  80. sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification
  81. describing how to shard the Tensor.
  82. Keyword args:
  83. src_rank (int, optional): The source rank which is used as the ground truth of
  84. the data for the parameter that would be sharded and scattered
  85. across the rest of the ranks.
  86. Default: 0.
  87. process_group (ProcessGroup, optional): The process group to work on. If None,
  88. the default process group will be used.
  89. .. warning::
  90. Only :class:`torch.distributed._shard.sharding_spec.ChunkShardingSpec` is
  91. currently supported as the ``sharding_spec``.
  92. """
  93. # Perform some validation first.
  94. if not hasattr(module, param_name):
  95. raise AttributeError(f'{module._get_name()} has no attribute `{param_name}`')
  96. tensor = getattr(module, param_name)
  97. if not isinstance(tensor, torch.Tensor):
  98. raise ValueError(f'Expected {type(module).__name__}.{param_name} to be a Tensor, but found {type(tensor).__name__}')
  99. if not tensor.is_contiguous():
  100. raise ValueError(f'param: {param_name} is not a contiguous Tensor')
  101. st = _shard_tensor(tensor, sharding_spec, src_rank, process_group)
  102. # Replace param with ShardedTensor.
  103. module.register_parameter(param_name, nn.Parameter(st))
  104. # Tracks the current process group in the load context manager.
  105. _CURRENT_PROCESS_GROUP: Optional[dist.ProcessGroup] = None
  106. @contextmanager
  107. def load_with_process_group(process_group):
  108. """
  109. Context manager to set the process group with which to load a ShardedTensor.
  110. """
  111. global _CURRENT_PROCESS_GROUP
  112. if _CURRENT_PROCESS_GROUP is not None:
  113. raise RuntimeError(
  114. 'ProcessGroup already set by previous "load_with_process_group" '
  115. 'context manager')
  116. _CURRENT_PROCESS_GROUP = process_group
  117. try:
  118. yield process_group
  119. finally:
  120. _CURRENT_PROCESS_GROUP = None
  121. def _get_current_process_group():
  122. """
  123. Retrieves the current process group set by ``load_with_process_group``.
  124. If not set, it just returns the default group.
  125. """
  126. global _CURRENT_PROCESS_GROUP
  127. if _CURRENT_PROCESS_GROUP is None:
  128. return distributed_c10d._get_default_group()
  129. else:
  130. return _CURRENT_PROCESS_GROUP
  131. def _reshard_output(
  132. module: torch.nn.Module,
  133. resharding_spec: ShardingSpec) -> torch.nn.Module:
  134. """
  135. Hook a module with output resharding in the forward pass according
  136. to the given ``resharding_spec``.
  137. Args:
  138. module (:class:`torch.nn.Module`): Module whose output needs to be resharded.
  139. resharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`):
  140. The specification describing how the output of the module will be resharded.
  141. Returns:
  142. A :class:`torch.nn.Module` object with reshard API hooked.
  143. """
  144. def hook_func(_module, _input, output):
  145. if isinstance(output, ShardedTensor):
  146. return output.reshard(resharding_spec)
  147. return output
  148. module.register_forward_hook(hook_func)
  149. return module
  150. def _collect_local_shard(module: torch.nn.Module) -> torch.nn.Module:
  151. """
  152. Hook a module with local shards collection in the forward pass.
  153. This API is typically used to convert a sharded representation back to data parallel
  154. representation. In particular, it returns the local tensor for this Shard. If the
  155. size along the sharding dimension for the local tensor is 1, this dimension is removed
  156. from the final result. For example a [4, 16] ShardedTensor across 4 ranks is typically
  157. a local Tensor of size [16] across each rank and not [1, 16] across each rank.
  158. Args:
  159. module (:class:`torch.nn.Module`): Module whose output is ShardedTensor and the
  160. local tensor value needs to be returned.
  161. Returns:
  162. A :class:`torch.nn.Module` object with collection API hooked.
  163. """
  164. def hook_func(_module, _input, output):
  165. if isinstance(output, ShardedTensor):
  166. local_tensor = output.local_tensor()
  167. # Squeeze the # of dimensions manually, only applicable to ChunkShardingSpec
  168. sharding_spec = output._sharding_spec
  169. if isinstance(sharding_spec, ChunkShardingSpec) \
  170. and local_tensor.size(sharding_spec.dim) == 1: # type: ignore[attr-defined, arg-type]
  171. local_tensor = local_tensor.squeeze(
  172. output._sharding_spec.dim # type: ignore[attr-defined]
  173. )
  174. return local_tensor
  175. module.register_forward_hook(hook_func)
  176. return module
  177. def shard_module(
  178. module: nn.Module,
  179. plan: ShardingPlan,
  180. src_rank=0,
  181. process_group=None
  182. ):
  183. """
  184. Shards a given module according to the provided sharding `plan`. This method
  185. first shards all the parameters according to the given sharding `plan`. Then if
  186. `output_plan` and `return_local_tensor` are specified in the sharding `plan`, it
  187. will tag the output of modules according `output_plan`, convert the module's
  188. output back to data parallel according to `return_local_tensor`.
  189. Needs to be called on all ranks in an SPMD fashion.
  190. Args:
  191. module (:class:`torch.nn.Module`): The module to apply sharding to
  192. plan (:class:`torch.distributed._shard.sharding_plan.ShardingPlan`):
  193. The ShardingPlan which specified param name to ShardingSpec to apply to
  194. each parameter.
  195. Keyword args:
  196. src_rank (int, optional): The source rank which is used as the ground truth of
  197. the data for the module that would be sharded and scattered across the rest
  198. of the ranks.
  199. Default: 0.
  200. process_group (ProcessGroup, optional): The process group to work on. If None,
  201. the default process group will be used.
  202. """
  203. # record Sharder paths for sanity check on the plan to ensure items in the plan
  204. # does not conflict with the submodule tree that the Sharder is working with
  205. sharder_paths = []
  206. for name, spec in plan.plan.items():
  207. if isinstance(spec, Sharder):
  208. sharder_paths.append(name)
  209. # shard the parameter according to the ShardingPlan
  210. for name, spec in plan.plan.items():
  211. if isinstance(spec, ShardingSpec):
  212. # if found a sharding spec, try to shard the parameter
  213. module_path, _, param_name = name.rpartition(".")
  214. for sharder_path in sharder_paths:
  215. if module_path.startswith(sharder_path):
  216. raise RuntimeError(f"ShardingPlan is in-valid, trying to shard a parameter: {name},"
  217. f" but there's already a Sharder entry for module {sharder_path},"
  218. f" parameter sharding should not conflict with the submodule tree"
  219. f" that a Sharder is working with!")
  220. mod = module.get_submodule(module_path)
  221. shard_parameter(
  222. mod,
  223. param_name,
  224. spec,
  225. src_rank=src_rank,
  226. process_group=process_group
  227. )
  228. elif isinstance(spec, Sharder):
  229. parent_mod_path, _, mod_name = name.rpartition(".")
  230. if name == "":
  231. raise KeyError("Module path must not be empty for custom sharder!")
  232. mod = module.get_submodule(name)
  233. parent_mod = module.get_submodule(parent_mod_path)
  234. sharded_mod = spec.shard(mod)
  235. # swap this submodule with the sharded module
  236. parent_mod.mod_name = sharded_mod
  237. else:
  238. raise TypeError(f"Only `ShardingSpec` and `Sharder` are supported to shard '{name}'")
  239. # reshard output if there's an entry in `reshard_output` for this module
  240. if plan.output_plan is not None:
  241. for module_path, output_spec in plan.output_plan.items():
  242. if isinstance(output_spec, ShardingSpec):
  243. mod = module.get_submodule(module_path)
  244. _reshard_output(mod, output_spec)
  245. else:
  246. raise TypeError(f"Only `ShardingSpec` is supported as output_plan for '{module_path}'")
  247. # convert the output back to data parallel for the modules appears in
  248. # `return_local_tensor` of the plan, we will call `_collect_local_shard`
  249. # to collect the local tensor for output of modules
  250. if plan.return_local_tensor is not None:
  251. for module_path in plan.return_local_tensor:
  252. mod = module.get_submodule(module_path)
  253. _collect_local_shard(mod)