Tensor Parallelism(TP) is built on top of the PyTorch DistributedTensor
(DTensor)
and provides different parallelism styles: Colwise, Rowwise, and Sequence Parallelism.
The entrypoint to parallelize your nn.Module using Tensor Parallelism is:
torch.distributed.tensor.parallel., , , ,
parallelize_module
(
module
device_mesh=None
parallelize_plan=None
*
src_data_rank=0
)
Apply Tensor Parallelism in PyTorch by parallelizing modules or sub-modules based on a user-specified plan.
We parallelize module or sub_modules based on a parallelize_plan. The parallelize_plan contains
ParallelStyle, which indicates how user wants the module or sub_module
to be parallelized.
User can also specify different parallel style per module fully qualified name (FQN).
Note that parallelize_module only accepts a 1-D DeviceMesh, if you have a 2-D or N-D DeviceMesh,
slice the DeviceMesh to a 1-D sub DeviceMesh first then pass to this API(i.e. device_mesh["tp"])
Parameters:
module (nn.Module) – Module to be parallelized.
device_mesh (DeviceMesh, optional) – Object which describes the mesh topology of devices for the DTensor.
If not specified, the call must be under a DeviceMesh context.
parallelize_plan (Union[ParallelStyle, Dict[str, ParallelStyle]], optional) – The plan used to parallelize the module. It can be either a
ParallelStyle object which contains how we prepare
input/output for Tensor Parallelism or it can be a dict of module
FQN and its corresponding ParallelStyle object. If not
specified, the call will do nothing at the moment.
Keyword Arguments:
src_data_rank (int, optional) – the rank of the source data for the logical/global tensor, it is used by
distribute_tensor() to scatter/broadcast the shards/replicas to other ranks. By default,
we use group_rank=0 on each DeviceMesh dimension as the source data to preserve the single-device
semantic. If passing None explicitly, parallelize_module() simply uses its local data instead
of trying to preserve the single-device semantic via scatter/broadcast. Default: 0
Apply Tensor Parallelism in PyTorch by parallelizing modules or sub-modules based on a user-specified plan.
We parallelize module or sub_modules based on a parallelize_plan. The parallelize_plan contains
ParallelStyle, which indicates how user wants the module or sub_module
to be parallelized.
User can also specify different parallel style per module fully qualified name (FQN).
Note that parallelize_module only accepts a 1-D DeviceMesh, if you have a 2-D or N-D DeviceMesh,
slice the DeviceMesh to a 1-D sub DeviceMesh first then pass to this API(i.e. device_mesh["tp"])
Parameters:
module (nn.Module) – Module to be parallelized.
device_mesh (DeviceMesh, optional) – Object which describes the mesh topology of devices for the DTensor.
If not specified, the call must be under a DeviceMesh context.
parallelize_plan (Union[ParallelStyle, Dict[str, ParallelStyle]], optional) – The plan used to parallelize the module. It can be either a
ParallelStyle object which contains how we prepare
input/output for Tensor Parallelism or it can be a dict of module
FQN and its corresponding ParallelStyle object. If not
specified, the call will do nothing at the moment.
Keyword Arguments
Example::
>>> fromtorch.distributed.tensor.parallelimportparallelize_module,ColwiseParallel>>> fromtorch.distributed.device_meshimportinit_device_mesh>>>>>> # Define the module.>>> m=Model(...)>>> tp_mesh=init_device_mesh
Tensor Parallelism supports the following parallel styles:
Partition a compatible nn.Module in a column-wise fashion. Currently supports nn.Linear and nn.Embedding.
Users can compose it together with RowwiseParallel to achieve the sharding of more complicated modules.
(i.e. MLP, Attention)
Keyword Arguments:
input_layouts (Placement, optional) – The DTensor layout of input tensor for the nn.Module, this is used to annotate the input tensor to
become a DTensor. If not specified, we assume the input tensor to be replicated.
output_layouts (Placement, optional) – The DTensor layout of the output for the nn.Module, this is used to ensure the output of the nn.Module
with the user desired layout. If not specified, the output tensor is sharded on the last dimension.
use_local_output (bool, optional) – Whether to use local torch.Tensor instead of DTensor for the module output, default: True.
Returns:
A ParallelStyle object that represents Colwise sharding of the nn.Module.
Example::
>>> fromtorch.distributed.tensor.parallelimportparallelize_module,ColwiseParallel>>> fromtorch.distributed.device_meshimportinit_device_mesh>>> ...>>> m=Model(...)# m is a nn.Module that contains a "w1" nn.Linear submodule>>> tp_mesh=init_device_mesh
Partition a compatible nn.Module in a row-wise fashion. Currently supports nn.Linear and nn.Embedding.
Users can compose it with ColwiseParallel to achieve the sharding of more complicated modules.
(i.e. MLP, Attention)
Keyword Arguments:
input_layouts (Placement, optional) – The DTensor layout of input tensor for the nn.Module, this is used to annotate the input tensor to
become a DTensor. If not specified, we assume the input tensor to be sharded on the last dimension.
output_layouts (Placement, optional) – The DTensor layout of the output for the nn.Module, this is used to ensure the output of the nn.Module
with the user desired layout. If not specified, the output tensor is replicated.
use_local_output (bool, optional) – Whether to use local torch.Tensor instead of DTensor for the module output, default: True.
Returns:
A ParallelStyle object that represents Rowwise sharding of the nn.Module.
Example::
>>> fromtorch.distributed.tensor.parallelimportparallelize_module,RowwiseParallel>>> fromtorch.distributed.device_meshimportinit_device_mesh>>> ...>>> m=Model(...)# m is a nn.Module that contains a "w2" nn.Linear submodule>>> tp_mesh=init_device_mesh
SequenceParallel replicates a compatible nn.Module parameters and runs the sharded computation with
input sharded on the sequence dimension. This currently supports nn.LayerNorm, nn.Dropout, and the
RMSNorm python implementation
If the input passed in to this nn.Module is a torch.Tensor, it assumes that the input is already sharded
on the sequence dimension and converts the input to a DTensor sharded on the sequence dimension. If the input
passed in to this nn.Module is already a DTensor but is not sharded on the sequence dimension, it would
redistribute the input to be sharded on the sequence dimension.
The output of the nn.Module will be sharded on the sequence dimension.
Keyword Arguments:
sequence_dim (int, optional) – The sequence dimension of the input tensor for the nn.Module, this is used to annotate the input tensor to
become a DTensor that is sharded on the sequence dimension, default: 1.
use_local_output (bool, optional) – Whether to use local torch.Tensor instead of DTensor for the module output, default: False.
Returns:
A object that represents Sequence Parallel of the .
Example::
>>> fromtorch.distributed.tensor.parallelimportparallelize_module,SequenceParallel>>> fromtorch.distributed.device_meshimportinit_device_mesh>>> ...>>> m=Model(...)# m is a nn.Module that contains a "norm" nn.LayerNorm submodule>>> tp_mesh=init_device_mesh
To simply configure the nn.Module’s inputs and outputs with DTensor layouts
and perform necessary layout redistributions, without distribute the module
parameters to DTensors, the following ParallelStyle s can be used in
the parallelize_plan when calling parallelize_module:
Configure the nn.Module’s inputs to convert the input tensors of the nn.Module to DTensors at runtime according to
input_layouts, and perform layout redistribution according to the desired_input_layouts.
Keyword Arguments:
input_layouts (Union[Placement, Tuple[Optional[Placement]]]) – The DTensor layouts of input tensors for the nn.Module, this is used to convert the input tensors to
DTensors. If some inputs are not torch.Tensor or no need to convert to DTensors, None need to be specified
as a placeholder. default: None.
desired_input_layouts (Union[Placement, Tuple[Optional[) – The desired DTensor layout of input tensors for the nn.Module, this is used to ensure the inputs of the nn.Module
have the desired DTensor layouts. This argument needs to have the same length with . default: None.
Example::
>>> fromtorch.distributed.tensor.parallelimportparallelize_module,PrepareModuleInput>>> fromtorch.distributed.device_meshimportinit_device_mesh>>> ...>>> block=TransformerBlock(...)# block is a nn.Module that contains an "attn" Attention submodule>>> tp_mesh=init_device_mesh
Configure the nn.Module’s outputs to convert the output tensors of the nn.Module to DTensors at runtime according to
output_layouts, and perform layout redistribution according to the desired_output_layouts.
Keyword Arguments:
output_layouts (Union[Placement, Tuple[Placement]]) – The DTensor layouts of output tensors for the nn.Module, this is used to convert the output tensors to
DTensors if they are torch.Tensor. If some outputs are not torch.Tensor or no need to convert to DTensors,
None need to be specified as a placeholder.
desired_output_layouts (Union[Placement, Tuple[Placement]]) – The desired DTensor layouts of output tensors for the nn.Module, this is used to ensure the outputs of the nn.Module
have the desired DTensor layouts.
use_local_output (bool, optional) – Whether to use local torch.Tensor instead of DTensor for the module outputs, default: True.
Returns:
A ParallelStyle object that prepares the sharding layouts of the nn.Module’s outputs.
Example::
>>> fromtorch.distributed.tensor.parallelimportparallelize_module,PrepareModuleOutput>>> fromtorch.distributed.device_meshimportinit_device_mesh>>> ...>>> block=TransformerBlock(...)# block is a nn.Module that contains an "attn" Attention submodule>>> tp_mesh=init_device_mesh
Configure the nn.Module’s inputs (and outputs) to convert the input tensors (and output tensors, respectively) of the nn.Module
to DTensors at runtime according to input_layouts (and output_layouts, respectively), and perform layout redistribution
according to the desired_input_layouts (and desired_output_layouts, respectively). This is a combination of
PrepareModuleInput and PrepareModuleOutput.
Keyword Arguments:
input_layouts (Union[Placement, Tuple[Optional[Placement]]]) – The DTensor layouts of input tensors for the nn.Module, this is used to convert the input tensors to
DTensors. If some inputs are not torch.Tensor or no need to convert to DTensors, None need to be specified
as a placeholder. default: None.
desired_input_layouts (Union[Placement, Tuple[Optional[) – The desired DTensor layout of input tensors for the nn.Module, this is used to ensure the inputs of the nn.Module
have the desired DTensor layouts. This argument needs to have the same length with . default: None.
Example::
>>> fromtorch.distributed.tensor.parallelimportparallelize_module,PrepareModuleInputOutput>>> fromtorch.distributed.device_meshimportinit_device_mesh>>> ...>>> block=TransformerBlock(...)# block is a nn.Module that contains an "attn" Attention submodule>>> tp_mesh=init_device_mesh
For models like Transformer, we recommend users to use ColwiseParallel
and RowwiseParallel together in the parallelize_plan for achieve the desired
sharding for the entire model (i.e. Attention and MLP).
Parallelized cross-entropy loss computation (loss parallelism), is supported via the following context manager:
torch.distributed.tensor.parallel.loss_parallel()
A context manager that enables loss parallelism, where efficient parallelized loss computation
can be performed when the input is sharded on the class dimension. Currently only the cross-entropy
loss is supported.
Within this context manager, one can use cross_entropy() or
CrossEntropyLoss as usual, with the following assumptions on the input parameters.
The corresponding backward() call, if any, also needs to happen under this context manager.
Both one-dimensional and multi-dimensional DeviceMesh are supported. On a
multi-dimensional mesh, exactly one mesh dim must shard the class dimension —
that dim is treated as the “TP” dim and can be in any position (not necessarily
last). The remaining mesh dims may be Shard (e.g. batch-sharded for DP/CP)
or Replicate.
Parameters:
input (DTensor) – Input logits. Assumed to be sharded on the class dimension on exactly
one mesh dim.
Must be ground truth class indices (class probabilities currently not
supported). Its placements are derived from input’s placements by
(1) replacing the TP dim’s Shard(class_dim) with Replicate and
(2) shifting any other Shard(d) with down by one
(since the class tensor dim is removed from the output):
Example
A sharded DTensor is manually created here to showcase the usage.
In practice, it is usually the output of a TP module.
A context manager that enables loss parallelism, where efficient parallelized loss computation
can be performed when the input is sharded on the class dimension. Currently only the cross-entropy
loss is supported.
Within this context manager, one can use cross_entropy() or
CrossEntropyLoss as usual, with the following assumptions on the input parameters.
The corresponding backward() call, if any, also needs to happen under this context manager.
Both one-dimensional and multi-dimensional DeviceMesh are supported. On a
multi-dimensional mesh, exactly one mesh dim must shard the class dimension —
that dim is treated as the “TP” dim and can be in any position (not necessarily
last). The remaining mesh dims may be Shard (e.g. batch-sharded for DP/CP)
or Replicate.
Parameters:
input (DTensor) – Input logits. Assumed to be sharded on the class dimension on exactly
one mesh dim.
Must be ground truth class indices (class probabilities currently not
supported). Its placements are derived from input’s placements by
(1) replacing the TP dim’s Shard(class_dim) with Replicate and
(2) shifting any other Shard(d) with down by one
(since the class tensor dim is removed from the output):
Example
A sharded DTensor is manually created here to showcase the usage.
In practice, it is usually the output of a TP module.
Register hooks to an nn.Module for input resharding, enabling sharding and restoration during backward computation.
Register hooks to an nn.Module with input resharding so that we can shard
per the given tp_device_mesh and input_reshard_dim and restore the
input back when recomputing the activations in the backward. The reason
why we can do this is that for Tensor Parallel(TP), the input are same
across all TP ranks.
Parameters:
module (nn.Module) – Module to be registered with input resharding.
tp_device_mesh (DeviceMesh) – Object which describes the mesh topology
of devices for Tensor Parallel.
input_reshard_dim (Optional[int]) – The dimension of where we perform the sharding
of input. If set None, there is no sharding of input.
Default: None
Returns:
A nn.Module object registered with TP input resharding.
src_data_rank (int, optional) – the rank of the source data for the logical/global tensor, it is used by
distribute_tensor() to scatter/broadcast the shards/replicas to other ranks. By default,
we use group_rank=0 on each DeviceMesh dimension as the source data to preserve the single-device
semantic. If passing None explicitly, parallelize_module() simply uses its local data instead
of trying to preserve the single-device semantic via scatter/broadcast. Default: 0
# By default, the input of the "w1" Linear will be converted to Replicated DTensor
>>>
# and the output of "w1" will return :class:`torch.Tensor` that shards on the last dim.
>>>
>>>
sharded_mod
=
parallelize_module
(
m
,
tp_mesh
,
{
"w1"
:
ColwiseParallel
()})
>>>
...
(
"cuda"
,
(
8
,))
>>>
>>>
# By default, the input of the "w2" Linear will be converted to DTensor that shards on the last dim
>>>
# and the output of "w2" will return a replicated :class:`torch.Tensor`.
>>>
>>>
sharded_mod
=
parallelize_module
(
m
,
tp_mesh
,
{
"w2"
:
RowwiseParallel
()}),
>>>
...
ParallelStyle
nn.Module
(
"cuda"
,
(
8
,))
>>>
>>>
# By default, the input of the "norm" will be converted to DTensor that shards on the sequence dim
>>>
# and the output of "norm" will return a sharded on sequence dimension :class:`DTensor`.
>>>
>>>
sharded_mod
=
parallelize_module
(
m
,
tp_mesh
,
{
"norm"
:
SequenceParallel
()}),
>>>
...
Placement
]
]
]
input_layouts
input_kwarg_layouts (Dict[str, Placement]) – The DTensor layouts of input kwargs for the nn.Module, this is used to convert the input kwarg tensors to DTensors.
default: None
desired_input_kwarg_layouts – (Dict[str, Placement]):
The desired DTensor layout of input kwargs for the nn.Module, this is used to ensure the inputs of the nn.Module
have the desired DTensor layouts. default: None.
use_local_output (bool, optional) – Whether to use local torch.Tensor instead of DTensor for the module inputs, default: False.
Returns:
A ParallelStyle object that prepares the sharding layouts of the nn.Module’s inputs.
(
"cuda"
,
(
8
,))
>>>
>>>
# According to the style specified below, the first input of attn will be annotated to Sharded DTensor
>>>
# and then redistributed to Replicated DTensor.
>>>
parallelize_module
(
>>>
block
,
# this can be a submodule or module
>>>
tp_mesh
,
>>>
parallelize_plan
=
{
>>>
"attn"
:
PrepareModuleInput
(
>>>
input_layouts
=
(
Shard
(
0
),
None
,
None
,
...
),
>>>
desired_input_layouts
=
(
Replicate
(),
None
,
None
,
...
)
>>>
),
>>>
}
>>>
)
(
"cuda"
,
(
8
,))
>>>
>>>
# According to the style specified below, the output of the TransformerBlock will be converted to Replicated DTensor
>>>
# and then redistributed to Sharded DTensor.
>>>
parallelize_module
(
>>>
block
,
# this can be a submodule or module
>>>
tp_mesh
,
>>>
parallelize_plan
=
PrepareModuleOutput
(
>>>
output_layouts
=
Replicate
(),
>>>
desired_output_layouts
=
Shard
(
0
)
>>>
)
>>>
)
Placement
]
]
]
input_layouts
input_kwarg_layouts (Dict[str, Placement]) – The DTensor layouts of input kwargs for the nn.Module, this is used to convert the input kwarg tensors to DTensors.
default: None
desired_input_kwarg_layouts – (Dict[str, Placement]):
The desired DTensor layout of input kwargs for the nn.Module, this is used to ensure the inputs of the nn.Module
have the desired DTensor layouts. default: None.
use_local_input (bool, optional) – Whether to use local torch.Tensor instead of DTensor for the module inputs, default: False.
output_layouts (Union[Placement, Tuple[Placement]]) – The DTensor layouts of output tensors for the nn.Module, this is used to convert the output tensors to
DTensors if they are torch.Tensor. If some outputs are not torch.Tensor or no need to convert to DTensors,
None need to be specified as a placeholder.
desired_output_layouts (Union[Placement, Tuple[Placement]]) – The desired DTensor layouts of output tensors for the nn.Module, this is used to ensure the outputs of the nn.Module
have the desired DTensor layouts.
use_local_output (bool, optional) – Whether to use local torch.Tensor instead of DTensor for the module outputs, default: True.
Returns:
A ParallelStyle object that prepares the sharding layouts of the nn.Module’s inputs and outputs.
(
"cuda"
,
(
8
,))
>>>
>>>
# According to the style specified below, the first input of attn will be annotated as Sharded DTensor
>>>
# and then redistributed to Replicated DTensor, and the output of the TransformerBlock will be annotated
>>>
# as Replicated DTensor and then redistributed to Sharded DTensor.
A plain torch.Tensor is only accepted when the derived target
placements are all Replicate (e.g. on a one-dimensional mesh);
otherwise a DTensor must be passed explicitly so that the
intended sharding is unambiguous.
weight (Union[torch.Tensor, DTensor], optional) – If given, assumed to be replicated across the DeviceMesh.
label_smoothing – Currently not supported.
Returns:
reduction="none" — per-sample loss; inherits the target
placements (Shard on batch-parallel dims, Replicate on TP).
reduction="sum" — scalar; Replicate on the TP dim (the custom
all-reduce makes each rank’s local value globally correct over TP),
Partial("sum") on every other Shard mesh dim so that the
cross-rank reduction happens lazily on materialization/redistribution,
and Replicate on Replicate mesh dims.
reduction="mean" — only supported on a one-dimensional mesh; returns
a fully replicated DTensor.
On a one-dimensional mesh all three cases simplify to a fully replicated
DTensor (the original behavior).
A plain torch.Tensor is only accepted when the derived target
placements are all Replicate (e.g. on a one-dimensional mesh);
otherwise a DTensor must be passed explicitly so that the
intended sharding is unambiguous.
weight (Union[torch.Tensor, DTensor], optional) – If given, assumed to be replicated across the DeviceMesh.
label_smoothing – Currently not supported.
Returns:
reduction="none" — per-sample loss; inherits the target
placements (Shard on batch-parallel dims, Replicate on TP).
reduction="sum" — scalar; Replicate on the TP dim (the custom
all-reduce makes each rank’s local value globally correct over TP),
Partial("sum") on every other Shard mesh dim so that the
cross-rank reduction happens lazily on materialization/redistribution,
and Replicate on Replicate mesh dims.
reduction="mean" — only supported on a one-dimensional mesh; returns
a fully replicated DTensor.
On a one-dimensional mesh all three cases simplify to a fully replicated
DTensor (the original behavior).