style.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. # mypy: allow-untyped-defs
  2. # Copyright (c) Meta Platforms, Inc. and affiliates
  3. from abc import ABC, abstractmethod
  4. from typing import Optional, Union, Tuple, Dict, Any
  5. from functools import partial
  6. import torch
  7. import torch.nn as nn
  8. from torch.distributed._tensor import DeviceMesh, DTensor, Placement, Replicate, Shard, distribute_tensor, distribute_module
  9. __all__ = [
  10. "ParallelStyle",
  11. "RowwiseParallel",
  12. "SequenceParallel",
  13. "ColwiseParallel",
  14. "PrepareModuleInput",
  15. "PrepareModuleOutput",
  16. ]
  17. class ParallelStyle(ABC):
  18. """
  19. The parallel style contract defines how the module or submodule should be parallelized.
  20. It only defines the ``apply`` method for ``parallelize_module`` to use, this allows maximum
  21. flexibility for different kind of style implementations.
  22. """
  23. @abstractmethod
  24. def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
  25. ...
  26. class ColwiseParallel(ParallelStyle):
  27. """
  28. Partition a compatible nn.Module in a column-wise fashion. Currently supports nn.Linear and nn.Embedding.
  29. Users can compose it together with RowwiseParallel to achieve the sharding of more complicated modules.
  30. (i.e. MLP, Attention)
  31. Keyword Args:
  32. input_layouts (Placement, optional):
  33. The DTensor layout of input tensor for the nn.Module, this is used to annotate the input tensor to
  34. become a DTensor. If not specified, we assume the input tensor to be replicated.
  35. output_layouts (Placement, optional):
  36. The DTensor layout of the output for the nn.Module, this is used to ensure the output of the nn.Module
  37. with the user desired layout. If not specified, the output tensor is sharded on the last dimension.
  38. use_local_output (bool, optional):
  39. Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module output, default: True.
  40. Returns:
  41. A :class:`ParallelStyle` object that represents Colwise sharding of the nn.Module.
  42. Example::
  43. >>> # xdoctest: +SKIP(failing)
  44. >>> from torch.distributed.tensor.parallel import parallelize_module, ColwiseParallel
  45. >>> from torch.distributed.device_mesh import init_device_mesh
  46. >>> ...
  47. >>> m = Model(...) # m is a nn.Module that contains a "w1" nn.Linear submodule
  48. >>> tp_mesh = init_device_mesh("cuda", (8,))
  49. >>>
  50. >>> # By default, the input of the "w1" Linear will be converted to Replicated DTensor
  51. >>> # and the output of "w1" will return :class:`torch.Tensor` that shards on the last dim.
  52. >>>
  53. >>> sharded_mod = parallelize_module(m, tp_mesh, {"w1": ColwiseParallel()})
  54. >>> ...
  55. .. note:: By default ``ColwiseParallel`` output is sharded on the last dimension if the ``output_layouts`` not
  56. specified, if there're operators that require specific tensor shape (i.e. before the paired ``RowwiseParallel``),
  57. keep in mind that if the output is sharded the operator might need to be adjusted to the sharded size.
  58. """
  59. def __init__(
  60. self,
  61. *,
  62. input_layouts: Optional[Placement] = None,
  63. output_layouts: Optional[Placement] = None,
  64. use_local_output: bool = True
  65. ):
  66. super().__init__()
  67. self.input_layouts = (input_layouts or Replicate(), )
  68. self.output_layouts = (output_layouts or Shard(-1), )
  69. # colwise linear runtime sharding (desired sharding):
  70. # 1. requires replicate input
  71. # 2. shard output on last dim
  72. self.desired_input_layouts = (Replicate(), )
  73. self.use_local_output = use_local_output
  74. @staticmethod
  75. def _prepare_input_fn(input_layouts, desired_input_layouts, mod, inputs, device_mesh):
  76. # TODO: figure out dynamo support for instance method and switch this to instance method
  77. # annotate module input placements/sharding with input_layouts
  78. input_tensor = inputs[0]
  79. if not isinstance(input_tensor, DTensor):
  80. input_tensor = DTensor.from_local(input_tensor, device_mesh, input_layouts, run_check=False)
  81. # transform the input layouts to the desired layouts of ColwiseParallel
  82. if input_layouts != desired_input_layouts:
  83. input_tensor = input_tensor.redistribute(placements=desired_input_layouts, async_op=True)
  84. return input_tensor
  85. def _partition_linear_fn(self, name, module, device_mesh):
  86. # colwise shard weight/bias to Shard(0), weight be Shard(0)
  87. # means Colwise as Linear is input * weight^T + bias, where
  88. # weight would become Shard(1)
  89. for name, param in module.named_parameters():
  90. dist_param = nn.Parameter(
  91. distribute_tensor(param, device_mesh, [Shard(0)])
  92. )
  93. module.register_parameter(name, dist_param)
  94. def _partition_embedding_fn(self, name, module, device_mesh):
  95. # colwise shard embedding.weight is straight forward as Shard(1)
  96. for name, param in module.named_parameters():
  97. dist_param = nn.Parameter(
  98. distribute_tensor(param, device_mesh, [Shard(1)])
  99. )
  100. module.register_parameter(name, dist_param)
  101. @staticmethod
  102. def _prepare_output_fn(output_layouts, use_local_output, mod, outputs, device_mesh):
  103. # outputs is a shard on last dimension DTensor, i.e. Shard(-1)
  104. if outputs.placements != output_layouts:
  105. outputs = outputs.redistribute(placements=output_layouts, async_op=True)
  106. # back to local tensor
  107. return outputs.to_local() if use_local_output else outputs
  108. def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
  109. if isinstance(module, nn.Linear):
  110. partition_fn = self._partition_linear_fn
  111. elif isinstance(module, nn.Embedding):
  112. partition_fn = self._partition_embedding_fn
  113. else:
  114. raise NotImplementedError("ColwiseParallel currently only support nn.Linear and nn.Embedding!")
  115. return distribute_module(
  116. module,
  117. device_mesh,
  118. partition_fn,
  119. partial(self._prepare_input_fn, self.input_layouts, self.desired_input_layouts),
  120. partial(self._prepare_output_fn, self.output_layouts, self.use_local_output),
  121. )
  122. class RowwiseParallel(ParallelStyle):
  123. """
  124. Partition a compatible nn.Module in a row-wise fashion. Currently supports nn.Linear and nn.Embedding.
  125. Users can compose it with ColwiseParallel to achieve the sharding of more complicated modules.
  126. (i.e. MLP, Attention)
  127. Keyword Args:
  128. input_layouts (Placement, optional):
  129. The DTensor layout of input tensor for the nn.Module, this is used to annotate the input tensor to
  130. become a DTensor. If not specified, we assume the input tensor to be sharded on the last dimension.
  131. output_layouts (Placement, optional):
  132. The DTensor layout of the output for the nn.Module, this is used to ensure the output of the nn.Module
  133. with the user desired layout. If not specified, the output tensor is replicated.
  134. use_local_output (bool, optional):
  135. Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module output, default: True.
  136. Returns:
  137. A :class:`ParallelStyle` object that represents Rowwise sharding of the nn.Module.
  138. Example::
  139. >>> # xdoctest: +SKIP(failing)
  140. >>> from torch.distributed.tensor.parallel import parallelize_module, RowwiseParallel
  141. >>> from torch.distributed.device_mesh import init_device_mesh
  142. >>> ...
  143. >>> m = Model(...) # m is a nn.Module that contains a "w2" nn.Linear submodule
  144. >>> tp_mesh = init_device_mesh("cuda", (8,))
  145. >>>
  146. >>> # By default, the input of the "w2" Linear will be converted to DTensor that shards on the last dim
  147. >>> # and the output of "w2" will return a replicated :class:`torch.Tensor`.
  148. >>>
  149. >>> sharded_mod = parallelize_module(m, tp_mesh, {"w2": RowwiseParallel()}),
  150. >>> ...
  151. """
  152. def __init__(
  153. self,
  154. *,
  155. input_layouts: Optional[Placement] = None,
  156. output_layouts: Optional[Placement] = None,
  157. use_local_output: bool = True
  158. ):
  159. super().__init__()
  160. self.input_layouts = (input_layouts or Shard(-1), )
  161. self.output_layouts = (output_layouts or Replicate(), )
  162. self.use_local_output = use_local_output
  163. @staticmethod
  164. def _prepare_input_fn(input_layouts, desired_input_layouts, mod, inputs, device_mesh):
  165. input_tensor = inputs[0]
  166. if not isinstance(input_tensor, DTensor):
  167. input_tensor = DTensor.from_local(input_tensor, device_mesh, input_layouts, run_check=False)
  168. if input_layouts != desired_input_layouts:
  169. input_tensor = input_tensor.redistribute(placements=desired_input_layouts, async_op=True)
  170. return input_tensor
  171. def _partition_linear_fn(self, name, module, device_mesh):
  172. # Rowwise shard weight to Shard(1), bias to Replicate(), weight be Shard(1)
  173. # means Rowwise as nn.Linear is input * weight^T + bias, where
  174. # weight would become Shard(0)
  175. module.register_parameter("weight", nn.Parameter(
  176. distribute_tensor(module.weight, device_mesh, [Shard(1)])
  177. ))
  178. if module.bias is not None:
  179. module.register_parameter("bias", nn.Parameter(
  180. distribute_tensor(module.bias, device_mesh, [Replicate()])
  181. ))
  182. def _partition_embedding_fn(self, name, module, device_mesh):
  183. # rowwise shard embedding.weight is Shard(0)
  184. for name, param in module.named_parameters():
  185. dist_param = nn.Parameter(
  186. distribute_tensor(param, device_mesh, [Shard(0)])
  187. )
  188. module.register_parameter(name, dist_param)
  189. @staticmethod
  190. def _prepare_output_fn(output_layouts, use_local_output, mod, outputs, device_mesh):
  191. # Rowwise sharding produces partial output, depending on output layouts:
  192. # 1. to replicate -> allreduce
  193. # 2. to shard -> reduce_scatter
  194. if outputs.placements != output_layouts:
  195. outputs = outputs.redistribute(placements=output_layouts, async_op=True)
  196. # back to local tensor if use_local_output is True
  197. return outputs.to_local() if use_local_output else outputs
  198. def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
  199. if isinstance(module, nn.Linear):
  200. partition_fn = self._partition_linear_fn
  201. # rowwise linear runtime sharding requires input tensor shard on last dim
  202. self.desired_input_layouts: Tuple[Placement, ...] = (Shard(-1), )
  203. elif isinstance(module, nn.Embedding):
  204. partition_fn = self._partition_embedding_fn
  205. # rowwise embedding runtime sharding requires input tensor replicated
  206. self.desired_input_layouts = (Replicate(), )
  207. else:
  208. raise NotImplementedError("RowwiseParallel currently only support nn.Linear and nn.Embedding!")
  209. return distribute_module(
  210. module,
  211. device_mesh,
  212. partition_fn,
  213. partial(self._prepare_input_fn, self.input_layouts, self.desired_input_layouts),
  214. partial(self._prepare_output_fn, self.output_layouts, self.use_local_output),
  215. )
  216. class SequenceParallel(ParallelStyle):
  217. """
  218. SequenceParallel replicates a compatible ``nn.Module`` parameters and runs the sharded computation with
  219. input sharded on the sequence dimension. This currently supports ``nn.LayerNorm``, ``nn.Dropout``, and the
  220. `RMSNorm python implementation <https://github.com/facebookresearch/llama/blob/main/llama/model.py#L34>`__
  221. This style implements the operation that is described in the paper
  222. `Reducing Activation Recomputation in Large Transformer Models <https://arxiv.org/abs/2205.05198>`__
  223. Both the input and output of the ``nn.Module`` will be sharded on the sequence dimension.
  224. Keyword Args:
  225. sequence_dim (int, optional):
  226. The sequence dimension of the input tensor for the ``nn.Module``, this is used to annotate the input tensor to
  227. become a DTensor that is sharded on the sequence dimension, default: 1.
  228. use_local_output (bool, optional):
  229. Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module output, default: False.
  230. Returns:
  231. A :class:`ParallelStyle` object that represents Sequence Parallel of the ``nn.Module``.
  232. Example::
  233. >>> # xdoctest: +SKIP(failing)
  234. >>> from torch.distributed.tensor.parallel import parallelize_module, SequenceParallel
  235. >>> from torch.distributed.device_mesh import init_device_mesh
  236. >>> ...
  237. >>> m = Model(...) # m is a nn.Module that contains a "norm" nn.LayerNorm submodule
  238. >>> tp_mesh = init_device_mesh("cuda", (8,))
  239. >>>
  240. >>> # By default, the input of the "norm" will be converted to DTensor that shards on the sequence dim
  241. >>> # and the output of "norm" will return a sharded on sequence dimension :class:`DTensor`.
  242. >>>
  243. >>> sharded_mod = parallelize_module(m, tp_mesh, {"norm": SequenceParallel()}),
  244. >>> ...
  245. .. note:: SequenceParallel style assumes ones initialization if there are weights in the nn.Module (i.e.
  246. ``nn.LayerNorm`` or ``RMSNorm``, and they by default have ones initialization). If you have custom
  247. inits for the weights on those modules, you need to broadcast the weights before/after parallelizing
  248. to ensure that they are replicated.
  249. """
  250. def __init__(
  251. self,
  252. *,
  253. sequence_dim: int = 1,
  254. use_local_output: bool = False
  255. ):
  256. super().__init__()
  257. self.sequence_dim = sequence_dim
  258. self.use_local_output = use_local_output
  259. def _replicate_module_fn(self, name: str, module: nn.Module, device_mesh: DeviceMesh):
  260. for p_name, param in module.named_parameters():
  261. # simple replication with fixed ones_ init from LayerNorm/RMSNorm, which allow
  262. # us to simply just use from_local
  263. replicated_param = torch.nn.Parameter(
  264. DTensor.from_local(param, device_mesh, [Replicate()], run_check=False)
  265. )
  266. module.register_parameter(p_name, replicated_param)
  267. @staticmethod
  268. def _prepare_input_fn(sequence_dim, mod, inputs, device_mesh):
  269. input_tensor = inputs[0]
  270. if isinstance(input_tensor, DTensor):
  271. return inputs
  272. elif isinstance(input_tensor, torch.Tensor):
  273. return DTensor.from_local(input_tensor, device_mesh, [Shard(sequence_dim)], run_check=False)
  274. else:
  275. raise ValueError(f"expecting input of {mod} to be a torch.Tensor or DTensor, but got {input_tensor}")
  276. @staticmethod
  277. def _prepare_output_fn(use_local_output, mod, outputs, device_mesh):
  278. return outputs.to_local() if use_local_output else outputs
  279. def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
  280. return distribute_module(
  281. module,
  282. device_mesh,
  283. self._replicate_module_fn,
  284. partial(self._prepare_input_fn, self.sequence_dim),
  285. partial(self._prepare_output_fn, self.use_local_output),
  286. )
  287. class PrepareModuleInput(ParallelStyle):
  288. """
  289. Configure the nn.Module's inputs to convert the input tensors of the nn.Module to DTensors at runtime according to
  290. ``input_layouts``, and perform layout redistribution according to the ``desired_input_layouts``.
  291. Keyword Args:
  292. input_layouts (Union[Placement, Tuple[Optional[Placement]]]):
  293. The DTensor layouts of input tensors for the nn.Module, this is used to convert the input tensors to
  294. DTensors. If some inputs are not torch.Tensor or no need to convert to DTensors, ``None`` need to be specified
  295. as a placeholder. default: None.
  296. desired_input_layouts (Union[Placement, Tuple[Optional[Placement]]]):
  297. The desired DTensor layout of input tensors for the nn.Module, this is used to ensure the inputs of the nn.Module
  298. have the desired DTensor layouts. This argument needs to have the same length with ``input_layouts``. default: None.
  299. input_kwarg_layouts (Dict[str, Placement]):
  300. The DTensor layouts of input kwargs for the nn.Module, this is used to convert the input kwarg tensors to DTensors.
  301. default: None
  302. desired_input_kwarg_layouts: (Dict[str, Placement]):
  303. The desired DTensor layout of input kwargs for the nn.Module, this is used to ensure the inputs of the nn.Module
  304. have the desired DTensor layouts. default: None.
  305. use_local_output (bool, optional):
  306. Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module inputs, default: False.
  307. Returns:
  308. A :class:`ParallelStyle` object that prepares the sharding layouts of the nn.Module's inputs.
  309. Example::
  310. >>> # xdoctest: +SKIP(failing)
  311. >>> from torch.distributed.tensor.parallel import parallelize_module, PrepareModuleInput
  312. >>> from torch.distributed.device_mesh import init_device_mesh
  313. >>> ...
  314. >>> block = TransformerBlock(...) # block is a nn.Module that contains an "attn" Attention submodule
  315. >>> tp_mesh = init_device_mesh("cuda", (8,))
  316. >>>
  317. >>> # According to the style specified below, the first input of attn will be annotated to Sharded DTensor
  318. >>> # and then redistributed to Replicated DTensor.
  319. >>> parallelize_module(
  320. >>> block, # this can be a submodule or module
  321. >>> tp_mesh,
  322. >>> parallelize_plan={
  323. >>> "attn": PrepareModuleInput(
  324. >>> input_layouts=(Shard(0), None, None, ...),
  325. >>> desired_input_layouts=(Replicate(), None, None, ...)
  326. >>> ),
  327. >>> }
  328. >>> )
  329. """
  330. def __init__(
  331. self,
  332. *,
  333. input_layouts: Optional[Union[Placement, Tuple[Optional[Placement]]]] = None,
  334. desired_input_layouts: Optional[Union[Placement, Tuple[Optional[Placement]]]] = None,
  335. input_kwarg_layouts: Optional[Dict[str, Placement]] = None,
  336. desired_input_kwarg_layouts: Optional[Dict[str, Placement]] = None,
  337. use_local_output: bool = False
  338. ):
  339. self.input_layouts = (input_layouts,) if isinstance(input_layouts, Placement) else input_layouts
  340. self.desired_input_layouts = \
  341. (desired_input_layouts,) if isinstance(desired_input_layouts, Placement) else desired_input_layouts
  342. self.use_local_output = use_local_output
  343. if self.input_layouts is not None:
  344. assert self.desired_input_layouts is not None, "desired module inputs should not be None!"
  345. assert len(self.input_layouts) == len(self.desired_input_layouts), \
  346. "input_layouts and desired_input_layouts should have same length!"
  347. self.with_kwargs = input_kwarg_layouts is not None
  348. self.input_kwarg_layouts = input_kwarg_layouts or {}
  349. self.desired_input_kwarg_layouts = desired_input_kwarg_layouts or {}
  350. if self.with_kwargs:
  351. assert len(self.input_kwarg_layouts) == len(self.desired_input_kwarg_layouts), \
  352. "input_kwarg_layouts and desired_input_kwarg_layouts should have same length!"
  353. def _prepare_input_arg(
  354. self,
  355. input: Any,
  356. mesh: DeviceMesh,
  357. input_layout: Optional[Placement],
  358. desired_layout: Optional[Placement]
  359. ):
  360. if input_layout is not None:
  361. if isinstance(input, DTensor):
  362. # TODO: re-enable the check once we fix the compile path
  363. # assert inp.placements[0] == input_layout
  364. dt_inp = input
  365. else:
  366. assert isinstance(input, torch.Tensor), "expecting input to be a torch.Tensor!"
  367. dt_inp = DTensor.from_local(input, mesh, (input_layout,), run_check=False)
  368. if desired_layout is not None and input_layout != desired_layout:
  369. dt_inp = dt_inp.redistribute(placements=(desired_layout,))
  370. return dt_inp.to_local() if self.use_local_output else dt_inp
  371. else:
  372. return input
  373. def _prepare_input_fn(self, inputs, device_mesh):
  374. if self.input_layouts is None:
  375. return inputs
  376. prepared_inputs = []
  377. if not isinstance(inputs, tuple):
  378. inputs = (inputs,)
  379. if len(inputs) != len(self.input_layouts):
  380. raise ValueError("module inputs and input_layouts should have same length!")
  381. assert self.desired_input_layouts is not None, "desired module inputs should not be None!"
  382. for inp, input_layout, desired_layout in zip(inputs, self.input_layouts, self.desired_input_layouts):
  383. prepared_inputs.append(self._prepare_input_arg(inp, device_mesh, input_layout, desired_layout))
  384. return tuple(prepared_inputs)
  385. def _prepare_input_kwarg_fn(self, inputs, kwarg_inputs, device_mesh):
  386. prepared_arg_inputs = self._prepare_input_fn(inputs, device_mesh)
  387. prepared_kwarg_inputs = {}
  388. for kwarg_key in kwarg_inputs.keys():
  389. kwarg_val = kwarg_inputs[kwarg_key]
  390. input_layout = self.input_kwarg_layouts.get(kwarg_key)
  391. desired_input_layout = self.desired_input_kwarg_layouts.get(kwarg_key)
  392. prepared_kwarg_inputs[kwarg_key] = self._prepare_input_arg(kwarg_val, device_mesh, input_layout, desired_input_layout)
  393. return (prepared_arg_inputs, prepared_kwarg_inputs)
  394. def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
  395. if self.with_kwargs:
  396. module.register_forward_pre_hook(
  397. lambda _, inputs, kwargs: self._prepare_input_kwarg_fn(inputs, kwargs, device_mesh),
  398. with_kwargs=True
  399. ) # type: ignore[misc]
  400. else:
  401. module.register_forward_pre_hook(lambda _, inputs: self._prepare_input_fn(inputs, device_mesh)) # type: ignore[misc, call-arg]
  402. return module
  403. class PrepareModuleOutput(ParallelStyle):
  404. """
  405. Configure the nn.Module's outputs to convert the output tensors of the nn.Module to DTensors at runtime according to
  406. ``output_layouts``, and perform layout redistribution according to the ``desired_output_layouts``.
  407. Keyword Args:
  408. output_layouts (Union[Placement, Tuple[Placement]]):
  409. The DTensor layouts of output tensors for the nn.Module, this is used to convert the output tensors to
  410. DTensors if they are :class:`torch.Tensor`. If some outputs are not torch.Tensor or no need to convert to DTensors,
  411. ``None`` need to be specified as a placeholder.
  412. desired_output_layouts (Union[Placement, Tuple[Placement]]):
  413. The desired DTensor layouts of output tensors for the nn.Module, this is used to ensure the outputs of the nn.Module
  414. have the desired DTensor layouts.
  415. use_local_output (bool, optional):
  416. Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module outputs, default: True.
  417. Returns:
  418. A ParallelStyle object that prepares the sharding layouts of the nn.Module's outputs.
  419. Example::
  420. >>> # xdoctest: +SKIP(failing)
  421. >>> from torch.distributed.tensor.parallel import parallelize_module, PrepareModuleOutput
  422. >>> from torch.distributed.device_mesh import init_device_mesh
  423. >>> ...
  424. >>> block = TransformerBlock(...) # block is a nn.Module that contains an "attn" Attention submodule
  425. >>> tp_mesh = init_device_mesh("cuda", (8,))
  426. >>>
  427. >>> # According to the style specified below, the output of the TransformerBlock will be converted to Replicated DTensor
  428. >>> # and then redistributed to Sharded DTensor.
  429. >>> parallelize_module(
  430. >>> block, # this can be a submodule or module
  431. >>> tp_mesh,
  432. >>> parallelize_plan = PrepareModuleOutput(
  433. >>> output_layouts=Replicate(),
  434. >>> desired_output_layouts=Shard(0)
  435. >>> )
  436. >>> )
  437. """
  438. def __init__(
  439. self,
  440. *,
  441. output_layouts: Union[Placement, Tuple[Placement]],
  442. desired_output_layouts: Union[Placement, Tuple[Placement]],
  443. use_local_output: bool = True
  444. ):
  445. self.output_layouts = (output_layouts,) if isinstance(output_layouts, Placement) else output_layouts
  446. self.desired_output_layouts = \
  447. (desired_output_layouts,) if isinstance(desired_output_layouts, Placement) else desired_output_layouts
  448. self.use_local_output = use_local_output
  449. assert len(self.output_layouts) == len(self.desired_output_layouts), \
  450. "output_layouts and desired_output_layouts should have same length!"
  451. def _prepare_out_fn(self, outputs, device_mesh):
  452. prepared_outputs = []
  453. if not isinstance(outputs, tuple):
  454. outputs = (outputs,)
  455. if len(outputs) != len(self.output_layouts):
  456. raise ValueError("module outputs and output_layouts should have same length!")
  457. for out, out_layout, desired_out_layout in zip(outputs, self.output_layouts, self.desired_output_layouts):
  458. if out_layout is not None:
  459. if isinstance(out, DTensor):
  460. # TODO: re-enable the check once we fix the compile path
  461. # assert out.placements[0] == out_layout
  462. dt_out = out
  463. else:
  464. dt_out = DTensor.from_local(out, device_mesh, (out_layout,), run_check=False)
  465. if out_layout != desired_out_layout:
  466. dt_out = dt_out.redistribute(placements=(desired_out_layout,))
  467. prepared_outputs.append(dt_out.to_local() if self.use_local_output else dt_out)
  468. else:
  469. prepared_outputs.append(out)
  470. if len(prepared_outputs) == 1:
  471. return prepared_outputs[0]
  472. else:
  473. return tuple(prepared_outputs)
  474. def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
  475. module.register_forward_hook(lambda _, inputs, outputs: self._prepare_out_fn(outputs, device_mesh)) # type: ignore[misc, call-arg]
  476. return module